Initial commit: thbd-portal, duplicated from elmi-portal

Rebranded for Thunderbird Portal (THBD): numbering prefix EL->TH, all
"ELMI"/"ЭЛМИ" UI strings genericized, ELMI's real contract templates and
company legal/bank details removed (not applicable to this company), fresh
VAPID keypair and encryption key, fresh single-migration schema history.
Same architecture as elmi-portal: Web Push notifications, unread-chat app
badge, cookie-session auth.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gh2UXUQUVBWroWEnn1FLFG
This commit is contained in:
ogrechkoandClaude Sonnet 5 committed 2026-08-31 16:33:30 +00:00
commit 579528edf7
197 files changed
+25022

No files matched your search

@@ -0,0 +1,101 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
interface Settings {
name: string;
inn: string;
kpp: string;
ogrn: string;
legalAddress: string;
postalAddress: string | null;
bankName: string;
bankAccount: string;
bankBik: string;
bankCorrAccount: string;
email: string | null;
signatoryName: string;
signatoryPosition: string;
signatoryBasis: string;
}
const FIELDS: { key: keyof Settings; label: string; span?: 1 | 2; required?: boolean }[] = [
{ key: "name", label: "Название", span: 2, required: true },
{ key: "inn", label: "ИНН", required: true },
{ key: "kpp", label: "КПП", required: true },
{ key: "ogrn", label: "ОГРН", required: true },
{ key: "email", label: "E-mail" },
{ key: "legalAddress", label: "Юридический адрес", span: 2, required: true },
{ key: "postalAddress", label: "Почтовый адрес (если отличается)", span: 2 },
{ key: "bankName", label: "Банк", span: 2, required: true },
{ key: "bankAccount", label: "Расчётный счёт", required: true },
{ key: "bankBik", label: "БИК", required: true },
{ key: "bankCorrAccount", label: "Корр. счёт", required: true },
{ key: "signatoryName", label: "Подписант (ФИО)", span: 2, required: true },
{ key: "signatoryPosition", label: "Должность подписанта", required: true },
{ key: "signatoryBasis", label: "Основание полномочий", required: true },
];
export function CompanySettingsForm({ initial }: { initial: Settings | undefined }) {
const router = useRouter();
const [values, setValues] = useState<Record<string, string>>(() => {
const v: Record<string, string> = {};
for (const f of FIELDS) v[f.key] = (initial?.[f.key] as string) ?? "";
if (!initial) {
v.signatoryPosition = "генерального директора";
v.signatoryBasis = "Устава";
}
return v;
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
setSaved(false);
const res = await fetch("/api/settings/company", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось сохранить");
return;
}
setSaved(true);
router.refresh();
}
return (
<form onSubmit={handleSubmit} className="card grid grid-cols-1 gap-3 p-4 sm:grid-cols-2">
{FIELDS.map((f) => (
<label key={f.key} className={`text-sm ${f.span === 2 ? "sm:col-span-2" : ""}`}>
<span className="mb-1 block font-medium text-text-muted">{f.label}</span>
<input
required={f.required}
value={values[f.key]}
onChange={(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
))}
{error && <p className="sm:col-span-2 rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
<div className="flex items-center gap-3 sm:col-span-2">
<button type="submit" disabled={loading} className="btn btn-primary">
{loading ? "Сохраняем…" : "Сохранить"}
</button>
{saved && <span className="text-sm text-text-muted">Сохранено</span>}
</div>
</form>
);
}
+24
View File
@@ -0,0 +1,24 @@
import { redirect } from "next/navigation";
import { getCurrentSession } from "@/lib/auth/session";
import { getCompanySettings } from "@/lib/company/settings";
import { CompanySettingsForm } from "./company-settings-form";
export default async function CompanySettingsPage() {
const session = await getCurrentSession();
if (!session) {
redirect("/orders");
}
const settings = await getCompanySettings();
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>
<CompanySettingsForm initial={settings} />
</div>
);
}
@@ -0,0 +1,194 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, Trash2, Pencil, Check, X } from "lucide-react";
interface Contact {
id: string;
name: string;
position: string | null;
phone: string | null;
email: string | null;
notes: string | null;
}
interface FormState {
name: string;
position: string;
phone: string;
email: string;
notes: string;
}
function emptyForm(): FormState {
return { name: "", position: "", phone: "", email: "", notes: "" };
}
export function ContactsList({ counterpartyId, initialContacts }: { counterpartyId: string; initialContacts: Contact[] }) {
const router = useRouter();
const [contacts, setContacts] = useState(initialContacts);
const [form, setForm] = useState<FormState>(emptyForm());
const [showForm, setShowForm] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
const [editForm, setEditForm] = useState<FormState>(emptyForm());
const [saving, setSaving] = useState(false);
async function refresh() {
const res = await fetch(`/api/counterparties/${counterpartyId}/contacts`);
if (res.ok) setContacts(await res.json());
}
async function handleCreate(e: React.FormEvent) {
e.preventDefault();
if (!form.name) return;
setSaving(true);
await fetch(`/api/counterparties/${counterpartyId}/contacts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
setForm(emptyForm());
setShowForm(false);
await refresh();
setSaving(false);
router.refresh();
}
function startEdit(c: Contact) {
setEditingId(c.id);
setEditForm({ name: c.name, position: c.position ?? "", phone: c.phone ?? "", email: c.email ?? "", notes: c.notes ?? "" });
}
async function saveEdit(id: string) {
setSaving(true);
await fetch(`/api/counterparties/${counterpartyId}/contacts/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(editForm),
});
setEditingId(null);
await refresh();
setSaving(false);
router.refresh();
}
async function handleDelete(id: string) {
if (!confirm("Удалить контакт?")) return;
await fetch(`/api/counterparties/${counterpartyId}/contacts/${id}`, { method: "DELETE" });
await refresh();
router.refresh();
}
return (
<div className="card p-4">
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-semibold text-text-muted">Дополнительные контактные лица</h2>
<button onClick={() => setShowForm((v) => !v)} className="btn btn-ghost">
<Plus size={14} />
Добавить
</button>
</div>
{showForm && (
<form onSubmit={handleCreate} className="mb-3 flex flex-wrap items-end gap-3 rounded-md border border-border p-3">
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Имя</span>
<input
required
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Должность</span>
<input
value={form.position}
onChange={(e) => setForm((f) => ({ ...f, position: e.target.value }))}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Телефон</span>
<input
value={form.phone}
onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Email</span>
<input
type="email"
value={form.email}
onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<button type="submit" disabled={saving} className="btn btn-primary">
Сохранить
</button>
</form>
)}
<div className="flex flex-col gap-2">
{contacts.map((c) =>
editingId === c.id ? (
<div key={c.id} className="flex flex-wrap items-end gap-3 rounded-md border border-border bg-surface-hover p-3">
<input
value={editForm.name}
onChange={(e) => setEditForm((f) => ({ ...f, name: e.target.value }))}
placeholder="Имя"
className="rounded-md border border-border bg-surface px-2 py-1.5 text-sm"
/>
<input
value={editForm.position}
onChange={(e) => setEditForm((f) => ({ ...f, position: e.target.value }))}
placeholder="Должность"
className="rounded-md border border-border bg-surface px-2 py-1.5 text-sm"
/>
<input
value={editForm.phone}
onChange={(e) => setEditForm((f) => ({ ...f, phone: e.target.value }))}
placeholder="Телефон"
className="rounded-md border border-border bg-surface px-2 py-1.5 text-sm"
/>
<input
value={editForm.email}
onChange={(e) => setEditForm((f) => ({ ...f, email: e.target.value }))}
placeholder="Email"
className="rounded-md border border-border bg-surface px-2 py-1.5 text-sm"
/>
<div className="flex gap-1">
<button onClick={() => saveEdit(c.id)} disabled={saving} className="btn btn-ghost px-2 text-success">
<Check size={14} />
</button>
<button onClick={() => setEditingId(null)} className="btn btn-ghost px-2">
<X size={14} />
</button>
</div>
</div>
) : (
<div key={c.id} className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2 text-sm">
<div>
<span className="font-medium">{c.name}</span>
{c.position && <span className="text-text-muted"> · {c.position}</span>}
<div className="text-xs text-text-faint">{[c.phone, c.email].filter(Boolean).join(" · ") || "—"}</div>
</div>
<div className="flex gap-1">
<button onClick={() => startEdit(c)} className="btn btn-ghost px-2">
<Pencil size={13} />
</button>
<button onClick={() => handleDelete(c.id)} className="btn btn-ghost px-2 text-danger">
<Trash2 size={13} />
</button>
</div>
</div>
),
)}
{contacts.length === 0 && <p className="text-sm text-text-faint">Пока нет дополнительных контактов.</p>}
</div>
</div>
);
}
@@ -0,0 +1,151 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import type { InferSelectModel } from "drizzle-orm";
import type { counterparties } from "@/lib/db/schema";
type Counterparty = InferSelectModel<typeof counterparties>;
function toDateInputValue(date: Date | null): string {
if (!date) return "";
const d = new Date(date);
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${yyyy}-${mm}-${dd}`;
}
const TEXT_FIELDS: { key: keyof Counterparty; label: string; span?: 1 | 2 }[] = [
{ key: "name", label: "Название", span: 2 },
{ key: "inn", label: "ИНН" },
{ key: "kpp", label: "КПП" },
{ key: "ogrn", label: "ОГРН" },
{ key: "legalAddress", label: "Юридический адрес", span: 2 },
{ key: "postalAddress", label: "Почтовый адрес (если отличается)", span: 2 },
{ key: "bankName", label: "Банк", span: 2 },
{ key: "bankAccount", label: "Расчётный счёт" },
{ key: "bankBik", label: "БИК" },
{ key: "bankCorrAccount", label: "Корр. счёт" },
{ key: "signatoryName", label: "Подписант (ФИО, именительный падеж)", span: 2 },
{ key: "signatoryPosition", label: "Должность подписанта" },
{ key: "signatoryBasis", label: "Основание полномочий" },
{ key: "contactName", label: "Контактное лицо" },
{ key: "contactPhone", label: "Телефон" },
{ key: "contactEmail", label: "Email" },
{ key: "notes", label: "Заметки", span: 2 },
];
export function CounterpartyEditForm({ counterparty }: { counterparty: Counterparty }) {
const router = useRouter();
const [values, setValues] = useState<Record<string, string>>(() => {
const v: Record<string, string> = {};
for (const f of TEXT_FIELDS) v[f.key as string] = (counterparty[f.key] as string) ?? "";
return v;
});
const [kind, setKind] = useState(counterparty.kind);
const [edoType, setEdoType] = useState(counterparty.edoType);
const [contractDate, setContractDate] = useState(toDateInputValue(counterparty.contractDate));
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
setSaved(false);
const res = await fetch(`/api/counterparties/${counterparty.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...values,
kind,
edoType,
contractDate: contractDate || undefined,
}),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось сохранить");
return;
}
setSaved(true);
router.refresh();
}
return (
<form onSubmit={handleSubmit} className="card grid grid-cols-1 gap-3 p-4 sm:grid-cols-2">
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">Тип</span>
<select
value={kind}
onChange={(e) => setKind(e.target.value as Counterparty["kind"])}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
>
<option value="client">Клиент</option>
<option value="carrier">Перевозчик</option>
<option value="both">Клиент и перевозчик</option>
</select>
</label>
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">ЭДО</span>
<select
value={edoType}
onChange={(e) => setEdoType(e.target.value as Counterparty["edoType"])}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
>
<option value="email">Почта</option>
<option value="diadoc">Диадок</option>
<option value="sbis">СБИС</option>
<option value="none">Нет</option>
</select>
</label>
{TEXT_FIELDS.map((f) => (
<label key={f.key as string} className={`text-sm ${f.span === 2 ? "sm:col-span-2" : ""}`}>
<span className="mb-1 block font-medium text-text-muted">{f.label}</span>
<input
required={f.key === "name"}
value={values[f.key as string]}
onChange={(e) => setValues((v) => ({ ...v, [f.key as string]: e.target.value }))}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
))}
<div className="grid grid-cols-2 gap-3 text-sm sm:col-span-2">
<label className="block">
<span className="mb-1 block font-medium text-text-muted">Договор №</span>
<input
value={values.contractNumber}
onChange={(e) => setValues((v) => ({ ...v, contractNumber: e.target.value }))}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="block">
<span className="mb-1 block font-medium text-text-muted">Дата договора</span>
<input
type="date"
value={contractDate}
onChange={(e) => setContractDate(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
</div>
{error && <p className="rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text sm:col-span-2">{error}</p>}
<div className="flex items-center gap-3 sm:col-span-2">
<button type="submit" disabled={loading} className="btn btn-primary">
{loading ? "Сохраняем…" : "Сохранить"}
</button>
{saved && <span className="text-sm text-text-muted">Сохранено</span>}
</div>
</form>
);
}
@@ -0,0 +1,31 @@
import { notFound, redirect } from "next/navigation";
import { getCurrentSession } from "@/lib/auth/session";
import { getCounterparty } from "@/lib/counterparties/service";
import { CounterpartyEditForm } from "./edit-form";
import { ContactsList } from "./contacts-list";
export default async function CounterpartyEditPage({ params }: { params: Promise<{ id: string }> }) {
const session = await getCurrentSession();
if (!session) {
redirect("/orders");
}
const { id } = await params;
const row = await getCounterparty(id);
if (!row) notFound();
return (
<div>
<div className="mb-5">
<h1 className="font-display text-xl font-bold tracking-tight">{row.name}</h1>
<p className="text-sm text-text-muted">Реквизиты контрагента для генерации документов</p>
</div>
<CounterpartyEditForm counterparty={row} />
<div className="mt-4">
<ContactsList counterpartyId={row.id} initialContacts={row.contacts} />
</div>
</div>
);
}
@@ -0,0 +1,105 @@
"use client";
import { useState } from "react";
import Link from "next/link";
interface Row {
id: string;
name: string;
kind: "client" | "carrier" | "both";
inn: string | null;
contractNumber: string | null;
contactName: string | null;
contactPhone: string | null;
edoType: "none" | "email" | "diadoc" | "sbis";
}
const KIND_LABEL: Record<Row["kind"], string> = {
client: "Клиент",
carrier: "Перевозчик",
both: "Клиент и перевозчик",
};
const EDO_LABEL: Record<Row["edoType"], string> = {
none: "Нет",
email: "Почта",
diadoc: "Диадок",
sbis: "СБИС",
};
type Tab = "all" | "client" | "carrier";
const TABS: { key: Tab; label: string }[] = [
{ key: "all", label: "Все" },
{ key: "client", label: "Клиенты" },
{ key: "carrier", label: "Исполнители" },
];
export function CounterpartiesTable({ rows }: { rows: Row[] }) {
const [tab, setTab] = useState<Tab>("all");
const visible = rows.filter((r) => {
if (tab === "all") return true;
if (tab === "client") return r.kind === "client" || r.kind === "both";
return r.kind === "carrier" || r.kind === "both";
});
return (
<div>
<div className="mb-3 flex gap-1">
{TABS.map((t) => (
<button
key={t.key}
onClick={() => setTab(t.key)}
className={`rounded-md px-3 py-1.5 text-sm font-medium ${
tab === t.key ? "bg-accent-soft text-accent-soft-text" : "text-text-muted hover:bg-surface-hover"
}`}
>
{t.label}
</button>
))}
</div>
<div className="card overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-text-muted">
<th className="px-4 py-3 font-medium">Название</th>
<th className="px-4 py-3 font-medium">Тип</th>
<th className="px-4 py-3 font-medium">ИНН</th>
<th className="px-4 py-3 font-medium">Договор</th>
<th className="px-4 py-3 font-medium">Контакт</th>
<th className="px-4 py-3 font-medium">ЭДО</th>
</tr>
</thead>
<tbody>
{visible.map((c) => (
<tr key={c.id} className="border-b border-border last:border-0 hover:bg-surface-hover">
<td className="px-4 py-3 font-medium">
<Link href={`/settings/counterparties/${c.id}`} className="hover:text-accent hover:underline">
{c.name}
</Link>
</td>
<td className="px-4 py-3 text-text-muted">{KIND_LABEL[c.kind]}</td>
<td className="px-4 py-3 text-text-muted">{c.inn || "—"}</td>
<td className="px-4 py-3 text-text-muted">{c.contractNumber || "—"}</td>
<td className="px-4 py-3 text-text-muted">
{c.contactName || "—"}
{c.contactPhone ? `, ${c.contactPhone}` : ""}
</td>
<td className="px-4 py-3 text-text-muted">{EDO_LABEL[c.edoType]}</td>
</tr>
))}
{visible.length === 0 && (
<tr>
<td colSpan={6} className="px-4 py-8 text-center text-text-faint">
{tab === "all" ? "Пока нет контрагентов." : "Нет контрагентов в этой категории."}
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,213 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { X } from "lucide-react";
export function NewCounterpartyModal({ open, onClose }: { open: boolean; onClose: () => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [kind, setKind] = useState<"client" | "carrier" | "both">("client");
const [inn, setInn] = useState("");
const [contractNumber, setContractNumber] = useState("");
const [contractDate, setContractDate] = useState("");
const [postalAddress, setPostalAddress] = useState("");
const [contactName, setContactName] = useState("");
const [contactPhone, setContactPhone] = useState("");
const [contactEmail, setContactEmail] = useState("");
const [edoType, setEdoType] = useState<"none" | "diadoc" | "sbis" | "email">("email");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
function reset() {
setName("");
setKind("client");
setInn("");
setContractNumber("");
setContractDate("");
setPostalAddress("");
setContactName("");
setContactPhone("");
setContactEmail("");
setEdoType("email");
setError(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const res = await fetch("/api/counterparties", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
kind,
inn,
contractNumber,
contractDate: contractDate || undefined,
postalAddress,
contactName,
contactPhone,
contactEmail,
edoType,
}),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось создать контрагента");
return;
}
reset();
onClose();
router.refresh();
}
return (
<AnimatePresence>
{open && (
<motion.div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onClose}
>
<motion.form
onClick={(e) => e.stopPropagation()}
onSubmit={handleSubmit}
initial={{ opacity: 0, y: 12, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 12, scale: 0.98 }}
transition={{ duration: 0.2, ease: "easeOut" }}
className="card w-full max-w-md p-5"
>
<div className="mb-4 flex items-center justify-between">
<h2 className="text-base font-semibold">Новый контрагент</h2>
<button type="button" onClick={onClose} className="text-text-muted hover:text-text">
<X size={18} />
</button>
</div>
<label className="mb-3 block text-sm">
<span className="mb-1 block font-medium text-text-muted">Название</span>
<input
required
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 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">Тип</span>
<select
value={kind}
onChange={(e) => setKind(e.target.value as typeof kind)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
>
<option value="client">Клиент</option>
<option value="carrier">Перевозчик</option>
<option value="both">Клиент и перевозчик</option>
</select>
</label>
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">ИНН</span>
<input
value={inn}
onChange={(e) => setInn(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
</div>
<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">Договор №</span>
<input
value={contractNumber}
onChange={(e) => setContractNumber(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">Дата договора</span>
<input
type="date"
value={contractDate}
onChange={(e) => setContractDate(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 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
value={postalAddress}
onChange={(e) => setPostalAddress(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 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">Контактное лицо</span>
<input
value={contactName}
onChange={(e) => setContactName(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">Телефон</span>
<input
value={contactPhone}
onChange={(e) => setContactPhone(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
</div>
<div className="mb-4 grid grid-cols-2 gap-3">
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">Email</span>
<input
type="email"
value={contactEmail}
onChange={(e) => setContactEmail(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">ЭДО</span>
<select
value={edoType}
onChange={(e) => setEdoType(e.target.value as typeof edoType)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
>
<option value="email">Почта</option>
<option value="diadoc">Диадок</option>
<option value="sbis">СБИС</option>
<option value="none">Нет</option>
</select>
</label>
</div>
{error && <p className="mb-3 rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
<button type="submit" disabled={loading} className="btn btn-primary w-full justify-center">
{loading ? "Создаём…" : "Создать"}
</button>
</motion.form>
</motion.div>
)}
</AnimatePresence>
);
}
@@ -0,0 +1,25 @@
import { redirect } from "next/navigation";
import { getCurrentSession } from "@/lib/auth/session";
import { listCounterparties } from "@/lib/counterparties/service";
import { CounterpartiesToolbar } from "./toolbar";
import { CounterpartiesTable } from "./counterparties-table";
export default async function CounterpartiesPage() {
const session = await getCurrentSession();
if (!session) {
redirect("/orders");
}
const rows = await listCounterparties();
return (
<div>
<div className="mb-5 flex items-center justify-between">
<h1 className="font-display text-xl font-bold tracking-tight">Контрагенты</h1>
<CounterpartiesToolbar />
</div>
<CounterpartiesTable rows={rows} />
</div>
);
}
@@ -0,0 +1,18 @@
"use client";
import { useState } from "react";
import { Plus } from "lucide-react";
import { NewCounterpartyModal } from "./new-counterparty-modal";
export function CounterpartiesToolbar() {
const [open, setOpen] = useState(false);
return (
<>
<button className="btn btn-primary" onClick={() => setOpen(true)}>
<Plus size={16} />
Новый контрагент
</button>
<NewCounterpartyModal open={open} onClose={() => setOpen(false)} />
</>
);
}
@@ -0,0 +1,127 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
interface Status {
configured: boolean;
enabled: boolean;
user: string | null;
imapHost: string | null;
verifiedAt: number | null;
}
export function MailboxForm({ status }: { status: Status }) {
const router = useRouter();
const [imapHost, setImapHost] = useState(status.imapHost ?? "");
const [imapPort, setImapPort] = useState("993");
const [user, setUser] = useState(status.user ?? "");
const [password, setPassword] = useState("");
const [allowInsecureTls, setAllowInsecureTls] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const res = await fetch("/api/settings/mailbox", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ imapHost, imapPort: Number(imapPort), user, password, allowInsecureTls }),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось подключиться к почтовому ящику");
return;
}
setPassword("");
router.refresh();
}
async function handleDisable() {
setLoading(true);
await fetch("/api/settings/mailbox", { method: "DELETE" });
setLoading(false);
router.refresh();
}
return (
<div className="card p-4">
<h2 className="mb-3 text-sm font-semibold text-text-muted">Почтовый ящик для запросов (IMAP)</h2>
<div className="mb-4 text-sm">
{status.configured ? (
<p className="text-text-muted">
{status.enabled ? "Активен" : "Отключен"}: {status.user} @ {status.imapHost}
{status.verifiedAt && ` — проверен ${new Date(status.verifiedAt).toLocaleString("ru-RU")}`}
</p>
) : (
<p className="text-text-faint">Ещё не настроен.</p>
)}
</div>
<form onSubmit={handleSubmit} className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">IMAP-сервер</span>
<input
required
value={imapHost}
onChange={(e) => setImapHost(e.target.value)}
placeholder="imap.yandex.ru"
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Порт</span>
<input
type="number"
required
value={imapPort}
onChange={(e) => setImapPort(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Логин</span>
<input
required
value={user}
onChange={(e) => setUser(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Пароль</span>
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="flex items-center gap-2 text-sm sm:col-span-2">
<input type="checkbox" checked={allowInsecureTls} onChange={(e) => setAllowInsecureTls(e.target.checked)} />
<span className="text-text-muted">Разрешить недоверенный TLS-сертификат</span>
</label>
{error && <p className="sm:col-span-2 rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
<div className="flex gap-2 sm:col-span-2">
<button type="submit" disabled={loading} className="btn btn-primary">
{loading ? "Проверяем…" : "Проверить и сохранить"}
</button>
{status.configured && status.enabled && (
<button type="button" onClick={handleDisable} disabled={loading} className="btn btn-ghost">
Отключить
</button>
)}
</div>
</form>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { redirect } from "next/navigation";
import { getCurrentSession } from "@/lib/auth/session";
import { getMailboxStatus } from "@/lib/mail/config";
import { MailboxForm } from "./mailbox-form";
export default async function EmailSettingsPage() {
const session = await getCurrentSession();
if (!session) redirect("/orders");
const status = await getMailboxStatus();
return (
<div>
<h1 className="mb-1 font-display text-xl font-bold tracking-tight">Почта</h1>
<p className="mb-5 text-sm text-text-muted">
Входящие письма распознаются через Claude в черновики запросов — менеджер подтверждает их на странице{" "}
«Запросы» перед созданием настоящего запроса.
</p>
<MailboxForm status={status} />
</div>
);
}
+26
View File
@@ -0,0 +1,26 @@
import Link from "next/link";
export default function SettingsLayout({ children }: { children: React.ReactNode }) {
return (
<div>
<div className="mb-5 flex gap-1 border-b border-border">
<Link href="/settings/company" className="px-3 py-2 text-sm font-medium text-text-muted hover:text-text">
Компания
</Link>
<Link href="/settings/counterparties" className="px-3 py-2 text-sm font-medium text-text-muted hover:text-text">
Контрагенты
</Link>
<Link href="/settings/users" className="px-3 py-2 text-sm font-medium text-text-muted hover:text-text">
Пользователи
</Link>
<Link href="/settings/templates" className="px-3 py-2 text-sm font-medium text-text-muted hover:text-text">
Шаблоны
</Link>
<Link href="/settings/email" className="px-3 py-2 text-sm font-medium text-text-muted hover:text-text">
Почта
</Link>
</div>
{children}
</div>
);
}
@@ -0,0 +1,78 @@
import { redirect } from "next/navigation";
import { getCurrentSession } from "@/lib/auth/session";
import { listTemplates } from "@/lib/documents/templates";
import { UploadTemplateForm } from "./upload-form";
const KIND_LABEL: Record<string, string> = {
power_of_attorney: "Доверенность",
forwarder_receipt: "Экспедиторская расписка",
contract_teo_forwarder: "Договор ТЭУ (наша компания — Экспедитор)",
contract_teo_customer: "Договор ТЭО (наша компания — Заказчик)",
appendix_order_forwarder: "Приложение — Поручение + Расписка (наша компания — Экспедитор)",
appendix_order_customer: "Приложение — Поручение + Расписка (наша компания — Заказчик)",
order_agreement_road_forwarder: "Договор-заявка на автоперевозку (наша компания — Экспедитор)",
order_agreement_teo_customer: "Договор-заявка на ТЭО (наша компания — Заказчик)",
other: "Другое",
};
export default async function TemplatesPage() {
const session = await getCurrentSession();
if (!session) redirect("/orders");
const templates = await listTemplates();
return (
<div>
<div className="mb-5 flex items-center justify-between">
<h1 className="font-display text-xl font-bold tracking-tight">Шаблоны документов</h1>
</div>
<p className="mb-4 text-sm text-text-muted">
Стартовые шаблоны загружаются в Настройки → Шаблоны. Загружая свой .docx взамен, используйте теги: заявка —{" "}
<code className="rounded bg-surface-hover px-1">{"{order_number}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{order_date}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{contract_date}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{cargo_description}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{route_from}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{route_to}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{flight_number}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{manager_name}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{load_date}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{unload_plan_date}"}</code>; доверенность —{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_number}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_date}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_valid_until}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_driver_name}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_driver_passport}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_vehicle_model}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{poa_vehicle_plate}"}</code>; реквизиты сторон — с
префиксом <code className="rounded bg-surface-hover px-1">{"company_*"}</code> (наша компания, из Настройки → Компания)
и <code className="rounded bg-surface-hover px-1">{"customer_*"}</code> (контрагент заявки), например{" "}
<code className="rounded bg-surface-hover px-1">{"{company_name}"}</code>,{" "}
<code className="rounded bg-surface-hover px-1">{"{customer_signatory_short}"}</code>. Полный список — в{" "}
<code className="rounded bg-surface-hover px-1">buildTemplateData</code>.
</p>
<div className="card mb-5 overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-text-muted">
<th className="px-4 py-3 font-medium">Название</th>
<th className="px-4 py-3 font-medium">Тип</th>
</tr>
</thead>
<tbody>
{templates.map((t) => (
<tr key={t.id} className="border-b border-border last:border-0">
<td className="px-4 py-3">{t.name}</td>
<td className="px-4 py-3 text-text-muted">{KIND_LABEL[t.kind]}</td>
</tr>
))}
</tbody>
</table>
</div>
<UploadTemplateForm />
</div>
);
}
@@ -0,0 +1,90 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
const KIND_OPTIONS = [
{ value: "power_of_attorney", label: "Доверенность" },
{ value: "forwarder_receipt", label: "Экспедиторская расписка" },
{ value: "contract_teo_forwarder", label: "Договор ТЭУ (наша компания — Экспедитор)" },
{ value: "contract_teo_customer", label: "Договор ТЭО (наша компания — Заказчик)" },
{ value: "appendix_order_forwarder", label: "Приложение — Поручение + Расписка (наша компания — Экспедитор)" },
{ value: "appendix_order_customer", label: "Приложение — Поручение + Расписка (наша компания — Заказчик)" },
{ value: "order_agreement_road_forwarder", label: "Договор-заявка на автоперевозку (наша компания — Экспедитор)" },
{ value: "order_agreement_teo_customer", label: "Договор-заявка на ТЭО (наша компания — Заказчик)" },
{ value: "other", label: "Другое" },
];
export function UploadTemplateForm() {
const router = useRouter();
const [name, setName] = useState("");
const [kind, setKind] = useState("power_of_attorney");
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!file) return;
setLoading(true);
setError(null);
const form = new FormData();
form.set("name", name);
form.set("kind", kind);
form.set("file", file);
const res = await fetch("/api/templates", { method: "POST", body: form });
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось загрузить шаблон");
return;
}
setName("");
setFile(null);
router.refresh();
}
return (
<form onSubmit={handleSubmit} className="card flex flex-wrap items-end gap-2 p-4">
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Название</span>
<input
required
value={name}
onChange={(e) => setName(e.target.value)}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Тип</span>
<select
value={kind}
onChange={(e) => setKind(e.target.value)}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
>
{KIND_OPTIONS.map((k) => (
<option key={k.value} value={k.value}>
{k.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Файл .docx</span>
<input
type="file"
required
accept=".docx"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
className="rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<button type="submit" disabled={loading} className="btn btn-primary">
{loading ? "Загружаем…" : "Загрузить"}
</button>
{error && <p className="w-full text-sm text-danger-soft-text">{error}</p>}
</form>
);
}
@@ -0,0 +1,152 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { X } from "lucide-react";
export function NewUserModal({ open, onClose }: { open: boolean; onClose: () => void }) {
const router = useRouter();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [name, setName] = useState("");
const [role, setRole] = useState<"admin" | "manager" | "accountant">("manager");
const [managerNumber, setManagerNumber] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
function reset() {
setEmail("");
setPassword("");
setName("");
setRole("manager");
setManagerNumber("");
setError(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email,
password,
name,
role,
managerNumber: role === "manager" && managerNumber ? Number(managerNumber) : undefined,
}),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось создать пользователя");
return;
}
reset();
onClose();
router.refresh();
}
return (
<AnimatePresence>
{open && (
<motion.div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onClose}
>
<motion.form
onClick={(e) => e.stopPropagation()}
onSubmit={handleSubmit}
initial={{ opacity: 0, y: 12, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 12, scale: 0.98 }}
transition={{ duration: 0.2, ease: "easeOut" }}
className="card w-full max-w-md p-5"
>
<div className="mb-4 flex items-center justify-between">
<h2 className="text-base font-semibold">Новый пользователь</h2>
<button type="button" onClick={onClose} className="text-text-muted hover:text-text">
<X size={18} />
</button>
</div>
<label className="mb-3 block text-sm">
<span className="mb-1 block font-medium text-text-muted">Имя</span>
<input
required
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<label className="mb-3 block text-sm">
<span className="mb-1 block font-medium text-text-muted">Email</span>
<input
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 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
type="password"
required
minLength={8}
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
<div className="mb-4 grid grid-cols-2 gap-3">
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">Роль</span>
<select
value={role}
onChange={(e) => setRole(e.target.value as typeof role)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
>
<option value="manager">Менеджер</option>
<option value="accountant">Бухгалтер</option>
<option value="admin">Администратор</option>
</select>
</label>
{role === "manager" && (
<label className="block text-sm">
<span className="mb-1 block font-medium text-text-muted">Номер менеджера</span>
<input
type="number"
required
value={managerNumber}
onChange={(e) => setManagerNumber(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-accent"
/>
</label>
)}
</div>
{error && <p className="mb-3 rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
<button type="submit" disabled={loading} className="btn btn-primary w-full justify-center">
{loading ? "Создаём…" : "Создать"}
</button>
</motion.form>
</motion.div>
)}
</AnimatePresence>
);
}
+51
View File
@@ -0,0 +1,51 @@
import { redirect } from "next/navigation";
import { getCurrentSession } from "@/lib/auth/session";
import { listUsers } from "@/lib/users/service";
import { UsersToolbar } from "./toolbar";
const ROLE_LABEL: Record<string, string> = {
admin: "Администратор",
manager: "Менеджер",
accountant: "Бухгалтер",
};
export default async function UsersPage() {
const session = await getCurrentSession();
if (!session) {
redirect("/orders");
}
const rows = await listUsers();
return (
<div>
<div className="mb-5 flex items-center justify-between">
<h1 className="font-display text-xl font-bold tracking-tight">Пользователи</h1>
<UsersToolbar />
</div>
<div className="card overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-text-muted">
<th className="px-4 py-3 font-medium">Имя</th>
<th className="px-4 py-3 font-medium">Email</th>
<th className="px-4 py-3 font-medium">Роль</th>
<th className="px-4 py-3 font-medium">№ менеджера</th>
</tr>
</thead>
<tbody>
{rows.map((u) => (
<tr key={u.id} className="border-b border-border last:border-0">
<td className="px-4 py-3 font-medium">{u.name}</td>
<td className="px-4 py-3 text-text-muted">{u.email}</td>
<td className="px-4 py-3 text-text-muted">{ROLE_LABEL[u.role]}</td>
<td className="px-4 py-3 text-text-muted">{u.managerNumber ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,18 @@
"use client";
import { useState } from "react";
import { Plus } from "lucide-react";
import { NewUserModal } from "./new-user-modal";
export function UsersToolbar() {
const [open, setOpen] = useState(false);
return (
<>
<button className="btn btn-primary" onClick={() => setOpen(true)}>
<Plus size={16} />
Новый пользователь
</button>
<NewUserModal open={open} onClose={() => setOpen(false)} />
</>
);
}