# -*- coding: utf-8 -*- """月报 / 周报数据采集:Git 提交 + 钉钉 AI 表格需求完成情况。 一条命令采齐写总结所需的客观数据(默认人读摘要,``--json`` 供 agent 组稿):: python -m dingtalk_sdk.report --month 2026-10 python -m dingtalk_sdk.report --week python -m dingtalk_sdk.report --week last --json 也可以当库用:: from dingtalk_sdk import report data = report.collect(month="2026-10", repo=r"d:\\work\\code\\37duAutomation") Git 代码量已排除构建产物(node_modules / dist* / win-unpacked / 锁文件 / LICENSES*.html), 否则行数虚高一个量级。 """ from __future__ import annotations import argparse import json import re import subprocess import sys from collections import Counter from datetime import date, datetime, timedelta from pathlib import Path from typing import Any, Optional from .aitable import AiTable, flatten, resolve_base from .config import get_settings DEFAULT_BASE = "workplan" DEFAULT_SHEET = "hERWDMS" DATE_FIELDS = ("上线日期", "测试日期", "需求对接日期") TYPE_LABEL = { "feat": "新功能", "fix": "缺陷修复", "refactor": "重构", "docs": "文档", "build": "构建/发版", "chore": "杂项", "test": "测试", "style": "格式", "perf": "性能", } # 代码量统计排除项(构建产物 / 依赖 / 锁文件) _EXCLUDE_RE = re.compile( r"(^|/)(node_modules|dist|dist-app\d*|win-unpacked|unpacked|\.venv|__pycache__|\.git)/" r"|(^|/)(pnpm-lock\.yaml|package-lock\.json|yarn\.lock|LICENSES[^/]*\.html)$" ) # ==================== 周期 ==================== def month_range(month: str) -> tuple: """``2026-10`` → ``(首日, 次月首日)``。""" try: first = datetime.strptime(month, "%Y-%m").date() except ValueError: raise ValueError(f"--month 需为 YYYY-MM:{month}") from None nxt = (date(first.year + 1, 1, 1) if first.month == 12 else date(first.year, first.month + 1, 1)) return first.isoformat(), nxt.isoformat() def week_range(ref: date) -> tuple: """含 ``ref`` 的自然周(周一~周日)。""" start = ref - timedelta(days=ref.weekday()) return start, start + timedelta(days=6) def _prev_months(month: str, n: int = 6) -> list: year, mon = int(month[:4]), int(month[5:7]) out = [] for _ in range(n): out.append(f"{year:04d}-{mon:02d}") mon -= 1 if mon == 0: year, mon = year - 1, 12 return list(reversed(out)) def _prev_weeks(ref: date, n: int = 6) -> list: start, _ = week_range(ref) return [(start - timedelta(weeks=i)).isoformat() for i in range(n - 1, -1, -1)] def parse_period(month: str = "", week: Optional[str] = None) -> dict: """统一成区间:``unit=week``(--week)或 ``month``(--month)。""" if week is not None: if week in ("", "current"): ref = date.today() elif week == "last": ref = date.today() - timedelta(days=7) else: try: ref = date.fromisoformat(week) except ValueError: raise ValueError(f"--week 需为 current / last / YYYY-MM-DD:{week}") from None start, end = week_range(ref) return { "unit": "week", "since": start.isoformat(), "until": end.isoformat(), "until_excl": (end + timedelta(days=1)).isoformat(), "label": f"{start.isoformat()} ~ {end.isoformat()}(第 {start.isocalendar()[1]} 周)", "ref": ref.isoformat(), } month = month or datetime.now().strftime("%Y-%m") since, until_excl = month_range(month) end = date.fromisoformat(until_excl) - timedelta(days=1) return { "unit": "month", "since": since, "until": end.isoformat(), "until_excl": until_excl, "label": month, } # ==================== Git ==================== def _git(args: list, repo: Path) -> str: try: proc = subprocess.run(["git", "-c", "core.quotepath=false", *args], cwd=str(repo), capture_output=True, text=True, encoding="utf-8", errors="replace") return proc.stdout if proc.returncode == 0 else "" except (FileNotFoundError, OSError): return "" def collect_git(since: str, until_excl: str, repo: Path) -> dict: """统计区间内的提交数 / 文件数 / 增删行 / 类型分布 / 逐日分布 / 提交标题。""" log = _git(["log", f"--since={since}", f"--until={until_excl}", "--pretty=format:%ad|%s", "--date=short"], repo) lines = [ln for ln in log.splitlines() if ln.strip()] subjects, by_day, by_type = [], Counter(), Counter() for line in lines: day, _, subject = line.partition("|") subjects.append(subject.strip()) by_day[day[5:]] += 1 m = re.match(r"^(\w+)(\([^)]*\))?[!:]", subject.strip()) by_type[m.group(1).lower() if m else "other"] += 1 numstat = _git(["log", f"--since={since}", f"--until={until_excl}", "--numstat", "--pretty=format:"], repo) files, ins, dele, skipped = set(), 0, 0, 0 for line in numstat.splitlines(): parts = line.split("\t") if len(parts) != 3: continue added, deleted, path = parts if path.startswith('"') and path.endswith('"'): path = path[1:-1] if _EXCLUDE_RE.search(path): skipped += 1 continue files.add(path) ins += int(added) if added.isdigit() else 0 dele += int(deleted) if deleted.isdigit() else 0 return { "commits": len(lines), "files_changed": len(files), "insertions": ins, "deletions": dele, "excluded_files": skipped, "by_type": dict(sorted(by_type.items(), key=lambda kv: -kv[1])), "by_day": dict(sorted(by_day.items())), "subjects": subjects, } # ==================== 需求表 ==================== def _in_range(value: Any, since: str, until: str) -> bool: text = str(value or "")[:10] return bool(text) and since <= text <= until def collect_table(period: dict, base: str = DEFAULT_BASE, sheet: str = DEFAULT_SHEET, operator: str = "", aliases: Optional[dict] = None) -> dict: """采集 AI 表格需求池统计(状态/部门/优先级分布、本期上线/提测/在研、上线趋势)。""" client = AiTable(operator=operator) try: base_id, link_sheet = resolve_base(base, aliases) sheet_id = client.resolve_sheet(base_id, sheet or link_sheet) rows = [flatten(r) for r in client.records(base_id, sheet_id)] finally: client.close() since, until = period["since"], period["until"] by_status = Counter(str(r.get("状态") or "(空)") for r in rows) by_dept = Counter(str(r.get("需求部门") or "(空)") for r in rows) by_pri = Counter(str(r.get("优先级") or "(空)") for r in rows) active = [r for r in rows if any(_in_range(r.get(f), since, until) for f in DATE_FIELDS)] released = [r for r in active if str(r.get("状态")) == "上线" and _in_range(r.get("上线日期"), since, until)] testing = [r for r in active if "提测" in str(r.get("状态")) or "验收" in str(r.get("状态"))] developing = [r for r in active if "开发" in str(r.get("状态"))] if period["unit"] == "week": keys = _prev_weeks(date.fromisoformat(until), 6) def keyf(value: Any) -> str: return week_range(date.fromisoformat(str(value)[:10]))[0].isoformat() else: keys = _prev_months(until[:7], 6) def keyf(value: Any) -> str: return str(value)[:7] trend = Counter() for row in rows: if str(row.get("状态")) == "上线" and row.get("上线日期"): trend[keyf(row["上线日期"])] += 1 def brief(items: list) -> list: return [{ "编号": r.get("需求编号", ""), "流程": str(r.get("流程名称", "")).replace("\n", " "), "状态": r.get("状态", ""), "部门": r.get("需求部门", ""), "优先级": r.get("优先级", ""), "难易": r.get("难易程度", ""), "负责人": r.get("开发负责人", ""), "上线": r.get("上线日期", ""), "测试": r.get("测试日期", ""), "对接": r.get("需求对接日期", ""), } for r in sorted(items, key=lambda x: str(x.get("需求编号", "")))] return { "base": base_id, "sheet": sheet_id, "total": len(rows), "by_status": dict(by_status.most_common()), "by_dept": dict(by_dept.most_common()), "by_priority": dict(by_pri.most_common()), "active_count": len(active), "active_by_dept": dict(Counter(str(r.get("需求部门") or "(空)") for r in active).most_common()), "released": brief(released), "testing": brief(testing), "developing": brief(developing), "trend": {k: trend.get(k, 0) for k in keys}, } # ==================== 汇总 ==================== def collect(month: str = "", week: Optional[str] = None, base: str = DEFAULT_BASE, sheet: str = DEFAULT_SHEET, operator: str = "", repo: Optional[str] = None, skip_git: bool = False) -> dict: """采集一份完整报数据(period + git + table)。""" period = parse_period(month, week) repo_dir = Path(repo) if repo else Path.cwd() data: dict = { "period": period, "range": {"since": period["since"], "until": period["until"]}, } data["git"] = {} if skip_git else collect_git(period["since"], period["until_excl"], repo_dir) data["table"] = collect_table(period, base, sheet, operator) return data def print_human(data: dict) -> None: g, t, pd = data["git"], data["table"], data["period"] word = "本月" if pd["unit"] == "month" else "本周" span = "个月" if pd["unit"] == "month" else "周" print(f"===== {pd['label']} 报数据 =====") if g: print(f"Git:{g['commits']} 次提交 / {g['files_changed']} 个文件 / " f"+{g['insertions']} -{g['deletions']}") print(" 提交类型:" + "、".join(f"{TYPE_LABEL.get(k, k)} {v}" for k, v in g["by_type"].items())) if g.get("subjects"): print(" 提交明细:") for subject in g["subjects"]: print(f" - {subject}") print(f"\n需求池:{t['total']} 单") print(" 状态:" + "、".join(f"{k} {v}" for k, v in t["by_status"].items())) print(" 部门:" + "、".join(f"{k} {v}" for k, v in t["by_dept"].items())) print(f"\n{word}活动 {t['active_count']} 条(" + "、".join(f"{k} {v}" for k, v in t["active_by_dept"].items()) + ")") print(f" 上线 {len(t['released'])} 个:") for row in t["released"]: print(f" {row['编号']} {row['流程']}" f"({row['部门']}/{row['优先级'] or '-'},上线 {row['上线']})") if t["testing"]: print(f" 提测/验收 {len(t['testing'])} 个:" + "、".join(f"{r['编号']} {r['流程']}" for r in t["testing"])) if t["developing"]: print(f" 开发中 {len(t['developing'])} 个:" + "、".join(f"{r['编号']} {r['流程']}({r['优先级'] or '-'})" for r in t["developing"])) print(f"\n近 6 {span}上线数:" + "、".join(f"{k} {v}" for k, v in t["trend"].items())) def main(argv: Optional[list] = None) -> int: try: sys.stdout.reconfigure(encoding="utf-8") except Exception: # noqa: BLE001 pass parser = argparse.ArgumentParser(prog="dingtalk-sdk-report", description="月报/周报数据采集(Git + 钉钉 AI 表格)") parser.add_argument("--month", default=datetime.now().strftime("%Y-%m"), help="YYYY-MM,默认当月") parser.add_argument("--week", nargs="?", const="current", default=None, help="统计本周(周一~周日):不带值=本周,last=上周,或给 YYYY-MM-DD") parser.add_argument("--base", default=DEFAULT_BASE, help="表格别名/baseId/链接") parser.add_argument("--sheet", default=DEFAULT_SHEET, help="sheet id 或名称") parser.add_argument("--operator", default="", help="操作人 unionId") parser.add_argument("--repo", default="", help="git 仓库根(默认当前目录)") parser.add_argument("--skip-git", action="store_true", help="只采表格数据") parser.add_argument("--json", action="store_true", help="输出完整 JSON") parser.add_argument("--out", default="", help="把 JSON 落盘到指定路径") args = parser.parse_args(argv) data = collect(month=args.month, week=args.week, base=args.base, sheet=args.sheet, operator=args.operator or get_settings().operator, repo=args.repo or "", skip_git=args.skip_git) if args.out: out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") print(f"[+] 已落盘 → {out}") if args.json: print(json.dumps(data, ensure_ascii=False, indent=1)) else: print_human(data) return 0 if __name__ == "__main__": raise SystemExit(main())