refactor: 重构多插件 UI 与配置结构,新增抖音/新美大平台核对插件
- 新增 XQ0042 抖音平台核对、XQ0041 新美大平台核对插件的 UI 源码与打包脚本 - 重构续签电子签、服务岗转正不通过电子签等插件的版本与配置 - 删除旧版考勤异常处理、微盟数据导出等冗余插件文件 - 修复出勤积分更新插件的 OPM 推送判断逻辑 - 优化壳子插件页面的 iframe 滚动条样式
This commit is contained in:
@@ -19,6 +19,9 @@
|
||||
读取工作簿「积分导入」「积分删除」→ OPM 登录校验 → multipart 上传
|
||||
(`/operation/point/list/importAttendance`、`.../importAttendanceDel`)。
|
||||
推送前界面会二次确认;不使用单独的试运行开关——只想看名单时只开第一步,两张表就在工作簿里。
|
||||
上传失败最多重传一次:先判会话是否还有效(有效则原会话直接重传,不白做重登),
|
||||
拿到登录页 / 401 才重登;OPM 偶发返回非 JSON(HTML / 空响应)时,日志会带出
|
||||
HTTP 状态、content-type 与响应体片段,重传若提示「已存在 / 未生成出勤积分」即判定首传已生效。
|
||||
|
||||
只推送不更新时,自动取目录中最新修改的工作簿(或界面「指定工作簿」),不新建批次。
|
||||
仅更新不推送时,不做任何 OPM 网络请求(无需填写 OPM 账号)。
|
||||
|
||||
@@ -78,7 +78,7 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
id = "xq0033"
|
||||
name = "门店管理及服务岗出勤积分更新"
|
||||
version = "1.0.7"
|
||||
version = "1.0.9"
|
||||
description = (
|
||||
"拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,"
|
||||
"自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,"
|
||||
@@ -326,19 +326,29 @@ class Xq0033Plugin(ScenePlugin):
|
||||
groups.setdefault(r[2].date(), []).append(r)
|
||||
if len(groups) > 1:
|
||||
ctx.log(f"{label} 共 {len(rows)} 行,按积分日期分 {len(groups)} 批上传", "INFO")
|
||||
parts, failed = [], []
|
||||
parts, failed, retried, existed = [], [], 0, 0
|
||||
for d in sorted(groups):
|
||||
chunk = groups[d]
|
||||
res = self._upload_once(client, ctx, f"积分导入_{d:%m-%d}", chunk, kind)
|
||||
if res["success"]:
|
||||
parts.append(f"{d:%m-%d} {len(chunk)} 行")
|
||||
item = f"{d:%m-%d} {len(chunk)} 行"
|
||||
if res.get("first_error"):
|
||||
retried += 1
|
||||
item += "(重试后确认)"
|
||||
elif res.get("kind") == "benign":
|
||||
# 服务端提示已存在/无需处理:这批此前已导入过,不是本次新写入
|
||||
existed += 1
|
||||
item += "(已存在)"
|
||||
parts.append(item)
|
||||
else:
|
||||
failed.append(f"{d:%m-%d}({res['message']})")
|
||||
results[label] = {
|
||||
"success": not failed,
|
||||
"message": ("分批成功:" + "、".join(parts)) if not failed
|
||||
else "失败批次:" + ";".join(failed),
|
||||
}
|
||||
msg = ("分批成功:" + "、".join(parts)) if not failed \
|
||||
else "失败批次:" + ";".join(failed)
|
||||
if not failed and retried:
|
||||
msg += f";其中 {retried} 批首传响应异常,已由重传结果确认"
|
||||
if not failed and existed:
|
||||
msg += f";其中 {existed} 批服务端提示已存在(此前已导入,本次未新增)"
|
||||
results[label] = {"success": not failed, "message": msg}
|
||||
else:
|
||||
results[label] = self._upload_once(client, ctx, label, rows, kind)
|
||||
res = results[label]
|
||||
@@ -348,18 +358,37 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
@staticmethod
|
||||
def _upload_once(client, ctx, label, rows, kind):
|
||||
"""单批上传;失败时重登会话再试一次(大请求超时后 OPM 常会重置会话返回 HTML)。"""
|
||||
"""单批上传,失败最多重传一次。
|
||||
|
||||
OPM 偶发返回非 JSON(HTML 登录页 / 空响应),此时无法确认是否已写入:
|
||||
- 会话仍有效 → 原会话直接重传,不白做一次重登;
|
||||
- 会话失效(拿到登录页 / 401) → 重登后重传;
|
||||
- 重传若提示「已存在/未生成出勤积分」→ 判定首传其实已生效,如实记录而不是报失败。
|
||||
"""
|
||||
url = client.import_url if kind == "import" else client.delete_url
|
||||
res = client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
payload = build_kaoqin_bytes(rows)
|
||||
res = client.upload(url, payload, f"{label}.xlsx")
|
||||
if res["success"]:
|
||||
return res
|
||||
ctx.log(f"{label} 上传失败,重登会话后重试一次:{res['message']}", "WARN")
|
||||
try:
|
||||
client.session = None
|
||||
client.ensure_session()
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"{res['message']};重登失败:{e}"}
|
||||
return client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
|
||||
need_relogin = res.get("kind") == "notfound" or not client.is_session_valid()
|
||||
ctx.log(f"{label} 第 1 次上传未确认成功:{res['message']}"
|
||||
f"(会话{'已失效,重登后重试' if need_relogin else '仍有效,直接重试'})", "WARN")
|
||||
if need_relogin:
|
||||
try:
|
||||
client.session = None
|
||||
client.ensure_session()
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"{res['message']};重登失败:{e}"}
|
||||
|
||||
res2 = client.upload(url, payload, f"{label}.xlsx")
|
||||
if res2["success"]:
|
||||
if res2.get("kind") == "benign":
|
||||
res2["message"] = (f"首传响应异常({res['message']}),重传提示已存在 → "
|
||||
f"判定首传已生效:{res2['message']}")
|
||||
res2["first_error"] = res["message"]
|
||||
return res2
|
||||
return {"success": False, "message": f"首传:{res['message']};重传:{res2['message']}"}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0033Plugin())
|
||||
|
||||
@@ -70,6 +70,8 @@ OPM_DELETE_PATH = "/operation/point/list/importAttendanceDel"
|
||||
OPM_TIMEOUT = 120
|
||||
# 服务端对「重复/无内容可删」的良性响应关键词:目标状态已达成,不算失败
|
||||
OPM_BENIGN_MSGS = ("不能重复添加", "未生成出勤积分", "已存在")
|
||||
# 同一条 message 里出现这些词说明确有行处理失败:不能因含良性关键词就整体判成功
|
||||
OPM_FATAL_MSGS = ("失败", "异常", "错误", "不存在", "格式不正确", "解析")
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
@@ -94,6 +94,36 @@ def build_kaoqin_bytes(rows):
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
# ==================== 响应诊断 ====================
|
||||
def _body_text(resp, limit=300):
|
||||
"""取响应体文本片段(诊断「响应非 JSON」到底返回了什么)。"""
|
||||
body = resp.content or b""
|
||||
if not body:
|
||||
return ""
|
||||
txt = None
|
||||
for enc in ("utf-8", "gbk"):
|
||||
try:
|
||||
txt = body.decode(enc)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if txt is None:
|
||||
txt = body.decode("utf-8", "replace")
|
||||
txt = " ".join(txt.split())
|
||||
return txt[:limit] + ("…" if len(txt) > limit else "")
|
||||
|
||||
|
||||
def _looks_like_login_page(txt):
|
||||
low = (txt or "").lower()
|
||||
return "<html" in low or "<!doctype" in low or ("<form" in low and "password" in low)
|
||||
|
||||
|
||||
def _fmt_msg(msg, limit=500):
|
||||
"""服务端 message 多为多行逐行提示,压成单行,保留更多内容。"""
|
||||
txt = ";".join(x.strip() for x in str(msg or "").splitlines() if x.strip())
|
||||
return txt[:limit] + ("…" if len(txt) > limit else "")
|
||||
|
||||
|
||||
# ==================== 客户端 ====================
|
||||
class OPMClient:
|
||||
"""OPM 登录 + 考勤积分上传(积分导入 / 积分删除)。"""
|
||||
@@ -115,6 +145,13 @@ class OPMClient:
|
||||
s.get(self.login_url, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
def _warm_up(self, session):
|
||||
"""对齐浏览器上下文:正式上传都在「积分列表」页发起,登录后先 GET 一次该页。"""
|
||||
try:
|
||||
session.get(self.base_url + "/point/list", timeout=TIMEOUT)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def is_session_valid(self, session=None):
|
||||
session = session or self.session
|
||||
if session is None:
|
||||
@@ -168,6 +205,7 @@ class OPMClient:
|
||||
raise OPMLoginError(f"OPM 登录被拒绝(账号或密码错误?):{msg}")
|
||||
if self.is_session_valid(session):
|
||||
self.session = session
|
||||
self._warm_up(session)
|
||||
config.logger.info("OPM 登录成功")
|
||||
return session
|
||||
last_msg = "登录接口返回成功但会话校验未通过"
|
||||
@@ -180,21 +218,50 @@ class OPMClient:
|
||||
return self.login()
|
||||
|
||||
def upload(self, url, file_bytes, filename):
|
||||
"""上传单个文件,返回 {success, message, kind}。
|
||||
|
||||
kind 用于上层判断该不该重登/重传:
|
||||
ok 服务端明确成功
|
||||
benign 服务端提示「已存在/未生成出勤积分」等,目标状态已达成(算成功)
|
||||
notfound 会话失效(拿到登录页/HTML),必须重登后再试
|
||||
unknown 响应非 JSON 或空响应,无法确认结果,需重传确认
|
||||
http HTTP 非 200
|
||||
error 服务端明确失败
|
||||
"""
|
||||
try:
|
||||
resp = self.session.post(
|
||||
url, files={"file": (filename, file_bytes, FILE_MIME)},
|
||||
headers={"Referer": self.base_url + "/point/list"}, timeout=config.OPM_TIMEOUT)
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"上传异常:{e}"}
|
||||
return {"success": False, "kind": "error", "message": f"上传异常:{e}"}
|
||||
if resp.status_code != 200:
|
||||
return {"success": False, "message": f"HTTP {resp.status_code}"}
|
||||
snippet = _body_text(resp, 200)
|
||||
msg = f"HTTP {resp.status_code}" + (f"({snippet})" if snippet else "")
|
||||
return {"success": False,
|
||||
"kind": "notfound" if resp.status_code in (401, 403) else "http",
|
||||
"message": msg}
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return {"success": False, "message": "响应非 JSON"}
|
||||
snippet = _body_text(resp)
|
||||
if not snippet:
|
||||
return {"success": False, "kind": "unknown",
|
||||
"message": "响应为空(HTTP 200 无内容)"}
|
||||
kind = "notfound" if _looks_like_login_page(snippet) else "unknown"
|
||||
ctype = resp.headers.get("content-type", "")
|
||||
return {"success": False, "kind": kind,
|
||||
"message": f"响应非 JSON(HTTP 200,{ctype or '无 content-type'}):{snippet}"}
|
||||
if not isinstance(data, dict):
|
||||
return {"success": False, "kind": "unknown",
|
||||
"message": f"响应格式异常:{_body_text(resp, 150)}"}
|
||||
ok = data.get("status") is True or data.get("code") == "S0"
|
||||
msg = data.get("message") or ""
|
||||
if not ok and any(k in msg for k in config.OPM_BENIGN_MSGS):
|
||||
return {"success": True,
|
||||
"message": f"部分已存在/无需处理(目标状态已达成):{msg[:200]}"}
|
||||
return {"success": bool(ok), "message": msg or ("" if ok else "导入失败")}
|
||||
msg = _fmt_msg(data.get("message"))
|
||||
if ok:
|
||||
return {"success": True, "kind": "ok", "message": msg}
|
||||
if msg and any(k in msg for k in config.OPM_BENIGN_MSGS):
|
||||
# 逐行提示里既有「已存在/未生成」又有「失败/不存在」等硬错误时不能算成功
|
||||
if not any(k in msg for k in config.OPM_FATAL_MSGS):
|
||||
return {"success": True, "kind": "benign",
|
||||
"message": f"部分已存在/无需处理(目标状态已达成):{msg}"}
|
||||
return {"success": False, "kind": "error",
|
||||
"message": msg or "导入失败(服务端未返回原因)"}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0033",
|
||||
"name": "门店管理及服务岗出勤积分更新",
|
||||
"version": "1.0.7",
|
||||
"version": "1.0.9",
|
||||
"description": "拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,COM 全量重算),可选将积分导入与删除表推送至 OPM 平台。",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -48,7 +48,7 @@ class _LogWriter:
|
||||
class Xq0034Plugin(ScenePlugin):
|
||||
id = "xq0034"
|
||||
name = "续签电子签"
|
||||
version = "1.0.18"
|
||||
version = "1.0.19"
|
||||
description = ("XQ0034 续签电子签:AI表格【续签名单到期跟进-月更新】驱动——否续签回填、"
|
||||
"是续签手机号校验后 HR 生效中合同属性页「续签合同」提交推送电子签并回填,"
|
||||
"HR 会话由壳子注入")
|
||||
|
||||
@@ -442,11 +442,12 @@ def renew_contract(session, ai, dry_run):
|
||||
# 「合同/协议到期日」须与【生效中合同】截止日期完全一致;不一致(含
|
||||
# AI 表未填)说明两边数据错位(旧合同已被替换/到期日填错),不发起
|
||||
# 续签,报异常转人工核对(该异常推送钉钉通知)。
|
||||
ai["_alert"] = True
|
||||
if old_expire is None:
|
||||
ai["_alert"] = True
|
||||
return "异常", ("AI表「合同/协议到期日」为空,无法核对生效中合同截止日期,"
|
||||
"不发起续签,请人工补充后重跑")
|
||||
if a_end != old_expire:
|
||||
ai["_alert"] = True
|
||||
return "异常", (f"AI表合同/协议到期日({old_expire})与生效中合同截止日期"
|
||||
f"({a_end or '?'})不一致,不发起续签,请人工核对")
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0034",
|
||||
"name": "续签电子签",
|
||||
"version": "1.0.18",
|
||||
"version": "1.0.19",
|
||||
"description": "XQ0034 续签电子签:钉钉AI表格【续签名单到期跟进-月更新】驱动——「是否续签=否」回填人资是否推送=否;「是否续签=是」前置默认补全(电子签接收电话为空取花名册号码回填、期望推送日期为空默认当天回填)后完整发起续签:校验电话与花名册一致(不一致且合法自动修正HR联系方式),发起前核对 AI 表「合同/协议到期日」与【生效中合同】截止日期,不一致或未填=异常不发起并推送钉钉通知,一致则在 HR【合同台账-生效中合同】属性页「续签合同」提交推送电子签(新合同信息直接取AI表字段,电子签模板按员工+签署单位实时查询,为空不提交转人工),成功回填人资是否推送=是+推送时间;核验:待生效+生效中联合取最新合同,时间与AI表续签期一致且签署记录is_initiate_sign=2已完成签署才回填完成签署=是(1已发起/3已撤销均不算);通知块格式与加班审批一致,推送成功/核验完成数量/核验未完成数量/失败/合同到期日异常;HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -52,7 +52,7 @@ class _LogWriter:
|
||||
class Xq0035Plugin(ScenePlugin):
|
||||
id = "xq0035"
|
||||
name = "服务岗转正不通过电子签"
|
||||
version = "1.0.2"
|
||||
version = "1.0.9"
|
||||
description = ("XQ0035 服务岗转正不通过电子签(离职+入职):①变更试用期主流程 "
|
||||
"②新签合同 ③签署生效复核,AI表格驱动、断点续跑,单步执行错峰定时")
|
||||
platform = "hr"
|
||||
|
||||
@@ -1294,6 +1294,13 @@ def _build_processed_msg(stage, rec, base_code, target_end_date):
|
||||
"跳过发起调动解除,请人工核查生效情况。")
|
||||
|
||||
|
||||
def _effective_reaches_target(proc_rec, target_end_date):
|
||||
"""已生效变更记录的新试用期结束日期是否已达到脚本目标(>= 目标日)。"""
|
||||
eff = _to_date((proc_rec or {}).get("hr_staff_probation.new_period_end_date"))
|
||||
tgt = _to_date(target_end_date)
|
||||
return bool(eff and tgt and eff >= tgt)
|
||||
|
||||
|
||||
# ==================== 钉钉 AI表格:名单读取 + 处理后回写 ====================
|
||||
_aitable_tok = {"at": "", "exp": 0.0}
|
||||
|
||||
@@ -1584,9 +1591,12 @@ def process_one(session, task):
|
||||
已发起 -> 跳过发起环节,离职推送时间取实际发起日期(create_time),而非本次操作日期。
|
||||
无生效中合同 = 调动解除(电子签)已走完生效,电子签链(发起/完善信息/CA签署)视为完成,
|
||||
直接进入变更试用期(测试号场景:电子签已走完、无生效中合同)。
|
||||
电子签(调动解除/CA 签署)发起失败:仅记 flow_error 异常,变更试用期仍继续(实测不依赖电子签)。
|
||||
交叉验证:处理前核查三个变更 Tab,命中(已被他人操作到任意环节)则 status=跳过,
|
||||
不发起点调动解除,仅提示人工核查,all_done=False 不回填 AI表格。
|
||||
电子签(调动解除/CA 签署)发起失败:仅记 flow_error 异常,变更试用期仍继续(实测不依赖电子签),
|
||||
但 all_done 恒为 False -> 不回填 AI 表格(判失败、入异常表+钉钉),下次运行自动续跑。
|
||||
交叉验证:处理前核查三个变更 Tab:
|
||||
待确认/待生效命中 -> status=跳过,不发起调动解除,仅提示人工核查,all_done=False 不回填 AI表格;
|
||||
已生效且新到期日已达目标、但生效中合同仍在(离职电子签未发起)-> 变更/确认视为已完成,
|
||||
跳过变更与确认,继续补做调动解除(离职电子签),跑通后照常回填 AI表格。
|
||||
"""
|
||||
base_code = str(task["base_code"]).strip()
|
||||
new_period_date = task.get("new_period_date") or FIXED_NEW_PERIOD_MONTHS
|
||||
@@ -1653,17 +1663,33 @@ def process_one(session, task):
|
||||
logger.info("【%s】未达龄(性别 %s,生日 %s,序列 %s),继续流程", base_code,
|
||||
"男" if str(r_sex) == "1" else "女", r_birth, seq_name or "未知")
|
||||
|
||||
# 1) 交叉验证:流程可能已被他人操作到任意环节,命中则跳过发起调动解除,提示人工核查
|
||||
# 1) 交叉验证:流程可能已被他人操作到任意环节
|
||||
# - 待确认/待生效:半途被他人操作,跳过并提示人工核查
|
||||
# - 已生效但生效中合同仍在(离职电子签未发起):变更/确认视为已完成,
|
||||
# 不重复提交变更,继续补做调动解除(离职电子签),跑通后照常回填台账
|
||||
stage, proc_rec = check_processed_stage(session, base_code)
|
||||
contract = query_active_contract(session, base_code)
|
||||
skip_change = False
|
||||
if stage is not None:
|
||||
result["status"] = "跳过"
|
||||
result["message"] = _build_processed_msg(stage, proc_rec, base_code, new_period_end_date)
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
if (stage == "done" and contract and contract.get("contract_id")
|
||||
and _effective_reaches_target(proc_rec, new_period_end_date)):
|
||||
result["stages"]["change"] = True
|
||||
result["stages"]["confirm"] = True
|
||||
skip_change = True
|
||||
logger.warning("【%s】交叉验证:试用期变更已生效(新到期 %s,操作人 %s,%s),"
|
||||
"但生效中合同仍在(离职电子签未发起)——跳过变更/确认,只补做调动解除",
|
||||
base_code,
|
||||
(proc_rec or {}).get("hr_staff_probation.new_period_end_date"),
|
||||
(proc_rec or {}).get("hr_staff_probation.operator_name"),
|
||||
(proc_rec or {}).get("hr_staff_probation.operate_time"))
|
||||
else:
|
||||
result["status"] = "跳过"
|
||||
result["message"] = _build_processed_msg(stage, proc_rec, base_code, new_period_end_date)
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
# 1) 调动解除(电子签):查生效合同 -> 断点续跑检测 -> 防重校验 -> 发起《(改签)离职电子签流程》
|
||||
logger.info("【%s】1/5 查询【生效中合同】并处理调动解除(电子签)……", base_code)
|
||||
contract = query_active_contract(session, base_code)
|
||||
logger.info("【%s】1/5 处理调动解除(电子签)……", base_code)
|
||||
if not contract or not contract.get("contract_id"):
|
||||
# 无生效中合同 = 调动解除(电子签)已走完生效(离职解除已生效)
|
||||
# -> 电子签链(发起/完善信息/CA签署)视为已完成,直接进入变更试用期
|
||||
@@ -1756,64 +1782,77 @@ def process_one(session, task):
|
||||
result["staff_name"] = staff.get("hr_staff_base.staff_name") or ""
|
||||
logger.info("【%s】命中员工:%s(base_id=%s)", base_code, result["staff_name"], base_id)
|
||||
|
||||
# 3) 提交变更试用期
|
||||
logger.info("【%s】3/5 提交变更试用期(类型=%s(%s),新试用期=%s 月,结束=%s)……",
|
||||
base_code, corr_name, correction_type, new_period_date, new_period_end_date)
|
||||
save_resp = change_trial_period(session, base_id, correction_type,
|
||||
new_period_date, new_period_end_date,
|
||||
trial_row=staff)
|
||||
if save_resp.get("state") != "1":
|
||||
meg = save_resp.get("meg") or ""
|
||||
if "已经存在子页面" in meg:
|
||||
# 幂等:该员工已有待确认记录(重复运行/断点续跑),视为已提交,继续确认
|
||||
logger.info("【%s】变更已提交过(待确认记录已存在),继续后续环节", base_code)
|
||||
else:
|
||||
result["message"] = f"提交变更试用期失败:{meg or save_resp}"
|
||||
if skip_change:
|
||||
# 变更/确认此前已生效(交叉验证命中),本次只补做调动解除,不重复提交
|
||||
logger.info("【%s】3~5/5 试用期变更此前已生效(新到期 %s),跳过变更与确认",
|
||||
base_code, new_period_end_date)
|
||||
else:
|
||||
# 3) 提交变更试用期
|
||||
logger.info("【%s】3/5 提交变更试用期(类型=%s(%s),新试用期=%s 月,结束=%s)……",
|
||||
base_code, corr_name, correction_type, new_period_date, new_period_end_date)
|
||||
save_resp = change_trial_period(session, base_id, correction_type,
|
||||
new_period_date, new_period_end_date,
|
||||
trial_row=staff)
|
||||
if save_resp.get("state") != "1":
|
||||
meg = save_resp.get("meg") or ""
|
||||
if "已经存在子页面" in meg:
|
||||
# 幂等:该员工已有待确认记录(重复运行/断点续跑),视为已提交,继续确认
|
||||
logger.info("【%s】变更已提交过(待确认记录已存在),继续后续环节", base_code)
|
||||
else:
|
||||
result["message"] = f"提交变更试用期失败:{meg or save_resp}"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["change"] = True
|
||||
|
||||
# 4) 定位待确认记录(变更提交后进入「变更/转正待确认」)
|
||||
# ⚠️ 服务端落库存在延迟:提交成功后立即查询可能查不到(实测),需重试等待
|
||||
logger.info("【%s】4/5 查询「变更/转正待确认」……", base_code)
|
||||
pending = None
|
||||
for attempt in range(1, 6):
|
||||
pending = query_pending(session, base_code)
|
||||
if pending:
|
||||
break
|
||||
logger.info("【%s】第 %d 次未查到待确认记录,服务端落库可能延迟,5 秒后重试",
|
||||
base_code, attempt)
|
||||
time.sleep(5)
|
||||
if not pending:
|
||||
result["message"] = "变更已提交,但未在「变更/转正待确认」中找到记录,需人工检查"
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
management_id = pending.get("hr_staff_probation.management_id")
|
||||
logger.info("【%s】待确认记录 management_id=%s", base_code, management_id)
|
||||
|
||||
# 5) 确认
|
||||
logger.info("【%s】5/5 执行确认……", base_code)
|
||||
confirm_resp = confirm_pending(session, management_id)
|
||||
if confirm_resp.get("state") != "1":
|
||||
result["message"] = f"确认失败:{confirm_resp.get('meg') or confirm_resp}"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["change"] = True
|
||||
result["stages"]["confirm"] = True
|
||||
|
||||
# 4) 定位待确认记录(变更提交后进入「变更/转正待确认」)
|
||||
# ⚠️ 服务端落库存在延迟:提交成功后立即查询可能查不到(实测),需重试等待
|
||||
logger.info("【%s】4/5 查询「变更/转正待确认」……", base_code)
|
||||
pending = None
|
||||
for attempt in range(1, 6):
|
||||
pending = query_pending(session, base_code)
|
||||
if pending:
|
||||
break
|
||||
logger.info("【%s】第 %d 次未查到待确认记录,服务端落库可能延迟,5 秒后重试",
|
||||
base_code, attempt)
|
||||
time.sleep(5)
|
||||
if not pending:
|
||||
result["message"] = "变更已提交,但未在「变更/转正待确认」中找到记录,需人工检查"
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
management_id = pending.get("hr_staff_probation.management_id")
|
||||
logger.info("【%s】待确认记录 management_id=%s", base_code, management_id)
|
||||
|
||||
# 5) 确认
|
||||
logger.info("【%s】5/5 执行确认……", base_code)
|
||||
confirm_resp = confirm_pending(session, management_id)
|
||||
if confirm_resp.get("state") != "1":
|
||||
result["message"] = f"确认失败:{confirm_resp.get('meg') or confirm_resp}"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["confirm"] = True
|
||||
result["all_done"] = all(result["stages"].values())
|
||||
change_desc = (f"试用期变更此前已生效(结束 {new_period_end_date}),本次跳过变更/确认"
|
||||
if skip_change else
|
||||
f"试用期已变更({corr_name},{new_period_date} 月,结束 {new_period_end_date})并确认生效")
|
||||
# 离职电子签(CA)未发起成功 = 整条未完成:all_done=False 不回填台账,下次运行续跑(防漏单)
|
||||
result["all_done"] = all(result["stages"].values()) and not result["flow_error"]
|
||||
|
||||
if result["flow_error"]:
|
||||
# 电子签(调动解除/CA 签署)发起失败但变更+确认已完成:
|
||||
# 异常已记录(异常表+钉钉),回填由 main() 按 all_done 决定
|
||||
result["status"] = "成功" if result["all_done"] else "失败"
|
||||
result["message"] = (f"{result['staff_name']} 试用期已变更({corr_name},"
|
||||
f"{new_period_date} 月,结束 {new_period_end_date})并确认生效;"
|
||||
f"⚠️ 电子签异常需人工处理:{result['flow_error']}")
|
||||
# 电子签(调动解除/CA 签署)发起失败:异常已记录(异常表+钉钉),
|
||||
# all_done 恒为 False → 不回填 AI 表格,保留待处理状态供下次重试
|
||||
result["status"] = "失败"
|
||||
result["message"] = (f"{result['staff_name']} {change_desc};"
|
||||
f"⚠️ 离职电子签发起失败需人工处理(台账未回填,下次运行续跑):"
|
||||
f"{result['flow_error']}")
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
result["status"] = "成功"
|
||||
result["message"] = (f"{result['staff_name']} 调动解除(电子签)已发起,"
|
||||
f"试用期已变更({corr_name},{new_period_date} 月,结束 {new_period_end_date})并确认生效")
|
||||
if skip_change:
|
||||
result["message"] = (f"{result['staff_name']} 调动解除(电子签)已补发起,"
|
||||
f"试用期变更此前已生效(结束 {new_period_end_date}),本次跳过变更/确认")
|
||||
else:
|
||||
result["message"] = (f"{result['staff_name']} 调动解除(电子签)已发起,{change_desc}")
|
||||
logger.info("【%s】✅ %s", base_code, result["message"])
|
||||
return result
|
||||
except LoginRequiredError as e:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0035",
|
||||
"name": "服务岗转正不通过电子签",
|
||||
"version": "1.0.7",
|
||||
"version": "1.0.9",
|
||||
"description": "XQ0035 服务岗转正不通过电子签(离职+入职):按步骤执行 ①变更试用期主流程(调动解除电子签+完善信息+发起离职电子签+变更试用期+确认生效+回填AI表格)②新签合同(超龄用工协议/劳动合同+回填新合同推送日期)③签署生效复核(回填签署跟进);AI表格驱动、断点续跑,HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0041 新美大平台核对 —— webhost 场景插件入口。
|
||||
|
||||
执行过程由 action 决定(UI 的两个开关派生):
|
||||
action='download' → 只下载:登录经营宝,按勾选下载打款记录 / 团购收益明细 / 预订收益明细;
|
||||
action='reconcile' → 只核对:**不开浏览器**,直接用本机最新的台账与收益明细并入台账、
|
||||
更新核对统计(适合数据已下载、只想重算的场景);
|
||||
action='all' → 下载后再核对(默认)。
|
||||
|
||||
签名说明:平台接口的签名参数由页面自身的前端组件生成,插件只在页面上下文发起请求,
|
||||
不涉及任何签名算法。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import browser, meituan_login, payment_download, profit_download
|
||||
from .logic import merge_ledger, stat_links
|
||||
|
||||
|
||||
def _parse_day(s):
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||
try:
|
||||
return datetime.strptime(str(s).strip(), fmt).date()
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_pair(raw_from, raw_to):
|
||||
"""解析一组日期:都空=昨天~今天;只给一端=单日;起止颠倒自动换序。"""
|
||||
d1 = _parse_day(raw_from) if raw_from else None
|
||||
d2 = _parse_day(raw_to) if raw_to else None
|
||||
if d1 is None and d2 is None:
|
||||
return ((date.today() - timedelta(days=1)).isoformat(), date.today().isoformat())
|
||||
if d1 is None:
|
||||
d1 = d2
|
||||
if d2 is None:
|
||||
d2 = d1
|
||||
if d2 < d1:
|
||||
d1, d2 = d2, d1
|
||||
return d1.isoformat(), d2.isoformat()
|
||||
|
||||
|
||||
def _resolve_action(fields):
|
||||
"""决定本次做什么:download / reconcile / all。
|
||||
|
||||
UI 会直接给 action;老配置(无 action)按开关推导,缺省视为全流程。
|
||||
"""
|
||||
action = str(fields.get('action') or '').strip().lower()
|
||||
if action in ('download', 'reconcile', 'all'):
|
||||
return action
|
||||
do_download = fields.get('do_download')
|
||||
do_reconcile = fields.get('do_reconcile')
|
||||
do_download = True if do_download is None else bool(do_download)
|
||||
do_reconcile = True if do_reconcile is None else bool(do_reconcile)
|
||||
if do_download and do_reconcile:
|
||||
return 'all'
|
||||
if do_download:
|
||||
return 'download'
|
||||
if do_reconcile:
|
||||
return 'reconcile'
|
||||
return ''
|
||||
|
||||
|
||||
class Xq0041Plugin(ScenePlugin):
|
||||
id = 'xq0041'
|
||||
name = '新美大平台核对'
|
||||
version = '1.1.2'
|
||||
description = ('美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、'
|
||||
'预订收益明细,把新产生的收益按验券时间并入月份台账,'
|
||||
'并给核对统计表补当天的团购统计表链接')
|
||||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0041']
|
||||
permissions = {'platforms': []}
|
||||
# 与 plugin.json.fields 一致(ui=true,前端按此渲染表单)
|
||||
fields = {
|
||||
'action': {'type': 'string', 'title': '执行过程', 'default': 'all',
|
||||
'enum': ['all', 'download', 'reconcile']},
|
||||
'do_download': {'type': 'boolean', 'title': '下载数据', 'default': True},
|
||||
'do_reconcile': {'type': 'boolean', 'title': '更新核对', 'default': True},
|
||||
'pay_enabled': {'type': 'boolean', 'title': '下载打款记录', 'default': True},
|
||||
'pay_date_from': {'type': 'string', 'title': '打款记录-开始日期', 'default': ''},
|
||||
'pay_date_to': {'type': 'string', 'title': '打款记录-结束日期', 'default': ''},
|
||||
'profit_group': {'type': 'boolean', 'title': '下载团购收益明细', 'default': True},
|
||||
'profit_booking': {'type': 'boolean', 'title': '下载预订收益明细', 'default': True},
|
||||
'profit_date_from': {'type': 'string', 'title': '收益明细-开始日期', 'default': ''},
|
||||
'profit_date_to': {'type': 'string', 'title': '收益明细-结束日期', 'default': ''},
|
||||
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
||||
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
||||
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx):
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(fields.get('debug_mode'))
|
||||
|
||||
# ---------- 参数 ----------
|
||||
action = _resolve_action(fields)
|
||||
if not action:
|
||||
raise RuntimeError('请至少选择一个执行过程(下载数据 / 更新核对)')
|
||||
do_download = action in ('all', 'download')
|
||||
do_reconcile = action in ('all', 'reconcile')
|
||||
|
||||
codes = []
|
||||
if fields.get('profit_group', True):
|
||||
codes.append(1)
|
||||
if fields.get('profit_booking', True):
|
||||
codes.append(11)
|
||||
pay_on = bool(fields.get('pay_enabled', True))
|
||||
|
||||
dry_run = bool(fields.get('dry_run'))
|
||||
run_merge = bool(fields.get('run_merge', True))
|
||||
run_links = bool(fields.get('run_links', True))
|
||||
save_dir = str(fields.get('save_dir') or config.WORK_DIR).strip().strip('"') or config.WORK_DIR
|
||||
|
||||
if do_download and not pay_on and not codes:
|
||||
raise RuntimeError('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
||||
|
||||
# 并入台账依赖团购收益明细(台账只收团购口径)
|
||||
if do_reconcile and run_merge and not codes and do_download:
|
||||
config.log('未勾选团购收益明细,本次跳过「并入台账」', 'WARN')
|
||||
run_merge = False
|
||||
|
||||
pay_from, pay_to = _resolve_pair(fields.get('pay_date_from'), fields.get('pay_date_to'))
|
||||
profit_from, profit_to = _resolve_pair(fields.get('profit_date_from'),
|
||||
fields.get('profit_date_to'))
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
plan = []
|
||||
if do_download:
|
||||
if pay_on:
|
||||
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
||||
if codes:
|
||||
name = '/'.join(n for c, n in ((1, '团购'), (11, '预订')) if c in codes)
|
||||
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
||||
if do_reconcile:
|
||||
plan.append('并入台账' if run_merge else '')
|
||||
plan.append('更新核对统计' if run_links else '')
|
||||
plan = [p for p in plan if p]
|
||||
config.log(('本次执行:' + ';'.join(plan) if plan else '本次没有可执行的动作')
|
||||
+ (f';目录 {save_dir}' if do_download else '')
|
||||
+ ('(只核对不写入)' if dry_run else ''))
|
||||
|
||||
detail = {'action': action, 'pay': None, 'profit': None, 'merge': None, 'links': None}
|
||||
files = []
|
||||
|
||||
# ---------- 1~3:登录 + 下载 ----------
|
||||
if do_download:
|
||||
ctx.progress(2)
|
||||
page = browser.open_page()
|
||||
try:
|
||||
ok, msg = meituan_login.ensure_login(page)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
ctx.progress(20 if do_reconcile else 30)
|
||||
|
||||
if pay_on:
|
||||
r1 = payment_download.download(page, pay_from, pay_to, save_dir, dry_run)
|
||||
if not r1.get('ok'):
|
||||
raise RuntimeError(f'打款记录下载失败:{r1.get("message")}')
|
||||
config.log(r1.get('message') or '')
|
||||
if r1.get('path'):
|
||||
files.append(r1['path'])
|
||||
detail['pay'] = r1
|
||||
ctx.progress(45 if do_reconcile else 65)
|
||||
|
||||
if codes:
|
||||
r2 = profit_download.download(page, profit_from, profit_to, save_dir,
|
||||
codes, dry_run)
|
||||
if not r2.get('ok'):
|
||||
raise RuntimeError(f'收益明细下载失败:{r2.get("message")}')
|
||||
config.log(r2.get('message') or '')
|
||||
files.extend(r2.get('paths') or [])
|
||||
detail['profit'] = r2
|
||||
ctx.progress(60 if do_reconcile else 95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
|
||||
# ---------- 4~5:并入台账 + 更新核对(不依赖浏览器) ----------
|
||||
if do_reconcile:
|
||||
ctx.progress(65 if do_download else 10)
|
||||
if run_merge:
|
||||
m = merge_ledger.run(dry_run=dry_run)
|
||||
config.log(m.get('message') or '')
|
||||
detail['merge'] = m
|
||||
if not m.get('ok'):
|
||||
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
||||
ctx.progress(85 if do_download else 60)
|
||||
|
||||
if run_links:
|
||||
# 纯核对时让后端按本机最新明细文件的日期推断(跟随实际数据);
|
||||
# 有下载则用本次的收益明细区间。
|
||||
link_from, link_to = (profit_from, profit_to) if do_download else (None, None)
|
||||
s = stat_links.run(link_from, link_to, dry_run=dry_run)
|
||||
config.log(s.get('message') or '')
|
||||
detail['links'] = s
|
||||
if not s.get('ok'):
|
||||
config.log(f'更新核对统计失败:{s.get("message")}', 'WARN')
|
||||
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
parts = []
|
||||
if files:
|
||||
parts.append(f'下载 {len(files)} 个文件')
|
||||
if detail['merge'] and detail['merge'].get('appended'):
|
||||
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
||||
if detail['links'] and detail['links'].get('rows'):
|
||||
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
||||
if not parts:
|
||||
parts.append('执行完成')
|
||||
if dry_run:
|
||||
parts.insert(0, '[只核对不写入]')
|
||||
return {
|
||||
'summary': ';'.join(parts),
|
||||
'detail': detail,
|
||||
'path': files[0] if files else '',
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0041Plugin())
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
输出 dist-plugin/xq0041_v<版本>.zip,zip 根含 plugin.json。
|
||||
排除:ui-src、__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0041 新美大平台核对\\_pack.py"
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0041 新美大平台核对 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
各业务模块统一经 config.log() / config.progress() 输出,由 run() 启动时注入 ctx。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
# ==================== 平台:美团经营宝 ====================
|
||||
HOME_URL = 'https://ecom.meituan.com/'
|
||||
|
||||
# 登录成功的落地页:经营宝按商家类型分流(kdb → ecom.meituan.com/meishi,
|
||||
# dp → e.dianping.com/app/...)。命中任一即已登录。
|
||||
BACKEND_HINTS = (
|
||||
'ecom.meituan.com/meishi',
|
||||
'e.dianping.com/app/',
|
||||
'e.dianping.com/meishi/',
|
||||
)
|
||||
LOGIN_PAGE_HINT = 'bizaccount/login.html'
|
||||
BIZ_CHOICE_HINT = 'bizaccount/biz-choice.html'
|
||||
PASSPORT_HINTS = (
|
||||
'passport.meituan.com', 'epassport.meituan.com', 'unifiedlogin', 'ssologin',
|
||||
'passport.dianping.com', 'account.dianping.com/login', 'e.dianping.com/login',
|
||||
)
|
||||
|
||||
# ==================== 打款记录(h5 账单页,iframe 内 smartBill 接口) ====================
|
||||
PAYMENT_PAGE_URL = (
|
||||
'https://e.dianping.com/app/merchant-platform/02a5e2f40d5d4b0'
|
||||
'?iUrl=Ly9oNS5kaWFucGluZy5jb20vL2FwcC9tZXJjaGFudC1iaWxsLXN0YXRpYy9pbmRleC5odG1sIy9wYXltZW50cmVjb3Jk')
|
||||
PAYMENT_LIST_API = 'https://e.dianping.com/gw/smartBill/paymentlist'
|
||||
PAYMENT_DOWNLOAD_API = 'https://e.dianping.com/gw/smartBill/paymentdownload'
|
||||
PAYMENT_HISTORY_API = 'https://e.dianping.com/gw/smartBill/paymenthistory'
|
||||
PAYMENT_FILE_TYPE = 6 # 6 = 打款记录
|
||||
PAYMENT_NAME_KEY = '打款记录'
|
||||
|
||||
# ==================== 收益明细(PC 商户中心 downloadManagement 接口) ====================
|
||||
PROFIT_PAGE_URL = 'https://e.dianping.com/finance/web/payment/download/list'
|
||||
SHOP_API = 'https://e.dianping.com/smartBill/queryAllShopIds'
|
||||
PRODUCT_API = 'https://e.dianping.com/finance/ajax/downloadManagement/productCodeList'
|
||||
PROFIT_REQUEST_API = 'https://e.dianping.com/finance/ajax/downloadManagement/request'
|
||||
PROFIT_LIST_API = 'https://e.dianping.com/finance/ajax/downloadManagement/list'
|
||||
PROFIT_LINK_API = 'https://e.dianping.com/finance/ajax/downloadManagement/downloadLink'
|
||||
PROFIT_FILE_TYPE = 201 # 201 = 收益明细
|
||||
|
||||
# ==================== 台账 ====================
|
||||
WORK_DIR = r'D:\资料\财务\新美大平台核对' # 账单 + 台账统一目录
|
||||
LEDGER_GLOB = '新美大到账统计*.xlsx'
|
||||
LEDGER_SHEET = '金色印象--新美大导出(收)'
|
||||
STAT_SHEET = '新美大核对统计'
|
||||
TIME_COL = '验券/退款/调整时间'
|
||||
DETAIL_GLOB = '团购收益明细_*.xlsx'
|
||||
HEADER_ROW = 2
|
||||
DATA_START_ROW = 3
|
||||
|
||||
# 「新美大核对统计」V/W 列的外部工作簿(与台账历史 62 条链接一致)
|
||||
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
||||
LINK_BOOK = '马敏团购总表'
|
||||
LINK_SHEET = '资金组取数'
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
LOGIN_WAIT = 600 # 等待人工登录(含选商家)超时
|
||||
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
|
||||
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
|
||||
POLL_SECONDS = 2
|
||||
RECORD_SECONDS = 120 # 账单生成后轮询记录的最长时间
|
||||
REUSE_MAX_AGE_MIN = 10 # 账单复用时效:记录生成时间距今 ≤ N 分钟才复用
|
||||
RETRY_MAX = 3
|
||||
HEADLESS = False # 人工登录必须可见浏览器
|
||||
|
||||
# ==================== 共享路径 ====================
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'meituan_cookies.json')
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'meituan_cookies_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'meituan_tokens.json')
|
||||
META_FILE = os.path.join(SESSIONS_DIR, 'meituan_session_meta.json')
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不占用日常 Chrome 配置。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0041')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶。
|
||||
|
||||
登录需要人工操作(账号密码 / 短信 / 扫码 / 选商家),窗口被其它窗口遮挡或最小化时
|
||||
用户容易漏看;置顶保证它一直在最前面。失败仅告警,不影响流程。
|
||||
"""
|
||||
try:
|
||||
page.set.window.full()
|
||||
except Exception as e:
|
||||
log(f'设置窗口全屏失败(忽略):{e}', 'WARN')
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
_set_topmost(page.process_id)
|
||||
except Exception as e:
|
||||
log(f'设置窗口置顶失败(忽略):{e}', 'WARN')
|
||||
|
||||
|
||||
def _set_topmost(pid):
|
||||
"""把指定进程的主窗口设为 HWND_TOPMOST(Win32 SetWindowPos,仅 Windows)。"""
|
||||
if not pid:
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
user32.IsWindowVisible.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
|
||||
hwnds = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def _collect(hwnd, _lparam):
|
||||
if user32.IsWindowVisible(hwnd) and user32.GetWindowTextLengthW(hwnd) > 0:
|
||||
proc = wintypes.DWORD()
|
||||
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(proc))
|
||||
if proc.value == pid:
|
||||
hwnds.append(hwnd)
|
||||
return True
|
||||
|
||||
user32.EnumWindows.argtypes = [ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),
|
||||
wintypes.LPARAM]
|
||||
user32.EnumWindows(_collect, 0)
|
||||
|
||||
user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int,
|
||||
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint]
|
||||
for hwnd in hwnds:
|
||||
user32.SetWindowPos(hwnd, wintypes.HWND(-1), 0, 0, 0, 0, 0x0001 | 0x0002) # NOSIZE | NOMOVE
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def set_debug(on):
|
||||
global _debug
|
||||
_debug = bool(on)
|
||||
|
||||
|
||||
def debug_enabled():
|
||||
return _debug
|
||||
|
||||
|
||||
def log(msg, level='INFO'):
|
||||
text = f'[{time.strftime("%H:%M:%S")}] {msg}'
|
||||
if level == 'DEBUG' and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f'[{level}] {text}')
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:登录态、打款记录与收益明细的下载。"""
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 三张表下载都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0041,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
import os
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/选商家),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR:mtgsig/yodaReady 由页面上的 Yoda(H5guard) SDK 自动补。
|
||||
|
||||
返回 (status:int, text:str)。
|
||||
"""
|
||||
import json as _json
|
||||
body_js = 'null'
|
||||
headers_js = ''
|
||||
if payload is not None:
|
||||
body_js = 'JSON.stringify(' + _json.dumps(payload, ensure_ascii=False) + ')'
|
||||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||||
js = '''
|
||||
try {
|
||||
var x = new XMLHttpRequest();
|
||||
x.open('%s', '%s', false);
|
||||
x.withCredentials = true;
|
||||
%s
|
||||
x.send(%s);
|
||||
return x.status + '||' + String(x.responseText || '');
|
||||
} catch (e) {
|
||||
return 'ERR||' + e;
|
||||
}
|
||||
''' % (method.upper(), url, headers_js, body_js)
|
||||
raw = page.run_js(js)
|
||||
if not raw or '||' not in str(raw):
|
||||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||||
status, _, text = str(raw).partition('||')
|
||||
try:
|
||||
return int(status), text
|
||||
except Exception:
|
||||
return 0, text
|
||||
|
||||
|
||||
def api_json(page, method, url, payload=None):
|
||||
import json as _json
|
||||
status, text = xhr(page, method, url, payload)
|
||||
name = url.split('/')[-1].split('?')[0]
|
||||
if status != 200:
|
||||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||||
return None
|
||||
try:
|
||||
return _json.loads(text)
|
||||
except Exception as e:
|
||||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def download_file(link, save_path):
|
||||
"""S3 预签名 URL 直下(无需 Cookie / mtgsig)。返回字节数,失败 0。"""
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
headers = {
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||||
'Accept': '*/*',
|
||||
}
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
resp = requests.get(link, headers=headers, timeout=300, stream=True)
|
||||
if resp.status_code != 200:
|
||||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
tmp = save_path + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in resp.iter_content(128 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, save_path)
|
||||
size = os.path.getsize(save_path)
|
||||
if size < 1024:
|
||||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
return size
|
||||
except Exception as e:
|
||||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
return 0
|
||||
|
||||
|
||||
def read_xlsx_summary(path):
|
||||
"""读 sheet 名/行列数,确认文件有效。"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(path, read_only=True, data_only=True)
|
||||
ws = wb.worksheets[0]
|
||||
info = {'sheet': ws.title, 'rows': ws.max_row, 'cols': ws.max_column}
|
||||
wb.close()
|
||||
return info
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""美团经营宝登录态:打开官方页面 → 人工登录(含选商家)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
为什么不用 requests 校验:经营宝所有业务接口带 mtgsig 动态签名(页面 H5guard 秒级生成),
|
||||
requests 复刻必然 403。登录态有效性只由浏览器判定,取数也一律在页面上下文发请求。
|
||||
|
||||
实测登录链路(2026-10):
|
||||
ecom.meituan.com → 外壳,未登录也先进这里
|
||||
ecom.meituan.com/meishi → 前端异步鉴权,约 20s 后才跳走,不可当已登录
|
||||
.../bizaccount/login.html → 真·未登录
|
||||
.../bizaccount/biz-choice.html → 账号已登录、待选商家
|
||||
e.dianping.com/app/... → 选完商家进后台(登录完成,dp 商家)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login / biz_choice / backend / other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if config.LOGIN_PAGE_HINT in low or any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
if config.BIZ_CHOICE_HINT in low:
|
||||
return 'biz_choice'
|
||||
if any(h in low for h in config.BACKEND_HINTS):
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _platform_cookie_header(cookies):
|
||||
skip = ('passport', 'certificates', 'report', 'lx', 'dreport')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and any(d in (c.get('domain') or '') for d in ('meituan.com', 'dianping.com'))
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _platform_cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 选商家」。返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = biz_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
|
||||
elif state == 'biz_choice' and time.time() - biz_hint_at > 30:
|
||||
biz_hint_at = time.time()
|
||||
config.log('账号已登录,请在页面上选择要进入的商家(脚本不自动选,避免进错店)')
|
||||
|
||||
if state == 'backend':
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进入商家后台,等待 {config.BACKEND_STABLE}s 确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('又回到登录/选商家页,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page):
|
||||
"""确保 page 已进入商家后台;必要时停在前台等人工登录。"""
|
||||
config.log(f'打开经营宝:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用一个短窗口:profile 里残留会话能直接进后台就不用打扰
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend':
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state in ('login', 'biz_choice'):
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
config.log(f'需要人工登录,最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' + ', '.join(sorted({c.get('name') for c in cookies if c.get('name')})),
|
||||
'WARN')
|
||||
return False, '登录超时(未进入商家后台)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""打款记录下载(h5 账单页,iframe 内 smartBill 三个接口)。
|
||||
|
||||
链路(实测):
|
||||
① 查询 POST /gw/smartBill/paymentlist body{payTime,productCodeList,payStatusList,shopList,pageIndex,pageSize}
|
||||
② 生成 POST /gw/smartBill/paymentdownload body 同上 + downloadFileType=6
|
||||
③ 记录 GET /gw/smartBill/paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6
|
||||
(必须带 downloadFileType + 分页参数,缺了返回 code=500)
|
||||
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
|
||||
|
||||
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
def _find_frame(page, timeout=30):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for f in page.get_frames():
|
||||
try:
|
||||
if 'merchant-bill' in (f.url or ''):
|
||||
return f
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def _history_items(frame):
|
||||
url = (f'{config.PAYMENT_HISTORY_API}?pageIndex=0&pageSize=20'
|
||||
f'&downloadFileType={config.PAYMENT_FILE_TYPE}')
|
||||
data = browser.api_json(frame, 'GET', url) or {}
|
||||
return (data.get('data') or {}).get('details') or []
|
||||
|
||||
|
||||
def _throttle_seconds(msg):
|
||||
import re
|
||||
m = re.search(r'(\d+)\s*秒', msg or '')
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def _age_minutes(add_time):
|
||||
try:
|
||||
dt = datetime.strptime(str(add_time).strip(), '%Y-%m-%d %H:%M:%S')
|
||||
return (datetime.now() - dt).total_seconds() / 60.0
|
||||
except Exception:
|
||||
return 1e9
|
||||
|
||||
|
||||
def download(page, d_from, d_to, save_dir, dry_run=False):
|
||||
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
match_key = d_from
|
||||
|
||||
config.log(f'打开打款记录页:{config.PAYMENT_PAGE_URL}', 'DEBUG')
|
||||
page.get(config.PAYMENT_PAGE_URL)
|
||||
frame = _find_frame(page)
|
||||
if not frame:
|
||||
return {'ok': False, 'message': '未找到账单 iframe(登录态可能已失效)'}
|
||||
config.log(f'账单 iframe:{frame.url}', 'DEBUG')
|
||||
|
||||
# ① 先查询(页面同款顺序:查询出数据后下载按钮才可用)
|
||||
query = {
|
||||
'payTime': f'{d_from},{d_to}',
|
||||
'productCodeList': [], 'payStatusList': [], 'shopList': [],
|
||||
'pageIndex': 0, 'pageSize': 10,
|
||||
}
|
||||
q = browser.api_json(frame, 'POST', config.PAYMENT_LIST_API, query)
|
||||
if q is None:
|
||||
return {'ok': False, 'message': '打款记录查询失败'}
|
||||
qdata = q.get('data') or {}
|
||||
total = qdata.get('totalCount')
|
||||
details = qdata.get('details') or []
|
||||
config.log(f'查询 {d_from}~{d_to}:totalCount={total}')
|
||||
if details:
|
||||
s = details[0]
|
||||
config.log(f' 首条 {s.get("payTime")} | {s.get("productCodeName")} | '
|
||||
f'{s.get("amount")} | {s.get("payStatusName")}')
|
||||
if not total:
|
||||
return {'ok': False, 'message': f'{d_from}~{d_to} 没有打款记录'}
|
||||
|
||||
# ② 已有记录时效内复用
|
||||
before = _history_items(frame)
|
||||
before_ids = {it.get('id') for it in before}
|
||||
target = None
|
||||
cands = [it for it in before
|
||||
if match_key in (it.get('timeInterval') or '') and it.get('downloadLink')]
|
||||
fresh = [it for it in cands if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
|
||||
if fresh and not dry_run:
|
||||
target = fresh[0]
|
||||
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
|
||||
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
|
||||
elif cands:
|
||||
config.log('同区间记录已过期,重新生成以取最新数据')
|
||||
|
||||
# ③ 生成 + 轮询
|
||||
if not target and not dry_run:
|
||||
payload = dict(query)
|
||||
payload.pop('pageIndex', None)
|
||||
payload.pop('pageSize', None)
|
||||
payload['downloadFileType'] = config.PAYMENT_FILE_TYPE
|
||||
config.log(f'提交账单生成:{json.dumps(payload, ensure_ascii=False)}')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
resp = browser.api_json(frame, 'POST', config.PAYMENT_DOWNLOAD_API, payload)
|
||||
if resp and resp.get('code') == 200:
|
||||
config.log('生成任务已受理')
|
||||
break
|
||||
msg = (resp or {}).get('message') or '无响应'
|
||||
wait = _throttle_seconds(msg)
|
||||
if wait and attempt < config.RETRY_MAX:
|
||||
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
|
||||
'WARN')
|
||||
time.sleep(wait + 3)
|
||||
continue
|
||||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||||
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history_items(frame)
|
||||
for it in items:
|
||||
if it.get('id') in before_ids:
|
||||
continue
|
||||
if match_key not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
target = it
|
||||
break
|
||||
if target:
|
||||
break
|
||||
config.log(' 等待账单生成…')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
|
||||
|
||||
if not target:
|
||||
return {'ok': False, 'message': f'{config.RECORD_SECONDS}s 内未拿到可下载记录'}
|
||||
|
||||
link = target.get('downloadLink')
|
||||
if not link:
|
||||
return {'ok': False, 'message': '记录里没有 downloadLink(可能仍在生成)'}
|
||||
|
||||
path = os.path.join(save_dir, f'{config.PAYMENT_NAME_KEY}_{tag}.xlsx')
|
||||
config.log(f'下载 → {path}')
|
||||
size = browser.download_file(link, path)
|
||||
if not size:
|
||||
return {'ok': False, 'message': '打款记录下载失败'}
|
||||
info = browser.read_xlsx_summary(path)
|
||||
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
|
||||
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
|
||||
@@ -0,0 +1,189 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""收益明细下载(PC 商户中心 downloadManagement 一套接口)。
|
||||
|
||||
链路(实测):
|
||||
① 门店 GET /smartBill/queryAllShopIds → data.availableShopIds(0=全部)
|
||||
② 类型 GET /finance/ajax/downloadManagement/productCodeList → [{1,团购},{11,预订}]
|
||||
③ 生成 POST /finance/ajax/downloadManagement/request
|
||||
body{beginDate,endDate,productCodeList,shopIdList,downloadFileType:201}
|
||||
(一次生成团购+预订两个文件,约 30~40 秒内限流一次)
|
||||
④ 记录 GET /finance/ajax/downloadManagement/list?pageSize=20&pageNum=1&beginDate&endDate
|
||||
⑤ 链接 GET /finance/ajax/downloadManagement/downloadLink?id=<记录id>(记录里 downloadLink 为空时)
|
||||
⑥ 下载 mss-shon 预签名 URL(requests 直下)
|
||||
|
||||
复用策略:按业务类型分组取最新一条,**任一类型缺失或过期就整体重新生成**,
|
||||
避免出现「只拿到团购、预订缺失」的半套数据。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
def _throttle_seconds(msg):
|
||||
import re
|
||||
m = re.search(r'(\d+)\s*秒', msg or '')
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def _age_minutes(add_time):
|
||||
try:
|
||||
dt = datetime.strptime(str(add_time).strip(), '%Y-%m-%d %H:%M:%S')
|
||||
return (datetime.now() - dt).total_seconds() / 60.0
|
||||
except Exception:
|
||||
return 1e9
|
||||
|
||||
|
||||
def _history(page, day_from, day_to):
|
||||
url = f'{config.PROFIT_LIST_API}?pageSize=20&pageNum=1&beginDate={day_from}&endDate={day_to}'
|
||||
data = browser.api_json(page, 'GET', url) or {}
|
||||
return data.get('data') or []
|
||||
|
||||
|
||||
def _expect_names(codes):
|
||||
"""勾选的业务类型 → 预期产出的明细名称。"""
|
||||
names = []
|
||||
if 1 in codes:
|
||||
names.append('团购收益明细')
|
||||
if 11 in codes:
|
||||
names.append('预订收益明细')
|
||||
return names
|
||||
|
||||
|
||||
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
||||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||||
|
||||
返回 {ok, paths, message}。
|
||||
"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
|
||||
config.log(f'打开收益明细页:{config.PROFIT_PAGE_URL}', 'DEBUG')
|
||||
page.get(config.PROFIT_PAGE_URL)
|
||||
time.sleep(4)
|
||||
|
||||
# ① 门店 / 业务类型
|
||||
shop_data = browser.api_json(page, 'GET', config.SHOP_API) or {}
|
||||
shop_ids = ((shop_data.get('data') or {}).get('availableShopIds')) or []
|
||||
if not shop_ids:
|
||||
config.log('未取到门店列表,回退 [0](全部)', 'WARN')
|
||||
shop_ids = [0]
|
||||
prod_data = browser.api_json(page, 'GET', config.PRODUCT_API) or {}
|
||||
products = prod_data.get('data') or []
|
||||
all_codes = [p.get('productCode') for p in products if p.get('productCode')] or [1, 11]
|
||||
# 只保留勾选的类型;未指定则全要
|
||||
want = [c for c in (codes or all_codes) if c in all_codes] or all_codes
|
||||
expect = _expect_names(want)
|
||||
config.log(f'门店 {len(shop_ids)} 个;本次下载类型:{json.dumps(products, ensure_ascii=False)}'
|
||||
f' → {expect}')
|
||||
|
||||
# ② 已有记录:按类型完整性 + 时效判断
|
||||
from datetime import date, timedelta
|
||||
list_from = (date.today() - timedelta(days=30)).isoformat()
|
||||
list_to = date.today().isoformat()
|
||||
before = _history(page, list_from, list_to)
|
||||
|
||||
targets = []
|
||||
groups = {}
|
||||
for it in before:
|
||||
if d_from not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
if it.get('downloadStatus') != 2:
|
||||
continue
|
||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
groups.setdefault(key, []).append(it)
|
||||
newest = {k: max(v, key=lambda x: str(x.get('addTime') or '')) for k, v in groups.items()}
|
||||
newest = {k: v for k, v in newest.items() if k in expect} # 只看勾选的类型
|
||||
ages = {k: _age_minutes(v.get('addTime')) for k, v in newest.items()}
|
||||
stale = [k for k, a in ages.items() if a > config.REUSE_MAX_AGE_MIN]
|
||||
if all(name in newest for name in expect) and not stale:
|
||||
targets = list(newest.values())
|
||||
config.log('同区间记录齐全且新鲜,直接复用:' +
|
||||
', '.join(f'{k}({ages[k]:.0f}分钟前)' for k in newest))
|
||||
elif newest:
|
||||
config.log(f'已有记录不完整或过期({len(newest)}/{len(expect)} 类,'
|
||||
f'过期:{",".join(stale) or "无"}),重新生成以取最新数据')
|
||||
|
||||
# ③ 生成
|
||||
if not targets and not dry_run:
|
||||
payload = {
|
||||
'beginDate': d_from,
|
||||
'endDate': d_to,
|
||||
'productCodeList': want,
|
||||
'shopIdList': shop_ids,
|
||||
'downloadFileType': config.PROFIT_FILE_TYPE,
|
||||
}
|
||||
config.log(f'提交生成:{d_from}~{d_to},类型 {want},门店 {len(shop_ids)} 个')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
resp = browser.api_json(page, 'POST', config.PROFIT_REQUEST_API, payload)
|
||||
if resp and resp.get('code') == 200:
|
||||
config.log('生成任务已受理')
|
||||
break
|
||||
msg = (resp or {}).get('message') or '无响应'
|
||||
wait = _throttle_seconds(msg)
|
||||
if wait and attempt < config.RETRY_MAX:
|
||||
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
|
||||
'WARN')
|
||||
time.sleep(wait + 3)
|
||||
continue
|
||||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||||
|
||||
before_ids = {it.get('id') for it in before}
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history(page, list_from, list_to)
|
||||
hits = [it for it in items
|
||||
if it.get('id') not in before_ids and d_from in (it.get('timeInterval') or '')]
|
||||
ready = [it for it in hits if it.get('downloadStatus') == 2]
|
||||
pending = [it for it in hits if it.get('downloadStatus') != 2]
|
||||
if ready:
|
||||
targets = ready
|
||||
if not pending:
|
||||
break
|
||||
config.log(' 已就绪 %d 条,仍有 %d 条生成中(%s)…' % (
|
||||
len(ready), len(pending),
|
||||
', '.join(str(it.get('productCodeName')) for it in pending)))
|
||||
else:
|
||||
config.log(' 等待生成…')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
||||
|
||||
if not targets:
|
||||
return {'ok': False, 'message': f'未拿到可下载的收益明细({config.RECORD_SECONDS}s 内未完成)'}
|
||||
|
||||
# ④ 逐个下载(同类型去重取最新)
|
||||
uniq = {}
|
||||
for it in targets:
|
||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
if expect and key not in expect:
|
||||
continue
|
||||
uniq.setdefault(key, it)
|
||||
|
||||
paths = []
|
||||
for it in uniq.values():
|
||||
name = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
link = it.get('downloadLink') or ''
|
||||
if not link:
|
||||
ld = browser.api_json(page, 'GET', f'{config.PROFIT_LINK_API}?id={it.get("id")}') or {}
|
||||
link = ((ld.get('data') or {}).get('downloadLink')) or ''
|
||||
if not link:
|
||||
config.log(f'{name} 未取到 downloadLink,跳过', 'WARN')
|
||||
continue
|
||||
path = os.path.join(save_dir, f'{name}_{tag}.xlsx')
|
||||
config.log(f'下载 {name} → {path}')
|
||||
size = browser.download_file(link, path)
|
||||
if not size:
|
||||
config.log(f'{name} 下载失败', 'ERROR')
|
||||
continue
|
||||
info = browser.read_xlsx_summary(path)
|
||||
config.log(f' {name} 完成:{size / 1024:.0f} KB | {info}')
|
||||
paths.append(path)
|
||||
|
||||
if not paths:
|
||||
return {'ok': False, 'message': '收益明细全部下载失败'}
|
||||
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""逻辑层:台账增量合并、核对统计 V/W 外部链接。"""
|
||||
@@ -0,0 +1,449 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账增量合并:把收益明细里比台账更新的行追加到「金色印象--新美大导出(收)」。
|
||||
|
||||
规则(业务口径):
|
||||
1. 找最新月份的台账(新美大到账统计YYYY.M月新.xlsx,排除备份文件);
|
||||
2. 取该 sheet「验券/退款/调整时间」列的最大时间;
|
||||
3. 明细里该列 < 最大时间的行剔除,其余按表头对齐追加;
|
||||
4. 从**真实数据末行**的下一行开始写(max_row 被尾部公式空行撑大,不能直接用);
|
||||
5. 台账第 32 列之后(AF~AP)全是公式 —— 几十万行不可能人工下拉,必须由脚本生成:
|
||||
模板行里内联公式直接按行号平移;共享公式(<f t="shared" si="N"/>)先按 si
|
||||
找到同列主定义,再从定义行平移到新行。效果与手工下拉完全一致。
|
||||
|
||||
写入方式:只改目标 sheet 的 XML(清掉尾部空行、在 </sheetData> 前插入新行、更新 dimension),
|
||||
其余部件逐字节拷贝 —— 台账含 5 个透视表 + 62 个外部链接,openpyxl 全量保存会丢透视表,
|
||||
且 645MB 的 sheet 也吃不下内存。
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
|
||||
_NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
_NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
_NS_PKGREL = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
_MONTH_RE = re.compile(r'(\d{4})[.\-年](\d{1,2})\s*月')
|
||||
_CELL_RE = re.compile(rb'<c r="([A-Z]+)(\d+)"([^>]*?)>(.*?)</c>', re.S)
|
||||
_F_RE = re.compile(rb'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
|
||||
|
||||
|
||||
# ==================== 通用小工具 ====================
|
||||
def _to_dt(v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, date):
|
||||
return datetime(v.year, v.month, v.day)
|
||||
s = str(v).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
|
||||
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
|
||||
try:
|
||||
return datetime.strptime(s, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _month_key(path):
|
||||
m = _MONTH_RE.search(os.path.basename(path))
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
|
||||
|
||||
|
||||
def _pick_latest(pattern, by_month=True):
|
||||
"""排除备份文件(`_备份20261027_155650.xlsx` 同样匹配 glob,曾误当成台账)。"""
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')]
|
||||
if not files:
|
||||
return None
|
||||
if by_month:
|
||||
files.sort(key=lambda p: (_month_key(p), os.path.getmtime(p)))
|
||||
else:
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _header_index(header):
|
||||
out = {}
|
||||
for i, v in enumerate(header):
|
||||
if v is None:
|
||||
continue
|
||||
name = str(v).strip()
|
||||
if name and name not in out:
|
||||
out[name] = i
|
||||
return out
|
||||
|
||||
|
||||
def _col_letter(n):
|
||||
s = ''
|
||||
while n > 0:
|
||||
n, r = divmod(n - 1, 26)
|
||||
s = chr(65 + r) + s
|
||||
return s
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _xml_text(v):
|
||||
return (str(v).replace('&', '&').replace('<', '<')
|
||||
.replace('>', '>').replace('"', '"'))
|
||||
|
||||
|
||||
def _cell_xml(col, row, value, style=None):
|
||||
letter = _col_letter(col) if isinstance(col, int) else col
|
||||
ref = f'{letter}{row}'
|
||||
s_attr = f' s="{style}"' if style else ''
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, bool):
|
||||
return f'<c r="{ref}"{s_attr} t="b"><v>{1 if value else 0}</v></c>'
|
||||
if isinstance(value, (int, float)):
|
||||
num = repr(round(float(value), 12)) if isinstance(value, float) else str(value)
|
||||
return f'<c r="{ref}"{s_attr}><v>{num}</v></c>'
|
||||
text = str(value)
|
||||
if text == '':
|
||||
return ''
|
||||
return f'<c r="{ref}"{s_attr} t="inlineStr"><is><t xml:space="preserve">{_xml_text(text)}</t></is></c>'
|
||||
|
||||
|
||||
# ==================== 公式:模板行 + 共享公式 ====================
|
||||
def _parse_shared_defs(chunk):
|
||||
"""共享公式主定义 {si: (定义行, 公式原文)}。
|
||||
|
||||
Excel 把连续行的同款公式存成一组共享公式:只有主定义带公式文本,
|
||||
其余单元格是自闭合的 <f t="shared" si="N"/>。要下拉必须先按 si 找到定义。
|
||||
"""
|
||||
out = {}
|
||||
for m in _CELL_RE.finditer(chunk):
|
||||
row, inner = int(m.group(2)), m.group(4)
|
||||
fm = _F_RE.search(inner)
|
||||
if not fm or b't="shared"' not in fm.group(1):
|
||||
continue
|
||||
text = (fm.group(2) or b'').decode('utf-8', 'replace')
|
||||
if not text.strip():
|
||||
continue
|
||||
sm = re.search(rb'si="(\d+)"', fm.group(1))
|
||||
if sm:
|
||||
out[sm.group(1).decode()] = (row, text)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_template_row(xml_bytes, row_no):
|
||||
"""模板行 {列字母: {'s': 样式, 'f': 内联公式, 'si': 共享公式组号}}。"""
|
||||
text = xml_bytes.decode('utf-8', 'replace')
|
||||
out = {}
|
||||
for m in re.finditer(r'<c r="([A-Z]+)' + str(row_no) + r'"([^>]*?)(/>|>(.*?)</c>)', text, re.S):
|
||||
col, attrs, inner = m.group(1), m.group(2), m.group(4) or ''
|
||||
sm = re.search(r'\bs="(\d+)"', attrs)
|
||||
fm = re.search(r'<f([^>]*?)(?:/>|>(.*?)</f>)', inner, re.S)
|
||||
f_text = si = None
|
||||
if fm:
|
||||
f_text = (fm.group(2) or None)
|
||||
if 't="shared"' in fm.group(1):
|
||||
sim = re.search(r'si="(\d+)"', fm.group(1))
|
||||
si = sim.group(1) if sim else None
|
||||
out[col] = {'s': sm.group(1) if sm else None, 'f': f_text, 'si': si}
|
||||
return out
|
||||
|
||||
|
||||
def _shift_formula(formula, from_row, to_row):
|
||||
"""把公式里的相对行号从 from_row 平移到 to_row($ 锁定的行号不动)。"""
|
||||
if not formula or from_row == to_row:
|
||||
return formula
|
||||
delta = to_row - from_row
|
||||
|
||||
def repl(m):
|
||||
col, lock, row = m.group(1), m.group(2), m.group(3)
|
||||
if lock == '$':
|
||||
return m.group(0)
|
||||
return f'{col}{int(row) + delta}'
|
||||
|
||||
return re.sub(r'(?<![A-Za-z0-9_])([A-Z]{1,3})(\$?)(\d+)', repl, formula)
|
||||
|
||||
|
||||
def _rows_xml(rows, start_row, col_map, tpl=None, tpl_row=None, shared=None):
|
||||
"""构造新行 XML:A~AE 填值,AF~AP 逐行下拉公式(内联公式 + 共享公式)。"""
|
||||
tpl = tpl or {}
|
||||
shared = shared or {}
|
||||
parts = []
|
||||
for i, row in enumerate(rows):
|
||||
r = start_row + i
|
||||
cells = []
|
||||
for didx, lcol in col_map:
|
||||
if didx < len(row):
|
||||
letter = _col_letter(lcol)
|
||||
c = _cell_xml(letter, r, row[didx], (tpl.get(letter) or {}).get('s'))
|
||||
if c:
|
||||
cells.append((lcol, c))
|
||||
for letter, info in tpl.items():
|
||||
cnum = _col_num(letter)
|
||||
if cnum <= 31:
|
||||
continue
|
||||
formula = None
|
||||
if info.get('f'):
|
||||
formula = _shift_formula(info['f'], tpl_row or start_row, r)
|
||||
elif info.get('si') and info['si'] in shared:
|
||||
def_row, text = shared[info['si']]
|
||||
formula = _shift_formula(text, def_row, r)
|
||||
if not formula:
|
||||
continue
|
||||
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
|
||||
cells.append((cnum, f'<c r="{letter}{r}"{s_attr}><f>{formula}</f></c>'))
|
||||
if not cells:
|
||||
continue
|
||||
cells.sort(key=lambda x: x[0])
|
||||
parts.append(f'<row r="{r}">{"".join(c for _, c in cells)}</row>')
|
||||
return ''.join(parts).encode('utf-8')
|
||||
|
||||
|
||||
# ==================== 原生 XML 写入 ====================
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{_NS_MAIN}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{_NS_REL}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for rel in rels.iter(f'{_NS_PKGREL}Relationship'):
|
||||
if rel.get('Id') == rid:
|
||||
t = (rel.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _append_rows_native(path, sheet_name, rows, start_row, col_map, new_max_row,
|
||||
skip_from_row=None, tpl_row=None):
|
||||
"""流式重写目标 sheet:先丢弃尾部空公式行,再在 </sheetData> 前插入带公式的新行。"""
|
||||
tmp = path + '.rebuild.tmp'
|
||||
marker = b'</sheetData>'
|
||||
skip_tag = f'<row r="{skip_from_row}"'.encode() if skip_from_row else None
|
||||
tpl_tag = f'<row r="{tpl_row}"'.encode() if tpl_row else None
|
||||
tpl = None
|
||||
shared_defs = {}
|
||||
cache = {'payload': None}
|
||||
|
||||
def _payload():
|
||||
if cache['payload'] is None:
|
||||
cache['payload'] = _rows_xml(rows, start_row, col_map,
|
||||
tpl=tpl, tpl_row=tpl_row, shared=shared_defs)
|
||||
return cache['payload']
|
||||
|
||||
inserted = False
|
||||
dim_done = False
|
||||
|
||||
with zipfile.ZipFile(path, 'r') as src:
|
||||
sheet_path = _sheet_xml_path(src, sheet_name)
|
||||
if not sheet_path:
|
||||
raise RuntimeError(f'workbook 里找不到 sheet「{sheet_name}」')
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in src.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
with src.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
if info.filename != sheet_path:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
continue
|
||||
|
||||
mode = 'skip' if skip_tag else 'plain'
|
||||
buf = b''
|
||||
while True:
|
||||
chunk = fin.read(4 << 20)
|
||||
if not chunk:
|
||||
if buf:
|
||||
fout.write(buf)
|
||||
break
|
||||
buf += chunk
|
||||
if not dim_done:
|
||||
buf = re.sub(
|
||||
rb'(<dimension ref="[A-Z]+\d+:[A-Z]+)\d+(")',
|
||||
lambda m: m.group(1) + str(new_max_row).encode() + m.group(2),
|
||||
buf, count=1)
|
||||
dim_done = True
|
||||
|
||||
# 模板行在尾部空行之前,只出现一次;就近拿共享公式主定义
|
||||
if tpl is None and tpl_tag:
|
||||
i = buf.find(tpl_tag)
|
||||
if i >= 0:
|
||||
j = buf.find(b'</row>', i)
|
||||
if j >= 0:
|
||||
shared_defs.update(_parse_shared_defs(buf[:i]))
|
||||
tpl = _parse_template_row(buf[i:j + 6], tpl_row)
|
||||
fcols = [c for c, v in tpl.items()
|
||||
if v.get('f') or v.get('si')]
|
||||
config.log(f'模板行 {tpl_row}:{len(tpl)} 个单元格,'
|
||||
f'计算列 {fcols or "无"},'
|
||||
f'计算规则 {len(shared_defs)} 组', 'DEBUG')
|
||||
|
||||
if mode == 'plain':
|
||||
idx = buf.find(marker)
|
||||
if idx == -1:
|
||||
keep = 64
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
continue
|
||||
fout.write(buf[:idx])
|
||||
fout.write(_payload())
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
|
||||
if mode == 'skip':
|
||||
i_skip = buf.find(skip_tag)
|
||||
i_mark = buf.find(marker)
|
||||
if i_mark >= 0 and (i_skip < 0 or i_mark < i_skip):
|
||||
fout.write(buf[:i_mark])
|
||||
fout.write(_payload())
|
||||
fout.write(buf[i_mark:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if i_skip < 0:
|
||||
keep = max(len(skip_tag), len(marker), 512 * 1024)
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
continue
|
||||
fout.write(buf[:i_skip])
|
||||
buf = buf[i_skip:]
|
||||
mode = 'drop'
|
||||
|
||||
idx = buf.find(marker)
|
||||
if idx < 0:
|
||||
buf = buf[-len(marker):]
|
||||
continue
|
||||
fout.write(_payload())
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if not inserted:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
raise RuntimeError('sheet xml 里没找到 </sheetData>,未做任何修改')
|
||||
os.replace(tmp, path)
|
||||
return len(_payload())
|
||||
|
||||
|
||||
def run(dry_run=False):
|
||||
"""执行合并。返回 {ok, appended, start_row, end_row, ledger, message}。"""
|
||||
if not os.path.isdir(config.WORK_DIR):
|
||||
return {'ok': False, 'message': f'目录不存在:{config.WORK_DIR}'}
|
||||
|
||||
ledger = _pick_latest(config.LEDGER_GLOB, by_month=True)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}({_month_key(ledger)})')
|
||||
|
||||
detail = _pick_latest(config.DETAIL_GLOB, by_month=False)
|
||||
if not detail:
|
||||
return {'ok': False, 'message': f'未找到收益明细:{config.DETAIL_GLOB}'}
|
||||
config.log(f'明细:{os.path.basename(detail)}')
|
||||
|
||||
t0 = time.time()
|
||||
wb = load_workbook(ledger, read_only=True, data_only=True)
|
||||
if config.LEDGER_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.LEDGER_SHEET}」'}
|
||||
ws = wb[config.LEDGER_SHEET]
|
||||
total_row = ws.max_row
|
||||
it = ws.iter_rows(values_only=True)
|
||||
next(it)
|
||||
lhead = _header_index(next(it))
|
||||
if config.TIME_COL not in lhead:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账表头缺少「{config.TIME_COL}」'}
|
||||
li = lhead[config.TIME_COL]
|
||||
|
||||
ledger_max = None
|
||||
ledger_rows = 0
|
||||
key_cols = [lhead[c] for c in ('账户名称', '订单号', '券号', config.TIME_COL) if c in lhead]
|
||||
last_data_row = config.HEADER_ROW
|
||||
for i, row in enumerate(it, start=config.DATA_START_ROW):
|
||||
if row is None:
|
||||
continue
|
||||
if key_cols and any(c < len(row) and row[c] not in (None, '') for c in key_cols):
|
||||
last_data_row = i
|
||||
if len(row) <= li:
|
||||
continue
|
||||
dt = _to_dt(row[li])
|
||||
if dt is None:
|
||||
continue
|
||||
ledger_rows += 1
|
||||
if ledger_max is None or dt > ledger_max:
|
||||
ledger_max = dt
|
||||
wb.close()
|
||||
if ledger_max is None:
|
||||
return {'ok': False, 'message': '台账该列没有有效时间'}
|
||||
config.log(f'台账有效行 {ledger_rows},最大时间 {ledger_max},真实末行 {last_data_row}'
|
||||
f'(max_row={total_row},尾部 {total_row - last_data_row} 行是公式撑出的空行)')
|
||||
|
||||
wb2 = load_workbook(detail, read_only=True, data_only=True)
|
||||
ws2 = wb2.worksheets[0]
|
||||
it2 = ws2.iter_rows(values_only=True)
|
||||
next(it2)
|
||||
dhead = _header_index(next(it2))
|
||||
if config.TIME_COL not in dhead:
|
||||
wb2.close()
|
||||
return {'ok': False, 'message': f'明细表头缺少「{config.TIME_COL}」'}
|
||||
di = dhead[config.TIME_COL]
|
||||
|
||||
keep, total, skip_old = [], 0, 0
|
||||
for row in it2:
|
||||
if row is None:
|
||||
continue
|
||||
total += 1
|
||||
dt = _to_dt(row[di]) if len(row) > di else None
|
||||
if dt is None or dt < ledger_max:
|
||||
skip_old += 1
|
||||
continue
|
||||
keep.append(row)
|
||||
wb2.close()
|
||||
config.log(f'明细 {total} 行:保留 {len(keep)},剔除 {skip_old}(耗时 {time.time() - t0:.1f}s)')
|
||||
|
||||
if not keep:
|
||||
return {'ok': True, 'appended': 0, 'message': '明细里没有比台账更新的记录'}
|
||||
|
||||
start_row = last_data_row + 1
|
||||
new_max_row = start_row + len(keep) - 1
|
||||
col_map = [(didx, lhead[name] + 1) for name, didx in dhead.items() if name in lhead]
|
||||
config.log(f'并入范围:台账第 {start_row} ~ {new_max_row} 行')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'appended': 0, 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'[演练] 将追加 {len(keep)} 行'}
|
||||
|
||||
bak = os.path.join(
|
||||
config.WORK_DIR,
|
||||
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||||
shutil.copy2(ledger, bak)
|
||||
config.log(f'已备份 → {os.path.basename(bak)}')
|
||||
|
||||
t1 = time.time()
|
||||
size = _append_rows_native(ledger, config.LEDGER_SHEET, keep, start_row, col_map,
|
||||
new_max_row, skip_from_row=start_row, tpl_row=last_data_row)
|
||||
config.log(f'并入完成:{len(keep)} 行,耗时 {time.time() - t1:.1f}s(数据量 {size / 1024:.0f} KB)')
|
||||
return {'ok': True, 'appended': len(keep), 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'已并入 {len(keep)} 行到台账'}
|
||||
@@ -0,0 +1,282 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「新美大核对统计」按日期补 V/W 列外部链接公式。
|
||||
|
||||
业务口径(从台账既有 62 条链接反推):
|
||||
V = =[N]资金组取数!$B$5 (应收岗-团购统计表-昨日遗留)
|
||||
W = =[N]资金组取数!$B$6 (应收岗-团购统计表-本日遗留)
|
||||
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
|
||||
|
||||
实现:能复用的链接按 target 匹配复用,缺的新增 externalLinkNN.xml + rels +
|
||||
workbook.xml 的 externalReferences + workbook.xml.rels + Content_Types 声明;
|
||||
目标 sheet 只改对应行的 V/W 单元格,其余部件原样拷贝。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
|
||||
_EXTLINK_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<externalLink xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
'<externalBook r:id="rId1"><sheetNames><sheetName val="%s"/></sheetNames>'
|
||||
'<sheetDataSet><sheetData sheetId="0"/></sheetDataSet></externalBook></externalLink>'
|
||||
)
|
||||
_EXTLINK_RELS_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/'
|
||||
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
|
||||
)
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||||
|
||||
|
||||
def _pick_latest(pattern):
|
||||
import glob
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p)]
|
||||
if not files:
|
||||
return None
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _target_path(d):
|
||||
return os.path.join(config.SHARE_ROOT, f'{d.year}年{d.month}月', f'{d.month}.{d.day}',
|
||||
f'{config.LINK_BOOK}{d.month}.{d.day}.xlsx')
|
||||
|
||||
|
||||
def _file_uri(path):
|
||||
"""与既有 rels 一致:file:///\\\\caiwu01\\共享文件夹\\...(XML 属性里反斜杠不转义)。"""
|
||||
return 'file:///' + path
|
||||
|
||||
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{main}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{rel}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for r in rels.iter(f'{pkg}Relationship'):
|
||||
if r.get('Id') == rid:
|
||||
t = (r.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _set_row_cells(row_xml, row_no, cells):
|
||||
keep = []
|
||||
style_default = None
|
||||
for m in _CELL_RE.finditer(row_xml):
|
||||
col = m.group(1)
|
||||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||||
if style_default is None and sm:
|
||||
style_default = sm.group(1)
|
||||
if col in cells:
|
||||
continue
|
||||
keep.append((_col_num(col), m.group(0)))
|
||||
for col, (formula, style) in cells.items():
|
||||
s = style or style_default
|
||||
s_attr = f' s="{s}"' if s else ''
|
||||
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||||
keep.sort(key=lambda x: x[0])
|
||||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||||
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
|
||||
return f'{head}{"".join(c for _, c in keep)}</row>'
|
||||
|
||||
|
||||
def _norm_uri(uri):
|
||||
"""外部链接目标归一化:`file:///\\\\caiwu01\\共享...` → `\\\\caiwu01\\共享...`(小写)。
|
||||
|
||||
比对方是本地路径,不带 file:/// 前缀;不归一会永远匹配不上,
|
||||
导致每次运行都新增一条重复的外部链接。
|
||||
"""
|
||||
u = (uri or '').strip()
|
||||
if u.lower().startswith('file:///'):
|
||||
u = u[len('file:///'):]
|
||||
return u.replace('\\\\', '\\').lower()
|
||||
|
||||
|
||||
def _parse_links(zf):
|
||||
mapping, max_n = {}, 0
|
||||
for name in zf.namelist():
|
||||
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
|
||||
if not m:
|
||||
continue
|
||||
n = int(m.group(1))
|
||||
max_n = max(max_n, n)
|
||||
txt = zf.read(name).decode('utf-8', 'replace')
|
||||
tm = re.search(r'Target="([^"]+)"', txt)
|
||||
if tm:
|
||||
mapping.setdefault(_norm_uri(tm.group(1)), n) # 同路径多条时保留最早那条
|
||||
return mapping, max_n
|
||||
|
||||
|
||||
def run(d_from=None, d_to=None, dry_run=False):
|
||||
"""按日期区间补 V/W。d_from/d_to 为空则取最新「团购收益明细_YYYYMMDD_YYYYMMDD.xlsx」的日期。"""
|
||||
ledger = _pick_latest(config.LEDGER_GLOB)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}')
|
||||
|
||||
if not d_from:
|
||||
detail = _pick_latest(config.DETAIL_GLOB)
|
||||
if detail:
|
||||
m = re.search(r'(\d{8})_(\d{8})', os.path.basename(detail)) or \
|
||||
re.search(r'(\d{8})', os.path.basename(detail))
|
||||
if m:
|
||||
d_from = m.group(1)
|
||||
d_to = m.group(2) if m.lastindex and m.lastindex >= 2 else m.group(1)
|
||||
if not d_from:
|
||||
today = date.today()
|
||||
d_from = (today - timedelta(days=1)).isoformat()
|
||||
d_to = today.isoformat()
|
||||
|
||||
d1 = datetime.strptime(d_from.replace('-', '')[:8], '%Y%m%d').date()
|
||||
d2 = datetime.strptime(str(d_to).replace('-', '')[:8], '%Y%m%d').date()
|
||||
config.log(f'日期区间:{d1} ~ {d2}')
|
||||
|
||||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||||
if config.STAT_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.STAT_SHEET}」'}
|
||||
ws = wb[config.STAT_SHEET]
|
||||
date_rows = {}
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||||
v = row[0]
|
||||
if isinstance(v, datetime):
|
||||
date_rows[v.date()] = i
|
||||
elif isinstance(v, date):
|
||||
date_rows[v] = i
|
||||
wb.close()
|
||||
|
||||
days, day = [], d1
|
||||
while day <= d2:
|
||||
days.append(day)
|
||||
day += timedelta(days=1)
|
||||
skipped = [d for d in days if d not in date_rows]
|
||||
if skipped:
|
||||
config.log(f'核对统计表里没有这些日期行,跳过:{[str(d) for d in skipped]}', 'WARN')
|
||||
days = [d for d in days if d in date_rows]
|
||||
if not days:
|
||||
return {'ok': False, 'message': '没有可处理的日期行'}
|
||||
|
||||
zf = zipfile.ZipFile(ledger)
|
||||
link_map, max_link = _parse_links(zf)
|
||||
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||||
|
||||
plan, need_new = [], []
|
||||
for d in days:
|
||||
path = _target_path(d)
|
||||
if _norm_uri(path) in link_map:
|
||||
plan.append((d, date_rows[d], link_map[_norm_uri(path)], path, '复用'))
|
||||
else:
|
||||
idx = max_link + len(need_new) + 1
|
||||
need_new.append((idx, path, _file_uri(path)))
|
||||
plan.append((d, date_rows[d], idx, path, '新增'))
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
config.log(f' {d} → 第{row_no}行 [{idx}]({mode}){path}')
|
||||
|
||||
if dry_run:
|
||||
zf.close()
|
||||
return {'ok': True, 'rows': [p[1] for p in plan],
|
||||
'message': f'[演练] {len(plan)} 行将更新 V/W,需新增 {len(need_new)} 条外部链接'}
|
||||
|
||||
if not os.path.isdir(config.SHARE_ROOT):
|
||||
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
|
||||
f'恢复后打开 Excel 点「更新链接」即可取值', 'WARN')
|
||||
|
||||
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
|
||||
if not sheet_path:
|
||||
zf.close()
|
||||
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
|
||||
sheet_xml = zf.read(sheet_path).decode('utf-8')
|
||||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
m = re.search(r'<row r="' + str(row_no) + r'"[^>]*>.*?</row>', sheet_xml, re.S)
|
||||
if not m:
|
||||
config.log(f'第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||||
continue
|
||||
# 注意:XML 的 <f> 里放公式正文,不带 Excel 界面上的前导 '='
|
||||
new_row = _set_row_cells(m.group(0), row_no, {
|
||||
'V': (f'[{idx}]{config.LINK_SHEET}!$B$5', None),
|
||||
'W': (f'[{idx}]{config.LINK_SHEET}!$B$6', None),
|
||||
})
|
||||
sheet_xml = sheet_xml[:m.start()] + new_row + sheet_xml[m.end():]
|
||||
config.log(f'{d} 行已补上团购统计表取数链接')
|
||||
|
||||
for idx, path, uri in need_new:
|
||||
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
|
||||
rid = f'rId{rid_num}'
|
||||
wb_rels = wb_rels.replace(
|
||||
'</Relationships>',
|
||||
f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/'
|
||||
f'officeDocument/2006/relationships/externalLink" '
|
||||
f'Target="externalLinks/externalLink{idx}.xml"/></Relationships>')
|
||||
wb_xml = wb_xml.replace('</externalReferences>',
|
||||
f'<externalReference r:id="{rid}"/></externalReferences>')
|
||||
ct_xml = ct_xml.replace(
|
||||
'</Types>',
|
||||
f'<Override PartName="/xl/externalLinks/externalLink{idx}.xml" '
|
||||
f'ContentType="application/vnd.openxmlformats-officedocument.'
|
||||
f'spreadsheetml.externalLink+xml"/></Types>')
|
||||
|
||||
tmp = ledger + '.rebuild.tmp'
|
||||
replace = {
|
||||
sheet_path: sheet_xml.encode('utf-8'),
|
||||
'xl/workbook.xml': wb_xml.encode('utf-8'),
|
||||
'xl/_rels/workbook.xml.rels': wb_rels.encode('utf-8'),
|
||||
'[Content_Types].xml': ct_xml.encode('utf-8'),
|
||||
}
|
||||
new_files = {}
|
||||
for idx, path, uri in need_new:
|
||||
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
|
||||
(_EXTLINK_TPL % config.LINK_SHEET).encode('utf-8')
|
||||
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
|
||||
(_EXTLINK_RELS_TPL % uri).encode('utf-8')
|
||||
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
if info.filename in replace:
|
||||
dst.writestr(zi, replace.pop(info.filename))
|
||||
else:
|
||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
for name, data in list(replace.items()) + list(new_files.items()):
|
||||
dst.writestr(name, data)
|
||||
zf.close()
|
||||
os.replace(tmp, ledger)
|
||||
|
||||
config.log(f'完成:{len(plan)} 行更新 V/W,新增外部链接 {len(need_new)} 条')
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'message': f'核对统计 V/W 已更新 {len(plan)} 行'}
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0041",
|
||||
"name": "新美大平台核对",
|
||||
"version": "1.1.2",
|
||||
"description": "美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、预订收益明细,把新产生的收益按验券时间并入月份台账,并给核对统计表补当天的团购统计表链接。登录一次后可长期复用。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"runTimeoutSeconds": 0,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0041"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"title": "执行过程",
|
||||
"default": "all",
|
||||
"enum": ["all", "download", "reconcile"],
|
||||
"description": "all=下载后核对;download=只下载;reconcile=只核对(不下载)"
|
||||
},
|
||||
"do_download": {
|
||||
"type": "boolean",
|
||||
"title": "下载数据",
|
||||
"default": true,
|
||||
"description": "登录经营宝,把账单下载到本机目录"
|
||||
},
|
||||
"do_reconcile": {
|
||||
"type": "boolean",
|
||||
"title": "更新核对",
|
||||
"default": true,
|
||||
"description": "读本机最新的台账与收益明细,并入台账并更新核对统计,不重新下载"
|
||||
},
|
||||
"pay_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "下载打款记录",
|
||||
"default": true,
|
||||
"description": "平台打款到门店的明细(打款金额、到账银行卡、打款状态、账单周期)"
|
||||
},
|
||||
"pay_date_from": {
|
||||
"type": "string",
|
||||
"title": "打款记录-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"pay_date_to": {
|
||||
"type": "string",
|
||||
"title": "打款记录-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"profit_group": {
|
||||
"type": "boolean",
|
||||
"title": "下载团购收益明细",
|
||||
"default": true,
|
||||
"description": "团购业务的收益明细(券号/订单号、结算价、总收入、技术服务费、渠道佣金)"
|
||||
},
|
||||
"profit_booking": {
|
||||
"type": "boolean",
|
||||
"title": "下载预订收益明细",
|
||||
"default": true,
|
||||
"description": "预订业务的收益明细(无预订业务时为空表)"
|
||||
},
|
||||
"profit_date_from": {
|
||||
"type": "string",
|
||||
"title": "收益明细-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"profit_date_to": {
|
||||
"type": "string",
|
||||
"title": "收益明细-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"run_merge": {
|
||||
"type": "boolean",
|
||||
"title": "并入台账",
|
||||
"default": true,
|
||||
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
||||
},
|
||||
"run_links": {
|
||||
"type": "boolean",
|
||||
"title": "更新核对统计",
|
||||
"default": true,
|
||||
"description": "给核对统计表对应日期的行补上当天团购统计表的取数链接"
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
"title": "只核对不写入",
|
||||
"default": false,
|
||||
"description": "只输出将要并入的行数与将更新的日期,不改动台账"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
openpyxl>=3.1
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>新美大平台核对</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1585
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0041-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 内联提示 -->
|
||||
<div v-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 执行配置(头部含方案工具:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="5" y="4" width="14" height="17" rx="2" />
|
||||
<path d="M9 4V3h6v1" />
|
||||
<path d="m9 13 2 2 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-form label-position="top">
|
||||
<!-- 01 下载内容 -->
|
||||
<section v-show="form.do_download" class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">下载内容</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="打款记录">
|
||||
<el-switch v-model="form.pay_enabled" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="团购收益明细">
|
||||
<el-switch v-model="form.profit_group" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="预订收益明细">
|
||||
<el-switch v-model="form.profit_booking" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="打款记录 日期">
|
||||
<el-date-picker v-model="payRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !form.pay_enabled" />
|
||||
</el-form-item>
|
||||
<el-form-item label="收益明细 日期">
|
||||
<el-date-picker v-model="profitRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !profitOn" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
打款记录:平台打款到门店的明细;收益明细:每笔券号/订单号、结算价、总收入、技术服务费、营销费用、渠道佣金。<br>
|
||||
默认昨天到今天;今天的账单次日才齐,需完整数据请选到昨天。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 执行过程 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">执行过程</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="下载数据">
|
||||
<el-switch v-model="form.do_download" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="更新核对">
|
||||
<el-switch v-model="form.do_reconcile" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
下载数据:登录经营宝,把账单下载到本机目录。<br>
|
||||
更新核对:读本机最新的台账与收益明细,把新记录并入台账并更新核对统计,不重新下载。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 默认日期区间:昨天 ~ 今天
|
||||
function defaultRange() {
|
||||
const today = new Date()
|
||||
const y = new Date(today.getTime() - 86400000)
|
||||
const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
return [fmt(y), fmt(today)]
|
||||
}
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
do_download: true,
|
||||
do_reconcile: true,
|
||||
pay_enabled: true,
|
||||
pay_date_from: '',
|
||||
pay_date_to: '',
|
||||
profit_group: true,
|
||||
profit_booking: true,
|
||||
profit_date_from: '',
|
||||
profit_date_to: '',
|
||||
})
|
||||
|
||||
const {
|
||||
form, loaded, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.do_download && !form.do_reconcile) {
|
||||
ElMessage.warning('请至少勾选一个执行过程(下载数据 / 更新核对)')
|
||||
return false
|
||||
}
|
||||
if (form.do_download && !form.pay_enabled && !form.profit_group && !form.profit_booking) {
|
||||
ElMessage.warning('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
||||
return false
|
||||
}
|
||||
const pairs = [
|
||||
['打款记录', form.pay_date_from, form.pay_date_to],
|
||||
['收益明细', form.profit_date_from, form.profit_date_to],
|
||||
]
|
||||
for (const [label, f, t] of pairs) {
|
||||
const a = (f || '').trim()
|
||||
const b = (t || '').trim()
|
||||
if (a && b && a > b) {
|
||||
ElMessage.warning(`${label}的开始日期不能晚于结束日期`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
},
|
||||
buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
const action = f.do_download && f.do_reconcile ? 'all' : (f.do_download ? 'download' : 'reconcile')
|
||||
return {
|
||||
action,
|
||||
pay_enabled: !!f.pay_enabled,
|
||||
pay_date_from: t(f.pay_date_from),
|
||||
pay_date_to: t(f.pay_date_to),
|
||||
profit_group: !!f.profit_group,
|
||||
profit_booking: !!f.profit_booking,
|
||||
profit_date_from: t(f.profit_date_from),
|
||||
profit_date_to: t(f.profit_date_to),
|
||||
// 核对就是完整流程:并入台账 + 更新核对统计,不做演练
|
||||
run_merge: true,
|
||||
run_links: true,
|
||||
dry_run: false,
|
||||
debug_mode: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function start() {
|
||||
run()
|
||||
}
|
||||
|
||||
const profitOn = computed(() => form.profit_group || form.profit_booking)
|
||||
|
||||
// 日期范围选择器 ↔ 两个字段(plugin.json 仍以 *_date_from/to 为契约,定时任务兼容)
|
||||
function makeRange(getFrom, getTo, setFrom, setTo) {
|
||||
return computed({
|
||||
get: () => {
|
||||
const a = getFrom()
|
||||
const b = getTo()
|
||||
return (a || b) ? [a || null, b || null] : null
|
||||
},
|
||||
set: (v) => {
|
||||
setFrom((v && v[0]) || '')
|
||||
setTo((v && v[1]) || '')
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const payRange = makeRange(
|
||||
() => form.pay_date_from, () => form.pay_date_to,
|
||||
(v) => { form.pay_date_from = v }, (v) => { form.pay_date_to = v },
|
||||
)
|
||||
const profitRange = makeRange(
|
||||
() => form.profit_date_from, () => form.profit_date_to,
|
||||
(v) => { form.profit_date_from = v }, (v) => { form.profit_date_to = v },
|
||||
)
|
||||
|
||||
// 配置加载完成后:日期为空则带出「昨天~今天」
|
||||
watch(loaded, (v) => {
|
||||
if (!v) return
|
||||
const [from, to] = defaultRange()
|
||||
if (!form.pay_date_from && !form.pay_date_to) {
|
||||
form.pay_date_from = from
|
||||
form.pay_date_to = to
|
||||
}
|
||||
if (!form.profit_date_from && !form.profit_date_to) {
|
||||
form.profit_date_from = from
|
||||
form.profit_date_to = to
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
@@ -0,0 +1 @@
|
||||
export const PLUGIN_ID = 'xq0041'
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus).mount('#app')
|
||||
@@ -0,0 +1,523 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v2)
|
||||
- 上半部分:壳子 design token 子集(权威源 desktop/electron-shell/design-app/styles.css)
|
||||
- 中间:Element Plus 变量映射到壳子 token(iframe 内与壳子同一套皮肤)
|
||||
- 下半部分:标准版式骨架(panel / sec / grid / actions),与其它插件保持一致
|
||||
规则:插件内只用 var(--xxx),不写字面色值。
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* ---- 底色与卡面 ---- */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* ---- 描边 ---- */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* ---- 文字四阶 ---- */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* ---- 主色(靛蓝) ---- */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* ---- 语义色 ---- */
|
||||
--good: #0E9F76;
|
||||
--good-soft: #EBF7F2;
|
||||
--good-line: #D3EDE3;
|
||||
--warn: #D98218;
|
||||
--warn-soft: #FDF3E4;
|
||||
--danger: #E5484D;
|
||||
--danger-soft: #FDEDED;
|
||||
--danger-line: #F6D7D8;
|
||||
|
||||
/* ---- 圆角 ---- */
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* ---- 阴影 ---- */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* ---- 字体 ---- */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
|
||||
/* ---- 间距 ---- */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Element Plus → 壳子 token 映射
|
||||
============================================================ */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
基础重置
|
||||
============================================================ */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
页面骨架(与其它插件一致:panel + sec 分区 + grid 栅格 + actions)
|
||||
============================================================ */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
/* 壳子 iframe 外层已有 padding,这里再留一层,避免内容贴着 iframe 边缘 */
|
||||
padding: 8px 16px 24px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ---------- 主容器:无边框平铺,外框由壳子 iframe 提供 ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.panel .el-card__header {
|
||||
padding: 4px 0 16px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel .el-card__body {
|
||||
padding: 16px 0 4px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部:标题 + 方案工具条 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: var(--r-btn);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font: 600 13.5px/1.25 var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 11.5px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good);
|
||||
font-size: 11.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved i {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--good);
|
||||
}
|
||||
|
||||
/* 尚无保存记录:占位,保持卡片头右侧元素对齐 */
|
||||
.saved.is-idle {
|
||||
background: var(--subtle);
|
||||
border-color: var(--line);
|
||||
color: var(--t4);
|
||||
}
|
||||
|
||||
.saved.is-idle i {
|
||||
background: var(--t5);
|
||||
}
|
||||
|
||||
/* ---------- 分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font: 600 11px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font: 600 13px/1.3 var(--f-cn);
|
||||
color: var(--t1);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--line-soft), transparent);
|
||||
}
|
||||
|
||||
/* ---------- 栅格 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
|
||||
/* ---------- 开关栅格:每格 = 名称 + 开关(规范 §5.2 / §7) ---------- */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
|
||||
/* 日期区间与开关行之间留出呼吸 */
|
||||
.grid-date {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
/* 栅格里的控件统一撑满 */
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-date-editor {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
/* ---------- 提示 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.65;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.tip b {
|
||||
color: var(--t2);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- 内联提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-field);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font-size: 12px;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
.notice .n-ico {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.notice.is-warn {
|
||||
background: var(--warn-soft);
|
||||
border-color: rgba(217, 130, 24, .24);
|
||||
color: #8A5B0E;
|
||||
}
|
||||
|
||||
.notice.is-error {
|
||||
background: var(--danger-soft);
|
||||
border-color: var(--danger-line);
|
||||
color: #CC3B40;
|
||||
}
|
||||
|
||||
.notice.is-ok {
|
||||
background: var(--good-soft);
|
||||
border-color: var(--good-line);
|
||||
color: var(--good);
|
||||
}
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.plan .p-tag {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 600;
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.plan .p-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.plan.is-empty .p-text {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
border-top: 1px dashed var(--line);
|
||||
padding-top: 18px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.actions .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* 底部通用操作(恢复参数/保存/恢复默认),不重复画分隔线 */
|
||||
.actions--foot {
|
||||
border-top: none;
|
||||
padding-top: 0;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background .15s, box-shadow .15s, transform .06s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
background: var(--brand-hover);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(1px);
|
||||
box-shadow: var(--sh-brand-sm);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态:进度条 + 一行说明 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: var(--r-sub);
|
||||
background: var(--brand-soft);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__outer {
|
||||
background: rgba(79, 89, 232, .14);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__inner {
|
||||
background: var(--brand);
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font: 600 13px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
font-size: 12px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.runline .pct {
|
||||
font: 600 12px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--brand);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--brand-soft);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try {
|
||||
msg = (await res.json()).detail || msg
|
||||
} catch (_) { /* 保留默认 */ }
|
||||
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
const schemeSel = ref('')
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||
}
|
||||
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
},
|
||||
))
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
try {
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary)
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子托管在 /pui/xq0041/ 下,构建产物输出到插件包 ui/ 目录。
|
||||
// dev 端口 5182(5180/5181 已被 xq0002/xq0047 占用),代理到本机壳子 8799。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0041/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5182,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>新美大平台核对</title>
|
||||
<script type="module" crossorigin src="/pui/xq0041/assets/index-D_F9Lnim.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-ficKgg0s.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,147 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0042 抖音平台核对 —— webhost 场景插件入口。
|
||||
|
||||
当前阶段:登录态获取 + 两类数据自动导出。
|
||||
打开抖音来客 → 人工登录(含验证码/滑块,浏览器里一次性完成,之后复用登录态)
|
||||
→ 按日期区间导出「核销明细」(履约管理订单列表)与「提现记录」(财务导出记录)
|
||||
→ 轮询生成状态 → 下载到本机目录(默认 D:\\资料\\财务\\抖音平台核对)。
|
||||
导出前查该类导出记录,超过保留阈值(界面可配,默认核销 60 / 提现 25)就删最早的。
|
||||
|
||||
接口签名(a_bogus / msToken)由页面 SDK 注入,插件只在页面上下文发请求,不逆向签名。
|
||||
|
||||
待补:并入台账 + 更新核对统计(口径确认后按 xq0041 的分层补齐)。
|
||||
"""
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import browser, douyin_export, douyin_login
|
||||
|
||||
|
||||
def _parse_day(s):
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||
try:
|
||||
return datetime.strptime(str(s).strip(), fmt).date()
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_pair(raw_from, raw_to):
|
||||
"""解析日期区间:都空=昨天~今天;只给一端=单日;起止颠倒自动换序。"""
|
||||
d1 = _parse_day(raw_from) if raw_from else None
|
||||
d2 = _parse_day(raw_to) if raw_to else None
|
||||
if d1 is None and d2 is None:
|
||||
return ((date.today() - timedelta(days=1)).isoformat(), date.today().isoformat())
|
||||
if d1 is None:
|
||||
d1 = d2
|
||||
if d2 is None:
|
||||
d2 = d1
|
||||
if d2 < d1:
|
||||
d1, d2 = d2, d1
|
||||
return d1.isoformat(), d2.isoformat()
|
||||
|
||||
|
||||
def _limit(raw, default):
|
||||
"""导出记录保留阈值:非法/过小则回退默认值。"""
|
||||
try:
|
||||
val = int(str(raw).strip())
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return val if val >= config.RECORD_LIMIT_MIN else default
|
||||
|
||||
|
||||
class Xq0042Plugin(ScenePlugin):
|
||||
id = 'xq0042'
|
||||
name = '抖音平台核对'
|
||||
version = '0.6.2'
|
||||
description = ('抖音来客数据自动导出:登录后按日期区间导出核销明细、提现记录,'
|
||||
'轮询生成完成后下载到本机目录;导出记录超阈值自动删最早的')
|
||||
platform = '' # 插件自带登录(抖音来客 SSO),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0042']
|
||||
permissions = {'platforms': []}
|
||||
fields = {
|
||||
'date_from': {'type': 'string', 'title': '核销时间-开始日期', 'default': ''},
|
||||
'date_to': {'type': 'string', 'title': '核销时间-结束日期', 'default': ''},
|
||||
'withdraw_from': {'type': 'string', 'title': '提现时间-开始日期', 'default': ''},
|
||||
'withdraw_to': {'type': 'string', 'title': '提现时间-结束日期', 'default': ''},
|
||||
'export_verify': {'type': 'boolean', 'title': '导出核销明细', 'default': True},
|
||||
'export_withdraw': {'type': 'boolean', 'title': '导出提现记录', 'default': True},
|
||||
'record_limit_verify': {'type': 'integer', 'title': '核销明细-导出记录保留条数',
|
||||
'default': config.RECORD_LIMIT_VERIFY},
|
||||
'record_limit_withdraw': {'type': 'integer', 'title': '提现记录-导出记录保留条数',
|
||||
'default': config.RECORD_LIMIT_WITHDRAW},
|
||||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
||||
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx):
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(fields.get('debug_mode'))
|
||||
|
||||
v_from, v_to = _resolve_pair(fields.get('date_from'), fields.get('date_to'))
|
||||
w_from, w_to = _resolve_pair(fields.get('withdraw_from'), fields.get('withdraw_to'))
|
||||
save_dir = (str(fields.get('save_dir') or '').strip().strip('"')
|
||||
or config.WORK_DIR)
|
||||
force = bool(fields.get('force_login'))
|
||||
do_verify = fields.get('export_verify', True) is not False
|
||||
do_withdraw = fields.get('export_withdraw', True) is not False
|
||||
if not do_verify and not do_withdraw:
|
||||
raise RuntimeError('请至少勾选一项导出内容(核销明细 / 提现记录)')
|
||||
limit_verify = _limit(fields.get('record_limit_verify'), config.RECORD_LIMIT_VERIFY)
|
||||
limit_withdraw = _limit(fields.get('record_limit_withdraw'), config.RECORD_LIMIT_WITHDRAW)
|
||||
|
||||
kinds = [k for k, on in (('核销明细', do_verify), ('提现记录', do_withdraw)) if on]
|
||||
ranges = []
|
||||
if do_verify:
|
||||
ranges.append(f'核销 {v_from} ~ {v_to}')
|
||||
if do_withdraw:
|
||||
ranges.append(f'提现 {w_from} ~ {w_to}')
|
||||
config.log(f'本次执行:导出{"、".join(kinds)}({";".join(ranges)})→ {save_dir}'
|
||||
+ ('(强制重新登录)' if force else ''))
|
||||
config.log(f'导出记录保留条数:核销明细 {limit_verify}、提现记录 {limit_withdraw}')
|
||||
config.progress(5)
|
||||
|
||||
page = browser.open_page()
|
||||
results = {}
|
||||
try:
|
||||
ok, msg = douyin_login.ensure_login(page, force=force)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
config.progress(30)
|
||||
|
||||
if do_verify:
|
||||
results['核销明细'] = douyin_export.run(page, v_from, v_to, save_dir,
|
||||
limit_verify)
|
||||
config.progress(65)
|
||||
if do_withdraw:
|
||||
results['提现记录'] = douyin_export.run_withdraw(page, w_from, w_to,
|
||||
save_dir, limit_withdraw)
|
||||
config.progress(95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
|
||||
failed = {k: v.get('message') for k, v in results.items() if not v.get('ok')}
|
||||
ok_parts = [v.get('message') for v in results.values() if v.get('ok')]
|
||||
path = next((v.get('path') for v in results.values() if v.get('ok')), '')
|
||||
if failed:
|
||||
detail = ';'.join(f'{k}失败:{m}' for k, m in failed.items())
|
||||
raise RuntimeError(('已完成:' + ';'.join(ok_parts) + '。' if ok_parts else '')
|
||||
+ detail)
|
||||
config.progress(100)
|
||||
return {
|
||||
'summary': f'{";".join(ranges)}:' + ';'.join(ok_parts),
|
||||
'detail': {'date_from': v_from, 'date_to': v_to,
|
||||
'withdraw_from': w_from, 'withdraw_to': w_to,
|
||||
'login': msg, 'results': results},
|
||||
'path': path,
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0042Plugin())
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
输出 dist-plugin/xq0042_v<版本>.zip,zip 根含 plugin.json。
|
||||
排除:ui-src、__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0042 抖音平台核对\\_pack.py"
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0042 抖音平台核对 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
各业务模块统一经 config.log() / config.progress() 输出,由 run() 启动时注入 ctx。
|
||||
|
||||
当前阶段只做「登录态获取与验证」(抖音来客)。
|
||||
2026-10-28 实测:
|
||||
登录页 https://life.douyin.com/p/login
|
||||
首页 https://life.douyin.com/p/home[?groupid=...]
|
||||
会话票据种在 .life.douyin.com:sessionid_ls / sessionid_ss_ls / sid_tt_ls / sid_guard_ls
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
# ==================== 平台:抖音来客 ====================
|
||||
HOME_URL = 'https://life.douyin.com/p/home'
|
||||
LOGIN_URL = 'https://life.douyin.com/p/login'
|
||||
|
||||
BACKEND_HOST = 'life.douyin.com' # 来客后台主域
|
||||
LOGIN_PAGE_HINTS = ('/p/login', 'login') # 登录页路径(同域下的排除项)
|
||||
PASSPORT_HINTS = ( # 统一登录/账号域
|
||||
'sso.douyin.com', 'passport.douyin.com', 'open.douyin.com',
|
||||
'douyin.com/login', 'account.douyin.com',
|
||||
)
|
||||
|
||||
# 登录票据 Cookie:名字带分区后缀 `_ls`(老版本/无分区时是裸名),按前缀匹配
|
||||
SESSION_COOKIE_PREFIXES = ('sessionid', 'sid_tt', 'sid_guard', 'sid_ucp')
|
||||
|
||||
# 票据候选(子串匹配,仅用于日志摘要)与埋点排除项
|
||||
TICKET_KEY_HINTS = ('session', 'sid', 'token', 'ticket', 'userid', 'user_id')
|
||||
IGNORE_KEY_HINTS = (
|
||||
'ttwid', 'mstoken', 'csrf', '_ga', '_gid', '__ac', 's_v_web_id', 'tt_scid',
|
||||
'monitor', 'abtest', 'odin', 'store-region', 'passport_csrf',
|
||||
)
|
||||
|
||||
# ==================== 核销明细导出(履约管理 → 导出工具) ====================
|
||||
# 实测 2026-10-28:导出工具弹窗「核销明细」提交的就是这个接口,
|
||||
# 返回 downloadStruct(download_id + status=1 生成中),完成后在「导出记录」里出现。
|
||||
ORDER_URL = ('https://life.douyin.com/p/liteapp/fulfillment-admin/order-list'
|
||||
'?admin_industry=45&groupid=1732612560882691')
|
||||
ORDER_GROUP_ID = '1732612560882691' # 当前账号(URL 里取不到时的兜底)
|
||||
ROOT_LIFE_ACCOUNT_ID = '7044832462517569568' # 主账号 ID(localStorage 解析失败时的兜底)
|
||||
VERIFY_EXPORT_API = ('https://life.douyin.com/life/trade_view/v1/management/verify/query/'
|
||||
'download_verify_record_list')
|
||||
DOWNLOAD_LIST_API = 'https://life.douyin.com/life/settle/v1/download/list/'
|
||||
DOWNLOAD_TYPE = 10031001 # 导出记录页(财务 → 导出记录)
|
||||
VERIFY_VIEW_TYPE = 'common_view_verify_record'
|
||||
VERIFY_SHOW_REASON = 'catering_comprehensive_coupon'
|
||||
# 商品类型过滤(与页面默认一致:团购券/次卡等全部可核销类型)
|
||||
VERIFY_PRODUCT_OPTIONS = ['1', '11', '15', '2601', '26', '130011', '2201', '1801', '1802',
|
||||
'1803', '1804', '2901', '1501', '2801', '100112', '110301', '1502']
|
||||
RECORD_SECONDS = 180 # 导出任务生成超时(秒)
|
||||
RECORD_POLL = 10 # 轮询生成状态的间隔(秒)
|
||||
|
||||
# ==================== 提现记录(余额提现记录)导出 ====================
|
||||
# 实测 2026-10-28:财务 → 导出记录(/p/fulfillsettle/export_records/16)点「导出」,
|
||||
# 走的是 GET withdraw/capital/download_records_list,时间参数为秒级时间戳;
|
||||
# 记录列表 download_type=16,文件名形如「资金账户交易提现记录_起_止.xlsx」。
|
||||
WITHDRAW_URL = ('https://life.douyin.com/p/fulfillsettle/export_records/16'
|
||||
'?groupid=1732612560882691')
|
||||
WITHDRAW_EXPORT_API = ('https://life.douyin.com/life/settle/v1/withdraw/capital/'
|
||||
'download_records_list/')
|
||||
WITHDRAW_DOWNLOAD_TYPE = 16 # 余额提现记录
|
||||
WITHDRAW_FUND_ACCOUNT_TYPE = 6 # 资金账户类型(页面默认)
|
||||
DELETE_API = 'https://life.douyin.com/life/settle/v1/download/delete/'
|
||||
|
||||
# 平台限制:提现记录类导出最多 30 条,满了再发起会返回
|
||||
# 224000002「最多仅支持30个待下载文件,请删除部分历史文件后重试」。
|
||||
# 因此每次导出前先查列表:记录数超过「保留阈值」就删最早的、只留最新 N 条。
|
||||
# 阈值可在插件界面手动改(record_limit_verify / record_limit_withdraw)。
|
||||
RECORD_LIMIT_VERIFY = 60 # 核销明细:该类列表暂未遇到 30 条限制,先记 60
|
||||
RECORD_LIMIT_WITHDRAW = 25 # 提现记录:平台 30 条硬上限,留 5 条余量
|
||||
RECORD_LIMIT_CODE = 224000002 # 「最多仅支持30个待下载文件」的业务错误码
|
||||
RECORD_LIMIT_MIN = 5 # 阈值下限:防止误填过小导致批量删记录
|
||||
|
||||
# 删除导出记录要限流:连续删除间隔随机抖动,单次运行设上限,避免被平台风控判定异常
|
||||
DELETE_MIN_INTERVAL = 1.0 # 两条删除之间的最短间隔(秒)
|
||||
DELETE_MAX_INTERVAL = 2.0 # 最长间隔(秒),实际取值在两者之间随机
|
||||
DELETE_MAX_PER_RUN = 20 # 单次运行最多删几条,超出部分留到下次运行
|
||||
|
||||
# ==================== 输出目录 ====================
|
||||
WORK_DIR = r'D:\资料\财务\抖音平台核对' # 核销明细 + 台账统一目录
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
LOGIN_WAIT = 600 # 等待人工登录(含验证码/滑块)超时
|
||||
BACKEND_STABLE = 15 # 后台页连续稳定秒数(登录后有短暂回跳登录页的现象)
|
||||
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
|
||||
POLL_SECONDS = 2
|
||||
RETRY_MAX = 3
|
||||
HEADLESS = False # 人工登录必须可见浏览器
|
||||
|
||||
# ==================== 共享路径 ====================
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'douyin_cookies.json')
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'douyin_cookies_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'douyin_tokens.json')
|
||||
META_FILE = os.path.join(SESSIONS_DIR, 'douyin_session_meta.json')
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不占用日常 Chrome 配置。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0042')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶(登录要人工操作,避免被其它窗口挡住)。"""
|
||||
try:
|
||||
page.set.window.full()
|
||||
except Exception as e:
|
||||
log(f'设置窗口全屏失败(忽略):{e}', 'WARN')
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
_set_topmost(page.process_id)
|
||||
except Exception as e:
|
||||
log(f'设置窗口置顶失败(忽略):{e}', 'WARN')
|
||||
|
||||
|
||||
def _set_topmost(pid):
|
||||
"""把指定进程的主窗口设为 HWND_TOPMOST(Win32 SetWindowPos,仅 Windows)。"""
|
||||
if not pid:
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
user32.IsWindowVisible.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
|
||||
hwnds = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def _collect(hwnd, _lparam):
|
||||
if user32.IsWindowVisible(hwnd) and user32.GetWindowTextLengthW(hwnd) > 0:
|
||||
proc = wintypes.DWORD()
|
||||
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(proc))
|
||||
if proc.value == pid:
|
||||
hwnds.append(hwnd)
|
||||
return True
|
||||
|
||||
user32.EnumWindows.argtypes = [ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),
|
||||
wintypes.LPARAM]
|
||||
user32.EnumWindows(_collect, 0)
|
||||
|
||||
user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int,
|
||||
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint]
|
||||
for hwnd in hwnds:
|
||||
user32.SetWindowPos(hwnd, wintypes.HWND(-1), 0, 0, 0, 0, 0x0001 | 0x0002) # NOSIZE | NOMOVE
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def set_debug(on):
|
||||
global _debug
|
||||
_debug = bool(on)
|
||||
|
||||
|
||||
def debug_enabled():
|
||||
return _debug
|
||||
|
||||
|
||||
def log(msg, level='INFO'):
|
||||
text = f'[{time.strftime("%H:%M:%S")}] {msg}'
|
||||
if level == 'DEBUG' and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f'[{level}] {text}')
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0042 抖音平台核对 - 数据层。"""
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 后续取数都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0042,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
import os
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/滑块),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,403 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出模块:核销明细 + 提现记录(余额提现记录)。
|
||||
|
||||
实测(2026-10-28):
|
||||
|
||||
核销明细(履约管理订单列表 → 导出工具)
|
||||
创建:POST /life/trade_view/v1/management/verify/query/download_verify_record_list
|
||||
body.condition.query_conditions = [商品类型 product_option, 核销时间 verify_time(秒级)]
|
||||
→ data.downloadStruct{download_id, file_name, status=1}
|
||||
轮询:GET /life/settle/v1/download/list/?download_type=10031001
|
||||
|
||||
提现记录(财务 → 导出记录 /p/fulfillsettle/export_records/16)
|
||||
创建:GET /life/settle/v1/withdraw/capital/download_records_list/?start_date=&end_date=
|
||||
轮询:GET /life/settle/v1/download/list/?download_type=16
|
||||
→ download_infos[] 里 status=2 表示生成完成,file_url 为预签名地址
|
||||
|
||||
公共约束
|
||||
平台同类导出记录最多 30 条,满了创建会返回 224000002;
|
||||
因此导出前先查列表,超限就删最早的(POST /life/settle/v1/download/delete/)。
|
||||
下载:file_url 直接 requests 取(带签名,不需要 Cookie)。
|
||||
|
||||
签名参数(a_bogus / msToken)由页面 SDK 注入,所以请求都在页面上下文里发。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR,返回 (status, text)。"""
|
||||
body_js = 'null'
|
||||
headers_js = ''
|
||||
if payload is not None:
|
||||
body_js = 'JSON.stringify(' + json.dumps(payload, ensure_ascii=False) + ')'
|
||||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||||
js = '''
|
||||
try {
|
||||
var x = new XMLHttpRequest();
|
||||
x.open('%s', '%s', false);
|
||||
x.withCredentials = true;
|
||||
%s
|
||||
x.send(%s);
|
||||
return x.status + '||' + String(x.responseText || '');
|
||||
} catch (e) {
|
||||
return 'ERR||' + e;
|
||||
}
|
||||
''' % (method.upper(), url, headers_js, body_js)
|
||||
raw = page.run_js(js)
|
||||
if not raw or '||' not in str(raw):
|
||||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||||
status, _, text = str(raw).partition('||')
|
||||
try:
|
||||
return int(status), text
|
||||
except Exception:
|
||||
return 0, text
|
||||
|
||||
|
||||
def _api_json(page, method, url, payload=None):
|
||||
status, text = _xhr(page, method, url, payload)
|
||||
name = url.split('/')[-1].split('?')[0]
|
||||
if status != 200:
|
||||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||||
return None
|
||||
try:
|
||||
return json.loads(text)
|
||||
except Exception as e:
|
||||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def _account_id(page):
|
||||
"""root_life_account_id:页面 localStorage 里是 {用户id: 主账号id} 的 JSON 映射,
|
||||
取映射值;读不到/解析失败用配置兜底。"""
|
||||
try:
|
||||
val = page.run_js("return localStorage.getItem('root_life_account_id') || '';")
|
||||
text = str(val or '').strip()
|
||||
if text:
|
||||
try:
|
||||
obj = json.loads(text)
|
||||
if isinstance(obj, dict) and obj:
|
||||
return str(list(obj.values())[0])
|
||||
if isinstance(obj, str) and obj:
|
||||
return obj.strip()
|
||||
except Exception:
|
||||
return text.strip('"')
|
||||
except Exception:
|
||||
pass
|
||||
return config.ROOT_LIFE_ACCOUNT_ID
|
||||
|
||||
|
||||
def _group_id(page):
|
||||
"""groupid 从当前 URL 里取(?groupid=...),取不到用配置兜底。"""
|
||||
url = page.url or ''
|
||||
if 'groupid=' in url:
|
||||
val = url.split('groupid=', 1)[1].split('&', 1)[0]
|
||||
if val.isdigit():
|
||||
return val
|
||||
return config.ORDER_GROUP_ID
|
||||
|
||||
|
||||
def _ensure_page(page, url, hint, label):
|
||||
"""切到导出所在页面(同域上下文,SDK 才会给请求签名)。"""
|
||||
target = url.replace(config.ORDER_GROUP_ID, _group_id(page))
|
||||
if hint not in (page.url or ''):
|
||||
config.log(f'打开{label}页面')
|
||||
page.get(target)
|
||||
try:
|
||||
page.wait.doc_loaded(timeout=20)
|
||||
except Exception:
|
||||
time.sleep(5)
|
||||
# SPA 首屏文档加载完之后前端才注入签名 SDK,留一点时间再发业务请求
|
||||
time.sleep(2)
|
||||
return target
|
||||
|
||||
|
||||
def _ensure_order_page(page):
|
||||
return _ensure_page(page, config.ORDER_URL,
|
||||
'fulfillment-admin/order-list', '履约管理订单列表')
|
||||
|
||||
|
||||
def _ensure_withdraw_page(page):
|
||||
return _ensure_page(page, config.WITHDRAW_URL,
|
||||
'fulfillsettle/export_records', '提现记录')
|
||||
|
||||
|
||||
def _list_records(page, download_type):
|
||||
"""查某类导出记录列表(新的在前)。"""
|
||||
aid = _account_id(page)
|
||||
url = (f'{config.DOWNLOAD_LIST_API}?download_type={download_type}'
|
||||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||||
data = _api_json(page, 'GET', url)
|
||||
return ((data or {}).get('download_infos') or [])
|
||||
|
||||
|
||||
def _delete_record(page, download_id):
|
||||
"""删除单条导出记录。"""
|
||||
aid = _account_id(page)
|
||||
url = config.DELETE_API + (f'?root_life_account_id={aid}' if aid else '')
|
||||
data = _api_json(page, 'POST', url, {'download_id': str(download_id)})
|
||||
base = ((data or {}).get('BaseResp') or {})
|
||||
return data is not None and base.get('StatusCode', -1) == 0
|
||||
|
||||
|
||||
def _delete_oldest(page, download_type, count, infos=None):
|
||||
"""删掉最早的 count 条导出记录(按 generate_start_time 升序)。返回删除条数。
|
||||
|
||||
限流:两条之间随机间隔 DELETE_MIN_INTERVAL ~ DELETE_MAX_INTERVAL 秒,
|
||||
单次运行最多删 DELETE_MAX_PER_RUN 条,避免短时间连续删除触发风控。
|
||||
"""
|
||||
if count <= 0:
|
||||
return 0
|
||||
limit = config.DELETE_MAX_PER_RUN
|
||||
if count > limit:
|
||||
config.log(f'本次只删最早的 {limit} 条(单次上限),其余留到下次运行', 'WARN')
|
||||
count = limit
|
||||
if infos is None:
|
||||
infos = _list_records(page, download_type)
|
||||
if not infos:
|
||||
return 0
|
||||
oldest_first = sorted(infos, key=lambda x: int(x.get('generate_start_time') or 0))[:int(count)]
|
||||
removed = 0
|
||||
for idx, rec in enumerate(oldest_first):
|
||||
did = rec.get('download_id')
|
||||
if not did:
|
||||
continue
|
||||
if idx or removed:
|
||||
pause = random.uniform(config.DELETE_MIN_INTERVAL, config.DELETE_MAX_INTERVAL)
|
||||
config.log(f'限流等待 {pause:.1f}s 再删下一条', 'DEBUG')
|
||||
time.sleep(pause)
|
||||
name = rec.get('file_name') or ''
|
||||
if _delete_record(page, did):
|
||||
removed += 1
|
||||
config.log(f'删除最早导出记录:{name}({did})')
|
||||
else:
|
||||
config.log(f'删除导出记录失败:{name}({did})', 'WARN')
|
||||
return removed
|
||||
|
||||
|
||||
def _ensure_capacity(page, download_type, limit):
|
||||
"""记录数超过保留阈值时,删最早的、只保留最新 limit 条。返回删除条数。"""
|
||||
infos = _list_records(page, download_type)
|
||||
total = len(infos)
|
||||
if total <= limit:
|
||||
config.log(f'导出记录 {total} 条(保留阈值 {limit}),无需清理', 'DEBUG')
|
||||
return 0
|
||||
config.log(f'导出记录 {total} 条,超过保留阈值 {limit},删除最早的 {total - limit} 条')
|
||||
return _delete_oldest(page, download_type, total - limit, infos)
|
||||
|
||||
|
||||
def _create_export(page, start_ts, end_ts):
|
||||
"""发起核销明细导出,返回 downloadStruct(含 download_id / file_name)。"""
|
||||
aid = _account_id(page)
|
||||
url = config.VERIFY_EXPORT_API + (f'?root_life_account_id={aid}' if aid else '')
|
||||
payload = {
|
||||
'condition': {
|
||||
'query_type': 101,
|
||||
'query_conditions': [
|
||||
{'column_name': 'product_option',
|
||||
'params': list(config.VERIFY_PRODUCT_OPTIONS), 'query_type': 9},
|
||||
{'column_name': 'verify_time',
|
||||
'params': [str(int(start_ts)), str(int(end_ts))], 'query_type': 12},
|
||||
],
|
||||
},
|
||||
'is_app': False,
|
||||
'show_reason': config.VERIFY_SHOW_REASON,
|
||||
'view_type': config.VERIFY_VIEW_TYPE,
|
||||
'download_field_option': 1,
|
||||
'permission_common_param': {},
|
||||
}
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
data = _api_json(page, 'POST', url, payload)
|
||||
if data is None:
|
||||
config.log(f'发起导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||||
time.sleep(3)
|
||||
continue
|
||||
base = (data.get('BaseResp') or {})
|
||||
struct = ((data.get('data') or {}).get('downloadStruct') or {})
|
||||
code = base.get('StatusCode')
|
||||
if code == 0 and struct.get('download_id'):
|
||||
return struct
|
||||
if code == config.RECORD_LIMIT_CODE:
|
||||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||||
_delete_oldest(page, config.DOWNLOAD_TYPE, 5)
|
||||
continue
|
||||
# 业务错误重试不会变好(如鉴权失败),直接返回,避免重复创建导出任务
|
||||
config.log(f'发起导出失败:{base.get("StatusMessage") or data}', 'WARN')
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _create_withdraw(page, start_ts, end_ts):
|
||||
"""发起提现记录导出,返回 (ok, 说明)。"""
|
||||
aid = _account_id(page)
|
||||
url = (f'{config.WITHDRAW_EXPORT_API}?life_account_id_list='
|
||||
f'&start_date={int(start_ts)}&end_date={int(end_ts)}&status_array='
|
||||
f'&fund_account_type_list={config.WITHDRAW_FUND_ACCOUNT_TYPE}'
|
||||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||||
msg = ''
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
data = _api_json(page, 'GET', url)
|
||||
if data is None:
|
||||
config.log(f'发起提现记录导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||||
time.sleep(3)
|
||||
continue
|
||||
code = data.get('status_code')
|
||||
base = (data.get('BaseResp') or {})
|
||||
if code == 0:
|
||||
return True, 'ok'
|
||||
msg = data.get('status_msg') or base.get('StatusMessage') or str(data)
|
||||
if code == config.RECORD_LIMIT_CODE:
|
||||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||||
_delete_oldest(page, config.WITHDRAW_DOWNLOAD_TYPE, 5)
|
||||
continue
|
||||
# 业务错误重试不会变好,直接返回,避免重复创建导出任务
|
||||
return False, msg
|
||||
return False, msg or '网络异常,未拿到导出响应'
|
||||
|
||||
|
||||
def _wait_record(page, download_type, match):
|
||||
"""轮询导出记录,等 status=2(生成完成)后返回记录;match(rec) 用来认本次任务。"""
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
last_status = None
|
||||
while time.time() < deadline:
|
||||
infos = _list_records(page, download_type)
|
||||
hit = next((x for x in infos if match(x)), None)
|
||||
if hit:
|
||||
status = hit.get('status')
|
||||
if status != last_status:
|
||||
last_status = status
|
||||
config.log(f'导出任务状态={status}({hit.get("file_name")})')
|
||||
if status == 2 and hit.get('file_url'):
|
||||
return hit
|
||||
if status not in (1, 2):
|
||||
config.log(f'导出任务异常:{hit}', 'WARN')
|
||||
return None
|
||||
else:
|
||||
config.log('导出记录里还没出现本次任务,继续等…', 'DEBUG')
|
||||
time.sleep(config.RECORD_POLL)
|
||||
config.log(f'等待导出生成超时({config.RECORD_SECONDS}s)', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def _download(file_url, save_path):
|
||||
"""预签名地址直下,返回字节数(失败 0)。"""
|
||||
headers = {
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||||
'Accept': '*/*',
|
||||
}
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
resp = requests.get(file_url, headers=headers, timeout=300, stream=True)
|
||||
if resp.status_code != 200:
|
||||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
tmp = save_path + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in resp.iter_content(128 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, save_path)
|
||||
size = os.path.getsize(save_path)
|
||||
if size < 1024:
|
||||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||||
try:
|
||||
os.remove(save_path)
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(2)
|
||||
continue
|
||||
return size
|
||||
except Exception as e:
|
||||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
return 0
|
||||
|
||||
|
||||
def _day_bounds(date_from, date_to):
|
||||
"""自然日区间 → 秒级时间戳(00:00:00 ~ 23:59:59)。"""
|
||||
start_ts = int(time.mktime(time.strptime(date_from + ' 00:00:00', '%Y-%m-%d %H:%M:%S')))
|
||||
end_ts = int(time.mktime(time.strptime(date_to + ' 23:59:59', '%Y-%m-%d %H:%M:%S')))
|
||||
return start_ts, end_ts
|
||||
|
||||
|
||||
def _save_record(record, save_dir, default_name, label):
|
||||
"""把生成好的记录下载落盘,返回统一结果 dict。"""
|
||||
download_id = str(record.get('download_id') or '')
|
||||
file_name = record.get('file_name') or default_name
|
||||
safe_name = str(file_name).replace('/', '_').replace('\\', '_')
|
||||
save_path = os.path.join(save_dir, safe_name)
|
||||
size = _download(record.get('file_url'), save_path)
|
||||
if not size:
|
||||
return {'ok': False, 'message': f'{label}文件下载失败', 'path': '',
|
||||
'download_id': download_id, 'file_name': safe_name}
|
||||
config.log(f'已下载:{save_path}({size / 1024:.0f} KB)')
|
||||
return {'ok': True, 'message': f'{label}已导出:{safe_name}', 'path': save_path,
|
||||
'download_id': download_id, 'file_name': safe_name, 'size': size}
|
||||
|
||||
|
||||
def run(page, date_from, date_to, save_dir=None, record_limit=None):
|
||||
"""导出指定「核销时间」区间的核销明细并下载。
|
||||
|
||||
date_from/date_to:YYYY-MM-DD;核销时间按自然日取整(00:00:00 ~ 23:59:59)。
|
||||
record_limit:导出记录保留条数(超出则先删最早的),默认 config.RECORD_LIMIT_VERIFY。
|
||||
返回 {ok, message, path, download_id, file_name}
|
||||
"""
|
||||
save_dir = save_dir or config.WORK_DIR
|
||||
limit = int(record_limit or config.RECORD_LIMIT_VERIFY)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||||
|
||||
_ensure_order_page(page)
|
||||
config.log(f'发起核销明细导出:核销时间 {date_from} ~ {date_to}')
|
||||
_ensure_capacity(page, config.DOWNLOAD_TYPE, limit)
|
||||
struct = _create_export(page, start_ts, end_ts)
|
||||
if not struct:
|
||||
return {'ok': False, 'message': '发起导出失败(接口未返回 download_id)', 'path': ''}
|
||||
download_id = str(struct.get('download_id'))
|
||||
file_name = struct.get('file_name') or f'核销明细_{date_from}_{date_to}.xlsx'
|
||||
config.log(f'导出任务已创建:download_id={download_id},文件名={file_name}')
|
||||
|
||||
record = _wait_record(page, config.DOWNLOAD_TYPE,
|
||||
lambda x: str(x.get('download_id')) == download_id)
|
||||
if not record:
|
||||
return {'ok': False, 'message': '导出任务未生成完成', 'path': '',
|
||||
'download_id': download_id, 'file_name': file_name}
|
||||
return _save_record(record, save_dir, file_name, '核销明细')
|
||||
|
||||
|
||||
def run_withdraw(page, date_from, date_to, save_dir=None, record_limit=None):
|
||||
"""导出指定区间的「提现记录」(资金账户交易提现记录)并下载。
|
||||
|
||||
该接口不回 download_id,创建后按 generate_start_time 找最新那条记录。
|
||||
record_limit:导出记录保留条数,默认 config.RECORD_LIMIT_WITHDRAW。
|
||||
"""
|
||||
save_dir = save_dir or config.WORK_DIR
|
||||
limit = int(record_limit or config.RECORD_LIMIT_WITHDRAW)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||||
|
||||
_ensure_withdraw_page(page)
|
||||
config.log(f'发起提现记录导出:{date_from} ~ {date_to}')
|
||||
_ensure_capacity(page, config.WITHDRAW_DOWNLOAD_TYPE, limit)
|
||||
before = int(time.time()) - 5
|
||||
ok, msg = _create_withdraw(page, start_ts, end_ts)
|
||||
if not ok:
|
||||
return {'ok': False, 'message': f'发起提现记录导出失败:{msg}', 'path': ''}
|
||||
|
||||
record = _wait_record(page, config.WITHDRAW_DOWNLOAD_TYPE,
|
||||
lambda x: int(x.get('generate_start_time') or 0) >= before)
|
||||
if not record:
|
||||
return {'ok': False, 'message': '提现记录导出任务未生成完成', 'path': ''}
|
||||
config.log(f'导出任务已创建:download_id={record.get("download_id")},'
|
||||
f'文件名={record.get("file_name")}')
|
||||
return _save_record(record, save_dir,
|
||||
f'资金账户交易提现记录_{date_from}_{date_to}.xlsx', '提现记录')
|
||||
@@ -0,0 +1,246 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抖音来客登录态:打开登录页 → 人工登录(含验证码/滑块/扫码)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
实测链路(2026-10-28):
|
||||
https://life.douyin.com/p/login 登录页(账密 / 短信验证码 / 扫码)
|
||||
sso.douyin.com / passport.douyin.com
|
||||
登录成功后跳 https://life.douyin.com/p/home?groupid=...,期间可能短暂回跳登录页
|
||||
|
||||
判定规则(三条同时满足):
|
||||
1) 当前 URL 是 life.douyin.com 的非登录页;
|
||||
2) douyin 域下存在会话票据 Cookie(sessionid* / sid_tt* / sid_guard*);
|
||||
3) 连续稳定 BACKEND_STABLE 秒,期间没有被踢回登录页。
|
||||
|
||||
落盘(%LOCALAPPDATA%\\37duAutomation\\.sessions\\douyin_*):
|
||||
douyin_cookies.json / douyin_cookies_header.txt / douyin_tokens.json / douyin_session_meta.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免中断留下半截快照(半截快照必然登录失效)。"""
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _host(url):
|
||||
try:
|
||||
return (url or '').split('://', 1)[-1].split('/', 1)[0].split('?', 1)[0].lower()
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login(登录页/统一登录域)/ backend(来客后台)/ other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
host = _host(low)
|
||||
if host.endswith(config.BACKEND_HOST):
|
||||
path = low.split(host, 1)[-1]
|
||||
if any(p in path for p in config.LOGIN_PAGE_HINTS):
|
||||
return 'login'
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _has_session_cookie(cookies):
|
||||
"""douyin 域下是否存在登录票据 Cookie(名字带 _ls 等分区后缀,按前缀匹配)。"""
|
||||
for c in cookies:
|
||||
name = (c.get('name') or '').strip().lower()
|
||||
if name.startswith(config.SESSION_COOKIE_PREFIXES) and c.get('value') \
|
||||
and 'douyin.com' in (c.get('domain') or ''):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _ticket_cookies(cookies):
|
||||
out = []
|
||||
for c in cookies:
|
||||
name = (c.get('name') or '').strip()
|
||||
low = name.lower()
|
||||
if not name or not c.get('value'):
|
||||
continue
|
||||
if any(k in low for k in config.IGNORE_KEY_HINTS):
|
||||
continue
|
||||
if any(k in low for k in config.TICKET_KEY_HINTS):
|
||||
out.append(name)
|
||||
return sorted(set(out))
|
||||
|
||||
|
||||
def _cookie_header(cookies):
|
||||
"""按浏览器原始顺序拼出 douyin 域 Cookie 头(passport/埋点域名不要)。"""
|
||||
skip = ('passport', 'sso', 'report', 'monitor', 'lx', 'dreport', 'open.douyin')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and 'douyin.com' in (c.get('domain') or '')
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
config.log(f'已保存 douyin 域 Cookie 头({header.count(";") + 1} 项)')
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'has_session_cookie': _has_session_cookie(cookies),
|
||||
'ticket_cookies': _ticket_cookies(cookies),
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
return summary
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 验证码」,返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录'
|
||||
'(账号密码 / 短信验证码 / 扫码 / 滑块均可,脚本不碰表单)')
|
||||
|
||||
if state == 'backend' and _has_session_cookie(_cookies(page)):
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进来客后台且票据已种下,等待 {config.BACKEND_STABLE}s '
|
||||
f'确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('离开后台或票据消失,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page, force=False):
|
||||
"""确保 page 已进入来客后台;必要时停在前台等人工登录。
|
||||
|
||||
force=True 跳过 profile 残留会话试探,直接等人工登录(换账号/排查问题用)。
|
||||
"""
|
||||
config.log(f'打开抖音来客:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用 profile 残留会话:能直接进后台就不用打扰用户
|
||||
if not force:
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend' and _has_session_cookie(_cookies(page)):
|
||||
config.log(f'profile 残留会话有效,直接复用(URL={page.url})')
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state == 'login':
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
config.log('profile 无有效会话,转人工登录', 'WARN')
|
||||
|
||||
config.log(f'需要人工登录(含验证码/滑块),最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' +
|
||||
', '.join(sorted({c.get('name') for c in cookies if c.get('name')})), 'WARN')
|
||||
return False, '登录超时(未进入来客后台或会话票据缺失)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0042",
|
||||
"name": "抖音平台核对",
|
||||
"version": "0.6.2",
|
||||
"description": "抖音来客(life.douyin.com)数据自动导出:打开官方页面人工登录(含验证码/滑块),按日期区间导出核销明细与提现记录,轮询生成完成后下载到本机目录;导出记录超过保留阈值自动删最早的(阈值可在界面改);并入台账与核对统计待补齐。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"runTimeoutSeconds": 0,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0042"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"date_from": {
|
||||
"type": "string",
|
||||
"title": "核销时间-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"date_to": {
|
||||
"type": "string",
|
||||
"title": "核销时间-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"withdraw_from": {
|
||||
"type": "string",
|
||||
"title": "提现时间-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"withdraw_to": {
|
||||
"type": "string",
|
||||
"title": "提现时间-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"export_verify": {
|
||||
"type": "boolean",
|
||||
"title": "导出核销明细",
|
||||
"default": true,
|
||||
"description": "履约管理订单列表 → 核销明细(按核销时间区间)"
|
||||
},
|
||||
"export_withdraw": {
|
||||
"type": "boolean",
|
||||
"title": "导出提现记录",
|
||||
"default": true,
|
||||
"description": "财务 → 导出记录 → 余额提现记录(资金账户交易提现记录)"
|
||||
},
|
||||
"record_limit_verify": {
|
||||
"type": "integer",
|
||||
"title": "核销明细-导出记录保留条数",
|
||||
"default": 60,
|
||||
"description": "导出前查记录,超过该条数就删最早的、只留最新 N 条;核销明细暂无平台 30 条限制,默认 60"
|
||||
},
|
||||
"record_limit_withdraw": {
|
||||
"type": "integer",
|
||||
"title": "提现记录-导出记录保留条数",
|
||||
"default": 25,
|
||||
"description": "导出前查记录,超过该条数就删最早的、只留最新 N 条;平台硬上限 30,默认 25 留余量"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=D:\\资料\\财务\\抖音平台核对"
|
||||
},
|
||||
"force_login": {
|
||||
"type": "boolean",
|
||||
"title": "强制重新登录",
|
||||
"default": false,
|
||||
"description": "忽略浏览器里残留的登录态,直接等人工重新登录(换账号/排查登录问题时用)"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "输出完整调试日志(含页面跳转轨迹,默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DrissionPage>=4.1
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>抖音平台核对</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1585
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0042-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 内联提示 -->
|
||||
<div v-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 执行配置(头部含方案工具:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="5" y="4" width="14" height="17" rx="2" />
|
||||
<path d="M9 4V3h6v1" />
|
||||
<path d="m9 13 2 2 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-form label-position="top">
|
||||
<!-- 01 导出范围 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">导出内容</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="核销明细">
|
||||
<el-switch v-model="form.export_verify" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="提现记录">
|
||||
<el-switch v-model="form.export_withdraw" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="核销明细 核销时间">
|
||||
<el-date-picker v-model="verifyRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !form.export_verify" />
|
||||
</el-form-item>
|
||||
<el-form-item label="提现记录 提现时间">
|
||||
<el-date-picker v-model="withdrawRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !form.export_withdraw" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running"
|
||||
placeholder="留空 = D:\资料\财务\抖音平台核对" clearable />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
<b>核销明细</b>:履约管理订单列表按核销时间导出;<b>提现记录</b>:财务 → 导出记录里的
|
||||
「余额提现记录」(资金账户交易提现记录),按其提现时间导出。<br>
|
||||
两类数据分别落到保存目录(文件名由平台生成)。<br>
|
||||
默认昨天到今天;今天的核销数据当天可导,如要完整日结数据建议选到昨天。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 执行设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">执行设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="强制重新登录">
|
||||
<el-switch v-model="form.force_login" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="核销明细-导出记录保留条数">
|
||||
<el-input-number v-model="form.record_limit_verify" :min="5" :step="5"
|
||||
:disabled="running" class="wide" />
|
||||
</el-form-item>
|
||||
<el-form-item label="提现记录-导出记录保留条数">
|
||||
<el-input-number v-model="form.record_limit_withdraw" :min="5" :step="5"
|
||||
:disabled="running" class="wide" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
登录态默认复用本机浏览器档案,仅在过期时才需要人工登录(含验证码/滑块)。<br>
|
||||
勾选<b>强制重新登录</b>会忽略残留登录态直接等人工登录,换账号或排查登录问题时用;
|
||||
<b>调试日志</b>输出页面跳转轨迹,日常保持关闭。<br>
|
||||
导出前先查该类的导出记录,<b>超过保留条数就删最早的、只留最新 N 条</b>;
|
||||
提现记录平台硬上限 30 条,默认 25 留余量。删除会限流(每条间隔 1~2 秒、单次最多 20 条)。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 默认日期区间:昨天 ~ 今天
|
||||
function defaultRange() {
|
||||
const today = new Date()
|
||||
const y = new Date(today.getTime() - 86400000)
|
||||
const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
return [fmt(y), fmt(today)]
|
||||
}
|
||||
|
||||
// 默认日期区间:昨天 ~ 今天(首屏即带出,不依赖配置接口)
|
||||
const DEFAULTS = () => {
|
||||
const [from, to] = defaultRange()
|
||||
return {
|
||||
date_from: from,
|
||||
date_to: to,
|
||||
withdraw_from: from,
|
||||
withdraw_to: to,
|
||||
export_verify: true,
|
||||
export_withdraw: true,
|
||||
record_limit_verify: 60,
|
||||
record_limit_withdraw: 25,
|
||||
save_dir: '',
|
||||
force_login: false,
|
||||
debug_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
form, loaded, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.export_verify && !form.export_withdraw) {
|
||||
ElMessage.warning('请至少勾选一项要导出的内容(核销明细 / 提现记录)')
|
||||
return false
|
||||
}
|
||||
const pairs = []
|
||||
if (form.export_verify) pairs.push(['核销时间', form.date_from, form.date_to])
|
||||
if (form.export_withdraw) pairs.push(['提现时间', form.withdraw_from, form.withdraw_to])
|
||||
for (const [label, rawA, rawB] of pairs) {
|
||||
const a = (rawA || '').trim()
|
||||
const b = (rawB || '').trim()
|
||||
if (a && b && a > b) {
|
||||
ElMessage.warning(`${label}的开始日期不能晚于结束日期`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
},
|
||||
buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
const n = (v, d) => {
|
||||
const x = Number(v)
|
||||
return Number.isFinite(x) && x >= 5 ? Math.floor(x) : d
|
||||
}
|
||||
return {
|
||||
date_from: t(f.date_from),
|
||||
date_to: t(f.date_to),
|
||||
withdraw_from: t(f.withdraw_from),
|
||||
withdraw_to: t(f.withdraw_to),
|
||||
export_verify: !!f.export_verify,
|
||||
export_withdraw: !!f.export_withdraw,
|
||||
record_limit_verify: n(f.record_limit_verify, 60),
|
||||
record_limit_withdraw: n(f.record_limit_withdraw, 25),
|
||||
save_dir: t(f.save_dir),
|
||||
force_login: !!f.force_login,
|
||||
debug_mode: !!f.debug_mode,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function start() {
|
||||
run()
|
||||
}
|
||||
|
||||
// 日期区间选择器 ↔ 两个字段(plugin.json 以 date_from/to、withdraw_from/to 为契约)
|
||||
const verifyRange = computed({
|
||||
get: () => {
|
||||
const a = form.date_from
|
||||
const b = form.date_to
|
||||
return (a || b) ? [a || null, b || null] : null
|
||||
},
|
||||
set: (v) => {
|
||||
form.date_from = (v && v[0]) || ''
|
||||
form.date_to = (v && v[1]) || ''
|
||||
},
|
||||
})
|
||||
|
||||
const withdrawRange = computed({
|
||||
get: () => {
|
||||
const a = form.withdraw_from
|
||||
const b = form.withdraw_to
|
||||
return (a || b) ? [a || null, b || null] : null
|
||||
},
|
||||
set: (v) => {
|
||||
form.withdraw_from = (v && v[0]) || ''
|
||||
form.withdraw_to = (v && v[1]) || ''
|
||||
},
|
||||
})
|
||||
|
||||
// 配置加载完成后:日期为空则带出「昨天~今天」
|
||||
watch(loaded, (v) => {
|
||||
if (!v) return
|
||||
const [from, to] = defaultRange()
|
||||
if (!form.date_from && !form.date_to) {
|
||||
form.date_from = from
|
||||
form.date_to = to
|
||||
}
|
||||
if (!form.withdraw_from && !form.withdraw_to) {
|
||||
form.withdraw_from = from
|
||||
form.withdraw_to = to
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
@@ -0,0 +1 @@
|
||||
export const PLUGIN_ID = 'xq0042'
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus).mount('#app')
|
||||
@@ -0,0 +1,524 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v2)
|
||||
- 上半部分:壳子 design token 子集(权威源 desktop/electron-shell/design-app/styles.css)
|
||||
- 中间:Element Plus 变量映射到壳子 token(iframe 内与壳子同一套皮肤)
|
||||
- 下半部分:标准版式骨架(panel / sec / grid / actions),与其它插件保持一致
|
||||
规则:插件内只用 var(--xxx),不写字面色值。
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* ---- 底色与卡面 ---- */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* ---- 描边 ---- */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* ---- 文字四阶 ---- */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* ---- 主色(靛蓝) ---- */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* ---- 语义色 ---- */
|
||||
--good: #0E9F76;
|
||||
--good-soft: #EBF7F2;
|
||||
--good-line: #D3EDE3;
|
||||
--warn: #D98218;
|
||||
--warn-soft: #FDF3E4;
|
||||
--danger: #E5484D;
|
||||
--danger-soft: #FDEDED;
|
||||
--danger-line: #F6D7D8;
|
||||
|
||||
/* ---- 圆角 ---- */
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* ---- 阴影 ---- */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* ---- 字体 ---- */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
|
||||
/* ---- 间距 ---- */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Element Plus → 壳子 token 映射
|
||||
============================================================ */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
基础重置
|
||||
============================================================ */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
页面骨架(与其它插件一致:panel + sec 分区 + grid 栅格 + actions)
|
||||
============================================================ */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
/* 壳子 iframe 外层已有 padding,这里再留一层,避免内容贴着 iframe 边缘 */
|
||||
padding: 8px 16px 24px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ---------- 主容器:无边框平铺,外框由壳子 iframe 提供 ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.panel .el-card__header {
|
||||
padding: 4px 0 16px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel .el-card__body {
|
||||
padding: 16px 0 4px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部:标题 + 方案工具条 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: var(--r-btn);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font: 600 13.5px/1.25 var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 11.5px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good);
|
||||
font-size: 11.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved i {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--good);
|
||||
}
|
||||
|
||||
/* 尚无保存记录:占位,保持卡片头右侧元素对齐 */
|
||||
.saved.is-idle {
|
||||
background: var(--subtle);
|
||||
border-color: var(--line);
|
||||
color: var(--t4);
|
||||
}
|
||||
|
||||
.saved.is-idle i {
|
||||
background: var(--t5);
|
||||
}
|
||||
|
||||
/* ---------- 分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font: 600 11px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font: 600 13px/1.3 var(--f-cn);
|
||||
color: var(--t1);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--line-soft), transparent);
|
||||
}
|
||||
|
||||
/* ---------- 栅格 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
|
||||
/* ---------- 开关栅格:每格 = 名称 + 开关(规范 §5.2 / §7) ---------- */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
|
||||
/* 日期区间与开关行之间留出呼吸 */
|
||||
.grid-date {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
/* 栅格里的控件统一撑满 */
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-input-number,
|
||||
.grid .el-date-editor {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
/* ---------- 提示 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.65;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.tip b {
|
||||
color: var(--t2);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- 内联提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-field);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font-size: 12px;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
.notice .n-ico {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.notice.is-warn {
|
||||
background: var(--warn-soft);
|
||||
border-color: rgba(217, 130, 24, .24);
|
||||
color: #8A5B0E;
|
||||
}
|
||||
|
||||
.notice.is-error {
|
||||
background: var(--danger-soft);
|
||||
border-color: var(--danger-line);
|
||||
color: #CC3B40;
|
||||
}
|
||||
|
||||
.notice.is-ok {
|
||||
background: var(--good-soft);
|
||||
border-color: var(--good-line);
|
||||
color: var(--good);
|
||||
}
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.plan .p-tag {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 600;
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.plan .p-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.plan.is-empty .p-text {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
border-top: 1px dashed var(--line);
|
||||
padding-top: 18px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.actions .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* 底部通用操作(恢复参数/保存/恢复默认),不重复画分隔线 */
|
||||
.actions--foot {
|
||||
border-top: none;
|
||||
padding-top: 0;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background .15s, box-shadow .15s, transform .06s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
background: var(--brand-hover);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(1px);
|
||||
box-shadow: var(--sh-brand-sm);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态:进度条 + 一行说明 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: var(--r-sub);
|
||||
background: var(--brand-soft);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__outer {
|
||||
background: rgba(79, 89, 232, .14);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__inner {
|
||||
background: var(--brand);
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font: 600 13px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
font-size: 12px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.runline .pct {
|
||||
font: 600 12px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--brand);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--brand-soft);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try {
|
||||
msg = (await res.json()).detail || msg
|
||||
} catch (_) { /* 保留默认 */ }
|
||||
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
const schemeSel = ref('')
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||
}
|
||||
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
},
|
||||
))
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
try {
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary)
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子托管在 /pui/xq0042/ 下,构建产物输出到插件包 ui/ 目录。
|
||||
// dev 端口 5199(避开已占用的 5180-5185/5188/5198),代理到本机壳子 8799。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0042/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5199,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>抖音平台核对</title>
|
||||
<script type="module" crossorigin src="/pui/xq0042/assets/index-BUp-ZeAA.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0042/assets/index-D2-8mbvQ.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user