feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
@@ -37,6 +37,23 @@ from .logic.workbook import (copy_today_to_prev, ensure_sheets, read_compare_res
|
||||
from .report.summary import build_summary
|
||||
|
||||
|
||||
def _gap_days(today, t2, covered_until):
|
||||
"""上轮已处理积分日期与 T-2 之间漏处理的日期(限本月、早于 T-2)。
|
||||
|
||||
跳天运行(如隔几天才跑一次)时,中间日期的考勤数据大多已在上轮快照里,
|
||||
按差值对比会因「差值=0」被漏掉,需按新增段口径全量补。
|
||||
"""
|
||||
if covered_until is None or covered_until >= t2 - timedelta(days=1):
|
||||
return []
|
||||
month_first = date(today.year, today.month, 1)
|
||||
d = max(covered_until + timedelta(days=1), month_first)
|
||||
days = []
|
||||
while d < t2 and d.month == today.month:
|
||||
days.append(d)
|
||||
d += timedelta(days=1)
|
||||
return days
|
||||
|
||||
|
||||
def _log_workbook_shape(ctx, path, wb):
|
||||
"""输出工作簿规模诊断:openpyxl 内存占用与「已存在单元格数」成正比。"""
|
||||
try:
|
||||
@@ -61,7 +78,7 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
id = "xq0033"
|
||||
name = "门店管理及服务岗出勤积分更新"
|
||||
version = "1.0.4"
|
||||
version = "1.0.7"
|
||||
description = (
|
||||
"拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,"
|
||||
"自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,"
|
||||
@@ -189,11 +206,17 @@ class Xq0033Plugin(ScenePlugin):
|
||||
if stats["cleared"]:
|
||||
ctx.log(f"已踢除离职当月再入职人员无效积分段 {stats['cleared']} 个考勤状态", "INFO")
|
||||
|
||||
# 3. 选择目标批次文件
|
||||
target_path, is_new_batch = pick_target_file(today, save_dir, force_file)
|
||||
# 3. 选择目标批次文件(同时据来源文件名推断上轮已处理的积分日期)
|
||||
target_path, is_new_batch, covered_until = pick_target_file(today, save_dir, force_file)
|
||||
file_key = os.path.basename(target_path)
|
||||
gap_days = _gap_days(today, t2, covered_until)
|
||||
ctx.progress(30)
|
||||
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})", "INFO")
|
||||
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})"
|
||||
f",上轮积分日期:{covered_until or '未知'}", "INFO")
|
||||
if gap_days:
|
||||
ctx.log(f"检测到 {covered_until} 之后、T-2={t2} 之前漏处理日期:"
|
||||
f"{'、'.join(d.strftime('%m-%d') for d in gap_days)},"
|
||||
"本轮按新增段口径全量补齐", "WARN")
|
||||
|
||||
# 4. 全程只加载一次工作簿(大体积模板多次全量加载会触发 MemoryError),
|
||||
# 写操作复用同一 wb;需要公式缓存值时另开 read_only 轻量读取。
|
||||
@@ -235,18 +258,20 @@ class Xq0033Plugin(ScenePlugin):
|
||||
recalc_target(target_path)
|
||||
ctx.progress(56)
|
||||
|
||||
# 6. 读对比结果 → 新增段 / 修正补 / 修正删
|
||||
# 6. 读对比结果 → 新增段(含补漏日期)/ 修正补 / 修正删
|
||||
wv = openpyxl.load_workbook(target_path, data_only=True, read_only=True)
|
||||
try:
|
||||
new_rows, fix_rows, del_rows = read_compare_results(wv, today, t2)
|
||||
new_rows, fix_rows, del_rows = read_compare_results(wv, today, t2, gap_days)
|
||||
finally:
|
||||
wv.close()
|
||||
wv = None
|
||||
gc.collect()
|
||||
stats["new"], stats["fix"], stats["del"] = len(new_rows), len(fix_rows), len(del_rows)
|
||||
stats["gap"] = len(gap_days)
|
||||
ctx.progress(62)
|
||||
ctx.log(f"积分计算结果:新增段 {len(new_rows)} 行({t2}),修正补 {len(fix_rows)} 行,"
|
||||
f"修正删 {len(del_rows)} 行", "INFO")
|
||||
ctx.log(f"积分计算结果:新增段 {len(new_rows)} 行(T-2={t2}"
|
||||
f"{',含补漏 ' + '、'.join(d.strftime('%m-%d') for d in gap_days) if gap_days else ''})"
|
||||
f",修正补 {len(fix_rows)} 行,修正删 {len(del_rows)} 行", "INFO")
|
||||
|
||||
# 7. 写积分导入 / 积分删除(新增段保护 + 修正段全月刷新)→ COM 收尾重算
|
||||
state_file = config.state_path(os.path.dirname(target_path))
|
||||
@@ -294,12 +319,47 @@ class Xq0033Plugin(ScenePlugin):
|
||||
ctx.progress(min(96, base + 8))
|
||||
|
||||
for label, rows, kind in valid:
|
||||
url = client.import_url if kind == "import" else client.delete_url
|
||||
res = client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
results[label] = res
|
||||
if kind == "import":
|
||||
# 跳天补漏后单次可能上万行,OPM 逐行处理易超时 → 按积分日期分批(每批约单日量)
|
||||
groups = {}
|
||||
for r in rows:
|
||||
groups.setdefault(r[2].date(), []).append(r)
|
||||
if len(groups) > 1:
|
||||
ctx.log(f"{label} 共 {len(rows)} 行,按积分日期分 {len(groups)} 批上传", "INFO")
|
||||
parts, failed = [], []
|
||||
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)} 行")
|
||||
else:
|
||||
failed.append(f"{d:%m-%d}({res['message']})")
|
||||
results[label] = {
|
||||
"success": not failed,
|
||||
"message": ("分批成功:" + "、".join(parts)) if not failed
|
||||
else "失败批次:" + ";".join(failed),
|
||||
}
|
||||
else:
|
||||
results[label] = self._upload_once(client, ctx, label, rows, kind)
|
||||
res = results[label]
|
||||
ctx.log(f"{label} 推送:{'成功' if res['success'] else '失败'}({res['message']})",
|
||||
"INFO" if res["success"] else "ERROR")
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def _upload_once(client, ctx, label, rows, kind):
|
||||
"""单批上传;失败时重登会话再试一次(大请求超时后 OPM 常会重置会话返回 HTML)。"""
|
||||
url = client.import_url if kind == "import" else client.delete_url
|
||||
res = client.upload(url, build_kaoqin_bytes(rows), 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")
|
||||
|
||||
|
||||
PLUGINS.append(Xq0033Plugin())
|
||||
|
||||
@@ -67,7 +67,7 @@ COM_PROG_IDS = ("Ket.Application", "et.Application", "Excel.Application")
|
||||
DEFAULT_OPM_URL = "https://opm.jsyxapp.com/login"
|
||||
OPM_IMPORT_PATH = "/operation/point/list/importAttendance"
|
||||
OPM_DELETE_PATH = "/operation/point/list/importAttendanceDel"
|
||||
OPM_TIMEOUT = 30
|
||||
OPM_TIMEOUT = 120
|
||||
# 服务端对「重复/无内容可删」的良性响应关键词:目标状态已达成,不算失败
|
||||
OPM_BENIGN_MSGS = ("不能重复添加", "未生成出勤积分", "已存在")
|
||||
|
||||
|
||||
@@ -59,11 +59,15 @@ def pick_latest_file(save_dir, force_file=None):
|
||||
|
||||
|
||||
def pick_target_file(today, save_dir, force_file=None):
|
||||
"""选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件)。"""
|
||||
"""选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件, 上轮已处理的积分日期)。
|
||||
|
||||
第三个返回值取「被复制批次文件名里的最大日期」,用于识别两次运行之间漏处理的日期;
|
||||
指定工作簿时来源不可信,返回 None(不做补漏推断)。
|
||||
"""
|
||||
if force_file:
|
||||
if not os.path.isfile(force_file):
|
||||
raise FileNotFoundError(f"指定的工作簿不存在:{force_file}")
|
||||
return os.path.abspath(force_file), False
|
||||
return os.path.abspath(force_file), False, None
|
||||
|
||||
if not os.path.isdir(save_dir):
|
||||
raise FileNotFoundError(f"工作簿目录不存在:{save_dir}")
|
||||
@@ -88,15 +92,18 @@ def pick_target_file(today, save_dir, force_file=None):
|
||||
path = os.path.join(save_dir, f)
|
||||
config.logger.info("命中文件名含 T-2(%s) 的数据文件:%s(续用追加模式)",
|
||||
t2.strftime("%m%d"), f)
|
||||
return path, False
|
||||
return path, False, t2
|
||||
|
||||
newest = max(files, key=lambda f: os.path.getmtime(os.path.join(save_dir, f)))
|
||||
src_dates = parse_name_dates(newest, today.year)
|
||||
covered_until = max(src_dates) if src_dates else None
|
||||
new_name = f"{config.FILE_PREFIX}{t2.strftime('%m%d')}.xlsx"
|
||||
new_path = os.path.join(save_dir, new_name)
|
||||
if os.path.exists(new_path):
|
||||
config.logger.warning("新批文件 %s 已存在但文件名未匹配 T-2,直接复用", new_name)
|
||||
return new_path, False
|
||||
return new_path, False, covered_until
|
||||
shutil.copy2(os.path.join(save_dir, newest), new_path)
|
||||
config.logger.info("未找到文件名含 T-2 的文件,已从最新文件 %s 复制新建批次文件:%s",
|
||||
newest, new_name)
|
||||
return new_path, True
|
||||
config.logger.info("未找到文件名含 T-2 的文件,已从最新文件 %s 复制新建批次文件:%s"
|
||||
"(上轮积分日期推断为 %s)",
|
||||
newest, new_name, covered_until or "未知")
|
||||
return new_path, True, covered_until
|
||||
|
||||
@@ -95,17 +95,26 @@ def write_compare_values(wb, sel_rows):
|
||||
return n
|
||||
|
||||
|
||||
def read_compare_results(wv, today, t2):
|
||||
"""读「对比结果」公式值 → (新增段行, 修正补行, 修正删行),每行为 (员工信息9列, date)。"""
|
||||
def read_compare_results(wv, today, t2, gap_days=()):
|
||||
"""读「对比结果」公式值 → (新增段行, 修正补行, 修正删行),每行为 (员工信息9列, date)。
|
||||
|
||||
新增段 = T-2 + gap_days(上轮积分日期到 T-2 之间漏处理的日期),两者均按镜像列=2
|
||||
全量取人;修正段 = 其余 [月首, T-3] 日期按差值 >0 补 / <0 删(gap_days 不参与差值,
|
||||
否则「上次快照已有值但从未推送」的日期会因差值=0 被漏掉)。
|
||||
"""
|
||||
ws = wv[config.SHEET_CMP]
|
||||
month_first = date(today.year, today.month, 1)
|
||||
mirror_idx = 40 + t2.day if t2 >= month_first else None
|
||||
if mirror_idx is None:
|
||||
gap_days = sorted(d for d in (gap_days or ()) if month_first <= d < t2)
|
||||
if t2 >= month_first:
|
||||
full_days = gap_days + [t2]
|
||||
else:
|
||||
config.logger.warning("T-2(%s) 不在本月报表范围,跳过新增段(月初边缘场景属正常)", t2)
|
||||
full_days = []
|
||||
fix_end = t2 - timedelta(days=1)
|
||||
gap_nums = {d.day for d in gap_days}
|
||||
fix_days = []
|
||||
if t2 >= month_first and fix_end >= month_first:
|
||||
fix_days = list(range(month_first.day, fix_end.day + 1))
|
||||
fix_days = [d for d in range(month_first.day, fix_end.day + 1) if d not in gap_nums]
|
||||
|
||||
new_rows, fix_rows, del_rows = [], [], []
|
||||
for row in ws.iter_rows(min_row=config.CMP_DATA_START, min_col=1, max_col=72,
|
||||
@@ -113,11 +122,14 @@ def read_compare_results(wv, today, t2):
|
||||
info = list(row[1:10])
|
||||
if clean(info[0]) == "":
|
||||
continue
|
||||
if mirror_idx is not None and mirror_idx < len(row):
|
||||
v = row[mirror_idx]
|
||||
for d in full_days:
|
||||
idx = 40 + d.day
|
||||
if idx >= len(row):
|
||||
continue
|
||||
v = row[idx]
|
||||
try:
|
||||
if v not in (None, "") and abs(float(v) - 2) < 1e-9:
|
||||
new_rows.append((info, t2))
|
||||
new_rows.append((info, d))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
for d in fix_days:
|
||||
@@ -136,6 +148,7 @@ def read_compare_results(wv, today, t2):
|
||||
fix_rows.append((info, fix_date))
|
||||
elif diff < 0:
|
||||
del_rows.append((info, fix_date))
|
||||
new_rows.sort(key=lambda x: x[1])
|
||||
fix_rows.sort(key=lambda x: x[1])
|
||||
del_rows.sort(key=lambda x: x[1])
|
||||
return new_rows, fix_rows, del_rows
|
||||
@@ -190,13 +203,16 @@ def write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_ne
|
||||
ws.cell(row=r, column=11).number_format = "yyyy/m/d"
|
||||
|
||||
dates = set(state.setdefault(file_key, {}).setdefault("new_dates", []))
|
||||
for _info, d in new_rows: # 新增段含补漏日期,全部纳入历史保护
|
||||
dates.add(d.isoformat())
|
||||
if t2 >= date(today.year, today.month, 1):
|
||||
dates.add(t2.isoformat())
|
||||
state[file_key]["new_dates"] = sorted(dates)
|
||||
state[file_key]["new_dates"] = sorted(dates)
|
||||
new_dates_txt = "、".join(sorted({d.isoformat() for _info, d in new_rows})) or t2.isoformat()
|
||||
config.logger.info(
|
||||
"积分导入:删除旧行 %d(历史新增段保护日期 %s),追加新增段 %d 行(%s)+ 修正段 %d 行,现共 %d 行",
|
||||
removed, state[file_key].get("new_dates") or "无", len(new_rows), t2, len(fix_rows),
|
||||
scan_last_data_row(ws, 2, config.IMP_DATA_START) - config.IMP_DATA_START + 1)
|
||||
removed, state[file_key].get("new_dates") or "无", len(new_rows), new_dates_txt,
|
||||
len(fix_rows), scan_last_data_row(ws, 2, config.IMP_DATA_START) - config.IMP_DATA_START + 1)
|
||||
return len(out)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0033",
|
||||
"name": "门店管理及服务岗出勤积分更新",
|
||||
"version": "1.0.4",
|
||||
"version": "1.0.7",
|
||||
"description": "拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,COM 全量重算),可选将积分导入与删除表推送至 OPM 平台。",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
"""按执行结果拼装 {summary, detail}。
|
||||
|
||||
stats: report_rows/selected/new/fix/del/rejoin_new/rejoin_total/cleared 计数;
|
||||
stats: report_rows/selected/new/fix/del/gap/rejoin_new/rejoin_total/cleared 计数;
|
||||
update=False 表示本轮仅推送(不展示更新计数)。
|
||||
push_result: {label: {success, message}} 或 None(未执行推送)。
|
||||
"""
|
||||
@@ -17,6 +17,7 @@ def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
"报表人数": stats.get("report_rows", 0),
|
||||
"圈人命中": stats.get("selected", 0),
|
||||
"新增积分行": stats.get("new", 0),
|
||||
"补漏日期数": stats.get("gap", 0),
|
||||
"修正补积分行": stats.get("fix", 0),
|
||||
"修正删积分行": stats.get("del", 0),
|
||||
"再入职新增行": stats.get("rejoin_new", 0),
|
||||
@@ -32,6 +33,8 @@ def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
]
|
||||
if stats.get("cleared"):
|
||||
lines.append(f"已踢除离职当月再入职人员无效积分段 {stats['cleared']} 个考勤状态。")
|
||||
if stats.get("gap"):
|
||||
lines.append(f"检测到漏处理日期 {stats['gap']} 天,已按新增段口径全量补齐。")
|
||||
else:
|
||||
detail = {"运行日": today.isoformat(), "工作簿": target_path}
|
||||
lines = [f"XQ0033 完成(运行日 {today},仅推送):工作簿 {target_path}"]
|
||||
|
||||
@@ -48,7 +48,7 @@ class _LogWriter:
|
||||
class Xq0034Plugin(ScenePlugin):
|
||||
id = "xq0034"
|
||||
name = "续签电子签"
|
||||
version = "1.0.17"
|
||||
version = "1.0.18"
|
||||
description = ("XQ0034 续签电子签:AI表格【续签名单到期跟进-月更新】驱动——否续签回填、"
|
||||
"是续签手机号校验后 HR 生效中合同属性页「续签合同」提交推送电子签并回填,"
|
||||
"HR 会话由壳子注入")
|
||||
|
||||
@@ -27,8 +27,9 @@ HR【劳动关系-合同台账-生效中合同】属性页「续签合同」提
|
||||
AI 表;补全后继续完整续签流程(不再跳过)。AI 信息不全的记录不提交
|
||||
(期限/开始/截止/类型缺失 -> 不提交,日志报出)。
|
||||
4. 通知(2026-10-16 精简,块格式与加班审批一致):只推送 续签推送成功数量 /
|
||||
核验完成数量 / 核验未完成数量 / 续签失败明细;防重、试算、跳过、异常、
|
||||
「是否续签=否」回填均只记日志不通知。
|
||||
核验完成数量 / 核验未完成数量 / 续签失败明细;防重、试算、跳过、「是否续签=否」
|
||||
回填均只记日志不通知。例外:合同到期日与生效中合同不一致的异常推送
|
||||
「合同到期日异常(未推送)」(2026-10-26 用户要求)。
|
||||
5. 核验流程(2026-10-16 口径修正):「是否续签=是」且「人资是否推送=是」且
|
||||
「完成签署」未填的记录逐条核验——【待生效合同】+【生效中合同】两 Tab 联合
|
||||
取该员工全部合同行,按合同开始日期取最新一条:
|
||||
@@ -57,7 +58,8 @@ HR【劳动关系-合同台账-生效中合同】属性页「续签合同」提
|
||||
无推送时间 -> 异常报出待人工核对。
|
||||
待生效无行 -> 查生效中合同:以 AI 表「合同/协议到期日」(旧合同到期日) 为界,
|
||||
生效中合同截止日期 > 旧合同到期日 = 续签新合同(可能已转生效,即使 AI 表续签期
|
||||
填错也视为已续签)-> 防重不回填发起;否则为旧合同 -> 正常发起续签。
|
||||
填错也视为已续签)-> 防重不回填发起;否则为旧合同 -> 核对 AI 表「合同/协议
|
||||
到期日」与生效中合同截止日期一致(不一致/未填 -> 异常,不发起续签)。
|
||||
4. 属性页 getPropPageData(businessKey=contract_id)-> 原样字段 + AI 表覆盖字段
|
||||
-> savePropPageData 提交(state=="1" 为成功);
|
||||
5. 复查:轮询【待生效合同】Tab 出现该员工行(HR 落库有秒级延迟);
|
||||
@@ -436,6 +438,17 @@ def renew_contract(session, ai, dry_run):
|
||||
return "防重", f"防重命中:{detail},回填推送时间={a_push}"
|
||||
return "防重", f"防重命中:{detail},行内无推送时间"
|
||||
# 生效中合同截止未超过旧合同到期日 -> 仍为旧合同 -> 正常走提交(发起续签)
|
||||
# 3.5) 旧合同到期日一致性闸门(2026-10-26 用户要求):发起续签前,AI 表
|
||||
# 「合同/协议到期日」须与【生效中合同】截止日期完全一致;不一致(含
|
||||
# AI 表未填)说明两边数据错位(旧合同已被替换/到期日填错),不发起
|
||||
# 续签,报异常转人工核对(该异常推送钉钉通知)。
|
||||
ai["_alert"] = True
|
||||
if old_expire is None:
|
||||
return "异常", ("AI表「合同/协议到期日」为空,无法核对生效中合同截止日期,"
|
||||
"不发起续签,请人工补充后重跑")
|
||||
if a_end != old_expire:
|
||||
return "异常", (f"AI表合同/协议到期日({old_expire})与生效中合同截止日期"
|
||||
f"({a_end or '?'})不一致,不发起续签,请人工核对")
|
||||
|
||||
# 4) 属性页连通性校验(businessKey=生效合同ID;提交体为固定构造,不用快照转发)
|
||||
resp = _request_retry("POST", GET_PROP_URL_RENEW, session,
|
||||
@@ -587,7 +600,7 @@ def process_renew(session, rec, dry_run):
|
||||
code = _norm_code(fields.get(F_CODE))
|
||||
r = {"record_id": rec.get("id"), "code": code,
|
||||
"name": _s(fields.get(F_NAME)), "status": "失败", "msg": "",
|
||||
"backfill": None, "prefill": None}
|
||||
"backfill": None, "prefill": None, "alert": False}
|
||||
if not code:
|
||||
r["msg"] = "工号为空"
|
||||
return r
|
||||
@@ -626,6 +639,7 @@ def process_renew(session, rec, dry_run):
|
||||
logger.info("【%s】电子签接收电话为空,默认取花名册联系方式回填", code)
|
||||
|
||||
status, msg = renew_contract(session, ai, dry_run)
|
||||
r["alert"] = bool(ai.pop("_alert", False)) # 合同到期日不一致类异常需推送钉钉
|
||||
fix_note = ai.pop("_phone_fixed", None)
|
||||
if fix_note:
|
||||
msg = f"{msg};🔧{fix_note}"
|
||||
@@ -803,10 +817,12 @@ def main(dry_run=False):
|
||||
v_done, v_wait, _ = run_verify(session, records, dry_run)
|
||||
|
||||
# 汇总消息(块格式与加班审批一致,2026-10-16 用户要求精简:
|
||||
# 只保留 推送成功明细 / 核验完成数量 / 核验未完成数量 / 失败明细)
|
||||
# 只保留 推送成功明细 / 核验完成数量 / 核验未完成数量 / 失败明细;
|
||||
# 合同到期日与生效中合同不一致的异常也推送,2026-10-26 用户要求)
|
||||
messages = []
|
||||
pushed = [r for r in results if r["status"] == "已推送"]
|
||||
fail = [r for r in results if r["status"] == "失败"]
|
||||
alerts = [r for r in results if r.get("alert")]
|
||||
|
||||
def _person_block(name, code, lines):
|
||||
"""单人 block(钉钉 Markdown 引用块内每行需空行分隔才会换行)。"""
|
||||
@@ -831,6 +847,11 @@ def main(dry_run=False):
|
||||
"blocks": [_person_block(
|
||||
r["name"], r["code"], [f"失败原因:{r['msg']}"])
|
||||
for r in fail]})
|
||||
if alerts:
|
||||
messages.append({"title": "【续签电子签】合同到期日异常(未推送)",
|
||||
"blocks": [_person_block(
|
||||
r["name"], r["code"], [f"异常原因:{r['msg']}"])
|
||||
for r in alerts]})
|
||||
if not messages:
|
||||
messages = ["续签电子签:无待处理名单"]
|
||||
for m in messages:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0034",
|
||||
"name": "续签电子签",
|
||||
"version": "1.0.17",
|
||||
"description": "XQ0034 续签电子签:钉钉AI表格【续签名单到期跟进-月更新】驱动——「是否续签=否」回填人资是否推送=否;「是否续签=是」前置默认补全(电子签接收电话为空取花名册号码回填、期望推送日期为空默认当天回填)后完整发起续签:校验电话与花名册一致(不一致且合法自动修正HR联系方式),在 HR【合同台账-生效中合同】属性页「续签合同」提交推送电子签(新合同信息直接取AI表字段,电子签模板按员工+签署单位实时查询,为空不提交转人工),成功回填人资是否推送=是+推送时间;核验:待生效+生效中联合取最新合同,时间与AI表续签期一致且签署记录is_initiate_sign=2已完成签署才回填完成签署=是(1已发起/3已撤销均不算);通知块格式与加班审批一致,仅推送成功/核验完成数量/核验未完成数量/失败;HR 会话由壳子注入",
|
||||
"version": "1.0.18",
|
||||
"description": "XQ0034 续签电子签:钉钉AI表格【续签名单到期跟进-月更新】驱动——「是否续签=否」回填人资是否推送=否;「是否续签=是」前置默认补全(电子签接收电话为空取花名册号码回填、期望推送日期为空默认当天回填)后完整发起续签:校验电话与花名册一致(不一致且合法自动修正HR联系方式),发起前核对 AI 表「合同/协议到期日」与【生效中合同】截止日期,不一致或未填=异常不发起并推送钉钉通知,一致则在 HR【合同台账-生效中合同】属性页「续签合同」提交推送电子签(新合同信息直接取AI表字段,电子签模板按员工+签署单位实时查询,为空不提交转人工),成功回填人资是否推送=是+推送时间;核验:待生效+生效中联合取最新合同,时间与AI表续签期一致且签署记录is_initiate_sign=2已完成签署才回填完成签署=是(1已发起/3已撤销均不算);通知块格式与加班审批一致,推送成功/核验完成数量/核验未完成数量/失败/合同到期日异常;HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
③ 待办完善信息提交 —— 完善信息环节自动保存+送审办结(合同期限/模板/签署单位计算)
|
||||
④ 发起离职电子签 —— 离职电子签办理环节发起(复用 XQ0035 initiate_resign_esign 内嵌副本)
|
||||
⑤ 回写AI表格跟进 —— HR 已发起者回写「改签离职电子签跟进-日更新」+ 回填发起日期
|
||||
(含「调动导出」已发人员补录,发起时间取操作时间)
|
||||
⑥ 签署完成核查回写 —— 离职/新合同签署完成核查 + checkbox 回写
|
||||
|
||||
会话:ctx.get_session("hr") 注入共享 HR 登录态(壳子运行前自动补登);
|
||||
@@ -64,10 +65,10 @@ class _LogWriter:
|
||||
class Xq0037Plugin(ScenePlugin):
|
||||
id = "xq0037"
|
||||
name = "调动改签离职电子签"
|
||||
version = "1.1.6"
|
||||
version = "1.1.7"
|
||||
description = ("XQ0037 调动改签离职电子签:①调动台账导出 ②HR调动信息置位(已发起名单+群提醒) "
|
||||
"③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进 ⑥签署完成核查回写,"
|
||||
"AI表格字段接力驱动、单步执行错峰定时")
|
||||
"③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进(含已发补录) "
|
||||
"⑥签署完成核查回写,AI表格字段接力驱动、单步执行错峰定时")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0037"]
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0037 步骤5:HR 已发起工号回写钉钉 AI 表格「改签离职电子签跟进-日更新」(新增行)。
|
||||
|
||||
链路最后一步,与 step2/3/4 同一作用域闸门:仅处理「待办工号列表.json」内工号
|
||||
(step2 置位时登记,step4 发起后保留),字段从当天推送表「已发起名单」取。
|
||||
链路最后一步,字段从当天推送表「已发起名单」取。两类来源:
|
||||
A. 待办工号列表(step2 置位时登记,step4 发起后保留)—— 与 step3/4 同一作用域闸门;
|
||||
B. 「调动导出」第34列公式判定 = 已发 的人员(前序已发起、名单中补录,
|
||||
多为人工在 HR 发起且流程可能已办结,运行中流程反查不到),
|
||||
直接按已发起回写,发起时间取「操作时间」(非当天)。
|
||||
发起成功以 HR 系统为准:
|
||||
1. HR 核查:遍历运行中「改签离职电子签」流程按表单 base_code 匹配工号,
|
||||
再按流程主键查签署记录,is_initiate_sign 非空非 0 即已发起
|
||||
1. HR 核查(仅待办路径):遍历运行中「改签离职电子签」流程按表单 base_code
|
||||
匹配工号,再按流程主键查签署记录,is_initiate_sign 非空非 0 即已发起
|
||||
(step4 自动发起与人工在 HR 里发起同样命中);未发起/运行中流程未找到
|
||||
的保留待办,不回写 AI 表、不回填、不移除;
|
||||
2. HR 已发起者,候选再与名单表取交集(列表内但名单无行的打日志提示,不回写);
|
||||
@@ -41,7 +44,8 @@ import openpyxl
|
||||
from .xq35_step2_sign_new_contract import ( # noqa: E402
|
||||
AITABLE_BASE_ID, AITABLE_OPERATOR_UNIONID, _aitable_request)
|
||||
from .step2_transfer_initiate import ( # noqa: E402
|
||||
TARGET_SHEET, _hr_session, load_pending_list, remove_pending)
|
||||
JUDGE_SENT, KEY_CODE_COL, OP_TIME_COL, SOURCE_HEADER_ROW, SOURCE_SHEET,
|
||||
TARGET_SHEET, VERDICT_COL, _hr_session, load_pending_list, remove_pending)
|
||||
from .step3_transfer_todo import ( # noqa: E402
|
||||
WORKFORM_FORM_ID, _find_push_table, _log, get_business_data,
|
||||
list_running_workflows)
|
||||
@@ -95,6 +99,46 @@ def _ms_day(value):
|
||||
|
||||
|
||||
# ---------- 数据源:待办列表 + 名单表字段 ----------
|
||||
def load_sent_rows():
|
||||
"""「调动导出」第34列 = 已发 的数据行 -> {工号: 操作时间ms}。
|
||||
|
||||
已发 = 前序已发起(HR 侧发起,流程可能早已办结,运行中流程反查不到),
|
||||
故不走 check_hr_initiated,直接按已发起回写;发起时间取「操作时间」。
|
||||
第34列公式缓存由第②步刷新落值;取不到缓存(当天未跑②)时本轮跳过该路径。
|
||||
"""
|
||||
path, _header = _find_push_table()
|
||||
try:
|
||||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||
except PermissionError as exc:
|
||||
raise RuntimeError(
|
||||
f"文件被占用,无法读取:{path}\n请先在 WPS/Excel 中关闭该文件后重试。") from exc
|
||||
try:
|
||||
if SOURCE_SHEET not in wb.sheetnames:
|
||||
raise RuntimeError(f"{os.path.basename(path)} 缺少「{SOURCE_SHEET}」sheet")
|
||||
ws = wb[SOURCE_SHEET]
|
||||
sent, uncached = {}, 0
|
||||
for r in range(SOURCE_HEADER_ROW + 1, ws.max_row + 1):
|
||||
code = _s(ws.cell(r, KEY_CODE_COL).value)
|
||||
if not code:
|
||||
continue
|
||||
raw = ws.cell(r, VERDICT_COL).value
|
||||
if raw is None:
|
||||
uncached += 1
|
||||
continue
|
||||
if str(raw).strip() != JUDGE_SENT:
|
||||
continue
|
||||
sent[code] = _ms_day(ws.cell(r, OP_TIME_COL).value)
|
||||
finally:
|
||||
wb.close()
|
||||
if uncached:
|
||||
_log(f"[已发] 「{SOURCE_SHEET}」第{VERDICT_COL}列有 {uncached} 行取不到公式结果,"
|
||||
f"已发回写本轮跳过(请先执行第②步刷新公式后重试)")
|
||||
return {}
|
||||
_log(f"[已发] 「{SOURCE_SHEET}」第{VERDICT_COL}列 = {JUDGE_SENT} 的 {len(sent)} 人"
|
||||
f"{':' + '、'.join(sorted(sent)) if sent else ''}")
|
||||
return sent
|
||||
|
||||
|
||||
def fetch_field_choices():
|
||||
"""「现/原单位名称」字段选项集(两字段选项一致,取并集兜底)。
|
||||
|
||||
@@ -244,9 +288,10 @@ def backfill_init_dates(rows, items):
|
||||
return done
|
||||
|
||||
|
||||
def build_fields(row, today_ms, choices):
|
||||
def build_fields(row, init_ms, choices):
|
||||
"""名单行 + 发起时间 + 选项集 -> AI 表新增行 fields(空值字段不写)。
|
||||
|
||||
发起时间 init_ms:待办路径=当天;已发路径=「调动导出」操作时间。
|
||||
singleSelect(是否已发起改签离职/现单位名称/原单位名称)写入传选项名字符串;
|
||||
单位名称经 pick_unit 匹配选项集,未命中不写该字段(留空告警)。
|
||||
"""
|
||||
@@ -254,7 +299,7 @@ def build_fields(row, today_ms, choices):
|
||||
"姓名": row["姓名"],
|
||||
"工号": row["工号"],
|
||||
FIELD_INITIATED: "是",
|
||||
FIELD_INIT_TIME: today_ms,
|
||||
FIELD_INIT_TIME: init_ms,
|
||||
}
|
||||
t = _ms_day(row["调动时间"])
|
||||
if t:
|
||||
@@ -313,28 +358,42 @@ def check_hr_initiated(session, pending):
|
||||
def main(dry_run=None):
|
||||
dry_run = DRY_RUN if dry_run is None else dry_run
|
||||
pending = load_pending_list()
|
||||
if not pending:
|
||||
_log("[待办] 待办工号列表为空(本批次无人待办),无事可做")
|
||||
sent = load_sent_rows()
|
||||
if not pending and not sent:
|
||||
_log("[待办] 待办工号列表为空,且「调动导出」无已发人员,无事可做")
|
||||
return {"added": 0, "skip_exists": 0, "skip_noroster": 0,
|
||||
"not_initiated": 0, "backfill": 0}
|
||||
_log("[待办] 本批待办 {} 人:{}".format(
|
||||
len(pending), "、".join(f"{c}{n}" for c, n in sorted(pending.items()))))
|
||||
"not_initiated": 0, "backfill": 0, "sent": 0}
|
||||
if pending:
|
||||
_log("[待办] 本批待办 {} 人:{}".format(
|
||||
len(pending), "、".join(f"{c}{n}" for c, n in sorted(pending.items()))))
|
||||
roster = load_roster_rows()
|
||||
existing = fetch_follow_records()
|
||||
|
||||
# 发起成功以 HR 为准:未发起/无流程的保留待办,不回写不回填不移除
|
||||
session = _hr_session()
|
||||
initiated, miss = check_hr_initiated(session, pending)
|
||||
stats = {"added": 0, "skip_exists": 0, "skip_noroster": 0,
|
||||
"not_initiated": len(miss), "backfill": 0}
|
||||
for code, reason in sorted(miss.items()):
|
||||
_log(f"[跳过] {code} {pending[code]} | {reason},保留待办等下次")
|
||||
if not initiated:
|
||||
_log("[完成] HR 侧无人已发起,本轮不回写(试算模式仅核查)"
|
||||
if dry_run else "[完成] HR 侧无人已发起,本轮不回写")
|
||||
"not_initiated": 0, "backfill": 0, "sent": len(sent)}
|
||||
# 待办路径:发起成功以 HR 为准,未发起/无流程的保留待办,不回写不回填不移除
|
||||
initiated = {}
|
||||
if pending:
|
||||
session = _hr_session()
|
||||
initiated, miss = check_hr_initiated(session, pending)
|
||||
stats["not_initiated"] = len(miss)
|
||||
for code, reason in sorted(miss.items()):
|
||||
_log(f"[跳过] {code} {pending[code]} | {reason},保留待办等下次")
|
||||
# 已发路径:公式已判定前序已发起(流程可能已办结),直接按已发起回写
|
||||
sent_only = {c: ms for c, ms in sent.items() if c not in initiated}
|
||||
|
||||
now_ms = _ms_day(datetime.now())
|
||||
# 回写目标:工号 -> 发起时间(已发优先取操作时间,待办取当天)
|
||||
targets = {code: (sent.get(code) or now_ms) for code in initiated}
|
||||
targets.update({code: (ms or now_ms) for code, ms in sent_only.items()})
|
||||
|
||||
if not targets:
|
||||
_log("[完成] 本轮无人可回写,不动 AI 表"
|
||||
+ ("(试算模式仅核查)" if dry_run else ""))
|
||||
_log(f"[汇总] HR已发起=0 未发起或无流程={stats['not_initiated']} "
|
||||
f"名单缺行={stats['skip_noroster']} 新增={stats['added']} "
|
||||
f"已有跳过={stats['skip_exists']} 发起日期回填={stats['backfill']}"
|
||||
f"已发={len(sent_only)} 名单缺行={stats['skip_noroster']} "
|
||||
f"新增={stats['added']} 已有跳过={stats['skip_exists']} "
|
||||
f"发起日期回填={stats['backfill']}"
|
||||
f"{'(试算模式)' if dry_run else ''}")
|
||||
return stats
|
||||
|
||||
@@ -342,27 +401,28 @@ def main(dry_run=None):
|
||||
if not choices:
|
||||
raise RuntimeError("未能获取「现/原单位名称」字段选项集,终止回写以免单位名称写空")
|
||||
add_items, done_codes, init_items = [], [], []
|
||||
today_ms = _ms_day(datetime.now())
|
||||
for code in sorted(initiated):
|
||||
for code, init_ms in sorted(targets.items()):
|
||||
tag = "已发" if code in sent_only else "待办"
|
||||
row = roster.get(code)
|
||||
if row is None:
|
||||
_log(f"[跳过] {code} {pending[code]} | 名单表中无该工号,无法取字段")
|
||||
_log(f"[跳过·{tag}] {code} | 名单表中无该工号,无法取字段")
|
||||
stats["skip_noroster"] += 1
|
||||
continue
|
||||
move_ms = _ms_day(row["调动时间"])
|
||||
dup = next(((rid, m, im) for rid, m, im in existing.get(code, [])
|
||||
if m is not None and m == move_ms), None)
|
||||
if dup:
|
||||
_log(f"[跳过] {code} {row['姓名']} | 本笔调动({row['调动时间']})"
|
||||
_log(f"[跳过·{tag}] {code} {row['姓名']} | 本笔调动({row['调动时间']})"
|
||||
f"AI 表已有记录(record {dup[0]}),视为已回写")
|
||||
stats["skip_exists"] += 1
|
||||
done_codes.append(code)
|
||||
init_items.append((code, dup[2]))
|
||||
continue
|
||||
fields = build_fields(row, today_ms, choices)
|
||||
fields = build_fields(row, init_ms, choices)
|
||||
warn = "" if ("现单位名称" in fields and "原单位名称" in fields) \
|
||||
else "(存在无匹配选项的单位名称,已留空待人工核对)"
|
||||
_log(f"[回写] {code} {row['姓名']} | 现单位 {fields.get('现单位名称') or '空'} | "
|
||||
_log(f"[回写·{tag}] {code} {row['姓名']} | "
|
||||
f"现单位 {fields.get('现单位名称') or '空'} | "
|
||||
f"原单位 {fields.get('原单位名称') or '空'} | 调动 {row['调动时间']}{warn}")
|
||||
add_items.append(fields)
|
||||
|
||||
@@ -371,7 +431,7 @@ def main(dry_run=None):
|
||||
_log(f"[完成] AI 表新增 {len(add_items)} 行(record id:{ids})")
|
||||
stats["added"] = len(add_items)
|
||||
done_codes.extend(f["工号"] for f in add_items)
|
||||
init_items.extend((f["工号"], today_ms) for f in add_items)
|
||||
init_items.extend((f["工号"], targets[f["工号"]]) for f in add_items)
|
||||
elif add_items:
|
||||
_log(f"[完成] 待新增 {len(add_items)} 行(试算模式,未写入)")
|
||||
|
||||
@@ -383,8 +443,9 @@ def main(dry_run=None):
|
||||
if done_codes and not dry_run:
|
||||
remove_pending(done_codes)
|
||||
_log("[待办] 回写完成,已从待办列表移除:{}".format("、".join(done_codes)))
|
||||
_log(f"[汇总] HR已发起={len(initiated)} 未发起或无流程={stats['not_initiated']} "
|
||||
f"名单缺行={stats['skip_noroster']} 新增={stats['added']} "
|
||||
f"已有跳过={stats['skip_exists']} 发起日期回填={stats['backfill']}"
|
||||
_log(f"[汇总] 待办已发起={len(initiated)} 已发={len(sent_only)} "
|
||||
f"未发起或无流程={stats['not_initiated']} 名单缺行={stats['skip_noroster']} "
|
||||
f"新增={stats['added']} 已有跳过={stats['skip_exists']} "
|
||||
f"发起日期回填={stats['backfill']}"
|
||||
f"{'(试算模式)' if dry_run else ''}")
|
||||
return stats
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0037",
|
||||
"name": "调动改签离职电子签",
|
||||
"version": "1.1.6",
|
||||
"description": "XQ0037 调动改签离职电子签:按步骤执行 ①调动台账导出(近三月台账 + 近3天筛选)②按公式判定已发/需要追加「已发起名单」+ HR置位+群提醒 ③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进 ⑥签署完成核查回写;钉钉AI表格字段接力驱动,HR 会话由壳子注入",
|
||||
"version": "1.1.7",
|
||||
"description": "XQ0037 调动改签离职电子签:按步骤执行 ①调动台账导出(近三月台账 + 近3天筛选)②按公式判定已发/需要追加「已发起名单」+ HR置位+群提醒 ③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进(含已发补录) ⑥签署完成核查回写;钉钉AI表格字段接力驱动,HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
|
||||
@@ -19,8 +19,8 @@ from .data import crm_export
|
||||
class CrmDataExportPlugin(ScenePlugin):
|
||||
id = "xq0048"
|
||||
name = "CRM数据导出"
|
||||
version = "1.0.0"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出,"
|
||||
version = "1.1.6"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出(导出内容可勾选),"
|
||||
"登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),"
|
||||
"按各报表日期规则自动计算区间,礼品卡订单按月拆分")
|
||||
platform = "" # CRM 为钉钉扫码登录,插件内自带登录流程,不使用底座共享登录态
|
||||
@@ -29,6 +29,8 @@ class CrmDataExportPlugin(ScenePlugin):
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致
|
||||
fields = {
|
||||
"reports": {"type": "array", "title": "导出内容", "default": [],
|
||||
"description": "勾选键列表(截图=__screenshot__,报表=接口#规则);空/缺省=全部导出"},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": "",
|
||||
"description": "留空=D:\\资料\\财务\\CRM数据导出"},
|
||||
"debug_mode": {"type": "boolean", "title": "调试日志", "default": False},
|
||||
@@ -44,12 +46,23 @@ class CrmDataExportPlugin(ScenePlugin):
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"保存目录:{save_dir}")
|
||||
|
||||
result = crm_export.run_export(save_dir)
|
||||
report_keys = fields.get("reports")
|
||||
reports, include_shot = config.filter_reports(report_keys)
|
||||
if not reports and not include_shot:
|
||||
raise RuntimeError("未勾选任何导出内容,请至少勾选一项")
|
||||
if report_keys is None:
|
||||
ctx.log("导出内容:全部(截图 + %d 张报表)" % len(reports))
|
||||
else:
|
||||
ctx.log(f"导出内容:{'截图、' if include_shot else ''}{len(reports)} 张报表(按勾选)")
|
||||
|
||||
result = crm_export.run_export(save_dir, report_keys=report_keys)
|
||||
config.progress(100)
|
||||
|
||||
files = result.get("exports") or []
|
||||
summary = (f"截图 {1 if result.get('screenshot') else 0}/1,"
|
||||
f"报表 {result.get('done')}/{result.get('total')},共 {len(files) + 1} 个文件")
|
||||
shot_part = f"截图 {1 if result.get('screenshot') else 0}/1," if include_shot else ""
|
||||
summary = (f"{shot_part}"
|
||||
f"报表 {result.get('done')}/{result.get('total')},"
|
||||
f"共 {len(files) + (1 if result.get('screenshot') else 0)} 个文件")
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
|
||||
@@ -45,6 +45,57 @@ def get_browser_profile_dir():
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0048')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶。
|
||||
|
||||
窗口被其它窗口遮挡或最小化时,渲染进程可能一直不出帧,Page.captureScreenshot
|
||||
会等到超时(DrissionPage 默认 30s)。全屏 + 置顶用于规避这种遮挡型超时;
|
||||
失败仅告警,不影响后续流程。"""
|
||||
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
|
||||
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3 # 截图/单报表重试
|
||||
PAGE_SIZE = 13 # 与页面一致;实测服务端导出不受分页影响
|
||||
@@ -64,7 +115,8 @@ UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
# 规则:prev=前一天单日;prev_today=昨日~今日;month_to_today=本月1日~今日;
|
||||
# prev_prev=昨日~昨日;month1_to_prev=本月1日~前一天;last_month=上月完整;
|
||||
# last3_months=近 3 个自然月按月拆分(止日不超过前一天)
|
||||
# 日期参数字段:报表统计类为 reportDate;开卡订单/会员退卡为 period;
|
||||
# 日期参数字段:报表统计类为 reportDate;淘宝订单为 createTimePeriod(页面「购买时间」);
|
||||
# 微盟核销为 validateDatePeriod;开卡订单/会员退卡为 period;
|
||||
# 礼品卡订单为 receiveTimePeriod(接口限制跨度 ≤31 天,故按月拆分)
|
||||
REPORTS = [
|
||||
('团购支付数据', 'report/groupPay/export', 'prev', None, 'reportDate'),
|
||||
@@ -72,9 +124,9 @@ REPORTS = [
|
||||
('第三方支付(门店)', 'report/thirdPayShop/export', 'prev', None, 'reportDate'),
|
||||
('支付数据', 'report/unionPay/export', 'prev', None, 'reportDate'),
|
||||
('团购数据', 'report/groupData/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'createTimePeriod'),
|
||||
('技师综合业绩', 'report/comprehensivePerformance/export', 'month_to_today', None, 'reportDate'),
|
||||
('微盟核销统计', 'report/weimeng/exportValidate', 'prev_prev', None, 'reportDate'),
|
||||
('微盟核销统计', 'report/weimeng/exportValidate', 'prev_prev', None, 'validateDatePeriod'), # 该页日期字段是 validateDatePeriod("起 止")
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'last_month', None, 'reportDate'),
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'month_to_today', None, 'reportDate'),
|
||||
('储值卡消费', 'report/debitCardConsume/export', 'month1_to_prev', None, 'reportDate'),
|
||||
@@ -87,6 +139,30 @@ REPORTS = [
|
||||
('礼品卡订单', 'giftcard/order/export', 'last3_months', None, 'receiveTimePeriod'),
|
||||
]
|
||||
|
||||
# ==================== 导出内容选择(UI 勾选) ====================
|
||||
SCREENSHOT_KEY = '__screenshot__' # 储值卡余额整页截图的勾选键
|
||||
|
||||
|
||||
def report_key(entry):
|
||||
"""报表稳定勾选键:导出接口#日期规则(与 UI 清单一一对应,跨版本稳定)。"""
|
||||
_title, path, rule, _extra, _date_key = entry
|
||||
return f'{path}#{rule}'
|
||||
|
||||
|
||||
def filter_reports(keys):
|
||||
"""按 UI 勾选键筛选导出内容。
|
||||
|
||||
keys 为 None(旧配置/未传)→ 全部导出;否则按勾选键过滤。
|
||||
返回 (报表列表, 是否含储值卡余额截图)。
|
||||
"""
|
||||
if keys is None:
|
||||
return list(REPORTS), True
|
||||
wanted = {str(k) for k in keys}
|
||||
include_shot = SCREENSHOT_KEY in wanted
|
||||
reports = [e for e in REPORTS if report_key(e) in wanted]
|
||||
return reports, include_shot
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
|
||||
@@ -27,6 +27,13 @@ from . import crm_login
|
||||
_auth_dead = False
|
||||
|
||||
|
||||
class ScanTimeoutError(RuntimeError):
|
||||
"""人工扫码/登录未完成——属人工未完成,不是浏览器异常。
|
||||
|
||||
必须与 DrissionPage 的 CDP 超时(内置 TimeoutError)区分:后者是浏览器卡顿,
|
||||
应正常重试,绝不能判定登录态失效、连带跳过全部报表。"""
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
@@ -142,7 +149,7 @@ def _goto_ready(page, url):
|
||||
time.sleep(2)
|
||||
if _is_login_page(page.url):
|
||||
if not _wait_login(page):
|
||||
raise TimeoutError(f"登录未完成({config.LOGIN_WAIT}s 超时),请在窗口内完成钉钉扫码")
|
||||
raise ScanTimeoutError(f"登录未完成({config.LOGIN_WAIT}s 超时),请在窗口内完成钉钉扫码")
|
||||
page.get(url)
|
||||
continue
|
||||
if config.PAGE_TITLE_KEYWORD in (page.title or ''):
|
||||
@@ -168,6 +175,8 @@ def _capture_balance(save_dir, date_str, headless):
|
||||
co.set_user_data_path(profile_dir)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
if not headless:
|
||||
config.apply_window_mode(page) # 全屏 + 置顶,规避遮挡导致的截图超时
|
||||
# 先看浏览器 profile 自身会话:有效就不注入,避免用旧快照覆盖仍有效的会话
|
||||
page.get(config.BALANCE_URL)
|
||||
if _is_login_page(page.url) or not _api_ok(page):
|
||||
@@ -190,13 +199,13 @@ def _capture_balance(save_dir, date_str, headless):
|
||||
|
||||
|
||||
def _screenshot(save_dir, date_str):
|
||||
"""截图重试 3 次;登录超时属人工未完成,不再重开浏览器。"""
|
||||
"""截图重试 3 次;仅人工扫码超时不重试,浏览器卡顿(CDP 超时)照常重试。"""
|
||||
last_err = None
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次截图 → {config.BALANCE_URL}")
|
||||
return _capture_balance(save_dir, date_str, config.HEADLESS)
|
||||
except TimeoutError:
|
||||
except ScanTimeoutError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
@@ -266,13 +275,13 @@ def _download(session, url, params):
|
||||
return None, False
|
||||
|
||||
|
||||
def _export_one(title, path, rule, extra, save_dir, date_key):
|
||||
def _export_one(title, path, rule, extra, save_dir, date_key, idx, total):
|
||||
"""导出单张报表(按月规则会产出多个文件),返回落盘路径列表。"""
|
||||
return [_export_window(title, path, beg, end, extra, save_dir, date_key)
|
||||
return [_export_window(title, path, beg, end, extra, save_dir, date_key, idx, total)
|
||||
for beg, end in _date_windows(rule)]
|
||||
|
||||
|
||||
def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
def _export_window(title, path, beg, end, extra, save_dir, date_key, idx, total):
|
||||
"""导出某个日期窗口(含 401 → 刷新登录态 → 重试),返回落盘路径。"""
|
||||
global _auth_dead
|
||||
|
||||
@@ -283,6 +292,7 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
if date_key == 'reportDate' and beg == end:
|
||||
date_val = f'{beg:%Y-%m-%d}'
|
||||
params = {'pageNum': 1, 'pageSize': config.PAGE_SIZE, date_key: date_val}
|
||||
date_desc = f'{date_key}={date_val}'
|
||||
if extra:
|
||||
params.update(extra)
|
||||
|
||||
@@ -301,7 +311,7 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
_auth_dead = True
|
||||
break
|
||||
try:
|
||||
_log(f"[{attempt}/{config.RETRY_MAX}] {filename} ← {path} {date_key}={date_val}")
|
||||
_log(f"[{idx}/{total}] {filename} ← {path} {date_desc}")
|
||||
content, auth_failed = _download(session, url, params)
|
||||
if content:
|
||||
with open(save_path, 'wb') as f:
|
||||
@@ -326,12 +336,14 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def run_export(save_dir='', date_str=''):
|
||||
"""截图 + 18 张报表导出。
|
||||
def run_export(save_dir='', date_str='', report_keys=None):
|
||||
"""截图 + 报表导出(可按勾选筛选导出内容)。
|
||||
|
||||
参数:
|
||||
save_dir 保存目录,默认 D:\\资料\\财务\\CRM数据导出
|
||||
date_str 截图文件名日期(YYYYMMDD),默认当日
|
||||
report_keys 勾选键列表(截图=__screenshot__,报表=接口#规则);
|
||||
None/缺省 = 全部导出
|
||||
返回:
|
||||
{'screenshot': 截图路径, 'exports': [xlsx 路径...], 'errors': [],
|
||||
'done': 成功报表数, 'total': 报表总数}
|
||||
@@ -342,6 +354,7 @@ def run_export(save_dir='', date_str=''):
|
||||
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
|
||||
date_str = (date_str or '').strip() or time.strftime('%Y%m%d')
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
reports, include_shot = config.filter_reports(report_keys)
|
||||
_auth_dead = False
|
||||
errors = []
|
||||
|
||||
@@ -352,31 +365,32 @@ def run_export(save_dir='', date_str=''):
|
||||
else:
|
||||
_log("登录态无效,本次运行需扫码一次(成功后后续步骤全部复用)……", "WARN")
|
||||
|
||||
# ---------- 1) 储值卡余额截图 ----------
|
||||
# ---------- 1) 储值卡余额截图(按勾选) ----------
|
||||
config.progress(5)
|
||||
shot = ''
|
||||
try:
|
||||
shot = _screenshot(save_dir, date_str)
|
||||
except TimeoutError as e:
|
||||
# 扫码超时属人工未完成,后续报表也必然 401,直接标记无救
|
||||
_auth_dead = True
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败(登录超时):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败:{e}", "ERROR")
|
||||
if include_shot:
|
||||
try:
|
||||
shot = _screenshot(save_dir, date_str)
|
||||
except ScanTimeoutError as e:
|
||||
# 扫码超时属人工未完成,后续报表也必然 401,直接标记无救
|
||||
_auth_dead = True
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败(登录超时):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败:{e}", "ERROR")
|
||||
config.progress(12)
|
||||
|
||||
# ---------- 2) 18 张报表导出 ----------
|
||||
# ---------- 2) 报表导出(按勾选) ----------
|
||||
saved, skipped = [], []
|
||||
done = 0
|
||||
total = len(config.REPORTS)
|
||||
for idx, (title, path, rule, extra, date_key) in enumerate(config.REPORTS, start=1):
|
||||
total = len(reports)
|
||||
for idx, (title, path, rule, extra, date_key) in enumerate(reports, start=1):
|
||||
if _auth_dead:
|
||||
skipped.append(title)
|
||||
continue
|
||||
try:
|
||||
saved.extend(_export_one(title, path, rule, extra, save_dir, date_key))
|
||||
saved.extend(_export_one(title, path, rule, extra, save_dir, date_key, idx, total))
|
||||
done += 1
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
@@ -385,7 +399,8 @@ def run_export(save_dir='', date_str=''):
|
||||
if skipped:
|
||||
errors.append(f"{'、'.join(skipped)}:登录态失效,已跳过")
|
||||
|
||||
_log(f"本次运行完成:截图 {1 if shot else 0}/1,报表 {done}/{total}(文件 {len(saved)} 个)")
|
||||
shot_part = f"截图 {1 if shot else 0}/1," if include_shot else ""
|
||||
_log(f"本次运行完成:{shot_part}报表 {done}/{total}(文件 {len(saved)} 个)")
|
||||
if errors:
|
||||
raise RuntimeError(f"存在失败项:{';'.join(errors)}")
|
||||
return {'screenshot': shot, 'exports': saved, 'errors': [],
|
||||
|
||||
@@ -334,6 +334,8 @@ def _attempt(force, headless, wait_scan):
|
||||
co.set_user_data_path(profile_dir)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
if not headless:
|
||||
config.apply_window_mode(page) # 全屏 + 置顶,扫码窗口不被遮挡
|
||||
if not force and _check_reuse(page):
|
||||
# 静默重登可能已在浏览器内刷新会话,等首屏请求结束后同步文件快照
|
||||
time.sleep(config.LOGIN_SETTLE)
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0048",
|
||||
"name": "CRM数据导出",
|
||||
"version": "1.0.0",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"version": "1.1.6",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出(导出内容可勾选)。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0048"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
@@ -16,6 +16,15 @@
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reports": {
|
||||
"type": "array",
|
||||
"title": "导出内容",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": [],
|
||||
"description": "勾选键列表(截图=__screenshot__,报表=接口#规则);空/缺省=全部导出"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
|
||||
@@ -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>CRM数据导出</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": "xq0048-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,635 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<transition name="fade-slide">
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
</transition>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<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">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="7 10 12 15 17 10" />
|
||||
<line x1="12" y1="15" x2="12" y2="3" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">勾选导出内容,参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span v-if="lastSavedAt" class="saved">
|
||||
<i class="dot" />已保存 {{ lastSavedAt }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running" @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">
|
||||
<!-- 执行说明 -->
|
||||
<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="flow-desc">
|
||||
<div class="flow-item"><span class="flow-no">1</span>登录态预检:约 30 分钟内免扫码;失效时自动打开浏览器,钉钉扫码一次后全程复用</div>
|
||||
<div class="flow-item"><span class="flow-no">2</span>「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png</div>
|
||||
<div class="flow-item"><span class="flow-no">3</span>按勾选的报表自动计算日期区间,逐张导出 xlsx(礼品卡订单因接口限制跨度 ≤31 天,按月拆分)</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 导出内容(按业务分组) -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">导出内容</span>
|
||||
<span class="sec-line" />
|
||||
<span class="sec-count">已选 <b>{{ form.reports.length }}</b> / {{ ALL_KEYS.length }} 项</span>
|
||||
<el-button size="small" text type="primary" :disabled="running" @click="selectAll">全选</el-button>
|
||||
<el-button size="small" text :disabled="running || !form.reports.length" @click="clearAll">清空</el-button>
|
||||
</div>
|
||||
<div class="groups">
|
||||
<div v-for="g in GROUPED" :key="g.name" class="grp">
|
||||
<div class="grp-head">
|
||||
<el-checkbox :model-value="g.all" :indeterminate="g.some" :disabled="running"
|
||||
@change="toggleGroup(g)">{{ g.name }}</el-checkbox>
|
||||
<span class="grp-count" :class="{ full: g.all }">{{ g.picked }}/{{ g.items.length }}</span>
|
||||
</div>
|
||||
<div class="grp-body">
|
||||
<el-checkbox v-for="it in g.items" :key="it.key" :model-value="form.reports.includes(it.key)"
|
||||
:disabled="running" class="rep-item" @change="toggleItem(it.key)">
|
||||
<span class="rep-name">{{ it.name }}</span>
|
||||
<el-tooltip :content="it.tag" placement="top" :show-after="150">
|
||||
<el-icon class="rep-info"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</el-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tip">日期区间由各报表规则自动计算:截图=当天;前一天;昨日~今日;昨日;本月1日~今日;本月1日~昨日;上月完整;近3个自然月(礼品卡订单按月拆分)</div>
|
||||
</section>
|
||||
|
||||
<!-- 执行设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">执行设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\财务\CRM数据导出" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">截图与全部 xlsx 统一输出到保存目录;「调试日志」开启后输出完整调试信息(默认关闭)</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<transition name="fade-slide">
|
||||
<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>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
|
||||
// 导出内容清单(key 与后端 config 一致:截图=__screenshot__,报表=导出接口#日期规则)
|
||||
const ITEMS = [
|
||||
{ key: '__screenshot__', name: '储值卡余额整页截图', tag: '截图·当天', group: '储值卡余额' },
|
||||
{ key: 'report/groupPay/export#prev', name: '团购支付数据', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/cashPay/export#prev', name: '现金支付', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/thirdPayShop/export#prev', name: '第三方支付(门店)', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/unionPay/export#prev', name: '支付数据', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/groupData/export#prev_today', name: '团购数据', tag: '昨日~今日', group: '支付数据' },
|
||||
{ key: 'report/taobaoTicket/export#prev_today', name: '淘宝订单数据', tag: '昨日~今日', group: '支付数据' },
|
||||
{ key: 'report/comprehensivePerformance/export#month_to_today', name: '技师综合业绩', tag: '本月1日~今日', group: '业绩与核销' },
|
||||
{ key: 'report/weimeng/exportValidate#prev_prev', name: '微盟核销统计', tag: '昨日', group: '业绩与核销' },
|
||||
{ key: 'report/debitCardConsume/export#month1_to_prev', name: '储值卡消费', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/depositData/export#month1_to_prev', name: '储值卡线上充值', tag: '本月1日~昨日·渠道=管理端', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderDeposit/export#month1_to_prev', name: '霸王餐充值明细', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderConsume/export#month1_to_prev', name: '霸王餐消费明细', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderBalance/export#month1_to_prev', name: '霸王餐余额查询', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'member/order/export#month1_to_prev', name: '开卡订单', tag: '本月1日~昨日', group: '会员与卡券' },
|
||||
{ key: 'member/cancel/export#month1_to_prev', name: '会员退卡', tag: '本月1日~昨日', group: '会员与卡券' },
|
||||
{ key: 'giftcard/order/export#last3_months', name: '礼品卡订单', tag: '近3个自然月·按月拆分', group: '会员与卡券' },
|
||||
{ key: 'report/miniProgramOrder/export#last_month', name: '小程序订单(上月完整)', tag: '上月完整', group: '小程序' },
|
||||
{ key: 'report/miniProgramOrder/export#month_to_today', name: '小程序订单(本月至今)', tag: '本月1日~今日', group: '小程序' },
|
||||
]
|
||||
const ALL_KEYS = ITEMS.map((i) => i.key)
|
||||
const GROUPS = [...new Set(ITEMS.map((i) => i.group))]
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
reports: [...ALL_KEYS],
|
||||
save_dir: '',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.reports.length) {
|
||||
ElMessage.warning('请至少勾选一项导出内容')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
// 按业务分组:组级全选状态 + 已选计数
|
||||
const GROUPED = computed(() => GROUPS.map((name) => {
|
||||
const items = ITEMS.filter((i) => i.group === name)
|
||||
const picked = items.filter((i) => form.reports.includes(i.key)).length
|
||||
return {
|
||||
name,
|
||||
items,
|
||||
picked,
|
||||
all: picked === items.length,
|
||||
some: picked > 0 && picked < items.length,
|
||||
}
|
||||
}))
|
||||
|
||||
function toggleItem(key) {
|
||||
const idx = form.reports.indexOf(key)
|
||||
if (idx >= 0) form.reports.splice(idx, 1)
|
||||
else form.reports.push(key)
|
||||
}
|
||||
|
||||
function toggleGroup(g) {
|
||||
const keys = g.items.map((i) => i.key)
|
||||
if (g.all) {
|
||||
form.reports = form.reports.filter((k) => !keys.includes(k))
|
||||
} else {
|
||||
keys.forEach((k) => {
|
||||
if (!form.reports.includes(k)) form.reports.push(k)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function selectAll() {
|
||||
form.reports = [...ALL_KEYS]
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
form.reports = []
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ---------- 页面骨架 ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 6px 4px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: opacity 0.25s ease, transform 0.25s ease;
|
||||
}
|
||||
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
/* ---------- 主容器(无边框平铺:外层由壳子 iframe 的边框统一包裹) ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.panel :deep(.el-card__header) {
|
||||
padding: 6px 2px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel :deep(.el-card__body) {
|
||||
padding: 16px 2px 2px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-6));
|
||||
box-shadow: inset 0 0 0 1px var(--el-color-primary-light-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
line-height: 1.2;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: #2ea44f;
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
border: 1px solid rgba(46, 164, 79, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #2ea44f;
|
||||
}
|
||||
|
||||
/* ---------- 表单分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--el-border-color-lighter), transparent);
|
||||
}
|
||||
|
||||
.sec-count {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-count b {
|
||||
color: var(--el-color-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 执行说明 */
|
||||
.flow-desc {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.flow-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.flow-no {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 6px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* ---------- 导出内容分组 ---------- */
|
||||
.groups {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.grp {
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 10px;
|
||||
padding: 10px 14px 12px;
|
||||
background: var(--el-fill-color-blank);
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.grp:hover {
|
||||
border-color: var(--el-color-primary-light-5);
|
||||
}
|
||||
|
||||
.grp-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding-bottom: 6px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: 1px dashed var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
.grp-head :deep(.el-checkbox__label) {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.grp-count {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
background: var(--el-fill-color);
|
||||
border-radius: 999px;
|
||||
padding: 1px 8px;
|
||||
}
|
||||
|
||||
.grp-count.full {
|
||||
color: var(--el-color-success);
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
}
|
||||
|
||||
.grp-body {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
gap: 2px 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.grp-body :deep(.el-checkbox) {
|
||||
margin-right: 0;
|
||||
height: 26px;
|
||||
}
|
||||
|
||||
.grp-body :deep(.el-checkbox__label) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-primary);
|
||||
padding-left: 4px;
|
||||
}
|
||||
|
||||
.rep-info {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
cursor: help;
|
||||
flex-shrink: 0;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.rep-info:hover {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(280px, 1fr) auto;
|
||||
gap: 0 18px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.grid :deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.grid :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 18px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
letter-spacing: 2px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
box-shadow: 0 6px 16px var(--el-color-primary-light-6);
|
||||
transition: filter 0.2s, box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
filter: brightness(1.06);
|
||||
box-shadow: 0 8px 20px var(--el-color-primary-light-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
|
||||
border: 1px solid var(--el-color-primary-light-6);
|
||||
box-shadow: 0 2px 10px var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar :deep(.el-progress-bar__outer) {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
|
||||
.status-bar :deep(.el-progress-bar__inner) {
|
||||
background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--el-color-primary);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--el-color-primary-light-6);
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px transparent;
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit,各插件 ui-src 只需声明自己的 id)
|
||||
export const PLUGIN_ID = 'xq0048'
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,340 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、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 new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return 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))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
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 })
|
||||
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) : {})
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + 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
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
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
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0048/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0048/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5198,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/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>CRM数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0048/assets/index-DLXNU8di.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0048/assets/index-CLtlaiAs.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user