docs: 更新 AGENTS/README 平台架构说明与月度总结,运行日志视图支持已取消状态

This commit is contained in:
2026-10-31 17:55:25 +08:00
parent 62de24eb4d
commit 85051f979b
201 changed files with 11049 additions and 7398 deletions
+70
View File
@@ -0,0 +1,70 @@
# aitable · 钉钉 AI 表格读写库
读写钉钉 AI 表格(notable OpenAPI)的独立 Python 库,附带月报 / 周报数据采集器。
与业务方向解耦:任何插件、脚本、agent 都可以直接引用,也可以单独 `pip install -e`。
## 安装 / 引用
```powershell
# 方式一:可编辑安装(推荐)
.venv\Scripts\python.exe -m pip install -e libs\aitable
# 方式二:直接跑文件,不需要安装
.venv\Scripts\python.exe libs\aitable\aitable\cli.py sheets workplan
```
## 凭证
按顺序读取(**不读已废弃的 `desktop/controlplane/.env`**):
1. 环境变量 `AITABLE_ENV_FILE` 指向的 .env
2. `desktop/controlplane-next/server/.env`(新中心机配置)
3. 仓库根 `.env`(兜底)
用到的键:`DINGTALK_APP_KEY`、`DINGTALK_APP_SECRET`、`AITABLE_OPERATOR_UNIONID`(可选)。
⚠️ notable 接口必须带 `operatorId`(操作人 unionId),且**该操作人必须是目标表格的协作者**;
个人空间文档默认不对应用开放,会返回 `forbidden.operationIllegal / permission deny`。
## 命令行
```powershell
cd d:\work\code\37duAutomation
$py = ".venv\Scripts\python.exe"
$cli = "libs\aitable\aitable\cli.py"
& $py $cli sheets workplan # 列出 sheet
& $py $cli fields workplan --sheet hERWDMS # 字段/类型/选项
& $py $cli list workplan --sheet hERWDMS --month 上线日期=2026-10 --json
& $py $cli summary workplan --sheet hERWDMS --by 状态
& $py $cli update workplan --sheet hERWDMS --record <id> --data '{\"状态\":\"上线\"}' --dry-run
```
base 支持三种写法:别名(`workplan` / `hr`)、baseId、`https://alidocs.dingtalk.com/i/nodes/<baseId>?sheetId=xxx`。
新增常用表在 `aitable/client.py` 的 `BASE_ALIASES` 里登记。
## 月报 / 周报数据采集
```powershell
& $py libs\aitable\aitable\report.py --month 2026-10 # 月报数据
& $py libs\aitable\aitable\report.py --week # 本周
& $py libs\aitable\aitable\report.py --week last --json # 上周,供 agent 组稿
```
输出 Git(提交数/代码量/类型分布/提交明细)+ 需求表(状态分布、本期上线/提测/在研、上线趋势)。
代码量默认排除构建产物与锁文件。写作流程见 `.trae/skills/37du-Monthly-Review/SKILL.md`。
## 自测
```powershell
.venv\Scripts\python.exe libs\aitable\_selftest.py # 离线:值归一/日期/区间/过滤
.venv\Scripts\python.exe libs\aitable\_selftest.py --online # 追加在线冒烟(需凭证与授权)
```
## 坑位
1. 记录列表接口必须是 **POST** `/records/list`(GET 返回 `resource.notFound 'list'`)。
2. 分页靠 `hasMore` + `nextToken`,单页上限 100,只取首页会漏数据。
3. 日期是**毫秒时间戳 + 北京时间**(UTC 16:00 = 次日 00:00),自行换算易整体差一天。
4. 写入:`singleSelect` 传选项名、`multipleSelect` 传数组、`date` 传毫秒、`user` 传 unionId 数组、`autoNumber` 只读。
5. 部分 Windows 机器 `api.dingtalk.com` 的 A 记录解析失败(11001),库内置 DoH 兜底,可用 `AITABLE_DNS_IP` 覆盖。
+141
View File
@@ -0,0 +1,141 @@
# -*- coding: utf-8 -*-
"""自测:默认全离线(不联网、不读写表格),--online 追加一条在线冒烟。
运行:
.venv\\Scripts\\python.exe libs\\aitable\\_selftest.py
.venv\\Scripts\\python.exe libs\\aitable\\_selftest.py --online
"""
from __future__ import annotations
import os
import sys
from datetime import date, datetime, timedelta, timezone
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from aitable import cli, report # noqa: E402
from aitable.client import (BASE_ALIASES, coerce_for_fields, flatten, # noqa: E402
norm, resolve_base, to_ms)
_passed = 0
TZ_CN = timezone(timedelta(hours=8))
def ok(cond: bool, msg: str) -> None:
global _passed
if not cond:
raise AssertionError(f"[FAIL] {msg}")
_passed += 1
print(f"[PASS] {msg}")
def test_norm() -> None:
ms = int(datetime(2026, 10, 31, tzinfo=TZ_CN).timestamp() * 1000)
ok(norm({"name": "上线", "id": "x"}) == "上线", "单选取 name")
ok(norm([{"name": "EHR"}, {"name": "钉钉"}]) == "EHR、钉钉", "多选顿号连接")
ok(norm(ms) == "2026-10-31", "毫秒时间戳按北京时间转日期")
ok(norm(28) == 28, "小数值不被误判为日期")
ok(norm("") == "", "空值原样返回")
def test_ms() -> None:
ms = to_ms("2026-10-31")
expect = int(datetime(2026, 10, 31, tzinfo=TZ_CN).timestamp() * 1000)
ok(ms == expect, "日期字符串 → 北京时间 00:00 毫秒")
ok(to_ms("2026/10/31") == expect, "斜杠日期兼容")
ok(to_ms(expect) == expect, "已是毫秒则原样返回")
try:
to_ms("10月31日")
ok(False, "非法日期应报错")
except SystemExit:
ok(True, "非法日期报错")
def test_coerce() -> None:
meta = {"value": [
{"name": "状态", "type": "singleSelect",
"property": {"choices": [{"name": "上线"}, {"name": "开发中"}]}},
{"name": "涉及系统", "type": "multipleSelect", "property": {"choices": []}},
{"name": "上线日期", "type": "date", "property": {}},
]}
out = coerce_for_fields(meta, {"状态": "上线", "涉及系统": "EHR,钉钉", "上线日期": "2026-10-31"})
ok(out["状态"] == "上线", "单选写入选项名")
ok(out["涉及系统"] == ["EHR", "钉钉"], "多选字符串拆数组")
ok(isinstance(out["上线日期"], int), "日期转毫秒")
for bad, desc in (({"状态": "不存在的状态"}, "非法单选值"), ({"不存在字段": 1}, "未知字段")):
try:
coerce_for_fields(meta, bad)
ok(False, f"{desc} 应报错")
except SystemExit:
ok(True, f"{desc} 报错")
def test_flatten() -> None:
rec = {"id": "abc", "fields": {"状态": {"name": "上线"}, "需求编号": "XQ0001"}}
row = flatten(rec)
ok(row["_id"] == "abc" and row["状态"] == "上线", "记录拍平 + 归一")
def test_resolve_base() -> None:
ok(resolve_base("workplan")[0] == BASE_ALIASES["workplan"], "别名解析")
link = ("https://alidocs.dingtalk.com/i/nodes/20eMKjyp81RON33AUrE4awEEWxAZB1Gv"
"?iframeQuery=sheetId%3DhERWDMS")
base, _ = resolve_base(link)
ok(base == "20eMKjyp81RON33AUrE4awEEWxAZB1Gv", "文档链接解析 baseId")
try:
resolve_base("unknown")
ok(False, "未知短标识应报错")
except SystemExit:
ok(True, "未知短标识报错")
def test_period() -> None:
m = report.parse_period("2026-10", None)
ok(m["since"] == "2026-10-01" and m["until"] == "2026-10-31", "月份区间")
ok(m["until_excl"] == "2026-11-01" and m["unit"] == "month", "次月首日/单位")
w = report.parse_period("2026-10", "2026-10-31")
ok(w["since"] == "2026-10-26" and w["until"] == "2026-11-01", "周区间(周一~周日,跨月)")
ok(w["unit"] == "week" and "第" in w["label"], "周标签")
last = report.parse_period("2026-10", "last")
ok(last["unit"] == "week", "上周模式")
def test_filters() -> None:
rows = [{"_id": "1", "状态": "上线", "上线日期": "2026-10-28"},
{"_id": "2", "状态": "开发中", "上线日期": ""},
{"_id": "3", "状态": "上线", "上线日期": "2026-09-30"}]
got = cli.apply_filters(rows, ["状态=上线"], ["上线日期=2026-10"])
ok(len(got) == 1 and got[0]["_id"] == "1", "--where + --month 组合过滤")
ok(len(cli.apply_filters(rows, [], ["上线日期=2026-10"])) == 1, "仅月份过滤")
def test_online() -> None:
from aitable import AiTable
cli_ = AiTable()
sheets = cli_.sheets(BASE_ALIASES["workplan"])
ok(any(s.get("id") == "hERWDMS" for s in sheets), "在线冒烟:能列出 workplan 的 sheet")
rows = cli_.records(BASE_ALIASES["workplan"], "hERWDMS")
ok(len(rows) > 0, f"在线冒烟:能读取记录({len(rows)} 条)")
print(f"[INFO] 近 6 周趋势(上线):{report.collect_table(report.parse_period('', 'current'), 'workplan', 'hERWDMS', '')['trend']}")
def main() -> int:
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
test_norm()
test_ms()
test_coerce()
test_flatten()
test_resolve_base()
test_period()
test_filters()
if "--online" in sys.argv:
test_online()
print(f"\n全部通过:{_passed} 项")
return 0
if __name__ == "__main__":
sys.exit(main())
+20
View File
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
"""aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。
对外只暴露三样:
- AiTable 表格客户端(列 sheet/字段、分页读、批量增改)
- cli / report 两个命令行入口(python -m aitable / python -m aitable.report)
- 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用)
"""
from __future__ import annotations
from .client import ( # noqa: F401
BASE_ALIASES, DEFAULT_OPERATOR, AiTable, coerce_for_fields, flatten,
install_dns_fallback, ms_to_str, norm, resolve_base, to_ms,
)
__version__ = "1.0.0"
__all__ = [
"AiTable", "BASE_ALIASES", "DEFAULT_OPERATOR", "coerce_for_fields", "flatten",
"install_dns_fallback", "ms_to_str", "norm", "resolve_base", "to_ms",
]
+6
View File
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
"""python -m aitable → 表格命令行(等价于 cli.py)。"""
from .cli import main
if __name__ == "__main__":
main()
+295
View File
@@ -0,0 +1,295 @@
# -*- coding: utf-8 -*-
"""钉钉 AI 表格命令行(agent 用):列 sheet/字段、拉记录、过滤、统计、增改、导出。
运行(仓库根):
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\cli.py sheets workplan
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\cli.py list workplan --sheet hERWDMS --month 上线日期=2026-10
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\cli.py summary workplan --sheet hERWDMS --by 状态
也支持 `python -m aitable`(需 PYTHONPATH 指向 libs/aitable 或 pip install -e)。
base 支持别名(workplan / hr)、baseId、alidocs 文档链接;凭证见 client.py。
"""
from __future__ import annotations
import argparse
import csv
import json
import sys
import unicodedata
from pathlib import Path
from typing import Any
try: # 作为包导入
from .client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, flatten,
resolve_base)
except ImportError: # 直接执行文件
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from aitable.client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, # noqa: F401
flatten, resolve_base)
# ==================== 过滤 / 输出 ====================
def apply_filters(rows: list, wheres: list, months: list) -> list:
"""--where 字段=值(精确,AND);--month 字段=YYYY-MM(任一命中,OR)。"""
for w in wheres or []:
if "=" not in w:
raise SystemExit(f"[x] --where 需为 字段=值:{w}")
k, v = w.split("=", 1)
rows = [r for r in rows if str(r.get(k.strip(), "")).strip() == v.strip()]
if months:
pairs = []
for m in months:
if "=" not in m:
raise SystemExit(f"[x] --month 需为 字段=YYYY-MM:{m}")
k, v = m.split("=", 1)
pairs.append((k.strip(), v.strip()))
rows = [r for r in rows
if any(str(r.get(k, "")).startswith(v) for k, v in pairs)]
return rows
def _disp_width(s: str) -> int:
return sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in s)
def _pad(s: str, width: int) -> str:
return s + " " * max(0, width - _disp_width(s))
def print_table(rows: list, columns: list) -> None:
if not rows:
print("(无记录)")
return
def _cell(v: Any) -> str:
return str(v if v is not None else "").replace("\r", " ").replace("\n", " ").strip()
cells = [[_cell(r.get(c)) for c in columns] for r in rows]
widths = [max(_disp_width(c), *(_disp_width(row[i]) for row in cells)) for i, c in enumerate(columns)]
print(" ".join(_pad(c, w) for c, w in zip(columns, widths)))
print(" ".join("-" * w for w in widths))
for row in cells:
print(" ".join(_pad(v, w) for v, w in zip(row, widths)))
def emit_json(obj: Any) -> None:
print(json.dumps(obj, ensure_ascii=False, indent=1))
def write_out(path: str, rows: list, columns: list) -> None:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
if p.suffix.lower() == ".json":
p.write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
else:
with p.open("w", encoding="utf-8-sig", newline="") as f: # utf-8-sig:Excel 打开不乱码
w = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
w.writeheader()
w.writerows([{k: r.get(k, "") for k in columns} for r in rows])
print(f"[+] 已导出 {len(rows)} 条 → {p}")
def pick_columns(rows: list, spec: str) -> list:
if spec:
return [c.strip() for c in spec.split(",") if c.strip()]
cols = []
for r in rows:
for k in r:
if k not in cols:
cols.append(k)
cols.sort(key=lambda c: c != "_id")
return cols
def _sheet_arg(args: argparse.Namespace, cli: AiTable, base: str, link_sheet: str) -> str:
raw = getattr(args, "sheet", "") or link_sheet
if not raw:
raise SystemExit("[x] 缺少 --sheet(可先跑 sheets 子命令查看 id/名称)")
return cli.resolve_sheet(base, raw)
# ==================== 子命令 ====================
def _cmd_sheets(args, cli) -> int:
base, _ = resolve_base(args.base)
items = cli.sheets(base)
if args.json:
emit_json({"base": base, "sheets": items})
else:
print(f"base {base} 共 {len(items)} 张 sheet:")
print_table([{"名称": s.get("name"), "id": s.get("id")} for s in items], ["名称", "id"])
return 0
def _cmd_fields(args, cli) -> int:
base, link_sheet = resolve_base(args.base)
sheet = _sheet_arg(args, cli, base, link_sheet)
meta = cli.fields(base, sheet)
if args.json:
emit_json({"base": base, "sheet": sheet, "fields": meta.get("value", [])})
return 0
rows = []
for f in meta.get("value", []):
choices = [c.get("name") for c in (f.get("property") or {}).get("choices") or []]
rows.append({"字段": f.get("name"), "类型": f.get("type"),
"选项": "/".join(map(str, choices))[:60]})
print(f"sheet {sheet} 共 {len(rows)} 个字段:")
print_table(rows, ["字段", "类型", "选项"])
return 0
def _cmd_list(args, cli) -> int:
base, link_sheet = resolve_base(args.base)
sheet = _sheet_arg(args, cli, base, link_sheet)
rows = [flatten(r) for r in cli.records(base, sheet)]
rows = apply_filters(rows, args.where, args.month)
if args.limit:
rows = rows[: args.limit]
cols = pick_columns(rows, args.columns)
if args.out:
write_out(args.out, rows, cols)
if args.json:
emit_json({"base": base, "sheet": sheet, "count": len(rows), "records": rows})
else:
print(f"共 {len(rows)} 条:")
print_table(rows, cols)
return 0
def _cmd_summary(args, cli) -> int:
base, link_sheet = resolve_base(args.base)
sheet = _sheet_arg(args, cli, base, link_sheet)
rows = apply_filters([flatten(r) for r in cli.records(base, sheet)], args.where, args.month)
bys = [b.strip() for b in args.by.split(",") if b.strip()]
result: dict = {}
for b in bys:
counter: dict = {}
for r in rows:
key = str(r.get(b) if r.get(b) not in (None, "") else "(空)")
counter[key] = counter.get(key, 0) + 1
result[b] = dict(sorted(counter.items(), key=lambda kv: -kv[1]))
if args.json:
emit_json({"base": base, "sheet": sheet, "total": len(rows), "summary": result})
return 0
print(f"共 {len(rows)} 条记录:")
for b, counter in result.items():
print(f"\n[{b}]")
print_table([{b: k, "数量": v} for k, v in counter.items()], [b, "数量"])
return 0
def _load_data(raw: str, file_path: str) -> dict:
if raw and file_path:
raise SystemExit("[x] --data 与 --data-file 只能二选一")
text = Path(file_path).read_text(encoding="utf-8") if file_path else (raw or "")
if not text.strip():
raise SystemExit("[x] 缺少 --data '{...}' 或 --data-file <json>")
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
raise SystemExit(f"[x] 数据不是合法 JSON:{exc}")
if not isinstance(data, dict):
raise SystemExit("[x] 数据必须是 JSON 对象(字段名 → 值)")
return data
def _cmd_add(args, cli) -> int:
base, link_sheet = resolve_base(args.base)
sheet = _sheet_arg(args, cli, base, link_sheet)
payload = coerce_for_fields(cli.fields(base, sheet), _load_data(args.data, args.data_file))
if args.dry_run:
print("[~] 试算,未写入:")
emit_json(payload)
return 0
n = cli.add(base, sheet, [payload])
print(f"[+] 新增 {n} 条 → sheet {sheet}")
return 0
def _cmd_update(args, cli) -> int:
base, link_sheet = resolve_base(args.base)
sheet = _sheet_arg(args, cli, base, link_sheet)
if not args.record:
raise SystemExit("[x] 缺少 --record(记录 id,可用 list --json 查看 _id)")
payload = coerce_for_fields(cli.fields(base, sheet), _load_data(args.data, args.data_file))
if args.dry_run:
print("[~] 试算,未写入:")
emit_json({"id": args.record, "fields": payload})
return 0
n = cli.update(base, sheet, [{"id": args.record, "fields": payload}])
print(f"[+] 更新 {n} 条 → sheet {sheet} / record {args.record}")
return 0
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="aitable",
description="钉钉 AI 表格读写 CLI(notable);base 支持别名 / baseId / alidocs 链接")
sub = p.add_subparsers(dest="cmd", required=True)
common = argparse.ArgumentParser(add_help=False)
common.add_argument("--operator", default=DEFAULT_OPERATOR,
help="操作人 unionId(须是目标表格协作者;默认人资专用号)")
common.add_argument("--json", action="store_true", help="以 JSON 输出(agent 解析用)")
s = sub.add_parser("sheets", help="列出 base 下全部 sheet", parents=[common])
s.add_argument("base", help="别名 / baseId / 文档链接")
s.set_defaults(func=_cmd_sheets)
s = sub.add_parser("fields", help="查看 sheet 字段名/类型/单选选项", parents=[common])
s.add_argument("base")
s.add_argument("--sheet", default="", help="sheet id 或名称")
s.set_defaults(func=_cmd_fields)
s = sub.add_parser("list", help="拉取记录(可过滤/导出)", parents=[common])
s.add_argument("base")
s.add_argument("--sheet", default="")
s.add_argument("--where", action="append", default=[], metavar="字段=值",
help="等值过滤,可重复(AND)")
s.add_argument("--month", action="append", default=[], metavar="日期字段=YYYY-MM",
help="按月份过滤(北京时间),可重复(OR)")
s.add_argument("--columns", default="", help="输出列,逗号分隔")
s.add_argument("--limit", type=int, default=0, help="最多输出条数")
s.add_argument("--out", default="", help="导出 .csv / .json")
s.set_defaults(func=_cmd_list)
s = sub.add_parser("summary", help="分组统计(状态分布 / 月度完成情况)", parents=[common])
s.add_argument("base")
s.add_argument("--sheet", default="")
s.add_argument("--by", required=True, help="分组字段,逗号分隔,如 状态,需求部门")
s.add_argument("--where", action="append", default=[], metavar="字段=值")
s.add_argument("--month", action="append", default=[], metavar="日期字段=YYYY-MM")
s.set_defaults(func=_cmd_summary)
s = sub.add_parser("add", help="新增记录", parents=[common])
s.add_argument("base")
s.add_argument("--sheet", default="")
s.add_argument("--data", default="", help='JSON 对象,如 \'{"需求编号":"XQ0100"}\'')
s.add_argument("--data-file", default="", help="从 JSON 文件读取字段")
s.add_argument("--dry-run", action="store_true", help="只打印转换后的字段,不写入")
s.set_defaults(func=_cmd_add)
s = sub.add_parser("update", help="更新记录", parents=[common])
s.add_argument("base")
s.add_argument("--sheet", default="")
s.add_argument("--record", default="", help="记录 id")
s.add_argument("--data", default="")
s.add_argument("--data-file", default="")
s.add_argument("--dry-run", action="store_true")
s.set_defaults(func=_cmd_update)
return p
def main(argv: list = None) -> None:
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
args = build_parser().parse_args(argv)
cli = AiTable(args.operator)
sys.exit(args.func(args, cli))
if __name__ == "__main__":
main()
+311
View File
@@ -0,0 +1,311 @@
# -*- coding: utf-8 -*-
"""钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值。
凭证读取顺序(**不读已废弃的 desktop/controlplane/.env**):
1. 环境变量 AITABLE_ENV_FILE 指定的 .env
2. 新中心机配置 desktop/controlplane-next/server/.env
3. 仓库根 .env(兜底)
键名:DINGTALK_APP_KEY / DINGTALK_APP_SECRET / AITABLE_OPERATOR_UNIONID(可选)。
"""
from __future__ import annotations
import json
import os
import socket
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Optional
import requests
API_HOST = "api.dingtalk.com"
API_BASE = f"https://{API_HOST}/v1.0"
TZ_CN = timezone(timedelta(hours=8)) # 表格日期按北京时间落库(毫秒时间戳)
REPO_ROOT = Path(__file__).resolve().parents[3] # libs/aitable/aitable/client.py → 仓库根
# base 别名(团队常用表格,避免每次粘长 id;新增表格在此登记)
BASE_ALIASES = {
"workplan": "20eMKjyp81RON33AUrE4awEEWxAZB1Gv", # 需求/插件完成情况(个人空间,sheet hERWDMS)
"hr": "YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA", # 人资 base(XQ0034/35/37 在用的团队空间表)
}
DEFAULT_OPERATOR = "o3mB4s7fjPUtELmYbl5Q3AiEiE" # 人资专用号,须为目标表格协作者
MAX_ATTEMPTS = 3
RETRY_DELAY_BASE = 1.5
PAGE_SIZE = 100 # records/list 单页上限
WRITE_BATCH = 20
_TS_FLOOR = 1_000_000_000_000 # 毫秒时间戳判定下限
# 凭证候选 .env(按优先级;故不包含已废弃的 desktop/controlplane)
ENV_CANDIDATES = (
os.getenv("AITABLE_ENV_FILE", ""),
str(REPO_ROOT / "desktop" / "controlplane-next" / "server" / ".env"),
str(REPO_ROOT / ".env"),
)
def _load_dotenv() -> None:
"""按候选顺序读 .env,环境变量优先(不覆盖已存在值)。"""
for cand in ENV_CANDIDATES:
if not cand:
continue
p = Path(cand)
if not p.is_file():
continue
for ln in p.read_text(encoding="utf-8", errors="replace").splitlines():
line = ln.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k, v = k.strip(), v.strip().strip('"').strip("'")
if k and k not in os.environ:
os.environ[k] = v
_load_dotenv()
APP_KEY = os.getenv("DINGTALK_APP_KEY", "").strip()
APP_SECRET = os.getenv("DINGTALK_APP_SECRET", "").strip()
DEFAULT_OPERATOR = os.getenv("AITABLE_OPERATOR_UNIONID", "").strip() or DEFAULT_OPERATOR
# ==================== 网络:DNS 兜底 ====================
def _doh_resolve(host: str) -> str:
"""系统 DNS 解析失败时用 DoH 兜底取 A 记录。
现场问题:部分 Windows 机器 api.dingtalk.com 的 CNAME 链能查到、A 记录取不到,
socket.getaddrinfo 直接 11001 失败,而 IP 直连是通的。
"""
for url in ("https://223.5.5.5/resolve", "https://119.29.29.29/resolve"):
try:
r = requests.get(url, params={"name": host, "type": "A"},
headers={"accept": "application/dns-json"},
timeout=8, verify=False)
for ans in r.json().get("Answer", []):
if ans.get("type") == 1 and ans.get("data"):
return str(ans["data"])
except Exception:
continue
return ""
def install_dns_fallback(host: str = API_HOST) -> None:
try:
requests.packages.urllib3.disable_warnings() # DoH 走 IP 直连,证书域名不匹配
except Exception:
pass
try:
socket.getaddrinfo(host, 443)
return # 系统解析正常
except socket.gaierror:
pass
ip = os.getenv("AITABLE_DNS_IP", "").strip() or _doh_resolve(host)
if not ip:
return
_orig = socket.getaddrinfo
def _gai(h, port, *args, **kwargs):
return _orig(ip if h == host else h, port, *args, **kwargs)
socket.getaddrinfo = _gai
# ==================== 值归一 / 类型转换 ====================
def ms_to_str(ms: Any, with_time: bool = False) -> str:
try:
dt = datetime.fromtimestamp(int(ms) / 1000, TZ_CN)
except (ValueError, OSError, OverflowError):
return str(ms)
return dt.strftime("%Y-%m-%d %H:%M" if with_time else "%Y-%m-%d")
def norm(v: Any) -> Any:
"""记录字段值 → 可读值:单选/成员取 name,日期毫秒转北京时间,多选顿号连接。"""
if isinstance(v, dict):
if v.get("name"):
return v["name"]
if v.get("unionId"):
return v.get("name") or v["unionId"]
return json.dumps(v, ensure_ascii=False)
if isinstance(v, list):
return "、".join(str(norm(x)) for x in v)
if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= _TS_FLOOR:
return ms_to_str(v)
return v
def to_ms(value: Any) -> Optional[int]:
"""'YYYY-MM-DD' / 'YYYY-MM-DD HH:MM[:SS]' / 毫秒数字 → 毫秒时间戳(北京时间)。"""
if value is None or value == "":
return None
if isinstance(value, (int, float)) and not isinstance(value, bool):
return int(value)
s = str(value).strip().replace("/", "-")
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return int(datetime.strptime(s, fmt).replace(tzinfo=TZ_CN).timestamp() * 1000)
except ValueError:
continue
raise SystemExit(f"[x] 无法解析日期:{value}(支持 YYYY-MM-DD / YYYY-MM-DD HH:MM)")
def coerce_for_fields(meta: dict, data: dict) -> dict:
"""按字段类型转换写入值;字段不存在或单选值非法直接报错。"""
by_name = {f.get("name"): f for f in meta.get("value", [])}
out = {}
for k, v in data.items():
f = by_name.get(k)
if not f:
raise SystemExit(f"[x] 字段不存在:{k}(可用字段:{', '.join(str(x) for x in by_name)})")
ftype = (f.get("type") or "").lower()
if ftype == "date" and not isinstance(v, (int, float)):
out[k] = to_ms(v)
elif ftype == "singleselect":
names = [c.get("name") for c in (f.get("property") or {}).get("choices") or []]
if names and v not in names:
raise SystemExit(f"[x] 「{k}」不是合法选项,可选:{', '.join(map(str, names))}")
out[k] = v
elif ftype.startswith("multi") and isinstance(v, str):
out[k] = [x.strip() for x in v.replace(",", ",").split(",") if x.strip()]
else:
out[k] = v
return out
def flatten(rec: dict) -> dict:
row = {"_id": rec.get("id", "")}
for k, v in (rec.get("fields") or {}).items():
row[k] = norm(v)
return row
# ==================== 客户端 ====================
class AiTable:
"""钉钉 AI 表格 notable OpenAPI 客户端(token 复用 + 3 次重试 + DNS 兜底)。"""
def __init__(self, operator: str = "") -> None:
if not APP_KEY or not APP_SECRET:
raise SystemExit("[x] 缺少 DINGTALK_APP_KEY / DINGTALK_APP_SECRET"
"(配置见 desktop/controlplane-next/server/.env,"
"或设置同名环境变量 / AITABLE_ENV_FILE)")
self.operator = operator or DEFAULT_OPERATOR
self._token, self._exp = "", 0.0
install_dns_fallback()
# ---- 底层 ----
def _access_token(self) -> str:
if self._token and self._exp > time.time() + 60:
return self._token
d = self._raw("POST", f"{API_BASE}/oauth2/accessToken", auth=False,
body={"appKey": APP_KEY, "appSecret": APP_SECRET})
tok = d.get("accessToken") or ""
if not tok:
raise SystemExit(f"[x] 获取钉钉 accessToken 失败:{d}")
self._token, self._exp = tok, time.time() + int(d.get("expireIn", 3600))
return tok
def _raw(self, method: str, url: str, params: Optional[dict] = None,
body: Optional[dict] = None, auth: bool = True,
retries: int = MAX_ATTEMPTS) -> dict:
last = None
for attempt in range(1, retries + 1):
try:
headers = {"Content-Type": "application/json"}
if auth:
headers["x-acs-dingtalk-access-token"] = self._access_token()
r = requests.request(method, url, headers=headers, params=params,
json=body, timeout=30)
d = r.json()
if d.get("code"):
raise RuntimeError(f"{d.get('code')}: {d.get('message')}")
return d
except SystemExit:
raise
except Exception as exc: # 网络抖动 / 限流 / 5xx
last = exc
if attempt < retries:
time.sleep(RETRY_DELAY_BASE * attempt)
raise SystemExit(f"[x] 钉钉接口请求失败({retries} 次重试后放弃):{last}")
def _sheet_url(self, base: str, sheet: str, tail: str = "") -> str:
url = f"{API_BASE}/notable/bases/{base}/sheets/{sheet}"
return f"{url}/{tail}" if tail else url
def _p(self, **extra) -> dict:
p = {"operatorId": self.operator}
p.update(extra)
return p
# ---- 读 ----
def sheets(self, base: str) -> list:
return self._raw("GET", f"{API_BASE}/notable/bases/{base}/sheets",
params=self._p()).get("value") or []
def resolve_sheet(self, base: str, sheet: str) -> str:
items = self.sheets(base)
for s in items:
if sheet in (s.get("id"), s.get("name")):
return s["id"]
raise SystemExit(f"[x] 未找到 sheet:{sheet}\n 可选:"
+ "、".join(f"{s.get('name')}({s.get('id')})" for s in items))
def fields(self, base: str, sheet: str) -> dict:
return self._raw("GET", self._sheet_url(base, sheet, "fields"), params=self._p())
def records(self, base: str, sheet: str) -> list:
url = self._sheet_url(base, sheet, "records/list")
out, nxt = [], ""
for _ in range(500): # 500 × 100 = 5 万条上限
body = {"maxResults": PAGE_SIZE}
if nxt:
body["nextToken"] = nxt
d = self._raw("POST", url, params=self._p(), body=body)
out.extend(d.get("records") or [])
if d.get("hasMore") and d.get("nextToken"):
nxt = d["nextToken"]
else:
break
return out
# ---- 写 ----
def add(self, base: str, sheet: str, rows: list) -> int:
url = self._sheet_url(base, sheet, "records")
ok = 0
for i in range(0, len(rows), WRITE_BATCH):
batch = rows[i:i + WRITE_BATCH]
d = self._raw("POST", url, params=self._p(),
body={"records": [{"fields": r} for r in batch]})
ok += len(d.get("value") or batch)
return ok
def update(self, base: str, sheet: str, rows: list) -> int:
url = self._sheet_url(base, sheet, "records")
ok = 0
for i in range(0, len(rows), WRITE_BATCH):
batch = rows[i:i + WRITE_BATCH]
d = self._raw("PUT", url, params=self._p(), body={"records": batch})
ok += len(d.get("value") or batch)
return ok
def resolve_base(raw: str) -> tuple:
"""别名 / baseId / alidocs 链接 → (baseId, 链接里带的 sheetId 或空)。"""
s = (raw or "").strip()
if s in BASE_ALIASES:
return BASE_ALIASES[s], ""
if "alidocs" in s or "/i/nodes/" in s:
import re
m = re.search(r"/i/nodes/([A-Za-z0-9]+)", s)
if not m:
raise SystemExit(f"[x] 无法从链接解析 baseId:{s}")
ms = re.search(r"sheetId=([A-Za-z0-9]+)", s)
return m.group(1), (ms.group(1) if ms else "")
if len(s) < 20:
raise SystemExit(f"[x] 未知 base:{s}(可用别名:{', '.join(BASE_ALIASES)},"
f"或直接给 baseId/文档链接)")
return s, ""
+301
View File
@@ -0,0 +1,301 @@
# -*- 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()
+19
View File
@@ -0,0 +1,19 @@
[build-system]
requires = ["setuptools>=64"]
build-backend = "setuptools.build_meta"
[project]
name = "aitable"
version = "1.0.0"
description = "钉钉 AI 表格(notable)读写库:列 sheet/字段、分页读取、过滤统计、按类型写值,附月报/周报数据采集"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
"requests>=2.28",
]
[project.urls]
Repository = "https://github.com/37du/37duAutomation"
[tool.setuptools]
packages = ["aitable"]