diff --git a/app/main.py b/app/main.py index f0ab244..e1875bf 100755 --- a/app/main.py +++ b/app/main.py @@ -8,7 +8,7 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles -from . import audit, config, finance, security +from . import audit, config, finance, security, work_report from .db import Base, SessionLocal, engine from .routers import ai, auth, board, custom, export, focus, projects, rbac, staff, weekly from .schema_patch import drop_stale_columns, ensure_columns @@ -70,6 +70,7 @@ api.include_router(projects.router, prefix="", tags=["projects"]) api.include_router(ai.router, prefix="", tags=["ai"]) api.include_router(custom.router, prefix="", tags=["custom"]) api.include_router(export.router, prefix="", tags=["export"]) +api.include_router(work_report.router, prefix="", tags=["export"]) api.include_router(staff.router, prefix="", tags=["staff"]) api.include_router(weekly.router, prefix="", tags=["weekly"]) api.include_router(focus.router, prefix="", tags=["focus"]) diff --git a/app/security.py b/app/security.py index 868e94b..90da37d 100755 --- a/app/security.py +++ b/app/security.py @@ -58,6 +58,7 @@ SEGMENT_MENU = { } # /export/xxx 跟着对应页面走 EXPORT_MENU = { + "board-report": "board", "custom": "custom", "custom-updates": "custom", "projects": "projects", diff --git a/app/work_report.py b/app/work_report.py new file mode 100644 index 0000000..23cc423 --- /dev/null +++ b/app/work_report.py @@ -0,0 +1,434 @@ +"""工作汇报页导出:把工作看板的全部板块合成一个可离线打开的 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"(]{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", "
") + + +def _rich_tag(tag: str) -> str: + lower = tag.lower() + if re.match(r"$", lower): + return "
" + if lower.startswith("

