Files
37duAutomation/libs/aitable/aitable/report.py
T

302 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""月报 / 周报数据采集:Git 提交 + 钉钉 AI 表格需求完成情况。
一条命令采齐写总结所需的客观数据(默认人读摘要,--json 供 agent 组稿):
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\report.py --month 2026-10
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\report.py --week
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\report.py --week last --json
Git 代码量已排除构建产物(node_modules / dist* / win-unpacked / 锁文件 / LICENSES*.html),
否则行数虚高一个量级。配套流程见 .trae/skills/37du-Monthly-Review/SKILL.md。
"""
from __future__ import annotations
import argparse
import json
import os
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
try: # 作为包导入
from .client import AiTable, DEFAULT_OPERATOR, flatten, resolve_base
except ImportError: # 直接执行文件
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from aitable.client import AiTable, DEFAULT_OPERATOR, flatten, resolve_base # noqa: F401
REPO_DIR = Path(__file__).resolve().parents[3] # libs/aitable/aitable/report.py → 仓库根
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 SystemExit(f"[x] --month 需为 YYYY-MM:{month}")
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:
start = ref - timedelta(days=ref.weekday())
return start, start + timedelta(days=6)
def _prev_months(month: str, n: int = 6) -> list:
y, m = int(month[:4]), int(month[5:7])
out = []
for _ in range(n):
out.append(f"{y:04d}-{m:02d}")
m -= 1
if m == 0:
y, m = y - 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]) -> dict:
"""统一成区间:unit=week(--week)或 month(--month);until 为闭区间末日。"""
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 SystemExit(f"[x] --week 需为 current / last / YYYY-MM-DD:{week}")
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(),
}
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:
r = subprocess.run(["git", "-c", "core.quotepath=false", *args], cwd=str(repo),
capture_output=True, text=True, encoding="utf-8", errors="replace")
return r.stdout if r.returncode == 0 else ""
except FileNotFoundError:
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 ln in lines:
day, _, subj = ln.partition("|")
subjects.append(subj.strip())
by_day[day[5:]] += 1
m = re.match(r"^(\w+)(\([^)]*\))?[!:]", subj.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 ln in numstat.splitlines():
parts = ln.split("\t")
if len(parts) != 3:
continue
a, d, 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(a) if a.isdigit() else 0
dele += int(d) if d.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(v: Any, since: str, until: str) -> bool:
s = str(v or "")[:10]
return bool(s) and since <= s <= until
def collect_table(period: dict, base: str, sheet: str, operator: str) -> dict:
cli = AiTable(operator)
base_id, link_sheet = resolve_base(base)
sheet_id = cli.resolve_sheet(base_id, sheet or link_sheet)
rows = [flatten(r) for r in cli.records(base_id, sheet_id)]
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(d: Any) -> str:
return week_range(date.fromisoformat(str(d)[:10]))[0].isoformat()
else:
keys = _prev_months(until[:7], 6)
def keyf(d: Any) -> str:
return str(d)[:7]
trend = Counter()
for r in rows:
if str(r.get("状态")) == "上线" and r.get("上线日期"):
trend[keyf(r["上线日期"])] += 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 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']} 报数据 =====")
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 s in g["subjects"]:
print(f" - {s}")
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 r in t["released"]:
print(f" {r['编号']} {r['流程']}({r['部门']}/{r['优先级'] or '-'},上线 {r['上线']})")
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: list = None) -> None:
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
p = argparse.ArgumentParser(prog="aitable-report",
description="月报/周报数据采集(Git + 钉钉 AI 表格)")
p.add_argument("--month", default=datetime.now().strftime("%Y-%m"), help="YYYY-MM,默认当月")
p.add_argument("--week", nargs="?", const="current", default=None,
help="统计本周(周一~周日):不带值=本周,last=上周,或给 YYYY-MM-DD 指定周")
p.add_argument("--base", default=DEFAULT_BASE, help="表格别名/baseId/链接")
p.add_argument("--sheet", default=DEFAULT_SHEET, help="sheet id 或名称")
p.add_argument("--operator", default=os.getenv("AITABLE_OPERATOR_UNIONID", "").strip()
or DEFAULT_OPERATOR, help="操作人 unionId")
p.add_argument("--repo", default=str(REPO_DIR), help="git 仓库根")
p.add_argument("--skip-git", action="store_true", help="只采表格数据")
p.add_argument("--json", action="store_true", help="输出完整 JSON")
p.add_argument("--out", default="", help="把 JSON 落盘到指定路径")
args = p.parse_args(argv)
period = parse_period(args.month, args.week)
data: dict = {"period": period,
"range": {"since": period["since"], "until": period["until"]}}
data["git"] = {} if args.skip_git else collect_git(period["since"], period["until_excl"],
Path(args.repo))
data["table"] = collect_table(period, args.base, args.sheet, args.operator)
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)
if __name__ == "__main__":
main()