Design overhaul, stats page, internal notes

Design: Onest+Unbounded font pairing (Cyrillic-verified, replacing plain
Golos Text), manual light/dark toggle wired to the data-theme cascade
already built in MVP-1, refreshed palette + new chart-mark tokens
(CVD-validated via the dataviz skill's validator), colored avatar
initials, per-channel colored badges, favicon, nicer empty states.

Stats: /stats page — status/channel breakdown, 14-day ticket volume,
avg first-response time, per-agent open-ticket workload. Colors and
chart forms follow the dataviz skill's procedure (categorical order
re-stepped to clear the CVD adjacency check in both themes).

Internal notes: messages.visibility ("public"/"internal") column.
Agent-only notes never reach customer-facing reads (getTicketForCustomer)
or the customer SSE stream (/api/portal/events, reused by the widget) —
fixed at both the initial-fetch and live-delivery layers.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcXH24ky6zjk2UyK5oZUPH
This commit is contained in:
ogrechkoandClaude Sonnet 5 committed 2026-07-26 14:38:52 +00:00
1 parent 4efce5f307
commit 9f1413f0b9
23 files changed
+1315 -64

No files matched your search

+33 -17
View File
@@ -3,17 +3,18 @@
import { useMemo, useState } from "react";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { Send, Globe, UserRound, Mail, MessageSquare, Plus } from "lucide-react";
import { Send, Globe, UserRound, Mail, MessageSquare, Plus, Inbox } 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";
const COLUMNS: { status: TicketStatus; label: string }[] = [
{ status: "new", label: "Новые" },
{ status: "open", label: "Открытые" },
{ status: "pending", label: "В ожидании" },
{ status: "closed", label: "Закрытые" },
const COLUMNS: { status: TicketStatus; label: string; empty: string }[] = [
{ status: "new", label: "Новые", empty: "Новых заявок нет" },
{ status: "open", label: "Открытые", empty: "Ничего в работе" },
{ status: "pending", label: "В ожидании", empty: "Никто не ждёт ответа" },
{ status: "closed", label: "Закрытые", empty: "Пока нечего закрывать" },
];
const CHANNEL_ICON = {
@@ -24,6 +25,15 @@ const CHANNEL_ICON = {
widget: MessageSquare,
} as const;
// Full literal strings — see components/avatar.tsx for why.
const CHANNEL_CHIP_CLASSES = {
telegram: "bg-info-soft text-info-soft-text",
email: "bg-accent-soft text-accent-soft-text",
widget: "bg-success-soft text-success-soft-text",
portal: "bg-warning-soft text-warning-soft-text",
manual: "bg-surface-hover text-text-muted",
} as const;
const PRIORITY_COLOR: Record<TicketDTO["priority"], string> = {
low: "var(--text-faint)",
normal: "var(--border-strong)",
@@ -58,7 +68,7 @@ export function TicketBoard({ initialTickets }: { initialTickets: TicketDTO[] })
return (
<div>
<div className="mb-5 flex items-center justify-between">
<h1 className="text-xl font-bold tracking-tight">Заявки</h1>
<h1 className="font-display text-xl font-bold tracking-tight">Заявки</h1>
<button className="btn btn-primary" onClick={() => setModalOpen(true)}>
<Plus size={16} />
Новая заявка
@@ -81,9 +91,10 @@ export function TicketBoard({ initialTickets }: { initialTickets: TicketDTO[] })
))}
</AnimatePresence>
{byStatus[col.status].length === 0 && (
<p className="rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-text-faint">
Пусто
</p>
<div className="flex flex-col items-center gap-2 rounded-md border border-dashed border-border px-3 py-8 text-center">
<Inbox size={18} className="text-text-faint" />
<p className="text-xs text-text-faint">{col.empty}</p>
</div>
)}
</div>
</div>
@@ -108,16 +119,21 @@ function TicketCard({ ticket }: { ticket: TicketDTO }) {
>
<Link
href={`/tickets/${ticket.id}`}
className="card block p-3 transition-shadow hover:shadow-md"
className="card block p-3 shadow-sm transition-shadow hover:shadow-md"
style={{ borderLeft: `3px solid ${PRIORITY_COLOR[ticket.priority]}` }}
>
<p className="mb-1.5 line-clamp-2 text-sm font-medium">{ticket.subject}</p>
<div className="flex items-center justify-between text-xs text-text-muted">
<span className="flex items-center gap-1 truncate">
<Icon size={12} />
{ticket.customerName}
<p className="mb-2 line-clamp-2 text-sm font-medium">{ticket.subject}</p>
<div className="flex items-center justify-between">
<span className="flex min-w-0 items-center gap-1.5">
<Avatar name={ticket.customerName} size={20} />
<span className="truncate text-xs text-text-muted">{ticket.customerName}</span>
</span>
<span className="flex shrink-0 items-center gap-1.5">
<span className={`flex h-5 w-5 items-center justify-center rounded-full ${CHANNEL_CHIP_CLASSES[ticket.channel]}`}>
<Icon size={11} />
</span>
<span className="text-xs text-text-faint">{formatRelativeTime(ticket.lastMessageAt)}</span>
</span>
<span className="shrink-0 text-text-faint">{formatRelativeTime(ticket.lastMessageAt)}</span>
</div>
</Link>
</motion.div>
+3 -1
View File
@@ -3,6 +3,7 @@ import { Ticket } from "lucide-react";
import { getCurrentSession } from "@/lib/auth/session";
import { LogoutButton } from "./logout-button";
import { NavLinks } from "./nav-links";
import { ThemeToggle } from "./theme-toggle";
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await getCurrentSession();
@@ -14,7 +15,7 @@ export default async function AdminLayout({ children }: { children: React.ReactN
<div className="flex min-h-screen flex-col bg-bg">
<header className="border-b border-border bg-surface">
<div className="mx-auto flex max-w-7xl items-center gap-6 px-6 py-3">
<div className="flex items-center gap-2 font-bold tracking-tight">
<div className="flex items-center gap-2 font-display text-[15px] font-bold tracking-tight">
<div className="flex h-7 w-7 items-center justify-center rounded-md bg-accent text-white">
<Ticket size={15} strokeWidth={2.5} />
</div>
@@ -23,6 +24,7 @@ export default async function AdminLayout({ children }: { children: React.ReactN
<NavLinks />
<div className="ml-auto flex items-center gap-3">
<span className="text-sm text-text-muted">{session.user.name}</span>
<ThemeToggle />
<LogoutButton />
</div>
</div>
+2 -1
View File
@@ -2,10 +2,11 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { LayoutDashboard, Send, Mail, Code2 } from "lucide-react";
import { LayoutDashboard, BarChart3, Send, Mail, Code2 } from "lucide-react";
const links = [
{ href: "/dashboard", label: "Дашборд", icon: LayoutDashboard },
{ href: "/stats", label: "Статистика", icon: BarChart3 },
{ href: "/settings/telegram", label: "Telegram", icon: Send },
{ href: "/settings/email", label: "Почта", icon: Mail },
{ href: "/settings/widget", label: "Виджет", icon: Code2 },
+89
View File
@@ -0,0 +1,89 @@
// Small inline HTML/CSS charts — see the dataviz skill guidance this file
// follows: thin marks (≤24px), 4px rounded data-end / square baseline,
// direct labels (never color alone), text in text tokens (never data color).
export function StatTile({ label, value }: { label: string; value: string }) {
return (
<div className="card p-4">
<p className="mb-1 text-xs text-text-muted">{label}</p>
<p className="text-2xl font-semibold">{value}</p>
</div>
);
}
const BAR_HEIGHT = 16;
export function HorizontalBar({
label,
value,
max,
colorClass,
}: {
label: string;
value: number;
max: number;
colorClass: string;
}) {
const pct = max > 0 ? (value / max) * 100 : 0;
return (
<div className="flex items-center gap-3">
<span className="w-24 shrink-0 truncate text-xs text-text-muted">{label}</span>
<div
className="flex-1 overflow-hidden bg-surface-hover"
style={{ height: BAR_HEIGHT, borderRadius: 4 }}
title={`${label}: ${value}`}
>
<div
className={colorClass}
style={{
width: `${pct}%`,
height: "100%",
borderRadius: "0 4px 4px 0",
transition: "width 300ms ease",
}}
/>
</div>
<span className="w-6 shrink-0 text-right text-xs font-medium text-text">{value}</span>
</div>
);
}
export function DailyBarChart({ data }: { data: { label: string; count: number }[] }) {
const max = Math.max(...data.map((d) => d.count), 1);
return (
<div>
<div className="flex h-32 items-end gap-1 border-b border-border pb-0.5">
{data.map((d, i) => (
<div key={i} className="group relative flex flex-1 flex-col items-center justify-end" title={`${d.label}: ${d.count}`}>
{d.count > 0 && (
<span className="mb-1 text-[10px] text-text-faint opacity-0 transition-opacity group-hover:opacity-100">
{d.count}
</span>
)}
<div
className="w-full bg-chart-1"
style={{
height: max > 0 ? `${Math.max((d.count / max) * 100, d.count > 0 ? 4 : 1)}%` : "1%",
borderRadius: "4px 4px 0 0",
opacity: d.count > 0 ? 1 : 0.15,
}}
/>
</div>
))}
</div>
<div className="mt-1 flex gap-1">
{data.map((d, i) => (
<span
key={i}
className="flex-1 truncate text-center text-[10px] text-text-faint"
style={{ visibility: i % 3 === 0 ? "visible" : "hidden" }}
>
{d.label}
</span>
))}
</div>
</div>
);
}
+105
View File
@@ -0,0 +1,105 @@
import { Inbox, CircleDot, Clock, CheckCircle2 } from "lucide-react";
import { getStatsOverview } from "@/lib/tickets/service";
import { formatDurationMinutes } from "@/lib/format";
import { StatTile, HorizontalBar, DailyBarChart } from "./charts";
const STATUS_META = {
new: { label: "Новые", icon: Inbox, soft: "--accent-soft", softText: "--accent-soft-text" },
open: { label: "Открытые", icon: CircleDot, soft: "--success-soft", softText: "--success-soft-text" },
pending: { label: "В ожидании", icon: Clock, soft: "--warning-soft", softText: "--warning-soft-text" },
closed: { label: "Закрытые", icon: CheckCircle2, soft: "--border", softText: "--text-muted" },
} as const;
const CHANNEL_META: Record<string, { label: string; colorClass: string }> = {
email: { label: "Почта", colorClass: "bg-chart-1" },
widget: { label: "Виджет", colorClass: "bg-chart-2" },
telegram: { label: "Telegram", colorClass: "bg-chart-3" },
portal: { label: "Портал", colorClass: "bg-chart-4" },
manual: { label: "Вручную", colorClass: "bg-chart-muted" },
};
export default async function StatsPage() {
const stats = await getStatsOverview();
const maxChannelCount = Math.max(...Object.values(stats.channelCounts), 1);
const maxAgentWorkload = Math.max(...stats.agentWorkload.map((a) => a.openCount), 1);
return (
<div>
<h1 className="mb-5 font-display text-xl font-bold tracking-tight">Статистика</h1>
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
<StatTile label="Всего заявок" value={String(stats.totalTickets)} />
<StatTile label="В работе сейчас" value={String(stats.openTickets)} />
<StatTile label="Новых сегодня" value={String(stats.newToday)} />
<StatTile
label="Среднее время ответа"
value={stats.avgFirstResponseMinutes != null ? formatDurationMinutes(stats.avgFirstResponseMinutes) : "—"}
/>
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="card p-4">
<h2 className="mb-3 text-sm font-semibold text-text-muted">По статусам</h2>
<div className="grid grid-cols-2 gap-2">
{(Object.keys(STATUS_META) as (keyof typeof STATUS_META)[]).map((status) => {
const meta = STATUS_META[status];
const Icon = meta.icon;
return (
<div
key={status}
className="flex items-center justify-between rounded-md px-3 py-2 text-sm"
style={{ background: `var(${meta.soft})`, color: `var(${meta.softText})` }}
>
<span className="flex items-center gap-1.5">
<Icon size={13} />
{meta.label}
</span>
<span className="font-semibold">{stats.statusCounts[status]}</span>
</div>
);
})}
</div>
</div>
<div className="card p-4">
<h2 className="mb-3 text-sm font-semibold text-text-muted">По каналам</h2>
<div className="flex flex-col gap-2">
{Object.entries(stats.channelCounts).map(([channel, count]) => (
<HorizontalBar
key={channel}
label={CHANNEL_META[channel]?.label ?? channel}
value={count}
max={maxChannelCount}
colorClass={CHANNEL_META[channel]?.colorClass ?? "bg-chart-muted"}
/>
))}
</div>
</div>
<div className="card p-4 lg:col-span-2">
<h2 className="mb-3 text-sm font-semibold text-text-muted">Заявки за 14 дней</h2>
<DailyBarChart data={stats.ticketsPerDay} />
</div>
<div className="card p-4 lg:col-span-2">
<h2 className="mb-3 text-sm font-semibold text-text-muted">Загрузка агентов (открытые заявки)</h2>
{stats.agentWorkload.length === 0 ? (
<p className="text-sm text-text-faint">Пока нет данных.</p>
) : (
<div className="flex flex-col gap-2">
{stats.agentWorkload.map((agent) => (
<HorizontalBar
key={agent.name}
label={agent.name}
value={agent.openCount}
max={maxAgentWorkload}
colorClass="bg-chart-1"
/>
))}
</div>
)}
</div>
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { Sun, Moon } from "lucide-react";
function getEffectiveTheme(): "light" | "dark" {
const stored = document.documentElement.dataset.theme;
if (stored === "light" || stored === "dark") return stored;
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
// Both icons always render; CSS (mirroring the same data-theme cascade the
// palette itself uses) decides which one shows — avoids a useState/useEffect
// pair just to reflect the DOM attribute the no-flash script already set.
export function ThemeToggle() {
function toggle() {
const next = getEffectiveTheme() === "dark" ? "light" : "dark";
document.documentElement.dataset.theme = next;
localStorage.setItem("theme", next);
}
return (
<button onClick={toggle} className="btn btn-ghost theme-toggle-btn" title="Переключить тему" aria-label="Переключить тему">
<Sun size={15} className="theme-icon-sun" />
<Moon size={15} className="theme-icon-moon" />
</button>
);
}
+77 -21
View File
@@ -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, StickyNote } from "lucide-react";
import { useTicketEvents } from "@/lib/events/use-ticket-events";
import { formatRelativeTime } from "@/lib/format";
import { Avatar } from "@/components/avatar";
import type { TicketDTO, MessageDTO, TicketStatus } from "@/lib/tickets/types";
const STATUS_LABEL: Record<TicketStatus, string> = {
@@ -27,6 +28,7 @@ export function TicketThread({
const [ticket, setTicket] = useState(initialTicket);
const [messages, setMessages] = useState(initialMessages);
const [draft, setDraft] = useState("");
const [visibility, setVisibility] = useState<"public" | "internal">("public");
const [sending, setSending] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
@@ -49,7 +51,7 @@ export function TicketThread({
const res = await fetch(`/api/tickets/${ticket.id}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: draft }),
body: JSON.stringify({ body: draft, visibility }),
});
setSending(false);
if (res.ok) setDraft("");
@@ -87,8 +89,11 @@ export function TicketThread({
<ArrowLeft size={13} />
Дашборд
</Link>
<h1 className="truncate text-lg font-bold">{ticket.subject}</h1>
<p className="text-sm text-text-muted">{ticket.customerName}</p>
<h1 className="truncate font-display text-lg font-bold">{ticket.subject}</h1>
<span className="flex items-center gap-1.5">
<Avatar name={ticket.customerName} size={18} />
<span className="text-sm text-text-muted">{ticket.customerName}</span>
</span>
</div>
<div className="flex shrink-0 items-center gap-2">
@@ -127,23 +132,53 @@ export function TicketThread({
<div ref={bottomRef} />
</div>
<div className="mt-3 flex gap-2">
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendReply();
}
}}
rows={2}
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={sendReply} disabled={sending || !draft.trim()} className="btn btn-primary self-end">
<Send size={15} />
</button>
<div className="mt-3">
<div className="mb-1.5 flex gap-1">
<button
type="button"
onClick={() => setVisibility("public")}
className={`rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${
visibility === "public" ? "bg-accent-soft text-accent-soft-text" : "text-text-faint hover:text-text-muted"
}`}
>
Ответ клиенту
</button>
<button
type="button"
onClick={() => setVisibility("internal")}
className={`rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${
visibility === "internal" ? "bg-warning-soft text-warning-soft-text" : "text-text-faint hover:text-text-muted"
}`}
>
Заметка для команды
</button>
</div>
<div className="flex gap-2">
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendReply();
}
}}
rows={2}
placeholder={visibility === "internal" ? "Заметка — клиент её не увидит…" : "Ответить клиенту…"}
className={`flex-1 resize-none rounded-md border px-3 py-2 text-sm outline-none ${
visibility === "internal"
? "border-warning-soft-text/30 bg-warning-soft focus:border-warning"
: "border-border bg-surface focus:border-accent"
}`}
/>
<button
onClick={sendReply}
disabled={sending || !draft.trim()}
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} />}
</button>
</div>
</div>
</div>
);
@@ -159,6 +194,27 @@ function MessageBubble({ message }: { message: MessageDTO }) {
);
}
if (message.visibility === "internal") {
return (
<motion.div
layout
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18 }}
className="mb-3 rounded-lg border border-dashed border-warning-soft-text/40 bg-warning-soft px-3 py-2"
>
<p className="mb-1 flex items-center gap-1.5 text-[11px] font-semibold text-warning-soft-text">
<StickyNote size={11} />
Внутренняя заметка
</p>
<p className="mb-1 whitespace-pre-wrap text-sm">{message.body}</p>
<p className="text-[11px] text-warning-soft-text/80">
{message.authorName} · {formatRelativeTime(message.createdAt)}
</p>
</motion.div>
);
}
return (
<motion.div
layout
+8 -3
View File
@@ -35,7 +35,12 @@ export default function LoginPage() {
}
return (
<main className="flex min-h-screen items-center justify-center bg-bg px-4">
<main
className="flex min-h-screen items-center justify-center px-4"
style={{
background: "radial-gradient(ellipse 60% 50% at 50% -10%, var(--accent-soft), var(--bg) 70%)",
}}
>
<motion.form
onSubmit={handleSubmit}
initial={{ opacity: 0, y: 12 }}
@@ -47,10 +52,10 @@ export default function LoginPage() {
<div className="flex h-9 w-9 items-center justify-center rounded-md bg-accent text-white">
<Ticket size={18} strokeWidth={2.5} />
</div>
<span className="text-lg font-bold tracking-tight">top-tickets</span>
<span className="font-display text-lg font-bold tracking-tight">top-tickets</span>
</div>
<h1 className="mb-1 text-xl font-semibold">Вход для агентов</h1>
<h1 className="mb-1 font-display text-xl font-semibold">Вход для агентов</h1>
<p className="mb-6 text-sm text-text-muted">Войдите, чтобы открыть дашборд заявок.</p>
<label className="mb-3 block text-sm">
+1 -1
View File
@@ -4,7 +4,7 @@ export default function PortalLayout({ children }: { children: React.ReactNode }
return (
<div className="flex min-h-screen flex-col bg-bg">
<header className="border-b border-border bg-surface">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-6 py-3 font-bold tracking-tight">
<div className="mx-auto flex max-w-2xl items-center gap-2 px-6 py-3 font-display font-bold tracking-tight">
<div className="flex h-7 w-7 items-center justify-center rounded-md bg-accent text-white">
<Ticket size={15} strokeWidth={2.5} />
</div>
+1 -1
View File
@@ -23,7 +23,7 @@ export default async function PortalTicketListPage({
return (
<div>
<h1 className="mb-1 text-xl font-bold tracking-tight">Здравствуйте, {customer.displayName}</h1>
<h1 className="mb-1 font-display text-xl font-bold tracking-tight">Здравствуйте, {customer.displayName}</h1>
<p className="mb-6 text-sm text-text-muted">Ваши обращения в поддержку.</p>
{tickets.length === 0 && <p className="text-sm text-text-muted">Заявок пока нет.</p>}
+8 -1
View File
@@ -20,5 +20,12 @@ export async function GET(request: Request) {
return NextResponse.json({ error: "Invalid token" }, { status: 404 });
}
return createEventStream((event) => ticketEventCustomerId(event) === customer.id);
return createEventStream((event) => {
if (ticketEventCustomerId(event) !== customer.id) return false;
// Internal notes must never reach a customer-facing stream, even though
// the initial page-load fetch (getTicketForCustomer) already filters
// them out — SSE is a second, independent delivery path for the same data.
if (event.type === "message.created" && event.message.visibility === "internal") return false;
return true;
});
}
+12 -1
View File
@@ -3,7 +3,7 @@ export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { recordAgentReply, getEmailThreadContext } from "@/lib/tickets/service";
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";
@@ -12,6 +12,7 @@ import { eq } from "drizzle-orm";
const messageSchema = z.object({
body: z.string().min(1).max(10_000),
visibility: z.enum(["public", "internal"]).default("public"),
});
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
@@ -30,6 +31,16 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
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);
+98 -11
View File
@@ -2,6 +2,7 @@
@theme {
--font-sans: var(--font-sans), ui-sans-serif, system-ui, sans-serif;
--font-display: var(--font-display), var(--font-sans), ui-sans-serif, sans-serif;
--font-mono: var(--font-mono), ui-monospace, monospace;
--color-bg: var(--bg);
@@ -30,25 +31,41 @@
--color-success-soft: var(--success-soft);
--color-success-soft-text: var(--success-soft-text);
--color-info: var(--info);
--color-info-soft: var(--info-soft);
--color-info-soft-text: var(--info-soft-text);
--color-rose: var(--rose);
--color-rose-soft: var(--rose-soft);
--color-rose-soft-text: var(--rose-soft-text);
/* Chart marks — validated categorical set (dataviz skill), distinct from
the softer *-soft badge tokens which are too light for dark-mode marks. */
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-muted: var(--chart-muted);
--radius-sm: var(--radius-sm-val);
--radius-md: var(--radius-md-val);
--radius-lg: var(--radius-lg-val);
}
:root {
--bg: #fafaf9;
--bg: #f8f7fb;
--surface: #ffffff;
--surface-hover: #f6f5ff;
--border: #e8e6f5;
--border-strong: #d6d1ee;
--text: #191524;
--text-muted: #6c6685;
--text-faint: #a29cc0;
--surface-hover: #f2effa;
--border: #e5e0f2;
--border-strong: #cec4e8;
--text: #171325;
--text-muted: #635d7a;
--text-faint: #9891ad;
--accent: #7c3aed;
--accent-hover: #6d28d9;
--accent-soft: #f3edff;
--accent-soft-text: #6d28d9;
--accent: #6d28d9;
--accent-hover: #5b21b6;
--accent-soft: #f0e8fe;
--accent-soft-text: #5b21b6;
--danger: #dc2626;
--danger-soft: #fef2f2;
@@ -62,6 +79,22 @@
--success-soft: #ecfdf9;
--success-soft-text: #0f766e;
--info: #2563eb;
--info-soft: #eff6ff;
--info-soft-text: #1d4ed8;
--rose: #e11d48;
--rose-soft: #fff1f2;
--rose-soft-text: #be123c;
/* Chart marks — fixed categorical order, CVD-validated (accent/success/
info/warning); reorder only after re-running the validator. */
--chart-1: #6d28d9;
--chart-2: #0d9488;
--chart-3: #2563eb;
--chart-4: #d97706;
--chart-muted: var(--border-strong);
--radius-sm-val: 8px;
--radius-md-val: 12px;
--radius-lg-val: 18px;
@@ -97,6 +130,22 @@
--success-soft: #0f2320;
--success-soft-text: #5eead4;
--info: #60a5fa;
--info-soft: #12203a;
--info-soft-text: #93c5fd;
--rose: #fb7185;
--rose-soft: #2a1420;
--rose-soft-text: #fda4af;
/* Darker/more saturated than the badge tokens above — validated
separately for the dark-mode lightness band (L 0.48–0.67). */
--chart-1: #8b5cf6;
--chart-2: #0d9488;
--chart-3: #3b82f6;
--chart-4: #d97706;
--chart-muted: var(--border-strong);
color-scheme: dark;
}
}
@@ -128,9 +177,46 @@
--success-soft: #0f2320;
--success-soft-text: #5eead4;
--info: #60a5fa;
--info-soft: #12203a;
--info-soft-text: #93c5fd;
--rose: #fb7185;
--rose-soft: #2a1420;
--rose-soft-text: #fda4af;
--chart-1: #8b5cf6;
--chart-2: #0d9488;
--chart-3: #3b82f6;
--chart-4: #d97706;
--chart-muted: var(--border-strong);
color-scheme: dark;
}
/* Theme-toggle icon: both render always, CSS picks which shows — same
data-theme cascade the palette above uses, so it never needs JS state. */
.theme-toggle-btn .theme-icon-sun {
display: none;
}
.theme-toggle-btn .theme-icon-moon {
display: inline;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .theme-toggle-btn .theme-icon-sun {
display: inline;
}
:root:not([data-theme="light"]) .theme-toggle-btn .theme-icon-moon {
display: none;
}
}
:root[data-theme="dark"] .theme-toggle-btn .theme-icon-sun {
display: inline;
}
:root[data-theme="dark"] .theme-toggle-btn .theme-icon-moon {
display: none;
}
* {
border-color: var(--border);
}
@@ -175,6 +261,7 @@ body {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}
.btn {
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<rect width="32" height="32" rx="8" fill="#6d28d9"/>
<path d="M9 10.5C9 9.11929 10.1193 8 11.5 8H20.5C21.8807 8 23 9.11929 23 10.5V17.5C23 18.8807 21.8807 20 20.5 20H14L10 23.5V20H11.5C10.1193 20 9 18.8807 9 17.5V10.5Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 330 B

+31 -3
View File
@@ -1,12 +1,18 @@
import type { Metadata } from "next";
import { Golos_Text, JetBrains_Mono } from "next/font/google";
import { Onest, Unbounded, JetBrains_Mono } from "next/font/google";
import "./globals.css";
const sans = Golos_Text({
const sans = Onest({
variable: "--font-sans",
subsets: ["latin", "cyrillic"],
});
const display = Unbounded({
variable: "--font-display",
subsets: ["latin", "cyrillic"],
weight: ["600", "700", "800"],
});
const mono = JetBrains_Mono({
variable: "--font-mono",
subsets: ["latin"],
@@ -17,9 +23,31 @@ export const metadata: Metadata = {
description: "Helpdesk for support@top-sysops.ru, Telegram, and the web.",
};
// Reads the persisted theme before hydration so there's no flash of the
// wrong theme — data-theme is absent by default (system preference via the
// CSS prefers-color-scheme block), and only set once the visitor has
// explicitly chosen a theme via the toggle.
const noFlashThemeScript = `
(function () {
try {
var stored = localStorage.getItem("theme");
if (stored === "light" || stored === "dark") {
document.documentElement.dataset.theme = stored;
}
} catch {}
})();
`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="ru" className={`${sans.variable} ${mono.variable}`} suppressHydrationWarning>
<html
lang="ru"
className={`${sans.variable} ${display.variable} ${mono.variable}`}
suppressHydrationWarning
>
<head>
<script dangerouslySetInnerHTML={{ __html: noFlashThemeScript }} />
</head>
<body>{children}</body>
</html>
);
+35
View File
@@ -0,0 +1,35 @@
// Full literal class strings so Tailwind's scanner picks them up — a
// runtime-interpolated class name (e.g. `bg-${hue}-soft`) wouldn't be
// detected since Tailwind scans source text, not computed output.
const PALETTE_CLASSES = [
"bg-accent-soft text-accent-soft-text",
"bg-success-soft text-success-soft-text",
"bg-warning-soft text-warning-soft-text",
"bg-info-soft text-info-soft-text",
"bg-rose-soft text-rose-soft-text",
"bg-danger-soft text-danger-soft-text",
] as const;
function classesFor(name: string): string {
let hash = 0;
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;
return PALETTE_CLASSES[Math.abs(hash) % PALETTE_CLASSES.length];
}
function initialsFor(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) return "?";
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
return (parts[0][0] + parts[1][0]).toUpperCase();
}
export function Avatar({ name, size = 28 }: { name: string; size?: number }) {
return (
<div
className={`flex shrink-0 items-center justify-center rounded-full font-display font-semibold ${classesFor(name)}`}
style={{ width: size, height: size, fontSize: size * 0.4 }}
>
{initialsFor(name)}
</div>
);
}
@@ -0,0 +1 @@
ALTER TABLE `messages` ADD `visibility` text DEFAULT 'public' NOT NULL;
@@ -0,0 +1,617 @@
{
"version": "6",
"dialect": "sqlite",
"id": "727e15bd-5319-45d7-9cc5-52683fe1dc2e",
"prevId": "59682ff3-ebbe-44b0-9eab-267734ad7e7c",
"tables": {
"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": {}
},
"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": {}
},
"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": {}
}
}
+7
View File
@@ -22,6 +22,13 @@
"when": 1785072485453,
"tag": "0002_broad_stellaris",
"breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1785076018169,
"tag": "0003_absurd_zemo",
"breakpoints": true
}
]
}
+6
View File
@@ -85,6 +85,12 @@ export const messages = sqliteTable("messages", {
authorName: text("author_name").notNull(),
body: text("body").notNull(),
direction: text("direction", { enum: ["in", "out"] }).notNull(),
// "internal" notes are agent-only — never sent to the customer over any
// channel, and filtered out of every customer-facing read path (portal,
// widget). Only ever set by recordInternalNote.
visibility: text("visibility", { enum: ["public", "internal"] })
.notNull()
.default("public"),
// RFC 5322 Message-ID of this email, when the message came in/out over the
// email channel — lets a customer's future reply be matched back to the
// exact ticket via In-Reply-To/References, even if they have other tickets.
+6
View File
@@ -17,3 +17,9 @@ export function formatRelativeTime(timestampMs: number): string {
}
return rtf.format(Math.round(diff / 1000), "second");
}
export function formatDurationMinutes(minutes: number): string {
if (minutes < 60) return `${Math.round(minutes)} мин`;
if (minutes < 60 * 24) return `${(minutes / 60).toFixed(1)} ч`;
return `${(minutes / 60 / 24).toFixed(1)} дн`;
}
+142 -3
View File
@@ -2,7 +2,7 @@ import { eq, and, ne, desc } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { customers, tickets, messages, users, widgetSites } from "@/lib/db/schema";
import { publishTicketEvent } from "@/lib/events/bus";
import type { TicketDTO, MessageDTO, TicketChannel } from "@/lib/tickets/types";
import type { TicketDTO, MessageDTO, TicketChannel, TicketStatus } from "@/lib/tickets/types";
function toTicketDTO(ticket: typeof tickets.$inferSelect, customerName: string): TicketDTO {
return {
@@ -28,6 +28,7 @@ function toMessageDTO(message: typeof messages.$inferSelect): MessageDTO {
authorName: message.authorName,
body: message.body,
direction: message.direction,
visibility: message.visibility,
createdAt: message.createdAt.getTime(),
};
}
@@ -55,6 +56,7 @@ async function appendMessage(params: {
authorName: string;
body: string;
direction: "in" | "out";
visibility?: "public" | "internal";
emailMessageId?: string;
}) {
const [message] = await db
@@ -66,6 +68,7 @@ async function appendMessage(params: {
authorName: params.authorName,
body: params.body,
direction: params.direction,
visibility: params.visibility ?? "public",
emailMessageId: params.emailMessageId,
})
.returning();
@@ -278,6 +281,33 @@ export async function recordAgentReply(params: {
});
}
/**
* Internal, agent-only note — never delivered over any channel, never
* visible to the customer (filtered out of getTicketForCustomer). Unlike
* recordAgentReply, doesn't reopen the ticket — it's team communication,
* not customer-facing activity.
*/
export async function recordInternalNote(params: {
ticketId: string;
agentId: string;
agentName: string;
body: string;
}) {
const ticket = await db.query.tickets.findFirst({ where: eq(tickets.id, params.ticketId) });
if (!ticket) throw new Error("Ticket not found");
return appendMessage({
ticket,
ticketIsNew: false,
authorType: "agent",
authorId: params.agentId,
authorName: params.agentName,
body: params.body,
direction: "out",
visibility: "internal",
});
}
export async function setTicketStatus(
ticketId: string,
status: (typeof tickets.$inferSelect)["status"],
@@ -366,11 +396,19 @@ export async function listTicketsForCustomer(customerId: string): Promise<Ticket
return rows.map((row) => toTicketDTO(row.ticket, row.customerName));
}
/** Returns the ticket+messages only if it actually belongs to this customer. */
/**
* Returns the ticket+messages only if it actually belongs to this customer,
* with internal-only notes stripped out — this is the customer-facing read
* path (portal, widget), unlike getTicketWithMessages which the admin
* thread view uses and which returns everything.
*/
export async function getTicketForCustomer(customerId: string, ticketId: string) {
const result = await getTicketWithMessages(ticketId);
if (!result || result.ticket.customerId !== customerId) return null;
return result;
return {
ticket: result.ticket,
messages: result.messages.filter((m) => m.visibility === "public"),
};
}
export async function createWidgetSite(name: string, allowedOrigin?: string) {
@@ -446,3 +484,104 @@ export async function createManualTicket(params: {
direction: "in",
});
}
export interface StatsOverview {
totalTickets: number;
openTickets: number;
newToday: number;
avgFirstResponseMinutes: number | null;
statusCounts: Record<TicketStatus, number>;
channelCounts: Record<TicketChannel, number>;
ticketsPerDay: { label: string; count: number }[];
agentWorkload: { name: string; openCount: number }[];
}
/**
* All stats computed in JS over the full table contents rather than SQL
* aggregation — simplest correct option at this ticket volume. Move to
* GROUP BY / date() SQL if the table grows into the tens of thousands.
*/
export async function getStatsOverview(): Promise<StatsOverview> {
const allTickets = await db.query.tickets.findMany();
const statusCounts: Record<TicketStatus, number> = { new: 0, open: 0, pending: 0, closed: 0 };
const channelCounts: Record<TicketChannel, number> = {
telegram: 0,
email: 0,
portal: 0,
widget: 0,
manual: 0,
};
for (const t of allTickets) {
statusCounts[t.status] += 1;
channelCounts[t.channel] += 1;
}
const dayMs = 24 * 60 * 60 * 1000;
const todayStart = new Date();
todayStart.setHours(0, 0, 0, 0);
const newToday = allTickets.filter((t) => t.createdAt.getTime() >= todayStart.getTime()).length;
const ticketsPerDay: { label: string; count: number }[] = [];
for (let i = 13; i >= 0; i--) {
const dayStart = todayStart.getTime() - i * dayMs;
const dayEnd = dayStart + dayMs;
const count = allTickets.filter((t) => {
const ts = t.createdAt.getTime();
return ts >= dayStart && ts < dayEnd;
}).length;
ticketsPerDay.push({
label: new Date(dayStart).toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" }),
count,
});
}
const agentMessages = await db.query.messages.findMany({
where: and(eq(messages.authorType, "agent"), eq(messages.visibility, "public")),
orderBy: messages.createdAt,
});
const firstAgentReplyAt = new Map<string, number>();
for (const m of agentMessages) {
if (!firstAgentReplyAt.has(m.ticketId)) {
firstAgentReplyAt.set(m.ticketId, m.createdAt.getTime());
}
}
const responseTimesMinutes: number[] = [];
for (const t of allTickets) {
const firstReply = firstAgentReplyAt.get(t.id);
if (firstReply) {
responseTimesMinutes.push((firstReply - t.createdAt.getTime()) / 60_000);
}
}
const avgFirstResponseMinutes =
responseTimesMinutes.length > 0
? responseTimesMinutes.reduce((a, b) => a + b, 0) / responseTimesMinutes.length
: null;
const agents = await listAgents();
const openCountByAgent = new Map<string, number>();
let unassignedOpen = 0;
for (const t of allTickets) {
if (t.status === "closed") continue;
if (t.assigneeId) {
openCountByAgent.set(t.assigneeId, (openCountByAgent.get(t.assigneeId) ?? 0) + 1);
} else {
unassignedOpen += 1;
}
}
const agentWorkload = agents.map((a) => ({ name: a.name, openCount: openCountByAgent.get(a.id) ?? 0 }));
if (unassignedOpen > 0) {
agentWorkload.push({ name: "Не назначено", openCount: unassignedOpen });
}
return {
totalTickets: allTickets.length,
openTickets: allTickets.filter((t) => t.status !== "closed").length,
newToday,
avgFirstResponseMinutes,
statusCounts,
channelCounts,
ticketsPerDay,
agentWorkload,
};
}
+2
View File
@@ -3,6 +3,7 @@ export type TicketPriority = "low" | "normal" | "high" | "urgent";
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 interface TicketDTO {
id: string;
@@ -25,5 +26,6 @@ export interface MessageDTO {
authorName: string;
body: string;
direction: MessageDirection;
visibility: MessageVisibility;
createdAt: number;
}