Files
shoplix/web-admin/src/main.tsx
T

484 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import {
Boxes,
Code2,
ChevronDown,
FileText,
FolderTree,
HelpCircle,
Image,
Mail,
Newspaper,
PanelsTopLeft,
Paintbrush,
Plus,
Search,
Settings,
Users,
X,
} from "lucide-react";
import "./styles.css";
import ProductEditor from "./ProductEditor";
import ContentEditor from "./ContentEditor";
import CategoryManager from "./CategoryManager";
import InquirySettingsPanel from "./InquirySettingsPanel";
import PageEditor from "./PageEditor";
import DecorationEditor from "./DecorationEditor";
import CustomCodeManager from "./CustomCodeManager";
import MediaCenter from "./MediaCenter";
const API = "http://localhost:8081/api/admin/v1";
const SITE_WEB = "http://localhost:5174";
const SITE = "SIT0000000000001";
type Section = "products" | "product-categories" | "NEWS" | "NEWS-categories" | "CASE" | "CASE-categories" | "HELP" | "HELP-categories" | "pages" | "decoration" | "custom-code" | "media" | "inquiries" | "inquiry-settings";
type EditorialSection = "NEWS" | "CASE" | "HELP";
type ContentEditorState = { contentType: EditorialSection; contentCode: string };
type Item = {
productCode?: string;
contentCode?: string;
pageCode?: string;
productName?: string;
title?: string;
pageName?: string;
slug: string;
status: string;
model?: string;
publishTime?: string;
inquiryCode?: string;
customerName?: string;
customerEmail?: string;
companyName?: string;
countryCode?: string;
clientIp?: string;
sourceType?: string;
statusLabel?: string;
createTime?: string;
};
async function post(path: string, body: unknown) {
const response = await fetch(API + path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok)
throw new Error((await response.json()).message || "请求失败");
return response.json();
}
const menus = [
{ key: "pages" as Section, label: "页面", icon: FileText },
{ key: "decoration" as Section, label: "店铺装修", icon: Paintbrush },
{ key: "custom-code" as Section, label: "自定义代码", icon: Code2 },
{ key: "media" as Section, label: "素材中心", icon: Image },
{ key: "inquiries" as Section, label: "询盘", icon: Mail },
];
const sectionLabels: Record<Section, string> = {
products: "产品", "product-categories": "产品分类", NEWS: "新闻", "NEWS-categories": "新闻分类",
CASE: "案例", "CASE-categories": "案例分类", HELP: "帮助", "HELP-categories": "帮助分类",
pages: "页面", decoration: "店铺装修", "custom-code": "自定义代码", media: "素材中心", inquiries: "询盘", "inquiry-settings": "询盘设置",
};
const statusLabels: Record<string, string> = { DRAFT: "草稿", PUBLISHED: "已上架", OFFLINE: "已下架" };
function App() {
const contentRoutes: Record<EditorialSection, string> = { NEWS: "news", CASE: "cases", HELP: "help" };
const resolveContentRoute = (): ContentEditorState | null => {
const match = window.location.pathname.match(/^\/(news|cases|help)\/(new|([^/]+)\/edit)$/);
if (!match) return null;
const contentType = ({ news: "NEWS", cases: "CASE", help: "HELP" } as const)[match[1] as "news" | "cases" | "help"];
return { contentType, contentCode: match[2] === "new" ? "" : decodeURIComponent(match[3]) };
};
const initialContentEditor = resolveContentRoute();
const [section, setSection] = useState<Section>(initialContentEditor?.contentType || (window.location.pathname.startsWith("/pages/") ? "pages" : "products"));
const [items, setItems] = useState<Item[]>([]);
const [error, setError] = useState("");
const [query, setQuery] = useState("");
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const resolveProductRoute = () => {
if (window.location.pathname === "/products/new") return "";
const match = window.location.pathname.match(/^\/products\/([^/]+)\/edit$/);
return match ? decodeURIComponent(match[1]) : null;
};
const resolvePageRoute = () => {
if (window.location.pathname === "/pages/new") return "";
const match = window.location.pathname.match(/^\/pages\/([^/]+)\/edit$/);
return match ? decodeURIComponent(match[1]) : null;
};
const [editingProduct, setEditingProduct] = useState<string | null>(resolveProductRoute);
const [editingContent, setEditingContent] = useState<ContentEditorState | null>(initialContentEditor);
const [editingPage, setEditingPage] = useState<string | null>(resolvePageRoute);
const [productMenuOpen, setProductMenuOpen] = useState(true);
const [contentMenuOpen, setContentMenuOpen] = useState(true);
const navigateSection = (next: Section) => {
setEditingProduct(null);
setEditingContent(null);
setEditingPage(null);
setSection(next);
window.history.pushState({}, "", "/");
};
const [form, setForm] = useState({
name: "",
slug: "",
summary: "",
body: "",
model: "",
status: "DRAFT",
});
const load = async () => {
try {
setError("");
const data =
section.endsWith("-categories")
? { items: [] }
: section === "products"
? await post("/products/list", { siteCode: SITE })
: section === "pages"
? await post("/pages/list", { siteCode: SITE })
: section === "decoration"
? { items: [] }
: section === "inquiries"
? await post("/inquiries/list", { siteCode: SITE })
: section === "inquiry-settings"
? { items: [] }
: await post("/contents/list", {
siteCode: SITE,
contentType: section,
});
setItems(data.items || []);
} catch (e) {
setError(e instanceof Error ? e.message : "加载失败");
setItems([]);
}
};
useEffect(() => {
void load();
}, [section]);
useEffect(() => {
const handlePopState = () => {
setEditingProduct(resolveProductRoute());
setEditingPage(resolvePageRoute());
const content = resolveContentRoute();
setEditingContent(content);
if (content) setSection(content.contentType);
};
window.addEventListener("popstate", handlePopState);
return () => window.removeEventListener("popstate", handlePopState);
}, []);
const openProductEditor = (productCode?: string) => {
const path = productCode
? `/products/${encodeURIComponent(productCode)}/edit`
: "/products/new";
window.history.pushState({}, "", path);
setEditingProduct(productCode || "");
};
const closeProductEditor = () => {
window.history.pushState({}, "", "/");
setEditingProduct(null);
void load();
};
const openContentEditor = (contentType: EditorialSection, contentCode?: string) => {
const route = contentRoutes[contentType];
const path = contentCode ? `/${route}/${encodeURIComponent(contentCode)}/edit` : `/${route}/new`;
window.history.pushState({}, "", path);
setEditingContent({ contentType, contentCode: contentCode || "" });
};
const closeContentEditor = () => {
window.history.pushState({}, "", "/");
setEditingContent(null);
};
const openPageEditor = (pageCode?: string) => {
window.history.pushState({}, "", pageCode ? `/pages/${encodeURIComponent(pageCode)}/edit` : "/pages/new");
setEditingPage(pageCode || "");
};
const closePageEditor = () => {
window.history.pushState({}, "", "/");
setEditingPage(null);
};
const title = sectionLabels[section];
const filtered = items.filter((x) =>
JSON.stringify(x).toLowerCase().includes(query.toLowerCase()),
);
const changeItemStatus = async (item: Item) => {
const status = item.status === "PUBLISHED" ? "OFFLINE" : "PUBLISHED";
try {
setError("");
if (section === "products" && item.productCode)
await post("/products/status", { siteCode: SITE, productCode: item.productCode, status });
else if (["NEWS", "CASE", "HELP"].includes(section) && item.contentCode)
await post("/contents/status", { siteCode: SITE, contentCode: item.contentCode, contentType: section, status });
await load();
} catch (operationError) { setError(operationError instanceof Error ? operationError.message : "状态更新失败"); }
};
const deleteItem = async (item: Item) => {
if (!window.confirm("删除后该内容将不再展示,确认删除吗?")) return;
try {
setError("");
if (section === "products" && item.productCode)
await post("/products/delete", { siteCode: SITE, productCode: item.productCode });
else if (["NEWS", "CASE", "HELP"].includes(section) && item.contentCode)
await post("/contents/delete", { siteCode: SITE, contentCode: item.contentCode, contentType: section });
await load();
} catch (operationError) { setError(operationError instanceof Error ? operationError.message : "删除失败"); }
};
const save = async () => {
try {
setSaving(true);
setError("");
if (section === "products")
await post("/products/save", {
siteCode: SITE,
productName: form.name,
slug: form.slug,
model: form.model,
summary: form.summary,
productContent: form.body,
featured: false,
inquiryEnabled: true,
sortNo: 0,
status: form.status,
specifications: [],
});
else if (section === "pages")
await post("/pages/save", {
siteCode: SITE,
pageName: form.name,
slug: form.slug,
summary: form.summary,
pageContent: form.body,
systemPage: false,
sortNo: 0,
status: form.status,
});
else
await post("/contents/save", {
siteCode: SITE,
contentType: section,
title: form.name,
slug: form.slug,
summary: form.summary,
contentBody: form.body,
featured: false,
sortNo: 0,
status: form.status,
});
setOpen(false);
setForm({
name: "",
slug: "",
summary: "",
body: "",
model: "",
status: "DRAFT",
});
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "保存失败");
} finally {
setSaving(false);
}
};
return (
<div className="shell">
<aside>
<div className="brand">
<span>S</span>
<div>
Shoplix<small>运营中心</small>
</div>
</div>
<nav>
<div className="nav-group">
<button className={["products", "product-categories"].includes(section) ? "group-active" : ""} onClick={() => setProductMenuOpen(!productMenuOpen)}><Boxes size={18}/>产品<ChevronDown className={productMenuOpen ? "expanded" : ""} size={16}/></button>
{productMenuOpen && <div className="nav-children"><button className={section === "products" ? "active" : ""} onClick={() => navigateSection("products")}>产品管理</button><button className={section === "product-categories" ? "active" : ""} onClick={() => navigateSection("product-categories")}>分类管理</button></div>}
</div>
<div className="nav-group">
<button className={["NEWS", "NEWS-categories", "CASE", "CASE-categories", "HELP", "HELP-categories"].includes(section) ? "group-active" : ""} onClick={() => setContentMenuOpen(!contentMenuOpen)}><FolderTree size={18}/>内容<ChevronDown className={contentMenuOpen ? "expanded" : ""} size={16}/></button>
{contentMenuOpen && <div className="nav-children content-children"><button className={["NEWS", "NEWS-categories"].includes(section) ? "active" : ""} onClick={() => navigateSection("NEWS")}><Newspaper size={15}/>新闻</button><button className={["CASE", "CASE-categories"].includes(section) ? "active" : ""} onClick={() => navigateSection("CASE")}><PanelsTopLeft size={15}/>案例</button><button className={["HELP", "HELP-categories"].includes(section) ? "active" : ""} onClick={() => navigateSection("HELP")}><HelpCircle size={15}/>帮助</button></div>}
</div>
{menus.map((m) => (
<button
key={m.key}
className={section === m.key ? "active" : ""}
onClick={() => navigateSection(m.key)}
>
<m.icon size={18} />
{m.label}
</button>
))}
</nav>
<div className="aside-bottom">
<button>
<Users size={18} />
CRM 客户
</button>
<button className={section === "inquiry-settings" ? "active" : ""} onClick={() => navigateSection("inquiry-settings")}>
<Settings size={18} />
询盘设置
</button>
</div>
</aside>
<main>
{section === "decoration" ? <DecorationEditor onBack={() => navigateSection("pages")}/> : section === "custom-code" ? <CustomCodeManager/> : section === "media" ? <MediaCenter/> : editingProduct !== null ? <ProductEditor productCode={editingProduct || undefined} onBack={closeProductEditor} /> : editingContent !== null ? <ContentEditor contentType={editingContent.contentType} contentCode={editingContent.contentCode || undefined} onBack={closeContentEditor} /> : editingPage !== null ? <PageEditor pageCode={editingPage || undefined} onBack={closePageEditor}/> : <>
{section.endsWith("-categories") ? <CategoryManager contentType={section === "NEWS-categories" ? "NEWS" : section === "CASE-categories" ? "CASE" : section === "HELP-categories" ? "HELP" : undefined}/> : <>
<header>
<div>
<h1>{title}管理</h1>
<p>Local Development Site · 英文站内容</p>
</div>
{!["inquiries", "inquiry-settings"].includes(section) && <div className="header-actions">
{["NEWS", "CASE", "HELP"].includes(section) && <button className="secondary" onClick={() => setSection(`${section}-categories` as Section)}><FolderTree size={17}/>管理分类</button>}
<button className="primary" onClick={() => section === "products" ? openProductEditor() : ["NEWS", "CASE", "HELP"].includes(section) ? openContentEditor(section as EditorialSection) : section === "pages" ? openPageEditor() : setOpen(true)}><Plus size={17}/>新建{title}</button>
</div>}
</header>
{section === "inquiry-settings" ? <InquirySettingsPanel/> : <><section className="toolbar">
<div className="search">
<Search size={17} />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={`搜索${title}名称或路径`}
/>
</div>
</section>
{error && (
<div className="notice">
{error}。请先启动 Admin 后端,并初始化本地站点数据。
</div>
)}
<section className={`table ${section === "inquiries" ? "inquiry-table" : ""}`}>
<div className="thead">
{section === "inquiries" ? <><span>公司名称</span><span>电子邮箱</span><span>国家 / IP地址</span><span>询盘时间</span><span>询盘来源</span><span>状态</span><span>操作</span></> : <><span>名称</span><span>英文路径</span><span>状态</span><span>发布时间</span><span>操作</span></>}
</div>
{filtered.length === 0 && !error ? (
<div className="empty">
<strong>暂无{title}数据</strong>
<p>点击右上角新建按钮录入第一条内容。</p>
</div>
) : (
filtered.map((item, index) => (
<div
className="row"
key={
item.productCode || item.contentCode || item.pageCode || item.inquiryCode || index
}
>
{section === "inquiries" ? <><span><strong>{item.companyName || item.customerName || "--"}</strong><small>{item.customerName || "--"}</small></span><span>{item.customerEmail || "--"}</span><span>{item.countryCode || "未知"}({item.clientIp || "--"})</span><span>{item.createTime?.replace("T", " ").slice(0, 16) || "--"}</span><span>{item.productName || item.sourceType || "网站询盘"}</span><span className={`status ${item.status.toLowerCase()}`}>{item.statusLabel || item.status}</span><div className="row-actions"><button className="link">查看</button></div></> : <><span><strong>{item.productName || item.title || item.pageName}</strong><small>{item.model || item.productCode || item.contentCode || item.pageCode}</small></span><code>/{item.slug}</code><span className={`status ${item.status.toLowerCase()}`}>{statusLabels[item.status] || item.status}</span><span>{item.publishTime?.replace("T", " ").slice(0, 16) || "--"}</span><div className="row-actions">{["products", "NEWS", "CASE", "HELP"].includes(section) && item.slug && <a className="link" href={`${SITE_WEB}/${section === "products" ? "products" : section === "CASE" ? "cases" : section === "NEWS" ? "news" : "help"}/${encodeURIComponent(item.slug)}`} target="_blank" rel="noreferrer">查看前台</a>}<button className="link" onClick={() => section === "products" && item.productCode ? openProductEditor(item.productCode) : ["NEWS", "CASE", "HELP"].includes(section) && item.contentCode ? openContentEditor(section as EditorialSection, item.contentCode) : section === "pages" && item.pageCode ? openPageEditor(item.pageCode) : undefined}>编辑</button>{["products", "NEWS", "CASE", "HELP"].includes(section) && <><button className="link" onClick={() => void changeItemStatus(item)}>{item.status === "PUBLISHED" ? "下架" : "上架"}</button><button className="link danger" onClick={() => void deleteItem(item)}>删除</button></>}</div></>}
</div>
))
)}
</section></>}
</>}
</>}
</main>
{open && (
<div className="mask">
<section className="dialog">
<div className="dialog-head">
<div>
<h2>新建{title}</h2>
<p>前台内容统一使用英文录入</p>
</div>
<button
className="icon"
onClick={() => setOpen(false)}
aria-label="关闭"
>
<X size={19} />
</button>
</div>
<div className="form-grid">
<label>
<span>
{section === "products"
? "产品名称"
: section === "pages"
? "页面名称"
: "标题"}
</span>
<input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder="English name"
/>
</label>
<label>
<span>英文路径</span>
<input
value={form.slug}
onChange={(e) =>
setForm({
...form,
slug: e.target.value
.toLowerCase()
.replace(/[^a-z0-9-]/g, "-"),
})
}
placeholder="industrial-pumps"
/>
</label>
{section === "products" && (
<label>
<span>产品型号</span>
<input
value={form.model}
onChange={(e) =>
setForm({ ...form, model: e.target.value })
}
placeholder="Model / Series"
/>
</label>
)}
<label>
<span>发布状态</span>
<select
value={form.status}
onChange={(e) => setForm({ ...form, status: e.target.value })}
>
<option value="DRAFT">草稿</option>
<option value="PUBLISHED">立即发布</option>
<option value="OFFLINE">下线</option>
</select>
</label>
<label className="wide">
<span>英文摘要</span>
<textarea
rows={3}
value={form.summary}
onChange={(e) =>
setForm({ ...form, summary: e.target.value })
}
/>
</label>
<label className="wide">
<span>英文正文</span>
<textarea
rows={9}
value={form.body}
onChange={(e) => setForm({ ...form, body: e.target.value })}
/>
</label>
</div>
<div className="dialog-actions">
<button onClick={() => setOpen(false)}>取消</button>
<button
className="primary"
disabled={saving || !form.name || !form.slug || !form.body}
onClick={save}
>
{saving ? "保存中..." : "保存"}
</button>
</div>
</section>
</div>
)}
</div>
);
}
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);