chore: 清理废弃插件与冗余文档,重构项目目录结构
1. 删除旧版xq0031_xq0032插件的冗余UI源码与配置文件 2. 迁移并标准化XQ0001-0100系列需求的插件、文档与工作流目录 3. 清理过期的需求列表、评分文档与流程底稿 4. 更新.gitignore匹配规则,适配新的目录结构
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件入口。
|
||||
|
||||
流程编排:
|
||||
1) 封存数据导出与预处理(全集团 → 白名单单位 → 学校剔除 → 固定路径封存表);
|
||||
2) 花名册导出(TTL 15 分钟缓存复用)、调动台账导出(自动);
|
||||
3) 依次执行检查1~6(在职天数/出勤排休/封存最新值/全勤验证/未封存/延时加班);
|
||||
4) 单工作簿输出(汇总 + 检查1~6 共 7 个 sheet)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = True
|
||||
(前端页眉月份选择器经 payload.ref_month 注入)。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data.seal_data_export import export_seal_data
|
||||
from .data.roster_export_api import export_roster
|
||||
from .data.transfer_roster_export_api import export_transfer_roster
|
||||
from .report.monthly_report_check import run_all_checks, write_workbook, _normalize_month
|
||||
|
||||
|
||||
class KqSealCheckPlugin(ScenePlugin):
|
||||
"""考勤月报封存检查(需求 XQ0011)。"""
|
||||
|
||||
id = "xq0011"
|
||||
name = "考勤月报封存检查"
|
||||
version = "1.0.0"
|
||||
description = ("考勤月报封存后自动检查:拉取当月全集团封存数据并按白名单单位预处理,"
|
||||
"自动导出花名册/调动台账,依次执行 6 项检查(在职天数排班/出勤及排休/"
|
||||
"封存最新值/全勤验证/未封存名单/延时加班),输出单工作簿异常名单")
|
||||
platform = "hr"
|
||||
uses_month = True
|
||||
capabilities = ["xq0011"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": r"D:\资料\人资\考勤月报封存检查",
|
||||
"description": "封存表/花名册/调动台账/汇总工作簿统一输出目录",
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string", "title": "花名册路径", "default": "",
|
||||
"description": "留空=输出目录/员工花名册.xlsx(自动导出,15 分钟内复用)",
|
||||
},
|
||||
"transfer_path": {
|
||||
"type": "string", "title": "调动台账路径", "default": "",
|
||||
"description": "留空=输出目录/调动台账.xlsx(自动导出,15 分钟内复用)",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / HR 会话 / userId ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
|
||||
month = _normalize_month(fields.get("ref_month") or fields.get("month") or "")
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
roster_path = (fields.get("roster_path") or "").strip() or os.path.join(save_dir, "员工花名册.xlsx")
|
||||
transfer_path = (fields.get("transfer_path") or "").strip() or os.path.join(save_dir, "调动台账.xlsx")
|
||||
config.set_roster_path(roster_path)
|
||||
session = config.get_session()
|
||||
|
||||
ctx.log(f"===== 考勤月报封存检查启动:月份 {month},输出目录 {save_dir} =====", "INFO")
|
||||
notes: list = []
|
||||
|
||||
# ---- 步骤1:封存数据导出与预处理(5% ~ 30%) ----
|
||||
ctx.progress(5)
|
||||
export_seal_data(month, save_dir)
|
||||
ctx.progress(30)
|
||||
|
||||
# ---- 步骤2:花名册导出(TTL 15 分钟缓存复用,30% ~ 45%) ----
|
||||
ctx.progress(30)
|
||||
try:
|
||||
export_roster(output_path=roster_path,
|
||||
download_dir=os.path.join(config.CACHE_DIR, "roster_tmp"),
|
||||
session=session)
|
||||
except Exception as e:
|
||||
notes.append(f"花名册导出失败(检查5/6 与部门回填将受影响):{e}")
|
||||
ctx.log(f"花名册导出失败:{e}", "WARN")
|
||||
ctx.progress(45)
|
||||
|
||||
# ---- 步骤3:调动台账导出(45% ~ 55%) ----
|
||||
try:
|
||||
export_transfer_roster(output_path=transfer_path, session=session)
|
||||
except Exception as e:
|
||||
notes.append(f"调动台账导出失败(检查4 将受影响):{e}")
|
||||
ctx.log(f"调动台账导出失败:{e}", "WARN")
|
||||
ctx.progress(55)
|
||||
|
||||
# ---- 步骤4:依次执行检查1~6(55% ~ 90%) ----
|
||||
result = run_all_checks(month, save_dir, roster_path, transfer_path)
|
||||
ctx.progress(90)
|
||||
|
||||
# ---- 步骤5:单工作簿输出(90% ~ 100%) ----
|
||||
save_path = write_workbook(result, save_dir)
|
||||
ctx.progress(100)
|
||||
|
||||
detail = {it["no"]: len(it["rows"]) for it in result["results"]}
|
||||
summary = ("考勤月报封存检查完成({ym}),异常合计 {total} 人:{detail}。"
|
||||
"汇总工作簿:{path}").format(
|
||||
ym=result["ym"], total=result["total"],
|
||||
detail="、".join(f"{k}:{v}" for k, v in detail.items()),
|
||||
path=save_path)
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
return {"summary": summary, "notes": notes,
|
||||
"detail": detail, "path": save_path, "ym": result["ym"]}
|
||||
|
||||
|
||||
PLUGINS.append(KqSealCheckPlugin())
|
||||
@@ -0,0 +1,53 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件打包脚本(统一规范版)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(与 xq0031 一致,目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe plugins\\XQ0001-0100\\XQ0011 考勤月报封存检查\\_pack.py
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0011_v<版本>.zip --id xq0011 --version <版本>
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_REPO_ROOT = _HERE.parents[2]
|
||||
_OUT_DIR = _REPO_ROOT / "dist-plugin"
|
||||
|
||||
# 排除项:打包脚本自身 / 前端源码与依赖 / 缓存 / 调试文件(_ 前缀为私有辅助)
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", ".git", ".idea", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid = manifest["id"]
|
||||
ver = manifest["version"]
|
||||
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
|
||||
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
count = 0
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
|
||||
or p.suffix in _EXCLUDE_SUFFIXES:
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
count += 1
|
||||
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.log() 输出日志、config.get_session()/get_user_id() 取登录态。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 共享目录(登录态/缓存,与影刀版同路径) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache') # 应勤天方案 1 天文件缓存
|
||||
|
||||
# ==================== HR 接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
STAT_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/kq_count_leave_StatV2/CoreRequest.mc"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
TEAM_EXTEND_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_extend_table_select/redApiExec.mc"
|
||||
TEAM_PLAN_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_minyq_plan_up_query_all/redApiExec.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ==================== 输出目录与文件(默认与影刀版一致) ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
|
||||
def _default_roster(save_dir):
|
||||
return os.path.join(save_dir, "员工花名册.xlsx")
|
||||
|
||||
|
||||
def _default_transfer(save_dir):
|
||||
return os.path.join(save_dir, "调动台账.xlsx")
|
||||
|
||||
|
||||
# ==================== 口径常量 ====================
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_WHITELIST = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
# 花名册剔除口径
|
||||
EXCLUDE_FIRST_DEPT = "职业技术培训学校" # 一级部门等于该值不参与检查
|
||||
EXCLUDE_EMPTY_FIRST_DEPT = True # 一级部门为空(直属根节点高管)不参与检查
|
||||
ROSTER_DEPT_COLS = ("一级部门", "二级部门", "三级部门", "四级部门", "五级部门")
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_JOIN_COL = "入职时间"
|
||||
ROSTER_LEAVE_COL = "离职时间"
|
||||
ROSTER_SEQ_COL = "职位序列"
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_roster_path = ""
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
uid = _user_id
|
||||
if not uid:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
return uid
|
||||
|
||||
|
||||
def set_roster_path(path):
|
||||
"""花名册路径全局配置(run() 解析后注入,部门回填/剔除默认使用)。"""
|
||||
global _roster_path
|
||||
_roster_path = str(path or "")
|
||||
|
||||
|
||||
def get_roster_path():
|
||||
return _roster_path or _default_roster(DEFAULT_SAVE_DIR)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 数据层:HR 接口数据导出与加载(封存数据 / 花名册 / 调动台账)。"""
|
||||
@@ -0,0 +1,467 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 员工花名册导出(由 workflows/share/roster_export_api.py 内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
|
||||
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致,含「职位序列」列)
|
||||
"员工基础信息": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||||
"hr_staff_base_ext.ext_star_level", # 星级
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||||
"pt_post_level.ext_grade_name", # 职等
|
||||
"hr_staff_base.mobile_phone", # 手机号码
|
||||
"hr_staff_base.person_status", # 在职状态
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||||
"hr_staff_base.nation", # 民族
|
||||
"hr_staff_base.sex", # 性别
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.period", # 试用期限(月)
|
||||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||||
"hr_staff_base.identity", # 用工类型
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数 ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
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 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
|
||||
def _build_session(session=None):
|
||||
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
|
||||
if session is not None:
|
||||
return session
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name):
|
||||
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
|
||||
try:
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
|
||||
return None
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先在插件界面重新完成 HR 登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
|
||||
_bind_session(session)
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
|
||||
单 sheet,表头在第1行,数据第2行起。
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None,
|
||||
ttl=DEFAULT_TTL_SECONDS, session=None):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_roster 一致。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
"""
|
||||
download_dir = download_dir or os.path.dirname(output_path or "") or "."
|
||||
output_path = output_path or "花名册.xlsx"
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None:
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
|
||||
template_name, statuses, leave_desc)
|
||||
|
||||
session = _build_session(session)
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
@@ -0,0 +1,399 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 封存数据导出与预处理(由影刀版 seal_data_export.py 移植)。
|
||||
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1~6 一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. HR 会话/用户 ID 由底座 RunContext 注入(config 全局钩子),不再自行读 cookies 构建;
|
||||
2. 登录态失效不再自动补登(插件无法自动登录),直接抛错提示重新登录;
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from datetime import date, datetime
|
||||
from functools import lru_cache
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import (
|
||||
logger, require_session, require_user_id, set_roster_path, get_roster_path,
|
||||
CACHE_DIR, SESSIONS_DIR,
|
||||
HR_BASE_URL, GET_CUR_USER_INFO_URL, SEAL_URL, SEAL_SQL_ID, PAGE_MAX_SIZE,
|
||||
DEFAULT_SAVE_DIR, SEAL_UNIT_WHITELIST, SEAL_CODE_FIELDS,
|
||||
EXCLUDE_FIRST_DEPT, EXCLUDE_EMPTY_FIRST_DEPT,
|
||||
ROSTER_CODE_COL, ROSTER_UNIT_COL, ROSTER_DEPT_COLS,
|
||||
)
|
||||
|
||||
# 所属单位白名单 / 剔除口径 / 花名册列定义统一取自 config
|
||||
|
||||
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
|
||||
CN_FIELD_MAP: Dict[str, str] = {
|
||||
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
|
||||
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
|
||||
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
|
||||
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
|
||||
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
|
||||
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
|
||||
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
|
||||
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
|
||||
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
|
||||
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
|
||||
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
|
||||
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
|
||||
"_年度福利假天": "kq_stat_leave_day_num24",
|
||||
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
|
||||
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
|
||||
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
|
||||
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
|
||||
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
|
||||
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
|
||||
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
|
||||
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
|
||||
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
|
||||
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
|
||||
"员工状态": "staff_status", "在职状态": "person_status_name",
|
||||
}
|
||||
|
||||
|
||||
# ==================== HR 登录态(底座注入) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _expired_error(label):
|
||||
return RuntimeError(
|
||||
f"{label}:HR 登录态已失效,无法自动补登。请在插件界面重新完成 HR 登录后重试。")
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(getPageAjaxList.mc + leave_wage_SelectV2) ====================
|
||||
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页考勤封存数据。
|
||||
|
||||
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
|
||||
"""
|
||||
params = {
|
||||
"tree_code": "cq37du",
|
||||
"user_id": user_id,
|
||||
"sqlId": SEAL_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"dept_org_name": "",
|
||||
"confirm_state": "",
|
||||
"person_status": "",
|
||||
"identity": "",
|
||||
"staff_status": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"post_type": "1",
|
||||
"custom_dept_ids": "",
|
||||
"custom_dept_names": "",
|
||||
"STAFF_ID": "",
|
||||
"sealOrgAlias": "",
|
||||
"seal_dept_stru_id": "",
|
||||
"kqDataOperatorName": "",
|
||||
"kqDataOperatorId": "",
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"yearmonth": yearmonth,
|
||||
"kq_data_state": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
|
||||
|
||||
|
||||
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
|
||||
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise _expired_error("考勤封存")
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤封存第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤封存无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
import time
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _text(v) -> str:
|
||||
return _clean(v)
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)[:10]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _month_days(ym: str) -> int:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
return pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
|
||||
|
||||
def _seal_path(save_dir: str, ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(save_dir, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
def _rename_columns_cn(frame: "pd.DataFrame", cn_map: Dict[str, str]) -> "pd.DataFrame":
|
||||
"""把封存数据列名按 中文导出列→接口字段 映射替换为中文表头。
|
||||
|
||||
仅重命名 cn_map 中存在的列,未映射的列(如各类 kq_stat_* 扩展字段)保留原英文名,
|
||||
列顺序不变,保证保存的封存数据信息不丢失。
|
||||
"""
|
||||
rename = {en: cn for cn, en in cn_map.items() if en in frame.columns}
|
||||
return frame.rename(columns=rename)
|
||||
|
||||
|
||||
# ==================== 预处理:所属单位白名单筛选 ====================
|
||||
def _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get("BELONG_UNIT_ORG_NAME")) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
def _rec_code(rec: dict) -> str:
|
||||
"""封存记录工号(base_code 优先,seal_base_code 兜底)。"""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
c = _clean(rec.get(f))
|
||||
if c:
|
||||
return c
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 花名册:剔除名单 & 工号→1-5级部门 缓存 ====================
|
||||
@lru_cache(maxsize=4)
|
||||
def _load_roster_maps(roster_path: str) -> Tuple[Dict[str, dict], Set[str]]:
|
||||
"""读取花名册(当日全量导出,在职+离职)→ (工号→所属单位/1-5级部门 映射, 剔除工号集合)。
|
||||
|
||||
剔除口径(不参与本检查):
|
||||
1) 一级部门 = EXCLUDE_FIRST_DEPT(职业技术培训学校);
|
||||
2) 一级部门为空 = 直属单位根节点的高管(未挂具体部门树),同样不参与检查。
|
||||
同一工号可能多行(在职/离职并存),后读取的行覆盖先前的行。
|
||||
花名册缺失时返回空映射与空集合,不影响检查主流程(仅部门回填为空、不剔除)。
|
||||
"""
|
||||
if not roster_path or not os.path.exists(roster_path):
|
||||
logger.warning("花名册不存在,跳过部门回填与学校剔除:%s", roster_path)
|
||||
return {}, set()
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
dept_map: Dict[str, dict] = {}
|
||||
excluded: Set[str] = set()
|
||||
school_n = exec_n = 0
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code:
|
||||
continue
|
||||
info = {
|
||||
"所属单位": _clean(row.get(ROSTER_UNIT_COL)),
|
||||
**{c: _clean(row.get(c)) for c in ROSTER_DEPT_COLS},
|
||||
}
|
||||
dept_map[code] = info
|
||||
if _clean(row.get(ROSTER_DEPT_COLS[0])) == EXCLUDE_FIRST_DEPT:
|
||||
excluded.add(code)
|
||||
school_n += 1
|
||||
elif EXCLUDE_EMPTY_FIRST_DEPT and not _clean(row.get(ROSTER_DEPT_COLS[0])):
|
||||
excluded.add(code) # 部门树为空的高管,不参与检查
|
||||
exec_n += 1
|
||||
logger.info("花名册读取完成:%s(%d 人,剔除「%s」%d 人 + 高管 %d 人)",
|
||||
roster_path, len(dept_map), EXCLUDE_FIRST_DEPT, school_n, exec_n)
|
||||
return dept_map, excluded
|
||||
|
||||
|
||||
def load_roster_dept_map(roster_path: str = None) -> Dict[str, dict]:
|
||||
"""工号 → {所属单位, 一级部门~五级部门} 映射(进程内按路径缓存,一次读取)。"""
|
||||
dept_map, _ = _load_roster_maps(roster_path or get_roster_path())
|
||||
return dept_map
|
||||
|
||||
|
||||
def load_excluded_codes(roster_path: str = None) -> Set[str]:
|
||||
"""一级部门 = 职业技术培训学校 的剔除工号集合。"""
|
||||
_, excluded = _load_roster_maps(roster_path or get_roster_path())
|
||||
return set(excluded)
|
||||
|
||||
|
||||
DEPT_CN_ORDER = ("一", "二", "三", "四", "五")
|
||||
DEPT_ORG_FIELDS = ("DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE")
|
||||
|
||||
|
||||
def enrich_dept_fields(target: dict, code: str, rec: dict = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""异常名单行回填「所属单位 + 一级~五级部门」:优先花名册(按工号),兜底封存记录字段。
|
||||
|
||||
Args:
|
||||
target: 待回填的行 dict(就地修改并返回)。
|
||||
code: 37工号。
|
||||
rec: 封存记录行(兜底部门来源),可为 None。
|
||||
"""
|
||||
info = load_roster_dept_map(roster_path).get(code) or {}
|
||||
rec = rec or {}
|
||||
target["所属单位"] = info.get("所属单位") or _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
for chn, cn, f in zip(DEPT_CN_ORDER, ROSTER_DEPT_COLS, DEPT_ORG_FIELDS):
|
||||
target[cn] = info.get(cn) or _clean(rec.get(f))
|
||||
return target
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
save_dir: 输出目录,默认 config.DEFAULT_SAVE_DIR。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = require_session()
|
||||
user_id = require_user_id()
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 2.1 花名册剔除:一级部门 = 职业技术培训学校 的不参与本检查
|
||||
excluded = load_excluded_codes()
|
||||
if excluded:
|
||||
before = len(filtered)
|
||||
filtered = [rec for rec in filtered if _rec_code(rec) not in excluded]
|
||||
logger.info("花名册剔除不参与人员(「%s」/高管):%d 人 → %d 人",
|
||||
EXCLUDE_FIRST_DEPT, before, len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
path = _seal_path(save_dir, ym)
|
||||
try:
|
||||
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
save_dir: 输出目录,默认 config.DEFAULT_SAVE_DIR。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
path = _seal_path(save_dir, ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先执行插件(封存导出步骤)导出并预处理当月封存数据后再检查。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
# 兜底剔除(防止历史封存表未做学校剔除):一级部门 = 职业技术培训学校 的工号
|
||||
excluded = load_excluded_codes()
|
||||
if excluded:
|
||||
before = len(rows)
|
||||
rows = [r for r in rows if _rec_code(r) not in excluded]
|
||||
if len(rows) != before:
|
||||
logger.warning("读取封存表后按花名册剔除不参与人员(「%s」/高管)%d 人:%d → %d",
|
||||
EXCLUDE_FIRST_DEPT, before - len(rows), before, len(rows))
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
@@ -0,0 +1,341 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 调动台账导出(由 workflows/share/transfer_roster_export_api.py 内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问调动台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(调动已生效 rosterId=10feec75,模板=排班异常识别导出,
|
||||
调动时间范围经 commonQuery 加密传入)-> 接收 "--end--|文件路径" 推送 -> 下载保存。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 调动台账查询/导出接口(浏览器抓包提取) ----------
|
||||
TRANSFER_ROSTER_ID = "10feec75-b094-11ea-b588-14187743d052"
|
||||
TRANSFER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{TRANSFER_ROSTER_ID}/getCustomCommonList.mc"
|
||||
TRANSFER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{TRANSFER_ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 调动台账导出固定入参(浏览器抓包提取)
|
||||
TRANSFER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "调动台账",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_move_info",
|
||||
"rosterId": TRANSFER_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,「排班异常识别导出」模板,含原/现职位序列、调动时间) ----------
|
||||
TRANSFER_TEMPLATE_FILTERS = {
|
||||
"排班异常识别导出": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_move_info.CHANGE_TYPE", # 调动类型
|
||||
"hr_staff_move_info.PRE_ORG_NAME", # 原所属单位
|
||||
"hr_staff_move_info.PRE_DEPT_NAME", # 原部门
|
||||
"hr_staff_move_info.PRE_PARENT_ORG_NAME", # 原上级部门
|
||||
"hr_staff_move_info_ext.ext_pre_dept_one", # 原一级部门
|
||||
"hr_staff_move_info_ext.ext_pre_dept_five", # 原五级部门
|
||||
"hr_staff_move_info.PRE_POST_NAME", # 原岗位
|
||||
"hr_staff_move_info.pre_first_type_id", # 原职位序列
|
||||
"hr_staff_move_info.NOW_ORG_NAME", # 现所属单位
|
||||
"hr_staff_move_info.DEPT_NAME", # 现部门
|
||||
"hr_staff_move_info.NOW_PARENT_ORG_NAME", # 现上级部门
|
||||
"hr_staff_move_info_ext.ext_now_dept_one", # 现一级部门
|
||||
"hr_staff_move_info_ext.ext_now_dept_five", # 现五级部门
|
||||
"hr_staff_move_info.POST_NAME", # 现岗位
|
||||
"hr_staff_move_info.now_first_type_id", # 现职位序列
|
||||
"pt_structure1.dept_org_four", # 原四级部门
|
||||
"pt_structure.dept_org_four", # 现四级部门
|
||||
"hr_staff_move_info.MOVE_DATE", # 调动时间
|
||||
"hr_staff_move_info.OPERAT_TIME", # 操作时间
|
||||
]),
|
||||
}
|
||||
|
||||
DEFAULT_TEMPLATE = "排班异常识别导出"
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(与花名册共用同一套自实现) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd"
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
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 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
|
||||
def _build_session(session=None):
|
||||
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
|
||||
if session is not None:
|
||||
return session
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成调动台账导出所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def get_transfer_range(today: date = None, days: int = 30):
|
||||
"""计算调动日期筛选范围,返回 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_move_date_conditions(start, end):
|
||||
"""调动时间区间条件(与页面「更多搜索 -> 调动时间」抓包条件一致)。"""
|
||||
return [
|
||||
build_condition("`hr_staff_move_info.MOVE_DATE`", ">=", start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_move_info.MOVE_DATE`", "<=", end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出 ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问调动台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(TRANSFER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先在插件界面重新完成 HR 登录后再重试。")
|
||||
|
||||
|
||||
def _export_once(session, download_dir, template_name, start, end):
|
||||
"""单次异步导出:提交任务 -> WS 收 --end-- -> 下载文件。"""
|
||||
_bind_session(session)
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
params = {k: str(v) for k, v in TRANSFER_QUERY_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = encode_common_query(_build_move_date_conditions(start, end))
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": TRANSFER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
ts = str(int(time.time() * 1000))
|
||||
params["_t"] = ts
|
||||
params["urlConditions"] = "#".join([
|
||||
f"_t:{ts}", "clickFlag:true", "treePermitType:permit",
|
||||
"useSealTreeData:0", "menuName:调动台账", f"_t:{ts}", ""])
|
||||
|
||||
resp = session.post(TRANSFER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(调动时间:%s ~ %s,模板:%s)", start, end, template_name)
|
||||
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
save_path = os.path.join(download_dir, "调动台账.xlsx")
|
||||
with open(save_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已保存导出文件:%s(%d 字节)", save_path, len(dl.content))
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_transfer_roster(download_dir: str = None, template_name: str = DEFAULT_TEMPLATE,
|
||||
output_path: str = None, start: str = None, end: str = None,
|
||||
session=None) -> str:
|
||||
"""执行调动台账自定义导出(调动已生效,调动时间近30天),返回导出 xlsx 文件路径。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_transfer_roster 一致。
|
||||
"""
|
||||
output_path = os.path.abspath(output_path or "调动台账.xlsx")
|
||||
download_dir = os.path.dirname(output_path)
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("===== 开始调动台账导出(模板:%s,日期:%s ~ %s),保存路径:%s =====",
|
||||
template_name, start, end, output_path)
|
||||
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
sess = _build_session(session)
|
||||
save_path = _export_once(sess, download_dir, template_name, start, end)
|
||||
if os.path.abspath(save_path) != output_path:
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
shutil.move(save_path, output_path)
|
||||
logger.info("===== 调动台账导出完成:%s =====", output_path)
|
||||
return output_path
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("调动台账导出第 %d 次失败:%s,%.1f 秒后重试", attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("调动台账导出连续 %d 次失败,放弃", MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 检查逻辑层:检查1~6(在职天数排班 / 出勤及排休 / 封存最新值 / 全勤验证 / 未封存 / 延时加班)。"""
|
||||
@@ -0,0 +1,451 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 检查2「出勤及排休天数验证」(由影刀版移植)。
|
||||
|
||||
根据排班方案关联的应勤天方案:
|
||||
实际出勤天不能超过应勤天;
|
||||
正休不能超过标准「当月天数-应勤天」。
|
||||
命中任一即输出异常名单。
|
||||
|
||||
数据来源:
|
||||
1) 考勤月报封存记录:由 seal_data_export.export_seal_data() 导出并预处理,本模块只读取;
|
||||
2) 排班数据:rf_p_kq_count_SelectBanci(不传工号 = 全集团批量),一个员工当月取出现最多的 team_name;
|
||||
3) 应勤天(三连接口):考勤方案列表 → 方案扩展表 ext_minyq_plan_id → 应勤天方案 month_XX;
|
||||
「排班方案 → 当月应勤天」映射做 1 天文件缓存;
|
||||
4) 技师(方案名含「技师岗」):固定按 8 天休息,不查询应勤天方案。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话/user_id 由底座 RunContext 注入(config 全局钩子),不自行构建;
|
||||
2. 登录态失效不再自动补登,抛错提示重新登录;
|
||||
3. 不单独落盘,仅返回异常名单行(单工作簿统一输出在 report 层)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from collections import Counter
|
||||
from datetime import date
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from ..config import (
|
||||
logger, require_session, require_user_id,
|
||||
HR_BASE_URL, PAGE_MAX_SIZE, CACHE_DIR, DEFAULT_SAVE_DIR,
|
||||
)
|
||||
from ..data.seal_data_export import (
|
||||
HRSessionExpiredError, hr_request_json,
|
||||
_clean, _num, _prev_month, _month_days, enrich_dept_fields, load_seal_rows,
|
||||
)
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
# 应勤天方案缓存:排班方案 → 当月应勤天 映射结果缓存 1 天(当天复用,次日失效重拉)。
|
||||
TEAM_PLAN_CACHE_DIR = CACHE_DIR
|
||||
|
||||
# 排班接口(一条记录 = 一个员工在查询范围内的全部排班,逐日带 {日期}_team_name)
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
SHIFT_SQL_ID = "kq_count_SelectBanci"
|
||||
|
||||
# 考勤方案列表接口(查询所有考勤方案,data.list 每条含 teamId/teamName)
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
TEAM_PAGE_SIZE = 50
|
||||
|
||||
# 方案查询接口(按 teamId 查扩展表,取 ext_minyq_plan_id)
|
||||
TEAM_EXTEND_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_extend_table_select/redApiExec.mc"
|
||||
|
||||
# 应勤天方案接口(按 teamId 查组织级全量方案,任意 teamId 返回一致,按 minyq_plan_id 过滤)
|
||||
TEAM_PLAN_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_minyq_plan_up_query_all/redApiExec.mc"
|
||||
|
||||
# 技师固定正休标准(排班方案名含「技师岗」,不查询应勤天方案,固定按 8 天休息)
|
||||
TECHNICIAN_KEYWORD = "技师岗"
|
||||
TECHNICIAN_REST_STANDARD = 8
|
||||
|
||||
# 异常类型(固定几种,便于筛选;详细说明一律放「异常明细」列)
|
||||
ABNORMAL_TYPE_OVER_WORK = "出勤天数超过应勤天"
|
||||
ABNORMAL_TYPE_OVER_REST = "正休天数超过标准"
|
||||
ABNORMAL_TYPE_NO_PLAN = "排班方案未匹配应勤天"
|
||||
|
||||
# 封存字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_ACTUAL_WORK_FIELD = "kq_stat_cal_ext19" # 实际出勤天日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # 休息天(正休)
|
||||
|
||||
# 输出列(对应需求文档异常名单字段,附 应勤天/实际出勤天/正休/标准 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"应勤天", "实际出勤天", "正休", "正休标准", "异常明细",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 考勤方案 → 应勤天接口(三连接口) ====================
|
||||
def fetch_team_page(session, page_no=1, page_size=TEAM_PAGE_SIZE):
|
||||
"""请求单页考勤方案列表。data.list 每条含 teamId/teamName 等。"""
|
||||
params = {
|
||||
"struTreeCode": "cq37du",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rule_name": "", "dk_num_type": "", "type": "", "containLower": "",
|
||||
"team_name": "", "work_date_name": "", "paiban_type": "",
|
||||
"IN_USE": "1", "start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc", "sortName": "t.operate_time",
|
||||
"pageNo": page_no, "pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", TEAM_LIST_URL, params, "考勤方案列表")
|
||||
|
||||
|
||||
def fetch_all_teams(session) -> List[dict]:
|
||||
"""分页抓取全部考勤方案(rf_p_kq_team_ajax_list,全集团 177 个)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_team_page(session, page_no)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("考勤方案列表:HR 登录态已失效,请重新登录 HR 后重试。")
|
||||
if data.get("code") != 200:
|
||||
logger.error("考勤方案第 %d 页请求失败:%s", page_no, data.get("message"))
|
||||
break
|
||||
body = data.get("data") or {}
|
||||
page_list = body.get("list") or []
|
||||
if not page_list:
|
||||
logger.info("考勤方案无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = body.get("pageCount") or 1
|
||||
logger.info("考勤方案已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_team_extend(session, team_id: str) -> str:
|
||||
"""按 teamId 查方案扩展表,返回 ext_minyq_plan_id(无则空串)。"""
|
||||
data = hr_request_json(session, "POST", TEAM_EXTEND_URL,
|
||||
{"team_id": team_id}, "方案查询")
|
||||
if data.get("code") != 200:
|
||||
return ""
|
||||
rows = data.get("data") or []
|
||||
if not rows:
|
||||
return ""
|
||||
return _clean(rows[0].get("ext_minyq_plan_id"))
|
||||
|
||||
|
||||
def fetch_team_plans(session, team_id: str) -> List[dict]:
|
||||
"""按 teamId 查应勤天方案(组织级全量方案,任意 teamId 返回一致)。"""
|
||||
data = hr_request_json(session, "POST", TEAM_PLAN_URL, {
|
||||
"rootId": "cq37du", "STRU_TREE_CODE": "cq37du",
|
||||
"teamId": team_id, "is_show_parent": "0",
|
||||
}, "应勤天方案")
|
||||
if data.get("code") != 200:
|
||||
return []
|
||||
return data.get("data") or []
|
||||
|
||||
|
||||
def build_team_plan_map(session, teams: List[dict], ym: str) -> Dict[str, dict]:
|
||||
"""全量缓存 考勤方案 → 当月应勤天(teamName → {yq_day, plan_code, plan_name})。"""
|
||||
if not teams:
|
||||
return {}
|
||||
# 1) 应勤天方案全量缓存(取前几个 team 直到拉到方案)
|
||||
plans: List[dict] = []
|
||||
for team in teams[:5]:
|
||||
plans = fetch_team_plans(session, _clean(team.get("teamId")))
|
||||
if plans:
|
||||
break
|
||||
if not plans:
|
||||
raise RuntimeError("未拉取到应勤天方案,请确认方案接口已配置。")
|
||||
plan_by_id = {_clean(p.get("minyq_plan_id")): p for p in plans
|
||||
if _clean(p.get("minyq_plan_id"))}
|
||||
logger.info("应勤天方案全量缓存:%d 个(%s)", len(plan_by_id), ym)
|
||||
month_key = f"month_{ym[5:7]:>02}"
|
||||
# 2) 逐个 team 查扩展表 → ext_minyq_plan_id → 当月应勤天
|
||||
team_map: Dict[str, dict] = {}
|
||||
miss_ext = miss_plan = 0
|
||||
for team in teams:
|
||||
team_id = _clean(team.get("teamId"))
|
||||
team_name = _clean(team.get("teamName"))
|
||||
if not team_id or not team_name:
|
||||
continue
|
||||
try:
|
||||
ext_plan_id = fetch_team_extend(session, team_id)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("方案查询:HR 登录态已失效,请重新登录 HR 后重试。")
|
||||
except Exception:
|
||||
logger.error("方案查询异常 teamId=%s,跳过", team_id)
|
||||
continue
|
||||
if not ext_plan_id:
|
||||
miss_ext += 1
|
||||
continue
|
||||
plan = plan_by_id.get(ext_plan_id)
|
||||
if not plan:
|
||||
miss_plan += 1
|
||||
continue
|
||||
yq_day = _num(plan.get(month_key))
|
||||
if yq_day <= 0:
|
||||
continue
|
||||
team_map[team_name] = {
|
||||
"yq_day": yq_day,
|
||||
"plan_code": _clean(plan.get("plan_code")),
|
||||
"plan_name": _clean(plan.get("plan_name")),
|
||||
"ext_minyq_plan_id": ext_plan_id,
|
||||
"team_id": team_id,
|
||||
}
|
||||
time.sleep(0.1)
|
||||
logger.info("考勤方案应勤天缓存完成:%d/%d 个 team(无方案 %d、方案未匹配 %d)",
|
||||
len(team_map), len(teams), miss_ext, miss_plan)
|
||||
return team_map
|
||||
|
||||
|
||||
# ==================== 应勤天方案 1 天文件缓存(当天复用,次日失效重拉) ====================
|
||||
def _team_plan_cache_path(ym: str) -> str:
|
||||
"""应勤天方案缓存文件路径(按检查月份区分,因应勤天随月份变化)。"""
|
||||
return os.path.join(TEAM_PLAN_CACHE_DIR, f"应勤天方案缓存_{ym}.json")
|
||||
|
||||
|
||||
def _load_team_plan_cache(cache_path: str, ym: str) -> Optional[Dict[str, dict]]:
|
||||
"""读取并校验应勤天方案缓存:仅「同月份且 cached_at 为今天」才复用。"""
|
||||
if not os.path.exists(cache_path):
|
||||
return None
|
||||
try:
|
||||
with open(cache_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except (OSError, ValueError) as e:
|
||||
logger.warning("应勤天方案缓存读取失败(%s),重新拉取", e)
|
||||
return None
|
||||
if data.get("month") != ym or data.get("cached_at") != date.today().isoformat():
|
||||
return None
|
||||
team_map = data.get("teams") or {}
|
||||
if not team_map:
|
||||
return None
|
||||
logger.info("命中应勤天方案缓存(%s 生成,当天有效):%d 个考勤方案",
|
||||
data["cached_at"], len(team_map))
|
||||
return team_map
|
||||
|
||||
|
||||
def _save_team_plan_cache(cache_path: str, ym: str, team_map: Dict[str, dict]) -> None:
|
||||
"""写入应勤天方案缓存(覆盖式,记录生成日期;写失败不影响本次检查)。"""
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
payload = {"month": ym, "cached_at": date.today().isoformat(), "teams": team_map}
|
||||
try:
|
||||
with open(cache_path, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, indent=2)
|
||||
logger.info("应勤天方案缓存已写入(%s):%s", ym, cache_path)
|
||||
except OSError as e:
|
||||
logger.warning("应勤天方案缓存写入失败(%s),不影响本次检查", e)
|
||||
|
||||
|
||||
def load_team_plan_cached(session, ym: str) -> Dict[str, dict]:
|
||||
"""取 排班方案 → 当月应勤天 映射(带 1 天文件缓存)。"""
|
||||
cache_path = _team_plan_cache_path(ym)
|
||||
cached = _load_team_plan_cache(cache_path, ym)
|
||||
if cached is not None:
|
||||
return cached
|
||||
teams = fetch_all_teams(session)
|
||||
if not teams:
|
||||
raise RuntimeError("未拉取到考勤方案列表,请确认方案接口已配置。")
|
||||
team_map = build_team_plan_map(session, teams, ym)
|
||||
_save_team_plan_cache(cache_path, ym, team_map)
|
||||
return team_map
|
||||
|
||||
|
||||
# ==================== 排班接口(rf_p_kq_count_SelectBanci,不传工号 = 全集团批量) ====================
|
||||
def fetch_shift_page(session, user_id, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页全集团排班数据(base_code 留空 = 不过滤,返回全部员工当月排班)。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": SHIFT_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, begin_date, end_date) -> List[dict]:
|
||||
"""分页抓取全集团当月排班数据(登录态失效抛错提示重新登录)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(session, user_id, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("排班数据:HR 登录态已失效,请重新登录 HR 后重试。")
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def _staff_main_team(row: dict) -> str:
|
||||
"""统计单条排班记录内逐日 {日期}_team_name 出现最多的值(换方案口径:取当月出现最多的)。"""
|
||||
counter: Counter = Counter()
|
||||
for key, val in row.items():
|
||||
if isinstance(key, str) and key.endswith("_team_name"):
|
||||
name = _clean(val)
|
||||
if name and name != "休息":
|
||||
counter[name] += 1
|
||||
if not counter:
|
||||
return ""
|
||||
return counter.most_common(1)[0][0]
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_abnormal(code: str, rec: dict, ym: str, abnormal_type: str,
|
||||
detail: str, extra: Dict[str, object]) -> dict:
|
||||
"""构造异常名单行(统一字段,部门由花名册回填)。"""
|
||||
row = {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": abnormal_type,
|
||||
"应勤天": extra.get("yq_day", ""),
|
||||
"实际出勤天": extra.get("actual_day", ""),
|
||||
"正休": extra.get("rest_day", ""),
|
||||
"正休标准": extra.get("rest_standard", ""),
|
||||
"异常明细": detail,
|
||||
}
|
||||
return enrich_dept_fields(row, code, rec)
|
||||
|
||||
|
||||
def run_attendance_rest_check(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""执行检查2「出勤及排休天数验证」,返回异常名单行列表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
save_dir: 输出目录(仅用于读取预处理封存表)。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
month_days = _month_days(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
month_days = _month_days(ym)
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
begin_date = f"{ym}-01"
|
||||
end_date = f"{ym}-{month_days:02d}"
|
||||
logger.info("===== 检查2「出勤及排休天数验证」月份:%s(%s ~ %s,自然天数 %d) =====",
|
||||
ym, begin_date, end_date, month_days)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym, save_dir)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map: Dict[str, dict] = {}
|
||||
for rec in seal_rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
seal_map.setdefault(code, rec)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
# 2. 拉取全部考勤方案 → 应勤天(三连接口,映射结果带 1 天文件缓存)
|
||||
session = require_session()
|
||||
user_id = require_user_id()
|
||||
if not user_id:
|
||||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||||
team_plan = load_team_plan_cached(session, ym)
|
||||
|
||||
# 3. 拉取全集团排班 → 工号 → 当月出现最多的 team_name
|
||||
shift_rows = fetch_all_shift(session, user_id, begin_date, end_date)
|
||||
staff_team: Dict[str, str] = {}
|
||||
no_team_cnt = 0
|
||||
for row in shift_rows:
|
||||
code = _clean(row.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
team = _staff_main_team(row)
|
||||
if not team:
|
||||
no_team_cnt += 1
|
||||
continue
|
||||
staff_team[code] = team
|
||||
logger.info("排班加载完成:%d 人带方案,%d 人无方案(跳过)", len(staff_team), no_team_cnt)
|
||||
|
||||
# 4. 逐人校验:技师固定正休≤8天;其余 实际出勤天≤应勤天、正休≤当月天数-应勤天
|
||||
abnormal: List[dict] = []
|
||||
no_plan_match = 0
|
||||
tech_cnt = 0
|
||||
for code, rec in seal_map.items():
|
||||
team = staff_team.get(code)
|
||||
if not team:
|
||||
continue # 排班无方案(无排班/全休息),跳过不误报
|
||||
actual_day = _num(rec.get(SEAL_ACTUAL_WORK_FIELD))
|
||||
rest_day = _num(rec.get(SEAL_REST_FIELD))
|
||||
# 技师:固定按 8 天休息,只查正休
|
||||
if TECHNICIAN_KEYWORD in team:
|
||||
tech_cnt += 1
|
||||
if rest_day > TECHNICIAN_REST_STANDARD:
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_OVER_REST,
|
||||
f"技师排班方案「{team}」,固定正休{TECHNICIAN_REST_STANDARD}天,"
|
||||
f"实际正休{rest_day:g}天,超出{rest_day - TECHNICIAN_REST_STANDARD:g}天",
|
||||
{"yq_day": "", "actual_day": actual_day,
|
||||
"rest_day": rest_day, "rest_standard": TECHNICIAN_REST_STANDARD}))
|
||||
continue
|
||||
info = team_plan.get(team)
|
||||
if not info:
|
||||
no_plan_match += 1
|
||||
logger.warning("工号 %s 排班方案「%s」未匹配到应勤天方案,输出异常", code, team)
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_NO_PLAN,
|
||||
f"排班方案「{team}」未匹配到应勤天方案,请核对",
|
||||
{"yq_day": "", "actual_day": actual_day,
|
||||
"rest_day": rest_day, "rest_standard": ""}))
|
||||
continue
|
||||
yq_day = info["yq_day"]
|
||||
rest_standard = month_days - yq_day
|
||||
plan_desc = f"{info['plan_code']} {info['plan_name']}(方案「{team}」)"
|
||||
if actual_day > yq_day:
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_OVER_WORK,
|
||||
f"排班方案{plan_desc},应勤天{yq_day:g},实际出勤{actual_day:g},超出{actual_day - yq_day:g}天",
|
||||
{"yq_day": yq_day, "actual_day": actual_day,
|
||||
"rest_day": rest_day, "rest_standard": rest_standard}))
|
||||
if rest_day > rest_standard:
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_OVER_REST,
|
||||
f"排班方案{plan_desc},正休{rest_day:g}天超过标准{rest_standard:g}天"
|
||||
f"(当月{month_days}天-应勤{yq_day:g}天),超出{rest_day - rest_standard:g}天",
|
||||
{"yq_day": yq_day, "actual_day": actual_day,
|
||||
"rest_day": rest_day, "rest_standard": rest_standard}))
|
||||
logger.info("检查2 校验完成:异常 %d 条,技师 %d 人,方案未匹配异常 %d 人",
|
||||
len(abnormal), tech_cnt, no_plan_match)
|
||||
return abnormal
|
||||
@@ -0,0 +1,217 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 检查4「全勤验证」(由影刀版 full_attendance_check.py 移植)。
|
||||
|
||||
月中晋升职能或管理岗,或存在迟到早退异常仍被标记全勤的,输出异常名单。
|
||||
|
||||
判定口径(对应需求文档检查4 规则A/B):
|
||||
规则A「月中途晋升,不享受全勤」:
|
||||
调动台账月中途(检查月内)从 门店服务序列/门店技师序列 调动到
|
||||
职能系专业序列/职能系管理序列/经营系管理序列 的,且封存「是否全勤」=1 → 异常;
|
||||
规则B「存在考勤异常,不享受全勤」:
|
||||
封存存在迟到或早退异常次数(迟到次数+早退次数>0)、且「是否全勤」=1 → 异常。
|
||||
|
||||
数据来源:
|
||||
1) 考勤封存记录:由 seal_data_export.export_seal_data() 导出并预处理,本模块只读取;
|
||||
2) 调动台账:由 transfer_roster_export_api.export_transfer_roster() 导出(表头在第 2 行 header=1)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话由底座注入(本模块只读本地文件,不直接请求 HR 接口);
|
||||
2. transfer_path 由 run() 解析注入,可显式指定;不单独落盘,仅返回异常名单行。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import logger, DEFAULT_SAVE_DIR
|
||||
from ..data.seal_data_export import enrich_dept_fields, load_seal_rows, _clean, _num, _parse_date
|
||||
|
||||
|
||||
def _default_transfer(save_dir: str) -> str:
|
||||
return os.path.join(save_dir, "调动台账.xlsx")
|
||||
|
||||
|
||||
# 异常类型(对应需求文档检查4 规则A/B)
|
||||
ABNORMAL_TYPE_PROMOTION = "月中途晋升,不享受全勤"
|
||||
ABNORMAL_TYPE_LATE_EARLY = "存在考勤异常,不享受全勤"
|
||||
|
||||
# 调动识别:原职位序列命中「门店系」(晋升起点)
|
||||
PRE_SEQ_KEYWORDS = ("门店服务序列", "门店技师序列")
|
||||
# 现职位序列命中「职能/经营系管理、专业」(晋升终点)
|
||||
NOW_SEQ_KEYWORDS = ("职能系专业序列", "职能系管理序列", "经营系管理序列")
|
||||
|
||||
# 封存记录工号字段 & 是否全勤 / 迟到 / 早退字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_FULL_ATT_FIELD = "kq_stat_cal_ext43" # 是否全勤
|
||||
SEAL_LATE_FIELDS = ("kq_stat_cal_ext60", "kq_stat_cal_ext61", "kq_stat_cal_ext62")
|
||||
SEAL_EARLY_FIELDS = ("kq_stat_cal_ext51", "kq_stat_cal_ext52", "kq_stat_cal_ext53")
|
||||
|
||||
# 调动台账列(与「排班异常识别导出」模板导出的列名一致)
|
||||
TRANSFER_CODE_COL = "工号"
|
||||
TRANSFER_DATE_COL = "调动时间"
|
||||
TRANSFER_PRE_SEQ_COL = "原职位序列"
|
||||
TRANSFER_NOW_SEQ_COL = "现职位序列"
|
||||
|
||||
# 输出列(对应需求文档检查4输出字段,附 异常明细 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"异常明细",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
if m == 2:
|
||||
import calendar
|
||||
total_days = calendar.monthrange(y, m)[1]
|
||||
else:
|
||||
total_days = 31 if m in (1, 3, 5, 7, 8, 10, 12) else 30
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _hit_keywords(value: str, keywords: Tuple[str, ...]) -> bool:
|
||||
"""字段值是否命中任一关键词(子串匹配)。"""
|
||||
return any(key in value for key in keywords)
|
||||
|
||||
|
||||
# ==================== 调动台账读取 ====================
|
||||
def _load_transfer_rows(transfer_path: str) -> List[dict]:
|
||||
"""读取调动台账(表头在第 2 行 header=1),返回记录行列表。"""
|
||||
if not os.path.exists(transfer_path):
|
||||
raise RuntimeError(
|
||||
f"未找到调动台账文件:{transfer_path}\n"
|
||||
"请先运行插件(调动台账导出步骤,模板=排班异常识别导出)导出调动台账;"
|
||||
"或通过 transfer_path 字段指定已有调动台账文件。")
|
||||
df = pd.read_excel(transfer_path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
for col in (TRANSFER_CODE_COL, TRANSFER_DATE_COL,
|
||||
TRANSFER_PRE_SEQ_COL, TRANSFER_NOW_SEQ_COL):
|
||||
if col not in df.columns:
|
||||
raise RuntimeError(
|
||||
f"调动台账缺少「{col}」列:{transfer_path}\n"
|
||||
"请使用模板「排班异常识别导出」导出。")
|
||||
rows = [dict(r) for r in df.to_dict(orient="records")]
|
||||
logger.info("已读取调动台账:%s,共 %d 行", transfer_path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 封存数据索引 ====================
|
||||
def _build_seal_map(rows: List[dict]) -> Dict[str, dict]:
|
||||
"""按工号建立 封存记录索引(一员工一条)。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
mapping.setdefault(code, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _count_abnormal(rec: dict, fields: Tuple[str, ...]) -> float:
|
||||
"""统计迟到/早退次数合计。"""
|
||||
return sum(_num(rec.get(f)) for f in fields)
|
||||
|
||||
|
||||
def _build_abnormal(code: str, rec: dict, ym: str, abnormal_type: str, detail: str) -> dict:
|
||||
"""构造异常名单行(统一字段,部门由花名册回填)。"""
|
||||
row = {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": abnormal_type,
|
||||
"异常明细": detail,
|
||||
}
|
||||
return enrich_dept_fields(row, code, rec)
|
||||
|
||||
|
||||
def run_full_attendance_check(month: str = None, save_dir: str = None,
|
||||
transfer_path: str = None) -> List[dict]:
|
||||
"""执行检查4「全勤验证」,返回异常名单行列表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
save_dir: 输出目录(默认路径下读取封存表与调动台账)。
|
||||
transfer_path: 调动台账文件路径,默认 save_dir/调动台账.xlsx。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
transfer_path = transfer_path or _default_transfer(save_dir)
|
||||
logger.info("===== 检查4「全勤验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读取预处理封存表(已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym, save_dir)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map = _build_seal_map(seal_rows)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
# 2. 读取调动台账
|
||||
transfer_rows = _load_transfer_rows(transfer_path)
|
||||
|
||||
# 3. 规则A:月中途晋升(门店系 → 职能/经营系),且全勤=1
|
||||
abnormal: List[dict] = []
|
||||
promotion_cnt = 0
|
||||
for row in transfer_rows:
|
||||
code = _clean(row.get(TRANSFER_CODE_COL))
|
||||
move_day = _parse_date(row.get(TRANSFER_DATE_COL))
|
||||
if not code or not move_day:
|
||||
continue
|
||||
if not (first <= move_day <= last):
|
||||
continue # 非检查月内的调动,跳过
|
||||
pre_seq = _clean(row.get(TRANSFER_PRE_SEQ_COL))
|
||||
now_seq = _clean(row.get(TRANSFER_NOW_SEQ_COL))
|
||||
if not _hit_keywords(pre_seq, PRE_SEQ_KEYWORDS):
|
||||
continue # 晋升起点非门店服务/技师序列
|
||||
if not _hit_keywords(now_seq, NOW_SEQ_KEYWORDS):
|
||||
continue # 晋升终点非职能/经营系管理、专业序列
|
||||
rec = seal_map.get(code)
|
||||
if not rec:
|
||||
continue # 无封存记录(未封存场景由检查5负责),跳过
|
||||
if _num(rec.get(SEAL_FULL_ATT_FIELD)) != 1:
|
||||
continue # 非全勤,正常
|
||||
promotion_cnt += 1
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_PROMOTION,
|
||||
f"调动时间{move_day},原职位序列:{pre_seq},现职位序列:{now_seq}"))
|
||||
logger.info("检查4 规则A 命中异常 %d 人(月中途晋升且全勤=1)", promotion_cnt)
|
||||
|
||||
# 4. 规则B:存在迟到/早退异常次数,且全勤=1
|
||||
late_early_cnt = 0
|
||||
for code, rec in seal_map.items():
|
||||
if _num(rec.get(SEAL_FULL_ATT_FIELD)) != 1:
|
||||
continue # 非全勤,正常
|
||||
late = _count_abnormal(rec, SEAL_LATE_FIELDS)
|
||||
early = _count_abnormal(rec, SEAL_EARLY_FIELDS)
|
||||
if late + early == 0:
|
||||
continue # 无迟到早退,正常
|
||||
late_early_cnt += 1
|
||||
abnormal.append(_build_abnormal(
|
||||
code, rec, ym, ABNORMAL_TYPE_LATE_EARLY,
|
||||
f"迟到次数合计{late:g},早退次数合计{early:g}"))
|
||||
logger.info("检查4 规则B 命中异常 %d 人(有迟到早退且全勤=1)", late_early_cnt)
|
||||
return abnormal
|
||||
@@ -0,0 +1,264 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 检查3「封存值是否为最新值」(由影刀版移植)。
|
||||
|
||||
考勤月报封存页面「对比」检索对比差异值是否全部为空,若有异常值则输出异常名单。
|
||||
|
||||
判定口径:
|
||||
对比「考勤封存值」与「实时统计值」两套数据的考勤指标字段,逐字段比较数值;
|
||||
任一字段存在差异(非空差异)→ 异常,异常类型「考勤封存非最新值,请重新封存」。
|
||||
|
||||
数据来源:
|
||||
1) 封存值:由 seal_data_export.export_seal_data() 导出并预处理,本模块只读取;
|
||||
2) 实时值:StatV2 接口,staff_ids 留空 = 全集团批量实时统计,按所属单位白名单筛选后比对。
|
||||
两接口返回均为 kq_stat_* 系列字段,同一员工以 staff_id(辅以工号)匹配。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话/user_id 由底座 RunContext 注入(config 全局钩子),不自行构建;
|
||||
2. 登录态失效不再自动补登,抛错提示重新登录;
|
||||
3. 不单独落盘,仅返回异常名单行。
|
||||
"""
|
||||
import time
|
||||
from datetime import date
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from ..config import logger, require_session, require_user_id, DEFAULT_SAVE_DIR
|
||||
from ..data.seal_data_export import (
|
||||
hr_request_json, enrich_dept_fields, load_seal_rows,
|
||||
SEAL_UNIT_WHITELIST, _clean,
|
||||
)
|
||||
|
||||
# 实时统计接口(对比右侧):不传 staff_ids = 全集团批量实时统计
|
||||
STAT_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/kq_count_leave_StatV2/CoreRequest.mc"
|
||||
STAT_PAGE_SIZE = 500
|
||||
|
||||
# 异常类型(对应需求文档检查3)
|
||||
ABNORMAL_TYPE = "考勤封存非最新值,请重新封存"
|
||||
|
||||
# 封存记录主键字段(实时侧同名匹配)
|
||||
SEAL_STAFF_ID_FIELD = "staff_id"
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 页面「对比」展示字段:中文标签 → 接口字段(来源:aa.md 封存页列定义 / CN_FIELD_MAP)
|
||||
COMPARE_FIELDS: List[Tuple[str, str]] = [
|
||||
("实际出勤天日", "kq_stat_cal_ext19"),
|
||||
("_在职应勤工作日", "kq_stat_month_yq_work_day_in"),
|
||||
("休息天", "kq_stat_cal_ext9"),
|
||||
("旷工天数", "kq_stat_cal_ext39"),
|
||||
("漏打卡次数", "kq_stat_cal_ext8"),
|
||||
("_特别福利假天", "kq_stat_leave_day_num23"),
|
||||
("_年度福利假天", "kq_stat_leave_day_num24"),
|
||||
("年假天", "kq_stat_leave_day_num1"),
|
||||
("_病假天", "kq_stat_leave_day_num4"),
|
||||
("_产假天", "kq_stat_leave_day_num5"),
|
||||
("_事假天", "kq_stat_leave_day_num9"),
|
||||
("_普通事假天", "kq_stat_leave_day_num16"),
|
||||
("_特殊事假天", "kq_stat_leave_day_num17"),
|
||||
("_小时特假小时", "kq_stat_leave_hour_num18"),
|
||||
("_普通事假(晚/高峰)天", "kq_stat_leave_day_num19"),
|
||||
("_普通事假(早/中)天", "kq_stat_leave_day_num20"),
|
||||
("_工作日加班转补贴小时", "kq_stat_ps_bt_hour"),
|
||||
("法定节假日加班转补贴天", "kq_stat_cal_ext69"),
|
||||
("休息日加班转补贴天", "kq_stat_cal_ext44"),
|
||||
("当月未休调休天", "kq_stat_cal_ext63"),
|
||||
("迟到30分钟内次数", "kq_stat_cal_ext60"),
|
||||
("迟到30到60分钟内次数", "kq_stat_cal_ext61"),
|
||||
("迟到60到120分钟内次数", "kq_stat_cal_ext62"),
|
||||
("早退30分钟内次数", "kq_stat_cal_ext51"),
|
||||
("早退30到60分钟内次数", "kq_stat_cal_ext52"),
|
||||
("早退60到120分钟内次数", "kq_stat_cal_ext53"),
|
||||
("连班次数", "kq_stat_cal_ext40"),
|
||||
("是否未休小时特假", "kq_stat_cal_ext42"),
|
||||
("是否全勤", "kq_stat_cal_ext43"),
|
||||
]
|
||||
|
||||
# 输出列(对应需求文档检查3输出字段,附 异常明细 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"异常明细",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _num(v) -> float:
|
||||
"""数值归一化:空/None → 0.0;数值字符串 → float。"""
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return 0.0
|
||||
try:
|
||||
return float(s)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _num_eq(a, b) -> bool:
|
||||
"""两字段值是否相等(数值口径:空/None 视为 0,浮点容差)。"""
|
||||
return abs(_num(a) - _num(b)) < 1e-9
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
if m == 2:
|
||||
import calendar
|
||||
total_days = calendar.monthrange(y, m)[1]
|
||||
else:
|
||||
total_days = 31 if m in (1, 3, 5, 7, 8, 10, 12) else 30
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
# ==================== 实时统计值拉取(StatV2,全集团批量分页) ====================
|
||||
def fetch_stat_all(session, user_id: str, ym: str, begin: date, end: date) -> List[dict]:
|
||||
"""分页拉取某月实时统计值(StatV2,staff_ids 留空 = 全集团批量)。
|
||||
|
||||
返回所有未白名单过滤的实时统计记录行(按所属单位白名单在调用方筛选)。
|
||||
"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
params = {
|
||||
"user_id": user_id,
|
||||
"treecode": "cq37du",
|
||||
"begin": begin.isoformat(),
|
||||
"end": end.isoformat(),
|
||||
"staff_ids": "",
|
||||
"type": "1",
|
||||
"start": str((page_no - 1) * STAT_PAGE_SIZE),
|
||||
"pageSize": str(STAT_PAGE_SIZE),
|
||||
"start_Time": ym,
|
||||
}
|
||||
data = hr_request_json(session, "POST", STAT_URL, params, "实时统计(StatV2)")
|
||||
if data.get("state") != "1":
|
||||
logger.error("实时统计第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("实时统计无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("实时统计已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def _build_stat_map(stat_rows: List[dict]) -> Dict[str, dict]:
|
||||
"""实时统计记录索引:优先 staff_id,缺失时用工号归一化兜底。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in stat_rows:
|
||||
key = _clean(rec.get("staff_id"))
|
||||
if not key:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
key = _clean(rec.get(f))
|
||||
if key:
|
||||
break
|
||||
if key:
|
||||
mapping.setdefault(key, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
def _record_key(rec: dict) -> str:
|
||||
"""封存记录主键(staff_id 优先,工号兜底,与实时索引同口径)。"""
|
||||
key = _clean(rec.get(SEAL_STAFF_ID_FIELD))
|
||||
if not key:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
key = _clean(rec.get(f))
|
||||
if key:
|
||||
break
|
||||
return key
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _compare_fields(seal_rec: dict, stat_rec: dict) -> List[str]:
|
||||
"""逐字段对比封存值与实时值,返回差异明细(空列表 = 全部一致)。"""
|
||||
diffs: List[str] = []
|
||||
for label, field in COMPARE_FIELDS:
|
||||
v_seal = seal_rec.get(field)
|
||||
v_stat = stat_rec.get(field) if stat_rec else None
|
||||
if _num_eq(v_seal, v_stat):
|
||||
continue
|
||||
diffs.append(f"{label}[{field}]:封存{_clean(v_seal) or 0} → 实时{_clean(v_stat) or 0}")
|
||||
return diffs
|
||||
|
||||
|
||||
def _build_abnormal(rec: dict, ym: str, detail: str) -> dict:
|
||||
"""构造异常名单行(37工号取封存记录工号,部门由花名册回填)。"""
|
||||
code = _clean(rec.get("base_code")) or _clean(rec.get("seal_base_code"))
|
||||
row = {
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"异常明细": detail,
|
||||
}
|
||||
return enrich_dept_fields(row, code, rec)
|
||||
|
||||
|
||||
def run_latest_seal_check(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""执行检查3「封存值是否为最新值」,返回异常名单行列表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
save_dir: 输出目录(仅用于读取预处理封存表)。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
begin, end = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
begin, end = _month_range(ym)
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
logger.info("===== 检查3「封存值是否为最新值」月份:%s(%s ~ %s) =====", ym, begin, end)
|
||||
|
||||
# 1. 读取预处理封存表(封存值,已按所属单位白名单筛选)
|
||||
seal_rows = load_seal_rows(ym, save_dir)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
logger.info("封存值加载完成,共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 拉取当月实时统计值(StatV2 全集团批量)→ 白名单筛选 → 按员工建立索引
|
||||
session = require_session()
|
||||
user_id = require_user_id()
|
||||
stat_all = fetch_stat_all(session, user_id, ym, begin, end)
|
||||
stat_whitelist = [r for r in stat_all
|
||||
if _clean(r.get("BELONG_UNIT_ORG_NAME")) in SEAL_UNIT_WHITELIST]
|
||||
stat_map = _build_stat_map(stat_whitelist)
|
||||
logger.info("实时统计全集团 %d 人 → 白名单单位 %d 人", len(stat_all), len(stat_whitelist))
|
||||
|
||||
# 3. 逐员工对比 封存值 vs 实时值,有差异 → 异常
|
||||
abnormal: List[dict] = []
|
||||
diff_cnt = miss_cnt = 0
|
||||
for rec in seal_rows:
|
||||
code = _record_key(rec)
|
||||
if not code:
|
||||
continue
|
||||
stat_rec = stat_map.get(code)
|
||||
if stat_rec is None:
|
||||
# 实时统计记录缺失:对比差异非空,视为封存非最新值
|
||||
miss_cnt += 1
|
||||
abnormal.append(_build_abnormal(rec, ym, "实时统计记录缺失,无法确认封存为最新值"))
|
||||
continue
|
||||
diffs = _compare_fields(rec, stat_rec)
|
||||
if not diffs:
|
||||
continue
|
||||
diff_cnt += 1
|
||||
abnormal.append(_build_abnormal(rec, ym, ";".join(diffs)))
|
||||
logger.info("检查3 命中异常 %d 人(差异字段 %d 人 + 实时记录缺失 %d 人)",
|
||||
len(abnormal), diff_cnt, miss_cnt)
|
||||
return abnormal
|
||||
@@ -0,0 +1,164 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 检查6「延时加班验证」(由影刀版移植)。
|
||||
|
||||
经营系管理岗不享受延时加班:识别职位序列为「经营系管理序列」的员工,若考勤封存页面
|
||||
字段「_工作日加班转补贴小时」(kq_stat_ps_bt_hour)为非零值,则输出异常名单。
|
||||
|
||||
判定口径:
|
||||
- 逐条封存记录,按工号从花名册取职位序列;
|
||||
- 职位序列命中「经营系管理序列」且「_工作日加班转补贴小时」非零(>0)→ 异常;
|
||||
- 花名册查不到职位序列的员工跳过(无法判断序列,不误报)。
|
||||
|
||||
数据来源:
|
||||
1) 考勤封存记录:由 seal_data_export.export_seal_data() 导出并预处理,本模块只读取;
|
||||
2) 职位序列:花名册「员工基础信息」模板导出(含「职位序列」列),roster_path 由 run() 注入。
|
||||
|
||||
插件化改造点:
|
||||
1. 花名册由 run() 自动导出(TTL 缓存复用),roster_path 可显式指定;
|
||||
2. 不单独落盘,仅返回异常名单行。
|
||||
"""
|
||||
import os
|
||||
from datetime import date
|
||||
from typing import Dict, List, Set, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import logger, DEFAULT_SAVE_DIR
|
||||
from ..data.seal_data_export import enrich_dept_fields, load_seal_rows, _clean, _num
|
||||
|
||||
|
||||
def _default_roster(save_dir: str) -> str:
|
||||
return os.path.join(save_dir, "员工花名册.xlsx")
|
||||
|
||||
|
||||
# 异常类型(对应需求文档检查6)
|
||||
ABNORMAL_TYPE = "经营系管理岗不应享受延时加班,请核对"
|
||||
|
||||
# 命中职位序列(经营系管理序列不享受延时加班)
|
||||
TARGET_SEQUENCES: Tuple[str, ...] = ("经营系管理序列",)
|
||||
|
||||
# 封存记录工号字段 & 加班转补贴小时字段(_工作日加班转补贴小时)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_OT_HOUR_FIELD = "kq_stat_ps_bt_hour"
|
||||
|
||||
# 花名册字段(「员工基础信息」模板导出的列名)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_SEQ_COL = "职位序列"
|
||||
|
||||
# 输出列(对应需求文档检查6输出字段,附 延时加班补贴小时 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"延时加班补贴小时",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _seal_code_set(rows: List[dict]) -> Set[str]:
|
||||
"""取当月封存记录的全部工号集合。"""
|
||||
codes: Set[str] = set()
|
||||
for rec in rows:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
codes.add(code)
|
||||
break
|
||||
return codes
|
||||
|
||||
|
||||
# ==================== 花名册职位序列读取 ====================
|
||||
def _load_roster_seq_map(roster_path: str) -> Dict[str, str]:
|
||||
"""读取花名册,建立 工号→职位序列 映射(同一工号多行取第一个非空序列)。"""
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先运行插件(花名册导出步骤,模板=员工基础信息,需包含「职位序列」列)导出花名册;"
|
||||
"或通过 roster_path 字段指定已有花名册文件。")
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
if ROSTER_SEQ_COL not in df.columns:
|
||||
raise RuntimeError(
|
||||
f"花名册缺少「{ROSTER_SEQ_COL}」列:{roster_path}\n"
|
||||
"请使用模板「员工基础信息」导出(含职位序列列)。")
|
||||
seq_map: Dict[str, str] = {}
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code or code in seq_map:
|
||||
continue
|
||||
seq_map[code] = _clean(row.get(ROSTER_SEQ_COL))
|
||||
logger.info("已读取花名册职位序列:%s,共 %d 人", roster_path, len(seq_map))
|
||||
return seq_map
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _is_target_sequence(seq: str) -> bool:
|
||||
"""职位序列是否命中目标序列(经营系管理序列)。"""
|
||||
return any(key in seq for key in TARGET_SEQUENCES)
|
||||
|
||||
|
||||
def run_overtime_compensation_check(month: str = None, save_dir: str = None,
|
||||
roster_path: str = None) -> List[dict]:
|
||||
"""执行检查6「延时加班验证」,返回异常名单行列表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
save_dir: 输出目录(默认路径下读取封存表与花名册)。
|
||||
roster_path: 花名册文件路径,默认 save_dir/员工花名册.xlsx。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
roster_path = roster_path or _default_roster(save_dir)
|
||||
logger.info("===== 检查6「延时加班验证」月份:%s =====", ym)
|
||||
|
||||
# 1. 读取预处理封存表(已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym, save_dir)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 读取花名册职位序列映射(工号→职位序列)
|
||||
seq_map = _load_roster_seq_map(roster_path)
|
||||
|
||||
# 3. 逐人检查:经营系管理序列 且 延时加班补贴小时非零
|
||||
abnormal: List[dict] = []
|
||||
no_seq_cnt = 0
|
||||
for rec in seal_rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if not code:
|
||||
continue
|
||||
seq = seq_map.get(code, "")
|
||||
if not seq:
|
||||
no_seq_cnt += 1
|
||||
continue # 花名册查不到职位序列,无法判断序列,不误报
|
||||
if not _is_target_sequence(seq):
|
||||
continue # 非经营系管理序列,正常
|
||||
ot_hour = _num(rec.get(SEAL_OT_HOUR_FIELD))
|
||||
if ot_hour == 0:
|
||||
continue # 无延时加班补贴小时,正常
|
||||
abnormal.append(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"延时加班补贴小时": ot_hour,
|
||||
}, code, rec, roster_path))
|
||||
logger.info("检查6命中异常 %d 人(经营系管理岗有延时加班补贴);花名册无职位序列跳过 %d 人",
|
||||
len(abnormal), no_seq_cnt)
|
||||
return abnormal
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 检查5「未封存名单」(由影刀版移植)。
|
||||
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有
|
||||
考勤月报封存记录;有在职记录但无封存记录者输出异常名单。
|
||||
|
||||
判定口径:
|
||||
- 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」:
|
||||
在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。
|
||||
- 仅统计所属单位在白名单内的员工;
|
||||
- 有在职记录但工号不在当月封存记录集合里 → 异常。
|
||||
|
||||
数据来源:
|
||||
1) 在职记录(花名册):由 roster_export_api.export_roster() 导出(模板=员工基础信息);
|
||||
2) 考勤封存记录:由 seal_data_export.export_seal_data() 导出并预处理,本模块只读取。
|
||||
|
||||
插件化改造点:
|
||||
1. 花名册由 run() 自动导出(TTL 缓存复用),roster_path 可显式指定;
|
||||
2. 不单独落盘,仅返回异常名单行。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional, Set, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import logger, DEFAULT_SAVE_DIR, get_roster_path
|
||||
from ..data.seal_data_export import (
|
||||
SEAL_UNIT_WHITELIST, enrich_dept_fields, load_excluded_codes, load_seal_rows,
|
||||
_clean, _parse_date,
|
||||
)
|
||||
|
||||
|
||||
def _default_roster(save_dir: str) -> str:
|
||||
return os.path.join(save_dir, "员工花名册.xlsx")
|
||||
|
||||
|
||||
# 异常类型(对应需求文档检查5)
|
||||
ABNORMAL_TYPE = "考勤月报未封存,请处理"
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 花名册字段(与「员工基础信息」模板导出的列名一致)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_JOIN_COL = "入职时间"
|
||||
ROSTER_LEAVE_COL = "离职时间"
|
||||
|
||||
# 输出列(对应需求文档检查5输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
if m == 2:
|
||||
import calendar
|
||||
total_days = calendar.monthrange(y, m)[1]
|
||||
else:
|
||||
total_days = 31 if m in (1, 3, 5, 7, 8, 10, 12) else 30
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _seal_code_set(rows: List[dict]) -> Set[str]:
|
||||
"""取当月封存记录的全部工号集合。"""
|
||||
codes: Set[str] = set()
|
||||
for rec in rows:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
codes.add(code)
|
||||
break
|
||||
return codes
|
||||
|
||||
|
||||
# ==================== 花名册在职判定 ====================
|
||||
def _load_roster(roster_path: str) -> "pd.DataFrame":
|
||||
"""读取花名册(「员工基础信息」模板导出,表头在第 1 行)。"""
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先运行插件(花名册导出步骤,模板=员工基础信息,在职状态=在职+离职)导出花名册;"
|
||||
"或通过 roster_path 字段指定已有花名册文件。")
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _in_month(join: Optional[date], leave: Optional[date], first: date, last: date) -> bool:
|
||||
"""判断员工检查月是否在职:入职 ≤ 月末 且(未离职 或 离职 ≥ 月初)。"""
|
||||
if join is None or join > last:
|
||||
return False
|
||||
if leave is None or leave >= first:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_unsealed_rows(df, seal_codes: Set[str], ym: str, first: date, last: date,
|
||||
roster_path: str = None) -> List[dict]:
|
||||
"""遍历花名册,找出检查月在职、所属单位在白名单内但无封存记录的员工,返回名单行列表。
|
||||
|
||||
与封存预处理口径一致:一级部门 = 职业技术培训学校 的员工不参与本检查,直接剔除。
|
||||
"""
|
||||
abnormal: List[dict] = []
|
||||
seen: Set[str] = set()
|
||||
excluded = load_excluded_codes(roster_path)
|
||||
excluded_n = 0
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code or code in seen:
|
||||
continue # 花名册在职/离职同一工号可能多行,取一行即可
|
||||
seen.add(code)
|
||||
unit = _clean(row.get(ROSTER_UNIT_COL))
|
||||
if unit not in SEAL_UNIT_WHITELIST:
|
||||
continue # 与封存表预处理口径一致:仅检查白名单单位员工
|
||||
if code in excluded:
|
||||
excluded_n += 1
|
||||
continue # 一级部门 = 职业技术培训学校,不参与本检查
|
||||
join = _parse_date(row.get(ROSTER_JOIN_COL))
|
||||
leave = _parse_date(row.get(ROSTER_LEAVE_COL))
|
||||
if not _in_month(join, leave, first, last):
|
||||
continue # 检查月不在职(尚未入职或已离职早于月初)
|
||||
if code in seal_codes:
|
||||
continue # 已有封存记录,正常
|
||||
abnormal.append(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _clean(row.get(ROSTER_NAME_COL)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
}, code, None, roster_path))
|
||||
if excluded_n:
|
||||
logger.info("检查5 剔除「职业技术培训学校」%d 人", excluded_n)
|
||||
return abnormal
|
||||
|
||||
|
||||
def run_unsealed_check(month: str = None, save_dir: str = None,
|
||||
roster_path: str = None) -> List[dict]:
|
||||
"""执行检查5「未封存名单」,返回异常名单行列表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
save_dir: 输出目录(默认路径下读取封存表与花名册)。
|
||||
roster_path: 花名册文件路径,默认 save_dir/员工花名册.xlsx。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
roster_path = roster_path or _default_roster(save_dir)
|
||||
logger.info("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读花名册(在职记录)
|
||||
df = _load_roster(roster_path)
|
||||
|
||||
# 2. 读取预处理封存表(已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym, save_dir)
|
||||
seal_codes = _seal_code_set(seal_rows)
|
||||
logger.info("考勤封存记录共 %d 人:%s", len(seal_codes), ym)
|
||||
|
||||
# 3. 找出在册未封存
|
||||
abnormal = _build_unsealed_rows(df, seal_codes, ym, first, last, roster_path)
|
||||
logger.info("检查5命中异常 %d 人(在册未封存)", len(abnormal))
|
||||
return abnormal
|
||||
@@ -0,0 +1,111 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 检查1「在职天数是否均排班验证」(由影刀版移植)。
|
||||
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
|
||||
在职天数 = 月初1日~末日 与 入职日起~离职日止 闭区间交集的自然天数(含首尾);
|
||||
差值 = 在职天数 - (在职应勤工作日 + 休息天);差值非 0 视为异常。
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from ..config import logger, DEFAULT_SAVE_DIR
|
||||
from ..data.seal_data_export import (
|
||||
enrich_dept_fields, load_seal_rows,
|
||||
_clean, _num, _text, _parse_date, _prev_month, _month_range,
|
||||
)
|
||||
|
||||
# 异常类型(对应需求文档检查1)
|
||||
ABNORMAL_TYPE = "当月在职天数有差缺排班"
|
||||
|
||||
# 封存记录字段(aa.md 列定义)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_NAME_FIELD = "staff_name"
|
||||
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
|
||||
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
|
||||
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天
|
||||
|
||||
# 输出列(对应需求文档检查1输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"在职天数", "应勤工作日", "休息天", "差值",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
def _working_days(first: date, last: date, join: Optional[date], leave: Optional[date]) -> int:
|
||||
"""计算员工当月在职自然天数(月区间 ∩ 在职区间闭区间,含首尾)。"""
|
||||
lo = first if not join else (join if join >= first else first)
|
||||
hi = last if not leave else (leave if leave <= last else last)
|
||||
if lo > hi:
|
||||
return 0
|
||||
return (hi - lo).days + 1
|
||||
|
||||
|
||||
def _build_seal_map(rows: List[dict]) -> Dict[str, dict]:
|
||||
"""按工号建立 封存记录索引(一员工一条)。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _text(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
mapping.setdefault(code, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
def run_working_days_shift_check(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""执行检查1「在职天数是否均排班验证」,返回异常名单行列表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
save_dir: 输出目录(仅用于读取预处理封存表)。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
seal_rows = load_seal_rows(ym, save_dir)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map = _build_seal_map(seal_rows)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
abnormal: List[dict] = []
|
||||
for code, rec in seal_map.items():
|
||||
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
|
||||
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
|
||||
wd = _working_days(first, last, join, leave)
|
||||
if wd <= 0:
|
||||
continue # 当月无在职日,跳过
|
||||
work = _num(rec.get(SEAL_WORK_FIELD))
|
||||
rest = _num(rec.get(SEAL_REST_FIELD))
|
||||
diff = wd - (work + rest)
|
||||
if diff != 0:
|
||||
abnormal.append(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"在职天数": wd,
|
||||
"应勤工作日": int(work),
|
||||
"休息天": int(rest),
|
||||
"差值": diff,
|
||||
}, code, rec))
|
||||
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
|
||||
return abnormal
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0011",
|
||||
"name": "考勤月报封存检查",
|
||||
"version": "1.0.0",
|
||||
"description": "考勤月报封存后自动检查:拉取当月全集团封存数据并按白名单单位预处理,自动导出花名册/调动台账,依次执行 6 项检查(在职天数排班/出勤及排休/封存最新值/全勤验证/未封存名单/延时加班),输出单工作簿异常名单",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": true,
|
||||
"ui": false,
|
||||
"capabilities": ["xq0011"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\考勤月报封存检查",
|
||||
"description": "封存表/花名册/调动台账/汇总工作簿统一输出目录"
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string",
|
||||
"title": "花名册路径",
|
||||
"default": "",
|
||||
"description": "留空=输出目录/员工花名册.xlsx(自动导出,15 分钟内复用)"
|
||||
},
|
||||
"transfer_path": {
|
||||
"type": "string",
|
||||
"title": "调动台账路径",
|
||||
"default": "",
|
||||
"description": "留空=输出目录/调动台账.xlsx(自动导出,15 分钟内复用)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 报告层:检查编排汇总与单工作簿输出。"""
|
||||
@@ -0,0 +1,144 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 汇总执行与单工作簿输出(由影刀版移植)。
|
||||
|
||||
依次运行检查1~检查6,将各异常名单合并写入一个 Excel 工作簿(每个检查一个 sheet),
|
||||
并生成「汇总」sheet 概览各检查异常人数。各检查模块不再单独落盘(单工作簿统一输出)。
|
||||
|
||||
插件化改造点:
|
||||
1. save_dir / roster_path / transfer_path 由 run() 解析注入;
|
||||
2. 各检查 run_fn 统一签名 (month=..., save_dir=..., **kwargs);
|
||||
3. 某检查失败不阻断其余检查(记 rows=[]),汇总仍输出。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime
|
||||
from typing import Callable, Dict, List, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import logger, DEFAULT_SAVE_DIR
|
||||
from ..logic.working_days_shift_check import (
|
||||
run_working_days_shift_check, OUTPUT_COLUMNS as COL_CHECK1,
|
||||
)
|
||||
from ..logic.attendance_rest_check import (
|
||||
run_attendance_rest_check, OUTPUT_COLUMNS as COL_CHECK2,
|
||||
)
|
||||
from ..logic.latest_seal_check import (
|
||||
run_latest_seal_check, OUTPUT_COLUMNS as COL_CHECK3,
|
||||
)
|
||||
from ..logic.full_attendance_check import (
|
||||
run_full_attendance_check, OUTPUT_COLUMNS as COL_CHECK4,
|
||||
)
|
||||
from ..logic.unsealed_check import (
|
||||
run_unsealed_check, OUTPUT_COLUMNS as COL_CHECK5,
|
||||
)
|
||||
from ..logic.overtime_compensation_check import (
|
||||
run_overtime_compensation_check, OUTPUT_COLUMNS as COL_CHECK6,
|
||||
)
|
||||
|
||||
# 检查元信息:(编号, sheet 名, 异常类型标签, run 函数, 输出列, run 额外 kwargs)
|
||||
CHECK_META: List[Tuple[str, str, str, Callable, List[str], Dict]] = [
|
||||
("检查1", "检查1-在职天数排班异常", "在职天数 ≠ 应勤工作日 + 休息天",
|
||||
run_working_days_shift_check, COL_CHECK1, {}),
|
||||
("检查2", "检查2-出勤及排休天数异常", "出勤/正休天数与应勤天标准不符",
|
||||
run_attendance_rest_check, COL_CHECK2, {}),
|
||||
("检查3", "检查3-封存非最新值", "考勤封存非最新值,请重新封存",
|
||||
run_latest_seal_check, COL_CHECK3, {}),
|
||||
("检查4", "检查4-全勤验证异常", "晋升当月要求全勤 / 迟到早退",
|
||||
run_full_attendance_check, COL_CHECK4, {}),
|
||||
("检查5", "检查5-未封存名单", "考勤月报未封存,请处理",
|
||||
run_unsealed_check, COL_CHECK5, {}),
|
||||
("检查6", "检查6-延时加班异常", "经营系管理岗不应享受延时加班,请核对",
|
||||
run_overtime_compensation_check, COL_CHECK6, {}),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def run_all_checks(month: str = None, save_dir: str = None,
|
||||
roster_path: str = None, transfer_path: str = None) -> Dict[str, object]:
|
||||
"""依次运行检查1~6,返回各检查异常名单行列表(每项含编号/sheet/类型/行列表)。"""
|
||||
ym = _normalize_month(month)
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
logger.info("===== 考勤月报封存检查(汇总)月份:%s =====", ym)
|
||||
results: List[dict] = []
|
||||
total = 0
|
||||
notes: List[str] = []
|
||||
for no, sheet_name, label, run_fn, _cols, kwargs in CHECK_META:
|
||||
kw = dict(kwargs)
|
||||
if no == "检查4":
|
||||
kw["transfer_path"] = transfer_path
|
||||
if no in ("检查5", "检查6"):
|
||||
kw["roster_path"] = roster_path
|
||||
try:
|
||||
rows = run_fn(month=ym, save_dir=save_dir, **kw)
|
||||
except Exception as e:
|
||||
logger.error("%s 执行失败:%s", no, e)
|
||||
notes.append(f"{no} 执行失败:{e}")
|
||||
rows = []
|
||||
results.append({
|
||||
"no": no,
|
||||
"sheet_name": sheet_name,
|
||||
"label": label,
|
||||
"rows": rows,
|
||||
})
|
||||
total += len(rows)
|
||||
logger.info("%s 完成:异常 %d 人", no, len(rows))
|
||||
return {"ym": ym, "results": results, "total": total, "notes": notes}
|
||||
|
||||
|
||||
def write_workbook(result: Dict[str, object], save_dir: str = None) -> str:
|
||||
"""将各检查异常名单写入单工作簿(汇总 + 每检查一个 sheet),返回文件路径。"""
|
||||
ym = result["ym"]
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(save_dir, f"考勤月报封存检查_{ym}_{ts}.xlsx")
|
||||
# 汇总 sheet 行
|
||||
summary_rows = [{
|
||||
"序号": i + 1,
|
||||
"检查编号": it["no"],
|
||||
"异常类型": it["label"],
|
||||
"异常人数": len(it["rows"]),
|
||||
} for i, it in enumerate(result["results"])]
|
||||
summary_rows.append({
|
||||
"序号": len(summary_rows) + 1,
|
||||
"检查编号": "合计",
|
||||
"异常类型": "",
|
||||
"异常人数": result["total"],
|
||||
})
|
||||
try:
|
||||
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
|
||||
pd.DataFrame(summary_rows).to_excel(
|
||||
writer, sheet_name="汇总", index=False)
|
||||
for it, (_, _, _, _, cols, _) in zip(result["results"], CHECK_META):
|
||||
rows = it["rows"]
|
||||
sheet_name = it["sheet_name"]
|
||||
if not rows:
|
||||
# 空结果也保留 sheet,便于人工核对
|
||||
pd.DataFrame(columns=cols).to_excel(
|
||||
writer, sheet_name=sheet_name, index=False)
|
||||
continue
|
||||
pd.DataFrame(rows, columns=cols).to_excel(
|
||||
writer, sheet_name=sheet_name, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("汇总工作簿已保存:%s(共 %d 人异常)", save_path, result["total"])
|
||||
return save_path
|
||||
@@ -0,0 +1,4 @@
|
||||
requests
|
||||
pandas
|
||||
openpyxl
|
||||
websocket-client
|
||||
@@ -0,0 +1,41 @@
|
||||
# ERP报表导出(xq0031_xq0032)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出插件:物料收发汇总表(需求31)+ 采购订单列表(需求32),
|
||||
支持新旧系统切换、仓库编码多选(或关系)、日期多档(N天 / 自定义区间)逐档导出。
|
||||
|
||||
## 目录结构
|
||||
|
||||
- `*.py` — 插件后端(ScenePlugin 注册 + ERP 登录 + 两报表逻辑),自包含,
|
||||
只引用标准库 / 第三方依赖 / 底座注入接口(`webhost.backend.plugins.base`)
|
||||
- `ui/` — 插件前端**构建产物**(壳子后端托管于 `/pui/xq0031_xq0032/`,勿手改)
|
||||
- `ui-src/` — 插件前端源码(Vue 3 + Element Plus + Vite)
|
||||
- `_pack.py` — 发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)
|
||||
|
||||
## 前端开发 / 构建
|
||||
|
||||
```bash
|
||||
cd ui-src
|
||||
npm install
|
||||
npm run build # 产物输出到 ../ui/(vite.config.js 里 base=/pui/xq0031_xq0032/)
|
||||
```
|
||||
|
||||
联调:先启动壳子(webhost),`npm run dev` 走 vite 代理(5180 → 127.0.0.1:8799)。
|
||||
|
||||
## 打包发布
|
||||
|
||||
1. 构建 ui(见上)
|
||||
2. `desktop/` 下执行:`../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py`
|
||||
→ 产出 `dist-plugin/xq0031_xq0032_v<版本>.zip`(自动排除 ui-src 等)
|
||||
3. `desktop/` 下发布:
|
||||
`.venv\Scripts\python.exe -m controlplane.tools.agent_cli publish dist-plugin\xq0031_xq0032_v<版本>.zip --id xq0031_xq0032 --version <版本> --admin puddy`
|
||||
|
||||
## 个性化配置(自带界面)
|
||||
|
||||
`plugin.json` 声明 `"ui": true`,壳子插件页展示「打开插件界面」入口(弹独立窗口,
|
||||
同源自动携带登录会话)。账号密码 / 仓库编码 / 日期选项等在窗口内填写:
|
||||
|
||||
- 配置经壳子 `GET/POST /api/plugin-config/xq0031_xq0032` 保存,
|
||||
落执行机本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\xq0031_xq0032.json`,
|
||||
下次打开自动回填(表单改动防抖自动保存);
|
||||
- 执行经现有 `POST /api/runs`,日志/进度经 `WS /ws` 实时回显(另有 5 秒轮询兜底);
|
||||
- 浏览器每次现场真登录(auto_port 独立实例),确保登录的就是本次配置的账号。
|
||||
@@ -0,0 +1,185 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次):
|
||||
物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出
|
||||
采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据
|
||||
|
||||
个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true):
|
||||
- ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写,
|
||||
经 /api/plugin-config 保存在执行机本机,下次打开自动回填;
|
||||
- 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间);
|
||||
- 浏览器现场真登录(固定默认用户目录,保留登录态/配置),确保用的就是本次配置的账号。
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import erp_login
|
||||
|
||||
# 执行模式
|
||||
MODE_31 = '物料收发汇总表'
|
||||
MODE_32 = '采购订单列表'
|
||||
MODE_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _as_str_list(value):
|
||||
"""fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
parts = value.replace(',', ',').replace(' ', ',').split(',')
|
||||
elif isinstance(value, (list, tuple)):
|
||||
parts = list(value)
|
||||
else:
|
||||
parts = [value]
|
||||
out, seen = [], set()
|
||||
for p in parts:
|
||||
s = str(p).strip()
|
||||
if s and s not in seen:
|
||||
seen.add(s)
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
class ErpReportExportPlugin(ScenePlugin):
|
||||
id = "xq0031_xq0032"
|
||||
name = "ERP物料收发汇总-采购订单报表导出"
|
||||
version = "1.0.10"
|
||||
description = "金蝶K3Cloud报表导出:物料收发汇总表+ 采购订单列表,支持新旧系统与个性化配置"
|
||||
platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
# 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口;
|
||||
# 此处仅作为无 manifest 时的兜底与参数契约文档
|
||||
fields = [
|
||||
{"key": "mode", "label": "执行模式", "type": "select",
|
||||
"options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH},
|
||||
{"key": "erp_system", "label": "ERP系统", "type": "select",
|
||||
"options": ["新版", "旧版"], "default": "新版"},
|
||||
{"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""},
|
||||
{"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""},
|
||||
{"key": "org_name", "label": "查询组织", "type": "text",
|
||||
"default": config.ORG_NAME},
|
||||
{"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect",
|
||||
"options": config.STOCK_CODES_DEFAULT + config.STOCK_CODES_DEFAULT_OLD,
|
||||
"default": list(config.STOCK_CODES_DEFAULT)},
|
||||
{"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect",
|
||||
"options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)},
|
||||
{"key": "scheme_name", "label": "采购订单快捷方案", "type": "text",
|
||||
"default": config.SCHEME_NAME},
|
||||
{"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
# 注入日志钩子(插件内全部模块经 config.log 输出)
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new'
|
||||
username = str(fields.get("erp_username") or "").strip()
|
||||
password = str(fields.get("erp_password") or "")
|
||||
org = str(fields.get("org_name") or "").strip() or (
|
||||
config.ORG_NAME_OLD if erp == 'old' else config.ORG_NAME)
|
||||
scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME
|
||||
codes = _as_str_list(fields.get("stock_codes")) # 空 = 全部仓库不筛选
|
||||
dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT)
|
||||
if not username or not password:
|
||||
raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_31, MODE_32):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if mode in (MODE_BOTH, MODE_31) and not dates:
|
||||
raise RuntimeError("物料收发汇总表需要日期选项(请在插件界面配置);仓库编码可留空=下载全部仓库")
|
||||
|
||||
save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"')
|
||||
save_dir = Path(save_dir_raw) if save_dir_raw else Path(
|
||||
_desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}"
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
ctx.log(f"保存目录: {save_dir}")
|
||||
|
||||
# ---------- 登录(一次,两种报表共用会话) ----------
|
||||
ctx.progress(3)
|
||||
ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]}),查询组织:{org}")
|
||||
ok, page = erp_login.erp_login(erp, username, password)
|
||||
if not ok:
|
||||
raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志")
|
||||
ctx.progress(8)
|
||||
|
||||
# ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ----------
|
||||
do_31 = mode in (MODE_BOTH, MODE_31)
|
||||
do_32 = mode in (MODE_BOTH, MODE_32)
|
||||
units_31 = len(dates) if do_31 else 0
|
||||
total = units_31 + (1 if do_32 else 0)
|
||||
|
||||
def _report(done_abs):
|
||||
ctx.progress(8 + int(88 * done_abs / max(1, total)))
|
||||
|
||||
saved, failed = [], []
|
||||
try:
|
||||
try:
|
||||
page.set.window.max()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
from .logic import material_summary, purchase_order
|
||||
from .report.merge_summary import merge_summary
|
||||
|
||||
if do_31:
|
||||
try:
|
||||
ctx.log(f"开始导出物料收发汇总表:下载全部仓库,按所选 {len(codes)} 个仓库中文名筛选" if codes else "开始导出物料收发汇总表:下载全部仓库(未筛选)")
|
||||
files31, failed31 = material_summary.run(
|
||||
page, save_dir, org, codes, dates,
|
||||
progress=lambda done_i, _total: _report(done_i),
|
||||
set_org=True) # 新旧系统均显式设置查询组织(旧系统登录默认组织已不再默认)
|
||||
saved += files31
|
||||
failed += [f"物料收发汇总表[{x}]" for x in failed31]
|
||||
except RuntimeError as e:
|
||||
failed.append(f"物料收发汇总表[{e}]")
|
||||
files31 = []
|
||||
# 各档报表导出后合并为汇总文件(合并失败不阻断整体结果)
|
||||
if files31:
|
||||
try:
|
||||
merged = merge_summary(save_dir)
|
||||
if merged:
|
||||
saved.append(str(merged))
|
||||
except Exception as e:
|
||||
ctx.log(f"汇总文件生成失败: {e}")
|
||||
if do_32:
|
||||
try:
|
||||
ctx.log(f"开始导出采购订单列表(方案:{scheme})")
|
||||
f32 = purchase_order.run(page, save_dir, scheme, erp=erp,
|
||||
progress=lambda _i, _t: _report(units_31 + 1))
|
||||
if f32:
|
||||
saved.append(f32)
|
||||
else:
|
||||
failed.append("采购订单列表")
|
||||
except RuntimeError as e:
|
||||
failed.append(f"采购订单列表[{e}]")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项"
|
||||
else:
|
||||
summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
# ================== 小工具 ==================
|
||||
def _desktop():
|
||||
from .data.k3_common import get_desktop
|
||||
return get_desktop()
|
||||
|
||||
|
||||
PLUGINS.append(ErpReportExportPlugin())
|
||||
@@ -0,0 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
把本插件压成 dist-plugin/xq0031_xq0032_v<版本>.zip,
|
||||
包根布局与 sb_person_change 一致:plugin.json / 各 .py / ui/ 直接位于 zip 根。
|
||||
排除项:ui-src(前端源码与 node_modules)、__pycache__、debug、本脚本、*.pyc。
|
||||
|
||||
用法(desktop/ 下执行):
|
||||
../.venv/Scripts/python.exe ../plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/_pack.py
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0031_xq0032_v1.0.0.zip --id xq0031_xq0032 --version 1.0.0
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py", "_test_both_export.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
if not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit("缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出(xq0031_xq0032)插件配置:默认值与运行参数。
|
||||
|
||||
合并 XQ0031(物料收发汇总表)+ XQ0032(采购订单列表)的固化配置,
|
||||
与 workflows 影刀版各源文件常量保持同源(四方向零依赖,各自演进)。
|
||||
|
||||
个性化配置(账号密码/仓库编码/日期选项等)由插件自带 Vue 界面维护,经
|
||||
webhost /api/plugin-config 落执行机本机,run() 时经 fields 注入;
|
||||
本文件只承载 fields 未传时的兜底默认与运行参数。
|
||||
"""
|
||||
|
||||
# ==================== 1. 业务默认值(fields 未传/留空时的兜底) ====================
|
||||
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织(新版默认)
|
||||
ORG_NAME_OLD = '99.01.07.01.01 石桥铺会馆' # 查询组织(旧版默认;登录已不再默认,须显式选择)
|
||||
# 仓库编码→仓库中文名(现场映射,供「下载全部仓库后按中文名筛选」使用):
|
||||
# 0101010101 重庆运营总仓 / 0101010201 重庆美得三方仓 / 0101020201 成都美得三方仓
|
||||
# 0101030201 长沙乐行三方仓 / 0101040201 西安美得三方仓 / 03010127 代管仓(旧版登录默认)
|
||||
# 前端仍要求选择仓库编码(决定最终保留哪些仓库),查询统一下载全部仓库,
|
||||
# 下载后用 openpyxl 按本映射把仓库中文名列筛到所选编码对应仓库,覆盖保存。
|
||||
STOCK_NAME_MAP = {
|
||||
'0101010101': '重庆运营总仓',
|
||||
'0101010201': '重庆美得三方仓',
|
||||
'0101020201': '成都美得三方仓',
|
||||
'0101030201': '长沙乐行三方仓',
|
||||
'0101040201': '西安美得三方仓',
|
||||
'03010127': '代管仓',
|
||||
}
|
||||
|
||||
# 前端可选仓库编码列表(与 STOCK_NAME_MAP 键一致;留空 = 全部仓库不筛选)
|
||||
STOCK_CODES_DEFAULT = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
|
||||
STOCK_CODES_DEFAULT_OLD = ['03010127'] # 旧版默认仓库(代管仓,随 ERP 系统选项切换)
|
||||
DATE_OPTIONS_DEFAULT = ['60D', '30D', '15D', '7D', '3D']
|
||||
SCHEME_NAME = '默认方案(个人)' # 需求32 快捷方案(精确匹配)
|
||||
FOLDER_NAME = '采购计划报表' # 保存目录命名前缀(31/32 同目录)
|
||||
FILE_PREFIX_31 = '物料收发汇总表' # 31 导出文件名前缀
|
||||
FILE_PREFIX_32 = '采购订单列表' # 32 导出文件名前缀
|
||||
|
||||
# ==================== 2. 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3
|
||||
TIMEOUT = 15 # 元素查找超时(秒)
|
||||
|
||||
# ==================== 3. 日志钩子(print → ctx.log) ====================
|
||||
_log_fn = print
|
||||
|
||||
|
||||
def set_log(fn) -> None:
|
||||
"""插件 run() 启动时把 ctx.log 注入进来,全部模块经 log() 输出。"""
|
||||
global _log_fn
|
||||
_log_fn = fn if fn else print
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
_log_fn(msg)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金蝶 K3Cloud(HTML5)ERP 登录模块(xq0031_xq0032 插件内自包含)。
|
||||
|
||||
自 workflows/share/erp_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env),个性化归属明确;
|
||||
- 使用固定默认用户目录(不再每次独立临时目录),保留登录态与浏览器配置;
|
||||
用完由调用方 page.quit() 关闭;
|
||||
- print → config.log。
|
||||
|
||||
登录页元素(新旧版一致):
|
||||
用户名输入框 <input id="user" placeholder="用户名">
|
||||
密码输入框 <input id="password" type="password">
|
||||
登录按钮 <button id="btnLogin" class="btnlogin k-button">登录</button>
|
||||
登录成功判定:URL 包含 /k3cloud/html5/dform.aspx,或站点页面无登录输入框(已登录态)。
|
||||
特殊弹窗:登录时若弹出「该帐号已登录在线,确认让对方下线」警告框,自动点确认。
|
||||
"""
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
# ================== 站点定义(新旧 ERP) ==================
|
||||
ERP_URLS = {
|
||||
'old': 'https://erp.37du.co/k3cloud/html5/index.aspx',
|
||||
'new': 'https://criterion.erp.37du.co/k3cloud/html5/index.aspx',
|
||||
}
|
||||
|
||||
# 登录页元素定位(新旧版元素 id 一致)
|
||||
USER_INPUT = '#user'
|
||||
PWD_INPUT = '#password'
|
||||
LOGIN_BTN = '#btnLogin'
|
||||
# 「该帐号已登录在线」弹窗的确认按钮(蓝色样式 class 固定,id 为动态 UUID)
|
||||
KICK_CONFIRM_BTN = 'css:.k-window .BlueButtonStyle'
|
||||
|
||||
# 登录成功标志:URL 包含该关键字即视为已登录(跳转到默认表单页)
|
||||
SUCCESS_KEYWORD = '/k3cloud/html5/dform.aspx'
|
||||
|
||||
# ================== 运行参数 ==================
|
||||
RETRY_MAX = config.RETRY_MAX # 全局重试次数(项目规范:最多 3 次)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
LOGIN_WAIT = 3 # 点击登录后等待(秒)
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def _resolve_url(erp):
|
||||
"""把 'old'/'new'/完整URL 统一解析为登录页 URL。"""
|
||||
if erp in ERP_URLS:
|
||||
return ERP_URLS[erp]
|
||||
if erp and erp.lower().startswith('http'):
|
||||
return erp
|
||||
raise ValueError(f"无效的 ERP 标识:{erp},可选 'old'、'new' 或完整登录页 URL")
|
||||
|
||||
|
||||
def _is_login_page(url):
|
||||
"""判断当前 URL 是否仍停留在登录页。"""
|
||||
return 'index.aspx' in (url or '').lower()
|
||||
|
||||
|
||||
def _is_login_success(url):
|
||||
"""登录成功判定:URL 包含 dform.aspx 即视为已登录。"""
|
||||
return SUCCESS_KEYWORD in (url or '')
|
||||
|
||||
|
||||
def _handle_kick_dialog(page):
|
||||
"""处理「该帐号已登录在线,确认让对方下线」弹窗:存在则点击蓝色确认按钮。"""
|
||||
for _ in range(3):
|
||||
btn = page.ele(KICK_CONFIRM_BTN, timeout=2)
|
||||
if not btn:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
config.log("[ERP登录] 检测到「已登录在线」弹窗,点击确认(让对方下线)")
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 点击弹窗确认异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def _open_browser(headless):
|
||||
"""启动浏览器(DrissionPage 固定默认用户目录,不再每次独立临时目录,保留登录态/配置)。
|
||||
附加禁用浏览器自身弹窗的 prefs/启动参数:保存密码、权限请求(通知/定位/音视频)、
|
||||
自动化测试 infobar、首次运行向导、打开外部应用确认框(K3 点引出/下载会请求打开
|
||||
Excel 等,防止弹「访问应用和服务」)等。"""
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
# —— 禁用浏览器自身弹窗(避免干扰自动化)——
|
||||
co.set_pref('credentials_enable_service', False) # 不保存密码
|
||||
co.set_pref('profile.password_manager_enabled', False) # 关闭密码管理器
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def erp_login(erp='new', username='', password='', headless=None):
|
||||
"""
|
||||
登录金蝶 K3Cloud ERP(新旧系统通用,现场真登录)。
|
||||
|
||||
参数:
|
||||
erp 'old' 旧版 erp.37du.co / 'new' 新版 criterion.erp.37du.co / 完整登录页 URL
|
||||
username 用户名(插件界面配置注入,必填)
|
||||
password 密码(插件界面配置注入,必填)
|
||||
|
||||
返回:
|
||||
(success, page) success=True 时 page 为已登录的 ChromiumPage;失败时 page 为 None。
|
||||
调用方使用完毕应 page.quit() 关闭浏览器(不保存任何目录/cookies)。
|
||||
"""
|
||||
login_url = _resolve_url(erp)
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[ERP登录] 登录账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return False, None
|
||||
headless = HEADLESS if headless is None else bool(headless)
|
||||
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[ERP登录] 第 {attempt}/{RETRY_MAX} 次 → {login_url}")
|
||||
page = _open_browser(headless)
|
||||
config.log("[ERP登录] 浏览器已启动(默认用户目录,保留登录态)")
|
||||
|
||||
# 回到目标登录页;已登录站点会跳转/保留会话,未登录则停在登录页
|
||||
page.get(login_url)
|
||||
time.sleep(2)
|
||||
|
||||
# 3) 已登录判定:页面无登录输入框 → 会话有效,直接复用
|
||||
if page.ele(USER_INPUT, timeout=3) is None:
|
||||
config.log("[ERP登录] 检测到已登录会话,直接复用")
|
||||
return True, page
|
||||
|
||||
# 4) 未登录 → 填表登录
|
||||
user = page.ele(USER_INPUT, timeout=TIMEOUT)
|
||||
if not user:
|
||||
config.log("[ERP登录] 找不到用户名输入框")
|
||||
continue
|
||||
user.clear()
|
||||
user.input(username)
|
||||
time.sleep(0.5)
|
||||
# 用户名框是 autocomplete 控件,需按回车关闭弹出的下拉提示框
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
time.sleep(0.3)
|
||||
|
||||
pwd = page.ele(PWD_INPUT, timeout=TIMEOUT)
|
||||
if not pwd:
|
||||
config.log("[ERP登录] 找不到密码输入框")
|
||||
continue
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
time.sleep(0.3)
|
||||
|
||||
btn = page.ele(LOGIN_BTN, timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[ERP登录] 找不到登录按钮")
|
||||
continue
|
||||
btn.click()
|
||||
|
||||
# 登录后轮询:处理「已登录在线」弹窗 + 等待跳转到 dform.aspx
|
||||
for _ in range(6):
|
||||
time.sleep(LOGIN_WAIT)
|
||||
if _is_login_success(page.url):
|
||||
config.log(f"[ERP登录] 登录成功 → {page.url}")
|
||||
return True, page
|
||||
_handle_kick_dialog(page)
|
||||
|
||||
config.log("[ERP登录] 点击登录后未跳转到 dform.aspx(账号密码错误或网络异常)")
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 异常:{e}")
|
||||
|
||||
# 走到这里说明本轮失败,关闭浏览器后重试(成功时在上方已直接 return)
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
config.log("[ERP登录] 重试 3 次均失败")
|
||||
return False, None
|
||||
@@ -0,0 +1,299 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""K3Cloud HTML5 页面操作公共件(xq0031_xq0032 插件内共享)。
|
||||
|
||||
自 workflows/XQ0001-0100/XQ0031、XQ0032 影刀版迁移的稳定交互原语,两报表共用。
|
||||
K3 现场验证结论(勿随手"优化",均为踩坑后的修复):
|
||||
- 残留窗口会被移到屏幕外,is_displayed 仍 True 但点击无效 → 必须同时校验视口位置
|
||||
- 工具栏/菜单项物理点击只选中文字不触发菜单 → 用 by_js;嵌套悬浮子菜单相反,
|
||||
必须真实鼠标悬浮(move_to 链不能断)
|
||||
- 浏览器断连(PageDisconnectedError)属致命异常,直接上抛,避免被容错吞掉空转
|
||||
"""
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from DrissionPage.errors import PageDisconnectedError
|
||||
except Exception:
|
||||
PageDisconnectedError = None
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def get_desktop():
|
||||
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
guid = wintypes.GUID(
|
||||
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
|
||||
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
|
||||
func = ctypes.windll.shell32.SHGetKnownFolderPath
|
||||
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
|
||||
ctypes.POINTER(ctypes.c_wchar_p)]
|
||||
ptr = ctypes.c_wchar_p()
|
||||
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
|
||||
return ptr.value
|
||||
except Exception:
|
||||
return str(Path.home() / 'Desktop')
|
||||
|
||||
|
||||
def is_in_viewport(el, page):
|
||||
"""元素是否真实显示在视口内。K3 残留窗口会被移到屏幕外,此时 is_displayed
|
||||
仍为 True,但其内元素点击无效——必须同时校验位置在视口内。"""
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
return False
|
||||
w, h = el.rect.size
|
||||
if w <= 0 or h <= 0:
|
||||
return False
|
||||
x, y = el.rect.location
|
||||
vw, vh = page.run_js(
|
||||
'return [window.innerWidth || document.documentElement.clientWidth,'
|
||||
' window.innerHeight || document.documentElement.clientHeight];')
|
||||
return 0 <= x < vw and 0 <= y < vh
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def click_visible(page, css, timeout=None, by_js=False):
|
||||
"""点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。
|
||||
by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。"""
|
||||
timeout = config.TIMEOUT if timeout is None else timeout
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
el.click(by_js=True) if by_js else el.click()
|
||||
return True
|
||||
except Exception as e:
|
||||
if PageDisconnectedError is not None and isinstance(e, PageDisconnectedError):
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def ele_visible(page, css, timeout=1):
|
||||
"""元素存在、且在视口内可见才算命中(K3 过滤窗口关闭后 DOM 里仍残留隐藏/屏幕外节点)。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def press_enter(page):
|
||||
"""模拟按一次回车键。"""
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
|
||||
|
||||
def press_enter_in(el, page):
|
||||
"""向指定元素直接发送回车(元素级,避免页面焦点漂移导致回车无效)。"""
|
||||
try:
|
||||
from DrissionPage.common import Keys
|
||||
el.input(Keys.ENTER)
|
||||
except Exception:
|
||||
press_enter(page)
|
||||
|
||||
|
||||
def visible_titles(page):
|
||||
"""返回所有可见窗口标题文本列表。"""
|
||||
titles = []
|
||||
try:
|
||||
for t in page.eles('css:.k-window-title'):
|
||||
try:
|
||||
if t.states.is_displayed:
|
||||
titles.append(t.text)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return titles
|
||||
|
||||
|
||||
def close_window_by_title(page, title, timeout=3, tag=''):
|
||||
"""物理点击关闭标题包含关键字的 k-window 弹窗(K3 下载窗口等残留,关闭按钮 by_js 不触发)。
|
||||
用包含匹配:实际标题可能是「文件下载」或「文档下载」,避免因标题差异关不掉。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
for w in page.eles('css:.k-window'):
|
||||
try:
|
||||
if not w.states.is_displayed:
|
||||
continue
|
||||
t = w.ele('css:.k-window-title', timeout=0.3)
|
||||
if t is None or title not in (t.text or ''):
|
||||
continue
|
||||
btn = w.ele('css:.k-window-actions .k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def reset_filter_state(page, tag='', wait_query=False):
|
||||
"""重试前清理脏界面状态:按 ESC 关闭残留的弹层/过滤窗口,兜底点各面板「取消」按钮。
|
||||
wait_query=True(需求31):若查询正在进行先等其结束(ESC 会打断正常查询)。"""
|
||||
if wait_query:
|
||||
end = time.time() + 120
|
||||
while time.time() < end:
|
||||
if not any('查询进度' in x for x in visible_titles(page)):
|
||||
break
|
||||
time.sleep(1)
|
||||
for _ in range(2):
|
||||
try:
|
||||
page.actions.key_down('ESC')
|
||||
page.actions.key_up('ESC')
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
click_visible(page, 'css:[id*="FBTNCANCEL_c"]', timeout=1)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def download_file(page, save_dir, new_name, tag=''):
|
||||
"""点「下载」按钮 → 等文件落盘到保存目录。
|
||||
做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录),
|
||||
然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。"""
|
||||
save_dir = Path(save_dir)
|
||||
try:
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
page.set.download_path(str(save_dir))
|
||||
page.set.when_download_file_exists('overwrite')
|
||||
except Exception as e:
|
||||
config.log(f'{tag} 设置下载目录异常: {e}')
|
||||
before_names = {b.name for b in save_dir.glob('*')} if save_dir.exists() else set()
|
||||
|
||||
# 清除上个报表/上次导出残留的「文件下载/文档下载」窗口,防止全页匹配误命中旧下载按钮
|
||||
# (需求31多档连导或需求31→32连导时残留)。此刻本次引出刚触发、尚在生成阶段,
|
||||
# 其下载窗口还未弹出,关闭残留窗口不影响本次导出。
|
||||
for _title in ('文件下载', '文档下载'):
|
||||
try:
|
||||
close_window_by_title(page, _title, timeout=1, tag=tag)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 找可见的「下载」按钮,以「引出进度」窗口为信号判定引出是否仍在进行:
|
||||
# - 点击引出后,K3 会先弹「引出进度」窗口(进度条 + 「正在获取引出数据:(n/N)」caption),
|
||||
# 取数完成后该窗口关闭并弹出「文件下载」窗口;正常 ≤30s,大数据量(百万行)约 1 分钟多;
|
||||
# - 「引出进度」窗口始终未出现 → 引出未被受理/已失败,快速返回失败,不做无谓死等;
|
||||
# - 进度窗口已消失但 GONE_GAP 内下载按钮未出现 → 引出失败,快速返回交外层重试。
|
||||
dl = None
|
||||
start = time.time()
|
||||
seen_busy = False # 是否见过「引出进度」窗口
|
||||
busy_gone_since = None # 进度窗口消失的时刻(None=尚未消失)
|
||||
WAIT_BUSY = 20 # 等「引出进度」窗口出现的最长时间
|
||||
GONE_GAP = 10 # 进度窗口消失后等下载按钮的窗口期
|
||||
OVERALL = 150 # 整体硬上限(含百万行大数据的取数时间)
|
||||
last_report = start
|
||||
|
||||
def _busy(titles):
|
||||
return any(k in t for t in titles for k in ('生成', '进度', '稍候', '处理中', '导出'))
|
||||
|
||||
def _progress_text():
|
||||
"""读「引出进度」窗口 caption(如「正在获取引出数据:(100001/1242812)」)。"""
|
||||
try:
|
||||
cap = page.ele('css:[id*="FPROGRESSBAR"] div[id*="lblCaption"]', timeout=0.3)
|
||||
return (cap.attr('title') or cap.text or '').strip() if cap else ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
while time.time() - start < OVERALL:
|
||||
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
dl = el
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl:
|
||||
break
|
||||
busy = _busy(visible_titles(page))
|
||||
if busy:
|
||||
seen_busy = True
|
||||
busy_gone_since = None
|
||||
elif seen_busy:
|
||||
if busy_gone_since is None:
|
||||
busy_gone_since = time.time()
|
||||
elif time.time() - busy_gone_since > GONE_GAP:
|
||||
config.log(f'{tag} 引出进度窗口已消失且下载按钮未出现,判定本次引出失败')
|
||||
return False
|
||||
elif time.time() - start > WAIT_BUSY:
|
||||
config.log(f'{tag} 未检测到「引出进度」窗口,判定本次引出未触发/失败')
|
||||
return False
|
||||
now = time.time()
|
||||
if now - last_report >= 30:
|
||||
last_report = now
|
||||
txt = _progress_text()
|
||||
config.log(f'{tag} 仍在等待(引出进度窗口'
|
||||
f'{txt or "可见"},已等 {int(now - start)}s)')
|
||||
time.sleep(0.5)
|
||||
if not dl:
|
||||
config.log(f'{tag} 找不到下载按钮(等待 {OVERALL}s 后 K3 仍未生成完成)')
|
||||
return False
|
||||
config.log(f'{tag} 点击下载按钮...')
|
||||
try:
|
||||
dl.click()
|
||||
except Exception:
|
||||
dl.click(by_js=True)
|
||||
|
||||
# 等新文件出现且大小连续两次不变(下载完成)
|
||||
config.log(f'{tag} 等待文件下载完成...')
|
||||
last_size, last_name = -1, None
|
||||
end = time.time() + 300
|
||||
while time.time() < end:
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names]
|
||||
if new_files:
|
||||
f = max(new_files, key=lambda x: x.stat().st_mtime)
|
||||
try:
|
||||
s = f.stat().st_size
|
||||
except Exception:
|
||||
s = 0
|
||||
if (f.suffix not in ('.crdownload', '.tmp', '.part')
|
||||
and s > 0 and s == last_size and f.name == last_name):
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag) # 只关下载窗口,其余残留不主动关
|
||||
return True
|
||||
last_size, last_name = s, f.name
|
||||
time.sleep(1)
|
||||
|
||||
# 兜底:超时但确有新文件也尝试落名
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names
|
||||
and f.suffix not in ('.crdownload', '.tmp', '.part')]
|
||||
for f in new_files:
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag)
|
||||
return True
|
||||
config.log(f'{tag} 下载失败/超时')
|
||||
return False
|
||||
|
||||
|
||||
def _save_as(src, dst):
|
||||
"""把下载产物重命名/移动到目标名;移动失败则原样保留并返回实际路径。"""
|
||||
if src == dst:
|
||||
return src
|
||||
try:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
shutil.move(str(src), str(dst))
|
||||
return dst
|
||||
except Exception:
|
||||
return src
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,510 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""需求32 - 金蝶 K3Cloud ERP「采购订单列表」自动导出(xq0031_xq0032 插件内模块)。
|
||||
|
||||
自 workflows/XQ0032 purchase_order_list_export.py 迁移:
|
||||
全局搜索「采购订单列表」→ 选中编号 CGDDLB 项 → 点快捷方案 → 等查询完成 →
|
||||
选项 → 引出 → 按列表引出数据 → 下载保存(与需求31同目录)。
|
||||
快捷方案名由插件界面配置注入;交互逻辑与影刀版保持同源。
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from ..data import k3_common as kc
|
||||
|
||||
TAG = '[采购订单列表]'
|
||||
REPORT_KEYWORD = '采购订单列表' # 全局搜索关键字
|
||||
REPORT_NUMBER = 'CGDDLB' # 搜索结果编号(列表项唯一标识)
|
||||
|
||||
|
||||
# ================== 列表操作 ==================
|
||||
def _diag_search(page):
|
||||
"""探针:搜索失败时打印当前页面/下拉状态,定位是下拉没出来还是选择器不匹配。"""
|
||||
try:
|
||||
config.log(f'{TAG} [探针] 当前 URL: {(page.url or "")[:120]}')
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 读 URL 异常: {e}')
|
||||
try:
|
||||
items = page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2)
|
||||
config.log(f'{TAG} [探针] 下拉结果项数量: {len(items)}')
|
||||
for i, li in enumerate(items[:10]):
|
||||
try:
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.3)
|
||||
txt = li.ele('css:span[searchitem="text"]', timeout=0.3)
|
||||
config.log(f'{TAG} [探针] 第{i + 1}项: '
|
||||
f'number={num.text if num else "?"} '
|
||||
f'text={txt.text if txt else "?"} '
|
||||
f'displayed={li.states.is_displayed}')
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 枚举下拉异常: {e}')
|
||||
filter_visible = kc.ele_visible(
|
||||
page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=1)
|
||||
config.log(f'{TAG} [探针] 过滤按钮可见: {filter_visible}')
|
||||
|
||||
|
||||
def _back_home(page, erp='new'):
|
||||
"""回 K3 主控台首页:优先点顶部常驻「主页」按钮(SPA 内部跳转,一次清掉全部标签页/浮动窗口)。
|
||||
注意:禁止用 page.get(index.aspx) 整页回首页——K3 整页重新加载会重新走会话校验,
|
||||
连导时需求31的 tab 还开着,实测会被判为重复登录直接跳登录页(全局搜索图标随之消失、
|
||||
卡在「找不到全局搜索图标」)。主页按钮找不到时,退化为逐个关闭非激活标签页。"""
|
||||
if _click_home_btn(page):
|
||||
config.log(f'{TAG} 已点主页按钮回主控台')
|
||||
time.sleep(2.5)
|
||||
return
|
||||
config.log(f'{TAG} 未找到主页按钮,改为逐个关闭非激活标签页')
|
||||
for _ in range(5): # 关闭一个后 DOM 会刷新,多次扫描确保关干净
|
||||
closed = 0
|
||||
for li in page.eles('css:ul.k-tabstrip-items li', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
if (li.attr('aria-selected') or '').strip().lower() == 'true':
|
||||
continue # 保留当前激活 tab
|
||||
btn = li.ele('css:.k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
btn = li.ele('css:.k-tabstrip-close', timeout=0.5)
|
||||
if btn is None:
|
||||
continue
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
closed += 1
|
||||
time.sleep(0.6)
|
||||
except Exception:
|
||||
pass
|
||||
if closed == 0:
|
||||
break
|
||||
config.log(f'{TAG} 已关闭 {closed} 个残留标签页')
|
||||
|
||||
|
||||
def _click_home_btn(page):
|
||||
"""点击 K3 顶部常驻「主页」按钮(span.k-link.kd-item-home)回主控台首页。
|
||||
K3 控件 by_js click 有时不触发,先物理点击,失败再 by_js 兜底。"""
|
||||
if kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3):
|
||||
return True
|
||||
return kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3, by_js=True)
|
||||
|
||||
|
||||
def _active_tab_title(page):
|
||||
"""当前激活的主标签页标题。K3 多表单标签残留(物料收发汇总表/采购订单列表并存)时,
|
||||
必须确认操作的是激活的那个,否则会读到隐藏标签页的旧条数。"""
|
||||
try:
|
||||
t = page.ele('css:li[aria-selected="true"] .k-link', timeout=2)
|
||||
if t is not None:
|
||||
return (t.text or '').strip()
|
||||
except Exception:
|
||||
pass
|
||||
return ''
|
||||
|
||||
|
||||
def _open_report(page, erp='new'):
|
||||
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
|
||||
打开后必须校验主标签页已切到「采购订单列表」,否则可能停留在上一个报表标签、
|
||||
读到错页面的行数;校验不过回主控台首页重新搜索进入(最多 2 轮)。"""
|
||||
for _ in range(2):
|
||||
if _do_search_open(page):
|
||||
if REPORT_KEYWORD in _active_tab_title(page):
|
||||
config.log(f'{TAG} 已打开列表({REPORT_NUMBER})')
|
||||
return True
|
||||
config.log(f'{TAG} 列表标签页未激活(可能残留其它表单标签),清理后重新搜索')
|
||||
_back_home(page, erp)
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 打开「采购订单列表」失败:未能确认列表标签页激活')
|
||||
return False
|
||||
|
||||
|
||||
def _do_search_open(page):
|
||||
"""执行一次全局搜索并点选 CGDDLB 结果(不校验标签页是否真的激活,由 _open_report 负责)。"""
|
||||
if not kc.click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
config.log(f'{TAG} 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
config.log(f'{TAG} 找不到搜索输入框')
|
||||
return False
|
||||
sbox.clear()
|
||||
sbox.input(REPORT_KEYWORD)
|
||||
time.sleep(0.8) # 输入即出联想下拉;不按回车(回车=直接进第一个结果)
|
||||
|
||||
# 结果下拉列表中找编号为 CGDDLB 的「采购订单列表」项
|
||||
end = time.time() + 20
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.5)
|
||||
if num is None:
|
||||
continue
|
||||
num_text = (num.attr('title') or num.text or '').strip().upper()
|
||||
if num_text == REPORT_NUMBER.upper():
|
||||
li.click()
|
||||
time.sleep(2)
|
||||
if kc.ele_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=2):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 未找到编号 {REPORT_NUMBER} 的搜索结果项')
|
||||
_diag_search(page) # 探针:输出诊断信息
|
||||
return False
|
||||
|
||||
|
||||
def _open_filter(page):
|
||||
"""确保过滤窗口打开:已开则复用,未开则点「过滤」按钮(by_js 触发菜单项)。"""
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="_Filter-FSCHEMELIST"]', timeout=2):
|
||||
return True
|
||||
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return kc.ele_visible(page, 'css:[id*="_Filter-FSCHEMELIST"]', timeout=5)
|
||||
return False
|
||||
|
||||
|
||||
def _select_scheme(page, scheme):
|
||||
"""在过滤窗口方案树中选中目标方案(默认「默认方案(个人)」)。
|
||||
方案树节点结构:li.k-item > .k-in.kd-treenode-textcnt > .kd-treenode-text。
|
||||
注意:K3 树节点用 by_js click 不触发选中事件(现场验证),必须真实鼠标点击
|
||||
.k-in.kd-treenode-textcnt 节点;选中成功后界面出现 SelectedSchemeItemControlTemplate。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.k-window li.k-item', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
t = li.ele('css:.kd-treenode-text', timeout=0.5)
|
||||
if t is None or scheme not in (t.text or ''):
|
||||
continue
|
||||
# 已选中:选中模板(SelectedSchemeItemControlTemplate)的文本须是目标方案,
|
||||
# 否则可能是上次选的其它方案,误判会导出错误数据
|
||||
cur = page.ele('css:.SelectedSchemeItemControlTemplate', timeout=1)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 方案已是: {t.text.strip()}')
|
||||
return True
|
||||
# 真实鼠标点击节点外层 .k-in.kd-treenode-textcnt(by_js 不触发选中)
|
||||
node = t.parent() # .k-in.kd-treenode-textcnt
|
||||
if node is None or not node.states.is_displayed:
|
||||
node = t
|
||||
try:
|
||||
ac.move_to(node)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
node.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
# 确认选中:出现 SelectedSchemeItemControlTemplate 才算点击成功
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate', timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
# 未生效:可能点到文本被全选,改为点 li 下的 .kd-treenode-textcnt 外层再试一次
|
||||
try:
|
||||
cnt = li.ele('css:.kd-treenode-textcnt', timeout=1)
|
||||
if cnt is not None and cnt.states.is_displayed:
|
||||
ac.move_to(cnt)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
time.sleep(0.8)
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate',
|
||||
timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 过滤窗口方案树中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _submit_filter(page):
|
||||
"""点过滤窗口「确定」触发查询。注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库等其它
|
||||
过滤面板的同 id 按钮,用 :not + .k-window 限定,防止误点。"""
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
config.log(f'{TAG} 找不到过滤窗口确定按钮')
|
||||
return False
|
||||
config.log(f'{TAG} 已提交过滤查询')
|
||||
return True
|
||||
|
||||
|
||||
def _read_rowcount(page):
|
||||
"""读分页栏行数统计(span[data-kdid="rowcount_pagerlist2"],文本形如「共519行」)。
|
||||
返回 (文本, 条数);未找到/未显示返回 (None, -1)。"""
|
||||
try:
|
||||
for el in page.eles('css:span[data-kdid="rowcount_pagerlist2"]', timeout=1):
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
continue
|
||||
txt = (el.text or '').strip()
|
||||
m = re.search(r'共\s*(\d+)\s*行', txt)
|
||||
return txt, (int(m.group(1)) if m else -1)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return None, -1
|
||||
|
||||
|
||||
def _wait_progress(page, timeout=30):
|
||||
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
|
||||
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。
|
||||
- 条数可用(数字):行数变 0 / 变化即完成。
|
||||
- 条数不可用:K3 未翻到最后一页时总行数显示「共*行」星号(读不到数字,现场确认),
|
||||
查询中不会有数字信号,仅等一个短窗口(NO_COUNT_GAP)让 K3 算出行数;
|
||||
窗口内星号→数字出现即视为查询完成,始终无数字 → 按查询已完成直接继续
|
||||
(避免 30s 白等,由上层重试机制兜底)。
|
||||
超时不再判定失败:现场结论查询可能太快、行数不经历 0 直接保持旧值,死等会白白卡
|
||||
几分钟。故超时后直接继续导出(由上层重试机制兜底,避免整单卡死)。"""
|
||||
txt0, init_cnt = _read_rowcount(page)
|
||||
if init_cnt >= 0:
|
||||
config.log(f'{TAG} 当前条数: {init_cnt},等待查询刷新...')
|
||||
elif txt0:
|
||||
config.log(f'{TAG} 当前条数: {txt0}(星号=总行数未计算),等待查询刷新...')
|
||||
else:
|
||||
config.log(f'{TAG} 当前条数: 无,等待查询刷新...')
|
||||
if init_cnt < 0:
|
||||
# 条数不可用:短窗口内等待 K3 算出数字;星号→数字出现即完成,否则直接继续
|
||||
NO_COUNT_GAP = 10
|
||||
end = time.time() + NO_COUNT_GAP
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt > 0:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 条数不可用({txt0 or "无"}),按查询已完成直接继续导出')
|
||||
return True
|
||||
saw_reset = False
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt == 0:
|
||||
saw_reset = True # 先变 0:查询已触发,正在刷新
|
||||
elif cnt > 0:
|
||||
if saw_reset or cnt != init_cnt:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 等待查询完成超时(行数未刷新,直接继续导出)')
|
||||
return True
|
||||
|
||||
|
||||
def _export_all_pages(page):
|
||||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 按列表引出数据。
|
||||
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||||
让子菜单展开后用 move_to+click 点中「按列表引出数据」;不点 span 文本,避免全选。
|
||||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。
|
||||
本列表页与需求31不同:选项=tbOptionLists,引出=tbInputOutput,目标=按列表引出数据(tbOutput)。"""
|
||||
ac = page.actions
|
||||
|
||||
def _clickable(span):
|
||||
"""内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。"""
|
||||
try:
|
||||
a = span.closest('css:a')
|
||||
if a is not None and a.tag.lower() == 'a' and a.states.is_displayed:
|
||||
return a
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
li = span.closest('css:li')
|
||||
if li is not None and li.states.is_displayed:
|
||||
return li
|
||||
except Exception:
|
||||
pass
|
||||
return span
|
||||
|
||||
# 1. 点「选项」打开配置菜单(点其 a/li,避开文本)
|
||||
opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点选项失败')
|
||||
return False
|
||||
time.sleep(1.2)
|
||||
|
||||
# 2. 定位「引出」(splitbutton)
|
||||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到导出(引出)按钮')
|
||||
return False
|
||||
|
||||
def _trigger():
|
||||
"""悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。"""
|
||||
try:
|
||||
ar = split.parent().ele('css:span.k-icon', timeout=1)
|
||||
if ar is not None and ar.states.is_displayed:
|
||||
return ar
|
||||
except Exception:
|
||||
pass
|
||||
return _clickable(split)
|
||||
|
||||
trigger = _trigger()
|
||||
|
||||
# 3. 悬浮展开「按列表引出数据」子菜单
|
||||
target = None
|
||||
for _ in range(4):
|
||||
try:
|
||||
ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
for _ in range(3):
|
||||
try:
|
||||
trigger.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到按列表引出数据')
|
||||
return False
|
||||
|
||||
# 4. 光标从「引出」连续移入「按列表引出数据」再点击(悬浮链不断,菜单不收起)
|
||||
try:
|
||||
ac.move_to(_clickable(target))
|
||||
time.sleep(0.5)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
target.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点击按列表引出数据失败')
|
||||
return False
|
||||
config.log(f'{TAG} 已触发按列表引出数据')
|
||||
return True
|
||||
|
||||
|
||||
def _click_quick_scheme(page, scheme):
|
||||
"""直接点击列表页顶部快捷方案条中的目标方案,无需打开过滤窗口。
|
||||
结构:div[filter-role="filterschemecontent"] > div.SchemeItemControlTemplate(含方案名,
|
||||
选中的为 SelectedSchemeItemControlTemplate)。
|
||||
注意:K3 控件用 by_js click 可能不触发,优先真实鼠标点击。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for item in page.eles(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div[class*="SchemeItemControlTemplate"]', timeout=2):
|
||||
try:
|
||||
if not item.states.is_displayed:
|
||||
continue
|
||||
txt = (item.text or '').strip()
|
||||
if txt != scheme: # 精确匹配:避免「默认方案」误命中「采购订单宽表默认方案」
|
||||
continue
|
||||
cls = item.attr('class') or ''
|
||||
if 'Selected' in cls:
|
||||
config.log(f'{TAG} 快捷方案已是: {txt}')
|
||||
return True
|
||||
try:
|
||||
ac.move_to(item)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
item.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
# 确认选中:快捷条中 Selected 方案变为目标方案
|
||||
cur = page.ele(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div.SelectedSchemeItemControlTemplate', timeout=2)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 已点选快捷方案: {txt}')
|
||||
return True
|
||||
# 未确认选中:返回 False 走过滤窗口回退,防止把旧数据当本次结果
|
||||
config.log(f'{TAG} 点击快捷方案未确认选中: {txt}')
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 快捷方案条中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _run_once(page, scheme):
|
||||
"""直接点快捷方案 → 等查询 → 按列表引出数据。
|
||||
快捷方案条不存在时回退到过滤窗口选方案。"""
|
||||
if _click_quick_scheme(page, scheme):
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
else:
|
||||
# 回退:过滤窗口选方案
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if not _select_scheme(page, scheme):
|
||||
return False
|
||||
if not _submit_filter(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
return _export_all_pages(page)
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def run(page, save_dir, scheme, erp='new', progress=None):
|
||||
"""先全局搜索打开列表(校验列表标签页已激活),再按方案导出(快捷方案 → 等查询 → 引出 → 下载,重试 3 次)。
|
||||
每次导出前校验仍处于「采购订单列表」标签页,不对则清理残留标签页后重新搜索进入。
|
||||
progress(done, total) 为整体进度回调;返回保存文件路径,失败返回 None。"""
|
||||
# 连导场景(需求31物料收发汇总后接需求32)会残留「物料收发汇总表」标签页:
|
||||
# 多标签下 page.eles 全页匹配可能命中残留标签页里的元素,干扰后续操作。
|
||||
# 先关掉非激活标签页(SPA 内关 tab,不能整页回 index.aspx,否则跳登录页),
|
||||
# 确保从干净状态开始本次导出。
|
||||
_back_home(page, erp)
|
||||
if not _open_report(page, erp):
|
||||
raise RuntimeError("打开「采购订单列表」失败:全局搜索未命中 CGDDLB 列表(详见日志)")
|
||||
new_name = f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx'
|
||||
config.log(f'{TAG} 导出文件: {new_name}')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
config.log(f'{TAG} 第 {attempt}/{config.RETRY_MAX} 次导出')
|
||||
# 做之前校验:当前激活标签必须是「采购订单列表」,否则回首页重新搜索进入
|
||||
if REPORT_KEYWORD not in _active_tab_title(page):
|
||||
config.log(f'{TAG} 当前标签页不是「采购订单列表」,清理残留标签页后重新搜索进入')
|
||||
if not _open_report(page, erp):
|
||||
break
|
||||
if _run_once(page, scheme):
|
||||
if kc.download_file(page, save_dir, new_name, tag=TAG):
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return str(save_dir / new_name)
|
||||
kc.reset_filter_state(page, tag=TAG) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
config.log(f'{TAG} 重试 {config.RETRY_MAX} 次均失败')
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0031_xq0032",
|
||||
"name": "ERP物料收发汇总-采购订单报表导出",
|
||||
"version": "1.0.10",
|
||||
"description": "金蝶K3Cloud报表自动导出:物料收发汇总表+ 采购订单列表,支持新旧系统、下载全部仓库后按所选仓库中文名自动筛选、日期多选(含自定义区间),个性化配置保存在本机",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0031_xq0032"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "物料收发汇总表", "采购订单列表"],
|
||||
"description": "需求31=物料收发汇总表(按仓库/日期多档导出),需求32=采购订单列表(按方案导出)"
|
||||
},
|
||||
"erp_system": {
|
||||
"type": "string",
|
||||
"title": "ERP系统",
|
||||
"default": "新版",
|
||||
"enum": ["新版", "旧版"],
|
||||
"description": "新版 criterion.erp.37du.co / 旧版 erp.37du.co"
|
||||
},
|
||||
"erp_username": {
|
||||
"type": "string",
|
||||
"title": "ERP登录账号",
|
||||
"default": "",
|
||||
"description": "用户自己的ERP账号,保存在本机下次免填"
|
||||
},
|
||||
"erp_password": {
|
||||
"type": "string",
|
||||
"title": "ERP登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"org_name": {
|
||||
"type": "string",
|
||||
"title": "查询组织",
|
||||
"default": "99.01 重庆金七象供应链管理有限公司",
|
||||
"description": "新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,插件界面切换ERP系统自动带出"
|
||||
},
|
||||
"stock_codes": {
|
||||
"type": "array",
|
||||
"title": "仓库编码(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201", "03010127"]
|
||||
},
|
||||
"default": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"],
|
||||
"description": "查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选保存;留空=全部仓库不筛选。新版默认=五个三方仓;旧版默认=03010127(代管仓,切换ERP系统自动带出)"
|
||||
},
|
||||
"date_options": {
|
||||
"type": "array",
|
||||
"title": "日期选项(多选,逐个导出)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["60D", "30D", "15D", "7D", "3D"]
|
||||
},
|
||||
"default": ["60D", "30D", "15D", "7D", "3D"],
|
||||
"description": "N天=今天往前推N天;可混入自定义区间如 2026-01-01~2026-09-15"
|
||||
},
|
||||
"scheme_name": {
|
||||
"type": "string",
|
||||
"title": "采购订单快捷方案",
|
||||
"default": "默认方案(个人)",
|
||||
"description": "需求32使用的过滤方案名(精确匹配)"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/采购计划报表_日期"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""report 层 - 「物料收发汇总表」各档报表合并汇总(xq0031_xq0032 插件内模块)。
|
||||
|
||||
与原影刀版 merge_summary.py 同源:把同一保存目录下各档「物料收发汇总表_标签.xlsx」
|
||||
合并为一个汇总文件「物料收发汇总表_<日期>.xlsx」:
|
||||
- 每个报表第 4 行是表头;合并时第 4 行表头第一列新增「时间区间」字段
|
||||
- 数据行第一列填入报表标签(60D / 30D / 自定义日期区间 ...)
|
||||
- 跳过每表最后一行汇总行
|
||||
返回汇总文件路径;无可合并报表返回 None。
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
from .. import config
|
||||
|
||||
TAG = '[物料收发汇总表]'
|
||||
|
||||
|
||||
def merge_summary(save_dir):
|
||||
m = re.search(r'(\d{4}-\d{2}-\d{2})', str(save_dir))
|
||||
date_tag = m.group(1) if m else datetime.now().strftime('%Y-%m-%d')
|
||||
out = Path(save_dir) / f'{config.FILE_PREFIX_31}_{date_tag}.xlsx'
|
||||
|
||||
def _label(name):
|
||||
m = re.match(rf'^{config.FILE_PREFIX_31}_(.+)\.xlsx$', name)
|
||||
return m.group(1) if m else None
|
||||
|
||||
files = sorted(p for p in Path(save_dir).glob(f'{config.FILE_PREFIX_31}_*.xlsx')
|
||||
if _label(p.name) and p.name != out.name)
|
||||
if not files:
|
||||
config.log(f'{TAG} 目录下没有可合并的报表: {save_dir}')
|
||||
return None
|
||||
|
||||
header = None
|
||||
all_rows, labels = [], []
|
||||
for f in files:
|
||||
label = _label(f.name)
|
||||
try:
|
||||
wb = openpyxl.load_workbook(f, data_only=True)
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [跳过] 无法读取的报表: {f.name}({e})')
|
||||
continue
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
h = [ws.cell(4, c).value for c in range(1, ws.max_column + 1)]
|
||||
if header is None:
|
||||
header = h
|
||||
elif h != header:
|
||||
config.log(f'{TAG} [跳过] 表头不一致: {f.name}')
|
||||
continue
|
||||
# 数据从第 5 行起,跳过最后一行汇总行
|
||||
n = 0
|
||||
for r in range(5, ws.max_row):
|
||||
row = [ws.cell(r, c).value for c in range(1, ws.max_column + 1)]
|
||||
if any(v is not None and str(v).strip() != '' for v in row):
|
||||
all_rows.append([label] + row)
|
||||
n += 1
|
||||
labels.append(label)
|
||||
config.log(f'{TAG} [{label}] 数据 {n} 行 <- {f.name}')
|
||||
wb.close()
|
||||
|
||||
if not all_rows:
|
||||
config.log(f'{TAG} 没有可合并的数据')
|
||||
return None
|
||||
if out.exists():
|
||||
out.unlink()
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'Sheet1'
|
||||
# 前 3 行说明,保持「表头在第 4 行」的结构与单报表一致
|
||||
ws.cell(1, 1, '物料收发汇总表(汇总)')
|
||||
ws.cell(2, 1, f'生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
||||
ws.cell(3, 1, f'合并报表: {", ".join(labels)}')
|
||||
# 第 4 行表头:第一列插入「时间区间」
|
||||
ws.cell(4, 1, '时间区间')
|
||||
for c, v in enumerate(header, start=2):
|
||||
ws.cell(4, c, v)
|
||||
# 数据(第一列为报表标签)
|
||||
for r, row in enumerate(all_rows, start=5):
|
||||
for c, v in enumerate(row, start=1):
|
||||
ws.cell(r, c, v)
|
||||
wb.save(out)
|
||||
wb.close()
|
||||
config.log(f'{TAG} 已生成汇总文件: {out}(共 {len(all_rows)} 条数据,{len(labels)} 个报表)')
|
||||
return out
|
||||
@@ -0,0 +1 @@
|
||||
DrissionPage>=4.0
|
||||
@@ -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>ERP报表导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0031-xq0032-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,380 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<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>
|
||||
|
||||
<!-- 执行配置 -->
|
||||
<el-card shadow="never" class="card">
|
||||
<template #header>
|
||||
<span class="card-title">执行配置</span>
|
||||
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
|
||||
</template>
|
||||
<el-form label-width="120px" label-position="right">
|
||||
<div class="grid">
|
||||
<el-form-item label="执行模式">
|
||||
<el-select v-model="form.mode" :disabled="running">
|
||||
<el-option label="两个都导" value="两个都导" />
|
||||
<el-option label="物料收发汇总表" value="物料收发汇总表" />
|
||||
<el-option label="采购订单列表" value="采购订单列表" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="ERP系统">
|
||||
<el-radio-group v-model="form.erp_system" :disabled="running">
|
||||
<el-radio-button value="新版">新版</el-radio-button>
|
||||
<el-radio-button value="旧版">旧版</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<el-form-item label="登录账号">
|
||||
<el-input v-model="form.erp_username" placeholder="你的ERP登录账号" :disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录密码">
|
||||
<el-input v-model="form.erp_password" type="password" show-password placeholder="仅保存在本机,下次免填"
|
||||
:disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="查询组织">
|
||||
<el-input v-model="form.org_name" :disabled="running" clearable
|
||||
placeholder="新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,切换ERP系统自动带出" />
|
||||
<div class="tip">切换 ERP 系统时会自动带出该系统默认组织;如已自定义组织名则保持不变</div>
|
||||
</el-form-item>
|
||||
|
||||
<template v-if="form.mode !== '采购订单列表'">
|
||||
<el-form-item label="仓库编码">
|
||||
<el-select v-model="form.stock_codes" multiple filterable allow-create default-first-option
|
||||
:reserve-keyword="false" placeholder="勾选预设或输入新编码后回车" :disabled="running" class="wide">
|
||||
<el-option v-for="c in STOCK_PRESETS" :key="c" :value="c" :label="c" />
|
||||
</el-select>
|
||||
<div class="tip">查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选;留空=全部不筛选。切换 ERP 系统自动带出该系统默认仓库(新版=五个三方仓;旧版=03010127 代管仓)
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="日期选项">
|
||||
<el-select v-model="form.date_options" multiple filterable allow-create default-first-option
|
||||
:reserve-keyword="false" placeholder="勾选预设,或输入自定义区间后回车" :disabled="running" class="wide">
|
||||
<el-option v-for="d in DATE_PRESETS" :key="d" :value="d" :label="d" />
|
||||
</el-select>
|
||||
<div class="tip">N天 = 今天往前推N天,逐档导出;自定义区间格式:2026-01-01~2026-09-15(输入后回车)</div>
|
||||
</el-form-item>
|
||||
</template>
|
||||
|
||||
<div class="grid">
|
||||
<el-form-item v-if="form.mode !== '物料收发汇总表'" label="快捷方案">
|
||||
<el-input v-model="form.scheme_name" :disabled="running" clearable placeholder="采购订单列表使用的过滤方案名(精确匹配)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable placeholder="留空 = 桌面/采购计划报表_今天日期" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<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>
|
||||
|
||||
<!-- 运行状态:进度条 + 日志位置提示(日志实时显示在壳子下方日志区) -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="8" class="status-bar" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { connectWS, getRun, loadConfig, saveConfig, startRun, stopRun } from './api'
|
||||
|
||||
const STOCK_PRESETS = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201', '03010127']
|
||||
const DATE_PRESETS = ['60D', '30D', '15D', '7D', '3D']
|
||||
|
||||
// 新旧系统各自的默认查询组织(旧系统登录已不再默认该组织,须在过滤界面显式选择)
|
||||
const ORG_DEFAULTS = {
|
||||
'新版': '99.01 重庆金七象供应链管理有限公司',
|
||||
'旧版': '99.01.07.01.01 石桥铺会馆',
|
||||
}
|
||||
|
||||
// 新旧系统各自的默认仓库编码(旧版登录默认仓库 = 03010127 代管仓)
|
||||
const STOCK_DEFAULTS = {
|
||||
'新版': ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201'],
|
||||
'旧版': ['03010127'],
|
||||
}
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
mode: '两个都导',
|
||||
erp_system: '新版',
|
||||
erp_username: '',
|
||||
erp_password: '',
|
||||
org_name: ORG_DEFAULTS['新版'],
|
||||
stock_codes: [...STOCK_DEFAULTS['新版']],
|
||||
date_options: [...DATE_PRESETS],
|
||||
scheme_name: '默认方案(个人)',
|
||||
save_dir: '',
|
||||
})
|
||||
|
||||
const form = reactive(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()
|
||||
Object.keys(form).forEach((k) => {
|
||||
if (saved[k] !== undefined && saved[k] !== null && saved[k] !== '') form[k] = saved[k]
|
||||
if (k === 'stock_codes' && Array.isArray(saved[k])) form.stock_codes = saved[k]
|
||||
if (k === 'date_options' && Array.isArray(saved[k])) form.date_options = saved[k]
|
||||
})
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖),执行中不改存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
// 切换 ERP 系统:组织名/仓库编码未自定义(空 或 仍是另一系统默认)时自动带出本系统默认
|
||||
watch(() => form.erp_system, (sys) => {
|
||||
if (!loaded.value || running.value) return
|
||||
const orgOther = sys === '新版' ? ORG_DEFAULTS['旧版'] : ORG_DEFAULTS['新版']
|
||||
if (!form.org_name || form.org_name === orgOther) form.org_name = ORG_DEFAULTS[sys]
|
||||
const stkOther = sys === '新版' ? STOCK_DEFAULTS['旧版'] : STOCK_DEFAULTS['新版']
|
||||
if (!form.stock_codes.length || sameArray(form.stock_codes, stkOther)) {
|
||||
form.stock_codes = [...STOCK_DEFAULTS[sys]]
|
||||
}
|
||||
})
|
||||
|
||||
function sameArray(a, b) {
|
||||
if (a.length !== b.length) return false
|
||||
const s = new Set(a)
|
||||
return b.every((x) => s.has(x))
|
||||
}
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(JSON.parse(JSON.stringify(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() {
|
||||
const sys = form.erp_system // 保留当前选择的 ERP 系统
|
||||
Object.assign(form, DEFAULTS())
|
||||
form.erp_system = sys
|
||||
form.org_name = ORG_DEFAULTS[sys] // 恢复默认时按当前系统默认组织
|
||||
form.stock_codes = [...STOCK_DEFAULTS[sys]] // 恢复默认时按当前系统默认仓库
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
function validate() {
|
||||
if (!form.erp_username.trim() || !form.erp_password) {
|
||||
ElMessage.warning('请先填写 ERP 登录账号和密码')
|
||||
return false
|
||||
}
|
||||
if (form.mode !== '采购订单列表') {
|
||||
if (!form.stock_codes.length) { ElMessage.warning('请至少选择一个仓库编码'); return false }
|
||||
if (!form.date_options.length) { ElMessage.warning('请至少选择一个日期选项'); return false }
|
||||
}
|
||||
if (form.mode !== '物料收发汇总表' && !form.scheme_name.trim()) {
|
||||
ElMessage.warning('请填写采购订单快捷方案名')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
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()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(JSON.parse(JSON.stringify(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 }
|
||||
}
|
||||
|
||||
async 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 }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 4px 2px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
float: right;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #67c23a;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
flex: 1;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 1.6;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 16px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,50 @@
|
||||
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
|
||||
export const PLUGIN_ID = 'xq0031_xq0032'
|
||||
|
||||
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 (e) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
export function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
@@ -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,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0031_xq0032/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0031_xq0032/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5180,
|
||||
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>ERP报表导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-B7DSB6ed.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-C1QhPHbp.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user