const state = {
active: "home",
data: null,
tenant: "科普·无界",
opFilter: "all",
projectView: null,
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?tenant=${encodeURIComponent(state.tenant)}`);
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;
const rows1 = [
["年度累计签约", money(m.signed_annual || m.signed_amount)],
["Q2 累计签约", money(m.signed_q2 || 0)],
["本月新增签约", money(m.signed_month || 0)],
["合同流程中", money(m.pipeline_amount)],
];
const rows2 = [
["年度累计确收", money(m.revenue_annual)],
["Q2 累计确收", money(m.revenue_q2)],
["本月新增确收", money(m.monthly_revenue)],
["已签约未执行", money(m.signed_not_executed)],
];
const rows3 = [
["年度累计毛利", money(m.gross_annual)],
["Q2 累计毛利", money(m.gross_q2)],
["本月新增毛利", money(m.monthly_net_profit)],
["合同毛利率", m.revenue_annual ? Math.round(m.gross_annual / m.revenue_annual * 100) + "%" : "—"],
];
const tblCard = (title, rows) => card(`${title}
${rows.map(([label, value]) => `| ${label} | ${value} |
`).join("")}
`, "p-4");
document.querySelector("#home").innerHTML = `
${[
["重点项目", m.total_projects, "projects"],
["业务方案", m.total_proposals, "proposals"],
["产品版本", m.total_products, "products"],
["本月确收", money(m.monthly_revenue), "finance"],
["本月毛利", money(m.monthly_gross || m.monthly_net_profit), "finance"],
["本月净利", money(m.monthly_net_profit), "finance"],
].map(([label, value, tab]) => ``).join("")}
${tblCard("合同金额", rows1)}${tblCard("确收金额", rows2)}${tblCard("确收毛利", rows3)}
${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.openTaskForm = (projectId, taskId) => {
const drawer = document.querySelector(`#task-drawer-${projectId}`);
const titleEl = drawer.querySelector(".task-drawer-title");
if (taskId === null) {
document.querySelector(`#task-id-${projectId}`).value = "";
document.querySelector(`#task-name-${projectId}`).value = "";
document.querySelector(`#task-phase-${projectId}`).value = "商务洽谈";
document.querySelector(`#task-owner-${projectId}`).value = "";
document.querySelector(`#task-due-${projectId}`).value = "";
document.querySelector(`#task-notes-${projectId}`).value = "";
document.querySelector(`#task-blockers-${projectId}`).value = "";
document.querySelector(`#task-submit-btn-${projectId}`).textContent = "确认新增";
if (titleEl) titleEl.textContent = "新增任务";
} else {
const task = (state.data.tasks || []).find((t) => t.id === taskId);
if (!task) return;
document.querySelector(`#task-id-${projectId}`).value = task.id;
document.querySelector(`#task-name-${projectId}`).value = task.task || "";
document.querySelector(`#task-phase-${projectId}`).value = task.phase || "商务洽谈";
document.querySelector(`#task-owner-${projectId}`).value = task.owner || "";
document.querySelector(`#task-due-${projectId}`).value = task.due_date || "";
document.querySelector(`#task-notes-${projectId}`).value = task.notes || "";
document.querySelector(`#task-blockers-${projectId}`).value = task.blockers || "";
document.querySelector(`#task-submit-btn-${projectId}`).textContent = "保存修改";
if (titleEl) titleEl.textContent = "编辑任务";
}
drawer.classList.add("open");
};
window.closeTaskDrawer = (projectId) => {
document.querySelector(`#task-drawer-${projectId}`).classList.remove("open");
};
window.submitTaskForm = async (event, projectId) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.currentTarget).entries());
data.project_id = Number(projectId);
const taskId = data.task_id;
delete data.task_id;
try {
if (taskId) {
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data }) });
} else {
await api("/api/tasks", { method: "POST", body: JSON.stringify({ data }) });
}
await load();
} catch (error) {
alert("保存失败:" + error.message);
}
};
window.createFinance = async (event) => {
event.preventDefault();
const form = event.currentTarget;
const data = Object.fromEntries(new FormData(form).entries());
data.tenant = state.tenant;
data.sign_amount = parseFloat(data.sign_amount) || 0;
for (const m of ["2026-06","2026-07","2026-08","2026-09"]) {
const k = m.replace("-","_");
data["rev_"+k] = parseFloat(data["rev_"+k]) || 0;
data["gross_"+k] = parseFloat(data["gross_"+k]) || 0;
}
try {
await api("/api/projectFinances", { method: "POST", body: JSON.stringify({ data }) });
form.reset();
await load();
} catch (error) {
alert("新增失败:" + error.message);
}
};
window.switchTab = switchTab;
window.switchTenant = (tenant) => {
state.tenant = tenant;
state.projectView = null;
const label = tenant.replace("·无界", "");
document.querySelector("#workspaceTitle").textContent = label + " OPC 工作台";
load();
};
function renderProjects() {
// 二级页面:项目任务详情
if (state.projectView) {
return renderProjectTasks(state.projectView);
}
const items = state.data.operations;
const rows = items.map((x) => [
`${x.project_name}`,
text(x.customer_need || x.notes),
badge(x.current_stage || x.project_status),
x.expected_contract_amount ? money(x.expected_contract_amount) : "—",
text(x.owner || "—"),
``
]);
document.querySelector("#projects").innerHTML = `
${card(formHtml([
{ label: "项目名称", input: `` },
{ label: "当前阶段", input: `` },
{ label: "项目金额", input: `` },
{ label: "负责人", input: `` },
], { handler: "createOperation", text: "新增项目" }), "p-4")}
${renderTable(["项目", "项目说明", "当前阶段", "项目金额", "负责人", "进展"], rows, items.map((x) => ({ resource: "operations", id: x.id })))}
`;
if (window.lucide) window.lucide.createIcons();
}
function renderProjectTasks(projectId) {
const project = state.data.operations.find((x) => x.id === projectId);
if (!project) { state.projectView = null; renderProjects(); return; }
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
const phases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
document.querySelector("#projects").innerHTML = `
${project.project_name}
${phases.map((phase) => {
const pt = tasks.filter((t) => t.phase === phase);
if (!pt.length) return "";
return `
${phase}${pt.length}
${pt.map((t) => `
${t.task}${t.notes ? `${t.notes}` : ""}${t.blockers ? `⚠ ${t.blockers}` : ""}
${t.owner || ""}${t.due_date || ""}`).join("")}
`;
}).join("")}
`;
if (window.lucide) window.lucide.createIcons();
}
function showTaskModal(projectId) {
const project = state.data.operations.find((x) => x.id === projectId);
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
const phases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
document.querySelector("#taskModal").innerHTML = `
${phases.map((phase) => {
const pt = tasks.filter((t) => t.phase === phase);
if (!pt.length) return "";
return `
${phase}${pt.length}
${pt.map((t) => `
${t.task}${t.notes ? `${t.notes}` : ""}${t.blockers ? `⚠ ${t.blockers}` : ""}
${t.owner || ""}${t.due_date || ""}`).join("")}
`;
}).join("")}
`;
document.querySelector("#taskModal").classList.add("active");
if (window.lucide) window.lucide.createIcons();
}
window.closeTaskModal = () => {
document.querySelector("#taskModal").classList.remove("active");
document.querySelector("#taskModal").innerHTML = "";
};
function renderProposals() {
const proposalRows = state.data.proposals.map((p) => [p.customer_or_project_name, p.version, badge(p.status), p.files.length + " 个"]);
const proposalClicks = state.data.proposals.map((p) => ({ resource: "proposals", id: p.id }));
document.querySelector("#proposals").innerHTML = `
${card(formHtml([
{ label: "客户/项目", input: `` },
{ label: "版本号", input: `` },
{ label: "状态", input: `` },
], { handler: "createProposal", text: "新增版本" }), "p-4")}
${renderTable(["客户/项目", "版本号", "状态", "文件数"], proposalRows, proposalClicks)}
`;
}
function fileGroup(module, ownerId, version, category, files) {
return `
${files.length ? files.map(fileItem).join("") : `
暂无文件
`}
`;
}
function fileItem(file) {
return ``;
}
window.deleteFile = async (fileId) => {
if (!confirm("确认删除此文件?")) return;
await api(`/api/files/${fileId}`, { method: "DELETE" });
await load();
closeDrawer();
};
window.uploadFile = async (event, module, ownerId, version, category) => {
const file = event.target.files[0];
if (!file) return;
const form = new FormData();
form.append("module", module);
form.append("owner_id", ownerId);
form.append("owner_version", version);
form.append("file_category", category);
form.append("file", file);
await api("/api/files/upload", { method: "POST", body: form });
await load();
};
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 pfs = state.data.projectFinances || [];
const ops = state.data.operations || [];
const months = ["2026-06","2026-07","2026-08","2026-09"];
const monthLabels = ["6月","7月","8月","9月"];
// Aggregates
const signed = pfs.filter(x => x.status === "已签单");
const pending = pfs.filter(x => x.status !== "已签单");
const sumSign = signed.reduce((s,x) => s + (x.sign_amount||0), 0);
const sumPending = pending.reduce((s,x) => s + (x.sign_amount||0), 0);
const monthRev = months.map(m => pfs.reduce((s,x) => s + (x["rev_"+m.replace("-","_")]||0), 0));
const monthGross = months.map(m => pfs.reduce((s,x) => s + (x["gross_"+m.replace("-","_")]||0), 0));
const renderPfRow = (pf) => {
const mCols = months.map(m => {
const rev = pf["rev_"+m.replace("-","_")] || 0;
const gross = pf["gross_"+m.replace("-","_")] || 0;
return `${rev ? money(rev) : '—'} ${gross ? money(gross) : '—'} | `;
}).join("");
return `| ${pf.customer_name} | ${pf.business_type} | ${pf.status === "已签单" ? badge("已签") : badge(pf.status,"amber")} | ${money(pf.sign_amount)} | ${mCols}${pf.sales_person || ""} |
`;
};
document.querySelector("#finance").innerHTML = `
${[["已签项目","" + signed.length],["签约金额",money(sumSign)],["待签项目","" + pending.length],["待签金额",money(sumPending)],["本月确收",money(monthRev[0])],["本月毛利",money(monthGross[0])]].map(([l,v]) => `
`).join("")}
${card(`
月度趋势
`, "p-5")}
${card(`
新增项目财务
`, "p-4")}
${card(`
项目明细 (${pfs.length})
| 客户 | 类型 | 状态 | 签约金额 | ${monthLabels.map(l => `${l} 确收/毛利 | `).join("")}销售 |
${pfs.map(renderPfRow).join("")}
`, "p-4")}
`;
if (window.lucide) window.lucide.createIcons();
}
window.toggleFinanceChart = () => {
const wrap = document.querySelector("#financeChartWrap");
const icon = document.querySelector("#financeChartIcon");
if (!wrap) return;
wrap.classList.toggle("hidden");
icon.classList.toggle("rotate-90");
if (!wrap.classList.contains("hidden") && !state.chart2) renderFinanceChart();
};
function renderFinanceChart() {
const { financeMonthly } = state.data;
const canvas = document.querySelector("#financeChart2");
if (!canvas || !window.Chart) return;
if (state.chart2) state.chart2.destroy();
state.chart2 = new Chart(canvas, {
type: "line",
data: {
labels: financeMonthly.map((x) => x.month),
datasets: [
{ label: "月度确收", data: financeMonthly.map((x) => x.revenue), borderColor: "#2563eb", tension: 0.3 },
{ label: "月度毛利", data: financeMonthly.map((x) => x.net_profit), borderColor: "#059669", 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 }, callback: (v) => v + "万" } } } },
});
}
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, customControl = null) {
const initialValue = text(value);
const control = customControl
? customControl
: 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","项目名称"],["owner","负责人"],["expected_sign_date","截止时间"],["expected_contract_amount","金额"],["notes","项目说明"]]
: 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",
owner: "user", 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("")}
` : ""}
${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();
});
const doSave = 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}`);
}
};
field.addEventListener("blur", doSave);
if (field.tagName === "SELECT") field.addEventListener("change", doSave);
});
}
window.openDrawer = openDrawer;
window.deleteDrawerItem = async (resource, id) => {
if (!confirm("确认删除?此操作不可撤销。")) return;
try {
await api(`/api/${resource}/${id}`, { method: "DELETE" });
closeDrawer();
await load();
} catch (error) {
alert("删除失败:" + error.message);
}
};
window.toggleTaskDone = async (taskId, projectId) => {
const task = (state.data.tasks || []).find((t) => t.id === taskId);
if (!task) return;
const newStatus = task.status === "done" ? "" : "done";
try {
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data: { status: newStatus } }) });
await load();
} catch (error) {
alert("更新失败:" + error.message);
}
};
window.deleteTask = async (projectId) => {
const taskId = document.querySelector(`#task-id-${projectId}`).value;
if (!taskId) return;
if (!confirm("确认删除该任务?此操作不可撤销。")) return;
try {
await api(`/api/tasks/${taskId}`, { method: "DELETE" });
closeTaskDrawer(projectId);
await load();
} catch (error) {
alert("删除失败:" + error.message);
}
};
let dragTaskId = null;
window.handleTaskDragStart = (event, taskId) => {
dragTaskId = taskId;
event.currentTarget.classList.add("dragging");
event.dataTransfer.effectAllowed = "move";
};
window.handleTaskDrop = async (event, projectId, phase) => {
event.preventDefault();
event.currentTarget.classList.remove("drag-over");
const target = event.currentTarget;
if (!dragTaskId) return;
// Find the dragged element and insert after the nearest task
const dragged = document.querySelector(`.task-row[data-id="${dragTaskId}"]`);
if (!dragged) return;
const afterElement = getDragAfterElement(target, event.clientY);
if (afterElement) {
target.insertBefore(dragged, afterElement);
} else {
target.appendChild(dragged);
}
dragged.classList.remove("dragging");
// Update sort_order in DB
const rows = [...target.querySelectorAll(".task-row")];
const updates = rows.map((row, i) => ({ id: parseInt(row.dataset.id), sort_order: i }));
try {
await api(`/api/tasks/batch-sort`, { method: "POST", body: JSON.stringify({ items: updates }) });
} catch (e) { /* non-critical */ }
dragTaskId = null;
};
function getDragAfterElement(container, y) {
const elements = [...container.querySelectorAll(".task-row:not(.dragging)")];
return elements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset, element: child };
}
return closest;
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
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 = ``;
});