feat: 更新3个插件版本并优化XQ0006考勤异常处理逻辑
- XQ0036门店员工起调薪处理:版本升至0.1.6,优化纳税单位解析逻辑,优先使用接口返回值,新增金色印象、金色湖畔、后浪会馆的纳税单位兜底规则 - XQ0047微盟数据导出:版本升至1.0.5,新增等待生成上限配置项,优化轮询超时处理逻辑 - XQ0006 EHR系统周考勤异常处理:版本升至1.4.1,重构推送逻辑,支持组织架构范围选择,新增dws推送通道,优化自动确认范围为整月轻微异常,新增组织架构同步功能
This commit is contained in:
@@ -5,21 +5,41 @@
|
||||
1) 会话校验:底座注入 HR session → getCurUserInfo 校验(失效提示重新登录);
|
||||
2) 拉取查询月份(默认 1 号查上月,否则当月)全部「未调整」考勤异常;
|
||||
3) 导出 Excel 底稿(试算模式只做这一步);
|
||||
4) 自动确认:范围=查询范围内全部数据(分批调用确认接口);
|
||||
5) 钉钉推送(口径与影刀版一致):仅推送上周职能序列 + 推送范围单位
|
||||
(默认总办/集团财经中心/金色湖畔事业部,部门路径不含「大区」)的严重异常给当事人,
|
||||
并把条数汇总推送到群机器人。
|
||||
4) 自动确认:整月轻微异常(迟到/早退 < 30 分钟,分批调用确认接口);
|
||||
5) 钉钉推送(口径):仅推送上周「组织架构勾选节点(含下级)」的严重异常给当事人,
|
||||
并把条数汇总推送到群。组织架构由界面「同步组织架构」拉取 HR 组织维护台账并固化为
|
||||
JSON,勾选节点按组织全路径前缀匹配数据行;未勾选则不推送当事人。
|
||||
优先用 dws(单聊 + 群、附 Excel);未装 dws 时当事人回退工作通知,
|
||||
群汇总不发送(需要附件能力)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from dingtalk_sdk.config import resolve_dws_bin
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_api, org_tree
|
||||
from .data.hr_api import HRSessionExpiredError
|
||||
from .logic import attendance_rules as rules
|
||||
from .report import attendance_report
|
||||
from .report import dingtalk_push
|
||||
|
||||
|
||||
def detect_dws(path_hint: str = "") -> str:
|
||||
"""检测 dws 是否可用,返回可执行路径(未安装返回空串)。
|
||||
|
||||
顺序:字段 dws_path > 环境变量 DINGTALK_DWS_BIN > 用户目录默认位置 > PATH。
|
||||
"""
|
||||
hint = str(path_hint or "").strip()
|
||||
if hint and os.path.isdir(hint):
|
||||
hint = os.path.join(hint, "dws.exe")
|
||||
try:
|
||||
return resolve_dws_bin(hint)
|
||||
except Exception: # noqa: BLE001 - 检测失败按未安装
|
||||
return ""
|
||||
|
||||
|
||||
def _as_bool(value, default=False):
|
||||
"""字段值转布尔(兼容 JSON 布尔与 "true"/"false" 字符串)。"""
|
||||
if value is None or value == "":
|
||||
@@ -29,14 +49,20 @@ def _as_bool(value, default=False):
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _split_units(value):
|
||||
"""把「总办, 集团财经中心」这类多值文本拆成单位列表(支持中英文逗号/顿号/分号)。"""
|
||||
def _parse_scope_paths(value):
|
||||
"""组织架构勾选结果 → 组织全路径列表(兼容 JSON 数组字符串 / 数组 / 换行文本)。"""
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [str(v).strip() for v in value if str(v or "").strip()]
|
||||
raw = str(value or "").strip()
|
||||
if not raw:
|
||||
return []
|
||||
for sep in (",", "、", ";", ";", "|", "\n"):
|
||||
raw = raw.replace(sep, ",")
|
||||
return [s.strip() for s in raw.split(",") if s.strip()]
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except ValueError:
|
||||
data = None
|
||||
if isinstance(data, list):
|
||||
return [str(v).strip() for v in data if str(v or "").strip()]
|
||||
return [s.strip() for s in raw.splitlines() if s.strip()]
|
||||
|
||||
|
||||
class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
@@ -44,10 +70,11 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0006"
|
||||
name = "EHR系统周考勤异常处理"
|
||||
version = "1.2.0"
|
||||
description = ("拉取查询月份未调整考勤异常并导出 Excel,整月全量自动确认;"
|
||||
"上周职能序列及推送范围单位(默认总办/集团财经中心/金色湖畔事业部/"
|
||||
"集团管理中心/集团营建中心/金色印象事业部,不含大区)的严重异常按人合并推送;"
|
||||
version = "1.4.1"
|
||||
description = ("拉取查询月份未调整考勤异常并导出 Excel,整月轻微异常自动确认;"
|
||||
"上周「组织架构所选范围(含下级)」的严重异常按人合并推送,"
|
||||
"组织架构支持一键同步最新并固化为 JSON;"
|
||||
"优先用 dws 单聊+群(附 Excel),未装 dws 时当事人回退工作通知、群汇总不发送;"
|
||||
"支持试算模式(只出表、不确认不推送)。")
|
||||
platform = "hr"
|
||||
uses_month = True
|
||||
@@ -70,38 +97,104 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
},
|
||||
"auto_confirm": {
|
||||
"type": "boolean", "title": "自动确认", "default": True,
|
||||
"description": "开启后对查询范围内全部异常调用确认接口(分批提交);试算模式下强制不确认",
|
||||
"description": "开启后对整月轻微异常(迟到/早退 < 30 分钟,不分职能序列)调用确认接口(分批提交);"
|
||||
"严重异常只推送不确认;试算模式下强制不确认",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉推送", "default": True,
|
||||
"description": "开启后推送上周职能序列及推送范围单位的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送",
|
||||
"description": "开启后推送上周组织架构所选范围的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送",
|
||||
},
|
||||
"push_units": {
|
||||
"type": "string", "title": "推送范围单位",
|
||||
"default": "总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部",
|
||||
"description": "除职能序列外,这些所属单位也推送(逗号/顿号分隔);留空=只推职能序列",
|
||||
"push_scope_paths": {
|
||||
"type": "string", "title": "推送范围(组织架构)", "default": "",
|
||||
"description": "界面组织树勾选的节点(组织全路径 JSON 数组,含全部下级);未勾选=不推送当事人",
|
||||
},
|
||||
"push_exclude_keyword": {
|
||||
"type": "string", "title": "推送排除关键字", "default": "大区",
|
||||
"description": "部门路径包含该关键字则不推送;留空表示不按部门路径排除",
|
||||
"dws_path": {
|
||||
"type": "string", "title": "dws 路径", "default": "",
|
||||
"description": "留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH);dws 负责当事人单聊与群汇总(附 Excel),"
|
||||
"检测不到时当事人回退工作通知、群汇总不发送",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
"push_group": {
|
||||
"type": "string", "title": "汇总群名", "default": "",
|
||||
"description": "dws 推送时的群全称(按群名精确匹配),留空用默认;并附带 Excel 底稿",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
"push_at_all": {
|
||||
"type": "boolean", "title": "汇总群 @所有人", "default": False,
|
||||
"description": "需群里有 @所有人 权限(仅 dws 通道生效)",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
fields = fields or {}
|
||||
# ---- 仅检测 dws(UI「检测」按钮:probe_dws=true,不取数、不推送) ----
|
||||
if _as_bool(fields.get("probe_dws"), False):
|
||||
path = detect_dws(str(fields.get("dws_path") or ""))
|
||||
if path:
|
||||
ctx.log(f"[INFO] dws 检测通过:{path}")
|
||||
else:
|
||||
ctx.log("[WARN] 未检测到 dws:执行时将回退工作通知 + 群机器人", "WARNING")
|
||||
return {
|
||||
"ok": True, "probe": True,
|
||||
"dws_available": bool(path), "dws_path": path,
|
||||
"summary": (f"dws 可用:{path}" if path
|
||||
else "未检测到 dws(执行时回退工作通知 + 群机器人)"),
|
||||
}
|
||||
# ---- 同步组织架构(UI「同步组织架构」按钮:action=sync_org,只拉组织、不取考勤) ----
|
||||
if str(fields.get("action") or "").strip() == "sync_org":
|
||||
try:
|
||||
return self._sync_org(ctx)
|
||||
except HRSessionExpiredError as e:
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再同步组织架构:{e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再同步组织架构") from e
|
||||
# ---- 读取已固化的组织架构(界面缓存丢失时回填,不访问 HR) ----
|
||||
if str(fields.get("action") or "").strip() == "load_org":
|
||||
payload = org_tree.load()
|
||||
if not payload:
|
||||
return {"ok": True, "org_tree": [], "count": 0,
|
||||
"summary": "本机还没有固化的组织架构,请点「同步组织架构」"}
|
||||
return {
|
||||
"ok": True,
|
||||
"org_tree": payload["tree"],
|
||||
"count": payload.get("count", 0),
|
||||
"fetched_at": payload.get("fetched_at", ""),
|
||||
"summary": f"已读取本机组织架构({payload.get('count', 0)} 个节点)",
|
||||
}
|
||||
try:
|
||||
return self._run(fields, ctx)
|
||||
except HRSessionExpiredError as e:
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再执行:{e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
|
||||
|
||||
def _sync_org(self, ctx):
|
||||
"""拉取 HR 组织维护台账 → 固化组织架构 JSON → 回传树供界面渲染。"""
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
session = config.require_session()
|
||||
ctx.progress(5)
|
||||
user_id, _treecode = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
ctx.progress(15)
|
||||
payload = org_tree.sync(
|
||||
session,
|
||||
on_progress=lambda page, total: ctx.progress(15 + int(75 * page / max(total, 1))))
|
||||
ctx.progress(100)
|
||||
summary = (f"组织架构同步完成:{payload['count']} 个组织节点,"
|
||||
f"已固化到 {config.ORG_TREE_FILE}")
|
||||
ctx.log(summary, "INFO")
|
||||
return {
|
||||
"ok": True,
|
||||
"sync_org": True,
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
"count": payload["count"],
|
||||
"fetched_at": payload["fetched_at"],
|
||||
"path": config.ORG_TREE_FILE,
|
||||
},
|
||||
"org_tree": payload["tree"],
|
||||
"fetched_at": payload["fetched_at"],
|
||||
"count": payload["count"],
|
||||
}
|
||||
|
||||
def _run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文 ----
|
||||
config.set_log(ctx.log)
|
||||
@@ -114,14 +207,21 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
dry_run = _as_bool(fields.get("dry_run"), config.DEFAULT_DRY_RUN)
|
||||
if dry_run: # 试算:只导出,不产生任何写入/外发动作
|
||||
auto_confirm, push_enabled = False, False
|
||||
push_units = _split_units(fields.get("push_units"))
|
||||
if fields.get("push_units") is None:
|
||||
push_units = config.DEFAULT_PUSH_EXTRA_UNITS
|
||||
push_exclude = (fields.get("push_exclude_keyword") or "").strip()
|
||||
if fields.get("push_exclude_keyword") is None:
|
||||
push_exclude = config.DEFAULT_PUSH_EXCLUDE_KEYWORD
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
scope_paths = _parse_scope_paths(fields.get("push_scope_paths"))
|
||||
if push_enabled:
|
||||
if scope_paths:
|
||||
ctx.log(f"推送范围:组织架构勾选 {len(scope_paths)} 个节点(含全部下级)", "INFO")
|
||||
else:
|
||||
ctx.log("推送范围:未勾选任何组织节点,本次不推送当事人"
|
||||
"(如需推送请用「选择组织范围」勾选)", "WARN")
|
||||
dws_path = detect_dws(str(fields.get("dws_path") or ""))
|
||||
if dws_path:
|
||||
ctx.log(f"dws 检测通过:{dws_path}(单聊 + 群推送,附 Excel)", "INFO")
|
||||
elif push_enabled:
|
||||
ctx.log("未检测到 dws:当事人回退企业内部应用工作通知;群汇总含 Excel 附件,不发送;"
|
||||
"需要群推送请把 dws.exe 加入 PATH 或填写「dws 路径」", "WARN")
|
||||
push_group = (fields.get("push_group") or "").strip() or config.DEFAULT_PUSH_GROUP
|
||||
push_at_all = _as_bool(fields.get("push_at_all"), False)
|
||||
|
||||
try:
|
||||
month = rules.resolve_month(fields.get("ref_month"))
|
||||
@@ -130,7 +230,7 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
begin, end = rules.month_range(month)
|
||||
ctx.log(f"===== 周考勤异常处理启动:{month} 整月({begin} ~ {end}),"
|
||||
f"试算模式={'是(只导出)' if dry_run else '否'},"
|
||||
f"自动确认={'开(全量)' if auto_confirm else '关'},"
|
||||
f"自动确认={'开(整月轻微)' if auto_confirm else '关'},"
|
||||
f"钉钉推送={'开' if push_enabled else '关'} =====", "INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
@@ -157,34 +257,54 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
path = attendance_report.export_excel(data, save_dir, month, dry_run=dry_run)
|
||||
ctx.progress(35)
|
||||
|
||||
# ---- 步骤4:自动确认(整月全量) ----
|
||||
split = rules.split_data(data, push_units, push_exclude)
|
||||
auto_count = len([it for it in data if it.get("abnormal_id")])
|
||||
# ---- 步骤4:自动确认(整月轻微异常) ----
|
||||
split = rules.split_data(data, scope_paths)
|
||||
auto_items = [it for it in data
|
||||
if it.get("abnormal_id") and rules.is_mild_abnormal(it)]
|
||||
auto_count = len(auto_items)
|
||||
confirmed_count, failed_ids = 0, []
|
||||
if auto_confirm:
|
||||
ctx.log(f"自动确认(整月全量){auto_count} 条 …", "INFO")
|
||||
ctx.log(f"自动确认(整月轻微异常){auto_count} 条 …", "INFO")
|
||||
_, confirmed_count, failed_ids = hr_api.auto_confirm_all(
|
||||
session, data,
|
||||
session, auto_items,
|
||||
on_progress=lambda done, total: ctx.progress(
|
||||
35 + int(35 * done / max(total, 1))))
|
||||
else:
|
||||
if dry_run:
|
||||
ctx.log(f"试算模式:仅统计待确认 {auto_count} 条,未执行确认", "INFO")
|
||||
ctx.log(f"试算模式:仅统计待确认轻微异常 {auto_count} 条,未执行确认", "INFO")
|
||||
else:
|
||||
ctx.log(f"自动确认未启用,仅统计待确认 {auto_count} 条,未执行确认", "WARN")
|
||||
ctx.log(f"自动确认未启用,仅统计待确认轻微异常 {auto_count} 条,未执行确认", "WARN")
|
||||
ctx.progress(72)
|
||||
|
||||
# ---- 步骤5:钉钉推送(只通知,不改口径) ----
|
||||
messages = rules.group_messages(split["func_list"])
|
||||
push_result = {"sent": 0, "failed": []}
|
||||
group_message = rules.build_group_summary(
|
||||
len(data), auto_count, confirmed_count, len(split["non_func_list"]),
|
||||
len(split["func_list"]), len(messages), len(split["other_list"]),
|
||||
month, begin, end)
|
||||
push_result = {"sent": 0, "failed": [], "group_sent": False, "note": ""}
|
||||
push_channel = "none"
|
||||
if push_enabled:
|
||||
if messages:
|
||||
push_result = dingtalk_push.push_person_messages(
|
||||
messages,
|
||||
if dws_path:
|
||||
# 首选 dws:当事人单聊 + 汇总群(附 Excel 底稿)
|
||||
push_channel = "dws"
|
||||
push_result = dingtalk_push.push_by_dws(
|
||||
messages, group_message, push_group, file_path=path,
|
||||
record_dir=os.path.join(save_dir, config.RECORD_SUBDIR),
|
||||
at_all=push_at_all, dws_path=dws_path,
|
||||
on_progress=lambda done, total: ctx.progress(
|
||||
72 + int(15 * done / max(total, 1))))
|
||||
else:
|
||||
ctx.log("无需推送的异常,跳过当事人钉钉通知", "INFO")
|
||||
# 回退:仅当事人工作通知;群汇总需 dws 附件,跳过
|
||||
push_channel = "worknotice"
|
||||
if messages:
|
||||
push_result = dingtalk_push.push_person_messages(
|
||||
messages,
|
||||
on_progress=lambda done, total: ctx.progress(
|
||||
72 + int(15 * done / max(total, 1))))
|
||||
else:
|
||||
ctx.log("无需推送的异常,跳过当事人钉钉通知", "INFO")
|
||||
ctx.log("未检测到 dws:群汇总(含 Excel 附件)未发送", "WARN")
|
||||
else:
|
||||
if dry_run:
|
||||
ctx.log("试算模式:未发送任何钉钉消息", "INFO")
|
||||
@@ -192,16 +312,7 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
ctx.log("钉钉推送未启用,未发送任何钉钉消息", "INFO")
|
||||
ctx.progress(90)
|
||||
|
||||
# ---- 步骤6:汇总日志 + 群条数汇总 ----
|
||||
group_message = rules.build_group_summary(
|
||||
len(data), auto_count, confirmed_count, len(split["non_func_list"]),
|
||||
len(split["func_list"]), len(messages), len(split["other_list"]),
|
||||
month, begin, end)
|
||||
group_sent = False
|
||||
if push_enabled:
|
||||
group_sent = dingtalk_push.send_group_text(
|
||||
group_message, webhook=webhook, secret=secret)
|
||||
|
||||
# ---- 步骤6:汇总日志 ----
|
||||
ctx.log("=" * 60, "INFO")
|
||||
ctx.log(group_message, "INFO")
|
||||
ctx.log(f"导出文件:{path}", "INFO")
|
||||
@@ -223,7 +334,8 @@ class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
"push_people": len(messages),
|
||||
"push_sent": push_result["sent"],
|
||||
"push_failed": len(push_result["failed"]),
|
||||
"group_pushed": group_sent,
|
||||
"push_channel": push_channel,
|
||||
"group_pushed": bool(push_result.get("group_sent")),
|
||||
}
|
||||
summary = f"{month} 周考勤异常处理完成:共 {counts['total']} 条"
|
||||
if dry_run:
|
||||
|
||||
@@ -21,6 +21,26 @@ ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAja
|
||||
ATTENDANCE_ADJUST_URL = f"{HR_BASE_URL}/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 组织树编码与集团根组织节点(考勤接口与台账接口共用)
|
||||
HR_TREE_CODE = "cq37du"
|
||||
GROUP_ROOT_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
|
||||
# ==================== 组织架构(推送范围选择) ====================
|
||||
# 组织维护台账实时查询接口(与 workflows/share/org_export.py 同款)
|
||||
ORG_QUERY_URL = (f"{HR_BASE_URL}/RedseaPlatform/hrRoster/"
|
||||
"110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc")
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
ORG_PAGE_SIZE = 500
|
||||
# 台账接口页面上下文身份(抓包常量,与 hr_sdk / workflows 组织导出保持同一套;可见范围仍受登录账号权限约束)
|
||||
ORG_CURRENT_ROLE_IDS = "POST_SYS_ADMIN,renshi"
|
||||
ORG_DEFAULT_USER_ID = "178b0efa-8a65-11f1-a7d9-000c296f9469"
|
||||
ORG_DEFAULT_STAFF_ID = "1342173e-36cf-4160-8826-6b17d7d084a4"
|
||||
|
||||
# 组织架构本地固化文件:%LOCALAPPDATA%\37duAutomation\plugin_data\xq0006\org_tree.json
|
||||
PLUGIN_DATA_DIR = os.path.join(_APP_DATA_DIR, 'plugin_data', 'xq0006')
|
||||
ORG_TREE_FILE = os.path.join(PLUGIN_DATA_DIR, 'org_tree.json')
|
||||
|
||||
# ==================== 输出与口径常量(与影刀版一致) ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\考勤异常"
|
||||
|
||||
@@ -76,13 +96,12 @@ DEFAULT_PUSH_ENABLED = True
|
||||
# 试算模式:只导出 Excel,不做自动确认、不发任何钉钉消息
|
||||
DEFAULT_DRY_RUN = False
|
||||
|
||||
# 推送范围扩充:除职能序列外,这些所属单位也推送(部门路径不含关键字,界面可覆盖)
|
||||
DEFAULT_PUSH_EXTRA_UNITS = ["总办", "集团财经中心", "金色湖畔事业部",
|
||||
"集团管理中心", "集团营建中心", "金色印象事业部"]
|
||||
DEFAULT_PUSH_EXCLUDE_KEYWORD = "大区"
|
||||
DEFAULT_PUSH_GROUP = "数字人沟通群"
|
||||
RECORD_SUBDIR = "推送记录"
|
||||
|
||||
# ==================== 钉钉推送(企业内部应用工作通知 + 群机器人) ====================
|
||||
# 个人通知:企业内部应用「工作通知」(按工号精确匹配接收人),与 XQ0012/XQ0052 同一应用。
|
||||
# ==================== 钉钉推送 ====================
|
||||
# 优先 dws(单聊 + 群,附 Excel);未装 dws 时当事人回退「工作通知」(按工号精确匹配接收人),
|
||||
# 群汇总因需要附件能力不再走群机器人。
|
||||
DINGTALK_APP_KEY = 'dingc1fnokzybr3u5bbl'
|
||||
DINGTALK_APP_SECRET = ('AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A')
|
||||
DINGTALK_AGENT_ID = '4974749954'
|
||||
@@ -92,12 +111,6 @@ DINGTALK_USER_SEARCH_URL = "https://api.dingtalk.com/v1.0/contact/users/search"
|
||||
DINGTALK_USER_GET_URL = "https://oapi.dingtalk.com/user/get"
|
||||
DINGTALK_WORK_SEND_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2"
|
||||
|
||||
# 群汇总:群机器人 Webhook(与 XQ0003/XQ0004 同一套默认机器人)
|
||||
DEFAULT_WEBHOOK = ('https://oapi.dingtalk.com/robot/send?access_token='
|
||||
'65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e')
|
||||
DEFAULT_SECRET = ""
|
||||
DINGTALK_GROUP_TITLE = "考勤异常处理汇总"
|
||||
|
||||
HTTP_TIMEOUT = 20
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 数据层:HR 组织架构(组织维护台账)拉取、树化与本地固化。
|
||||
|
||||
数据源:组织维护台账实时查询接口(与 workflows/share/org_export.py 同款、已在生产使用),
|
||||
返回全部「在用」组织,字段含组织名称 / 组织编号 / 组织类型 / 组织全路径(集团-A-B-C)。
|
||||
树按组织全路径的 "-" 层级切分构建,节点 id 即全路径,正好与考勤异常行的
|
||||
ORG_FULL_PATH 同口径,界面勾选的节点可直接按路径前缀匹配数据行。
|
||||
|
||||
固化位置:%LOCALAPPDATA%\\37duAutomation\\plugin_data\\xq0006\\org_tree.json;
|
||||
界面「同步组织架构」按钮触发 sync(),只写这一个文件,不随插件升级丢失。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from .. import config
|
||||
from .hr_api import HRSessionExpiredError
|
||||
|
||||
# ==================== 接口与固定入参 ====================
|
||||
ORG_QUERY_URL = config.ORG_QUERY_URL
|
||||
ORG_PAGE_SIZE = config.ORG_PAGE_SIZE
|
||||
MAX_ATTEMPTS = 3
|
||||
RETRY_WAIT = 1.5
|
||||
|
||||
# commonQuery 前端加密(等价浏览器行为,已实测接口可用)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd"
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
if len(chunk) == 1:
|
||||
enc3, enc4 = 64, 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
result += [_CUSTOM_CHARS[enc1], _CUSTOM_CHARS[enc2],
|
||||
_CUSTOM_CHARS[enc3], _CUSTOM_CHARS[enc4]]
|
||||
return "".join(result)
|
||||
|
||||
|
||||
def _encode_common_query(conditions):
|
||||
"""查询条件列表 → commonQuery 串(URI 编码 + 自定义 Base64 + 盐 + 首尾重排)。"""
|
||||
raw = json.dumps(conditions, ensure_ascii=False, separators=(",", ":"))
|
||||
uri = urllib.parse.quote(raw, safe="-_.~!*'()")
|
||||
en = _custom_base64_encode(uri.encode("utf-8")) + _SALT
|
||||
return en[:2] + en[-3:] + en[2:-3]
|
||||
|
||||
|
||||
_COMMON_QUERY = _encode_common_query([{
|
||||
"queryField": "`pt_organzation.IN_USE`", "leftBracket": "(", "queryType": "in",
|
||||
"queryValue": "1", "queryText": "1", "rightBracket": ")", "logic": "AND",
|
||||
"inputType": "select",
|
||||
}])
|
||||
|
||||
_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": _COMMON_QUERY,
|
||||
"newCondition": "",
|
||||
"urlConditions": ("_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23"
|
||||
"treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A"
|
||||
"%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23"),
|
||||
"exportConfig": "",
|
||||
"tableId": config.ORG_TABLE_ID,
|
||||
"rosterId": config.ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": config.HR_TREE_CODE,
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": config.GROUP_ROOT_STRU_ID,
|
||||
"belongUnitStruId": config.GROUP_ROOT_STRU_ID,
|
||||
"rootId": config.HR_TREE_CODE,
|
||||
"isVirtual": "0",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# 接口字段:组织名称 / 编号 / 类型 / 组织全路径(上级组织仅作兜底参考)
|
||||
F_NAME = "pt_organzation.ORG_NAME"
|
||||
F_CODE = "pt_organzation.ORG_CODE"
|
||||
F_TYPE = "pt_organzation.ORG_TYPE_CODE"
|
||||
F_PATH = "pt_structure.ORG_FULL_PATH"
|
||||
F_PARENT = "pt_structure1.ORG_ALIAS"
|
||||
|
||||
|
||||
def _date_params():
|
||||
"""组织维护查询固定带的日期参数(接口校验用,取当前时刻)。"""
|
||||
now = time.localtime()
|
||||
return {
|
||||
"currentDate": time.strftime("%Y-%m-%d", now),
|
||||
"currentMonth": time.strftime("%Y%m", now),
|
||||
"currentMonthBar": time.strftime("%Y-%m", now),
|
||||
"lastMonth": time.strftime("%Y%m", now),
|
||||
"lastMonFirstDay": time.strftime("%Y-%m", now) + "-01",
|
||||
"lastMonLastDay": time.strftime("%Y-%m-%d", now),
|
||||
"curYearFirstMon": time.strftime("%Y", now) + "01",
|
||||
"curYearFirstMonBar": time.strftime("%Y", now) + "-01",
|
||||
}
|
||||
|
||||
|
||||
def _fetch_page_once(session, page_no, page_size):
|
||||
params = dict(_BASE_PARAMS)
|
||||
params.update(_date_params())
|
||||
params.update({
|
||||
"currentUserRootId": config.HR_TREE_CODE,
|
||||
"currentUserId": config.ORG_DEFAULT_USER_ID,
|
||||
"currentRoleIds": config.ORG_CURRENT_ROLE_IDS,
|
||||
"currentStaffId": config.ORG_DEFAULT_STAFF_ID,
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
resp = session.request("POST", ORG_QUERY_URL, params=params,
|
||||
timeout=config.HTTP_TIMEOUT * 3)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError("组织架构:HR 登录态失效(返回非 JSON),请重新登录 HR 后重试")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _fetch_page(session, page_no):
|
||||
last_err = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _fetch_page_once(session, page_no, ORG_PAGE_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 网络/接口异常按项目规范重试 3 次
|
||||
last_err = e
|
||||
config.logger.warning("组织架构第 %d 页第 %d/%d 次失败:%s",
|
||||
page_no, attempt, MAX_ATTEMPTS, e)
|
||||
if attempt < MAX_ATTEMPTS:
|
||||
time.sleep(RETRY_WAIT * attempt)
|
||||
raise RuntimeError(f"组织架构第 {page_no} 页拉取失败:{last_err}")
|
||||
|
||||
|
||||
def fetch_all_orgs(session, on_progress=None):
|
||||
"""分页拉取全部在用组织记录(接口原始行)。"""
|
||||
rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
data = _fetch_page(session, page_no)
|
||||
if str(data.get("state")) != "1":
|
||||
raise RuntimeError(f"组织架构第 {page_no} 页接口返回失败:{data.get('meg')}")
|
||||
page_list = data.get("datas") or []
|
||||
if not page_list:
|
||||
break
|
||||
rows.extend(page_list)
|
||||
total_page = int(data.get("pageCount", 0) or 0)
|
||||
config.logger.info("组织架构已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(rows))
|
||||
if on_progress:
|
||||
on_progress(page_no, total_page)
|
||||
if total_page and page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return rows
|
||||
|
||||
|
||||
def build_tree(records):
|
||||
"""组织记录 → 树(节点 id/child 关系均由组织全路径的 '-' 层级推导)。
|
||||
|
||||
Returns:
|
||||
(树节点列表, 跳过条数)
|
||||
"""
|
||||
nodes = {}
|
||||
skipped = 0
|
||||
for r in records:
|
||||
path = str(r.get(F_PATH) or "").strip()
|
||||
if not path:
|
||||
skipped += 1
|
||||
continue
|
||||
name = str(r.get(F_NAME) or "").strip()
|
||||
segs = [s for s in path.split("-") if s]
|
||||
if not segs:
|
||||
skipped += 1
|
||||
continue
|
||||
acc = []
|
||||
for seg in segs:
|
||||
acc.append(seg)
|
||||
p = "-".join(acc)
|
||||
node = nodes.get(p)
|
||||
if node is None:
|
||||
node = {"path": p, "name": seg, "code": "", "type": "", "children": []}
|
||||
nodes[p] = node
|
||||
leaf = nodes[path]
|
||||
leaf["name"] = name or segs[-1]
|
||||
leaf["code"] = str(r.get(F_CODE) or "")
|
||||
leaf["type"] = str(r.get(F_TYPE) or "")
|
||||
|
||||
roots = []
|
||||
for p, node in nodes.items():
|
||||
parent_path = p.rsplit("-", 1)[0] if "-" in p else ""
|
||||
parent = nodes.get(parent_path)
|
||||
if parent is not None:
|
||||
parent["children"].append(node)
|
||||
else:
|
||||
roots.append(node)
|
||||
return roots, skipped
|
||||
|
||||
|
||||
def _count_nodes(tree):
|
||||
total = 0
|
||||
stack = list(tree)
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
total += 1
|
||||
stack.extend(node.get("children") or [])
|
||||
return total
|
||||
|
||||
|
||||
def save(tree, count):
|
||||
"""把树固化到 plugin_data/xq0006/org_tree.json(先写临时文件再替换)。"""
|
||||
payload = {
|
||||
"schema": 1,
|
||||
"fetched_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"count": count,
|
||||
"tree": tree,
|
||||
}
|
||||
os.makedirs(os.path.dirname(config.ORG_TREE_FILE), exist_ok=True)
|
||||
tmp = config.ORG_TREE_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, separators=(",", ":"))
|
||||
os.replace(tmp, config.ORG_TREE_FILE)
|
||||
return payload
|
||||
|
||||
|
||||
def load():
|
||||
"""读取本地固化的组织架构;不存在/损坏返回 None。"""
|
||||
try:
|
||||
with open(config.ORG_TREE_FILE, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, ValueError) as e:
|
||||
config.logger.warning("组织架构本地文件读取失败:%s", e)
|
||||
return None
|
||||
if not isinstance(data, dict) or not isinstance(data.get("tree"), list):
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def sync(session, on_progress=None):
|
||||
"""拉取最新组织架构 → 建树 → 固化 → 返回 payload(含 tree)。"""
|
||||
records = fetch_all_orgs(session, on_progress=on_progress)
|
||||
if not records:
|
||||
raise RuntimeError("组织架构接口未返回任何组织数据(请确认账号有组织维护查询权限)")
|
||||
tree, skipped = build_tree(records)
|
||||
if skipped:
|
||||
config.logger.warning("组织架构有 %d 条记录缺少组织全路径,已跳过", skipped)
|
||||
count = _count_nodes(tree)
|
||||
payload = save(tree, count)
|
||||
config.logger.info("组织架构同步完成:%d 个节点,已固化到 %s", count, config.ORG_TREE_FILE)
|
||||
return payload
|
||||
@@ -1,5 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 逻辑层:日期范围、分级分类、通知文本与汇总口径(规则与影刀版一致)。"""
|
||||
import calendar
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from .. import config
|
||||
@@ -30,8 +31,10 @@ def resolve_month(value):
|
||||
|
||||
|
||||
def month_range(month):
|
||||
"""整月查询范围(与影刀版一致:-01 ~ -31)。"""
|
||||
return f"{month}-01", f"{month}-31"
|
||||
"""整月查询范围:当月 1 号 ~ 当月最后一天(按真实天数,避免出现 -31)。"""
|
||||
year, mon = (int(x) for x in str(month).split("-")[:2])
|
||||
last = calendar.monthrange(year, mon)[1]
|
||||
return f"{month}-01", f"{month}-{last:02d}"
|
||||
|
||||
|
||||
def last_week_range(today=None):
|
||||
@@ -61,29 +64,25 @@ def classify_abnormal(item):
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item):
|
||||
"""是否职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
def is_mild_abnormal(item):
|
||||
"""轻微异常:迟到/早退 且 异常时长 < 30 分钟(自动确认范围,不分职能序列)。"""
|
||||
return not classify_abnormal(item)
|
||||
|
||||
|
||||
def is_push_scope(item, extra_units=None, exclude_keyword=None):
|
||||
"""是否属于当事人推送范围:
|
||||
职能序列,或所属单位在「推送范围单位」内且部门路径不含排除关键字。
|
||||
"""
|
||||
if is_func_staff(item):
|
||||
return True
|
||||
units = config.DEFAULT_PUSH_EXTRA_UNITS if extra_units is None else extra_units
|
||||
keyword = config.DEFAULT_PUSH_EXCLUDE_KEYWORD if exclude_keyword is None \
|
||||
else exclude_keyword
|
||||
if not units:
|
||||
def in_org_scope(item, scope_paths):
|
||||
"""数据行是否落在所选组织节点内(节点本身或其下级,按组织全路径前缀匹配)。"""
|
||||
path = str(item.get("ORG_FULL_PATH", "") or "").strip()
|
||||
if not path:
|
||||
return False
|
||||
unit = str(item.get("BELONG_UNIT_ORG_NAME", "") or "").strip()
|
||||
return unit in units and (not keyword
|
||||
or keyword not in str(item.get("ORG_FULL_PATH", "") or ""))
|
||||
for p in scope_paths or ():
|
||||
p = str(p or "").strip()
|
||||
if p and (path == p or path.startswith(p + "-")):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def split_data(data, push_units=None, push_exclude_keyword=None):
|
||||
"""按推送口径切分;自动确认范围不在此切分(由 run 全量确认)。"""
|
||||
def split_data(data, scope_paths=None):
|
||||
"""按推送口径切分:只看组织架构勾选范围(含下级);未勾选=不推送当事人。"""
|
||||
push_begin, push_end = last_week_range()
|
||||
push_list = [it for it in data
|
||||
if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
|
||||
@@ -92,10 +91,8 @@ def split_data(data, push_units=None, push_exclude_keyword=None):
|
||||
return {
|
||||
"push_list": push_list,
|
||||
"other_list": other_list,
|
||||
"func_list": [it for it in push_list
|
||||
if is_push_scope(it, push_units, push_exclude_keyword)],
|
||||
"non_func_list": [it for it in push_list
|
||||
if not is_push_scope(it, push_units, push_exclude_keyword)],
|
||||
"func_list": [it for it in push_list if in_org_scope(it, scope_paths)],
|
||||
"non_func_list": [it for it in push_list if not in_org_scope(it, scope_paths)],
|
||||
"push_begin": push_begin,
|
||||
"push_end": push_end,
|
||||
}
|
||||
@@ -134,13 +131,13 @@ def build_notify_text(items):
|
||||
|
||||
def build_group_summary(total_count, auto_count, confirmed_count, non_func_count, func_count,
|
||||
push_count, other_count, month, begin, end):
|
||||
"""群汇总文本(推送段落口径不变;自动确认段落为整月全量)。"""
|
||||
"""群汇总文本(推送段落口径不变;自动确认段落为整月轻微异常)。"""
|
||||
return (
|
||||
"【考勤异常处理汇总】\n\n"
|
||||
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n\n"
|
||||
f"考勤异常总数:{total_count} 条\n\n"
|
||||
f"自动确认(整月全量):{auto_count} 条,确认成功 {confirmed_count} 条\n\n"
|
||||
f"待通知(职能及指定单位,上周):{func_count} 条,合并为 {push_count} 条推送\n\n"
|
||||
f"上周非职能(不推送):{non_func_count} 条\n\n"
|
||||
f"自动确认(整月轻微异常):{auto_count} 条,确认成功 {confirmed_count} 条\n\n"
|
||||
f"待通知(组织架构所选范围,上周):{func_count} 条,合并为 {push_count} 条推送\n\n"
|
||||
f"上周范围外(不推送):{non_func_count} 条\n\n"
|
||||
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
|
||||
)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0006",
|
||||
"name": "EHR系统周考勤异常处理",
|
||||
"version": "1.2.0",
|
||||
"description": "拉取查询月份未调整考勤异常并导出 Excel,整月全量自动确认;上周职能序列及推送范围单位(默认总办/集团财经中心/金色湖畔事业部/集团管理中心/集团营建中心/金色印象事业部,不含大区)的严重异常按人合并推送;支持试算模式(只出表、不确认不推送)。",
|
||||
"version": "1.4.1",
|
||||
"description": "拉取查询月份未调整考勤异常并导出 Excel,整月轻微异常自动确认;上周「组织架构所选范围(含下级)」的严重异常按人合并推送,组织架构支持一键同步最新并固化为 JSON;优先用 dws 单聊+群(附 Excel),未装 dws 时当事人回退工作通知、群汇总不发送;支持试算模式(只出表、不确认不推送)。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
@@ -49,37 +49,37 @@
|
||||
"type": "boolean",
|
||||
"title": "自动确认",
|
||||
"default": true,
|
||||
"description": "开启后对查询范围内全部异常调用确认接口(分批提交);试算模式下强制不确认"
|
||||
"description": "开启后对整月轻微异常(迟到/早退 < 30 分钟,不分职能序列)调用确认接口(分批提交);严重异常只推送不确认;试算模式下强制不确认"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉推送",
|
||||
"default": true,
|
||||
"description": "开启后推送上周职能序列及推送范围单位的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送"
|
||||
"description": "开启后推送上周组织架构所选范围的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送"
|
||||
},
|
||||
"push_units": {
|
||||
"push_scope_paths": {
|
||||
"type": "string",
|
||||
"title": "推送范围单位",
|
||||
"default": "总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部",
|
||||
"description": "除职能序列外,这些所属单位也推送(逗号/顿号分隔);留空=只推职能序列"
|
||||
},
|
||||
"push_exclude_keyword": {
|
||||
"type": "string",
|
||||
"title": "推送排除关键字",
|
||||
"default": "大区",
|
||||
"description": "部门路径包含该关键字则不推送;留空表示不按部门路径排除"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"title": "推送范围(组织架构)",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
"description": "界面组织树勾选的节点(组织全路径 JSON 数组,含全部下级);未勾选=不推送当事人"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"dws_path": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"title": "dws 路径",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
"description": "留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH);dws 负责当事人单聊与群汇总(附 Excel),检测不到时当事人回退工作通知、群汇总不发送"
|
||||
},
|
||||
"push_group": {
|
||||
"type": "string",
|
||||
"title": "汇总群名",
|
||||
"default": "",
|
||||
"description": "dws 推送时的群全称(按群名精确匹配),留空用默认;汇总附带 Excel 底稿"
|
||||
},
|
||||
"push_at_all": {
|
||||
"type": "boolean",
|
||||
"title": "汇总群 @所有人",
|
||||
"default": false,
|
||||
"description": "仅 dws 通道生效,且需群里有 @所有人 权限"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
||||
@@ -2,15 +2,16 @@
|
||||
"""XQ0006 报告层:钉钉推送。
|
||||
|
||||
推送口径与影刀版一致(消息文本不改):
|
||||
- 当事人:一人一条文本,按「姓名+工号」精确定位钉钉账号,走企业内部应用工作通知;
|
||||
- 群汇总:条数汇总文本推送到群机器人,走 dingtalk_sdk 统一格式
|
||||
(彩色标题 + 正文 + 页脚署名/时间,Markdown)。
|
||||
- 当事人:一人一条文本,按「姓名+工号」精确定位钉钉账号;
|
||||
- 群汇总:条数汇总文本推送到群。
|
||||
优先走 dws(单聊 + 群,汇总附带 Excel 底稿);未装 dws 时当事人回退
|
||||
企业内部应用工作通知,群汇总不发送(群机器人无法带附件)。
|
||||
所有发送失败只记日志与计数,不中断主流程。
|
||||
"""
|
||||
import time
|
||||
|
||||
import requests
|
||||
from dingtalk_sdk.robot import Robot
|
||||
from dingtalk_sdk import Dws
|
||||
|
||||
from .. import config
|
||||
|
||||
@@ -157,24 +158,43 @@ def push_person_messages(messages, on_progress=None):
|
||||
return {"sent": sent, "failed": failed, "no_uid": len(failed)}
|
||||
|
||||
|
||||
def send_group_text(text, webhook="", secret="", title=""):
|
||||
"""群机器人推送统一格式 Markdown(彩色标题 + 正文 + 页脚,走 dingtalk_sdk)。
|
||||
# ==================== dws 推送(首选通道) ====================
|
||||
def push_by_dws(messages, group_text, group_name, file_path="", record_dir="",
|
||||
at_all=False, dws_path="", on_progress=None):
|
||||
"""用 dws 命令行推送:当事人单聊 + 汇总群(可带 Excel 底稿)。
|
||||
|
||||
正文口径与影刀版一致;消息体由 dingtalk_sdk 渲染,仅去掉与标题重复的首行标签。
|
||||
返回 True/False。
|
||||
messages: [(姓名, 工号, 正文)];返回 {sent, failed, group_sent, note}。
|
||||
"""
|
||||
webhook = webhook or config.DEFAULT_WEBHOOK
|
||||
secret = secret or config.DEFAULT_SECRET
|
||||
if not webhook:
|
||||
config.logger.warning("未配置群机器人 Webhook,跳过群汇总推送")
|
||||
return False
|
||||
title = title or config.DINGTALK_GROUP_TITLE
|
||||
body = str(text or "").replace(f"【{title}】", "", 1).strip()
|
||||
payload = [("text", name, code, text, "") for name, code, text in messages]
|
||||
if group_text:
|
||||
payload.append({
|
||||
"group": group_name,
|
||||
"content": group_text,
|
||||
"file_path": file_path,
|
||||
"at_all": bool(at_all),
|
||||
})
|
||||
try:
|
||||
Robot(webhook=webhook, secret=secret, log=config.logger.info).send(
|
||||
title, body, status="info")
|
||||
config.logger.info("群汇总推送成功(Markdown + 页脚)")
|
||||
return True
|
||||
client = Dws(bin=dws_path, record_dir=record_dir, log=config.logger.info)
|
||||
result = client.push(payload)
|
||||
except Exception as e: # noqa: BLE001
|
||||
config.logger.error("群汇总推送失败:%s", e)
|
||||
return False
|
||||
config.logger.error("dws 推送失败:%s", e)
|
||||
return {"sent": 0, "failed": [f"dws 推送失败:{e}"], "group_sent": False,
|
||||
"note": f"dws 推送失败:{e}"}
|
||||
|
||||
results = result.get("results") or []
|
||||
sent, failed = 0, []
|
||||
for idx, (name, code, _text) in enumerate(messages):
|
||||
item = results[idx] if idx < len(results) else {}
|
||||
if item.get("success"):
|
||||
sent += 1
|
||||
else:
|
||||
failed.append(f"{name}({code}):{item.get('message') or '失败'}")
|
||||
if on_progress:
|
||||
on_progress(idx + 1, len(messages))
|
||||
group_sent = False
|
||||
if group_text and len(results) > len(messages):
|
||||
group_sent = bool(results[len(messages)].get("success"))
|
||||
note = str(result.get("message") or "")
|
||||
config.logger.info("dws 推送完成:单聊成功 %d/%d,群汇总 %s;%s",
|
||||
sent, len(messages), "成功" if group_sent else "失败", note)
|
||||
return {"sent": sent, "failed": failed, "group_sent": group_sent, "note": note}
|
||||
|
||||
@@ -75,8 +75,8 @@
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="对查询范围内全部异常(不再只限迟到/早退<30 分钟)批量调用确认接口,接口按批次提交">
|
||||
<span class="lbl">自动确认(全量)</span>
|
||||
content="对整月轻微异常(迟到/早退<30 分钟,不分职能序列)批量调用确认接口;严重异常只推送不确认">
|
||||
<span class="lbl">自动确认(轻微)</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-switch v-model="form.auto_confirm" :disabled="running || form.dry_run" />
|
||||
@@ -84,7 +84,7 @@
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="推送上周职能序列及下方推送范围单位的严重异常给当事人,并把条数汇总推送到钉钉群;消息内容与影刀版一致">
|
||||
content="推送上周组织架构所选范围的严重异常给当事人,并把条数汇总推送到钉钉群;消息内容与影刀版一致">
|
||||
<span class="lbl">钉钉推送</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
@@ -92,10 +92,11 @@
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
自动确认会<b>真正提交</b>到 EHR(范围=本次查询到的全部异常),关闭则只导出与统计。
|
||||
自动确认会<b>真正提交</b>到 EHR(范围=整月轻微异常:迟到/早退 < 30 分钟,不分职能序列),
|
||||
关闭则只导出与统计。
|
||||
<b>试算模式</b>只出表:不确认、不推送,用于核对数据。
|
||||
钉钉推送口径:仅上周严重异常,覆盖职能序列 + 推送范围单位
|
||||
(部门路径不含排除关键字),按人合并推送,当事人需 2 日内对接人事处理。
|
||||
钉钉推送口径:仅上周严重异常,覆盖组织架构所选范围(含下级),
|
||||
按人合并推送,当事人需 2 日内对接人事处理。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
@@ -111,36 +112,60 @@
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<span class="lbl">推送范围(组织架构)</span>
|
||||
<span v-if="orgMeta.count" class="org-meta">
|
||||
组织架构 {{ orgMeta.count }} 个节点<template v-if="orgMeta.fetched_at"> · 同步于 {{ orgMeta.fetched_at }}</template>
|
||||
</span>
|
||||
</template>
|
||||
<div class="scope-row">
|
||||
<span class="scope-summary" :class="{ empty: !selectedPaths.length }">
|
||||
{{ selectedPaths.length
|
||||
? `已选 ${selectedPaths.length} 个组织节点(含全部下级)`
|
||||
: '未选择组织(不推送当事人)' }}
|
||||
</span>
|
||||
<el-button size="small" type="primary" plain :disabled="running"
|
||||
@click="openScopeDialog">选择组织范围</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<div class="grid">
|
||||
<el-form-item label="推送范围单位">
|
||||
<el-input v-model="form.push_units" :disabled="running" clearable
|
||||
placeholder="总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部(留空 = 只推职能序列)" />
|
||||
<el-form-item label="dws 路径(留空自动检测)">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.dws_path" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空 = 自动检测 DINGTALK_DWS_BIN / 用户目录 / PATH" />
|
||||
<el-button class="dir-btn" :disabled="running || pickingDws"
|
||||
:loading="pickingDws" @click="pickDws">选择</el-button>
|
||||
<el-button class="dir-btn" :disabled="running || probing"
|
||||
:loading="probing" @click="probeDws">检测</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="部门路径包含该关键字则不推送;留空表示不按部门路径排除">
|
||||
<span class="lbl">排除部门路径关键字</span>
|
||||
content="dws 推送时的群全称,按群名精确匹配;汇总消息附带本次 Excel 底稿">
|
||||
<span class="lbl">汇总群名</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-input v-model="form.push_exclude_keyword" :disabled="running" clearable
|
||||
placeholder="留空 = 不排除" />
|
||||
<el-input v-model="form.push_group" :disabled="running" clearable
|
||||
placeholder="留空 = 数字人沟通群" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="钉钉 Webhook(可选)">
|
||||
<el-input v-model="form.dingtalk_webhook" placeholder="留空 = 内置机器人"
|
||||
:disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="加签密钥(可选)">
|
||||
<el-input v-model="form.dingtalk_secret" type="password" show-password
|
||||
placeholder="机器人启用了加签才填" :disabled="running" />
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="仅 dws 通道生效;需群里有 @所有人 权限">
|
||||
<span class="lbl">汇总群 @所有人</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-switch v-model="form.push_at_all" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
当事人提醒走企业内部应用「工作通知」(按<b>工号</b>精确匹配账号);
|
||||
群汇总走群机器人。推送范围=职能序列 ∪ 上方单位(部门路径不含排除关键字),
|
||||
单位与关键字均可改,留空分别=只推职能序列 / 不按部门路径排除。
|
||||
推送范围=<b>组织架构勾选的节点</b>(勾父节点即含其全部下级,按组织全路径匹配当事人所在部门);
|
||||
<b>未勾选则本次不推送当事人</b>。组织架构不随插件升级,需在弹窗里点「同步组织架构」拉取最新。
|
||||
检测到 dws 时:当事人走 <b>dws 单聊</b>,汇总连同 <b>Excel 底稿</b>发到「汇总群名」;
|
||||
未检测到 dws 时:当事人回退企业内部应用「工作通知」(按<b>工号</b>精确匹配账号),
|
||||
群汇总需要附件能力、<b>不发送</b>。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
@@ -154,15 +179,15 @@
|
||||
(1 号运行查上月,否则查当月;手动指定月份则查该月),自动分页拉全。</div>
|
||||
<div class="hb-line"><b>② 导出</b>:按固定列口径导出 Excel 底稿到输出目录,
|
||||
文件名「周考勤异常_YYYY-MM_时间戳.xlsx」;试算模式只做这一步,文件名带「_试算」前缀。</div>
|
||||
<div class="hb-line"><b>③ 自动确认(全量)</b>:对查询范围内<b>全部异常</b>批量调用确认接口
|
||||
(每 200 条一批,失败自动重试 3 次、单批失败不影响其余批次);试算模式不执行。</div>
|
||||
<div class="hb-line"><b>③ 自动确认(轻微)</b>:对整月<b>轻微异常</b>(迟到/早退 < 30 分钟,不分职能序列)
|
||||
批量调用确认接口(每 200 条一批,失败自动重试 3 次、单批失败不影响其余批次);严重异常只推送不确认;试算模式不执行。</div>
|
||||
<div class="hb-line"><b>④ 当事人推送</b>:仅取<b>上周</b>、<b>严重异常</b>(迟到/早退 ≥ 30 分钟或其他类型),
|
||||
推送范围=<b>职能序列</b> ∪ <b>推送范围单位</b>(默认总办 / 集团财经中心 / 金色湖畔事业部 /
|
||||
集团管理中心 / 集团营建中心 / 金色印象事业部,部门路径不含排除关键字,界面可改),
|
||||
按「姓名+工号」合并为一人一条文本,经内部应用工作通知发送。</div>
|
||||
<div class="hb-line"><b>⑤ 群汇总</b>:推送条数汇总(总数、自动确认、待通知、上周非职能、
|
||||
其他严重异常)到钉钉群,走 dingtalk_sdk 统一格式(彩色标题 + 正文 + 页脚署名/时间);
|
||||
「自动确认」段落为<b>整月全量</b>口径,「待通知」含职能与推送范围单位。
|
||||
推送范围=<b>组织架构勾选的节点</b>(含全部下级,按组织全路径匹配),未勾选则不推送;
|
||||
按「姓名+工号」合并为一人一条文本;检测到 dws 时走 <b>dws 单聊</b>,否则回退内部应用工作通知。</div>
|
||||
<div class="hb-line"><b>⑤ 群汇总</b>:推送条数汇总(总数、自动确认、待通知、上周范围外、
|
||||
其他严重异常)到钉钉群;检测到 dws 时发到「汇总群名」并附带 <b>Excel 底稿</b>,
|
||||
未检测到 dws 时不发送(群机器人无法带附件)。
|
||||
「自动确认」段落为<b>整月轻微异常</b>口径,「待通知」含组织架构所选范围。
|
||||
试算模式不发送任何钉钉消息。</div>
|
||||
</div>
|
||||
</details>
|
||||
@@ -186,13 +211,50 @@
|
||||
<span>正在执行,日志与进度实时显示在工作台下方「运行日志」区</span>
|
||||
<span class="pct">{{ progress }}%</span>
|
||||
</div>
|
||||
|
||||
<!-- 组织架构选择弹窗 -->
|
||||
<el-dialog v-model="scopeDialog" title="选择推送范围(组织架构)" width="720px"
|
||||
append-to-body class="scope-dialog" @opened="applyDraftToTree">
|
||||
<div class="org-box">
|
||||
<div class="org-tools">
|
||||
<el-button size="small" type="primary" plain :loading="syncing" :disabled="running"
|
||||
@click="syncOrg">同步组织架构</el-button>
|
||||
<el-button size="small" :disabled="running || syncing || !draftPaths.length"
|
||||
@click="clearDraft">清空选择</el-button>
|
||||
<span class="org-count">已选 {{ draftPaths.length }} 个节点</span>
|
||||
<span class="spacer" />
|
||||
<span v-if="orgMeta.count" class="org-meta">
|
||||
共 {{ orgMeta.count }} 个节点<template v-if="orgMeta.fetched_at"> · 同步于 {{ orgMeta.fetched_at }}</template>
|
||||
</span>
|
||||
</div>
|
||||
<el-input v-model="orgKeyword" size="small" clearable class="org-search"
|
||||
:disabled="running || !orgTree.length" placeholder="搜索组织名称" />
|
||||
<div v-if="!orgTree.length" class="org-empty">
|
||||
尚未加载组织架构:点「同步组织架构」从 HR 拉取最新组织并固化为 JSON(本机缓存,升级不丢)
|
||||
</div>
|
||||
<div v-else class="org-tree">
|
||||
<el-tree ref="treeRef" :data="orgTree" show-checkbox node-key="path"
|
||||
:props="treeProps" :filter-node-method="filterNode"
|
||||
:expand-on-click-node="false" @check="onTreeCheck" />
|
||||
</div>
|
||||
<div class="org-note">
|
||||
勾选父节点=其全部下级一并纳入;按当事人所在组织的全路径(集团-事业部-…)匹配。
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<span class="scope-foot-count">已选 {{ draftPaths.length }} 个节点</span>
|
||||
<el-button @click="scopeDialog = false">取消</el-button>
|
||||
<el-button type="primary" :disabled="running || syncing" @click="confirmScope">确定</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { nextTick, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
ref_month: '',
|
||||
@@ -200,39 +262,206 @@ const DEFAULTS = () => ({
|
||||
dry_run: false,
|
||||
auto_confirm: true,
|
||||
push_enabled: true,
|
||||
push_units: '总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部',
|
||||
push_exclude_keyword: '大区',
|
||||
dingtalk_webhook: '',
|
||||
dingtalk_secret: '',
|
||||
push_scope_paths: '',
|
||||
dws_path: '',
|
||||
push_group: '数字人沟通群',
|
||||
push_at_all: false,
|
||||
})
|
||||
|
||||
function buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
return {
|
||||
ref_month: t(f.ref_month),
|
||||
save_dir: t(f.save_dir),
|
||||
dry_run: !!f.dry_run,
|
||||
auto_confirm: !!f.auto_confirm,
|
||||
push_enabled: !!f.push_enabled,
|
||||
push_scope_paths: t(f.push_scope_paths),
|
||||
dws_path: t(f.dws_path),
|
||||
push_group: t(f.push_group),
|
||||
push_at_all: !!f.push_at_all,
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
form, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
return {
|
||||
ref_month: t(f.ref_month),
|
||||
save_dir: t(f.save_dir),
|
||||
dry_run: !!f.dry_run,
|
||||
auto_confirm: !!f.auto_confirm,
|
||||
push_enabled: !!f.push_enabled,
|
||||
push_units: t(f.push_units),
|
||||
push_exclude_keyword: t(f.push_exclude_keyword),
|
||||
dingtalk_webhook: t(f.dingtalk_webhook),
|
||||
dingtalk_secret: t(f.dingtalk_secret),
|
||||
}
|
||||
},
|
||||
})
|
||||
} = usePluginUI({ defaults: DEFAULTS, buildPayload })
|
||||
|
||||
function start() {
|
||||
run()
|
||||
}
|
||||
|
||||
// ---------------- 推送范围:组织架构树 ----------------
|
||||
const ORG_CACHE_KEY = `plugin:${PLUGIN_ID}:orgTree`
|
||||
const orgTree = ref([])
|
||||
const orgMeta = ref({ count: 0, fetched_at: '' })
|
||||
const selectedPaths = ref([])
|
||||
const orgKeyword = ref('')
|
||||
const treeRef = ref(null)
|
||||
const treeProps = { label: 'name', children: 'children' }
|
||||
const syncing = ref(false)
|
||||
// 弹窗内草稿:确定才写回 selectedPaths / 配置,取消不影响已保存范围
|
||||
const scopeDialog = ref(false)
|
||||
const draftPaths = ref([])
|
||||
let applyingTree = false
|
||||
|
||||
function parseScope(value) {
|
||||
if (Array.isArray(value)) return value.filter(Boolean)
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw) return []
|
||||
try {
|
||||
const data = JSON.parse(raw)
|
||||
if (Array.isArray(data)) return data.filter(Boolean)
|
||||
} catch (_) { /* 兼容换行文本 */ }
|
||||
return raw.split('\n').map((s) => s.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
// 勾选父节点时 setCheckedKeys 会连带勾选全部下级,保存前去掉「已有祖先被选中」的冗余路径
|
||||
function pruneScope(keys) {
|
||||
const paths = [...new Set(keys)].sort((a, b) => a.length - b.length)
|
||||
const kept = []
|
||||
paths.forEach((p) => {
|
||||
if (!kept.some((q) => p === q || p.startsWith(q + '-'))) kept.push(p)
|
||||
})
|
||||
return kept
|
||||
}
|
||||
|
||||
function openScopeDialog() {
|
||||
draftPaths.value = [...selectedPaths.value]
|
||||
scopeDialog.value = true
|
||||
}
|
||||
|
||||
function applyDraftToTree() {
|
||||
if (!treeRef.value) return
|
||||
applyingTree = true
|
||||
treeRef.value.setCheckedKeys(draftPaths.value)
|
||||
nextTick(() => { applyingTree = false })
|
||||
}
|
||||
|
||||
function onTreeCheck() {
|
||||
if (applyingTree || !treeRef.value) return
|
||||
draftPaths.value = pruneScope(treeRef.value.getCheckedKeys())
|
||||
}
|
||||
|
||||
function clearDraft() {
|
||||
draftPaths.value = []
|
||||
if (treeRef.value) treeRef.value.setCheckedKeys([])
|
||||
}
|
||||
|
||||
function confirmScope() {
|
||||
selectedPaths.value = pruneScope(draftPaths.value)
|
||||
// 空值也存 "[]":配置合并规则会跳过空字符串,存空串会导致切方案时清不掉旧范围
|
||||
form.push_scope_paths = JSON.stringify(selectedPaths.value)
|
||||
scopeDialog.value = false
|
||||
}
|
||||
|
||||
function filterNode(value, data) {
|
||||
if (!value) return true
|
||||
return String(data.name || '').includes(String(value).trim())
|
||||
}
|
||||
|
||||
watch(orgKeyword, (v) => { if (treeRef.value) treeRef.value.filter(v) })
|
||||
|
||||
watch(() => form.push_scope_paths, (v) => {
|
||||
const paths = parseScope(v)
|
||||
if (JSON.stringify(paths) === JSON.stringify(selectedPaths.value)) return
|
||||
selectedPaths.value = paths
|
||||
})
|
||||
|
||||
function readOrgCache() {
|
||||
try {
|
||||
const raw = localStorage.getItem(ORG_CACHE_KEY)
|
||||
if (!raw) return null
|
||||
const data = JSON.parse(raw)
|
||||
return data && Array.isArray(data.tree) ? data : null
|
||||
} catch (_) { return null }
|
||||
}
|
||||
|
||||
function writeOrgCache(tree) {
|
||||
try {
|
||||
localStorage.setItem(ORG_CACHE_KEY, JSON.stringify({
|
||||
count: orgMeta.value.count, fetched_at: orgMeta.value.fetched_at, tree,
|
||||
}))
|
||||
} catch (_) { /* 缓存写入失败不影响当次使用 */ }
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const cache = readOrgCache()
|
||||
selectedPaths.value = parseScope(form.push_scope_paths)
|
||||
if (cache && cache.tree.length) {
|
||||
orgTree.value = cache.tree
|
||||
orgMeta.value = { count: cache.count || 0, fetched_at: cache.fetched_at || '' }
|
||||
} else if (selectedPaths.value.length) {
|
||||
// 浏览器缓存丢了但已配过范围:读本机固化的 org_tree.json 回填,打开弹窗时即可看到勾选
|
||||
loadOrgFromDisk()
|
||||
}
|
||||
})
|
||||
|
||||
// 起一次运行并轮询到结束(组织架构同步/读取共用)
|
||||
async function startRunAndWait(fields, maxTries) {
|
||||
const r = await fetch('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (!d.run_id) throw new Error('未返回 run_id')
|
||||
const run = await waitRunDone(d.run_id, maxTries)
|
||||
if (run.status === 'error') throw new Error(run.error || '运行失败')
|
||||
if (run.status === 'cancelled') throw new Error(run.error || '运行已取消')
|
||||
return run.result || {}
|
||||
}
|
||||
|
||||
async function loadOrgFromDisk() {
|
||||
try {
|
||||
const res = await startRunAndWait({ action: 'load_org' }, 20)
|
||||
const tree = Array.isArray(res.org_tree) ? res.org_tree : []
|
||||
if (!tree.length) return
|
||||
orgTree.value = tree
|
||||
orgMeta.value = { count: Number(res.count || 0), fetched_at: String(res.fetched_at || '') }
|
||||
writeOrgCache(tree)
|
||||
if (scopeDialog.value) nextTick(applyDraftToTree)
|
||||
} catch (_) { /* 读不到就保持空态,用户可手动同步 */ }
|
||||
}
|
||||
|
||||
async function syncOrg() {
|
||||
if (syncing.value) return
|
||||
syncing.value = true
|
||||
try {
|
||||
const res = await startRunAndWait(
|
||||
{ ...buildPayload(form), action: 'sync_org' }, 600)
|
||||
const tree = Array.isArray(res.org_tree) ? res.org_tree : []
|
||||
if (!tree.length) throw new Error('未返回组织架构数据')
|
||||
const count = Number(res.count || (res.detail || {}).count || 0)
|
||||
const fetchedAt = String(res.fetched_at || (res.detail || {}).fetched_at || '')
|
||||
orgTree.value = tree
|
||||
orgMeta.value = { count, fetched_at: fetchedAt }
|
||||
// 组织可能改名/撤销:保留仍然存在的已选路径
|
||||
const exists = new Set()
|
||||
const stack = [...tree]
|
||||
while (stack.length) {
|
||||
const node = stack.pop()
|
||||
exists.add(node.path)
|
||||
;(node.children || []).forEach((c) => stack.push(c))
|
||||
}
|
||||
const kept = draftPaths.value.filter((p) => exists.has(p))
|
||||
const dropped = draftPaths.value.length - kept.length
|
||||
draftPaths.value = kept
|
||||
nextTick(applyDraftToTree)
|
||||
writeOrgCache(tree)
|
||||
ElMessage.success(`组织架构已同步:${count || exists.size} 个节点`
|
||||
+ (dropped ? `,${dropped} 个已选节点已不存在` : ''))
|
||||
} catch (e) {
|
||||
ElMessage.error('同步组织架构失败:' + (e.message || e))
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框(壳子 /api/dialog/directory,仅返回路径)
|
||||
const picking = ref(false)
|
||||
async function pickDir() {
|
||||
@@ -252,6 +481,79 @@ async function pickDir() {
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 选择 dws:先弹文件选择,取消则改选目录(dws.exe 可能放在任意目录)
|
||||
const pickingDws = ref(false)
|
||||
async function pickDws() {
|
||||
pickingDws.value = true
|
||||
try {
|
||||
const r = await fetch('/api/dialog/file', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择 dws.exe', filter: 'exe' }),
|
||||
})
|
||||
if (r.status === 404) {
|
||||
const d = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择 dws.exe 所在目录', current: form.dws_path || '' }),
|
||||
}).then((x) => x.json().catch(() => ({}))).catch(() => ({}))
|
||||
if (d.path) form.dws_path = d.path
|
||||
return
|
||||
}
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.dws_path = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('选择文件失败:' + e.message)
|
||||
} finally {
|
||||
pickingDws.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// dws 检测:跑一次只检测的运行(probe_dws),命中路径回填
|
||||
const probing = ref(false)
|
||||
async function waitRunDone(runId, maxTries = 40) {
|
||||
for (let i = 0; i < maxTries; i += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
const r = await fetch('/api/runs/' + encodeURIComponent(runId))
|
||||
if (!r.ok) continue
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (['done', 'error', 'cancelled'].includes(d.status)) return d
|
||||
}
|
||||
throw new Error('等待运行结束超时')
|
||||
}
|
||||
|
||||
async function probeDws() {
|
||||
probing.value = true
|
||||
try {
|
||||
const r = await fetch('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
plugin_id: PLUGIN_ID,
|
||||
fields: { ...buildPayload(form), probe_dws: true },
|
||||
}),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (!d.run_id) throw new Error('未返回 run_id')
|
||||
const run = await waitRunDone(d.run_id)
|
||||
const path = String((run.result || {}).dws_path || '')
|
||||
if (path) {
|
||||
form.dws_path = path
|
||||
ElMessage.success('dws 可用,已回填路径')
|
||||
} else if (run.status === 'error') {
|
||||
throw new Error(run.error || '检测失败')
|
||||
} else {
|
||||
ElMessage.warning('未检测到 dws:执行时将回退工作通知 + 群机器人')
|
||||
}
|
||||
} catch (e) {
|
||||
ElMessage.warning('检测失败:' + (e.message || e))
|
||||
} finally {
|
||||
probing.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -265,4 +567,20 @@ async function pickDir() {
|
||||
.row-4 .lbl { cursor: help; white-space: nowrap; border-bottom: 1px dashed var(--line-soft); }
|
||||
/* 区块标题右侧的即时摘要 */
|
||||
.sec-tag { flex: 0 0 auto; font-size: 12px; opacity: 0.6; white-space: nowrap; }
|
||||
/* 组织架构范围:按钮栏 + 搜索 + 可滚动树 */
|
||||
.org-box { width: 100%; border: 1px solid var(--line-soft); border-radius: 8px;
|
||||
padding: var(--space-2); display: flex; flex-direction: column; gap: var(--space-2); }
|
||||
.org-tools { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; }
|
||||
.org-tools .spacer { flex: 1 1 auto; }
|
||||
.org-count { font-size: 12px; opacity: 0.7; }
|
||||
.org-search { max-width: 260px; }
|
||||
.org-tree { max-height: 46vh; overflow: auto; }
|
||||
.org-empty { font-size: 12px; opacity: 0.65; padding: 10px 2px; }
|
||||
.org-meta { margin-left: var(--space-2); font-size: 12px; font-weight: normal; opacity: 0.55; }
|
||||
.org-note { font-size: 12px; opacity: 0.7; }
|
||||
/* 表单里的范围摘要行 + 弹窗底部计数 */
|
||||
.scope-row { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; }
|
||||
.scope-summary { font-size: 13px; }
|
||||
.scope-summary.empty { opacity: 0.6; }
|
||||
.scope-foot-count { float: left; line-height: 32px; font-size: 12px; opacity: 0.7; }
|
||||
</style>
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>EHR系统周考勤异常处理</title>
|
||||
<script type="module" crossorigin src="/pui/xq0006/assets/index-D1cP9BaK.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0006/assets/index-Dx1hGP4s.css">
|
||||
<script type="module" crossorigin src="/pui/xq0006/assets/index-FQtc5qxI.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0006/assets/index-fBDsV2zg.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
|
||||
@@ -37,7 +37,7 @@ class WageStartChangePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0036"
|
||||
name = "门店员工起调薪处理"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
description = ("花名册职位序列过滤(仅门店服务/技师/管理序列):入职起薪、其他调薪"
|
||||
"(自动判断换账套与调薪类型),核对工资项/岗位名称/固定项总额与标准一致后提交;"
|
||||
"离职不处理。默认试算不提交,结果导出 xlsx。")
|
||||
|
||||
@@ -15,7 +15,7 @@ import os
|
||||
|
||||
PLUGIN_ID = "xq0036"
|
||||
PLUGIN_NAME = "门店员工起调薪处理"
|
||||
PLUGIN_VERSION = "0.1.5"
|
||||
PLUGIN_VERSION = "0.1.6"
|
||||
|
||||
# ==================== 输出 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\门店员工起调薪处理"
|
||||
@@ -112,7 +112,10 @@ CHANGE_WAGE_TYPE_NAMES = {
|
||||
}
|
||||
|
||||
# ==================== 纳税单位 ====================
|
||||
#: 纳税单位清单(来源:起薪/调薪弹窗 taxUnitSelect;value=纳税单位ID)
|
||||
#: 名称兜底字典(value=纳税单位ID)。
|
||||
#: 纳税单位**优先取接口返回值**(待办行 si_area/si_name、已起薪记录 taxUnitId/taxUnitName),
|
||||
#: 本表只在接口没给名称时用于 ID→名称 反查、以及部门全路径兜底(名称→ID)时使用。
|
||||
#: 清单本身来源于起薪/调薪弹窗 taxUnitSelect 快照,新增/改名会滞后,勿作为判定依据。
|
||||
TAX_UNITS = {
|
||||
"7d352d34-89d8-11ef-bf3a-000c296f9469": "龙湖欢肆行政会馆",
|
||||
"25902c5b-1728-11ef-b449-000c296f9469": "龙湖U城行政会馆",
|
||||
@@ -234,6 +237,12 @@ TAX_UNITS = {
|
||||
"f4244842-74a5-11ee-b449-000c296f9469": "爱琴海行政会馆",
|
||||
}
|
||||
|
||||
#: 后浪会馆:四级部门名只有基础名,纳税单位按岗位细分(同 XQ0035 口径)
|
||||
HOULANG_UNIT_KEY = "后浪新天地LIFE+主题会馆"
|
||||
HOULANG_FNB_POSTS = ("小吃厨师", "吧员", "员工餐厨师", "餐饮组长")
|
||||
#: 金色湖畔:整个事业部共用一个纳税单位
|
||||
HULANG_COMPANY = "金色湖畔企业管理公司"
|
||||
|
||||
# ==================== 线下标准表 ====================
|
||||
#: 标准表薪资总额的九个城市列(顺序与表列一致)
|
||||
CITIES = ("重庆", "成都", "长沙", "西安", "海口", "郑州", "南宁", "深圳", "昆明")
|
||||
@@ -362,14 +371,39 @@ def save_dir(fields: dict = None) -> str:
|
||||
or DEFAULT_WORK_DIR)
|
||||
|
||||
|
||||
def tax_unit_by_org_path(org_path: str) -> tuple:
|
||||
"""按组织全路径匹配纳税单位(取路径中包含的最长会馆名);返回 (id, name)。"""
|
||||
def tax_unit_by_org_path(org_path: str, post: str = "", brand: str = "") -> tuple:
|
||||
"""按组织部门层级兜底匹配纳税单位,返回 (id, name)。
|
||||
|
||||
金色印象:取四级部门(路径里的会馆名);
|
||||
金色湖畔:整个事业部共用一个纳税单位,按品牌定;
|
||||
后浪会馆:四级部门只有基础名,纳税单位按岗位细分为(餐饮)/(非餐饮)。
|
||||
"""
|
||||
path = norm(org_path)
|
||||
if not path:
|
||||
return "", ""
|
||||
|
||||
# 后浪会馆:路径里是不带后缀的基础名,按岗位细分餐饮/非餐饮(与 XQ0035 同口径)
|
||||
if HOULANG_UNIT_KEY in path:
|
||||
is_fnb = any(norm(k) in norm(post) for k in HOULANG_FNB_POSTS)
|
||||
return _tax_unit_by_name(HOULANG_UNIT_KEY + ("(餐饮)" if is_fnb else "(非餐饮)"))
|
||||
|
||||
# 金色湖畔:事业部内所有部门共用一个纳税单位
|
||||
if brand == "金色湖畔" or "金色湖畔事业部" in path:
|
||||
return _tax_unit_by_name(HULANG_COMPANY)
|
||||
|
||||
# 金色印象:取路径中包含的最长会馆名(四级部门)
|
||||
best_id, best_name = "", ""
|
||||
for uid, name in TAX_UNITS.items():
|
||||
key = norm(name)
|
||||
if key and key in path and len(key) > len(norm(best_name)):
|
||||
best_id, best_name = uid, name
|
||||
return best_id, best_name
|
||||
|
||||
|
||||
def _tax_unit_by_name(name: str) -> tuple:
|
||||
"""按名称(忽略全半角/大小写差异)在兜底字典里反查纳税单位 ID。"""
|
||||
target = norm(name)
|
||||
for uid, unit_name in TAX_UNITS.items():
|
||||
if norm(unit_name) == target:
|
||||
return uid, unit_name
|
||||
return "", ""
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""纳税单位兜底:优先沿用已显示/花名册值,缺省时按部门全路径中的会馆匹配。"""
|
||||
"""纳税单位解析:优先取接口实时返回值,缺省时再按部门层级兜底。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,10 +7,20 @@ from .. import config
|
||||
|
||||
|
||||
def resolve(row: dict, started: dict = None, staff_base: dict = None) -> dict:
|
||||
"""返回 {id, name, source};纳税单位缺失时始终按部门全路径兜底。"""
|
||||
"""返回 {id, name, source}。
|
||||
|
||||
取值优先级:待办行 si_area/si_name(接口实时值)→ 已起薪记录 → 花名册 → 部门层级兜底。
|
||||
待办行是当前组织口径,换店调薪时比已起薪记录里的旧值更准。
|
||||
"""
|
||||
started = started or {}
|
||||
staff_base = staff_base or {}
|
||||
|
||||
unit_id = config.text(row.get("si_area"))
|
||||
if unit_id:
|
||||
return {"id": unit_id,
|
||||
"name": config.text(row.get("si_name")) or config.TAX_UNITS.get(unit_id, ""),
|
||||
"source": "待办(接口)"}
|
||||
|
||||
unit_id = config.text(started.get("taxUnitId"))
|
||||
if unit_id:
|
||||
return {"id": unit_id,
|
||||
@@ -23,8 +33,12 @@ def resolve(row: dict, started: dict = None, staff_base: dict = None) -> dict:
|
||||
"name": config.TAX_UNITS.get(unit_id, ""),
|
||||
"source": "花名册"}
|
||||
|
||||
unit_id, unit_name = config.tax_unit_by_org_path(row.get("ORG_FULL_PATH"))
|
||||
unit_id, unit_name = config.tax_unit_by_org_path(
|
||||
row.get("ORG_FULL_PATH"),
|
||||
post=row.get("POST_ORG_NAME"),
|
||||
brand=config.brand_for_unit(row.get("BELONG_UNIT_ORG_NAME")),
|
||||
)
|
||||
if unit_id:
|
||||
return {"id": unit_id, "name": unit_name, "source": "部门全路径"}
|
||||
return {"id": unit_id, "name": unit_name, "source": "部门层级"}
|
||||
|
||||
return {"id": "", "name": "", "source": "未匹配"}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0036",
|
||||
"name": "门店员工起调薪处理",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"description": "花名册职位序列过滤(仅门店服务/技师/管理序列):入职起薪、其他调薪(自动判断换账套与调薪类型),核对工资项/岗位名称/固定项总额与线下标准一致后提交;离职不处理;纳税单位缺失时按部门全路径会馆兜底;技师岗免核对固定项总额。默认试算不提交,结果导出 xlsx。",
|
||||
"category": "人资",
|
||||
"icon": "",
|
||||
|
||||
@@ -163,12 +163,13 @@
|
||||
## 6. 纳税单位
|
||||
|
||||
优先级:
|
||||
1. 工资记录里**已显示**的 `taxUnitId` / `taxUnitName`;
|
||||
2. 员工基础信息(花名册)里的纳税单位字段;
|
||||
3. 按部门全路径匹配「会馆」名称(取路径中包含的最长会馆名,如「石桥铺会馆」);
|
||||
4. 都取不到 → 待人工。
|
||||
1. 待办行接口实时返回的 `si_area` / `si_name`(当前组织口径,换店调薪也准);
|
||||
2. 工资记录里**已显示**的 `taxUnitId` / `taxUnitName`;
|
||||
3. 员工基础信息(花名册)里的纳税单位字段;
|
||||
4. 按部门层级兜底:金色印象取**四级部门**(路径里的会馆名);金色湖畔整个事业部共用「金色湖畔企业管理公司」;后浪会馆的四级部门只有基础名,按岗位细分「(餐饮)」「(非餐饮)」;
|
||||
5. 都取不到 → 待人工。
|
||||
|
||||
第 3 步默认始终执行(不提供开关)。
|
||||
纳税单位清单不再写死参与判定:代码里的 `TAX_UNITS` 只作名称兜底(ID↔名称互查),匹配一律以接口返回为准。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -16,10 +16,20 @@ from . import config
|
||||
from .data import weimob_export, weimob_login
|
||||
|
||||
|
||||
def _parse_timeout_min(raw):
|
||||
"""界面「等待生成上限(分钟)」→ int,非法值回落默认值并夹到允许范围。"""
|
||||
lo, hi = config.POLL_TIMEOUT_LIMITS
|
||||
try:
|
||||
val = int(float(str(raw).strip() or config.POLL_TIMEOUT_MIN))
|
||||
except (TypeError, ValueError):
|
||||
return config.POLL_TIMEOUT_MIN
|
||||
return max(lo, min(hi, val))
|
||||
|
||||
|
||||
class WeimobExportPlugin(ScenePlugin):
|
||||
id = "xq0047"
|
||||
name = "微盟数据导出"
|
||||
version = "1.0.3"
|
||||
version = "1.0.5"
|
||||
description = ("微盟商家后台订单数据自动导出:登录微盟(腾讯验证码需人工完成,登录态缓存复用),"
|
||||
"按订单量自动等分时间区间批量创建导出任务,统一轮询下载并合并为一个 Excel")
|
||||
platform = "" # 微盟自带登录页(腾讯验证码),插件内现场真登录,不使用底座共享登录态
|
||||
@@ -32,6 +42,8 @@ class WeimobExportPlugin(ScenePlugin):
|
||||
"wm_password": {"type": "string", "title": "微盟登录密码", "default": "",
|
||||
"format": "password"},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
"poll_timeout_min": {"type": "number", "title": "等待生成上限(分钟)",
|
||||
"default": config.POLL_TIMEOUT_MIN},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
@@ -42,11 +54,13 @@ class WeimobExportPlugin(ScenePlugin):
|
||||
username = str(fields.get("wm_username") or "").strip()
|
||||
password = str(fields.get("wm_password") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or config.default_output_dir()
|
||||
timeout_min = _parse_timeout_min(fields.get("poll_timeout_min"))
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("微盟登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"保存目录:{save_dir}")
|
||||
ctx.log(f"等待生成上限:{timeout_min} 分钟")
|
||||
|
||||
# ---------- 登录(缓存复用,失效时浏览器现场登录) ----------
|
||||
ctx.progress(2)
|
||||
@@ -57,7 +71,7 @@ class WeimobExportPlugin(ScenePlugin):
|
||||
ctx.progress(10)
|
||||
|
||||
# ---------- 导出 ----------
|
||||
result = weimob_export.run_export(save_dir, ctx.progress)
|
||||
result = weimob_export.run_export(save_dir, ctx.progress, timeout_min)
|
||||
if not result.get("success"):
|
||||
raise RuntimeError(result.get("message") or "微盟订单导出失败")
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ INTERVAL_MAX = 5 # 请求间限流上限(秒,随机化模拟人
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试3次) ====================
|
||||
RETRY_MAX = 3 # 单段 exportOrder 最大重试次数
|
||||
POLL_MAX = 180 # 统一轮询 download/list 最大次数(180×10s ≈ 30 分钟)
|
||||
POLL_TIMEOUT_MIN = 180 # 等待导出任务生成的默认上限(分钟),界面「等待上限」可覆盖
|
||||
POLL_TIMEOUT_LIMITS = (5, 720) # 等待上限允许范围(分钟):5 分钟 ~ 12 小时
|
||||
POLL_INTERVAL = 10 # 轮询间隔(秒)
|
||||
DOWNLOAD_WORKERS = 4 # 并发下载线程数
|
||||
TIMEOUT = 25 # 接口请求超时(秒)
|
||||
|
||||
@@ -289,13 +289,15 @@ def create_export_tasks(session, segments, progress=None):
|
||||
return tasks
|
||||
|
||||
|
||||
def wait_all_done(session, tasks, progress=None):
|
||||
def wait_all_done(session, tasks, progress=None, timeout_min=None):
|
||||
"""统一轮询 download/list,一次请求取回全部任务状态(异步并行等待)。
|
||||
|
||||
timeout_min:等待上限(分钟),None 取 config.POLL_TIMEOUT_MIN。
|
||||
任务归属:第 i 段任务 = createTime ∈ [trigger_i, trigger_{i+1}),末段上界为 None;
|
||||
下界留 1 秒容差,兼容 createTime 秒级截断。
|
||||
返回与 tasks 顺序一致的完成记录列表;超时返回 None(打印最近记录便于诊断)。
|
||||
"""
|
||||
poll_max = max(1, int((timeout_min or config.POLL_TIMEOUT_MIN) * 60 / config.POLL_INTERVAL))
|
||||
windows = []
|
||||
for i, t in enumerate(tasks):
|
||||
lo = t["trigger_ms"] - 1000
|
||||
@@ -306,7 +308,7 @@ def wait_all_done(session, tasks, progress=None):
|
||||
done = {}
|
||||
used = set()
|
||||
pending = list(range(len(tasks)))
|
||||
for round_no in range(1, config.POLL_MAX + 1):
|
||||
for round_no in range(1, poll_max + 1):
|
||||
time.sleep(config.POLL_INTERVAL if round_no > 1 else 3)
|
||||
items = _fetch_download_items(session, page_size)
|
||||
if items is None:
|
||||
@@ -325,12 +327,19 @@ def wait_all_done(session, tasks, progress=None):
|
||||
_emit(progress, 35 + 25 * len(done) / max(1, len(tasks)))
|
||||
if not pending:
|
||||
return [done[i] for i in range(len(tasks))]
|
||||
config.log(f" 轮询 {round_no}/{config.POLL_MAX}:已完成 {len(done)}/{len(tasks)}")
|
||||
config.log(f" 轮询 {round_no}/{poll_max}:已完成 {len(done)}/{len(tasks)}")
|
||||
|
||||
config.log(" 等待超时,最近导出记录:", "ERROR")
|
||||
config.log(f" 等待超时(上限 {timeout_min or config.POLL_TIMEOUT_MIN} 分钟):"
|
||||
f"{len(pending)}/{len(tasks)} 段未完成", "ERROR")
|
||||
for idx in pending:
|
||||
t = tasks[idx]
|
||||
config.log(f" 段 {idx + 1}/{len(tasks)} 未匹配到导出记录:{_fmt_range(t['start'], t['end'])}",
|
||||
"ERROR")
|
||||
config.log(" 最近导出记录:", "ERROR")
|
||||
for it in (_fetch_download_items(session, page_size) or [])[:10]:
|
||||
config.log(f" id={it.get('id')} status={it.get('status')} "
|
||||
f"fileName={it.get('fileName')} createTime={it.get('createTime')}")
|
||||
config.log(" 提示:任务可能仍在平台侧排队生成,可稍后到微盟「导出中心」确认,勿反复重导", "ERROR")
|
||||
return None
|
||||
|
||||
|
||||
@@ -499,9 +508,10 @@ def merge_excels(paths, out_dir):
|
||||
|
||||
|
||||
# ================== 主流程 ==================
|
||||
def run_export(out_dir, progress=None):
|
||||
def run_export(out_dir, progress=None, timeout_min=None):
|
||||
"""微盟订单导出主流程(登录态须已就绪)。
|
||||
|
||||
timeout_min:等待导出任务生成的上限(分钟),None 取 config.POLL_TIMEOUT_MIN。
|
||||
探测条数 → 按条数等分并逐段校验 → 批量建导出任务 → 统一轮询 → 下载解压 → 合并一个 Excel。
|
||||
返回 dict {success, excel_path, message, segments, rows}。
|
||||
"""
|
||||
@@ -535,8 +545,8 @@ def run_export(out_dir, progress=None):
|
||||
"message": "创建导出任务失败(请检查登录态或风控状态后重试)"}
|
||||
|
||||
# 阶段 3:统一轮询全部任务(一次请求拿全部状态,等最慢的一段)
|
||||
config.log("等待全部导出任务生成:")
|
||||
items = wait_all_done(session, tasks, progress)
|
||||
config.log(f"等待全部导出任务生成(上限 {timeout_min or config.POLL_TIMEOUT_MIN} 分钟):")
|
||||
items = wait_all_done(session, tasks, progress, timeout_min)
|
||||
if items is None:
|
||||
return {"success": False, "excel_path": "", "segments": len(segments), "rows": 0,
|
||||
"message": "等待导出任务完成超时(已创建任务可能仍在生成,稍后可重试)"}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0047",
|
||||
"name": "微盟数据导出",
|
||||
"version": "1.0.3",
|
||||
"version": "1.0.5",
|
||||
"description": "微盟商家后台(master.weimob.com)订单数据自动导出:登录微盟(腾讯验证码需人工完成,登录态缓存复用),按订单量自动等分时间区间批量创建导出任务,统一轮询下载 zip 并合并为一个 Excel",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
@@ -36,6 +36,12 @@
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/微盟订单导出;输出单个 xlsx(微盟订单_YYYYMMDD_HHMMSS.xlsx),各段源文件同目录保留"
|
||||
},
|
||||
"poll_timeout_min": {
|
||||
"type": "number",
|
||||
"title": "等待生成上限(分钟)",
|
||||
"default": 180,
|
||||
"description": "等待平台生成导出文件的最长时间,范围 5~720 分钟。平台偶发排队可能超过 30 分钟,建议不低于 60"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -76,6 +76,11 @@
|
||||
placeholder="留空 = 桌面/微盟订单导出" />
|
||||
<div class="tip">导出区间固定为上月 1 日 00:00 至执行时刻;按 4.5 万单自动分段导出并合并为一份 xlsx(含各分段中间文件)</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="等待生成上限(分钟)">
|
||||
<el-input-number v-model="form.poll_timeout_min" :min="5" :max="720" :step="30"
|
||||
:disabled="running" controls-position="right" style="width: 180px" />
|
||||
<div class="tip">等待平台生成导出文件的最长时间。平台偶发排队会超过 30 分钟,建议不低于 60</div>
|
||||
</el-form-item>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
@@ -114,6 +119,7 @@ const DEFAULTS = () => ({
|
||||
wm_username: '',
|
||||
wm_password: '',
|
||||
save_dir: '',
|
||||
poll_timeout_min: 180,
|
||||
})
|
||||
|
||||
const {
|
||||
@@ -135,6 +141,7 @@ const {
|
||||
wm_username: f.wm_username.trim(),
|
||||
wm_password: f.wm_password.trim(),
|
||||
save_dir: f.save_dir,
|
||||
poll_timeout_min: Number(f.poll_timeout_min) || 180,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
+14
-14
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>微盟数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0047/assets/index-DZHj0Evd.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0047/assets/index-BS4ABaKl.css">
|
||||
<script type="module" crossorigin src="/pui/xq0047/assets/index-CBMZ2MXA.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0047/assets/index-DjJie4MG.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Reference in New Issue
Block a user