Compare commits

..

4 Commits

4 changed files with 78 additions and 23 deletions

View File

@@ -317,12 +317,29 @@ def attach_common(conn, resource, items):
def monthly_finance(conn, tenant="科普·无界"): def monthly_finance(conn, tenant="科普·无界"):
from datetime import date
today = date.today()
# 12 months: 9 before + current + 2 after
from dateutil.relativedelta import relativedelta
start = today + relativedelta(months=-9)
months = []
for i in range(12):
m = start + relativedelta(months=i)
months.append(m.strftime("%Y-%m"))
data = [] data = []
for item in rows(conn, "SELECT DISTINCT month FROM finance_records WHERE tenant=? ORDER BY month", (tenant,)): for month in months:
month = item["month"] def s(cat):
revenue = one(conn, "SELECT COALESCE(SUM(amount),0) AS v FROM finance_records WHERE month=? AND record_type='revenue' AND tenant=?", (month, tenant))["v"] return one(conn, "SELECT COALESCE(SUM(amount),0) AS v FROM finance_records WHERE month=? AND category=? AND tenant=?", (month, cat, tenant))["v"]
cost = one(conn, "SELECT COALESCE(SUM(amount),0) AS v FROM finance_records WHERE month=? AND record_type='cost_expense' AND tenant=?", (month, tenant))["v"] revenue = s("确认收入") + s("签单")
data.append({"month": month, "revenue": revenue, "gross_profit": revenue - cost, "cost_expense": cost, "net_profit": revenue - cost}) labor = s("人力成本")
expense = s("费用")
purchase = s("外部采购")
net = revenue - labor - expense - purchase
data.append({
"month": month, "revenue": revenue,
"labor": labor, "expense": expense, "purchase": purchase,
"net_profit": net,
})
return data return data
@@ -346,16 +363,22 @@ def bootstrap():
tasks = q("SELECT * FROM project_tasks WHERE tenant=? ORDER BY phase, sort_order, id", tenant) tasks = q("SELECT * FROM project_tasks WHERE tenant=? ORDER BY phase, sort_order, id", tenant)
current_month = "2026-06" current_month = "2026-06"
# Finance aggregates # Finance aggregates
def sum_finance(months, rtype): def sum_cat(months, cat):
return sum(x["amount"] for x in finance if x["month"] in months and x["record_type"] == rtype) return sum(x["amount"] for x in finance if x["month"] in months and x.get("category") == cat)
months_2026 = [f"2026-{m:02d}" for m in range(1,7)] months_2026 = [f"2026-{m:02d}" for m in range(1,7)]
months_q2 = ["2026-04","2026-05","2026-06"] months_q2 = ["2026-04","2026-05","2026-06"]
revenue_annual = sum_finance(months_2026, "revenue") rev_annual = sum_cat(months_2026, "确认收入") + sum_cat(months_2026, "签单")
cost_annual = sum_finance(months_2026, "cost_expense") labor_annual = sum_cat(months_2026, "人力成本")
revenue_q2 = sum_finance(months_q2, "revenue") expense_annual = sum_cat(months_2026, "费用")
cost_q2 = sum_finance(months_q2, "cost_expense") purchase_annual = sum_cat(months_2026, "外部采购")
revenue_month = sum_finance([current_month], "revenue") rev_q2 = sum_cat(months_q2, "确认收入") + sum_cat(months_q2, "签单")
cost_month = sum_finance([current_month], "cost_expense") labor_q2 = sum_cat(months_q2, "人力成本")
expense_q2 = sum_cat(months_q2, "费用")
purchase_q2 = sum_cat(months_q2, "外部采购")
rev_month = sum_cat([current_month], "确认收入") + sum_cat([current_month], "签单")
labor_month = sum_cat([current_month], "人力成本")
expense_month = sum_cat([current_month], "费用")
purchase_month = sum_cat([current_month], "外部采购")
# Contract aggregates — time-based # Contract aggregates — time-based
signed_amount = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_status"] == "已签约") signed_amount = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_status"] == "已签约")
from datetime import date from datetime import date
@@ -378,8 +401,9 @@ def bootstrap():
"active_sales": len([x for x in sales if x["status"] in ["待跟进", "跟进中", "方案中", "商务谈判"]]), "active_sales": len([x for x in sales if x["status"] in ["待跟进", "跟进中", "方案中", "商务谈判"]]),
"execution_projects": len([x for x in operations if x["project_type"] == "execution"]), "execution_projects": len([x for x in operations if x["project_type"] == "execution"]),
"risk_projects": len([x for x in operations if x["project_status"] == "有风险" or x["risks"]]), "risk_projects": len([x for x in operations if x["project_status"] == "有风险" or x["risks"]]),
"monthly_revenue": revenue_month, "monthly_revenue": rev_month,
"monthly_net_profit": revenue_month - cost_month, "monthly_net_profit": rev_month - labor_month - expense_month - purchase_month,
"monthly_gross": rev_month - labor_month - expense_month - purchase_month,
"upcoming_products": len([x for x in products if x["status"] in ["规划中", "设计中", "开发中", "测试中"]]), "upcoming_products": len([x for x in products if x["status"] in ["规划中", "设计中", "开发中", "测试中"]]),
"total_projects": len(operations), "total_projects": len(operations),
"total_proposals": len(proposals), "total_proposals": len(proposals),
@@ -390,10 +414,10 @@ def bootstrap():
"signed_q2": signed_q2, "signed_q2": signed_q2,
"signed_month": signed_month, "signed_month": signed_month,
"pipeline_amount": pipeline_amount, "pipeline_amount": pipeline_amount,
"revenue_annual": revenue_annual, "revenue_annual": rev_annual,
"revenue_q2": revenue_q2, "revenue_q2": rev_q2,
"gross_annual": revenue_annual - cost_annual, "gross_annual": rev_annual - labor_annual - expense_annual - purchase_annual,
"gross_q2": revenue_q2 - cost_q2, "gross_q2": rev_q2 - labor_q2 - expense_q2 - purchase_q2,
"signed_not_executed": signed_not_executed, "signed_not_executed": signed_not_executed,
}, },
"recent": q("SELECT * FROM follow_up_records WHERE tenant=? ORDER BY id DESC LIMIT 8", tenant), "recent": q("SELECT * FROM follow_up_records WHERE tenant=? ORDER BY id DESC LIMIT 8", tenant),

