Add email channel: IMAP IDLE inbound, SMTP outbound, thread matching
Inbound mail on support@top-sysops.ru creates/updates tickets in realtime (IMAP IDLE, not polling). Replies thread via In-Reply-To/References against stored Message-IDs, falling back to the customer's open ticket. Mailbox credentials configured and encrypted via Settings -> Почта, same pattern as the Telegram channel. TLS verification is opt-in-skippable per mailbox (mail.top-sysops.ru's cert is currently expired; LAN-only server). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QcXH24ky6zjk2UyK5oZUPH
This commit is contained in:
1 parent
cf0b6cf58e
commit
7e62ed739b
18 files changed
+1739
-7
No files matched your search
@@ -3,7 +3,7 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { Send, Globe, UserRound, Plus } from "lucide-react";
|
||||
import { Send, Globe, UserRound, Mail, Plus } from "lucide-react";
|
||||
import { useTicketEvents } from "@/lib/events/use-ticket-events";
|
||||
import { formatRelativeTime } from "@/lib/format";
|
||||
import type { TicketDTO, TicketStatus } from "@/lib/tickets/types";
|
||||
@@ -16,7 +16,7 @@ const COLUMNS: { status: TicketStatus; label: string }[] = [
|
||||
{ status: "closed", label: "Закрытые" },
|
||||
];
|
||||
|
||||
const CHANNEL_ICON = { telegram: Send, portal: Globe, manual: UserRound } as const;
|
||||
const CHANNEL_ICON = { telegram: Send, portal: Globe, manual: UserRound, email: Mail } as const;
|
||||
|
||||
const PRIORITY_COLOR: Record<TicketDTO["priority"], string> = {
|
||||
low: "var(--text-faint)",
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { LayoutDashboard, Settings } from "lucide-react";
|
||||
import { LayoutDashboard, Send, Mail } from "lucide-react";
|
||||
|
||||
const links = [
|
||||
{ href: "/dashboard", label: "Дашборд", icon: LayoutDashboard },
|
||||
{ href: "/settings/telegram", label: "Telegram", icon: Settings },
|
||||
{ href: "/settings/telegram", label: "Telegram", icon: Send },
|
||||
{ href: "/settings/email", label: "Почта", icon: Mail },
|
||||
];
|
||||
|
||||
export function NavLinks() {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { CheckCircle2, XCircle } from "lucide-react";
|
||||
|
||||
interface Status {
|
||||
configured: boolean;
|
||||
enabled: boolean;
|
||||
user: string | null;
|
||||
imapHost: string | null;
|
||||
allowInsecureTls: boolean;
|
||||
verifiedAt: number | null;
|
||||
}
|
||||
|
||||
export function MailboxSettingsForm({ initialStatus }: { initialStatus: Status }) {
|
||||
const [status, setStatus] = useState(initialStatus);
|
||||
const [host, setHost] = useState(initialStatus.imapHost ?? "");
|
||||
const [imapPort, setImapPort] = useState("993");
|
||||
const [smtpPort, setSmtpPort] = useState("587");
|
||||
const [user, setUser] = useState(initialStatus.user ?? "");
|
||||
const [password, setPassword] = useState("");
|
||||
const [allowInsecureTls, setAllowInsecureTls] = useState(true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleConnect(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await fetch("/api/mailbox/config", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
host,
|
||||
imapPort: Number(imapPort),
|
||||
smtpPort: Number(smtpPort),
|
||||
user,
|
||||
password,
|
||||
allowInsecureTls,
|
||||
}),
|
||||
});
|
||||
|
||||
setLoading(false);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
setError(data?.error ?? "Не удалось подключить почту");
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus({ configured: true, enabled: true, user, imapHost: host, allowInsecureTls, verifiedAt: Date.now() });
|
||||
setPassword("");
|
||||
}
|
||||
|
||||
async function handleDisable() {
|
||||
setLoading(true);
|
||||
await fetch("/api/mailbox/config", { method: "DELETE" });
|
||||
setLoading(false);
|
||||
setStatus((s) => ({ ...s, enabled: false }));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card p-5">
|
||||
<div className="mb-4 flex items-center gap-2 text-sm">
|
||||
{status.enabled ? (
|
||||
<>
|
||||
<CheckCircle2 size={16} className="text-success" />
|
||||
<span>Подключено: {status.user}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle size={16} className="text-text-faint" />
|
||||
<span className="text-text-muted">Почта не подключена</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleConnect}>
|
||||
<label className="mb-3 block text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">Хост (IMAP и SMTP)</span>
|
||||
<input
|
||||
required
|
||||
value={host}
|
||||
onChange={(e) => setHost(e.target.value)}
|
||||
placeholder="mail.top-sysops.ru или 10.33.33.42"
|
||||
className="w-full rounded-md border border-border bg-surface px-3 py-2 font-mono text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="mb-3 grid grid-cols-2 gap-3">
|
||||
<label className="block text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">IMAP порт</span>
|
||||
<input
|
||||
required
|
||||
value={imapPort}
|
||||
onChange={(e) => setImapPort(e.target.value)}
|
||||
className="w-full rounded-md border border-border bg-surface px-3 py-2 font-mono text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">SMTP порт</span>
|
||||
<input
|
||||
required
|
||||
value={smtpPort}
|
||||
onChange={(e) => setSmtpPort(e.target.value)}
|
||||
className="w-full rounded-md border border-border bg-surface px-3 py-2 font-mono text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="mb-3 block text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">Логин</span>
|
||||
<input
|
||||
required
|
||||
type="email"
|
||||
value={user}
|
||||
onChange={(e) => setUser(e.target.value)}
|
||||
placeholder="support@top-sysops.ru"
|
||||
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="mb-3 block text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">Пароль</span>
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(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 flex items-center gap-2 text-sm text-text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allowInsecureTls}
|
||||
onChange={(e) => setAllowInsecureTls(e.target.checked)}
|
||||
/>
|
||||
Не проверять TLS-сертификат сервера (нужно, пока сертификат просрочен)
|
||||
</label>
|
||||
|
||||
{error && <p className="mb-3 rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={loading} className="btn btn-primary">
|
||||
{status.configured ? "Обновить" : "Подключить"}
|
||||
</button>
|
||||
{status.enabled && (
|
||||
<button type="button" onClick={handleDisable} disabled={loading} className="btn btn-ghost">
|
||||
Отключить
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { getMailboxStatus } from "@/lib/mail/config";
|
||||
import { MailboxSettingsForm } from "./mailbox-settings-form";
|
||||
|
||||
export default async function EmailSettingsPage() {
|
||||
const status = await getMailboxStatus();
|
||||
return (
|
||||
<div className="max-w-lg">
|
||||
<h1 className="mb-1 text-xl font-bold tracking-tight">Почта</h1>
|
||||
<p className="mb-6 text-sm text-text-muted">
|
||||
Письма на этот ящик будут превращаться в заявки, ответы агентов уходят обратно по SMTP.
|
||||
</p>
|
||||
<MailboxSettingsForm initialStatus={status} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/auth/require";
|
||||
import { getMailboxStatus } from "@/lib/mail/config";
|
||||
import { configureMailbox, disableMailListener } from "@/lib/mail/imap";
|
||||
import { verifySmtp } from "@/lib/mail/smtp";
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
if (!session) return response;
|
||||
|
||||
return NextResponse.json(await getMailboxStatus());
|
||||
}
|
||||
|
||||
const configureSchema = z.object({
|
||||
host: z.string().min(1),
|
||||
imapPort: z.coerce.number().int().positive(),
|
||||
smtpPort: z.coerce.number().int().positive(),
|
||||
user: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
allowInsecureTls: z.boolean(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { session, response } = await requireSession();
|
||||
if (!session) return response;
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = configureSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
const settings = {
|
||||
imapHost: parsed.data.host,
|
||||
imapPort: parsed.data.imapPort,
|
||||
smtpHost: parsed.data.host,
|
||||
smtpPort: parsed.data.smtpPort,
|
||||
user: parsed.data.user,
|
||||
password: parsed.data.password,
|
||||
allowInsecureTls: parsed.data.allowInsecureTls,
|
||||
};
|
||||
|
||||
try {
|
||||
await verifySmtp(settings);
|
||||
await configureMailbox(settings);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Unknown error";
|
||||
return NextResponse.json({ error: `Не удалось подключиться: ${message}` }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE() {
|
||||
const { session, response } = await requireSession();
|
||||
if (!session) return response;
|
||||
|
||||
await disableMailListener();
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -3,8 +3,9 @@ export const runtime = "nodejs";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/auth/require";
|
||||
import { recordAgentReply } from "@/lib/tickets/service";
|
||||
import { recordAgentReply, 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";
|
||||
@@ -24,11 +25,30 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
|
||||
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
const ticket = await db.query.tickets.findFirst({ where: (t, { eq: eqOp }) => eqOp(t.id, id) });
|
||||
if (!ticket) {
|
||||
return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
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") {
|
||||
|
||||
Reference in new issue
Block a user