#!/usr/bin/env python3 """ 订单汇总 A–X 全量镜像刷新 触发:Step2(Cursor Step1 完成后 @小溪) 归属:小溪 (xiaoxi) 进表条件:K=是 · O>0 · 非全额退(P空或P 23 and raw[23] not in (None, "") else 0 except (ValueError, TypeError): x_val = 0 if x_val != 1: continue order_rows.append(r) print(f"Order rows after filter: {len(order_rows)}") # ── Step 2.5: 去重(同 UID 多表出现,保留行号最小)── uid_best = {} for r in order_rows: raw = r["raw"] uid = str(raw[7]).strip() if len(raw) > 7 and raw[7] not in (None, "") else "" try: uid = str(int(float(raw[7]))) except: pass if not uid: continue if uid not in uid_best or r["row"] < uid_best[uid][0]: uid_best[uid] = (r["row"], r) order_rows = [v[1] for v in uid_best.values()] print(f" After UID dedup: {len(order_rows)} rows") # ── Step 3: 按 K 下单日降序 ── order_rows.sort(key=lambda r: str(r["raw"][10]) if len(r["raw"]) > 10 and r["raw"][10] else "", reverse=True) # ── Step 4: 构建 A–W 行(A-V 镜像 + W=渠道=三表Y + 无X列)── summary_rows = [] for r in order_rows: raw = r["raw"] # A–V 原样镜像 (indices 0-21) new_row = list(raw[:22]) # W: 渠道归属 = 三表 Y 列 (index 24) y_val = str(raw[24]).strip() if len(raw) > 24 and raw[24] not in (None, "") else "" new_row.append(y_val) summary_rows.append(new_row) print(f"Summary rows: {len(summary_rows)}") # ── Step 5: 写入订单汇总(使用安全写入工具,自动遵守 5000 格上限)── print("Writing to 订单汇总...") writer = FeishuSheetWriter(SPREADSHEET_TOKEN, token) # 先清空旧数据区(23 列 A-W,自动计算批大小 ≤ 4400 格/批) writer.clear(SUMMARY_SHEET, start_row=3, end_row=2000, cols=23) time.sleep(0.5) # 写入新数据(23 列 A-W,自动分批) total = len(summary_rows) writer.write(SUMMARY_SHEET, start_row=3, rows=summary_rows, cols=23) # ── Step 6: 清除多余旧行 ── existing = read_sheet(token, SUMMARY_SHEET, "A3:A4000") old_count = len([r for r in existing if r and any(c for c in r if c)]) if old_count > total: writer.clear(SUMMARY_SHEET, start_row=3 + total, end_row=3 + old_count - 1, cols=23) print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] ✅ 订单汇总刷新完成") if __name__ == "__main__": main()