View File

@@ -1 +1,2 @@
Flask==3.0.3 Flask==3.0.3
python-dateutil==2.9.0

View File

@@ -249,6 +249,8 @@ window.switchTab = switchTab;
window.switchTenant = (tenant) => { window.switchTenant = (tenant) => {
state.tenant = tenant; state.tenant = tenant;
state.projectView = null; state.projectView = null;
const label = tenant.replace("·无界", "");
document.querySelector("#workspaceTitle").textContent = label + " OPC 工作台";
load(); load();
}; };
@@ -421,16 +423,44 @@ function renderProducts() {
function renderFinance() { function renderFinance() {
const rows = state.data.finance.map((x) => [x.month, x.category, money(x.amount), text(x.notes)]); const rows = state.data.finance.map((x) => [x.month, x.category, money(x.amount), text(x.notes)]);
document.querySelector("#finance").innerHTML = `<div class="grid gap-4"> document.querySelector("#finance").innerHTML = `<div class="grid gap-4">
${card(`<h2 class="mb-4 text-lg font-bold">收入、毛利、成本/费用、净利月度曲线</h2><div style="position:relative;height:300px"><canvas id="financeChart2"></canvas></div>`, "p-5")} ${card(`<div class="flex items-center justify-between cursor-pointer" onclick="toggleFinanceChart()"><h2 class="text-lg font-bold text-slate-700">收入、毛利、成本/费用、净利月度曲线</h2><i data-lucide="chevron-down" class="transition-transform rotate-90" id="financeChartIcon"></i></div><div id="financeChartWrap" class="hidden mt-4"><div style="position:relative;height:300px"><canvas id="financeChart2"></canvas></div></div>`, "p-5")}
${card(formHtml([ ${card(formHtml([
{ label: "日期", input: `<input name="month" type="date" required>` }, { label: "日期", input: `<input name="month" type="date" required>` },
{ label: "类型", input: `<select name="category"><option>签单</option><option></option><option></option><option></option><option></option></select>` }, { label: "类型", input: `<select name="category"><option>签单</option><option></option><option></option><option></option><option></option></select>` },
{ label: "金额/万", input: `<input name="amount" type="number" step="0.01" required>` }, { label: "金额/万", input: `<input name="amount" type="number" step="0.01" required>` },
{ label: "费用说明", input: `<input name="notes" placeholder="摘要说明">` }, { label: "费用说明", input: `<input name="notes" placeholder="摘要说明">` },
], { handler: "createFinance", text: "新增明细" }), "p-4")} ], { handler: "createFinance", text: "新增明细" }), "p-4")}
${card(`<div class="flex items-center justify-between cursor-pointer" onclick="document.querySelector('#finance-table').classList.toggle('hidden'); this.querySelector('i').classList.toggle('rotate-90')"><h3 class="font-bold text-slate-700">明细列表 <span class="text-slate-400 font-normal">(${state.data.finance.length})</span></h3><i data-lucide="chevron-down" class="transition-transform rotate-90"></i></div><div id="finance-table" class="hidden mt-3">${renderTable(["日期", "类型", "金额", "备注"], rows)}</div>`, "p-4")} ${card(`<h3 class="font-bold text-slate-700 mb-3">明细列表 <span class="text-slate-400 font-normal">(${state.data.finance.length})</span></h3>${renderTable(["日期", "类型", "金额", "备注"], rows)}`, "p-4")}
</div>`; </div>`;
renderChartOn("financeChart2", state.data.financeMonthly); 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.labor), borderColor: "#ef4444", tension: 0.3 },
{ label: "费用", data: financeMonthly.map((x) => x.expense), borderColor: "#d97706", tension: 0.3 },
{ label: "外部采购", data: financeMonthly.map((x) => x.purchase), borderColor: "#8b5cf6", tension: 0.3 },
{ label: "月度净利", data: financeMonthly.map((x) => x.net_profit), borderColor: "#059669", tension: 0.3, borderDash: [5,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) { function renderChartOn(id, data) {

View File

@@ -31,7 +31,7 @@
<div> <div>
<p class="eyebrow text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">OPC Manager</p> <p class="eyebrow text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">OPC Manager</p>
<div class="flex items-center gap-3 mt-1"> <div class="flex items-center gap-3 mt-1">
<h1 class="text-2xl font-semibold">无界 OPC 工作台</h1> <h1 class="text-2xl font-semibold" id="workspaceTitle">科普 OPC 工作台</h1>
<select id="tenantSelect" class="rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 outline-none focus:border-blue-500" onchange="switchTenant(this.value)"> <select id="tenantSelect" class="rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 outline-none focus:border-blue-500" onchange="switchTenant(this.value)">
<option value="科普·无界">科普·无界</option> <option value="科普·无界">科普·无界</option>
<option value="科研·无界">科研·无界</option> <option value="科研·无界">科研·无界</option>