代码管理

push_kdocs_range.py

← 返回编辑
#!/usr/bin/env python3
"""把 kdocs MCP 的 rangeData 结果转成系统存储格式并回传云端。

MCP 返回的是**按单元格**的扁平列表,每项带 rowFrom/colFrom + cellText,
需要先按坐标重排成二维矩阵。

用法:
    python3 push_kdocs_range.py <落盘文件> 
"""
import json
import subprocess
import sys
import time
import urllib.request

EP = "https://guangrui-dealer-dashboard.app.workbuddy.host"
# 2026-11-12 起平台启用 sharecode 访问门:请求必须带 sharecode 参数
SHARECODE = "H2MANGX4QF"
def _url(path):
    sep = "&" if "?" in path else "?"
    return EP + path + sep + "sharecode=" + SHARECODE
TOKEN_FILE = "/tmp/gr_tok"


def get_token():
    try:
        return open(TOKEN_FILE).read().split("=", 1)[1].strip()
    except Exception:
        return ""


def put_data(ds_id, cols, rows):
    body = json.dumps({
        "columns": json.dumps(cols, ensure_ascii=False),
        "rows": json.dumps(rows, ensure_ascii=False),
        "fetched_at": time.strftime("%Y-%m-%d %H:%M:%S"),
    }, ensure_ascii=False).encode()
    req = urllib.request.Request(
        _url(f"/api/datasets/{ds_id}/data"), data=body, method="PUT")
    req.add_header("x-auth-token", get_token())
    req.add_header("Content-Type", "application/json")
    with urllib.request.urlopen(req, timeout=180) as r:
        return json.loads(r.read().decode())


def convert(path):
    """rangeData(单元格列表)→ (cols, rows)。"""
    j = json.loads(open(path, encoding="utf-8").read())
    cells = ((j.get("data") or {}).get("detail") or {}).get("rangeData") or []
    if not cells:
        return [], []
    max_r = max((c.get("originRow") or 0) for c in cells)
    max_c = max((c.get("originCol") or 0) for c in cells)
    grid = {}
    for c in cells:
        r = c.get("originRow")
        col = c.get("originCol")
        if r is None or col is None:
            continue
        # 优先用原始值(保留数字精度),回退到显示文本
        v = c.get("originalCellValue")
        if v is None or v == "":
            v = c.get("cellText")
        grid[(r, col)] = "" if v is None else str(v)
    rows = []
    for r in range(max_r + 1):
        rows.append([grid.get((r, c), "") for c in range(max_c + 1)])
    # 去掉尾部全空行
    while rows and not any(x.strip() for x in rows[-1]):
        rows.pop()
    # 去掉右侧全空列(逐列判断,不是只看首行 —— 首行常是合并的大标题)
    if rows:
        keep = []
        for c in range(len(rows[0])):
            if any((rw[c] if c < len(rw) else "").strip() for rw in rows):
                keep.append(c)
        rows = [[(rw[c] if c < len(rw) else "") for c in keep] for rw in rows]
    cols = [str(i) for i in range(len(rows[0]) if rows else 0)]
    return cols, rows


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("用法: python3 push_kdocs_range.py <落盘文件> ")
        sys.exit(1)
    path, ds_id = sys.argv[1], sys.argv[2]
    cols, rows = convert(path)
    if not rows:
        print(f"✗ {ds_id}: 未解析出数据")
        sys.exit(1)
    r = put_data(ds_id, cols, rows)
    print(f"✓ {ds_id}: {len(cols)} 列 × {len(rows)} 行 → {r}")