const state = {
active: "home",
data: null,
opFilter: "all",
chart: null,
chart2: null,
productPlatform: "all",
};
const money = (value) => `${Number(value || 0).toLocaleString("zh-CN")} 万`;
const text = (value) => value === undefined || value === null || value === "" ? "—" : value;
async function api(path, options = {}) {
const response = await fetch(path, {
headers: options.body instanceof FormData ? undefined : { "Content-Type": "application/json" },
...options,
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || "请求失败");
return data;
}
function badge(value) {
const val = String(value || "—");
let cls = "badge-slate";
if (["P0", "有风险", "已丢单", "已延期"].includes(val)) cls = "badge-red";
if (["P1", "方案中", "方案已提交", "商务谈判", "待客户确认"].includes(val)) cls = "badge-amber";
if (["已签约", "已上线", "已完成", "已归档"].includes(val)) cls = "badge-green";
if (["execution", "已签约执行项目"].includes(val)) cls = "badge-blue";
return `${val === "execution" ? "已签约执行项目" : val === "opportunity" ? "业务机会项目" : val}`;
}
function card(content, cls = "") {
return ``;
}
function renderTable(headers, rows, rowClicks) {
const trAttrs = (rowClicks || []).map((rc) => rc ? `onclick="openDrawer('${rc.resource}', ${rc.id})" class="clickable-row"` : "");
return card(`
${headers.map((h) => `| ${h} | `).join("")}
${rows.map((row, i) => `${row.map((c) => `| ${c} | `).join("")}
`).join("")}
`);
}
async function load() {
state.data = await api("/api/bootstrap");
render();
}
function switchTab(tab) {
state.active = tab;
document.querySelectorAll("#tabs button").forEach((btn) => btn.classList.toggle("active", btn.dataset.tab === tab));
document.querySelectorAll(".panel").forEach((panel) => panel.classList.toggle("active", panel.id === tab));
render();
}
function render() {
if (!state.data) return;
renderHome();
renderProjects();
renderProposals();
renderProducts();
renderFinance();
if (window.lucide) window.lucide.createIcons();
// Decode and render rich HTML content in followup records
drawer.querySelectorAll(".rich-content").forEach((el) => {
const html = el.dataset.html;
if (html) el.innerHTML = decodeURIComponent(html);
});
// Initialize Squire editor
const squireDiv = drawer.querySelector(".squire-editor");
if (squireDiv && window.Squire) {
const id = squireDiv.id;
if (window.squireInstances[id]) window.squireInstances[id].destroy();
const sq = new Squire(squireDiv, { blockTag: "P" });
sq.addEventListener("input", () => {
const form = squireDiv.closest("form");
const btn = form.querySelector(".comment-submit");
});
window.squireInstances[id] = sq;
// Handle placeholder
squireDiv.addEventListener("focus", () => squireDiv.classList.add("focused"));
squireDiv.addEventListener("blur", () => {
if (!squireDiv.textContent.trim()) squireDiv.classList.remove("focused");
});
}
}
function renderHome() {
const { summary, financeMonthly } = state.data;
const m = summary.metrics;
document.querySelector("#home").innerHTML = `
${[
["P0 客户数", m.p0_customers, "projects"],
["跟进中销售机会", m.active_sales, "projects"],
["已签约执行项目", m.execution_projects, "projects"],
["有风险项目", m.risk_projects, "projects"],
["本月收入", money(m.monthly_revenue), "finance"],
["本月净利", money(m.monthly_net_profit), "finance"],
["即将上线版本", m.upcoming_products, "products"],
["已签约未执行", money(m.signed_not_executed), "finance"],
].map(([label, value, tab]) => ``).join("")}
${[
["已签约合同总额", money(m.signed_amount), "projects"],
["合同流程中", money(m.pipeline_amount), "projects"],
["年度累计确收", money(m.revenue_annual), "finance"],
["Q2 累计确收", money(m.revenue_q2), "finance"],
["年度累计毛利", money(m.gross_annual), "finance"],
["Q2 累计毛利", money(m.gross_q2), "finance"],
].map(([label, value, tab]) => ``).join("")}
${card(`
财务趋势
${badge("YYYY-MM")}`, "p-4")}
${card(`
风险提醒
${(summary.risks.length ? summary.risks : [{ title: "暂无高风险", content: "当前无明确阻塞,按周更新即可。" }]).map((r) => `
`).join("")}
`, "p-5")}
${card(`
近期动态
${summary.recent.map((r) => `
${r.content}${r.followed_at}
`).join("")}
`, "p-5")}
`;
renderChart(financeMonthly);
}
function renderChart(data) {
const canvas = document.querySelector("#financeChart");
if (!canvas || !window.Chart) return;
if (state.chart) state.chart.destroy();
state.chart = new Chart(canvas, {
type: "line",
data: {
labels: data.map((x) => x.month),
datasets: [
{ label: "收入", data: data.map((x) => x.revenue), borderColor: "#2563eb", tension: 0.3 },
{ label: "毛利", data: data.map((x) => x.gross_profit), borderColor: "#059669", tension: 0.3 },
{ label: "成本/费用", data: data.map((x) => x.cost_expense), borderColor: "#d97706", tension: 0.3 },
{ label: "净利", data: data.map((x) => x.net_profit), borderColor: "#7c3aed", tension: 0.3 },
],
},
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: "bottom", labels: { boxWidth: 12, font: { size: 11 } } } }, scales: { x: { ticks: { font: { size: 11 } }, grid: { display: false } }, y: { ticks: { font: { size: 11 } } } } },
});
}
function formHtml(fields, button) {
return ``;
}
async function createResource(event, resource) {
event.preventDefault();
const form = event.currentTarget;
const data = Object.fromEntries(new FormData(form).entries());
try {
await api(`/api/${resource}`, { method: "POST", body: JSON.stringify({ data }) });
form.reset();
await load();
} catch (error) {
alert("创建失败:" + error.message);
}
}
window.createSales = (event) => createResource(event, "sales");
window.createProposal = (event) => createResource(event, "proposals");
window.createOperation = (event) => createResource(event, "operations");
window.createProduct = (event) => createResource(event, "products");
window.createFinance = (event) => createResource(event, "finance");
window.switchTab = switchTab;
function renderProjects() {
// Merge sales_leads and operation_projects into one table
const salesItems = state.data.sales.map((x) => ({
name: x.target_customer,
version: "",
type: "opportunity",
status: x.status,
amount: 0,
stage: "",
files: 0,
followup: x.latest_follow_up_record,
resource: "sales",
id: x.id,
}));
const opItems = state.data.operations.map((x) => ({
name: x.project_name,
version: x.project_version,
type: x.project_type,
status: x.project_status,
amount: x.expected_contract_amount || 0,
stage: x.current_stage || x.sop_stage,
files: x.files.length,
followup: x.latest_follow_up_record,
resource: "operations",
id: x.id,
}));
const allItems = [...salesItems, ...opItems];
const items = state.opFilter === "all" ? allItems : allItems.filter((x) => x.type === state.opFilter || (state.opFilter === "opportunity" && x.type === "opportunity"));
const rows = items.map((x) => [`${x.name}${x.version ? `${x.version}
` : ""}`, badge(x.type), badge(x.status), x.amount ? money(x.amount) : "—", text(x.stage), text(x.followup)]);
const clicks = items.map((x) => ({ resource: x.resource, id: x.id }));
document.querySelector("#projects").innerHTML = `
${card(formHtml([
{ label: "业务机会", input: `
` },
{ label: "优先级", input: `
` },
{ label: "状态", input: `
` },
], { handler: "createSales", text: `
新增业务机会` }), "p-4")}
${card(formHtml([
{ label: "项目名称", input: `
` },
{ label: "项目版本", input: `
` },
{ label: "项目类型", input: `
` },
{ label: "状态", input: `
` },
], { handler: "createOperation", text: "新增项目" }), "p-4")}
${[["all","全部"],["opportunity","业务机会"],["execution","已签约执行"]].map(([k,v]) => ``).join("")}
${renderTable(["项目/客户", "类型", "状态", "金额", "当前阶段", "最新跟进"], rows, clicks)}
`;
}
function renderProducts() {
const items = state.productPlatform === "all" ? state.data.products : state.data.products.filter((x) => (x.platform || "") === state.productPlatform);
document.querySelector("#products").innerHTML = `
${card(formHtml([
{ label: "产品名称", input: `
` },
{ label: "版本号", input: `
` },
{ label: "平台", input: `
` },
{ label: "上线日期", input: `
` },
{ label: "状态", input: `
` },
], { handler: "createProduct", text: "新增版本" }), "p-4")}
${[["all","全部"],["真研平台","真研"],["科普平台","科普"],["关爱平台","关爱"]].map(([k,v]) => ``).join("")}
${renderTable(["产品名称", "版本号", "版本目标", "核心功能", "平台", "上线日期", "状态"], items.map((p) => [p.product_name, p.version, text(p.version_goal), text(p.feature_list), text(p.platform), text(p.launch_date), badge(p.status)]), items.map((p) => ({ resource: "products", id: p.id })))}
`;
}
function renderFinance() {
const rows = state.data.finance.map((x) => [x.month, badge(x.record_type === "revenue" ? "收入" : "成本/费用"), x.category, money(x.amount), x.occurred_date, text(x.notes)]);
document.querySelector("#finance").innerHTML = `
${card(`
收入、毛利、成本/费用、净利月度曲线
`, "p-5")}
${card(formHtml([
{ label: "月份", input: `
` },
{ label: "类型", input: `
` },
{ label: "分类", input: `
` },
{ label: "金额/万", input: `
` },
{ label: "发生日期", input: `
` },
], { handler: "createFinance", text: "新增明细" }), "p-4")}
${renderTable(["月份", "类型", "分类", "金额", "发生日期", "备注"], rows)}
`;
renderChartOn("financeChart2", state.data.financeMonthly);
}
function renderChartOn(id, data) {
const canvas = document.querySelector(`#${id}`);
if (!canvas || !window.Chart) return;
if (state.chart2) state.chart2.destroy();
state.chart2 = new Chart(canvas, {
type: "line",
data: {
labels: data.map((x) => x.month),
datasets: [
{ label: "收入", data: data.map((x) => x.revenue), borderColor: "#2563eb", tension: 0.3 },
{ label: "毛利", data: data.map((x) => x.gross_profit), borderColor: "#059669", tension: 0.3 },
{ label: "成本/费用", data: data.map((x) => x.cost_expense), borderColor: "#d97706", tension: 0.3 },
{ label: "净利", data: data.map((x) => x.net_profit), borderColor: "#7c3aed", tension: 0.3 },
],
},
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: "bottom", labels: { boxWidth: 12, font: { size: 11 } } } }, scales: { x: { ticks: { font: { size: 11 } }, grid: { display: false } }, y: { ticks: { font: { size: 11 } } } } },
});
}
function drawerField(icon, label, name, value, multiline = false) {
const initialValue = text(value);
const control = multiline
? ``
: ``;
return ``;
}
function openDrawer(resource, id) {
const list = resource === "sales" ? state.data.sales : resource === "operations" ? state.data.operations : resource === "proposals" ? state.data.proposals : state.data.products;
const item = list.find((x) => x.id === id);
const drawer = document.querySelector("#drawer");
const fields = resource === "sales"
? [["target_customer","业务机会"],["priority","优先级"],["status","状态"]]
: resource === "operations"
? [["project_name","项目名称"],["project_version","项目版本"],["project_status","项目状态"],["current_stage","当前阶段"],["target_customer","业务机会"],["customer_need","客户需求"],["expected_contract_amount","预计签约金额"],["expected_sign_date","预计签约时间"],["sign_probability","签约概率"],["sop_stage","SOP 阶段"],["execution_progress","执行进度"],["current_deliverable","当前交付物"],["risks","风险与阻塞"],["next_action","下一步动作"]]
: resource === "proposals"
? [["customer_or_project_name","客户/项目"],["version","版本号"],["description","版本说明"],["created_date","创建日期"],["status","状态"]]
: [["product_name","产品名称"],["version","版本号"],["version_goal","版本目标"],["feature_list","核心功能清单"],["platform","平台"],["launch_date","上线日期"],["status","当前状态"],["notes","备注"]];
const fieldIcons = {
target_customer: "user", priority: "flag", status: "circle-dot",
project_name: "briefcase-business", project_version: "git-branch", project_status: "circle-dot", current_stage: "map-pin",
customer_need: "file-text", expected_contract_amount: "banknote", expected_sign_date: "calendar",
sign_probability: "percent", sop_stage: "list-checks", execution_progress: "activity",
current_deliverable: "package", risks: "alert-triangle", next_action: "arrow-right",
product_name: "box", version: "tag", version_goal: "target", feature_list: "list", platform: "layers",
launch_date: "calendar", notes: "sticky-note"
};
const multilineFields = ["customer_need", "current_deliverable", "risks", "next_action", "version_goal", "feature_list", "notes"];
const followupTarget = resource === "sales" ? "sales" : resource === "proposals" ? "proposal" : resource === "operations" ? "operation" : resource === "products" ? "product" : "";
const title = item.target_customer || item.project_name || item.customer_or_project_name || item.product_name;
drawer.innerHTML = `
${resource === "proposals" ? `
方案文件
${["方案","成本","SOP","财务流程"].map((cat) => fileGroup("proposal", item.id, item.version, cat, item.files.filter((f) => f.file_category === cat))).join("")}
` : ""}
${resource === "operations" ? (() => {
const tasks = (state.data.tasks || []).filter((t) => t.project_id === id);
if (!tasks.length) return "";
const phases = [...new Set(tasks.map((t) => t.phase))];
return `
项目任务
${phases.map((phase) => {
const pt = tasks.filter((t) => t.phase === phase);
return `
${phase}
${pt.map((t) => {
const due = t.due_date ? `
📅 ${t.due_date}` : "";
const owner = t.owner ? `
👤 ${t.owner}` : "";
const blocker = t.blockers ? `
⚠ ${t.blockers}
` : "";
return `
${t.milestone ? t.milestone + ":": ""}${t.task}${due}${owner}
${blocker}
`;
}).join("")}
`;
}).join("")}
`;
})() : ""}
${followupTarget ? `
活动 / 跟进
${(item.followups || []).map((f) => `
${f.follower} · ${f.follow_up_method}${f.followed_at}
${f.next_action ? `
下一步:${text(f.next_action)}
` : ""}
`).join("")}
` : ""}
`;
drawer.classList.add("open");
bindDrawerAutosave(resource, item.id, item);
if (window.lucide) window.lucide.createIcons();
// Decode and render rich HTML content in followup records
drawer.querySelectorAll(".rich-content").forEach((el) => {
const html = el.dataset.html;
if (html) el.innerHTML = decodeURIComponent(html);
});
// Initialize Squire editor
const squireDiv = drawer.querySelector(".squire-editor");
if (squireDiv && window.Squire) {
const id = squireDiv.id;
if (window.squireInstances[id]) window.squireInstances[id].destroy();
const sq = new Squire(squireDiv, { blockTag: "P" });
sq.addEventListener("input", () => {
const form = squireDiv.closest("form");
const btn = form.querySelector(".comment-submit");
});
window.squireInstances[id] = sq;
// Handle placeholder
squireDiv.addEventListener("focus", () => squireDiv.classList.add("focused"));
squireDiv.addEventListener("blur", () => {
if (!squireDiv.textContent.trim()) squireDiv.classList.remove("focused");
});
}
}
function setDrawerSaveStatus(message, tone = "muted") {
const el = document.querySelector("#drawerSaveStatus");
if (!el) return;
el.textContent = message;
el.dataset.tone = tone;
}
function bindDrawerAutosave(resource, id, item) {
document.querySelectorAll("#drawerForm .drawer-value").forEach((field) => {
field.addEventListener("keydown", (event) => {
if (event.key === "Enter" && field.tagName !== "TEXTAREA") field.blur();
});
field.addEventListener("blur", async () => {
const value = field.value;
if (value === field.dataset.original) return;
const previous = field.dataset.original;
field.dataset.original = value;
setDrawerSaveStatus("保存中…");
try {
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { [field.name]: value } }) });
item[field.name] = value;
const titleValue = item.target_customer || item.project_name || item.customer_or_project_name || item.product_name;
const titleEl = document.querySelector(".drawer-title");
if (titleEl) titleEl.textContent = titleValue;
render();
setDrawerSaveStatus("已保存", "success");
setTimeout(() => setDrawerSaveStatus(""), 1200);
} catch (error) {
field.dataset.original = previous;
setDrawerSaveStatus("保存失败", "danger");
alert(`自动保存失败:${error.message}`);
}
});
});
}
window.openDrawer = openDrawer;
window.closeDrawer = () => document.querySelector("#drawer").classList.remove("open");
window.squireInstances = {};
window.squireCmd = (cmd) => {
const currentEditor = document.querySelector(".squire-editor");
if (!currentEditor) return;
const id = currentEditor.id;
const sq = window.squireInstances[id];
if (!sq) return;
sq.focus();
setTimeout(() => {
if (cmd === "bold") {
sq.hasFormat("b") || sq.hasFormat("strong") ? sq.removeBold() : sq.bold();
} else if (cmd === "italic") {
sq.hasFormat("i") || sq.hasFormat("em") ? sq.removeItalic() : sq.italic();
} else if (cmd === "underline") {
sq.hasFormat("u") ? sq.changeFormat(null, { tag: "u" }, null) : sq.changeFormat({ tag: "u" }, null, null);
} else if (cmd === "strikethrough") {
sq.hasFormat("s") || sq.hasFormat("del") || sq.hasFormat("strike") ? sq.changeFormat(null, { tag: "s" }, null) : sq.changeFormat({ tag: "s" }, null, null);
} else {
sq[cmd]();
}
}, 10);
};
window.submitComment = async (event, targetType, targetId, resource) => {
event.preventDefault();
const form = event.currentTarget;
const editorDiv = form.querySelector(".squire-editor");
const sq = window.squireInstances[editorDiv.id];
const content = sq ? sq.getHTML().trim() : "";
if (!content || content === "
" || content === "
") return;
const button = form.querySelector(".comment-submit");
button.disabled = true;
button.textContent = "发送中…";
await api(`/api/followups/${targetType}/${targetId}`, { method: "POST", body: JSON.stringify({ data: { content } }) });
await load();
openDrawer(resource, targetId);
};
window.deleteFollowup = async (event, followupId, resource, targetId) => {
event.stopPropagation();
if (!confirm("确认删除这条评论?")) return;
await api(`/api/followups/${followupId}`, { method: "DELETE" });
await load();
openDrawer(resource, targetId);
};
document.querySelector("#tabs").addEventListener("click", (event) => {
const button = event.target.closest("button[data-tab]");
if (button) switchTab(button.dataset.tab);
});
document.querySelector("#refreshBtn").addEventListener("click", load);
load().catch((error) => {
document.querySelector("main").innerHTML = ``;
});