435 lines
19 KiB
Python
435 lines
19 KiB
Python
"""工作汇报页导出:把工作看板的全部板块合成一个可离线打开的 HTML 文件。
|
||
|
||
数据口径直接复用看板已有的三路数据:
|
||
· /api/weekly 自研产品 / 执行记录 + 定制项目本期动态
|
||
· /api/focus 每周重点工作(标题 + 内容)
|
||
· /api/custom/finance 年度任务财务情况表
|
||
本模块只读,不新增任何业务口径,也不写库。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import html
|
||
import re
|
||
from datetime import datetime
|
||
from typing import Any, Iterable
|
||
from urllib.parse import quote
|
||
|
||
from fastapi import APIRouter, Depends
|
||
from fastapi.responses import Response
|
||
from sqlalchemy.orm import Session
|
||
|
||
from . import constants, finance
|
||
from .db import get_db
|
||
from .export import plain
|
||
from .models import CustomProject, Period, WeeklyFocus
|
||
from .routers.board import resolve_period_ids
|
||
from .routers.weekly import weekly as weekly_endpoint
|
||
|
||
router = APIRouter()
|
||
|
||
STATUS_NAMES = {code: name for code, name, _ in constants.STATUSES}
|
||
STAGE_NAMES = {code: name for code, name, _, _ in constants.CUSTOM_STAGES}
|
||
RISK_NAME = {code: name for code, name in (("1.高风险", "高风险"), ("2.低风险", "低风险"))}
|
||
RICH_TAG = re.compile(r"(</?(?:b|i|u|br|p|div|span)\b[^>]{0,60}?>)", re.I)
|
||
RICH_COLORS = {
|
||
"danger": "#dc2626",
|
||
"warning": "#d97706",
|
||
"primary": "#2563eb",
|
||
"success": "#16a34a",
|
||
"muted": "#64748b",
|
||
}
|
||
|
||
|
||
def _esc(value: Any) -> str:
|
||
return html.escape("" if value is None else str(value), quote=True)
|
||
|
||
|
||
def _rich(value: Any) -> str:
|
||
"""正文里的白名单富文本保留;其它标签与属性一律不进导出页。"""
|
||
raw = value
|
||
if not isinstance(raw, str):
|
||
return ""
|
||
output: list[str] = []
|
||
pos = 0
|
||
for match in RICH_TAG.finditer(raw):
|
||
output.append(html.escape(raw[pos:match.start()], quote=False))
|
||
output.append(_rich_tag(match.group(0)))
|
||
pos = match.end()
|
||
output.append(html.escape(raw[pos:], quote=False))
|
||
return "".join(output).replace("\n", "<br>")
|
||
|
||
|
||
def _rich_tag(tag: str) -> str:
|
||
lower = tag.lower()
|
||
if re.match(r"<br\s*/?>$", lower):
|
||
return "<br>"
|
||
if lower.startswith("</p>") or lower.startswith("</div>"):
|
||
return "</div>"
|
||
if lower.startswith("<p") or lower.startswith("<div"):
|
||
return "<div>"
|
||
if re.match(r"</?(?:b|i|u)>", lower):
|
||
return lower
|
||
if lower.startswith("</span>"):
|
||
return "</span>"
|
||
color = re.search(r'data-c=["\']([^"\']+)["\']', lower)
|
||
if color and color.group(1) in RICH_COLORS:
|
||
return f'<span style="color:{RICH_COLORS[color.group(1)]}">'
|
||
return "<span>"
|
||
|
||
|
||
def _status(value: Any) -> str:
|
||
key = str(value or "")
|
||
return STATUS_NAMES.get(key, key or "—")
|
||
|
||
|
||
def _stage(value: Any) -> str:
|
||
key = str(value or "")
|
||
return STAGE_NAMES.get(key, key or "—")
|
||
|
||
|
||
def _risk(value: Any) -> str:
|
||
raw = str(value or "").strip()
|
||
if not raw:
|
||
return ""
|
||
return RISK_NAME.get(raw, raw)
|
||
|
||
|
||
def _wan(amount: Any) -> str:
|
||
try:
|
||
return f"{float(amount or 0) / 10000:,.1f}"
|
||
except (TypeError, ValueError):
|
||
return "0.0"
|
||
|
||
|
||
def _date_range(db: Session, period_id: int | None, year: int | None, month: int | None,
|
||
label: str) -> tuple[str, str, str]:
|
||
ids = resolve_period_ids(db, period_id, year, month)
|
||
rows = db.query(Period).filter(Period.id.in_(ids)).order_by(Period.sort_key).all() if ids else []
|
||
if rows:
|
||
start = min(constants.period_first_day(p.year, p.month, p.week) for p in rows)
|
||
end = max(constants.period_last_day(p.year, p.month, p.week) for p in rows)
|
||
return start, end, label or rows[-1].full_label or rows[-1].label
|
||
if year and month:
|
||
start = constants.period_first_day(year, month, 1)
|
||
end = constants.period_last_day(year, month, 4)
|
||
return start, end, label or f"{year}年{month}月"
|
||
return "", "", label or "未选周期"
|
||
|
||
|
||
def _focus_rows(db: Session, period_ids: list[int], keyword: str | None) -> tuple[list[dict], list[dict]]:
|
||
"""选中周期录入的重点工作 + 更早录入且延期未完成的结转条目。"""
|
||
periods = {p.id: p for p in db.query(Period).filter(Period.id.in_(period_ids)).all()}
|
||
if not periods:
|
||
return [], []
|
||
selected_sorts = [int(getattr(p, "sort_key", 0) or 0) for p in periods.values()]
|
||
rows = db.query(WeeklyFocus).filter(WeeklyFocus.archived.is_(False)).order_by(WeeklyFocus.id).all()
|
||
all_periods = {p.id: p for p in db.query(Period).all()} if any(
|
||
row.period_id not in periods for row in rows
|
||
) else periods
|
||
if keyword:
|
||
kw = keyword.strip()
|
||
rows = [f for f in rows if kw in str(f.content or "") or kw in plain(f.detail or "") or kw in plain(f.result or "")]
|
||
week, carry = [], []
|
||
for item in rows:
|
||
period = all_periods.get(item.period_id)
|
||
sort = int(getattr(period, "sort_key", 0) or 0)
|
||
if sort not in selected_sorts:
|
||
continue
|
||
entry = {
|
||
"content": item.content or "",
|
||
"detail": _rich(item.detail),
|
||
"result": _rich(item.result),
|
||
"status": _status(item.status),
|
||
"due": item.due_date or "",
|
||
"period": period.full_label if period else "",
|
||
"late": bool(item.delayed) and item.status != "done",
|
||
}
|
||
if sort in selected_sorts:
|
||
week.append(entry)
|
||
return carry, week
|
||
|
||
|
||
def _custom_sections(db: Session, weekly: dict, start: str, end: str, keyword: str | None = None) -> dict[str, list[dict]]:
|
||
placed = set(constants.CUSTOM_PLACED_ORIGINS) | {"提前交付"}
|
||
kw = (keyword or "").strip()
|
||
|
||
def in_scope(value: Any) -> bool:
|
||
day = str(value or "")[:10]
|
||
return bool(start and end and day and start <= day <= end)
|
||
|
||
added, accepted = [], []
|
||
weekly_ids = {row.get("id") for row in weekly.get("custom", [])}
|
||
rows = db.query(CustomProject).filter(CustomProject.archived.is_(False)).all()
|
||
for row in rows:
|
||
data = row.to_dict()
|
||
summary = next((u.summary for u in row.updates if u.summary), None)
|
||
summary = summary or next((u.content for u in row.updates if u.content), None)
|
||
item = {
|
||
"name": data.get("name"),
|
||
"owner": data.get("owner") or "—",
|
||
"region": data.get("region") or "—",
|
||
"stage": _stage(data.get("stage")),
|
||
"status": str(data.get("project_status") or "—"),
|
||
"amount": _wan(data.get("amount")),
|
||
"risk": _risk(data.get("risk_level")),
|
||
"sign_date": str(data.get("sign_date") or "")[:10],
|
||
"update_date": str(data.get("update_date") or "")[:10],
|
||
"summary": _rich(summary),
|
||
}
|
||
plain_summary = plain(summary or "")
|
||
if kw and not any(kw in str(value or "") for value in (
|
||
data.get("name"), data.get("customer"), data.get("region"),
|
||
data.get("owner"), plain(data.get("remark")), plain_summary,
|
||
)):
|
||
continue
|
||
if row.id in weekly_ids and in_scope(item["sign_date"]) and (str(data.get("origin") or "") in placed):
|
||
added.append(item)
|
||
if row.id in weekly_ids and in_scope(item["update_date"]) and str(data.get("project_status") or "") == "已验收":
|
||
accepted.append(item)
|
||
return {"added": added, "accepted": accepted}
|
||
|
||
|
||
def _finance_table(data: dict) -> str:
|
||
annual = data.get("annual") or {}
|
||
quarters = annual.get("quarters") or []
|
||
unscheduled = annual.get("unscheduled") or {}
|
||
total = annual.get("total") or {}
|
||
ctx = data.get("context") or {}
|
||
|
||
def row(cells: Iterable[Any], cls: str = "") -> str:
|
||
return "<tr" + (f' class="{cls}"' if cls else "") + ">" + "".join(f"<td>{c}</td>" for c in cells) + "</tr>"
|
||
|
||
body = []
|
||
for item in quarters:
|
||
target = _wan(item.get("target"))
|
||
rate = item.get("rate")
|
||
rate_text = f"{float(rate) * 100:.1f}%" if rate is not None else "—"
|
||
cls = "current" if item.get("current") else ""
|
||
body.append(row([
|
||
_esc(ctx.get("year", annual.get("year", ""))) + " Q" + _esc(item.get("q", "")),
|
||
_esc(item.get("acc_count", 0)), _wan(item.get("acc_amount")),
|
||
_esc(item.get("sign_count", 0)), _wan(item.get("sign_amount")),
|
||
target, rate_text,
|
||
], cls))
|
||
body.append(row([
|
||
"未分季", _esc(unscheduled.get("acc_count", 0)), _wan(unscheduled.get("acc_amount")),
|
||
_esc(unscheduled.get("sign_count", 0)), _wan(unscheduled.get("sign_amount")),
|
||
"—", "—",
|
||
]))
|
||
body.append(row([
|
||
"<strong>合计</strong>", f"<strong>{_esc(total.get('acc_count', 0))}</strong>",
|
||
f"<strong>{_wan(total.get('acc_amount'))}</strong>",
|
||
f"<strong>{_esc(total.get('sign_count', 0))}</strong>",
|
||
f"<strong>{_wan(total.get('sign_amount'))}</strong>",
|
||
f"<strong>{_wan(total.get('target'))}</strong>", "",
|
||
], "sum"))
|
||
return (
|
||
"<table><thead><tr><th>季度</th><th>验收项目数</th><th>验收金额(万元)</th>"
|
||
"<th>下单项目数</th><th>下单金额(万元)</th><th>计收目标(万元)</th><th>目标完成率</th>"
|
||
"</tr></thead><tbody>" + "".join(body) + "</tbody></table>"
|
||
)
|
||
|
||
|
||
STYLE = """
|
||
:root{--ink:#1f2937;--muted:#64748b;--line:#e2e8f0;--bg:#f6f8fb;--blue:#2563eb;--green:#16a34a;--red:#dc2626;--amber:#d97706}
|
||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
|
||
.page{max-width:1080px;margin:0 auto;padding:36px 28px 60px}h1{font-size:28px;margin:0 0 6px;letter-spacing:.02em}h2{font-size:19px;margin:0 0 14px;padding-left:10px;border-left:4px solid var(--blue)}
|
||
h3{font-size:15px;margin:20px 0 8px;color:var(--muted)}.sub{color:var(--muted);margin:0 0 24px}
|
||
.section{background:#fff;border:1px solid var(--line);border-radius:12px;padding:22px;margin:0 0 20px;break-inside:avoid}
|
||
.summary{display:flex;flex-wrap:wrap;gap:12px}.summary div{flex:1 1 130px;border:1px solid var(--line);border-radius:8px;padding:10px 14px;background:#fafcff}
|
||
.summary b{display:block;font-size:22px;color:var(--blue)}.summary span{font-size:12px;color:var(--muted)}
|
||
.item{border-top:1px dashed var(--line);padding:10px 0}.item:first-of-type{border-top:0}.title{font-weight:600;margin-bottom:3px}
|
||
.meta{font-size:12px;color:var(--muted);display:flex;flex-wrap:wrap;gap:12px}.body{white-space:normal;margin:4px 0 0;color:#334155}
|
||
.note{color:var(--muted);font-size:13px;padding:8px 0}.warn{color:var(--red)}
|
||
table{width:100%;border-collapse:collapse;font-size:13px}th,td{border:1px solid var(--line);padding:7px 9px;text-align:left;vertical-align:top}
|
||
th{background:#eef2f8;white-space:nowrap}td{white-space:nowrap}td:nth-child(1){font-weight:600}tr.current td{background:#eff6ff}tr.sum td{background:#f8fafc}
|
||
@media print{body{background:#fff}.page{padding:0;max-width:none}.section{border:0;padding:12px 0;page-break-inside:avoid}h2{page-break-after:avoid}}
|
||
"""
|
||
|
||
|
||
def build_html(payload: dict) -> str:
|
||
daily = payload["daily"]
|
||
products = payload["products"]
|
||
custom = payload["custom"]
|
||
finance_data = payload["finance"]
|
||
kpi = payload["kpi"]
|
||
|
||
def items(rows: list[dict], empty: str) -> str:
|
||
if not rows:
|
||
return f'<p class="note">{empty}</p>'
|
||
out = []
|
||
for entry in rows:
|
||
out.append(
|
||
'<div class="item"><div class="title">'
|
||
+ (entry.get("title_html") or _esc(entry.get("content") or entry.get("name") or "—"))
|
||
+ "</div>"
|
||
+ '<div class="meta">'
|
||
+ "".join(f"<span>{_esc(part)}</span>" for part in entry.get("meta", []) if part)
|
||
+ "</div>"
|
||
+ (f'<div class="body">{entry.get("detail") or entry.get("summary") or ""}</div>'
|
||
if entry.get("detail") or entry.get("summary") else "")
|
||
+ "</div>"
|
||
)
|
||
return "".join(out)
|
||
|
||
daily_rows = []
|
||
for entry in daily["carry"] + daily["week"]:
|
||
meta = [entry["status"]]
|
||
if entry["due"]:
|
||
meta.append("预计完成 " + entry["due"])
|
||
if entry["period"]:
|
||
meta.append("录入 " + entry["period"])
|
||
if entry["late"]:
|
||
meta.append("延期")
|
||
detail = entry["detail"]
|
||
if entry["result"]:
|
||
detail += ("<br>" if detail else "") + "<b>结果:</b>" + entry["result"]
|
||
daily_rows.append({"title_html": _rich(entry["content"]), "meta": meta, "detail": detail})
|
||
|
||
product_sections = []
|
||
for project in products:
|
||
update_rows = []
|
||
for update in project["updates"]:
|
||
meta = [_status(update.get("status"))]
|
||
if update.get("task_name"):
|
||
meta.append(str(update["task_name"]))
|
||
if update.get("progress") is not None:
|
||
meta.append(f"进度 {update['progress']}%")
|
||
if update.get("period_label"):
|
||
meta.append(str(update["period_label"]))
|
||
detail = ""
|
||
for label, field in (("风险:", "risk"), ("下一步:", "next_step")):
|
||
if update.get(field):
|
||
rich = _rich(update[field])
|
||
detail += ("<br>" if detail else "") + "<b>" + label + "</b>" + rich
|
||
update_rows.append({"title_html": _rich(update.get("summary") or update.get("content") or "(无正文)"),
|
||
"meta": meta, "detail": detail})
|
||
if not project["updates"]:
|
||
update_rows.append({"title_html": "本期无执行记录", "meta": [project["status"]], "detail": ""})
|
||
product_sections.append(
|
||
f'<h3>{_esc(project["name"])}</h3>' + items(update_rows, "本期无执行记录")
|
||
)
|
||
product_rows = "".join(product_sections) if product_sections else items([], "本期没有自研产品记录")
|
||
|
||
def custom_rows(rows: list[dict], fields: list[tuple[str, str]]) -> str:
|
||
if not rows:
|
||
return '<p class="note">本期没有符合条件的定制项目</p>'
|
||
out = []
|
||
for row in rows:
|
||
meta = []
|
||
for field, suffix in fields:
|
||
value = row.get(field)
|
||
if value:
|
||
meta.append(str(value) + suffix)
|
||
out.append(
|
||
'<div class="item"><div class="title">' + _esc(row["name"]) + "</div>"
|
||
+ '<div class="meta">' + "".join(f"<span>{_esc(x)}</span>" for x in meta) + "</div>"
|
||
+ (f'<div class="body">{row["summary"]}</div>' if row.get("summary") else "")
|
||
+ "</div>"
|
||
)
|
||
return "".join(out)
|
||
|
||
summary_cards = [
|
||
("重点工作", len(daily["week"]) + len(daily["carry"])),
|
||
("自研产品", len(products)),
|
||
("执行记录", kpi.get("update_count", 0)),
|
||
("定制新增", len(custom["added"])),
|
||
("定制验收", len(custom["accepted"])),
|
||
]
|
||
ctx = finance_data.get("context") or {}
|
||
head = (
|
||
"<h1>工作汇报</h1>"
|
||
+ '<p class="sub">统计区间:'
|
||
+ _esc(payload["range_label"])
|
||
+ " | 财务年度:"
|
||
+ _esc(ctx.get("year", "—"))
|
||
+ " | 生成时间:"
|
||
+ _esc(payload["generated_at"])
|
||
+ "</p>"
|
||
)
|
||
body = (
|
||
'<section class="section"><h2>概要</h2><div class="summary">'
|
||
+ "".join(f"<div><b>{_esc(value)}</b><span>{_esc(label)}</span></div>" for label, value in summary_cards)
|
||
+ "</div></section>"
|
||
+ '<section class="section"><h2>一、日常工作</h2>'
|
||
+ items(daily_rows, "本期没有重点工作")
|
||
+ "</section>"
|
||
+ '<section class="section"><h2>二、自研产品</h2>'
|
||
+ product_rows
|
||
+ "</section>"
|
||
+ '<section class="section"><h2>三、年度任务财务情况</h2>'
|
||
+ _finance_table(finance_data)
|
||
+ "</section>"
|
||
+ '<section class="section"><h2>四、定制项目</h2>'
|
||
+ "<h3>新增</h3>" + custom_rows(custom["added"], [("region", ""), ("owner", ""), ("sign_date", ""), ("stage", ""), ("amount", " 万元")])
|
||
+ "<h3>验收</h3>" + custom_rows(custom["accepted"], [("region", ""), ("owner", ""), ("update_date", ""), ("status", ""), ("amount", " 万元")])
|
||
+ "</section>"
|
||
)
|
||
return (
|
||
"<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\">"
|
||
'<meta name="viewport" content="width=device-width,initial-scale=1">'
|
||
"<title>工作汇报-" + _esc(payload["range_label"]) + "</title><style>" + STYLE + "</style></head><body>"
|
||
+ '<main class="page">' + head + body + "</main></body></html>"
|
||
)
|
||
|
||
|
||
def _content(payload: dict, filename: str) -> Response:
|
||
stamp = datetime.now().strftime("%Y%m%d_%H%M")
|
||
full = f"{filename}_{stamp}.html"
|
||
quoted = quote(full)
|
||
return Response(
|
||
content=build_html(payload).encode("utf-8"),
|
||
media_type="text/html",
|
||
headers={
|
||
"Content-Disposition": f"attachment; filename=\"{quoted}\"; filename*=UTF-8''{quoted}",
|
||
"Access-Control-Expose-Headers": "Content-Disposition",
|
||
},
|
||
)
|
||
|
||
|
||
@router.get("/export/board-report")
|
||
def export_board_report(
|
||
period_id: int | None = None,
|
||
year: int | None = None,
|
||
month: int | None = None,
|
||
keyword: str | None = None,
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""看板当前周期的完整工作汇报(单页 HTML),不改变任何看板数据口径。"""
|
||
weekly = weekly_endpoint(period_id=period_id, year=year, month=month, db=db)
|
||
period_ids = [int(p["id"]) for p in weekly.get("periods", [])]
|
||
fin = finance.summary(db, finance.period_context(db, period_id=period_id, year=year, month=month))
|
||
periods = weekly.get("periods") or []
|
||
range_label = "、".join(str(p.get("full_label") or p.get("label") or "") for p in periods) or (
|
||
f"{year}年{month}月" if year and month else "未选周期"
|
||
)
|
||
start, end, range_label = _date_range(db, period_id, year, month, range_label)
|
||
carry, week = _focus_rows(db, period_ids, keyword)
|
||
products = []
|
||
kw = (keyword or "").strip()
|
||
for row in sorted(weekly.get("projects", []), key=lambda item: str(item.get("name") or "")):
|
||
updates = row.get("updates") or []
|
||
if kw:
|
||
updates = [update for update in updates if any(kw in str(value or "") for value in (
|
||
row.get("name"), plain(update.get("summary")), plain(update.get("content")),
|
||
update.get("task_name"), plain(update.get("risk")), plain(update.get("next_step")),
|
||
))]
|
||
if not updates:
|
||
continue
|
||
products.append({
|
||
"name": row.get("name"),
|
||
"status": _status(row.get("status")),
|
||
"progress": row.get("progress"),
|
||
"updates": updates,
|
||
})
|
||
payload = {
|
||
"range_label": range_label,
|
||
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
||
"daily": {"carry": carry, "week": week},
|
||
"products": products,
|
||
"custom": _custom_sections(db, weekly, start, end, keyword),
|
||
"finance": fin,
|
||
"kpi": weekly.get("kpi") or {},
|
||
}
|
||
return _content(payload, "工作汇报")
|