") or lower.startswith(""): + return "" + if lower.startswith("" + if re.match(r"", lower): + return lower + if lower.startswith(""): + return "" + color = re.search(r'data-c=["\']([^"\']+)["\']', lower) + if color and color.group(1) in RICH_COLORS: + return f'' + return "" + + +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 "" + "".join(f"{c}" for c in cells) + "" + + 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([ + "合计", f"{_esc(total.get('acc_count', 0))}", + f"{_wan(total.get('acc_amount'))}", + f"{_esc(total.get('sign_count', 0))}", + f"{_wan(total.get('sign_amount'))}", + f"{_wan(total.get('target'))}", "", + ], "sum")) + return ( + "" + "" + "" + "".join(body) + "
季度验收项目数验收金额(万元)下单项目数下单金额(万元)计收目标(万元)目标完成率
" + ) + + +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'

{empty}

' + out = [] + for entry in rows: + out.append( + '
' + + (entry.get("title_html") or _esc(entry.get("content") or entry.get("name") or "—")) + + "
" + + '
' + + "".join(f"{_esc(part)}" for part in entry.get("meta", []) if part) + + "
" + + (f'
{entry.get("detail") or entry.get("summary") or ""}
' + if entry.get("detail") or entry.get("summary") else "") + + "
" + ) + 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 += ("
" if detail else "") + "结果:" + 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 += ("
" if detail else "") + "" + label + "" + 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'

{_esc(project["name"])}

' + 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 '

本期没有符合条件的定制项目

' + out = [] + for row in rows: + meta = [] + for field, suffix in fields: + value = row.get(field) + if value: + meta.append(str(value) + suffix) + out.append( + '
' + _esc(row["name"]) + "
" + + '
' + "".join(f"{_esc(x)}" for x in meta) + "
" + + (f'
{row["summary"]}
' if row.get("summary") else "") + + "
" + ) + 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 = ( + "

工作汇报

" + + '

统计区间:' + + _esc(payload["range_label"]) + + " | 财务年度:" + + _esc(ctx.get("year", "—")) + + " | 生成时间:" + + _esc(payload["generated_at"]) + + "

" + ) + body = ( + '

概要

' + + "".join(f"
{_esc(value)}{_esc(label)}
" for label, value in summary_cards) + + "
" + + '

一、日常工作

' + + items(daily_rows, "本期没有重点工作") + + "
" + + '

二、自研产品

' + + product_rows + + "
" + + '

三、年度任务财务情况

' + + _finance_table(finance_data) + + "
" + + '

四、定制项目

' + + "

新增

" + custom_rows(custom["added"], [("region", ""), ("owner", ""), ("sign_date", ""), ("stage", ""), ("amount", " 万元")]) + + "

验收

" + custom_rows(custom["accepted"], [("region", ""), ("owner", ""), ("update_date", ""), ("status", ""), ("amount", " 万元")]) + + "
" + ) + return ( + "" + '' + "工作汇报-" + _esc(payload["range_label"]) + "" + + '
' + head + body + "
" + ) + + +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, "工作汇报") diff --git a/scripts/run.sh b/scripts/run.sh index d913e8c..9982cf4 100755 --- a/scripts/run.sh +++ b/scripts/run.sh @@ -273,11 +273,11 @@ NPM_REGISTRY="${NPM_REGISTRY:-$(env_get NPM_REGISTRY)}" NPM_REGISTRY="${NPM_REGISTRY:-https://registry.npmmirror.com}" need_build() { - [ "${WEB}" = "0" ] && ${ log " 前端构建:跳过(WEB=0)"; return 1; } + [ "${WEB}" = "0" ] && { log " 前端构建:跳过(WEB=0)"; return 1; } [ -f web/dist/index.html ] || return 0 [ "${WEB}" = "force" ] && return 0 # dist 比任何源文件旧就重建(配置 / src / lockfile) - [ -z "$(find web/src web/index.html web/vite.config.ts web/tsconfig.json web/package-lock.json -newer web/dist/index.html 2>/dev/null | head -1)" ] && ${ log " 前端构建:已是最新,跳过"; return 1; } + [ -z "$(find web/src web/index.html web/vite.config.ts web/tsconfig.json web/package-lock.json -newer web/dist/index.html 2>/dev/null | head -1)" ] && { log " 前端构建:已是最新,跳过"; return 1; } return 0 } diff --git a/tests/test_api_contract.py b/tests/test_api_contract.py index cad1b6b..0e03718 100755 --- a/tests/test_api_contract.py +++ b/tests/test_api_contract.py @@ -30,7 +30,7 @@ def test_校验失败返回中文detail(h): def test_未登记导出接口fail_closed(): """/export/* 一律按 EXPORT_MENU 判权限;没登记的导出名不允许 fail-open 成「登录即可下载」。""" - assert set(EXPORT_MENU) >= {"custom", "custom-updates", "projects", "updates", "staff", "focus"} + assert set(EXPORT_MENU) >= {"board-report", "custom", "custom-updates", "projects", "updates", "staff", "focus"} for name, menu in EXPORT_MENU.items(): assert resolve_rule("/api/export/" + name, "GET") == (menu, False) with pytest.raises(HTTPException) as e: diff --git a/tests/test_rbac.py b/tests/test_rbac.py index 429e5ef..41714a4 100755 --- a/tests/test_rbac.py +++ b/tests/test_rbac.py @@ -54,6 +54,9 @@ def test_导出接口跟着对应页面的权限(h): assert viewer.get("/api/export/custom").status_code == 200 assert viewer.get("/api/export/focus").status_code == 200 assert viewer.get("/api/export/projects").status_code == 403 + assert viewer.get("/api/export/board-report").status_code == 403 + board_reader = h.user_client("board_reader", menus={"board": "ro"}) + assert board_reader.get("/api/export/board-report").status_code == 200 writer = h.user_client("writer", menus={"projects": "rw"}) assert writer.get("/api/export/projects").status_code == 200 assert writer.get("/api/export/custom").status_code == 403 diff --git a/tests/test_work_report.py b/tests/test_work_report.py new file mode 100644 index 0000000..12410a5 --- /dev/null +++ b/tests/test_work_report.py @@ -0,0 +1,63 @@ +"""看板工作汇报页:单页 HTML 同时覆盖日常工作、自研产品、定制项目与年度财务表。""" +from __future__ import annotations + +from app import constants +from app.db import SessionLocal +from app.models import CustomProject + + +def test_看板导出完整工作汇报页(h): + week = h.period(2028, 3, 2) + old_week = h.period(2028, 2, 1) + first = constants.period_first_day(2028, 3, 2) + project = h.project("自研甲", owners=["王芳"], is_key=True) + second_project = h.project("自研乙", owners=["李四"], is_key=True) + h.update(project["id"], week["id"], content="完成联调", + summary='
接口联调完成待确认
补充说明
', + status="at_risk", risk="等文档") + h.update(second_project["id"], week["id"], content="完成方案", summary="方案评审通过") + h.focus("准备验收材料", period_id=week["id"], + detail='

整理验收清单完成

第二行

', due_date="2028-03-20") + h.focus("历史遗留任务", period_id=old_week["id"], detail="不该出现在选中周期", delayed=True) + added = h.custom("新增乙", origin="华智下单", amount=100000, sign_date=first, update_date=first, + project_status="进行中") + accepted = h.custom("验收丙", origin="华智下单", amount=200000, update_date=first, + project_status="已验收") + risky = h.custom("高风险丁", origin="华智下单", amount=300000, risk_level="1.高风险") + idle_risky = h.custom("高风险戊", origin="华智下单", amount=400000, risk_level="1.高风险") + h.custom_update(risky["id"], week["id"], content="协调风险") + # 创建接口固定写今天;把周期字段改成选中周期,对齐看板的「本期」口径 + with SessionLocal() as db: + for name in ("新增乙", "验收丙"): + row = next(row for row in db.query(CustomProject).all() if row.name == name) + row.update_date = first + " 09:00" + row.sign_date = first + db.commit() + + resp = h.admin.get("/api/export/board-report", params={"period_id": week["id"]}) + assert resp.status_code == 200, resp.text + assert resp.headers["content-type"].startswith("text/html") + assert "attachment" in resp.headers["content-disposition"] + assert ".html" in resp.headers["content-disposition"] + + body = resp.text + for text in ("工作汇报", "一、日常工作", "二、自研产品", "三、年度任务财务情况", "四、定制项目", + "准备验收材料", "新增乙", "验收丙", "计收目标(万元)"): + assert text in body, text + assert "高风险丁" not in body + assert "高风险戊" not in body + assert "本期没有重点工作" not in body + assert "2028 Q1" in body + assert "历史遗留任务" not in body + assert body.index("自研乙") < body.index("方案评审通过") < body.index("自研甲") < body.index("联调完成") + assert body.index("三、年度任务财务情况") < body.index("四、定制项目") + assert "接口联调完成" in body + assert '待确认' in body + assert "整理" in body + assert "完成" in body + assert "第二行" in body + + filtered = h.admin.get("/api/export/board-report", params={"period_id": week["id"], "keyword": "不存在的工作"}) + assert "本期没有重点工作" in filtered.text + assert "接口联调完成" not in filtered.text + assert "新增乙" not in filtered.text diff --git a/web/src/api/client.ts b/web/src/api/client.ts index b902882..7f6eaa3 100755 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -51,7 +51,7 @@ export const post = async (path: string, body?: unknown): Promise => (awai export const patch = async (path: string, body?: unknown): Promise => (await http.patch(path, body ?? {})).data; export const del = async (path: string, q?: Query): Promise => (await http.delete(path, { params: clean(q) })).data; -/** 导出 Excel:fetch + blob。403/500 的 JSON 错误用 toast 报出,不用 跳转把 SPA 顶成错误页。 +/** 导出文件:fetch + blob。403/500 的 JSON 错误用 toast 报出,不用 跳转把 SPA 顶成错误页。 * btn 传触发按钮:等待期间 disabled + aria-busy(等待要有交代)。*/ export async function download(url: string, btn?: (HTMLElement & { disabled?: boolean }) | null, onMsg?: (m: string) => void): Promise { if (btn) { btn.disabled = true; btn.setAttribute("aria-busy", "true"); } @@ -67,7 +67,7 @@ export async function download(url: string, btn?: (HTMLElement & { disabled?: bo const m = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(cd); const a = document.createElement("a"); a.href = URL.createObjectURL(blob); - a.download = m ? decodeURIComponent(m[1]) : "export.xlsx"; + a.download = m ? decodeURIComponent(m[1]) : ((res.headers.get("content-type") || "").includes("html") ? "export.html" : "export.xlsx"); document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); onMsg?.("已下载 " + a.download); diff --git a/web/src/api/endpoints.ts b/web/src/api/endpoints.ts index 08da03d..cc47ae8 100755 --- a/web/src/api/endpoints.ts +++ b/web/src/api/endpoints.ts @@ -108,6 +108,8 @@ export const fetchLogs = (q?: Query) => export const clearLogs = (days: number) => del("/rbac/logs", { days }); /* ---------- 导出 Excel(返回完整 URL,交给 download() 走 fetch+blob)---------- */ +export const exportBoardReportUrl = (q?: Query) => + "/export/board-report" + tail({ period_id: q?.period_id, year: q?.year, month: q?.month, keyword: q?.keyword }); export const exportProjectsUrl = (q?: Query) => "/export/projects" + tail({ category_id: q?.category_id, keyword: q?.keyword, owner: q?.owner, idle_only: q?.idle_only, period_id: q?.period_id, year: q?.year, month: q?.month, archived: q?.archived }); export const exportUpdatesUrl = (q?: Query) => diff --git a/web/src/components/FormDrawer.tsx b/web/src/components/FormDrawer.tsx index 1225c12..72f5bfe 100755 --- a/web/src/components/FormDrawer.tsx +++ b/web/src/components/FormDrawer.tsx @@ -1,10 +1,11 @@ -import { Button, Drawer } from "antd"; +import { Button } from "antd"; import type { ReactNode } from "react"; +import { NestedSidePanel, SidePanel } from "./SidePanel"; /** * 新增 / 修改表单的统一容器:一律右侧侧滑(用户要求:表单不混用弹窗)。 * 破坏性动作的确认框不在这里,仍走 modal.confirm(危险按钮 danger)。 - * 头部结构与其他抽屉同款(.drawer-head-text / .dlg-title / .drawer-sub),底部固定「取消 + 保存」右对齐, + * 头部结构与其他抽屉同款(.drawer-head-text / .dlg-title / .drawer-sub),主按钮固定在顶部 Header 右侧, * 焦点进出、Esc 关闭、焦点归还触发元素都交给 AntD Drawer,不自己实现焦点栈。 */ export function FormDrawer(props: { @@ -22,24 +23,31 @@ export function FormDrawer(props: { className?: string; /** 需要自定义底部(比如右侧再放个说明)时给;给了就不再渲染默认按钮 */ footer?: ReactNode; + /** 追加到顶部按钮条的内容(危险动作等),主按钮始终在最右 */ + extraActions?: ReactNode; + /** 从其它侧面板里打开的二次表单面板:嵌在父面板内,不另开遮罩 */ + nested?: boolean; }) { - const { open, title, subtitle, onClose, onSubmit, okText = "保存", cancelText = "取消", busy, width = 560, children, footer, className } = props; + const { open, title, subtitle, onClose, onSubmit, okText = "保存", cancelText = "取消", busy, width = 560, children, footer, className, extraActions, nested } = props; + const Panel = nested ? NestedSidePanel : SidePanel; + const actions = ( +
+ {extraActions} + + {/* 表单校验失败会让 onSubmit 的 promise reject(AntD Form 的老行为),这里吞掉即可:错误已在字段下面红字显示 */} + +
+ ); return ( -

{title}

{subtitle ?
{subtitle}
: null} - }> + } + extra={actions}>
{children}
- {footer === undefined ? ( -
- - {/* 表单校验失败会让 onSubmit 的 promise reject(AntD Form 的老行为),这里吞掉即可: - 错误已经在字段下面红字显示,不要再往控制台丢一条 unhandled rejection */} - -
- ) : footer} -
+ {footer === undefined ? null : footer} + ); } diff --git a/web/src/components/LoginGate.tsx b/web/src/components/LoginGate.tsx index ba80412..518eeb4 100755 --- a/web/src/components/LoginGate.tsx +++ b/web/src/components/LoginGate.tsx @@ -20,24 +20,41 @@ export function LoginGate() { finally { setBusy(false); } }; return ( -
-
-
-
-

DMS管理平台

-

软件开发部 · 关键任务与项目跟踪。登录后按角色看到有权限的菜单。

+
+
+
+
+
+ DMS管理平台 +
+
+

关键任务 管理平台

+

全流程任务与项目协作跟踪,让每一项工作都清晰可控。

+
+
+
+ 团队知识共享 + 大模型能力加持 +
+ © 2024 DMS管理平台. All rights reserved. +
-
-

登录

+
+
+
+
账号登录
+

欢迎回来,请输入您的登录凭证。

- - + + } /> - + } /> {err ? : null} - +
diff --git a/web/src/components/OverlayModal.tsx b/web/src/components/OverlayModal.tsx new file mode 100644 index 0000000..92b6bef --- /dev/null +++ b/web/src/components/OverlayModal.tsx @@ -0,0 +1,9 @@ +import { Modal } from "antd"; +import type { ModalProps } from "antd"; +import { useOverlayLayer } from "../store/overlay"; + +/** 弹层栈内的 Modal:打开时暂停下层侧面板,关闭后恢复。 */ +export function OverlayModal({ open, ...props }: ModalProps & { open: boolean }) { + const active = useOverlayLayer(open); + return ; +} diff --git a/web/src/components/SidePanel.tsx b/web/src/components/SidePanel.tsx new file mode 100644 index 0000000..79fcae6 --- /dev/null +++ b/web/src/components/SidePanel.tsx @@ -0,0 +1,35 @@ +import { Drawer } from "antd"; +import type { DrawerProps } from "antd"; +import { useOverlayLayer } from "../store/overlay"; + +/** 子面板:与父面板共用一个弹层栈;打开时父面板关闭,关闭后父面板恢复。 */ +export function NestedSidePanel(props: DrawerProps & { open: boolean }) { + const active = useOverlayLayer(props.open); + return ( + + ); +} + +/** 全站侧面板:右侧抽屉 + 统一头部/脚部内边距 + 二次弹层交替置顶。 */ +export function SidePanel(props: DrawerProps & { open: boolean }) { + return ( + + ); +} diff --git a/web/src/store/overlay.ts b/web/src/store/overlay.ts new file mode 100644 index 0000000..a22e8d8 --- /dev/null +++ b/web/src/store/overlay.ts @@ -0,0 +1,31 @@ +import { useEffect, useLayoutEffect, useRef } from "react"; +import { create } from "zustand"; + +let sequence = 0; + +/** 全站弹层栈:后开的弹层置顶,此前那个自动收起;关闭后自动恢复前一个。 */ +export const useOverlay = create<{ stack: string[]; push: (id: string) => void; remove: (id: string) => void }>((set) => ({ + stack: [], + push: (id) => set((state) => (state.stack.includes(id) ? state : { stack: [...state.stack, id] })), + remove: (id) => set((state) => (state.stack.includes(id) ? { stack: state.stack.filter((item) => item !== id) } : state)), +})); + +export function nextOverlayId(): string { + sequence += 1; + return `overlay-${sequence}`; +} + +/** 弹层是否位于栈顶。逻辑上仍开着、只是被后一个弹层顶下去时返回 false。 */ +export function useOverlayLayer(open: boolean): boolean { + const id = useRef(nextOverlayId()).current; + const stack = useOverlay((state) => state.stack); + + useLayoutEffect(() => { + if (open) useOverlay.getState().push(id); + else useOverlay.getState().remove(id); + }, [open, id]); + + useEffect(() => () => useOverlay.getState().remove(id), [id]); + + return open && stack[stack.length - 1] === id; +} diff --git a/web/src/store/usePanelConfirm.ts b/web/src/store/usePanelConfirm.ts new file mode 100644 index 0000000..9bdb71b --- /dev/null +++ b/web/src/store/usePanelConfirm.ts @@ -0,0 +1,35 @@ +import { App } from "antd"; +import type { ModalFuncProps } from "antd"; +import { useCallback } from "react"; +import { nextOverlayId, useOverlay } from "./overlay"; + +/** 侧面板里的破坏性确认:压入同一个弹层栈,关闭后把抽屉恢复为可交互的顶层。 */ +export function usePanelConfirm() { + const { modal } = App.useApp(); + + return useCallback((config: ModalFuncProps) => { + const id = nextOverlayId(); + useOverlay.getState().push(id); + let settled = false; + const settle = () => { + if (settled) return; + settled = true; + useOverlay.getState().remove(id); + }; + return modal.confirm({ + ...config, + afterClose: () => { + settle(); + config.afterClose?.(); + }, + onOk: async (event) => { + try { await config.onOk?.(event); } + catch (error) { settle(); throw error; } + }, + onCancel: (event) => { + settle(); + config.onCancel?.(event); + }, + }); + }, [modal]); +} diff --git a/web/src/styles/app.css b/web/src/styles/app.css index e6199fe..b89d3f3 100755 --- a/web/src/styles/app.css +++ b/web/src/styles/app.css @@ -198,49 +198,47 @@ button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible .app.nav-folded .nav-fold .ic-unfold { display: inline-flex; } -.auth-shell { width: min(880px, 100%); display: grid; grid-template-columns: 1.05fr .95fr; - background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; - box-shadow: var(--shadow-xl); } +.auth-mask { --auth-bg: #eef4ff; --auth-ink-2: #475467; + position: fixed; inset: 0; z-index: var(--z-modal); display: grid; grid-template-columns: minmax(0, 2fr) minmax(380px, 1fr); + background: var(--auth-bg); } -.auth-brand { --auth-g1: #16255c; --auth-g2: #1f3f9e; --auth-g3: #3b5fd0; - --auth-ink: #e8f0ff; --auth-ink-70: rgba(232, 240, 255, .7); --auth-ink-85: rgba(232, 240, 255, .85); - position: relative; overflow: hidden; padding: 34px 34px 30px; - display: flex; flex-direction: column; gap: 28px; color: var(--auth-ink); - background: linear-gradient(155deg, var(--auth-g1) 0%, var(--auth-g2) 52%, var(--auth-g3) 100%); } +.auth-brand { min-width: 0; padding: 56px clamp(40px, 7vw, 132px); + display: flex; align-items: stretch; color: var(--text); } +.auth-brand-inner { width: 100%; max-width: 720px; display: flex; flex-direction: column; } +.auth-logo { display: flex; align-items: center; gap: 12px; font-size: 20px; font-weight: 600; color: var(--primary); } +.auth-logo .brand-mark { width: 42px; height: 42px; border-radius: var(--radius-md); background: var(--primary); color: var(--text-inverse); } +.auth-logo .brand-mark .ic { width: 24px; height: 24px; } +.auth-hero { margin: auto 0; } +.auth-hero h1 { margin: 0 0 20px; font-size: clamp(34px, 4vw, 52px); line-height: 1.25; letter-spacing: -.5px; } +.auth-hero h1 span { color: var(--primary); } +.auth-hero p { margin: 0; color: var(--auth-ink-2); font-size: 16px; } +.auth-points { display: flex; gap: 28px; margin-bottom: 10px; color: var(--auth-ink-2); font-size: 13px; } +.auth-points span { display: inline-flex; align-items: center; gap: 7px; } +.auth-points i { width: 7px; height: 7px; border-radius: 50%; background: var(--primary); } +.auth-foot small { color: var(--muted); } -.auth-brand::before, .auth-brand::after { content: ""; position: absolute; border-radius: 50%; pointer-events: none; } +.auth-form { min-width: 0; padding: 96px clamp(32px, 5vw, 72px) 48px; background: var(--panel); display: flex; align-items: flex-start; justify-content: center; } +.auth-form-inner { width: 100%; max-width: 380px; } +.auth-title-row { display: flex; border-bottom: 1px solid var(--border); margin-bottom: 30px; } +.auth-title-row span { position: relative; padding-bottom: 12px; color: var(--text-2); font-weight: 600; } +.auth-title-row .active { color: var(--primary); } +.auth-title-row .active::after { content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; background: var(--primary); } +.auth-hint { margin: 0 0 26px; color: var(--muted); font-size: 13px; } +.auth-form .ant-form-item { margin-bottom: 22px; } +.auth-form .ant-form-item-label > label { color: var(--text); font-weight: 500; } +.auth-form .ant-form-item-label > label::before { color: var(--primary); } +.auth-form .ant-input-affix-wrapper { height: 46px; border-radius: var(--radius-sm); } +.auth-form .ant-input-prefix { color: var(--muted); margin-right: 10px; } +.auth-err { margin-bottom: 16px; } +.auth-ok { height: 48px; border-radius: var(--radius-sm); font-weight: 600; } +.auth-ok .ic { width: 18px; height: 18px; margin-left: 6px; } -.auth-brand::before { width: 360px; height: 360px; right: -170px; top: -130px; - background: radial-gradient(closest-side, color-mix(in srgb, var(--panel) 17%, transparent), transparent); } - -.auth-brand::after { width: 260px; height: 260px; left: -130px; bottom: -140px; - background: radial-gradient(closest-side, color-mix(in srgb, var(--auth-g3) 55%, var(--panel)) , transparent); } - -.auth-brand .brand-mark { background: color-mix(in srgb, var(--panel) 16%, transparent); color: var(--text-inverse); } - -.ab-top .brand-text h1 { color: var(--text-inverse); } - -.ab-top .brand-text span { color: var(--auth-ink-70); } - -.ab-mid li .ic { width: 15px; height: 15px; flex: none; opacity: .85; } - -.auth-form { padding: 40px 40px 32px; display: flex; flex-direction: column; } - -.auth-form h3 { margin: 0; font-size: 21px; letter-spacing: .2px; } - -.auth-form .notice.err { margin-bottom: 14px; } - -@media (max-width: 780px) { -.auth-shell { grid-template-columns: 1fr; } -} -@media (max-width: 780px) { -.auth-brand { padding: 18px 20px; gap: 0; } -} -@media (max-width: 780px) { -.auth-brand .ab-mid { display: none; } -} -@media (max-width: 780px) { -.auth-form { padding: 26px 22px 22px; } +@media (max-width: 900px) { + .auth-mask { grid-template-columns: 1fr; overflow: auto; } + .auth-brand { padding: 40px 24px 24px; } + .auth-brand-inner { max-width: none; } + .auth-hero { margin: 56px 0; } + .auth-form { padding: 40px 24px 56px; } } .rbac-menu-th { font-size: 11px !important; white-space: nowrap; } @@ -968,13 +966,27 @@ textarea.inp { height: auto; padding: 8px 10px; line-height: 1.6; } .form-drawer .ant-drawer-body { padding: 0; } .form-drawer .drawer-head-text { min-width: 0; } .form-drawer .drawer-head-text .dlg-title { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; } -.form-drawer .ant-drawer-footer { padding: 12px 20px; } -.form-drawer .btn-bar { display: flex; gap: 10px; justify-content: flex-end; } @media (max-width: 640px) { /* 窄屏给全宽,理由同旧版底部弹窗:560px 的抽屉在手机上只剩一条缝(className 落在 .ant-drawer-section 面板上)*/ .form-drawer { width: 100% !important; max-width: 100vw; box-shadow: none; } } +/* ---------- 侧面板统一外壳(components/SidePanel)---------- + 头部、正文、底部一律 20px 水平内边距;详情/修改档的主按钮随标题常驻头部。 */ +.ant-drawer .panel-header { padding: 14px 20px; gap: 12px; align-items: flex-start; } +.ant-drawer .panel-header .ant-drawer-header-title { align-items: flex-start; } +.ant-drawer .panel-header .drawer-head-text, +.ant-drawer .panel-header .ant-drawer-title { min-width: 0; } +.ant-drawer .panel-header .dlg-title { margin: 0; font-size: 16px; font-weight: 600; } +.ant-drawer .panel-header .btn-bar { flex-wrap: nowrap; gap: 8px; } +.ant-drawer .panel-body { padding: 18px 20px 40px; } +.ant-drawer .panel-footer { padding: 12px 20px; } +.form-drawer .panel-body { padding: 18px 20px 40px; } +@media (max-width: 900px) { + .ant-drawer .panel-header { flex-wrap: wrap; } + .ant-drawer .panel-header .btn-bar { width: 100%; justify-content: flex-end; } +} + /* ---------- 正文富文本(components/RichEditor + RichText,口径见 utils/richtext.ts)---------- 编辑区外观跟原来的多行文本框一致,只是多了上面一条工具栏。 */ .rich-field { width: 100%; } diff --git a/web/src/theme/antd.ts b/web/src/theme/antd.ts index ac1517b..a3d5bf3 100755 --- a/web/src/theme/antd.ts +++ b/web/src/theme/antd.ts @@ -63,7 +63,7 @@ export function buildAntdTheme(mode: ThemeMode): ThemeConfig { components: { Card: { borderRadiusLG: GEOM.radiusCard, paddingLG: 16 }, Table: { headerBg: mode === "dark" ? p.panel2 : p.panel, cellPaddingBlockSM: 7, cellPaddingInlineSM: 10, borderRadiusLG: GEOM.radiusCard }, - Drawer: { paddingLG: 18 }, + Drawer: { paddingLG: 20 }, Tabs: { horizontalItemPadding: "8px 2px" }, }, }; diff --git a/web/src/views/BoardView.tsx b/web/src/views/BoardView.tsx index e739168..101871e 100755 --- a/web/src/views/BoardView.tsx +++ b/web/src/views/BoardView.tsx @@ -27,6 +27,7 @@ import { INK, focusDueText, focusIsLate, isHighRisk, tint } from "../domain/ink" import { CatPill, FocusPill, StagePill, StarMark, StatusPill, TagMini } from "../domain/pills"; import { Icon, IconBadge, PipeIcon, StatusIcon, nameOfStage, nameOfStatus } from "../icons/Icon"; import { stageMeta, statusMeta, useMeta } from "../store/meta"; +import { usePanelConfirm } from "../store/usePanelConfirm"; import { useCan } from "../store/session"; import { periodCrossDays, periodCrossNote, periodOptionLabel, shortDay } from "../utils/period"; import { usePeriodParams, useUi } from "../store/ui"; @@ -541,7 +542,7 @@ function RecordModal({ dlg, onClose }: { dlg: RecDlg; onClose: () => void }) { }; return ( -
@@ -616,7 +617,8 @@ function WkGroup({ icon, title, count, foot, children }: { /* -------------------------------------------------------------------- 视图 */ /** 工作看板:本期 KPI → 看板工具栏 → 左栏三条清单 + 右栏执行详情 */ export function BoardView() { - const { message, modal } = App.useApp(); + const { message } = App.useApp(); + const modal = usePanelConfirm(); const { r, w } = useCan(); const nav = useNavigate(); const gran = useUi((s) => s.gran); @@ -638,6 +640,7 @@ export function BoardView() { const [delCustom, setDelCustom] = useState(null); const canReadStaff = r("staff"); const canReadProjects = r("projects"); + const canReadBoard = r("board"); /* 旧版 renderBoard 起手的四路并发(负责人筛选只过滤两栏清单); customMeta 是阶段色 / 台账状态的唯一来源,先补齐再并发取数。 @@ -694,19 +697,18 @@ export function BoardView() { const row = sel && sel.kind !== "focus" && sel.kind !== "customs" ? all.find((x) => x.kind === sel.kind && x.id === sel.id) || null : null; - /* 看板工具栏:负责人筛选只过滤两栏清单;导出按顶栏周期导出全部执行记录 - (与列表页「导出 Excel」同一位置语义,按后端权限归「自研产品」菜单) */ + /* 看板工具栏:负责人筛选只过滤两栏清单;导出按顶栏周期生成当前看板的完整工作汇报 */ const doExport = async () => { const key = "board-export"; - message.loading({ content: "正在生成 Excel,请稍候…", key, duration: 0 }); + message.loading({ content: "正在生成工作汇报页,请稍候…", key, duration: 0 }); try { - await download(api.exportUpdatesUrl({ ...params, keyword: keyword || undefined }), exportRef.current, + await download(api.exportBoardReportUrl({ ...params, keyword: keyword || undefined }), exportRef.current, (m) => (m.startsWith("已下载") ? message.success({ content: m, key }) : message.error({ content: m, key }))); } catch { /* download 已经把失败文案报出来了 */ } }; /* 删除一条周期记录:破坏性动作走确认框(旧版 confirmDialog 同文案) */ - const delUpdate = (u: UpdateRow, kind: "project" | "custom") => modal.confirm({ + const delUpdate = (u: UpdateRow, kind: "project" | "custom") => modal({ title: "删除这条记录?", okText: "永久删除", cancelText: "取消", @@ -736,7 +738,7 @@ export function BoardView() { /* 归档 / 恢复:可逆动作,但定制项目归档后整条移出统计,仍按旧版弹一次确认 */ const archiveCustom = (p: CustomProject) => { const toArchive = !p.archived; - modal.confirm({ + modal({ title: toArchive ? "归档定制项目" : "恢复定制项目", okText: toArchive ? "确认归档" : "确认恢复", cancelText: "取消", @@ -761,7 +763,7 @@ export function BoardView() { bump(); }; const removeFocus = (f: FocusItem) => { - modal.confirm({ + modal({ title: "删除重点工作条目", okText: "永久删除", cancelText: "取消", @@ -850,9 +852,9 @@ export function BoardView() { .concat(staff.map((s) => ({ value: s.name, label: s.name + (s.archived ? "(已归档)" : "") })))} /> ) : 全部负责人} - {canReadProjects ? ( - + {canReadBoard ? ( + ) : null}
diff --git a/web/src/views/CustomView.tsx b/web/src/views/CustomView.tsx index 28dd412..8283c3f 100755 --- a/web/src/views/CustomView.tsx +++ b/web/src/views/CustomView.tsx @@ -1,7 +1,7 @@ /* 定制项目(路由 /custom,menu=custom):项目总览 / 本周进展 / 年度任务。 口径、文案、默认值逐项对齐旧版 web/legacy/app.js 的 renderCustom / renderCustomList / renderCustomWeekly / renderCustomAnnual / openCustomDrawer / openNewCustomDialog。 */ -import { Alert, App, Button, Checkbox, DatePicker, Drawer, Input, InputNumber, Modal, Select, Table, Tabs } from "antd"; +import { Alert, App, Button, Checkbox, DatePicker, Input, InputNumber, Select, Table, Tabs } from "antd"; import type { TableColumnsType } from "antd"; import dayjs from "dayjs"; import { useEffect, useMemo, useState } from "react"; @@ -15,6 +15,8 @@ import { EmptyState, ErrorState, Notice, TableSkeleton } from "../components/Dat import { KpiCard } from "../components/KpiCard"; import { PageHead, VIEW_META } from "../components/PageHead"; import { FormDrawer } from "../components/FormDrawer"; +import { OverlayModal } from "../components/OverlayModal"; +import { SidePanel } from "../components/SidePanel"; import { RichEditor } from "../components/RichEditor"; import { RichText } from "../components/RichText"; import { richIsEmpty, richToText } from "../utils/richtext"; @@ -27,6 +29,7 @@ import { INK, isHighRisk, tint } from "../domain/ink"; import { CustomStatusPill, Pill, StagePill, StarMark, StatusPill, TagMini } from "../domain/pills"; import { Icon, PipeIcon } from "../icons/Icon"; import { stageMeta, useMeta } from "../store/meta"; +import { usePanelConfirm } from "../store/usePanelConfirm"; import { useCan } from "../store/session"; import { usePeriodParams, useUi, type CustomTab, type SortState } from "../store/ui"; import type { CustomMeta, CustomProject, EnumItem, Finance, Query, Week } from "../types/domain"; @@ -202,7 +205,7 @@ function UpdateDialog({ cid, update, periodId, customStatus, weeks, statusOpts, }; return ( -
@@ -333,7 +336,7 @@ export function DeleteCustomDialog({ p, onClose, onDeleted }: { p: CustomProject } catch (e) { setBusy(false); setErr("删除失败:" + apiMsg(e)); } }; return ( - 将连同该项目 {p.update_count || 0} 条周期记录一并删除,删除后无法恢复。
    @@ -347,7 +350,7 @@ export function DeleteCustomDialog({ p, onClose, onDeleted }: { p: CustomProject onChange={(e) => setText(e.target.value)} onPressEnter={submit} />
{err ? : null} - + ); } @@ -435,9 +438,9 @@ export function CustomDrawer({ cid, mode, onClose, onArchive, onAskDelete }: { const delUpdate = (u: any) => { modalConfirmDelete(u); }; - const { modal } = App.useApp(); + const modal = usePanelConfirm(); function modalConfirmDelete(u: any) { - modal.confirm({ + modal({ title: "删除这条记录?", okText: "永久删除", cancelText: "取消", @@ -461,22 +464,22 @@ export function CustomDrawer({ cid, mode, onClose, onArchive, onAskDelete }: { const numOrDash = (v: unknown) => (v === null || v === undefined ? "—" : String(Math.round(Number(v)))); const timeline = (data?.timeline || []).slice().reverse(); - const footer = effMode === "edit" ? ( -
+ const actions = effMode === "edit" ? ( + <> -
+ ) : ( -
+ <> {canWrite ? : null} {canWrite ? : null} {canWrite ? : null} {canWrite ? : null} -
+ ); return ( -
@@ -487,7 +490,8 @@ export function CustomDrawer({ cid, mode, onClose, onArchive, onAskDelete }: { {progPct ? 进度 {progPct} : null}
- ) : "定制项目"}> + ) : "定制项目"} + extra={actions ?
{actions}
: undefined}> {loading ? : null} {!loading && error ? : null} {!loading && !error && p && form && effMode === "edit" ? ( @@ -610,7 +614,7 @@ export function CustomDrawer({ cid, mode, onClose, onArchive, onAskDelete }: { setDialog(null)} onDone={() => setDialog(null)} /> ) : null} -
+ ); } diff --git a/web/src/views/FocusView.tsx b/web/src/views/FocusView.tsx index 0014938..b147ae1 100755 --- a/web/src/views/FocusView.tsx +++ b/web/src/views/FocusView.tsx @@ -5,7 +5,7 @@ week = 本周录入的;overdue = 更早周次录入、标了延期又没做完的结转条目。 「已完成」是交叉视图,已完成条目仍留在自己那一周里,避免录完就看不见。 更早周次里没标延期的未完成条目不进当周视图,只能在「全部」里查得到。 */ -import { App, Alert, Button, DatePicker, Drawer, Input, Select, Switch, Table } from "antd"; +import { App, Alert, Button, DatePicker, Input, Select, Switch, Table } from "antd"; import type { TableColumnsType } from "antd"; import dayjs from "dayjs"; import { useEffect, useMemo, useRef, useState } from "react"; @@ -15,6 +15,7 @@ import { EmptyState, ErrorState, TableSkeleton } from "../components/DataState"; import { PageHead, VIEW_META } from "../components/PageHead"; import { KeywordBox } from "../components/KeywordBox"; import { PanelCard, SectionTitle } from "../components/PanelCard"; +import { SidePanel } from "../components/SidePanel"; import { PagerBar } from "../components/PagerBar"; import { useResizableColumns } from "../components/ResizableTable"; import { ReadOnlyRow, Trunc } from "../components/Trunc"; @@ -24,6 +25,7 @@ import { INK, focusDueText, focusIsLate } from "../domain/ink"; import { FocusPill, Pill, StatusPill } from "../domain/pills"; import { Icon } from "../icons/Icon"; import { useMeta } from "../store/meta"; +import { usePanelConfirm } from "../store/usePanelConfirm"; import { useCan } from "../store/session"; import { usePeriodParams, useUi } from "../store/ui"; import type { FocusItem, Query, Week } from "../types/domain"; @@ -217,7 +219,7 @@ export function FocusDrawer({ fid, initialMode, week, onClose, onArchive, onRemo
; return ( -

{titleText}

{inner.mode === "create" @@ -228,14 +230,15 @@ export function FocusDrawer({ fid, initialMode, week, onClose, onArchive, onRemo
} extra={actions || viewActions ?
{actions || viewActions}
: undefined}> {body} -
+ ); } /** 每周工作视图:重点工作清单(本周 / 延期 / 已完成 / 全部)+ 抽屉新增·修改 */ export function FocusView() { const { r, w } = useCan(); - const { message, modal } = App.useApp(); + const { message } = App.useApp(); + const modal = usePanelConfirm(); const keyword = useUi((s) => s.keyword); const focusFilter = useUi((s) => s.focusFilter); const focusArchived = useUi((s) => s.focusArchived); @@ -270,7 +273,7 @@ export function FocusView() { }; /* 条目不是项目,危险确认即可,不要求逐字输入 */ const removeFocus = (f: FocusItem, closeDrawer = false) => { - modal.confirm({ + modal({ title: "删除重点工作条目", okText: "永久删除", cancelText: "取消", diff --git a/web/src/views/ProjectsView.tsx b/web/src/views/ProjectsView.tsx index c2eff3f..380d22d 100755 --- a/web/src/views/ProjectsView.tsx +++ b/web/src/views/ProjectsView.tsx @@ -1,6 +1,6 @@ /* 自研产品(menu=projects):项目台账 + 项目详情抽屉(执行记录 / 历史进度走势)+ 新建 / 修改 / 归档 / 删除。 行为、文案、默认值与 web/legacy/app.js 的 renderProjects + openDrawer + deleteProject + openUpdateDialog 逐项一致。*/ -import { Alert, App, Button, Checkbox, Drawer, Input, InputNumber, Modal, Segmented, Select, Switch, Table, Tooltip } from "antd"; +import { Alert, App, Button, Checkbox, Input, InputNumber, Segmented, Select, Switch, Table, Tooltip } from "antd"; import type { TableProps } from "antd"; import { useEffect, useMemo, useState } from "react"; import { useNavigate } from "react-router-dom"; @@ -9,6 +9,8 @@ import * as api from "../api/endpoints"; import { EmptyState, ErrorState, TableSkeleton } from "../components/DataState"; import { PageHead, VIEW_META } from "../components/PageHead"; import { FormDrawer } from "../components/FormDrawer"; +import { OverlayModal } from "../components/OverlayModal"; +import { SidePanel } from "../components/SidePanel"; import { RichEditor } from "../components/RichEditor"; import { RichText } from "../components/RichText"; import { richIsEmpty } from "../utils/richtext"; @@ -24,6 +26,7 @@ import { statusMeta, useMeta } from "../store/meta"; import { useCan } from "../store/session"; import { type ProjSort, usePeriodParams, useUi } from "../store/ui"; import { useAsync, usePaged } from "../utils/hooks"; +import { usePanelConfirm } from "../store/usePanelConfirm"; import { dash, pct } from "../utils/format"; import type { Category, Project, Query, Staff, UpdateRow, Week } from "../types/domain"; import "./ProjectsView.css"; @@ -242,7 +245,7 @@ function DeleteProjectModal({ project, onClose, onDeleted }: { }; return ( -
将连同 {project?.task_count} 个子任务、{project?.update_count} 条执行记录一并删除,删除后无法恢复。 @@ -253,7 +256,7 @@ function DeleteProjectModal({ project, onClose, onDeleted }: { setText(e.target.value)} onPressEnter={submit} />
- + ); } @@ -307,7 +310,7 @@ function UpdateRecordModal({ projectId, update, defaultStatus, onClose }: { }; return ( -
@@ -391,7 +394,8 @@ export function ProjectDrawer({ pid, mode, canWrite, categories, staff, onMode, pid: number; mode: DrawerMode; canWrite: boolean; categories: Category[]; staff: Staff[]; onMode: (m: DrawerMode) => void; onClose: () => void; }) { - const { message, modal } = App.useApp(); + const { message } = App.useApp(); + const modal = usePanelConfirm(); const nav = useNavigate(); const periodParams = usePeriodParams(); const dataRev = useMeta((s) => s.dataRev); @@ -462,7 +466,7 @@ export function ProjectDrawer({ pid, mode, canWrite, categories, staff, onMode, onMode("view"); }; const remove = () => setDeleting(true); - const askDeleteUpdate = (u: UpdateRow) => modal.confirm({ + const askDeleteUpdate = (u: UpdateRow) => modal({ title: "删除这条记录?", content: ( <> @@ -533,7 +537,7 @@ export function ProjectDrawer({ pid, mode, canWrite, categories, staff, onMode, ); return ( -

{p?.is_key ? : null}{p?.name || "项目详情"}

@@ -546,7 +550,7 @@ export function ProjectDrawer({ pid, mode, canWrite, categories, staff, onMode, ) : null}
} - extra={actions}> + extra={actions ?
{actions}
: undefined}> {loading ? : null} {!loading && error ? : null} {!loading && !error && p ? ( @@ -653,7 +657,7 @@ export function ProjectDrawer({ pid, mode, canWrite, categories, staff, onMode, {deleting && p ? ( setDeleting(false)} onDeleted={() => { setDeleting(false); onClose(); bump(); }} /> ) : null} - + ); }