chore: 清理废弃插件与冗余文档,重构项目目录结构
1. 删除旧版xq0031_xq0032插件的冗余UI源码与配置文件 2. 迁移并标准化XQ0001-0100系列需求的插件、文档与工作流目录 3. 清理过期的需求列表、评分文档与流程底稿 4. 更新.gitignore匹配规则,适配新的目录结构
This commit is contained in:
@@ -0,0 +1,467 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: pre_entry_roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-27
|
||||
@Description: 预入职台账自定义导出(排班异常识别 步骤2-预入职,影刀版,单文件自包含)。
|
||||
复用「37duHR登录」指令写入的共享 cookies,通过 DrissionPage 浏览器自动化操作:
|
||||
进入预入职台账页 -> 组织机构(集团) -> 点击「已入职」-> 更多搜索
|
||||
-> 输入预入职日期(近30天)-> 筛选 -> 自定义导出 -> 选择模板「排班异常识别导出」
|
||||
-> 确认导出,接收下载文件重命名为《预入职台账.xlsx》(表头在第 2 行)。
|
||||
与调动台账导出(transfer_roster_export.py)流程基本一致,仅页面地址、tab 文案、
|
||||
日期占位符、文件名不同。
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage
|
||||
|
||||
登录(共享登录态,本脚本仅读取共享 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令完成登录,再运行本流程。
|
||||
|
||||
运行:直接执行本文件即可(会弹出浏览器窗口,请勿关闭)。
|
||||
输出目录默认 D:\\资料\\人资\\排班异常识别,可用环境变量 pre_entry_output_dir 覆盖。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:必须预先装齐,不懒加载) ====================
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# 预入职台账页地址 & 导出模板(与 app/service/hrbp/ehr/common/config.py 一致)
|
||||
PRE_ENTRY_ROSTER_URL = ("https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-07406&nworktoday-40175-24311|/RedseaPlatform/hrRoster/10fe9cd6-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E9%A2%84%E5%85%A5%E8%81%8C%E5%8F%B0%E8%B4%A6")
|
||||
TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出"
|
||||
|
||||
# 流程步骤所用文案常量(aa.md 提供)
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
TAB_ONBOARDED = "已入职" # 预入职台账「已入职」tab(只导已入职人员)
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索"
|
||||
PRE_ENTRY_RANGE_PLACEHOLDER = "请选择预入职日期"
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
RETRY_TIMES = 3 # 单次导出失败重试次数(AGENTS.md:最大重试3次)
|
||||
|
||||
# 输出目录 & 文件名
|
||||
OUTPUT_DIR = os.getenv("pre_entry_output_dir") or r"D:\资料\人资\排班异常识别"
|
||||
SAVE_NAME = "预入职台账.xlsx"
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,影刀版约定) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies(由「37duHR登录」指令写入)。"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在有效的 HR 登录态;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令完成登录,"
|
||||
"或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== 预入职日期范围(近30天) ====================
|
||||
def get_pre_entry_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算预入职日期筛选范围,返回 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_more_search_button(page):
|
||||
"""定位当前活跃 tab 的「更多搜索」按钮(仅取可见的那个,避免展开错 tab)。"""
|
||||
btns = page.eles('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btns:
|
||||
btns = page.eles('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btns:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
return btn if _is_displayed(btn) else None
|
||||
for b in btns:
|
||||
if _is_displayed(b):
|
||||
return b
|
||||
logger.warning("未找到可见的「更多搜索」按钮(DOM 中共 %d 个)", len(btns))
|
||||
return None
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""展开当前活跃 tab 的「更多搜索」popover,返回其内容元素;失败返回 None。"""
|
||||
btn = _find_more_search_button(page)
|
||||
if not btn:
|
||||
return None
|
||||
for _ in range(3):
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return popover
|
||||
try:
|
||||
btn.run_js('this.click();')
|
||||
except Exception:
|
||||
btn.click()
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return None
|
||||
|
||||
|
||||
def _click_filter(page, popover):
|
||||
"""点击活跃 tab「更多搜索」弹层底部的「筛选」按钮(限定在弹出容器内)。"""
|
||||
result = popover.run_js(
|
||||
'var btns=this.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn";'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _find_visible_range_input(page, placeholder):
|
||||
"""在页面级查找可见的预入职日期选择器(页面宽/窄布局不同,取可见的第一个)。"""
|
||||
rngs = page.eles(f'css:div.split-datetime-range[placeholder="{placeholder}"]', timeout=3)
|
||||
for r in rngs:
|
||||
if _is_displayed(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def _fill_range(page, rng, start, end):
|
||||
"""填入日期范围并回车确认。"""
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到预入职日期起止输入框")
|
||||
start_input.input(start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("预入职日期已设置:%s ~ %s", start, end)
|
||||
|
||||
|
||||
def _set_pre_entry_date_range(page, start=None, end=None):
|
||||
"""设置「预入职日期」筛选范围(近30天)并应用筛选。"""
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("设置预入职日期范围:%s ~ %s", start, end)
|
||||
popover = _open_more_search(page)
|
||||
if not popover:
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置预入职日期")
|
||||
rng = _find_visible_range_input(page, PRE_ENTRY_RANGE_PLACEHOLDER)
|
||||
if not rng:
|
||||
rng = popover.ele(
|
||||
f'css:div.split-datetime-range[placeholder="{PRE_ENTRY_RANGE_PLACEHOLDER}"]', timeout=5)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「预入职日期」选择器")
|
||||
_fill_range(page, rng, start, end)
|
||||
_click_filter(page, popover)
|
||||
|
||||
|
||||
# ==================== 打开台账页并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问预入职台账页面;若被重定向到登录页则提示先完成「37duHR登录」。"""
|
||||
page.get(PRE_ENTRY_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError(
|
||||
"HR 登录态已失效。\n"
|
||||
"请先重新运行「37duHR登录」指令,或本地执行 python workflows/share/hr_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
logger.info("已进入预入职台账页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 预入职台账导出主流程(aa.md 步骤) ====================
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||||
if org_tab:
|
||||
org_tab.click()
|
||||
logger.info("已点击左侧「组织机构」")
|
||||
time.sleep(WAIT_MID)
|
||||
else:
|
||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||||
_click_text(page, TAB_ORG)
|
||||
time.sleep(WAIT_MID)
|
||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||||
if not group:
|
||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||||
if not group:
|
||||
raise RuntimeError("组织树中未找到「集团」节点")
|
||||
group.click()
|
||||
logger.info("已点击组织树根节点「集团」")
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
|
||||
def _click_onboarded_tab(page):
|
||||
"""点击「已入职」tab,只保留已入职的预入职人员。"""
|
||||
tab = page.ele(f'xpath://div[contains(@class,"tab-info")]//*[normalize-space(.)="{TAB_ONBOARDED}"]',
|
||||
timeout=10)
|
||||
if not tab:
|
||||
_click_text(page, TAB_ONBOARDED)
|
||||
return
|
||||
tab.click()
|
||||
logger.info("已点击「%s」tab", TAB_ONBOARDED)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _open_custom_export_dialog(page):
|
||||
"""点击「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||||
tpl_label = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||||
if tpl_label and _is_displayed(tpl_label):
|
||||
logger.info("导出弹窗已打开,跳过「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
return
|
||||
btn = page.ele('xpath://button[normalize-space(.)="自定义导出"]', timeout=15)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://*[contains(@class,"btn") and normalize-space(.)="自定义导出"]', timeout=5)
|
||||
if not btn:
|
||||
raise RuntimeError("未找到「自定义导出」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=TEMPLATE_SHIFT_ABNORMAL):
|
||||
"""选择导出模板「排班异常识别导出」。"""
|
||||
tpl = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||||
'/following-sibling::div[contains(@class,"el-select")]',
|
||||
timeout=15,
|
||||
)
|
||||
if not tpl:
|
||||
raise RuntimeError("未找到「模板」下拉框")
|
||||
panel = None
|
||||
for _ in range(3):
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||||
if panel and _is_displayed(panel):
|
||||
break
|
||||
tpl.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
if not panel:
|
||||
raise RuntimeError("模板下拉面板未能展开")
|
||||
opt = panel.ele(f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||||
timeout=5)
|
||||
if not opt:
|
||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||||
opt.click()
|
||||
logger.info("已选择模板:%s", template_name)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_confirm_export(page):
|
||||
"""点击「确认导出」,触发下载。"""
|
||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||||
timeout=10)
|
||||
if not btn:
|
||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「确认导出」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ==================== 下载等待 ====================
|
||||
def _wait_download(download_dir, before, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
deadline = time.time() + timeout
|
||||
last_sizes = {}
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
files = os.listdir(download_dir)
|
||||
except Exception:
|
||||
files = []
|
||||
for f in files:
|
||||
if f in before or f.startswith('~$'):
|
||||
continue
|
||||
if f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||||
continue
|
||||
p = os.path.join(download_dir, f)
|
||||
if not os.path.isfile(p):
|
||||
continue
|
||||
try:
|
||||
size = os.path.getsize(p)
|
||||
except Exception:
|
||||
continue
|
||||
if size <= 0:
|
||||
continue
|
||||
if last_sizes.get(p) == size:
|
||||
logger.info("预入职台账导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||||
return p
|
||||
last_sizes[p] = size
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ==================== 单次导出(带重试,AGENTS.md:最大3次) ====================
|
||||
def _export_one(page, download_dir, template_name, start=None, end=None):
|
||||
"""执行单次预入职台账导出(筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(1, RETRY_TIMES + 1):
|
||||
logger.info(">>> 预入职台账导出 第 %d/%d 次(模板:%s)", attempt, RETRY_TIMES, template_name)
|
||||
try:
|
||||
_set_pre_entry_date_range(page, start, end)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
# 触发下载前捕获目录快照,避免下载过快时真实文件被误判为已存在而漏检
|
||||
before = set(os.listdir(download_dir))
|
||||
_click_confirm_export(page)
|
||||
path = _wait_download(download_dir, before)
|
||||
logger.info(">>> 预入职台账导出完成")
|
||||
return path
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.exception("预入职台账导出失败(第 %d 次),尝试重试:", attempt)
|
||||
time.sleep(WAIT_MID)
|
||||
raise RuntimeError(f"预入职台账导出连续失败:{last_err}")
|
||||
|
||||
|
||||
# ==================== 对外入口 ====================
|
||||
def export_pre_entry_roster(download_dir: str = None, template_name: str = TEMPLATE_SHIFT_ABNORMAL,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行预入职台账自定义导出(预入职日期近30天),返回下载后的 xlsx 文件路径。"""
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("===== 开始预入职台账导出(模板:%s,日期:%s ~ %s),下载目录:%s =====",
|
||||
template_name, start, end, download_dir)
|
||||
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
logger.info("加载共享 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入共享 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
_click_onboarded_tab(page)
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
path = _export_one(page, download_dir, template_name, start, end)
|
||||
|
||||
if output_path:
|
||||
output_path = os.path.abspath(output_path)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
shutil.move(path, output_path)
|
||||
path = output_path
|
||||
elif path.endswith('.xlsx'):
|
||||
renamed = os.path.join(download_dir, SAVE_NAME)
|
||||
if os.path.abspath(path) != os.path.abspath(renamed):
|
||||
shutil.move(path, renamed)
|
||||
path = renamed
|
||||
|
||||
logger.info("===== 预入职台账导出完成:%s =====", path)
|
||||
return path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
"""影刀入口:导出预入职台账。缺依赖/未登录会先行报错退出。"""
|
||||
try:
|
||||
out = export_pre_entry_roster()
|
||||
logger.info("===== 预入职台账导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("预入职台账导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,898 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-27
|
||||
@Description: 排班异常识别 + 钉钉单聊推送 + 汇总群聊推送(第三步,影刀版,单文件自包含)。
|
||||
读取第二步导出的《调动台账.xlsx》《预入职台账.xlsx》(表头均在 2 行),结合 HR 排班接口
|
||||
判断每人排班是否异常,生成异常明细(写回一份 Excel + 输出到全局变量),并通知各店长:
|
||||
最后一步由共享指令「37du钉钉推送」(workflows/share/dingtalk_dws_push.py)完成发送,
|
||||
本脚本只负责「按异常人员工号解析对应店长 → 按店长分组 → 构造通知内容 → 写入影刀全局变量 messages」。
|
||||
单聊消息结构与共享指令 main(messages) 完全一致(五元组 (msg_type, name, user_id, content, file_path),
|
||||
此处均为 ("text", 店长姓名, 店长工号, 纯文本内容, ""))。
|
||||
|
||||
汇总群聊推送(识别出异常后追加):
|
||||
将《排班异常名单_时间戳.xlsx》汇总表格 + 汇总文案推送到指定群聊(默认「金色印象人行条线沟通工作群」,
|
||||
可用环境变量 shift_abnormal_push_group 覆盖;shift_abnormal_push_at_all="1" 时 @所有人)。
|
||||
文案:【今日门店HR系统排班异常提示】今日提示日期{核查窗口起始日}至{核查窗口截止日},
|
||||
具体提示名单详见表格,已单独钉钉信息提示对应店长。
|
||||
群聊消息以 dict(含 group 键)追加到全局变量 messages,共享指令 main(messages) 自动识别为群聊
|
||||
并发送文本+附件 Excel,无需单独配置推送通道。
|
||||
|
||||
判断口径(与 app 版 shift_abnormal_check.py 一致):
|
||||
- 调动台账:按「调动时间」近 {DAYS} 天;「现职位序列」含「职能」按「现单位」比对、
|
||||
其余按「现四级部门」比对;用 rf_s_kq_work_date_query 接口按比对部门查出该部门
|
||||
全部排班集合,当日排班({日期}_team_name)属于该集合才正常(接口查不到集合时兜底
|
||||
原「完整排班名包含部门名」判断),否则为排班异常(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」近 {DAYS} 天;查询「预入职日期」当日完整排班名,有即正常,否则异常。
|
||||
|
||||
不推送过滤(不纳入异常、不推送):
|
||||
- 「现职位序列」命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的,直接剔除;
|
||||
- 花名册查不到工号的按离职处理剔除(调动+预入职均生效)。
|
||||
|
||||
店长解析(花名册):
|
||||
- 所有异常行已通过「离职过滤」保证工号在花名册内(未入册者已被剔除,含预入职);
|
||||
- 按异常人员「工号」查其「四级部门」,再找该部门内岗位含「店长」的人;
|
||||
- 仍解析不到的异常,若配置 shift_abnormal_default_manager 则归入默认处理人,否则仅记录不推送。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
花名册(店长解析数据源):
|
||||
默认 D:\\资料\\人资\\排班异常识别\\员工花名册.xlsx,可用环境变量 shift_abnormal_roster_path 覆盖;
|
||||
需含列:工号 / 姓名 / 四级部门 / 岗位。缺失时提示先运行「37du花名册导出」并准备好该文件
|
||||
(模板需含上述列,如「员工基础信息」含岗位、四级部门)。
|
||||
|
||||
环境变量(可选):
|
||||
shift_abnormal_save_dir 输出目录,默认 D:\\资料\\人资\\排班异常识别
|
||||
transfer_ledger / preentry_ledger 调动/预入职台账路径(默认同输出目录下的固定文件名)
|
||||
shift_abnormal_roster_path 花名册路径(默认 %shift_abnormal_save_dir%\\员工花名册.xlsx)
|
||||
shift_abnormal_default_manager 无法解析店长时归入的默认处理人 工号or姓名(可多个用英文逗号分隔)
|
||||
shift_abnormal_push_group 汇总群推送目标群(群全称,默认「金色印象人行条线沟通工作群」)
|
||||
shift_abnormal_push_at_all "1" 时汇总群推送 @所有人(需确认群权限,默认不 @)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先装齐,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
# 按部门查询排班集合(aa.md 提供):org_name=部门名,返回该部门全部排班
|
||||
# (data.list 记录含 work_date_name 排班名、org_name 部门名,逐条记录 = 一个排班)
|
||||
WORK_DATE_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_work_date_query/redApiExec.mc"
|
||||
# 集团根组织 struId(aa.md 提供,与考勤统计报表共用)
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
WORK_DATE_PAGE_SIZE = 50
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 输出目录 & 第二步导出的台账文件名(表头均在第 2 行)
|
||||
SAVE_DIR = os.getenv("shift_abnormal_save_dir") or r"D:\资料\人资\排班异常识别"
|
||||
TRANSFER_FILE = os.getenv("transfer_ledger") or os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.getenv("preentry_ledger") or os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
# 每 N 次查询校验一次登录态(避免会话过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 店长解析:花名册路径 & 关键字段
|
||||
ROSTER_PATH = os.getenv("shift_abnormal_roster_path") or os.path.join(SAVE_DIR, "员工花名册.xlsx")
|
||||
COL_NAME = "姓名"
|
||||
COL_CODE = "工号"
|
||||
COL_DEPT4 = "四级部门"
|
||||
COL_POSITION = "岗位"
|
||||
MANAGER_KEYWORD = "店长"
|
||||
|
||||
# 现职位序列命中以下序列的异常不推送(不纳入异常、不推送)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
# 无法解析店长时归入默认处理人(多个英文逗号分隔则轮流分配;空则不归并、仅记录不推送)
|
||||
DEFAULT_MANAGER = os.getenv("shift_abnormal_default_manager", "")
|
||||
|
||||
# 汇总群聊推送:目标群名(群全称,按群名精确匹配)& 是否 @所有人("1" 时开启)
|
||||
PUSH_GROUP_ENV = "shift_abnormal_push_group"
|
||||
PUSH_AT_ALL_ENV = "shift_abnormal_push_at_all"
|
||||
DEFAULT_PUSH_GROUP = "数字人沟通群" # 默认汇总推送群(与 XQ0009 固定推送群一致)
|
||||
|
||||
# 异常名单导出列
|
||||
COLUMNS = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
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 hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
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 _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
# ==================== 排班接口(内联自 app 版 hr_api/shift.py) ====================
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据。datas 记录含 {日期}_team_name 完整排班名,休息日可靠判定用 bc_name==休息。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"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": 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, base_code, begin_date, end_date):
|
||||
"""分页抓取指定工号、日期范围内全部排班数据;登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
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 fetch_work_date_page(session, org_name, page_no=1, page_size=WORK_DATE_PAGE_SIZE):
|
||||
"""请求单页「某部门排班集合」。data.list 记录含 work_date_name(排班名)、org_name(部门名)。"""
|
||||
params = {
|
||||
"stru_tree_code": "cq37du",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"containLower": "",
|
||||
"work_date_name": "",
|
||||
"paiban_type": "",
|
||||
"holiday_plan_name": "",
|
||||
"org_name": org_name,
|
||||
"work_status": "1",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "create_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", WORK_DATE_QUERY_URL, params, "部门排班")
|
||||
|
||||
|
||||
def fetch_all_work_date(session, org_name):
|
||||
"""分页抓取某部门的全部排班名列表(work_date_name)。登录态失效自动补登后续抓。"""
|
||||
names = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_work_date_page(session, org_name, page_no)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("部门排班 HR 登录态过期,自动补登录后续抓")
|
||||
session = _relogin_get_user_id()[0]
|
||||
data = fetch_work_date_page(session, org_name, page_no)
|
||||
if not data.get("success"):
|
||||
logger.error("部门排班第 %d 页请求失败:%s", page_no, data.get("message") or data.get("meg"))
|
||||
break
|
||||
data_block = data.get("data", {}) or {}
|
||||
page_list = data_block.get("list", []) or []
|
||||
if not page_list:
|
||||
logger.info("部门排班无更多数据")
|
||||
break
|
||||
for rec in page_list:
|
||||
name = _clean(rec.get("work_date_name"))
|
||||
if name:
|
||||
names.append(name)
|
||||
total_page = data_block.get("pageCount", 0)
|
||||
logger.info("部门排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(names))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return names
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。")
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ==================== 排班查询器(带缓存) ====================
|
||||
class _ShiftFetcher:
|
||||
"""按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
self.cache: Dict[Tuple[str, date], str] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, code: str, day: date) -> str:
|
||||
"""返回某工号某日的完整排班名({日期}_team_name);无排班则返回空串。"""
|
||||
key = (code, day)
|
||||
if key not in self.cache:
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
self.cache[key] = self._query(code, day)
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ==================== 异常判定(与 app 版一致) ====================
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day)
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
pj_day = _parse_date(r.get("预入职日期")) # 排班检查日期:预入职日期
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day)
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", end: date,
|
||||
days: int = DAYS) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end, days)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, days)
|
||||
rows = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 店长解析(花名册) ====================
|
||||
def _to_text(v):
|
||||
"""将工号等主键值统一转为文本(浮点/整型转 str),避免文本/数字混存匹配失败。"""
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return _clean(v)
|
||||
|
||||
|
||||
def _read_roster(roster_path: str) -> "pd.DataFrame":
|
||||
"""读取花名册并定位表头行(含「工号」列的行),返回列名为字段名的 DataFrame。
|
||||
|
||||
需含列:工号 / 姓名 / 四级部门 / 岗位。
|
||||
"""
|
||||
path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册:{path}\n"
|
||||
f"请先运行「37du花名册导出」指令导出到该路径,或设置环境变量 shift_abnormal_roster_path。")
|
||||
probe = pd.read_excel(path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{path}")
|
||||
df = pd.read_excel(path, header=header_row)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({path})")
|
||||
return df
|
||||
|
||||
|
||||
def _find_manager_by_code(df, code):
|
||||
"""按异常人员工号解析店长:查其四级部门 → 部门内岗位含「店长」的人。
|
||||
|
||||
返回 (manager_code, manager_name);找不到返回 (None, None)。
|
||||
"""
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return None, None
|
||||
row = df[df[COL_CODE].map(_to_text) == code]
|
||||
if row.empty:
|
||||
logger.warning("花名册中无该工号:%s", code)
|
||||
return None, None
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门,无法解析店长", code)
|
||||
return None, None
|
||||
return _find_manager_by_dept(df, dept4)
|
||||
|
||||
|
||||
def _find_manager_by_dept(df, dept_name, label=""):
|
||||
"""按部门名解析店长:花名册中该部门内岗位含「店长」的人,命中多个取第一个。
|
||||
|
||||
返回 (manager_code, manager_name);找不到返回 (None, None)。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return None, None
|
||||
dept_col = df[COL_DEPT4].map(_to_text)
|
||||
candidates = df[(dept_col == dept_name) & (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))]
|
||||
if candidates.empty:
|
||||
logger.warning("%s未在花名册「%s」部门找到店长", label, dept_name)
|
||||
return None, None
|
||||
first = candidates.iloc[0]
|
||||
return _to_text(first[COL_CODE]), _to_text(first[COL_NAME]) or ""
|
||||
|
||||
|
||||
def resolve_manager(roster_df, row: dict) -> Tuple[str, str]:
|
||||
"""解析某条异常名单行对应的店长:工号已保证在花名册(离职过滤已剔除未入册者),
|
||||
直接按工号查其四级部门 → 部门内岗位含「店长」的人;找不到返回 (None, None)。"""
|
||||
return _find_manager_by_code(roster_df, row.get("工号", ""))
|
||||
|
||||
|
||||
# ==================== 消息构造 ====================
|
||||
def _item_line(row: dict) -> str:
|
||||
"""异常明细一行(钉钉 markdown 纯文本,<br> 做单行换行),统一模板:
|
||||
|
||||
- 调动:{姓名}({工号}){调动时间}调入本店;
|
||||
- 新入职:{姓名}({工号}){预入职日期}新入职本店。
|
||||
"""
|
||||
name = row.get("姓名", "")
|
||||
code = row.get("工号", "")
|
||||
day = row.get("调动/入职时间", "")
|
||||
if row.get("类别") == "调动":
|
||||
return f"{name}({code}){day}调入本店"
|
||||
return f"{name}({code}){day}新入职本店"
|
||||
|
||||
|
||||
def _resolve_manager_identity(df, keyword: str) -> Tuple[str, str]:
|
||||
"""把「工号 or 姓名」归一化为 (工号, 姓名)(默认处理人场景)。
|
||||
花名册能查到就取登记值;查不到则按形态回退:像工号当工号(姓名为空,
|
||||
推送会因缺姓名失败并在记录中体现),否则当姓名。
|
||||
"""
|
||||
keyword = _to_text(keyword).strip()
|
||||
if not keyword:
|
||||
return "", ""
|
||||
hit = df[df[COL_CODE].map(_to_text) == keyword]
|
||||
if hit.empty:
|
||||
hit = df[df[COL_NAME].map(_to_text) == keyword]
|
||||
if not hit.empty:
|
||||
return _to_text(hit.iloc[0][COL_CODE]), _to_text(hit.iloc[0][COL_NAME]) or ""
|
||||
if keyword.isdigit():
|
||||
return keyword, ""
|
||||
return "", keyword
|
||||
|
||||
|
||||
def _find_dept4_by_manager(df, mc: str, mn: str) -> str:
|
||||
"""按店长工号/姓名在花名册查询其四级部门(门店名),查不到返回空串。
|
||||
|
||||
问候语里的门店名以花名册为准,不使用异常表里的 现四级部门/现单位 字段。
|
||||
"""
|
||||
if mc:
|
||||
hit = df[df[COL_CODE].map(_to_text) == mc]
|
||||
elif mn:
|
||||
hit = df[df[COL_NAME].map(_to_text) == mn]
|
||||
else:
|
||||
return ""
|
||||
if hit.empty:
|
||||
return ""
|
||||
return _to_text(hit.iloc[0][COL_DEPT4])
|
||||
|
||||
|
||||
def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
"""按店长分组构造钉钉单聊推送消息列表,结构与共享模块 dingtalk_dws_push.main(messages) 一致。
|
||||
|
||||
每组一条消息:("text", 店长姓名, 店长工号, 纯文本内容, "")。
|
||||
无法解析店长的异常,若配置 DEFAULT_MANAGER 则归入默认处理人(多个用英文逗号分隔,
|
||||
轮流分配),否则仅日志记录、不推送。
|
||||
"""
|
||||
messages: List[tuple] = []
|
||||
groups: Dict[Tuple[str, str], List[dict]] = {} # (店长工号, 店长姓名) -> 异常行列表
|
||||
unresolved: List[dict] = []
|
||||
default_managers = [m.strip() for m in DEFAULT_MANAGER.split(",") if m.strip()]
|
||||
|
||||
for row in rows:
|
||||
mc, mn = resolve_manager(roster_df, row)
|
||||
if mc or mn:
|
||||
groups.setdefault((mc or "", mn or ""), []).append(row)
|
||||
else:
|
||||
unresolved.append(row)
|
||||
|
||||
if unresolved:
|
||||
logger.warning("有 %d 条异常无法解析店长:%s",
|
||||
len(unresolved),
|
||||
[f"{r.get('姓名')}/{r.get('工号')}" for r in unresolved])
|
||||
if default_managers:
|
||||
# 配置多个默认处理人(英文逗号分隔)时,无法解析店长的异常轮流分配,不遗漏
|
||||
for i, row in enumerate(unresolved):
|
||||
mgr = default_managers[i % len(default_managers)]
|
||||
key = _resolve_manager_identity(roster_df, mgr)
|
||||
groups.setdefault(key, []).append(row)
|
||||
|
||||
for (mc, mn), items in groups.items():
|
||||
dept = _find_dept4_by_manager(roster_df, mc, mn) # 门店名以花名册店长四级部门为准
|
||||
line_items = "<br>".join(_item_line(r) for r in items)
|
||||
content = (
|
||||
f"【新入职/调入员工的排班异常提醒】<br>"
|
||||
f"{dept}店长您好,近期在排班核查中发现您的门店员工排班异常,"
|
||||
f"请从新入职当天或调入之日起开始排班,异常名单如下:<br>"
|
||||
f"{line_items}<br><br>"
|
||||
f"如有疑问可联系经营中心人行确认。"
|
||||
)
|
||||
messages.append(("text", mn, mc, content, ""))
|
||||
logger.info("已构造店长[%s%s]单聊推送消息,含 %d 条异常", mn, f"/{mc}" if mc else "", len(items))
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def _build_group_push_message(save_path: str, begin: date, end: date) -> Optional[dict]:
|
||||
"""构造群聊汇总推送消息(汇总文案 + 名单表格附件)。
|
||||
|
||||
识别出排班异常后调用:把《排班异常名单_时间戳.xlsx》及汇总文案打包成一条群聊消息
|
||||
(dict 含 group 键,共享指令「37du钉钉推送」main(messages) 自动识别为群聊并发送文本+附件),
|
||||
目标群默认 DEFAULT_PUSH_GROUP(金色印象人行条线沟通工作群),可用环境变量
|
||||
shift_abnormal_push_group 覆盖;shift_abnormal_push_at_all="1" 时 @所有人(需群权限)。
|
||||
|
||||
Args:
|
||||
save_path: 排班异常名单 Excel 绝对路径
|
||||
begin: 核查窗口开始日期(近 DAYS 天,含)
|
||||
end: 核查窗口结束日期(当天)
|
||||
|
||||
Returns:
|
||||
群聊推送消息 dict;文件不存在时返回 None(流程指令收到空则不发送)。
|
||||
"""
|
||||
if not save_path or not os.path.exists(save_path):
|
||||
logger.warning("排班异常名单文件不存在,跳过群聊汇总推送消息构造:%s", save_path)
|
||||
return None
|
||||
group = (os.getenv(PUSH_GROUP_ENV, "") or DEFAULT_PUSH_GROUP).strip()
|
||||
at_all = (os.getenv(PUSH_AT_ALL_ENV) or "0").strip().lower() in ("1", "true", "yes", "y")
|
||||
text = (
|
||||
f"【今日门店HR系统排班异常提示】今日提示日期{begin}至{end},"
|
||||
f"具体提示名单详见表格,已单独钉钉信息提示对应店长"
|
||||
)
|
||||
if at_all:
|
||||
text += "\n<@all>" # @所有人 需在内容中含占位符 <@all>(与共享模块约定一致)
|
||||
return {
|
||||
"group": group,
|
||||
"content": text,
|
||||
"file_path": save_path,
|
||||
"title": "",
|
||||
"at_all": at_all,
|
||||
"at_open_ids": "",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
roster_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> Tuple[List[dict], List[dict]]:
|
||||
"""执行排班异常识别,返回 (异常名单行列表, 推送消息列表)。
|
||||
|
||||
- 异常名单行列表:合并调动+预入职的异常明细(未写文件);
|
||||
- 推送消息列表:单聊消息按店长分组(五元组 ("text", 店长姓名, 店长工号, 内容, "")),
|
||||
识别出异常时末尾追加一条群聊汇总推送 dict(含 group 键,自动识别为群聊,文案+名单表格附件),
|
||||
统一由共享指令「37du钉钉推送」main(messages) 发送(单聊/群聊按消息结构自动识别)。
|
||||
脚本内部会将名单写入 SAVE_DIR 下《排班异常名单_时间戳.xlsx》便于人工留档。
|
||||
"""
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
roster_path = roster_path or ROSTER_PATH
|
||||
# 前置校验:花名册必须存在,避免台账读取与 HR 排班接口调用跑完后才发现缺失
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册:{roster_path}\n"
|
||||
"请先运行「37du花名册导出」指令导出到该路径,或设置环境变量 shift_abnormal_roster_path。")
|
||||
roster_df = _read_roster(roster_path) # 早读花名册:用于离职判定(工号查不到=离职剔除)
|
||||
roster_codes = set(_to_text(c) for c in roster_df[COL_CODE])
|
||||
end = date.today()
|
||||
begin, end_window = _recent_window(end, days) # 核查窗口(近 DAYS 天,含当天),用于汇总文案日期
|
||||
|
||||
rows: List[dict] = []
|
||||
fetcher = None
|
||||
if os.path.exists(transfer_path) or os.path.exists(preentry_path):
|
||||
session = build_hr_session()
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
else:
|
||||
raise RuntimeError(
|
||||
"调动台账、预入职台账均不存在,请先运行第二步导出后再执行本模块。\n"
|
||||
f"(调动:{transfer_path},预入职:{preentry_path})")
|
||||
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end, days))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end, days))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
# 离职过滤:花名册查不到工号的按离职处理,不纳入异常、不推送(调动+预入职均生效)
|
||||
if rows:
|
||||
resigned = [r for r in rows if _to_text(r.get("工号")) not in roster_codes]
|
||||
if resigned:
|
||||
logger.warning("花名册查不到工号,按离职剔除 %d 人:%s",
|
||||
len(resigned), [f"{r.get('姓名')}/{r.get('工号')}" for r in resigned])
|
||||
rows = [r for r in rows if _to_text(r.get("工号")) in roster_codes]
|
||||
|
||||
if not rows:
|
||||
logger.info("未识别到排班异常,无需推送。")
|
||||
messages = []
|
||||
else:
|
||||
# 补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
# 导出名单留档
|
||||
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"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
|
||||
# 解析店长并构造单聊推送消息
|
||||
messages = build_messages(rows, roster_df)
|
||||
|
||||
# 汇总群聊推送:汇总文案 + 名单表格附件(dict 含 group 键,共享指令自动识别为群聊)
|
||||
group_msg = _build_group_push_message(save_path, begin, end_window)
|
||||
if group_msg:
|
||||
messages.append(group_msg)
|
||||
logger.info("已构造群聊汇总推送消息(群「%s」,含名单表格附件)", group_msg.get("group"))
|
||||
|
||||
return rows, messages
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""影刀入口:排班异常识别并构造钉钉推送消息(单聊按店长 + 汇总群聊),写入全局变量 messages。
|
||||
由流程拖「37du钉钉推送」指令完成实际发送(单聊/群聊按消息结构自动识别)。
|
||||
"""
|
||||
try:
|
||||
rows, messages = run_shift_abnormal_check()
|
||||
_set_glv("shift_abnormal_rows", rows)
|
||||
_set_glv("messages", messages)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 异常人数:%d", len(rows))
|
||||
logger.info(" 待推送消息:%d 条(含单聊+汇总群聊,已写入全局变量 messages,请拖「37du钉钉推送」指令发送)", len(messages))
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,467 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: transfer_roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-27
|
||||
@Description: 调动台账自定义导出(排班异常识别 步骤2-调动,影刀版,单文件自包含)。
|
||||
复用「37duHR登录」指令写入的共享 cookies,通过 DrissionPage 浏览器自动化操作:
|
||||
进入调动台账页 -> 组织机构(集团) -> 点击「调动已生效」-> 更多搜索
|
||||
-> 输入调动时间(近30天)-> 筛选 -> 自定义导出 -> 选择模板「排班异常识别导出」
|
||||
-> 确认导出,接收下载文件重命名为《调动台账.xlsx》(表头在第 2 行)。
|
||||
与预入职台账导出(pre_entry_roster_export.py)流程基本一致,仅页面地址、tab 文案、
|
||||
日期占位符、文件名不同。
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage
|
||||
|
||||
登录(共享登录态,本脚本仅读取共享 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令完成登录,再运行本流程。
|
||||
|
||||
运行:直接执行本文件即可(会弹出浏览器窗口,请勿关闭)。
|
||||
输出目录默认 D:\\资料\\人资\\排班异常识别,可用环境变量 transfer_output_dir 覆盖。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:必须预先装齐,不懒加载) ====================
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# 调动台账页地址 & 导出模板(与 app/service/hrbp/ehr/common/config.py 一致)
|
||||
TRANSFER_ROSTER_URL = ("https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-39687&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1123d951-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E8%B0%83%E5%8A%A8%E5%8F%B0%E8%B4%A6")
|
||||
TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出"
|
||||
|
||||
# 流程步骤所用文案常量(aa.md 提供)
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
TAB_TRANSFER_EFFECTIVE = "调动已生效" # 只导已生效调动
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索"
|
||||
TRANSFER_RANGE_PLACEHOLDER = "请选择调动时间"
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
RETRY_TIMES = 3 # 单次导出失败重试次数(AGENTS.md:最大重试3次)
|
||||
|
||||
# 输出目录 & 文件名
|
||||
OUTPUT_DIR = os.getenv("transfer_output_dir") or r"D:\资料\人资\排班异常识别"
|
||||
SAVE_NAME = "调动台账.xlsx"
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,影刀版约定) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies(由「37duHR登录」指令写入)。"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在有效的 HR 登录态;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令完成登录,"
|
||||
"或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== 调动日期范围(近30天) ====================
|
||||
def get_transfer_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算调动日期筛选范围,返回 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_more_search_button(page):
|
||||
"""定位当前活跃 tab 的「更多搜索」按钮(仅取可见的那个,避免展开错 tab)。"""
|
||||
btns = page.eles('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btns:
|
||||
btns = page.eles('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btns:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
return btn if _is_displayed(btn) else None
|
||||
for b in btns:
|
||||
if _is_displayed(b):
|
||||
return b
|
||||
logger.warning("未找到可见的「更多搜索」按钮(DOM 中共 %d 个)", len(btns))
|
||||
return None
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""展开当前活跃 tab 的「更多搜索」popover,返回其内容元素;失败返回 None。"""
|
||||
btn = _find_more_search_button(page)
|
||||
if not btn:
|
||||
return None
|
||||
for _ in range(3):
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return popover
|
||||
try:
|
||||
btn.run_js('this.click();')
|
||||
except Exception:
|
||||
btn.click()
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return None
|
||||
|
||||
|
||||
def _click_filter(page, popover):
|
||||
"""点击活跃 tab「更多搜索」弹层底部的「筛选」按钮(限定在弹出容器内)。"""
|
||||
result = popover.run_js(
|
||||
'var btns=this.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn";'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _find_visible_range_input(page, placeholder):
|
||||
"""在页面级查找可见的调动时间选择器(页面宽/窄布局不同,取可见的第一个)。"""
|
||||
rngs = page.eles(f'css:div.split-datetime-range[placeholder="{placeholder}"]', timeout=3)
|
||||
for r in rngs:
|
||||
if _is_displayed(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def _fill_range(page, rng, start, end):
|
||||
"""填入日期范围并回车确认。"""
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到调动时间起止输入框")
|
||||
start_input.input(start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("调动时间已设置:%s ~ %s", start, end)
|
||||
|
||||
|
||||
def _set_transfer_date_range(page, start=None, end=None):
|
||||
"""设置「调动时间」筛选范围(近30天)并应用筛选。"""
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("设置调动时间范围:%s ~ %s", start, end)
|
||||
popover = _open_more_search(page)
|
||||
if not popover:
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置调动时间")
|
||||
rng = _find_visible_range_input(page, TRANSFER_RANGE_PLACEHOLDER)
|
||||
if not rng:
|
||||
rng = popover.ele(
|
||||
f'css:div.split-datetime-range[placeholder="{TRANSFER_RANGE_PLACEHOLDER}"]', timeout=5)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「调动时间」选择器")
|
||||
_fill_range(page, rng, start, end)
|
||||
_click_filter(page, popover)
|
||||
|
||||
|
||||
# ==================== 打开台账页并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问调动台账页面;若被重定向到登录页则提示先完成「37duHR登录」。"""
|
||||
page.get(TRANSFER_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError(
|
||||
"HR 登录态已失效。\n"
|
||||
"请先重新运行「37duHR登录」指令,或本地执行 python workflows/share/hr_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
logger.info("已进入调动台账页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 调动台账导出主流程(aa.md 步骤) ====================
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||||
if org_tab:
|
||||
org_tab.click()
|
||||
logger.info("已点击左侧「组织机构」")
|
||||
time.sleep(WAIT_MID)
|
||||
else:
|
||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||||
_click_text(page, TAB_ORG)
|
||||
time.sleep(WAIT_MID)
|
||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||||
if not group:
|
||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||||
if not group:
|
||||
raise RuntimeError("组织树中未找到「集团」节点")
|
||||
group.click()
|
||||
logger.info("已点击组织树根节点「集团」")
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
|
||||
def _click_transfer_tab(page):
|
||||
"""点击「调动已生效」tab,只保留已生效的调动记录。"""
|
||||
tab = page.ele(f'xpath://div[contains(@class,"tab-info")]//*[normalize-space(.)="{TAB_TRANSFER_EFFECTIVE}"]',
|
||||
timeout=10)
|
||||
if not tab:
|
||||
_click_text(page, TAB_TRANSFER_EFFECTIVE)
|
||||
return
|
||||
tab.click()
|
||||
logger.info("已点击「%s」tab", TAB_TRANSFER_EFFECTIVE)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _open_custom_export_dialog(page):
|
||||
"""点击「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||||
tpl_label = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||||
if tpl_label and _is_displayed(tpl_label):
|
||||
logger.info("导出弹窗已打开,跳过「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
return
|
||||
btn = page.ele('xpath://button[normalize-space(.)="自定义导出"]', timeout=15)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://*[contains(@class,"btn") and normalize-space(.)="自定义导出"]', timeout=5)
|
||||
if not btn:
|
||||
raise RuntimeError("未找到「自定义导出」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=TEMPLATE_SHIFT_ABNORMAL):
|
||||
"""选择导出模板「排班异常识别导出」。"""
|
||||
tpl = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||||
'/following-sibling::div[contains(@class,"el-select")]',
|
||||
timeout=15,
|
||||
)
|
||||
if not tpl:
|
||||
raise RuntimeError("未找到「模板」下拉框")
|
||||
panel = None
|
||||
for _ in range(3):
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||||
if panel and _is_displayed(panel):
|
||||
break
|
||||
tpl.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
if not panel:
|
||||
raise RuntimeError("模板下拉面板未能展开")
|
||||
opt = panel.ele(f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||||
timeout=5)
|
||||
if not opt:
|
||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||||
opt.click()
|
||||
logger.info("已选择模板:%s", template_name)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_confirm_export(page):
|
||||
"""点击「确认导出」,触发下载。"""
|
||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||||
timeout=10)
|
||||
if not btn:
|
||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「确认导出」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ==================== 下载等待 ====================
|
||||
def _wait_download(download_dir, before, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
deadline = time.time() + timeout
|
||||
last_sizes = {}
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
files = os.listdir(download_dir)
|
||||
except Exception:
|
||||
files = []
|
||||
for f in files:
|
||||
if f in before or f.startswith('~$'):
|
||||
continue
|
||||
if f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||||
continue
|
||||
p = os.path.join(download_dir, f)
|
||||
if not os.path.isfile(p):
|
||||
continue
|
||||
try:
|
||||
size = os.path.getsize(p)
|
||||
except Exception:
|
||||
continue
|
||||
if size <= 0:
|
||||
continue
|
||||
if last_sizes.get(p) == size:
|
||||
logger.info("调动台账导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||||
return p
|
||||
last_sizes[p] = size
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ==================== 单次导出(带重试,AGENTS.md:最大3次) ====================
|
||||
def _export_one(page, download_dir, template_name, start=None, end=None):
|
||||
"""执行单次调动台账导出(筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(1, RETRY_TIMES + 1):
|
||||
logger.info(">>> 调动台账导出 第 %d/%d 次(模板:%s)", attempt, RETRY_TIMES, template_name)
|
||||
try:
|
||||
_set_transfer_date_range(page, start, end)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
# 触发下载前捕获目录快照,避免下载过快时真实文件被误判为已存在而漏检
|
||||
before = set(os.listdir(download_dir))
|
||||
_click_confirm_export(page)
|
||||
path = _wait_download(download_dir, before)
|
||||
logger.info(">>> 调动台账导出完成")
|
||||
return path
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.exception("调动台账导出失败(第 %d 次),尝试重试:", attempt)
|
||||
time.sleep(WAIT_MID)
|
||||
raise RuntimeError(f"调动台账导出连续失败:{last_err}")
|
||||
|
||||
|
||||
# ==================== 对外入口 ====================
|
||||
def export_transfer_roster(download_dir: str = None, template_name: str = TEMPLATE_SHIFT_ABNORMAL,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行调动台账自定义导出(调动时间近30天),返回下载后的 xlsx 文件路径。"""
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("===== 开始调动台账导出(模板:%s,日期:%s ~ %s),下载目录:%s =====",
|
||||
template_name, start, end, download_dir)
|
||||
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
logger.info("加载共享 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入共享 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
_click_transfer_tab(page)
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
path = _export_one(page, download_dir, template_name, start, end)
|
||||
|
||||
if output_path:
|
||||
output_path = os.path.abspath(output_path)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
shutil.move(path, output_path)
|
||||
path = output_path
|
||||
elif path.endswith('.xlsx'):
|
||||
renamed = os.path.join(download_dir, SAVE_NAME)
|
||||
if os.path.abspath(path) != os.path.abspath(renamed):
|
||||
shutil.move(path, renamed)
|
||||
path = renamed
|
||||
|
||||
logger.info("===== 调动台账导出完成:%s =====", path)
|
||||
return path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
"""影刀入口:导出调动台账。缺依赖/未登录会先行报错退出。"""
|
||||
try:
|
||||
out = export_transfer_roster()
|
||||
logger.info("===== 调动台账导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("调动台账导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,935 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: add_sub_import.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-23
|
||||
@Description: 雇主险流程「步骤3:增减员导入」(影刀版,单文件自包含)——在 HR「待增减人员」页面
|
||||
执行增员/减员导入(复刻 aa.md 与 app 版 add_sub_import 的操作流程):
|
||||
访问页面 -> 更多操作 -> 增员导入/减员导入 -> 上传文件 -> 下一步 -> 下一步 -> 关闭。
|
||||
登录态复用「37duHR登录」写入的共享 hr_cookies.json(只读不补登)。
|
||||
@Version: 1.8.0
|
||||
- v1.8.0:全部成功时 HR 端不调用结果接口(getTmpDataPage.mc 仅在存在异常行时返回逐行结果),
|
||||
原逻辑会把「未捕获到接口响应」误报为「待人工确认」(成功 0 条)——现改为:流程完整
|
||||
走完(两步「下一步」+「关闭」成功)、监听正常启动且未捕获到任何异常行时,视为全部
|
||||
导入成功,成功数按导入文件条数计,不再误报未确认。
|
||||
- v1.7.1:修复导入条数统计把模板预格式化空白行也计入的问题——改为读 A列序号,
|
||||
取最大序号即需导入条数(原 max_row-3 会因官方模板自带 2000~3000 行空白
|
||||
格式化行误报为几千条)。
|
||||
- v1.7.0:汇总统计「本次调度需增员/减员条数」改从增减员导入文件统计,
|
||||
接口未返回结果的类别仍计入需导入条数并在汇总标注「待人工确认」,避免误报为没有增减员。
|
||||
- v1.6.0:增减员执行顺序改为「先减员、后增员」(原为增员在前,替换/修改人员若先增员
|
||||
会因人员方案冲突直接报错;必须先撤下旧方案,再上新方案)。
|
||||
- v1.5.0:修复监听时机与全量分页——监听从第一个「下一步」前即开启(HR 端流程调整后结果接口
|
||||
可能在第一步即触发,原「第二步前才监听」导致漏捕、误报「未捕获到导入结果接口响应」);
|
||||
wait() 超时返回 False 的判断修正;跳过无 imp_fixed_msg 的格式校验/预览响应;
|
||||
全量翻页改为按首次请求 body 改 pageNo/start 后 POST 拉取(原 GET URL 对 POST 接口无效)。
|
||||
- v1.4.0:钉钉推送改为汇总 + 异常名单拆分多条消息(汇总一条,增员/减员异常名单各一条,
|
||||
名单过长自动分批),仅推接口返回的业务结果。
|
||||
- v1.3.0:导入异常消息写入影刀全局变量 messages(块格式分组列表),供「37du钉钉群机器人推送」指令直接推送;无异常时写入完成提示。
|
||||
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
|
||||
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
|
||||
|
||||
设计说明(与 workflows 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 登录态复用共享 hr_cookies.json(缺失/失效引导先运行「37duHR登录」指令,不自动补登)。
|
||||
- 按类别传参(category_names 列表,空/None=全部类别),导入文件取各类别文件夹内的
|
||||
商业保险增员导入.xlsx / 商业保险减员导入.xlsx(由 schedule 步骤生成)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
employer_insurance_base_dir = 雇主险文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
|
||||
运行:直接执行本文件,按 __main__ 中的示例传参(增员/减员 + 类别列表)调用 main()
|
||||
main(category_names=['三十七度']) 或 import_employee_change(import_type, category_names)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise ImportError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
) from _import_err
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 影刀全局变量(消息/结果写 glv,生成与发送解耦) ====================
|
||||
# 约定见 workflows/README.md 5.2:业务脚本只生成消息文本写全局变量,
|
||||
# 发送一律由「37du钉钉群机器人推送」指令(workflows/share/dingtalk_robot.py)完成。
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 app 版 config 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
|
||||
# 共享 HR 登录态:由「37duHR登录」指令(workflows/share/hr_login.py)写入
|
||||
_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')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统「待增减人员」页面(与 app 版 ehr/common/config 一致) ----------
|
||||
ADD_SUB_URL = (
|
||||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
"#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664"
|
||||
"|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/"
|
||||
"getCustomCommonList.mc?menuName=待增减人员"
|
||||
)
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理,与 app 版 config.CATEGORIES 一致) ----------
|
||||
CATEGORIES = [
|
||||
{"name": "三十七度", "folder": os.path.join(BASE_DIR, "三十七度")},
|
||||
{"name": "水庄餐饮", "folder": os.path.join(BASE_DIR, "水庄餐饮")},
|
||||
{"name": "湖畔酒店", "folder": os.path.join(BASE_DIR, "湖畔酒店")},
|
||||
{"name": "秒创传媒", "folder": os.path.join(BASE_DIR, "秒创传媒")},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用,与 app 版 config 一致) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内,由 schedule 步骤生成)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内,由 schedule 步骤生成)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
|
||||
# ---------- 流程步骤文案常量(与 app 版 add_sub_import 一致) ----------
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
|
||||
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
|
||||
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行导入结果说明:
|
||||
# 异常行如「存在已参保的人员,不允许重复增员!」;成功行返回「导入成功;」(不纳入异常上报)。
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 导入内容结果接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""打开页面被重定向到登录页(cookies 缺失或失效)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。
|
||||
|
||||
用于区分「UI 状态类失败」(页面没加载出来、元素定位器失效)与其它运行时错误,
|
||||
便于调用方针对性地重试或提示人工介入。
|
||||
"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||||
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _create_page():
|
||||
"""创建新的 ChromiumPage(统一配置,非无头)。"""
|
||||
co = ChromiumOptions()
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 打开待增减人员页面并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,提示先运行「37duHR登录」指令。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效/缺失。请先在影刀流程开头调用「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python workflows/share/hr_login.py")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 增员/减员导入主流程(aa.md 步骤) ====================
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
# 若下拉菜单已可见,直接返回
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
# 定位「更多操作」按钮(#more-btns 容器内的 btn-success dropdown-toggle)
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件。
|
||||
|
||||
aa.md:选择文件夹按钮(glyphicon glyphicon-folder-open)会弹出文件选择器;
|
||||
这里直接用 DrissionPage 对 <input type="file"> 设置文件路径,跳过系统文件选择框。
|
||||
"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
# 接口返回的每一行即本次调度的一条需导入记录,全部计入需导入总条数
|
||||
result["total_count"] += 1
|
||||
# HR 对导入成功的行同样返回「导入成功;」等固定文案,成功行只统计数量,
|
||||
# 不纳入异常(否则会被误报为异常,如「异常:导入成功;」)
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""读取共享 hr_cookies.json 构建可访问 HR 接口的 requests.Session(仅注入 37du.co 域 cookies)。
|
||||
|
||||
与 hr_login.py 的 API 校验同一套构建方式,保证接口请求携带同一登录态。
|
||||
"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
raise FileNotFoundError(f"缺少共享登录态:{SHARED_HR_COOKIE_FILE}")
|
||||
with open(SHARED_HR_COOKIE_FILE, "r", encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in str(c.get("domain", "")):
|
||||
session.cookies.set(c.get("name"), c.get("value"),
|
||||
domain=c.get("domain"), path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页时监听只能统计到 15 条,
|
||||
实际导入量常超 15,导致汇总「需增/减员条数、成功/失败数」被截断、异常明细漏统计。
|
||||
此函数用 HR 登录态按 pageNo 主动拉取剩余页并合并全部结果,保证统计覆盖全量。
|
||||
|
||||
注意:该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中而非 URL 查询串,必须复用首次请求 body 改页码后 POST 拉取,
|
||||
直接 GET URL 会拿不到目标页数据。"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
try:
|
||||
session = _build_hr_session()
|
||||
except Exception as e:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话):%s,仅统计弹窗第一页", e)
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获返回的全部异常。
|
||||
|
||||
监听自第一个「下一步」之前即已开启(见 _import_one),因此无论 HR 端是在第一步
|
||||
格式校验/预览还是第二步「真正导入」时才请求 getTmpDataPage.mc 都能捕获到。
|
||||
本函数只处理携带导入结果说明的响应:
|
||||
- state="1" 表示接口正常;meg 为全局提示;
|
||||
- datas[].imp_fixed_msg 为逐行导入结果说明:异常行如「存在已参保的人员,不允许重复增员!」,
|
||||
成功行返回「导入成功;」(成功行不纳入异常上报);
|
||||
- 第一步格式校验/预览的响应行内 imp_fixed_msg 为空,视为无效响应跳过,继续等待最终结果。
|
||||
接口分页返回(每页固定 pageSize=15,响应带 pageCount 总页数),弹窗默认只加载第一页,
|
||||
故捕获首响应后主动按 pageNo 翻页拉取剩余页合并,保证总条数/成功数/异常明细覆盖全量,
|
||||
不再出现「每次固定 15 条」的截断问题。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"captured": bool, # 是否捕获到解析接口响应
|
||||
"state": str, # 接口 state(未捕获到为空串)
|
||||
"meg": str, # 全局提示
|
||||
"listen_ok": bool, # 接口监听是否成功启动(False=未监听,结果不可信)
|
||||
"success_count": int, # 接口返回的导入成功行数
|
||||
"total_count": int, # 接口返回的需导入总行数(成功+异常,即本次需导入条数)
|
||||
"exceptions": [ # 全部异常明细
|
||||
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
|
||||
],
|
||||
}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# DrissionPage wait() 超时返回 False(非 None),统一按「无新响应」处理:
|
||||
# 若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 第一步「下一步」(格式校验/预览)也可能请求 getTmpDataPage.mc,但此时行内
|
||||
# imp_fixed_msg 为空;仅当携带导入结果说明(imp_fixed_msg 非空)时才视为真正的
|
||||
# 导入结果,空说明的预览/校验响应跳过,继续等待最终结果。
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
# 记录第一页 URL、请求 body 与总页数,用于主动翻页拉全(弹窗默认只加载第一页 15 条)
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
# 该接口为 POST,分页参数在 body 中,保存首次请求 body 供翻页复用
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
# 若接口存在多页(实际导入量超过一页 15 条),主动翻页拉取剩余页后结束
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _count_import_rows(file_path):
|
||||
"""统计导入文件需导入条数(本次调度生成的增减员导入文件)。
|
||||
|
||||
模板结构:第1行标题 / 第2行表头 / 第3行示例说明,第4行起为数据行,
|
||||
第1列(A列)为数据行序号(1,2,3,...),最大序号即需导入条数。
|
||||
官方模板自带大量预格式化的空白行(max_row 可达 2000~3000 行),因此不能
|
||||
直接用 max_row 统计;取最大序号即可得到真实导入量,与接口是否捕获无关。
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
max_seq = 0
|
||||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||||
max_col=1, values_only=True):
|
||||
v = seq[0]
|
||||
if v is None or str(v).strip() == "":
|
||||
continue
|
||||
try:
|
||||
max_seq = max(max_seq, int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return max_seq
|
||||
finally:
|
||||
wb.close()
|
||||
except Exception as e:
|
||||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||||
return 0
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label, file_path=None):
|
||||
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启对 getTmpDataPage.mc 的监听:HR 端流程调整后,
|
||||
结果接口可能在第一步「格式校验/预览」或第二步「真正导入」时触发,提前监听避免漏捕;
|
||||
监听捕获导入返回的全部异常,异常仅记录并上报,不中断导入流程。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
|
||||
"""
|
||||
file_path = file_path or (
|
||||
category_import_add_file(category) if menu_label == MENU_ADD
|
||||
else category_import_sub_file(category))
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
# 需导入条数:从本次调度生成的导入文件统计(与接口是否捕获无关,供汇总使用)
|
||||
expected_total = _count_import_rows(file_path)
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 在第一个「下一步」前开启 getTmpDataPage.mc 监听,贯穿「格式校验/预览 + 真正导入」全过程
|
||||
# 监听启动失败必须上报:若静默继续,未捕获到异常会被误报为「正常」,产生假成功
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:下一步(格式校验/预览,同时可能在监听中触发结果接口)
|
||||
_click_next(page) # 第二步:下一步(真正导入内容,触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
import_result["expected_total"] = expected_total # 需导入条数(来自导入文件)
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 全部成功时 HR 端不会调用结果接口(getTmpDataPage.mc 只在存在异常行时返回逐行结果)。
|
||||
# 若流程已完整走完(两步「下一步」均成功、监听正常启动、未捕获到任何异常行),
|
||||
# 说明全部导入成功:成功数按导入文件条数计,避免误报「接口未返回/待人工确认」。
|
||||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||||
import_result["assumed_all_success"] = True
|
||||
import_result["success_count"] = expected_total
|
||||
import_result["total_count"] = expected_total
|
||||
|
||||
# 上报:全部异常逐条打日志
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
|
||||
elif not import_result.get("listen_ok", True):
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif import_result.get("assumed_all_success"):
|
||||
logger.info("类别[%s] %s:全部导入成功(全部成功时 HR 不返回结果接口,按文件 %d 条计成功),无异常",
|
||||
category["name"], menu_label, expected_total)
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page) # 第三步:关闭
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 钉钉群消息生成(写入全局变量,由「37du钉钉群机器人推送」指令发送) ====================
|
||||
def _build_group_messages(import_type, categories, results, exception_count):
|
||||
"""构建钉钉群机器人推送消息(块格式分组列表 [{title, blocks, status}])。
|
||||
|
||||
拆分为多条独立消息推送(避免异常名单过多时单条消息过长):
|
||||
1. 汇总:标题「雇主险增减员操作完成」,正文为需增员/减员条数、导入成功/失败条数;
|
||||
2. 增员导入异常名单(接口返回的业务异常明细);
|
||||
3. 减员导入异常名单。
|
||||
某操作无异常则不发对应异常名单消息(全部成功时只有 1 条汇总);
|
||||
单条异常名单内异常再多,也会由「37du钉钉群机器人推送」指令按批自动分批发送。
|
||||
|
||||
「本次调度需增员/减员条数」取自已生成的增减员导入文件(results 的 expected_total,
|
||||
与接口是否捕获无关);「导入成功/失败条数」取接口返回的业务结果。
|
||||
代码/流程异常(error)的类别不纳入统计;接口未返回结果(captured=False / state!=1)
|
||||
的类别分两种情况:若流程完整走完且无异常行(assumed_all_success,全部成功时 HR
|
||||
不调用结果接口)→ 按文件条数计全部成功;否则成功/失败未知,汇总中标注「待人工确认」,
|
||||
避免误报为没有增减员。
|
||||
全部类别均无导入数据(文件为空或全部流程失败)→ 返回空列表,不推送。
|
||||
results 每项可带 "menu" 字段(增员导入/减员导入),main() 合并增/减员时使用。
|
||||
"""
|
||||
# 按菜单(增员导入/减员导入)分组统计;需导入条数来自导入文件,成功/失败来自接口
|
||||
group_stats = {} # menu -> {"total":, "success":, "fail":, "excs": [(category, exc), ...]}
|
||||
unconfirmed_menus = {} # menu -> [category, ...](接口未确认结果的类别)
|
||||
for r in results:
|
||||
# 代码/流程异常(登录失败/元素找不到/文件缺失等):无导入数据,不纳入统计(报错进日志)
|
||||
if r.get("error"):
|
||||
continue
|
||||
menu = r.get("menu") or import_type
|
||||
stat = group_stats.setdefault(
|
||||
menu, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
category = r.get("category") or ""
|
||||
# 需导入条数:本次调度生成的增减员导入文件(与接口是否捕获无关)
|
||||
stat["total"] += r.get("expected_total") or 0
|
||||
if not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK:
|
||||
# 接口未捕获/未返回成功:
|
||||
# - assumed_all_success(全部成功时 HR 不调用结果接口,流程完整走完且无异常)
|
||||
# → 按文件条数计全部成功,不再误报「待人工确认」;
|
||||
# - 其余情况成功/失败未知,需导入条数仍计入,记入未确认
|
||||
if r.get("assumed_all_success"):
|
||||
stat["success"] += r.get("success_count") or 0
|
||||
continue
|
||||
unconfirmed_menus.setdefault(menu, []).append(category)
|
||||
continue
|
||||
excs = r.get("exceptions") or []
|
||||
stat["success"] += r.get("success_count") or 0
|
||||
stat["fail"] += len(excs)
|
||||
stat["excs"].extend((category, exc) for exc in excs)
|
||||
|
||||
# 全部无导入数据(文件为空或全部流程失败):不推送,报错交给日志
|
||||
if not any(s["total"] or s["excs"] for s in group_stats.values()):
|
||||
return []
|
||||
|
||||
add_stat = group_stats.get(MENU_ADD, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
sub_stat = group_stats.get(MENU_SUB, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
unconf_add = unconfirmed_menus.get(MENU_ADD, [])
|
||||
unconf_sub = unconfirmed_menus.get(MENU_SUB, [])
|
||||
|
||||
# 标题:按实际分组自动带操作名(减+增合并为「减员增员」,单类型为「减员/增员」)
|
||||
# 顺序与执行顺序一致:先减员、后增员
|
||||
ops = []
|
||||
if sub_stat["total"] or sub_stat["excs"]:
|
||||
ops.append("减员")
|
||||
if add_stat["total"] or add_stat["excs"]:
|
||||
ops.append("增员")
|
||||
title = "雇主险{}操作完成".format("".join(ops) if ops else import_type)
|
||||
|
||||
# 汇总块:需导入条数取自本次调度生成的增减员导入文件;成功/失败取接口返回的业务结果
|
||||
summary_lines = [
|
||||
"**本次调度需增员 {} 条,减员 {} 条**".format(add_stat["total"], sub_stat["total"]),
|
||||
"其中增员导入成功 {} 条,失败 {} 条".format(add_stat["success"], add_stat["fail"]),
|
||||
"其中减员导入成功 {} 条,失败 {} 条".format(sub_stat["success"], sub_stat["fail"]),
|
||||
]
|
||||
if unconf_add:
|
||||
summary_lines.append("⚠️ 增员 {} 个类别接口未返回/未捕获,导入结果待人工确认:{}".format(
|
||||
len(unconf_add), "、".join(unconf_add)))
|
||||
if unconf_sub:
|
||||
summary_lines.append("⚠️ 减员 {} 个类别接口未返回/未捕获,导入结果待人工确认:{}".format(
|
||||
len(unconf_sub), "、".join(unconf_sub)))
|
||||
summary = "\n\n".join(summary_lines)
|
||||
messages = [{
|
||||
"title": title,
|
||||
"blocks": [summary],
|
||||
# 有业务异常或存在未确认类别 → 橙色 warning(提醒查看);全部成功 → 绿色 success
|
||||
"status": "warning" if (add_stat["fail"] or sub_stat["fail"]
|
||||
or unconf_add or unconf_sub) else "success",
|
||||
}]
|
||||
|
||||
# 增员/减员异常名单各拆一条独立消息(名单再长由推送指令按批自动分批发送)
|
||||
for menu, stat in ((MENU_ADD, add_stat), (MENU_SUB, sub_stat)):
|
||||
if not stat["excs"]:
|
||||
continue
|
||||
exc_blocks = []
|
||||
for category, exc in stat["excs"]:
|
||||
exc_blocks.append(
|
||||
"**🔹 {} / {}**\n\n"
|
||||
"> 工号:{}\n\n"
|
||||
"> 姓名:{}\n\n"
|
||||
"> 方案:{}\n\n"
|
||||
"> 异常:{}".format(
|
||||
category,
|
||||
exc.get("staff_name", ""),
|
||||
exc.get("staff_code", ""),
|
||||
exc.get("staff_name", ""),
|
||||
exc.get("insurance_name", "") or "-",
|
||||
exc.get("message", ""),
|
||||
)
|
||||
)
|
||||
messages.append({
|
||||
"title": "【{}】异常名单({} 条)".format(menu, stat["fail"]),
|
||||
"blocks": exc_blocks,
|
||||
"status": "error",
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
def _write_group_messages_glv(import_type, categories, results, exception_count):
|
||||
"""把增/减员导入结果写入影刀全局变量 messages,供「37du钉钉群机器人推送」指令读取推送。
|
||||
|
||||
汇总「需导入条数」取自已生成的增减员导入文件(与接口是否捕获无关);代码/流程异常
|
||||
只报错进日志;接口未返回结果的类别分两种情况:全部成功(assumed_all_success,HR
|
||||
全部成功时不调用结果接口)→ 按文件条数计成功;其余未返回 → 需导入条数仍计入汇总并
|
||||
标注「待人工确认」。全部类别均无导入数据时 messages 为空列表,推送指令不会真正发送。
|
||||
"""
|
||||
messages = _build_group_messages(import_type, categories, results, exception_count)
|
||||
_set_glv("messages", messages)
|
||||
biz_exceptions = sum(len(r.get("exceptions") or []) for r in results)
|
||||
# 未确认结果:流程异常、或接口未返回成功(captured=False/state!=1);全部成功推定除外
|
||||
unconfirmed = sum(1 for r in results
|
||||
if not r.get("exceptions")
|
||||
and not r.get("assumed_all_success")
|
||||
and (r.get("error") or not r.get("captured")
|
||||
or r.get("state") != TMP_DATA_STATE_OK))
|
||||
if biz_exceptions:
|
||||
logger.error("汇总消息已写入全局变量 messages:共 %d 条业务异常(由「37du钉钉群机器人推送」指令发送)",
|
||||
biz_exceptions)
|
||||
if unconfirmed:
|
||||
logger.warning("另有 %d 个类别导入结果未确认(流程异常或接口未返回),需导入条数已计入汇总并标注「待人工确认」,请人工核对",
|
||||
unconfirmed)
|
||||
if not biz_exceptions and not unconfirmed:
|
||||
logger.info("完成汇总消息已写入全局变量 messages(由「37du钉钉群机器人推送」指令发送)")
|
||||
|
||||
|
||||
# ==================== 对外入口(函数传参调用,支持多类别) ====================
|
||||
# 参数兼容「增员/减员」短名 与「增员导入/减员导入」菜单全名
|
||||
_IMPORT_TYPE_MAP = {
|
||||
"增员": MENU_ADD,
|
||||
"减员": MENU_SUB,
|
||||
MENU_ADD: MENU_ADD,
|
||||
MENU_SUB: MENU_SUB,
|
||||
}
|
||||
|
||||
|
||||
def import_employee_change(import_type="增员", category_names=None, file_path=None):
|
||||
"""执行增员/减员导入(可一次传入一个或多个类别,复用同一浏览器)。
|
||||
|
||||
Args:
|
||||
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
file_path: 要上传的文件路径;若传入则对每个类别使用同一文件(覆盖类别解析);
|
||||
不传则按类别文件夹取 schedule 步骤生成的 商业保险增员/减员导入.xlsx。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 全部类别流程是否均完成
|
||||
"import_type": str, # 菜单文案(增员导入/减员导入)
|
||||
"categories": [str], # 类别名列表
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions);
|
||||
# 类别流程失败时含 error(错误信息)/error_type(异常类型)字段
|
||||
"exception_count": int, # 上传表格返回的异常总条数
|
||||
}
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 HR 登录态缺失/失效,需先运行「37duHR登录」指令。
|
||||
ValueError: import_type 非法。
|
||||
"""
|
||||
if import_type not in _IMPORT_TYPE_MAP:
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||
menu_label = _IMPORT_TYPE_MAP[import_type]
|
||||
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
|
||||
logger.info("===== 开始%s,类别:%s =====", menu_label,
|
||||
[c["name"] for c in categories])
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies))
|
||||
page.set.cookies(cookies)
|
||||
_ensure_logged_in(page)
|
||||
|
||||
ok = 0
|
||||
results = []
|
||||
for category in categories:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label, file_path))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
ok += 1
|
||||
except Exception as e:
|
||||
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"error": str(e),
|
||||
"error_type": type(e).__name__,
|
||||
})
|
||||
exception_count = sum(len(r.get("exceptions") or []) for r in results)
|
||||
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
|
||||
menu_label, ok, len(categories), exception_count)
|
||||
# 异常/完成消息写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
|
||||
_write_group_messages_glv(
|
||||
menu_label,
|
||||
[c["name"] for c in categories],
|
||||
results,
|
||||
exception_count,
|
||||
)
|
||||
return {
|
||||
"success": ok == len(categories),
|
||||
"import_type": menu_label,
|
||||
"categories": [c["name"] for c in categories],
|
||||
"results": results,
|
||||
"exception_count": exception_count,
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main(category_names=None):
|
||||
"""影刀自定义指令入口「37du增减员导入」:对指定/全部类别完成减员+增员导入。
|
||||
|
||||
★执行顺序:必须先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错(必须先撤下旧方案,再上新方案)。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表,空/None=全部类别。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 减员+增员全部类别是否均完成
|
||||
"categories": [str],
|
||||
"details": {"减员导入": bool, "增员导入": bool},
|
||||
"exceptions": [dict], # 全部异常明细(上传表格返回的异常 + 类别流程失败,合并减/增员)
|
||||
"exception_count": int, # 异常总条数
|
||||
}
|
||||
"""
|
||||
load_dotenv()
|
||||
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||
else [c["name"] for c in CATEGORIES]
|
||||
details = {}
|
||||
exceptions = []
|
||||
all_results = []
|
||||
ok_all = True
|
||||
# 执行顺序:先全部减员,再全部增员(先增员会让替换/修改人员因方案冲突直接报错)
|
||||
for import_type in ("减员", "增员"):
|
||||
result = import_employee_change(import_type, category_names)
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
|
||||
ok_all = ok_all and result["success"]
|
||||
for r in result["results"]:
|
||||
r["menu"] = r.get("menu") or _IMPORT_TYPE_MAP[import_type]
|
||||
all_results.append(r)
|
||||
# 类别流程本身失败(元素找不到/登录失败/文件缺失等):合并为一条异常上报,避免在推送中漏报
|
||||
if r.get("error"):
|
||||
exceptions.append({
|
||||
"category": r.get("category", ""),
|
||||
"menu": r.get("menu", ""),
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
for exc in r.get("exceptions") or []:
|
||||
exceptions.append({
|
||||
"category": r.get("category", ""),
|
||||
"menu": r.get("menu", ""),
|
||||
"staff_code": exc["staff_code"],
|
||||
"staff_name": exc["staff_name"],
|
||||
"insurance_name": exc["insurance_name"],
|
||||
"message": exc["message"],
|
||||
})
|
||||
if exceptions:
|
||||
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
|
||||
for exc in exceptions:
|
||||
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
|
||||
exc["category"], exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
# 合并增/减员结果,覆盖写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
|
||||
_write_group_messages_glv("增员/减员", categories, all_results, len(exceptions))
|
||||
return {
|
||||
"success": ok_all,
|
||||
"categories": categories,
|
||||
"details": details,
|
||||
"exceptions": exceptions,
|
||||
"exception_count": len(exceptions),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统「步骤2.5:导出变更清单独立工作簿」(影刀版,单文件自包含)
|
||||
前置:先运行 employer_insurance_schedule.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选,与 employer_insurance_schedule.py 一致):
|
||||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
|
||||
运行:直接执行本文件即可处理全部类别;仅处理部分类别时以列表传参调用
|
||||
main(category_names=['湖畔酒店'])
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from copy import copy
|
||||
from datetime import datetime, date
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from openpyxl import Workbook, load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,与 employer_insurance_schedule.py 一致) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 employer_insurance_schedule.py 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
# 变更清单 sheet 名沿用历史模板命名:无横线、月/日不补前导零(如 8.19 / 8.1)
|
||||
DATE_SHORT = f"{datetime.now().month}.{datetime.now().day}"
|
||||
|
||||
# ---------- 四大类别(与 employer_insurance_schedule.py 的 CATEGORIES 一致) ----------
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(与 employer_insurance_schedule.py 一致) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。
|
||||
|
||||
Args:
|
||||
filename: 目标文件名,如「三十七度-雇主险变更记录-2026.08.20.xlsx」/
|
||||
「水庄餐饮-雇主险变更记录-7.23.xlsx」
|
||||
|
||||
Returns:
|
||||
date 对象;无法解析返回 None
|
||||
"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(datetime.now().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||||
os.path.getmtime(path))
|
||||
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
|
||||
return f"{category['change_sheet_prefix']}{DATE_SHORT}"
|
||||
|
||||
|
||||
# ==================== 步骤2.5:导出变更清单独立工作簿 ====================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_names: list[str] = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance_schedule.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口(与调度步骤保持一致,默认处理三十七度)
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
@@ -0,0 +1,446 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「第二步:筛选复制」(影刀版,单文件自包含)——校验源表(员工花名册)
|
||||
与各类别目标表(各文件夹内最新的「*雇主险变更记录*.xlsx」)文件存在性,
|
||||
从花名册按类别 include/exclude 所属单位筛选数据复制到各自类别目标表,
|
||||
并剔除「入职时间 > 当天」的未来入职员工(当天起自动纳入)。
|
||||
前置/后置及流程设计见 docs/雇主险名额调度/需求文档.md、流程文档.md。
|
||||
@Version: 2.0.0
|
||||
|
||||
设计说明(与 workflows 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 源表读取(pandas):自动定位表头行(B 列=「所属单位」),业务列 B~O 共14列;
|
||||
目标表写入(openpyxl):覆盖写入 + 清空超出的旧行。
|
||||
- 源表缺失时默认懒加载共享「37du花名册导出」模块(share/roster_export.py)自动导出(开关见下方环境变量)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
roster_filter_export_on_missing = true|false 源表缺失时是否自动导出(默认 true)
|
||||
|
||||
运行:直接执行本文件即可完成全部类别筛选复制;仅处理单个类别时以函数传参调用
|
||||
main(category_names=['湖畔酒店']) 或 filter_and_copy_roster(category)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import numbers
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 app 版 config/roster_filter 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d") # 目标表文件名带日期(如 2026.08.13)
|
||||
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx") # 源表(花名册)
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息" # 目标 Sheet
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理,与 app 版 config.CATEGORIES 一致) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」;
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用,与 app 版 config 一致) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。
|
||||
|
||||
Args:
|
||||
filename: 目标文件名,如「三十七度-雇主险变更记录-2026.08.20.xlsx」/
|
||||
「水庄餐饮-雇主险变更记录-7.23.xlsx」
|
||||
|
||||
Returns:
|
||||
datetime 对象;无法解析返回 None
|
||||
"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return datetime(datetime.now().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or datetime.min,
|
||||
os.path.getmtime(path))
|
||||
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
# 过滤规则(与 aa.md 宏一致)
|
||||
EXCLUDE_REGIONS = ["虚拟大区"] # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
|
||||
|
||||
# N列 姓名在数据切片(B~O)内的 0-based 索引
|
||||
NAME_COL = 12
|
||||
|
||||
# M列 入职时间在数据切片(B~O)内的 0-based 索引(入职时间 > 当天的行剔除,未来才入职的不管)
|
||||
JOIN_DATE_COL = 11
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 源表缺失时是否自动调用共享导出模块(默认 true)
|
||||
AUTO_EXPORT_ON_MISSING = os.getenv("roster_filter_export_on_missing", "true").lower() == "true"
|
||||
|
||||
# F列 工号(必须文本格式,否则与「手动维护-在参名单」B列及表内公式匹配失败)
|
||||
CODE_COL = 4 # 数据切片(B~O)内 0-based 索引,即目标表第6列(F列)
|
||||
|
||||
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||||
|
||||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_join_date(value):
|
||||
"""解析入职时间为 date 对象(兼容 datetime/字符串「YYYY-MM-DD」「YYYY.M.D」等)。
|
||||
|
||||
Args:
|
||||
value: 入职时间原始值(datetime / str / 数字等)
|
||||
|
||||
Returns:
|
||||
date 对象;无法解析(含空值)返回 None
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[.\-/年](\d{1,2})[.\-/月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def filter_and_copy_roster(category: dict, employee_file: str = None, target_file: str = None) -> int:
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(CATEGORIES 中的一项),含 name/folder/include_dept/exclude_dept
|
||||
employee_file: 源表路径,默认 {BASE_DIR}\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category["folder"]))
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
probe = pd.read_excel(employee_file, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_file, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~region.isin(EXCLUDE_REGIONS)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
|
||||
# 入职时间 > 当天的行剔除(未来才入职的员工暂不纳入,留到当天再筛选出来)
|
||||
today = datetime.now().date()
|
||||
join_dates = data.iloc[:, JOIN_DATE_COL].map(_parse_join_date)
|
||||
future_mask = join_dates.map(lambda d: d is not None and d > today)
|
||||
n_future = int(future_mask.sum())
|
||||
mask &= ~future_mask
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除 %s,姓名剔除含 %s,剔除未来入职 %d 人)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", " / ".join(EXCLUDE_REGIONS),
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS), n_future)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据,本地化 cell 引用减少开销;F列工号强制文本格式)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
c = cell(row=i, column=j)
|
||||
if j - 2 == CODE_COL:
|
||||
c.value = _to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _export_roster():
|
||||
"""源表缺失时,懒加载共享「37du花名册导出」模块(share/roster_export.py)导出雇主险源表。
|
||||
|
||||
登录态复用「37duHR登录」指令写入的共享 hr_cookies.json(共享模块只读不补登)。
|
||||
"""
|
||||
import importlib.util
|
||||
share_script = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
"share", "roster_export.py")
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("share_roster_export", share_script)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"源表缺失且无法加载共享导出模块 share/roster_export.py({e}),"
|
||||
f"请先运行「37du花名册导出」指令导出花名册到 {EMPLOYEE_FILE}") from e
|
||||
output = mod.export_roster(
|
||||
template_name=EXPORT_TEMPLATE,
|
||||
statuses=["在职"],
|
||||
output_path=EMPLOYEE_FILE,
|
||||
)
|
||||
logger.info("花名册导出完成:%s", output)
|
||||
|
||||
|
||||
def main(category_names: list[str] = None) -> None:
|
||||
"""第二步:文件存在性校验 + 类别筛选复制(源表缺失时自动导出)。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance_schedule.py)。
|
||||
"""
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出
|
||||
if not os.path.exists(EMPLOYEE_FILE):
|
||||
if AUTO_EXPORT_ON_MISSING:
|
||||
logger.info("源表不存在:%s,自动调用导出步骤...", EMPLOYEE_FILE)
|
||||
_export_roster()
|
||||
else:
|
||||
raise FileNotFoundError(f"源表不存在:{EMPLOYEE_FILE}")
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 逐类别筛选复制(目标文件=各文件夹内最新的雇主险变更记录)
|
||||
ok = 0
|
||||
for category in categories:
|
||||
try:
|
||||
target_file = find_latest_target(category["folder"])
|
||||
except FileNotFoundError as e:
|
||||
logger.error("跳过类别[%s]:%s", category["name"], e)
|
||||
continue
|
||||
logger.info("=" * 70)
|
||||
logger.info("处理类别[%s],目标文件:%s", category["name"], target_file)
|
||||
try:
|
||||
n = filter_and_copy_roster(category, target_file=target_file)
|
||||
ok += 1
|
||||
logger.info("类别[%s] 完成,写入 %d 行", category["name"], n)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 处理失败", category["name"])
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成(成功 %d/%d 个类别)。请手动打开各目标文件刷新公式计算结果(Ctrl+S 保存),",
|
||||
ok, len(categories))
|
||||
logger.info("确认无误后运行:python employer_insurance_schedule.py")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
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,876 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查(单文件版,app 与影刀共用)——复用共享 HR 登录态 -> 调用工资卡接口
|
||||
下载在职+离职工资卡数据 -> 核对身份证/姓名/银行卡号 -> 单工作簿输出三个 sheet
|
||||
(工资卡异常名单 / 工资卡完整核对结果 / 工资卡原始数据)
|
||||
-> 结果工作簿路径写入全局变量 messages(由「37du钉钉推送」指令发群聊「数字人沟通群」)。
|
||||
规则:姓名含「虚拟」的记录直接剔除不校验;员工姓名与开户人姓名、身份证均不一致
|
||||
记为「代发」(不算异常,除非银行卡 BIN 核对错误);无工资卡记录并入异常名单。
|
||||
异常 sheet 仅保留精简列(员工姓名/37工号/身份证/组织全路径/入职日期/离职日期/
|
||||
开户人姓名/开户人身份证/银行开户行/银行卡号/备注/合同签署单位/操作人/操作时间/
|
||||
异常原因)。
|
||||
规则见 docs/银行卡检查/需求文档.md。
|
||||
@Version: 1.3.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 登录态复用共享 hr_cookies.json(由「37duHR登录」指令写入),只读、缺失/失效时
|
||||
友好提示先运行登录指令,不自动补登。
|
||||
- 结果打包后仅写影刀全局变量 messages(file 类型,指向 zip),发送由推送指令完成。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install python-dotenv requests pandas openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
可选:wage_card_output_dir=结果输出目录(默认 D:\\资料\\人资\\银行卡检查)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install python-dotenv requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 业务缓存(银行字典等)统一放在 %LOCALAPPDATA%\37duAutomation\BankCardCheck(影刀版独立子目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', 'BankCardCheck'
|
||||
)
|
||||
# 共享登录态 cookies:由「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.sessions', 'hr_cookies.json'
|
||||
)
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
# ---------- 工资卡接口 ----------
|
||||
WAGE_CARD_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
|
||||
BANK_DICT_URL = f"{HR_BASE_URL}/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
BANK_DICT_LIST_FILE = os.path.join(_APP_DATA_DIR, "bank_dict_list.json")
|
||||
BANK_DICT_MAP_FILE = os.path.join(_APP_DATA_DIR, "bank_dict_map.json")
|
||||
|
||||
# ---------- 输出 ----------
|
||||
OUTPUT_DIR = os.getenv("wage_card_output_dir") or r"D:\资料\人资\银行卡检查"
|
||||
RESULT_NAME = "工资卡核对结果.xlsx" # 单工作簿输出(含全部 sheet)
|
||||
|
||||
# ---------- 推送(消息写全局变量 messages,由「37du钉钉推送」指令发群聊) ----------
|
||||
PUSH_GROUP = "数字人沟通群" # 固定推送群名(群全称,按群名精确匹配)
|
||||
|
||||
# ---------- 单工作簿 sheet 名称(按输出顺序) ----------
|
||||
SHEET_ABNORMAL = "工资卡异常名单" # 异常 + 无工资卡(精简列,第一个 sheet 方便直接看)
|
||||
SHEET_FULL = "工资卡完整核对结果" # 全量 + 核对列(含代发标记)
|
||||
SHEET_DATA = "工资卡原始数据" # 接口原始数据(剔除虚拟人员,未核对)
|
||||
|
||||
# ---------- 剔除规则 ----------
|
||||
# 员工姓名含这些关键字的记录直接剔除,不参与核对(人资/测试账号/虚拟账号等)
|
||||
EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"]
|
||||
|
||||
# ---------- 工资卡字段映射 ----------
|
||||
COL_MAP = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "37工号",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "合同签署单位",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "37工号", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "合同签署单位", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# ---------- 异常 sheet 精简列(无银行卡表/异常名单 按此输出) ----------
|
||||
ABNORMAL_COL_MAP = {
|
||||
"员工姓名": "员工姓名",
|
||||
"37工号": "37工号",
|
||||
"身份证号": "身份证",
|
||||
"组织全路径": "组织全路径",
|
||||
"入职日期": "入职日期",
|
||||
"离职日期": "离职日期",
|
||||
"开户人姓名": "开户人姓名",
|
||||
"开户人身份证": "开户人身份证",
|
||||
"开卡银行": "银行开户行",
|
||||
"银行卡号": "银行卡号",
|
||||
"备注": "备注",
|
||||
"合同签署单位": "合同签署单位",
|
||||
"操作人": "操作人",
|
||||
"操作时间": "操作时间",
|
||||
}
|
||||
|
||||
# ---------- 核对相关列名 ----------
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
COL_REMARK = "备注"
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
# ---------- 银行卡校验规则 ----------
|
||||
# 16 位银联卡 BIN(按银行归类,经实际工资卡数据比对核验)
|
||||
BIN_16 = {
|
||||
# 招商银行
|
||||
"621483", "621485", "621486", "622588", "622609",
|
||||
# 民生银行
|
||||
"621691", "622615", "622617", "622619", "622620", "622622",
|
||||
# 民生银行信用卡(16 位贷记卡)
|
||||
"622601",
|
||||
# 重庆农村商业银行
|
||||
"621258", "621465", "621528", "622867",
|
||||
# 浦东发展银行
|
||||
"621792", "621793", "622521",
|
||||
# 其他银行
|
||||
"621499", # 建设银行理财金卡
|
||||
"621755", # 重庆三峡银行
|
||||
"623020", # 华夏银行
|
||||
}
|
||||
# 18 位银联储蓄卡 BIN
|
||||
BIN_18 = {"622908"} # 兴业银行
|
||||
# 非 62 开头但合法的老版储蓄卡 BIN(历史卡仍在使用,标准均为 19 位)
|
||||
NON62_BIN = {
|
||||
"436742", # 建设银行龙卡储蓄卡
|
||||
"601382", # 中国银行长城电子借记卡
|
||||
"955882", # 工商银行牡丹灵通卡
|
||||
}
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
def retry(max_attempts=3):
|
||||
def decorator(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
logger.error("%s 连续 %d 次失败: %s", func.__name__, max_attempts, e)
|
||||
break
|
||||
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
raise last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== 共享登录态(只读共享 cookies,不自动补登) ====================
|
||||
def _ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态 cookies 缺失或失效,需先调用「37duHR登录」指令。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||||
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
return None
|
||||
|
||||
|
||||
# ==================== HR 登录态(requests.Session) ====================
|
||||
def get_hr_session():
|
||||
"""构建 HR requests.Session(只读共享 cookies,缺失/失效抛 LoginRequiredError)。"""
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in cookies)
|
||||
if not has_hr:
|
||||
raise LoginRequiredError(
|
||||
"共享 cookies 中无 hr.37du.co 登录态,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("复用共享 HR 登录态(hr.37du.co,%d 个 cookies)", len(cookies))
|
||||
return _build_hr_session(cookies)
|
||||
|
||||
|
||||
def _build_hr_session(cookies=None):
|
||||
cookies = cookies or _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and c["domain"].endswith("hr.37du.co"):
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 银行字典接口(aa.md 提供) ====================
|
||||
def _fetch_bank_dict(session=None):
|
||||
"""远程调用接口获取银行字典,并写入本地缓存。
|
||||
|
||||
返回 (list[dict], dict[code->name])。
|
||||
"""
|
||||
if session is None:
|
||||
session = get_hr_session()
|
||||
payload = {
|
||||
"codeType": BANK_DICT_CODE_TYPE,
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
|
||||
resp.raise_for_status()
|
||||
resp_json = resp.json()
|
||||
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
|
||||
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
|
||||
for item in raw_list]
|
||||
result_map = {item["code"]: item["name"] for item in result_list}
|
||||
|
||||
_ensure_dir(_APP_DATA_DIR)
|
||||
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_list, f, ensure_ascii=False, indent=2)
|
||||
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_map, f, ensure_ascii=False, indent=2)
|
||||
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
|
||||
return result_list, result_map
|
||||
|
||||
|
||||
def _load_bank_dict_cache():
|
||||
"""读取本地银行字典缓存,失败返回 (None, None)。"""
|
||||
try:
|
||||
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
|
||||
lst = json.load(f)
|
||||
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
|
||||
mp = json.load(f)
|
||||
return lst, mp
|
||||
except Exception as e:
|
||||
logger.warning("银行字典本地缓存读取失败:%s", e)
|
||||
return None, None
|
||||
|
||||
|
||||
def get_bank_dict(session=None, force_refresh=False):
|
||||
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
|
||||
|
||||
:param session: 可选的 HR requests.Session;未提供时自动构建
|
||||
:param force_refresh: True 强制重新调用接口
|
||||
:return: (list版本, map版本)
|
||||
"""
|
||||
need_refresh = force_refresh
|
||||
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
|
||||
need_refresh = True
|
||||
else:
|
||||
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
|
||||
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
|
||||
need_refresh = True
|
||||
|
||||
if need_refresh:
|
||||
try:
|
||||
return _fetch_bank_dict(session)
|
||||
except Exception as e:
|
||||
logger.error("银行字典远程拉取失败:%s", e)
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is not None:
|
||||
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
return [], {}
|
||||
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is None:
|
||||
# 缓存异常时重新拉取
|
||||
return _fetch_bank_dict(session)
|
||||
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
|
||||
|
||||
def _bank_type_to_name(bank_type, bank_map):
|
||||
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
|
||||
if bank_type is None:
|
||||
return ""
|
||||
if isinstance(bank_type, float):
|
||||
if bank_type != bank_type: # NaN
|
||||
return ""
|
||||
bank_type = str(int(bank_type))
|
||||
elif isinstance(bank_type, int):
|
||||
bank_type = str(bank_type)
|
||||
else:
|
||||
bank_type = str(bank_type).strip()
|
||||
return bank_map.get(bank_type, "")
|
||||
|
||||
|
||||
# ==================== 工资卡接口 ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch_wage_card_page(session, status, page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
leave_start=None, leave_end=None):
|
||||
params = {
|
||||
"start": (page_no - 1) * page_size,
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ftl_list_STRU_TREE_CODE": "cq37du",
|
||||
"sortName": "hr_staff_wage_card.STAFF_NAME",
|
||||
"sortType": "asc",
|
||||
"commonQuery": "[]",
|
||||
"person_status": status,
|
||||
}
|
||||
if status == 1:
|
||||
params["leaveOffice_date"] = ""
|
||||
elif leave_start and leave_end:
|
||||
params["leaveOffice_date[0]"] = leave_start
|
||||
params["leaveOffice_date[1]"] = leave_end
|
||||
params["leaveOffice_date_start"] = leave_start
|
||||
params["leaveOffice_date_end"] = leave_end
|
||||
|
||||
resp = session.post(WAGE_CARD_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("工资卡请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if text and not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = text[:200]
|
||||
raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_wage_card(session, status, status_name, leave_start=None, leave_end=None):
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
except HRSessionExpiredError:
|
||||
raise LoginRequiredError(
|
||||
f"【{status_name}】HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("【%s】无更多数据", status_name)
|
||||
break
|
||||
|
||||
for item in page_list:
|
||||
item["人员类型"] = status_name
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total = data.get("count", 0)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
|
||||
status_name, page_no, total_page, len(all_rows), total)
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 离职时间范围 ====================
|
||||
def get_leave_range(today=None):
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 工资卡数据构建(接口原始数据,不落盘) ====================
|
||||
def build_wage_card_df(data_on_job, data_leave):
|
||||
"""合并在职/离职原始数据,字段映射为中文、补充开卡银行并调整列顺序,返回 DataFrame。"""
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法构建工资卡数据")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: _bank_type_to_name(c, bank_map))
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
return df
|
||||
|
||||
|
||||
# ==================== 银行卡校验 ====================
|
||||
def check_bank_card(card_raw):
|
||||
card = str(card_raw).strip()
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw:
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
card_len = len(card)
|
||||
# 纯数字但位数过短(<16 位):填写错误/卡号截断(如只填了 0、123 等),不再走 BIN 校验
|
||||
if card_len < 16:
|
||||
return {"card": card, "status": "无效", "reason": f"卡号过短仅{card_len}位,填写错误"}
|
||||
|
||||
bin6 = card[:6]
|
||||
if not (card.startswith("62") or bin6 in NON62_BIN):
|
||||
# 非银联卡但属国际信用卡(万事达 53/54/55、Visa 4 开头,标准 16 位):
|
||||
# 单独标记「非银联储蓄卡-疑似信用卡」,进异常名单由人工确认,不算格式错误
|
||||
if len(card) == 16 and (card.startswith(("53", "54", "55")) or card.startswith("4")):
|
||||
return {"card": card, "status": "疑似信用卡", "reason": "非银联储蓄卡-疑似信用卡"}
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ==================== 核对分类 ====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
bank_name="", remark=""):
|
||||
"""按核对规则对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, bank_info)
|
||||
issues: 标签(写入核对结果);姓名与身份证均不一致记为「代发」
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
bank_info: 银行卡校验结果 dict(无卡时为 None)
|
||||
规则:
|
||||
1. 开户人身份证/姓名、银行卡三项均空白 -> 统一记为「未提供银行卡」;仅单项空白保留原标签
|
||||
2. 员工姓名与开户人姓名、身份证均不一致 -> 代发(不算异常,除非银行卡 BIN 核对错误)
|
||||
3. 仅身份证不一致 -> 异常;仅姓名不一致(身份证一致)-> 「姓名不一致身份证一致」
|
||||
4. 开卡银行/银行卡号/备注任一列含「现金」-> 直接标记「现金发放」,其余不再核对
|
||||
5. 银行卡非空但格式/位数错误 -> 「银行卡信息异常」并附带原因(异常名单同步展示);
|
||||
纯数字短卡号(<16 位)-> 同上,原因「卡号过短仅X位,填写错误」;
|
||||
非银联国际信用卡(万事达 53/54/55、Visa 4 开头 16 位)-> 「非银联储蓄卡-疑似信用卡」
|
||||
"""
|
||||
# 统一清洗入参:None/NaN 一律归一为空串,保证不同数据源(接口 JSON null / 空字符串 / 表格 NaN)
|
||||
# 判空结果一致,避免 str(None)='None' 被误判为非空导致分支不一致(不同电脑结果不一致问题)
|
||||
idcard = _normalize_id(idcard)
|
||||
card_idcard = _normalize_id(card_idcard)
|
||||
staff_name = _clean_str(staff_name)
|
||||
card_name = _clean_str(card_name)
|
||||
bank_account = _clean_str(bank_account)
|
||||
bank_name = _clean_str(bank_name)
|
||||
remark = _clean_str(remark)
|
||||
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 0. 现金发放优先:开卡银行/银行卡号/备注任一含「现金」-> 直接标记「现金发放」,其余不再核对 ----
|
||||
cash_hit = any("现金" in str(v) for v in (bank_name, bank_account, remark))
|
||||
if cash_hit:
|
||||
return ["现金发放"], ["开卡银行/银行卡号/备注含「现金」,标记为现金发放"], None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白(三项全空合并为「未提供银行卡」,单个还是单个) ----
|
||||
blank_id = _is_empty(card_idcard)
|
||||
blank_name = _is_empty(card_name)
|
||||
blank_bank = _is_empty(bank_account)
|
||||
if blank_id and blank_name and blank_bank:
|
||||
issues.append("未提供银行卡")
|
||||
basis.append("未提供银行卡(开户人姓名/身份证/银行卡均空白)")
|
||||
else:
|
||||
if blank_id:
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if blank_name:
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if blank_bank:
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 代发 / 身份证、姓名不一致(开户人信息非空才比对) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
name_inconsistent = (not _is_empty(card_name)) and staff_name != card_name
|
||||
if id_inconsistent and name_inconsistent:
|
||||
# 姓名与身份证均与开户人不一致 -> 代发卡(薪资代发给他人,不算异常)
|
||||
issues.append("代发")
|
||||
basis.append(f"代发(员工:{staff_name}/{idcard} vs 开户人:{card_name}/{card_idcard})")
|
||||
else:
|
||||
if id_inconsistent:
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
if name_inconsistent:
|
||||
issues.append("姓名不一致身份证一致")
|
||||
basis.append(f"姓名不一致身份证一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 3. 银行卡信息异常(非空但格式/位数错误)或疑似信用卡:标签附带原因,异常名单同步展示 ----
|
||||
if not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
if bank_info["status"] == "疑似信用卡":
|
||||
issues.append("非银联储蓄卡-疑似信用卡")
|
||||
basis.append("非银联储蓄卡-疑似信用卡")
|
||||
else:
|
||||
issues.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
basis.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
|
||||
return issues, basis, bank_info
|
||||
|
||||
|
||||
# ==================== 核对辅助 ====================
|
||||
def _is_empty(val):
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val:
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() in ("nan", "none", "null")
|
||||
|
||||
|
||||
def _clean_str(val):
|
||||
"""安全转字符串并去除首尾空白;None/NaN 返回空串(避免 str(None) 变成 'None' 被误判为非空)。"""
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float) and val != val:
|
||||
return ""
|
||||
return str(val).strip()
|
||||
|
||||
|
||||
def _normalize_id(val):
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val:
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
# ==================== 核对主逻辑 ====================
|
||||
def check_wage_card(wage_data, output_path=None):
|
||||
"""执行核对并输出单工作簿(四个 sheet)。
|
||||
|
||||
Args:
|
||||
wage_data: 工资卡 DataFrame(build_wage_card_df 产出)或汇总表 xlsx 路径
|
||||
output_path: 输出工作簿路径,默认 {OUTPUT_DIR}\\工资卡核对结果.xlsx
|
||||
|
||||
Returns:
|
||||
dict {"核对结果": 工作簿路径}
|
||||
"""
|
||||
if isinstance(wage_data, str):
|
||||
df = pd.read_excel(wage_data)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", wage_data, len(df))
|
||||
else:
|
||||
df = wage_data.copy()
|
||||
logger.info("接收工资卡数据(%d 行)", len(df))
|
||||
|
||||
# 剔除员工姓名含关键字的记录(如「虚拟」测试账号),不参与核对
|
||||
name_raw = df[COL_STAFF_NAME].astype(str).fillna("")
|
||||
exclude_mask = pd.Series(False, index=df.index)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
exclude_mask |= name_raw.str.contains(kw, na=False)
|
||||
if exclude_mask.any():
|
||||
logger.info("剔除姓名含 %s 的记录 %d 条(不参与核对)",
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS), int(exclude_mask.sum()))
|
||||
df = df[~exclude_mask].reset_index(drop=True)
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: _bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
raw_df = df.copy() # 未核对的原始数据(工资卡数据 sheet 用)
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
bank_name=row.get(COL_BANK_NAME, ""), remark=row.get(COL_REMARK, ""),
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"] if bk else ""
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"] if bk else ""
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 输出单工作簿(sheet 顺序:工资卡异常名单 / 工资卡完整核对结果 / 工资卡原始数据)
|
||||
if output_path is None:
|
||||
output_path = os.path.join(OUTPUT_DIR, RESULT_NAME)
|
||||
_ensure_dir(os.path.dirname(output_path))
|
||||
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
full_df = df[check_cols + other_cols] # 完整核对结果(核对列置前)
|
||||
|
||||
# 异常 sheet 精简列视图:按 ABNORMAL_COL_MAP 保留精简列 + 异常原因
|
||||
def _abnormal_view(src):
|
||||
view = pd.DataFrame({
|
||||
out: src.get(col) for col, out in ABNORMAL_COL_MAP.items()
|
||||
})
|
||||
# 异常原因:只保留核对结果标签(括号内详细明细见「工资卡完整核对结果」sheet 的校验依据列)
|
||||
view["异常原因"] = src[COL_CHECK_RESULT]
|
||||
return view
|
||||
|
||||
# 异常名单 = 除「通过」「代发」外的全部记录(纯代发不算异常;代发+BIN错误仍计入)
|
||||
# 按异常原因种类排序(核对结果标签),同类原因聚在一起便于查看
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (df[COL_CHECK_RESULT] != "代发")
|
||||
abnormal_view = _abnormal_view(
|
||||
df[mask].sort_values(COL_CHECK_RESULT, kind="stable")
|
||||
)
|
||||
|
||||
with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
|
||||
abnormal_view.to_excel(writer, sheet_name=SHEET_ABNORMAL, index=False)
|
||||
full_df.to_excel(writer, sheet_name=SHEET_FULL, index=False)
|
||||
raw_df.to_excel(writer, sheet_name=SHEET_DATA, index=False)
|
||||
|
||||
logger.info("核对结果已保存(单工作簿):%s", output_path)
|
||||
logger.info(" %s sheet:%d 条(含无工资卡 %d 条)", SHEET_ABNORMAL, len(abnormal_view), len(no_bank_rows))
|
||||
logger.info(" %s sheet:%d 条(全量)", SHEET_FULL, len(full_df))
|
||||
logger.info(" %s sheet:%d 条", SHEET_DATA, len(raw_df))
|
||||
|
||||
return {"核对结果": output_path,
|
||||
"统计": {"total": len(df), "passed": passed,
|
||||
"abnormal": len(abnormal_view), "no_bank": len(no_bank_rows),
|
||||
"daifa": int((df[COL_CHECK_RESULT] == "代发").sum())}}
|
||||
|
||||
|
||||
# ==================== 结果推送(写全局变量 messages,由推送指令发送) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _build_push_messages(file_path, content):
|
||||
"""构造 dws 群聊推送消息(消息 dict 含 group 键,由「37du钉钉推送」指令发送文件到群)。"""
|
||||
return [{
|
||||
"group": PUSH_GROUP,
|
||||
"content": content,
|
||||
"file_path": file_path,
|
||||
"title": "",
|
||||
"at_all": False,
|
||||
"at_open_ids": "",
|
||||
}]
|
||||
|
||||
|
||||
def _notify_result(result_path, content):
|
||||
"""群聊推送消息写入影刀全局变量 messages(dws 发文件到「数字人沟通群」)。"""
|
||||
if not (result_path and os.path.exists(result_path)):
|
||||
logger.warning("无有效结果工作簿,跳过推送")
|
||||
return
|
||||
_set_glv("messages", _build_push_messages(result_path, content))
|
||||
logger.info("已写全局变量 messages,交由「37du钉钉推送」指令发送 %s 到群「%s」",
|
||||
os.path.basename(result_path), PUSH_GROUP)
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def download_wage_card(save_dir=None):
|
||||
"""下载在职 + 离职工资卡数据,构建并返回工资卡 DataFrame(不落盘)。"""
|
||||
save_dir = save_dir or OUTPUT_DIR
|
||||
# 只读共享登录态;缺失/失效抛 LoginRequiredError 提示先运行「37duHR登录」指令
|
||||
session = get_hr_session()
|
||||
|
||||
# 预检登录态
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
raise LoginRequiredError(
|
||||
"预检发现 HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return build_wage_card_df(data_on_job, data_leave)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 核对并输出单工作簿 -> 结果路径写 messages。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
wage_df = None
|
||||
try:
|
||||
wage_df = download_wage_card()
|
||||
results["工资卡数据"] = f"成功({len(wage_df)} 条)"
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡数据"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对并输出单工作簿 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
result_path = None
|
||||
if wage_df is not None:
|
||||
try:
|
||||
check_result = check_wage_card(wage_df)
|
||||
result_path = check_result.get("核对结果")
|
||||
results["核对结果"] = result_path
|
||||
logger.info("工资卡核对完成:%s", result_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡数据未获取,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 + 推送 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
if result_path:
|
||||
stats = check_result.get("统计", {})
|
||||
content = (
|
||||
"【银行卡检查】核对完成:通过 {passed} / 总计 {total},"
|
||||
"工资卡异常 {abnormal} 人(含无工资卡 {no_bank} 人),"
|
||||
"代发 {daifa} 人,详见附件。"
|
||||
).format(**stats)
|
||||
_notify_result(result_path, content)
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
load_dotenv()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,705 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal.py
|
||||
@Description: 周考勤异常处理(影刀单文件版)- 独立自 app/service/hrbp/ehr/attendance/attendance_abnormal.py,
|
||||
业务逻辑:分页拉取本月(1 号查上月,否则当月)未调整考勤异常 → 导出 Excel → 分级分类
|
||||
(轻微直接自动确认[整月]/其余仅上周钉钉核实)→ 按姓名-工号合并推送当事人(仅上周)
|
||||
→ 生成条数汇总(自动确认数、推送当事人确认数)写入群全局变量。
|
||||
规则见 docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md。
|
||||
@Version: 1.1.0
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
钉钉推送(消息生成与发送解耦,本脚本不内联发送):
|
||||
main() 将待推送 messages(元组列表 (msg_type, name, user_id, content, file_path),即
|
||||
("text", 姓名, 工号, 文本内容, ""))写入影刀全局变量
|
||||
glv['messages'];处理条数汇总(自动确认数、推送当事人确认数)写入 glv['group_messages']
|
||||
(文本列表,每项一条),分别由流程拖「37du钉钉单聊推送」(个人,workflows/share/dingtalk_dws_push.py)/
|
||||
「37du钉钉群机器人推送」(群)指令完成发送。
|
||||
自动确认:仅轻微异常(迟到/早退 < 30 分钟,不分职能序列)自动调用确认接口,确认条数计入群汇总。
|
||||
由 AUTO_CONFIRM_ENABLED 总开关控制(布尔值,默认 True,本次起默认启用;置 False 关闭仅统计不执行)。
|
||||
|
||||
小范围测试按钮(影刀「调用模块」传 main(test_mode=True)):
|
||||
仅筛选所属单位为「集团管理中心」「集团营建中心」「金色印象事业部」、且部门路径不含「大区」
|
||||
的考勤异常作为完整数据源,跑通导出/分级/推送全流程;导出文件名带「测试」、
|
||||
汇总消息标注「小范围测试」,与正式结果区分。筛选条件见 TEST_BELONG_UNITS 常量与 filter_test_units。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 workflows/share/hr_login.py):
|
||||
dingtalk_push_enabled=true|false(默认 false,是否启用钉钉推送,总开关)
|
||||
dingtalk_notify_target=人资专用号钉钉联系人姓名(处理汇总报表推送对象,如 夏一平)
|
||||
attendance_save_dir=(可选)Excel 导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
"(钉钉推送相关依赖 pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/"
|
||||
"rapidocr onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一,见 app/common/app_paths.py) ====================
|
||||
_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')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
# 考勤异常确认/调整接口(type=1 自动确认异常)
|
||||
ATTENDANCE_ADJUST_URL = f"{HR_BASE_URL}/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 默认保存目录(可用环境变量覆盖)
|
||||
SAVE_DIR = os.getenv("attendance_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 手动导出的考勤异常列,仅导出这些列)
|
||||
COL_MAP = {
|
||||
"base_code": "工号",
|
||||
"STAFF_NAME": "姓名",
|
||||
"sex": "性别",
|
||||
"age": "年龄",
|
||||
"ORG_FULL_PATH": "部门路径",
|
||||
"BELONG_UNIT_ORG_NAME": "所属单位",
|
||||
"DEPT_ORG_NAME": "部门",
|
||||
"POST_ORG_NAME": "岗位",
|
||||
"join_date": "入职日期",
|
||||
"work_day": "日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"is_adjusted": "处理状态",
|
||||
"actual_begin_time": "开始时间",
|
||||
"actual_end_time": "结束时间",
|
||||
"abnormal_minute": "时长(分)",
|
||||
"add_reason": "补签原因",
|
||||
"operateName": "操作人",
|
||||
"operateTime": "操作时间",
|
||||
}
|
||||
|
||||
# 导出列顺序(与 aa.md 手动导出一致;「班段」由 begin_time~end_time 合成)
|
||||
SHOW_ORDER = [
|
||||
"工号", "姓名", "性别", "年龄", "部门路径", "所属单位", "部门", "岗位",
|
||||
"入职日期", "日期", "班次", "班段", "异常类型", "处理状态", "处理方式",
|
||||
"开始时间", "结束时间", "时长(分)", "补签原因", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# 处理状态 is_adjusted 编码 → 中文(0=未调整、1=补签调整、2=确认异常、3=正常调整)
|
||||
STATUS_MAP = {
|
||||
"0": "未调整",
|
||||
"1": "补签调整",
|
||||
"2": "确认异常",
|
||||
"3": "正常调整",
|
||||
}
|
||||
|
||||
# 考勤异常调整状态过滤(本次只查询「未调整」);0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有
|
||||
IS_ADJUSTED = "0"
|
||||
# 钉钉推送总开关(True=启用,False=关闭)
|
||||
DINGTALK_PUSH_ENABLED = True
|
||||
# 自动确认总开关(默认启用:整月轻微异常直接批量确认;置 False 关闭仅统计不执行)
|
||||
AUTO_CONFIRM_ENABLED = True
|
||||
# 小范围测试:仅筛选以下所属单位(BELONG_UNIT_ORG_NAME)的考勤异常,且部门路径(ORG_FULL_PATH)
|
||||
# 不含「大区」,作为「完整数据源」跑通全流程。
|
||||
# 影刀流程通过 main(test_mode=True) 触发(即「小范围测试」按钮入口),
|
||||
# 测试数据照常导出/分级/推送,但文件名与汇总消息会标注「测试」以区分正式结果。
|
||||
TEST_BELONG_UNITS = ["集团管理中心", "集团营建中心", "金色印象事业部"]
|
||||
# ======================================================
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件(由「37duHR登录」指令写入);缺失时提示先运行登录指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
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 _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
# ==================== HR 接口 ====================
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": abnormal_type,
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
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 adjust_abnormal(session, abnormal_ids, type_code=1):
|
||||
"""确认/调整考勤异常单据(调用 HR 接口,type=1 自动确认异常)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(按接口约定)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
"""
|
||||
if isinstance(abnormal_ids, (list, tuple)):
|
||||
ids = ",".join(str(i) for i in abnormal_ids)
|
||||
else:
|
||||
ids = str(abnormal_ids)
|
||||
params = {"abnormalIds": ids, "type": type_code}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
|
||||
|
||||
|
||||
def confirm_abnormal(abnormal_ids, type_code=1, session=None):
|
||||
"""确认/调整考勤异常单据(按 abnormal_id 唯一编号),会话为空时自动构建并校验。
|
||||
|
||||
Args:
|
||||
abnormal_ids: 异常单据 id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(默认)
|
||||
session: 已登录会话;为空时自动构建并校验
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
"""
|
||||
if session is None:
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
session, _, _ = _relogin_get_user_info()
|
||||
return adjust_abnormal(session, abnormal_ids, type_code)
|
||||
|
||||
|
||||
def is_mild_abnormal(item):
|
||||
"""轻微异常:迟到/早退 且 异常时长 < 30 分钟(自动确认范围,不分职能序列)。"""
|
||||
return not classify_abnormal(item)
|
||||
|
||||
|
||||
def auto_confirm_mild(data, session=None):
|
||||
"""自动确认轻微异常(迟到/早退 < 30 分钟,不分职能序列)。
|
||||
|
||||
Args:
|
||||
data: 未调整考勤异常记录列表
|
||||
session: 已登录会话;为空时自动构建
|
||||
|
||||
Returns:
|
||||
确认成功的条数
|
||||
"""
|
||||
mild = [it for it in data if is_mild_abnormal(it) and it.get("abnormal_id")]
|
||||
if not mild:
|
||||
logger.info("无轻微异常(迟到/早退<30分钟),跳过自动确认")
|
||||
return 0
|
||||
ids = [it["abnormal_id"] for it in mild]
|
||||
logger.info("自动确认轻微异常 %d 条(不分职能序列)", len(ids))
|
||||
result = confirm_abnormal(ids, session=session)
|
||||
if result.get("state") == "1":
|
||||
logger.info("自动确认接口返回处理成功,共 %d 条", len(ids))
|
||||
return len(ids)
|
||||
logger.error("自动确认失败:%s", result.get("meg") or result)
|
||||
return 0
|
||||
|
||||
|
||||
def build_group_summary(total_count, mild_count, confirmed_count, non_func_count, func_count,
|
||||
push_count, other_count, month, begin, end, test_mode=False):
|
||||
"""生成考勤异常处理条数汇总消息(与汇总日志格式一致,供钉钉群机器人推送)。"""
|
||||
if test_mode:
|
||||
title = "【考勤异常处理汇总(小范围测试)】"
|
||||
else:
|
||||
title = "【考勤异常处理汇总】"
|
||||
return (
|
||||
f"{title}\n\n"
|
||||
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n\n"
|
||||
f"考勤异常总数:{total_count} 条\n\n"
|
||||
f"直接处理(轻微,整月自动确认):{mild_count} 条,确认成功 {confirmed_count} 条\n\n"
|
||||
f"待通知(职能,上周):{func_count} 条,合并为 {push_count} 条推送\n\n"
|
||||
f"上周非职能(不推送):{non_func_count} 条\n\n"
|
||||
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 业务规则(与 app 版一致) ====================
|
||||
def last_week_range(today=None):
|
||||
"""返回上周查询范围:(上周一, 上周日)。
|
||||
|
||||
上周定义:本周一往前推 7 天为上周一,上周一 + 6 天为上周日。
|
||||
"""
|
||||
today = today or date.today()
|
||||
this_monday = today - timedelta(days=today.weekday()) # 本周一
|
||||
last_monday = this_monday - timedelta(days=7)
|
||||
last_sunday = this_monday - timedelta(days=1)
|
||||
return last_monday.strftime("%Y-%m-%d"), last_sunday.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def query_month(today=None):
|
||||
"""本次查询月份:1 号(2 号之前,不含 2 号)查上月,否则查当月。
|
||||
|
||||
当月数据过少(仅 1 天)时补处理上月整月;2 号及以后按当月处理。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day < 2:
|
||||
first_of_this_month = today.replace(day=1)
|
||||
return (first_of_this_month - timedelta(days=1)).strftime("%Y-%m")
|
||||
return today.strftime("%Y-%m")
|
||||
|
||||
|
||||
def in_last_week(item, push_begin, push_end):
|
||||
"""判断异常记录(按 work_day)是否落在上周范围内;work_day 缺失时返回 False。"""
|
||||
work_day = str(item.get("work_day") or "")[:10]
|
||||
return bool(work_day) and push_begin <= work_day <= push_end
|
||||
|
||||
|
||||
def filter_test_units(data, units=None, exclude_path_keyword="大区"):
|
||||
"""小范围测试:仅保留指定所属单位(BELONG_UNIT_ORG_NAME)的考勤异常作为完整数据源,
|
||||
且部门路径(ORG_FULL_PATH)不包含指定关键字(默认排除「大区」)。
|
||||
|
||||
units 为空时返回原数据(不筛选)。
|
||||
"""
|
||||
units = units or TEST_BELONG_UNITS
|
||||
if not units:
|
||||
return data
|
||||
kept = [
|
||||
it for it in data
|
||||
if str(it.get("BELONG_UNIT_ORG_NAME", "") or "").strip() in units
|
||||
and exclude_path_keyword not in str(it.get("ORG_FULL_PATH", "") or "")
|
||||
]
|
||||
logger.warning("小范围测试:所属单位 %s 且部门路径不含「%s」,保留 %d/%d 条",
|
||||
"、".join(units), exclude_path_keyword, len(kept), len(data))
|
||||
return kept
|
||||
|
||||
|
||||
def classify_abnormal(item):
|
||||
"""判断该条异常是否需要钉钉推送。
|
||||
迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常,直接处理);
|
||||
迟到/早退 >= 30 分钟 或 其他类型(旷工/工时不足/漏打卡等)→ 推送。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item):
|
||||
"""判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
|
||||
|
||||
def build_notify_text(items):
|
||||
"""按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。"""
|
||||
first = items[0]
|
||||
lines = [
|
||||
"【考勤异常提醒】",
|
||||
f"姓名:{first.get('STAFF_NAME', '')}",
|
||||
f"工号:{first.get('base_code', '')}",
|
||||
f"共{len(items)}条考勤异常,请在2日内主动对接人事处理考勤异常确认/请假审批/漏打卡监控查询等,"
|
||||
"超时未对接,将视为考勤异常直接封存",
|
||||
]
|
||||
for idx, item in enumerate(items, 1):
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute") or "0"
|
||||
lines.append(
|
||||
f"{idx}、考勤日期:{item.get('work_day', '')}|异常类型:{abnormal}|异常时长:{minute}分钟"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ==================== 导出 Excel ====================
|
||||
def _status_cn(value):
|
||||
"""处理状态 is_adjusted 编码转中文;空值/未知编码保持原样。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
return STATUS_MAP.get(str(value), str(value))
|
||||
|
||||
|
||||
def export_excel(data, save_dir, month_str, test_mode=False):
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
|
||||
# 处理方式:轻微异常(自动确认)/ 需核实(钉钉推送)
|
||||
df["处理方式"] = df.apply(
|
||||
lambda r: "自动确认" if not classify_abnormal(r) else "钉钉推送", axis=1
|
||||
)
|
||||
|
||||
# 班段:班次时段 begin_time~end_time(如 "09:00~18:00",无班段留空)
|
||||
df["班段"] = df.apply(
|
||||
lambda r: (
|
||||
f"{str(r.get('begin_time') or '').strip()}~{str(r.get('end_time') or '').strip()}"
|
||||
if (r.get("begin_time") or r.get("end_time")) else ""
|
||||
),
|
||||
axis=1,
|
||||
)
|
||||
|
||||
# 英文字段 → 中文字段
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
|
||||
# 处理状态:is_adjusted 编码转中文
|
||||
if "处理状态" in df.columns:
|
||||
df["处理状态"] = df["处理状态"].apply(_status_cn)
|
||||
|
||||
# 仅保留 aa.md 目标列(顺序一致;缺失列补空)
|
||||
for col in SHOW_ORDER:
|
||||
if col not in df.columns:
|
||||
df[col] = ""
|
||||
df = df[SHOW_ORDER]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
# 测试模式:文件名标注「测试」,与正式结果区分,避免误用
|
||||
prefix = "周考勤异常_测试" if test_mode else "周考勤异常"
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"{prefix}_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("考勤异常数据:%d 条", len(data))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 钉钉推送(总开关控制) ====================
|
||||
def push_abnormal(items):
|
||||
"""按「工号-姓名」分组,合并为 messages 元组列表,写入影刀全局变量 messages,
|
||||
由流程拖「37du钉钉单聊推送」指令(workflows/share/dingtalk_dws_push.py)发送(本脚本不内联发送,
|
||||
保持单文件自包含)。
|
||||
每项为 (msg_type, name, user_id, content, file_path) 五元组,此处均为 ("text", 姓名, 工号, 文本, ""):
|
||||
msg_type 消息类型,文本推送固定 "text"
|
||||
name 接收人姓名(发文本时仅用于记录/展示)
|
||||
user_id 接收人工号(dws 按工号发送,避免同名误发)
|
||||
content 消息内容
|
||||
file_path 文件地址(文本推送留空)
|
||||
返回 (待推送条数, 失败数=0)。
|
||||
"""
|
||||
groups = {}
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
key = (it.get("base_code", "") or "", name)
|
||||
groups.setdefault(key, []).append(it)
|
||||
|
||||
messages = []
|
||||
for (code, name), group in groups.items():
|
||||
# 消息类型固定 "text",工号用于 dws 按工号发送,姓名用于记录
|
||||
messages.append(("text", name, code, build_notify_text(group), ""))
|
||||
# 写入影刀全局变量,供流程「37du钉钉单聊推送」指令读取(无数据也置空,避免 NameError)
|
||||
_set_glv('messages', messages)
|
||||
logger.info("当事人消息已生成并写入全局变量 messages:共 %d 条(由流程推送)", len(messages))
|
||||
return len(messages), 0
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_attendance_abnormal(save_dir=None, month=None, test_mode=False):
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
|
||||
# 1. 会话:复用共享登录态,必要时补登
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,自动补登")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
info = {"userId": user_id, "rootId": treecode}
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
|
||||
# 2. 查询范围:整月(1 号查上月,否则当月);推送仍按上周(周一~周日)
|
||||
month = month or query_month()
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s(%s 整月),调整状态:%s =====",
|
||||
begin, end, month, IS_ADJUSTED or "所有")
|
||||
|
||||
# 3. 拉取数据
|
||||
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end, IS_ADJUSTED)
|
||||
# 小范围测试:仅保留指定所属单位数据,作为完整数据源跑通全流程
|
||||
if test_mode:
|
||||
data = filter_test_units(data)
|
||||
if not data:
|
||||
logger.info("本月(%s)无考勤异常数据,跳过导出与推送", month)
|
||||
return None
|
||||
|
||||
# 4. 导出 Excel 底稿
|
||||
month_str = month or end[:7] # 文件名月份标识取上周日所在月
|
||||
path = export_excel(data, save_dir, month_str, test_mode=test_mode)
|
||||
|
||||
# 5. 分级分类:轻微异常整月自动确认;需推送的仅上周(周一~周日)严重异常
|
||||
mild_list = [it for it in data if not classify_abnormal(it)]
|
||||
push_begin, push_end = last_week_range()
|
||||
push_list = [it for it in data if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
|
||||
other_list = [it for it in data if classify_abnormal(it) and not in_last_week(it, push_begin, push_end)]
|
||||
func_list = [it for it in push_list if is_func_staff(it)]
|
||||
non_func_list = [it for it in push_list if not is_func_staff(it)]
|
||||
|
||||
# 6. 自动确认轻微异常(整月,迟到/早退<30分钟,不分职能序列)——总开关 AUTO_CONFIRM_ENABLED 控制
|
||||
# 统计不受开关影响:始终按数据计算实际条数,便于查看真实情况(开关只决定是否真正调用确认接口)
|
||||
mild_count = len([it for it in mild_list if it.get("abnormal_id")])
|
||||
if AUTO_CONFIRM_ENABLED:
|
||||
confirmed_count = auto_confirm_mild(mild_list, session=session)
|
||||
else:
|
||||
confirmed_count = 0
|
||||
logger.warning("自动确认未启用(AUTO_CONFIRM_ENABLED=%s),仅统计待自动确认 %d 条,未执行确认",
|
||||
AUTO_CONFIRM_ENABLED, mild_count)
|
||||
|
||||
# 7. 钉钉推送(总开关控制)
|
||||
push_count, fail_count = 0, 0
|
||||
if DINGTALK_PUSH_ENABLED:
|
||||
if func_list:
|
||||
push_count, fail_count = push_abnormal(func_list)
|
||||
else:
|
||||
logger.info("无需推送的异常,跳过当事人钉钉通知")
|
||||
logger.info("当事人推送完成:成功 %d 条,失败 %d 条", push_count, fail_count)
|
||||
else:
|
||||
logger.info("钉钉推送未启用(dingtalk_push_enabled!=true),未发送任何钉钉消息")
|
||||
|
||||
# 8. 汇总日志 + 钉钉群条数汇总(与日志格式一致)
|
||||
logger.info("=" * 60)
|
||||
if test_mode:
|
||||
logger.info("【考勤异常处理汇总(小范围测试)】")
|
||||
else:
|
||||
logger.info("【考勤异常处理汇总】")
|
||||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||||
logger.info(" 直接处理(轻微,整月自动确认):%d 条,确认成功 %d 条", mild_count, confirmed_count)
|
||||
logger.info(" 待通知(职能,上周):%d 条,合并为 %d 条推送", len(func_list), push_count)
|
||||
logger.info(" 上周非职能(不推送):%d 条", len(non_func_list))
|
||||
logger.info(" 本月其他严重异常(非上周,仅导出留痕):%d 条", len(other_list))
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
group_message = build_group_summary(
|
||||
len(data), mild_count, confirmed_count, len(non_func_list), len(func_list), push_count,
|
||||
len(other_list), month, begin, end, test_mode=test_mode)
|
||||
_set_glv('group_messages', [group_message])
|
||||
logger.info("处理条数汇总已写入全局变量 group_messages:%s", group_message)
|
||||
return path
|
||||
|
||||
|
||||
def main(save_dir=None, month=None, test_mode=False):
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行,仅支持关键字参数。
|
||||
|
||||
参数说明:
|
||||
save_dir: 导出目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM";默认本月(1 号查上月,否则当月);指定则查该月
|
||||
test_mode: True=小范围测试:仅筛选 TEST_BELONG_UNITS 所属单位数据跑通全流程,默认 False
|
||||
|
||||
例:
|
||||
main() # 正式全量
|
||||
main(test_mode=True) # 小范围测试(按 TEST_BELONG_UNITS 筛选且排除大区)
|
||||
main(test_mode=True, month="2026-08")
|
||||
"""
|
||||
# 始终定义影刀全局变量 messages / group_messages(默认空),避免后续流程步骤引用时 NameError
|
||||
_set_glv('messages', [])
|
||||
_set_glv('group_messages', [])
|
||||
if not save_dir:
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
if not month:
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
if not test_mode and len(sys.argv) > 3:
|
||||
test_mode = str(sys.argv[3]).strip().lower() in ("1", "true", "yes", "on")
|
||||
try:
|
||||
out = handle_attendance_abnormal(save_dir, month, test_mode)
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:本月无数据 =====")
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("考勤异常处理失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(test_mode=True)
|
||||
@@ -0,0 +1,791 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: social_change.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07
|
||||
@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——复用共享 OA 登录态导出参保/停保名单
|
||||
-> 清洗去重 -> 复用共享 HR 登录态核对参保记录 -> 追加结果列
|
||||
-> 写全局变量 messages(文本汇总+表文件,单文件直接推/多文件打包 zip,
|
||||
由「37du钉钉单聊推送」指令发送)。
|
||||
业务判定及规则见 docs/社保增减名单/需求文档.md。
|
||||
@Version: 2.3.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- OA 登录态复用共享 oa_cookies.json(由「37duOA登录」指令写入),HR 登录态复用共享
|
||||
hr_cookies.json(由「37duHR登录」指令写入);均只读,缺失/失效时友好提示先运行
|
||||
对应登录指令,不自动补登。
|
||||
- 结果推送写全局变量 messages(text 汇总 + file 附件),发送由「37du钉钉单聊推送」指令完成。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv requests xlrd openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
可选:social_change_query_date=查询起始日期(如 2026-08-01,默认当月1号)
|
||||
social_change_output_dir=结果输出目录(默认 D:\资料\人资\员工社保增减名单)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from urllib.parse import urljoin, urlparse, parse_qs
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import xlrd
|
||||
from openpyxl import load_workbook as _load_workbook
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
from openpyxl.styles import PatternFill, Font, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage python-dotenv requests xlrd openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 共享登录态 cookies 统一由对应登录指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\
|
||||
_SHARED_SESSIONS_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.sessions'
|
||||
)
|
||||
# OA 登录态 cookies:由「37duOA登录」指令写入(只读,缺失/失效提示先运行登录指令,不自动补登)
|
||||
COOKIE_FILE_OA = os.path.join(_SHARED_SESSIONS_DIR, 'oa_cookies.json')
|
||||
# HR 登录态 cookies:由「37duHR登录」指令写入(只读,缺失/失效提示先运行登录指令,不自动补登)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SHARED_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619903d5"
|
||||
LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp"
|
||||
SEARCH_URL = f"{BASE_URL}/sys/search/search.do"
|
||||
MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
DEFAULT_FIXED_PARAMS = {
|
||||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||||
"canClose": "false", "isNew": "true",
|
||||
"j_aside": "false", "j_rIframe": "true", "j_iframe": "true",
|
||||
}
|
||||
DEFAULT_EXPORT_COLUMNS = (
|
||||
"fd_38e9dd25e050e0;docCreator;fd_38d49cbc0ceeae;"
|
||||
"fd_390c6988e241ea;fd_390c639f265c78;fd_38e77e5cd6e9fe;"
|
||||
"fd_38d49cd67211e2;fd_38d49cd73eff02;fd_38deea220dc8c4;docStatus"
|
||||
)
|
||||
DEFAULT_EXPORT_COLUMNS_SUSPEND = (
|
||||
"fd_38d32213b2e9cc;fd_38d322164f42f2;fd_38e6887c2b3690;"
|
||||
"fd_3ec504d4c63e02;fd_38dad8035e33e4;fd_38e6887d6b0088;"
|
||||
"fd_38d32227f7a496;fd_38dee9ae569d6a;fd_38e687e91f4fc6;"
|
||||
"fd_38e687eb56dc4c;docStatus;docPublishTime"
|
||||
)
|
||||
MENU_NAME_PARTICIPATE = "员工参保申请"
|
||||
MENU_NAME_SUSPEND = "员工停保申请"
|
||||
FILTER_IDX_PARTICIPATE = "2"
|
||||
FILTER_IDX_SUSPEND = "3"
|
||||
|
||||
# ---------- HR 参保记录核对(si_main 接口) ----------
|
||||
SI_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
|
||||
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
|
||||
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
|
||||
"postStruId": "1", "regist_property": "", "identity": "",
|
||||
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
|
||||
"siName": "", "belongUnitId": "", "belongUnitName": "",
|
||||
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
SI_RESULT_COL = "社保记录查询结果"
|
||||
SI_BATCH_SIZE = 15
|
||||
|
||||
# ---------- 打包推送(结果写全局变量 messages,由「37du钉钉单聊推送」指令发送) ----------
|
||||
PUSH_RECEIVER_NAME = "周卫"
|
||||
PUSH_RECEIVER_ID = "37001166"
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
def decorator(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
logger.error("%s 连续 %d 次尝试失败: %s", func.__name__, max_attempts, e)
|
||||
break
|
||||
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== Cookies 读取(共享登录态,只读) ====================
|
||||
def _ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def load_cookies(path):
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ==================== OA 会话(复用共享登录态) ====================
|
||||
def is_oa_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需启动浏览器)。"""
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("OA 会话已失效: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_oa_session():
|
||||
"""从共享 oa_cookies.json 构建 OA 会话(SessionPage + ChromiumPage)。
|
||||
缺失/失效抛 LoginRequiredError,提示先运行「37duOA登录」指令。"""
|
||||
cookies = load_cookies(COOKIE_FILE_OA)
|
||||
if not cookies:
|
||||
raise LoginRequiredError("未找到 OA 登录态 cookies,请先调用「37duOA登录」指令完成登录后再重试。")
|
||||
session = SessionPage()
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
if hasattr(session, 'session'):
|
||||
session.session.headers.update({
|
||||
"Referer": LIST_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||||
})
|
||||
if not is_oa_session_valid(session):
|
||||
raise LoginRequiredError("OA 登录态已失效,请先重新调用「37duOA登录」指令完成登录后再重试。")
|
||||
browser = ChromiumPage()
|
||||
browser.set.cookies(cookies)
|
||||
return browser, session
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies,只读不补登) ====================
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态 cookies 缺失或失效,需先调用「37duHR登录」指令。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||||
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
return None
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
"""构建 HR requests.Session(只读共享 cookies,缺失/失效抛 LoginRequiredError)。"""
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in cookies)
|
||||
if not has_hr:
|
||||
raise LoginRequiredError(
|
||||
"共享 cookies 中无 hr.37du.co 登录态,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("复用共享 HR 登录态(hr.37du.co,%d 个 cookies)", len(cookies))
|
||||
return _build_hr_session(cookies)
|
||||
|
||||
|
||||
def _build_hr_session(cookies=None):
|
||||
cookies = cookies or _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and c["domain"].endswith("hr.37du.co"):
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 导出(fdId / searchId / 总数 / 导出) ====================
|
||||
def _check_response(resp, action):
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{action}失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{action}失败,状态码: {resp.status_code}")
|
||||
|
||||
|
||||
def _resolve_query_date(query_date=None):
|
||||
return query_date or datetime.now().strftime("%Y-%m-01")
|
||||
|
||||
|
||||
def _build_filter_params(filter_idx, query_date=None):
|
||||
day = _resolve_query_date(query_date)
|
||||
# ge=不早于(包含起始日当天):申请日期 >= 当月1号
|
||||
return {f"v0_{filter_idx}": "ge", f"v1_{filter_idx}": day}
|
||||
|
||||
|
||||
def _get_cookies_with_domain(session):
|
||||
cookies = []
|
||||
try:
|
||||
raw = session.session.cookies
|
||||
for c in raw:
|
||||
cookies.append({"name": c.name, "value": c.value, "domain": c.domain, "path": c.path or "/"})
|
||||
except Exception:
|
||||
cookies = load_cookies(COOKIE_FILE_OA) or []
|
||||
return cookies
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session, browser=None):
|
||||
own_browser = browser is None
|
||||
if own_browser:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||||
browser = ChromiumPage(ChromiumOptions())
|
||||
browser.set.cookies(cookies)
|
||||
try:
|
||||
browser.listen.start()
|
||||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
# 兜底:若浏览器 cookies 失效会停在登录页,快速失败避免空等,且异常含『登录』可触发主流程自动重登
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
deadline = time.time() + 10
|
||||
target = None
|
||||
while time.time() < deadline:
|
||||
req = browser.listen.wait(timeout=1)
|
||||
if req and 'sysPortalNav.do' in req.url:
|
||||
target = req
|
||||
break
|
||||
if target is None:
|
||||
raise RuntimeError("超时未监听到菜单请求,请检查网络或登录态")
|
||||
qs = parse_qs(urlparse(target.url).query)
|
||||
fd_id = qs.get('fdId', [None])[0]
|
||||
if not fd_id:
|
||||
raise RuntimeError("菜单请求中未包含 fdId")
|
||||
logger.info("动态获取到 fdId: %s", fd_id)
|
||||
return fd_id
|
||||
finally:
|
||||
browser.listen.stop()
|
||||
if own_browser:
|
||||
browser.quit()
|
||||
|
||||
|
||||
def get_search_id_from_menu(session, fd_id, menu_name=MENU_NAME_PARTICIPATE):
|
||||
params = {"method": "portlet", "fdId": fd_id, "f_s": "sourcejs", "t": str(int(time.time() * 1000))}
|
||||
session.get(f"{BASE_URL}{MENU_API_PATH}", params=params)
|
||||
_check_response(session.response, "获取菜单")
|
||||
data = session.response.json()
|
||||
|
||||
def find_item(items):
|
||||
for item in items:
|
||||
if item.get("text") == menu_name:
|
||||
return item
|
||||
if "children" in item:
|
||||
found = find_item(item["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
items = data if isinstance(data, list) else data.get("children", [])
|
||||
item = find_item(items)
|
||||
if not item:
|
||||
raise RuntimeError(f"菜单中未找到 '{menu_name}'")
|
||||
qs = parse_qs(urlparse(urljoin(BASE_URL, item["href"])).query)
|
||||
search_id = qs.get("searchId", [None])[0]
|
||||
if not search_id:
|
||||
raise RuntimeError("菜单链接中未包含 searchId")
|
||||
logger.info("从菜单获取到 searchId: %s", search_id)
|
||||
return search_id
|
||||
|
||||
|
||||
def get_total_count(session, base_params, search_id, timestamp):
|
||||
params = {"method": "result", "searchId": search_id, "j_timestamp": timestamp, **base_params}
|
||||
session.get(SEARCH_URL, params=params, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "查询总数")
|
||||
html = session.response.text
|
||||
for pat in (r'exportNum:\s*"(\d+)"', r'总记录数[::]\s*(\d+)', r'共\s*(\d+)\s*条'):
|
||||
m = re.search(pat, html)
|
||||
if m:
|
||||
total = int(m.group(1))
|
||||
logger.info("获取到总记录数: %d", total)
|
||||
return total
|
||||
logger.warning("未找到总条数,默认为 0")
|
||||
return 0
|
||||
|
||||
|
||||
def export_all_data(session, base_params, total, columns, search_id, timestamp):
|
||||
data = {
|
||||
"method": "exportResult", "searchId": search_id, "j_timestamp": timestamp, **base_params,
|
||||
"fdColumns": columns, "fdNum": str(total), "fdNumStart": "1", "fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true", "checkIdValues": "",
|
||||
}
|
||||
session.post(SEARCH_URL, data=data, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "导出数据")
|
||||
return session.response.content
|
||||
|
||||
|
||||
# ==================== 读取 + 清洗去重 ====================
|
||||
def _normalize_date_key(value):
|
||||
if value is None:
|
||||
return 0.0
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
if isinstance(value, str):
|
||||
m = re.match(r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})", value.strip())
|
||||
if m:
|
||||
try:
|
||||
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
return (datetime(y, mo, d) - datetime(1899, 12, 30)).days
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _date_display(value, wb):
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
dt = xlrd.xldate_as_datetime(float(value), wb.datemode)
|
||||
except Exception:
|
||||
return value
|
||||
if float(value).is_integer():
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return value
|
||||
|
||||
|
||||
def _read_and_clean(xls_path):
|
||||
wb = xlrd.open_workbook(xls_path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
|
||||
def find_col(keyword):
|
||||
for i, h in enumerate(headers):
|
||||
if keyword in h:
|
||||
return i
|
||||
return None
|
||||
|
||||
emp_col = find_col("工号")
|
||||
date_col = find_col("申请日期")
|
||||
status_col = find_col("文档状态")
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
rows = []
|
||||
for r in range(1, sh.nrows):
|
||||
row = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if sh.cell_type(r, c) == xlrd.XL_CELL_DATE:
|
||||
v = _date_display(v, wb)
|
||||
row.append(v)
|
||||
emp = str(row[emp_col]).strip()
|
||||
if not emp:
|
||||
continue
|
||||
if status_col is not None and str(row[status_col]).strip() == "废弃":
|
||||
continue
|
||||
row[emp_col] = emp
|
||||
rows.append(row)
|
||||
|
||||
latest = {}
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
key = _normalize_date_key(row[date_col]) if date_col is not None else 0.0
|
||||
if emp not in latest or key > latest[emp][0]:
|
||||
latest[emp] = (key, row)
|
||||
|
||||
ordered, seen = [], set()
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
if emp not in seen:
|
||||
seen.add(emp)
|
||||
ordered.append(latest[emp][1])
|
||||
|
||||
logger.info("清洗完成:去掉废弃后 %d 条,去重后 %d 条", len(rows), len(ordered))
|
||||
return headers, ordered, emp_col
|
||||
|
||||
|
||||
# ==================== HR 参保记录核对 ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _si_is_expired(text):
|
||||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _si_query_batch(session, codes_batch):
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
|
||||
resp.raise_for_status()
|
||||
if _si_is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _si_found_codes(response_json):
|
||||
datas = response_json.get("datas") or []
|
||||
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
|
||||
|
||||
|
||||
def _si_check_batch(session, codes_batch):
|
||||
"""返回这一批中『能查到参保记录』的工号集合;查询失败上抛,由调用方决定重登或标注异常。"""
|
||||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||||
|
||||
|
||||
def _si_preflight(session):
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期/异常抛 LoginRequiredError 提示先运行登录指令。"""
|
||||
try:
|
||||
_si_query_batch(session, ["0"])
|
||||
except HRSessionExpiredError as e:
|
||||
raise LoginRequiredError(
|
||||
f"预检发现 HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试: {e}")
|
||||
except Exception as e:
|
||||
# 网络超时也可能由 cookies 过期(重定向到登录页后加载超时)引发,同样按登录态失效处理
|
||||
raise LoginRequiredError(
|
||||
f"预检查询异常(可能 HR 登录态已过期),请先重新调用「37duHR登录」指令完成登录后再重试: {e}")
|
||||
return session
|
||||
|
||||
|
||||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".", session=None):
|
||||
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。
|
||||
|
||||
session 由调用方预检后传入(复用,避免重复探测);为 None 时内部自行预检。
|
||||
"""
|
||||
unique_codes, seen = [], set()
|
||||
for row in rows:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code and code not in seen:
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
if session is None:
|
||||
session = _si_preflight(get_hr_session())
|
||||
found = set()
|
||||
failed_codes = set()
|
||||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||||
try:
|
||||
found |= _si_check_batch(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
# 登录态失效时不自动补登,上抛提示先重新运行「37duHR登录」指令(避免大批误标异常)
|
||||
raise LoginRequiredError(
|
||||
f"HR 登录态已过期(第 {min(i + SI_BATCH_SIZE, len(unique_codes))}/{len(unique_codes)} 批),"
|
||||
f"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
except Exception as e:
|
||||
# 网络超时/其它异常:宁可标注查询异常,也不当作『无记录』避免误判
|
||||
logger.warning("参保记录查询失败(该批标注查询异常,需人工复核): %s", e)
|
||||
failed_codes |= set(batch)
|
||||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3)
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in rows:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code in failed_codes:
|
||||
val = "异常:参保记录查询失败,需人工复核"
|
||||
else:
|
||||
has_record = code in found
|
||||
if is_participate:
|
||||
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
|
||||
else:
|
||||
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
|
||||
new_rows.append(row + [val])
|
||||
|
||||
out_path = os.path.abspath(os.path.join(output_dir, f"{base_name}_参保核对.xlsx"))
|
||||
out_wb = _XlsxWorkbook()
|
||||
|
||||
# 样式:异常行标红 + 结果列加粗红字(仅当样式可用)
|
||||
red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") if PatternFill else None
|
||||
red_font = Font(color="9C0006", bold=True) if Font else None
|
||||
head_fill = PatternFill(start_color="DDEBF7", end_color="DDEBF7", fill_type="solid") if PatternFill else None
|
||||
|
||||
ws = out_wb.active
|
||||
ws.title = "核对明细"
|
||||
ws.append(headers + [SI_RESULT_COL])
|
||||
for c in range(1, len(headers) + 2):
|
||||
cell = ws.cell(1, c)
|
||||
cell.fill = head_fill
|
||||
cell.font = Font(bold=True) if Font else None
|
||||
cell.alignment = Alignment(horizontal="center") if Alignment else None
|
||||
for idx, row in enumerate(new_rows, start=2):
|
||||
ws.append(row)
|
||||
if str(row[-1]).startswith("异常"):
|
||||
for c in range(1, len(row) + 1):
|
||||
cell = ws.cell(idx, c)
|
||||
cell.fill = red_fill
|
||||
if c == len(row):
|
||||
cell.font = red_font
|
||||
ws.freeze_panes = "A2"
|
||||
ws.auto_filter.ref = ws.dimensions
|
||||
if get_column_letter:
|
||||
for c in range(1, len(headers) + 2):
|
||||
ws.column_dimensions[get_column_letter(c)].width = 20
|
||||
|
||||
out_wb.save(out_path)
|
||||
|
||||
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
|
||||
logger.info("参保核对完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
|
||||
len(unique_codes), len(found), len(abnormal), out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ==================== 导出 + 核对一条龙 ====================
|
||||
def export_employee_change_list(menu_name, filter_idx, columns, output_dir, query_date=None):
|
||||
logger.info("社保增减名单核对流程开始,菜单:%s", menu_name)
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **_build_filter_params(filter_idx, query_date)}
|
||||
|
||||
# 预检 HR 登录态:缺失/失效抛 LoginRequiredError 提示先运行「37duHR登录」指令
|
||||
hr_session = _si_preflight(get_hr_session())
|
||||
|
||||
# 获取 OA 会话:缺失/失效抛 LoginRequiredError 提示先运行「37duOA登录」指令
|
||||
browser, session = get_oa_session()
|
||||
try:
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
output_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir,
|
||||
session=hr_session)
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
return final_path
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e)
|
||||
# 登录态失效(OA/HR):直接上抛,提示先运行对应登录指令,不自动补登
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(output_dir=".", query_date=None):
|
||||
return export_employee_change_list(
|
||||
MENU_NAME_PARTICIPATE, FILTER_IDX_PARTICIPATE, DEFAULT_EXPORT_COLUMNS, output_dir, query_date)
|
||||
|
||||
|
||||
def export_suspension(output_dir=".", query_date=None):
|
||||
return export_employee_change_list(
|
||||
MENU_NAME_SUSPEND, FILTER_IDX_SUSPEND, DEFAULT_EXPORT_COLUMNS_SUSPEND, output_dir, query_date)
|
||||
|
||||
|
||||
# ==================== 结果推送(写全局变量 messages,由「37du钉钉单聊推送」指令发送) ====================
|
||||
def _read_abnormal(xlsx_path, label):
|
||||
"""读取标注表,返回 (总条数, 异常行列表)。异常行形如 [工号, 申请人/姓名, 结果] 说明文本。"""
|
||||
if not os.path.exists(xlsx_path):
|
||||
return 0, []
|
||||
ws = _load_workbook(xlsx_path).active
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
headers = [str(h) if h is not None else "" for h in rows[0]]
|
||||
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
|
||||
res_col = headers.index(SI_RESULT_COL)
|
||||
name_candidates = ("参保人",) if label == "参保" else ("停保人姓名",)
|
||||
name_col = next((i for i, h in enumerate(headers) if h in name_candidates), None)
|
||||
abnormal = []
|
||||
for r in rows[1:]:
|
||||
val = r[res_col] if res_col < len(r) else ""
|
||||
if val and str(val).startswith("异常"):
|
||||
emp = str(r[emp_col]) if emp_col is not None and emp_col < len(r) else ""
|
||||
name = str(r[name_col]) if name_col is not None and name_col < len(r) else ""
|
||||
abnormal.append(f" · 工号{emp} {name} —— {val}")
|
||||
return len(rows) - 1, abnormal
|
||||
|
||||
|
||||
def build_push_text(part_path, susp_path):
|
||||
p_total, p_abn = _read_abnormal(part_path, "参保")
|
||||
s_total, s_abn = _read_abnormal(susp_path, "停保")
|
||||
lines = ["【社保增减名单核对结果】"]
|
||||
lines.append(f"参保表:共 {p_total} 条,异常 {len(p_abn)} 条")
|
||||
if p_abn:
|
||||
lines.extend(p_abn)
|
||||
else:
|
||||
lines.append(" 无异常")
|
||||
lines.append("")
|
||||
lines.append(f"停保表:共 {s_total} 条,异常 {len(s_abn)} 条")
|
||||
if s_abn:
|
||||
lines.extend(s_abn)
|
||||
else:
|
||||
lines.append(" 无异常")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _package_files(paths, save_dir):
|
||||
"""单文件直接返回原路径;多文件打包 zip(时间戳命名);无有效文件返回 None。"""
|
||||
exist_files = [p for p in paths if p and os.path.exists(p)]
|
||||
if not exist_files:
|
||||
return None
|
||||
if len(exist_files) == 1:
|
||||
return exist_files[0]
|
||||
_ensure_dir(save_dir)
|
||||
zip_path = os.path.join(
|
||||
save_dir,
|
||||
f"社保增减名单_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip",
|
||||
)
|
||||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for fp in exist_files:
|
||||
zf.write(fp, os.path.basename(fp))
|
||||
logger.info("多文件已打包 %d 个到 %s", len(exist_files), zip_path)
|
||||
return zip_path
|
||||
|
||||
|
||||
def _build_push_messages(part_path, susp_path, save_dir):
|
||||
"""构造 dws 单聊推送消息:先发文本汇总,再发表文件(单文件直接推,多文件打包 zip)。"""
|
||||
messages = [{
|
||||
"msg_type": "text",
|
||||
"name": PUSH_RECEIVER_NAME,
|
||||
"user_id": PUSH_RECEIVER_ID,
|
||||
"content": build_push_text(part_path, susp_path),
|
||||
"file_path": "",
|
||||
}]
|
||||
file_target = _package_files([part_path, susp_path], save_dir)
|
||||
if file_target:
|
||||
messages.append({
|
||||
"msg_type": "file",
|
||||
"name": PUSH_RECEIVER_NAME,
|
||||
"user_id": PUSH_RECEIVER_ID,
|
||||
"content": "",
|
||||
"file_path": file_target,
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
load_dotenv()
|
||||
args = sys.argv[1:]
|
||||
output_dir = os.getenv("social_change_output_dir") or r"D:\资料\人资\员工社保增减名单"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
query_date = None
|
||||
change_type = "全部"
|
||||
for a in args:
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2}$", a):
|
||||
query_date = a
|
||||
elif a in ("参保", "participate"):
|
||||
change_type = "参保"
|
||||
elif a in ("停保", "suspend"):
|
||||
change_type = "停保"
|
||||
|
||||
if query_date is None:
|
||||
query_date = os.getenv("social_change_query_date") or None
|
||||
|
||||
part_path = ""
|
||||
susp_path = ""
|
||||
if change_type in ("参保", "全部"):
|
||||
part_path = export_participation(output_dir=output_dir, query_date=query_date)
|
||||
if change_type in ("停保", "全部"):
|
||||
susp_path = export_suspension(output_dir=output_dir, query_date=query_date)
|
||||
|
||||
# 写全局变量 messages(dws 单聊推送:文本汇总 + 表文件,单文件直接推/多文件打包 zip)
|
||||
if part_path or susp_path:
|
||||
messages = _build_push_messages(part_path, susp_path, output_dir)
|
||||
_set_glv("messages", messages)
|
||||
logger.info("已写全局变量 messages(%d 条),交由「37du钉钉单聊推送」指令发送给 %s(%s)",
|
||||
len(messages), PUSH_RECEIVER_NAME, PUSH_RECEIVER_ID)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,409 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: generate_add.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保增员导入名单制作 —— 单文件自包含版(影刀直接运行)
|
||||
1. 读取《XX月社保变更及增减名单》中【参保名单】sheet(表头在第3行),
|
||||
筛选【区域=重庆】且【参保类型=指定类型】的记录
|
||||
2. 按【参保单位】分组,复制《增员模版.xls》(保留下拉字典 Sheet2),
|
||||
写入 B1(社保号)/D1(参保单位全称) 及 B4 起的数据行,逐店另存为
|
||||
《XX店增员导入名单.xls》至 BASE_DIR/新参保-增员 或 BASE_DIR/转移参保-增员
|
||||
(按参保类型分文件夹存放)
|
||||
3. 日期规则:1号 → 制作「转移参保」;11号 → 制作「新参保」
|
||||
填写标准:首次参加工作日期=本月1号、个人身份=24.工人、
|
||||
工伤参保时间=当日、其他参保时间=本月1号
|
||||
@Version: 1.2.0
|
||||
- v1.2.0:输出按参保类型分文件夹(新参保-增员 / 转移参保-增员),不再混放同一目录。
|
||||
- v1.1.0:适配真实文件——源表表头第3行、类型列「参保类型」(非"申请")、
|
||||
sheet 名按月匹配(202609参保名单)、模板为 .xls(xlrd/xlutils 复制保留下拉);
|
||||
月基本工资额取源表「工资申报」列(按用户要求,申报基数大量为空);
|
||||
影刀单文件自包含(内联全部配置)。
|
||||
- v1.0.0:按 aa.md 拆 config.py + generate_add.py(已废弃,合并进本文件)
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl xlrd xlwt xlutils
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
|
||||
|
||||
运行:python generate_add.py
|
||||
(如需强制生成指定类型:python 中调用 generate_add.process_add_members('新参保'))
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import math
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行 ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
import xlrd
|
||||
import xlwt
|
||||
from xlutils.copy import copy as xl_copy
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pandas openpyxl xlrd xlwt xlutils\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
|
||||
SOURCE_GLOB = "*社保*.xlsx"
|
||||
# 增员导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
|
||||
TEMPLATE_FILE = "增员模版.xls"
|
||||
# 输出子目录(按参保类型分文件夹:新参保 / 转移参保 各存一份,避免混放)
|
||||
OUTPUT_DIR_NAME = {
|
||||
'新参保': '新参保-增员',
|
||||
'转移参保': '转移参保-增员',
|
||||
}
|
||||
# 目标区域
|
||||
TARGET_REGION = "重庆"
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
# 参保名单 sheet 名按月变化(如 202609参保名单),按关键字匹配
|
||||
SHEET_KEY = "参保名单"
|
||||
# 源表表头在第3行(H3-AY3)
|
||||
SOURCE_HEADER_ROW = 3
|
||||
# 源表筛选列:区域(筛选重庆)、参保类型(新参保/转移参保)、办理状态(只办空白的)
|
||||
REGION_COL = "区域"
|
||||
TYPE_COL = "参保类型"
|
||||
STATUS_COL = "办理状态"
|
||||
|
||||
# ==================== 3. 源表列名 ↔ 模板列名映射 ====================
|
||||
# 键为模板列含义,值为源表列名
|
||||
COLUMN_MAP = {
|
||||
'姓名': '姓名',
|
||||
'证件号码': '身份证号码',
|
||||
'民族': '民族',
|
||||
'月基本工资额': '工资', # 用户指定:月基本工资额取「工资申报」列(申报基数大量为空)
|
||||
'户口性质': '户口性质',
|
||||
'文化程度': '文化程度',
|
||||
'联系电话': '电话号码',
|
||||
'单位名称': '参保单位', # 用于分组
|
||||
'社保号': '社保号', # 用于 B1 单元格
|
||||
'参保单位全称': '参保单位全称', # 用于 D1 单元格
|
||||
'备注': '备注',
|
||||
}
|
||||
|
||||
# ==================== 4. 学历映射 ====================
|
||||
EDU_MAP = {
|
||||
'硕士研究生': '14.硕士研究生',
|
||||
'本科': '21.大学本科',
|
||||
'大专': '31.大学专科',
|
||||
'高中': '61.普通中学',
|
||||
'职高/中专/中技': '44.职业高中',
|
||||
'初中': '71.初级中学',
|
||||
'小学': '81.小学',
|
||||
}
|
||||
def translate_education(val):
|
||||
if val is None:
|
||||
return '90.其他'
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return '90.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
# ==================== 5. 民族映射 ====================
|
||||
NATION_MAP = {
|
||||
'汉族': '01.汉族', '蒙古族': '02.蒙古族', '回族': '03.回族', '藏族': '04.藏族',
|
||||
'维吾尔族': '05.维吾尔族', '苗族': '06.苗族', '彝族': '07.彝族', '壮族': '08.壮族',
|
||||
'布依族': '09.布依族', '朝鲜族': '10.朝鲜族', '满族': '11.满族', '侗族': '12.侗族',
|
||||
'瑶族': '13.瑶族', '白族': '14.白族', '土家族': '15.土家族', '哈尼族': '16.哈尼族',
|
||||
'哈萨克族': '17.哈萨克族', '傣族': '18.傣族', '黎族': '19.黎族', '傈僳族': '20.傈僳族',
|
||||
'佤族': '21.佤族', '畲族': '22.畲族', '高山族': '23.高山族', '拉祜族': '24.拉祜族',
|
||||
'水族': '25.水族', '东乡族': '26.东乡族', '纳西族': '27.纳西族', '景颇族': '28.景颇族',
|
||||
'柯尔克孜族': '29.柯尔克孜族', '土族': '30.土族', '达斡尔族': '31.达斡尔族',
|
||||
'仫佬族': '32.仫佬族', '羌族': '33.羌族', '布朗族': '34.布朗族', '撒拉族': '35.撒拉族',
|
||||
'毛南族': '36.毛南族', '仡佬族': '37.仡佬族', '锡伯族': '38.锡伯族', '阿昌族': '39.阿昌族',
|
||||
'普米族': '40.普米族', '塔吉克族': '41.塔吉克族', '怒族': '42.怒族',
|
||||
'乌孜别克族': '43.乌孜别克族', '俄罗斯族': '44.俄罗斯族', '鄂温克族': '45.鄂温克族',
|
||||
'德昂族': '46.德昂族', '保安族': '47.保安族', '裕固族': '48.裕固族', '京族': '49.京族',
|
||||
'塔塔尔族': '50.塔塔尔族', '独龙族': '51.独龙族', '鄂伦春族': '52.鄂伦春族',
|
||||
'赫哲族': '53.赫哲族', '门巴族': '54.门巴族', '珞巴族': '55.珞巴族', '基诺族': '56.基诺族',
|
||||
'少数民族': '57.少数民族', '其他': '99.其他',
|
||||
}
|
||||
def translate_nation(val):
|
||||
if val is None:
|
||||
return '99.其他'
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return '99.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
# ==================== 6. 户籍类型映射 ====================
|
||||
RESIDENCE_MAP = {
|
||||
'本地城镇': '11.本市城镇',
|
||||
'本地农村': '21.本市农村',
|
||||
'外地城镇': '12.外市城镇',
|
||||
'外地农村': '22.外市农村',
|
||||
}
|
||||
def translate_residence(val):
|
||||
if val is None:
|
||||
return ''
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
# ==================== 7. 固定默认值 ====================
|
||||
DEFAULT_VALUES = {
|
||||
'个人身份': '24.工人',
|
||||
'证件类型': '01.居民身份证(户口簿)',
|
||||
'国籍': 'CHN.中国',
|
||||
'专职技能': '499.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '', # 留空
|
||||
'备注': '', # 留空
|
||||
}
|
||||
|
||||
# ==================== 8. 增员模版配置(表头 B2:U2,数据从第4行起) ====================
|
||||
TPL_DATA_START_ROW = 4 # 数据从第4行开始
|
||||
# 模板表头(B2:U2,共20列,顺序固定)
|
||||
TPL_COLS = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
# 需按日期写入的模板列(工伤保险=当日,其余=本月1日)
|
||||
DATE_COLS = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
|
||||
|
||||
# ==================== 9. 通用辅助 ====================
|
||||
def _to_text(value):
|
||||
"""转可写文本:证件号/电话等长数字统一为字符串,避免丢精度/科学计数。"""
|
||||
if value is None:
|
||||
return ''
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」,
|
||||
避免「某某店」拼成「某某店店…」,也避免「某某店店」被全剥成「某某」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _get_dates():
|
||||
"""返回(当日, 当月1日):工伤保险参保时间用当日,其余用当月1日。"""
|
||||
today = datetime.now()
|
||||
first_day = today.replace(day=1)
|
||||
return today, first_day
|
||||
|
||||
|
||||
def find_source_file():
|
||||
"""定位源表(*社保*.xlsx,排除 Excel 临时文件 ~$,取最新)。"""
|
||||
candidates = [
|
||||
p for p in glob(os.path.join(BASE_DIR, SOURCE_GLOB))
|
||||
if not os.path.basename(p).startswith("~$")
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到源表(匹配 {SOURCE_GLOB}),请先准备《社保变更及增减名单》。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_template_file():
|
||||
"""定位《增员模版.xls》(优先精确名,其次按 *增员模版*.xls 匹配)。"""
|
||||
exact = os.path.join(BASE_DIR, TEMPLATE_FILE)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(BASE_DIR, "*增员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到《{TEMPLATE_FILE}》,请先准备增员导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_source_sheet(source_file):
|
||||
"""按关键字匹配源表【参保名单】sheet(sheet 名按月变化,如 202609参保名单)。"""
|
||||
xl = pd.ExcelFile(source_file)
|
||||
for name in xl.sheet_names:
|
||||
if SHEET_KEY in name:
|
||||
return name
|
||||
raise ValueError(
|
||||
f"源表 {os.path.basename(source_file)} 中未找到包含「{SHEET_KEY}」的 sheet,"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
|
||||
|
||||
def get_output_dir(operation_type):
|
||||
"""按参保类型取输出目录(BASE_DIR/新参保-增员 或 BASE_DIR/转移参保-增员)。
|
||||
|
||||
新参保、转移参保分别存放到不同文件夹,避免混放;目录不存在则自动创建。
|
||||
"""
|
||||
sub = OUTPUT_DIR_NAME.get(operation_type)
|
||||
if not sub:
|
||||
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(OUTPUT_DIR_NAME)})")
|
||||
out_dir = os.path.join(BASE_DIR, sub)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
# ==================== 10. 模板写入(xlrd 读取 + xlutils 复制,保留下拉字典) ====================
|
||||
def _write_template(template_file, output_path, unit_no, unit_name, records):
|
||||
"""复制《增员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
|
||||
|
||||
- 使用 xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,
|
||||
保留 Sheet2 下拉字典与数据有效性;
|
||||
- B1=社保号,D1=参保单位全称;数据从模板第4行起,按 TPL_COLS 顺序写入 B~U 列;
|
||||
- 日期列以 yyyy/m/d 文本写入(如 2026/9/1;工伤=当日,其余在 rec 中已填本月1日);
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 社保号
|
||||
ws.write(0, 3, unit_name) # D1 参保单位全称
|
||||
for i, rec in enumerate(records):
|
||||
r = TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
|
||||
for c, col in enumerate(TPL_COLS):
|
||||
val = rec.get(col)
|
||||
if col in DATE_COLS and val is not None:
|
||||
# yyyy/m/d 文本格式(不补零),如 2026/9/1
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}") # 列 c+1:B=1 ... U=20
|
||||
else:
|
||||
ws.write(r, c + 1, _clean_value(val))
|
||||
# 清空模板原数据区(第4行起)未被覆盖的多余示例行
|
||||
for r in range(TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(TPL_COLS) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
# ==================== 11. 主流程 ====================
|
||||
def process_add_members(operation_type):
|
||||
"""
|
||||
生成增员导入名单
|
||||
operation_type: '新参保' 或 '转移参保'
|
||||
"""
|
||||
# 1. 读取源表【参保名单】sheet(表头在第3行)
|
||||
source_file = find_source_file()
|
||||
sheet_name = find_source_sheet(source_file)
|
||||
print(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file,
|
||||
sheet_name=sheet_name,
|
||||
header=SOURCE_HEADER_ROW - 1,
|
||||
# 身份证/电话按文本读:18 位身份证若被推断为数字会丢精度(与停保脚本一致);
|
||||
# 工资申报等数值列保持默认数值读法,写模板时才是数字而非 "5200.0" 文本
|
||||
dtype={'身份证号码': str, '电话号码': str}
|
||||
)
|
||||
|
||||
# 2. 筛选:区域=重庆,参保类型=指定类型,办理状态=空/NULL
|
||||
# (待审核=已提交社保局、参保成功/失败=已办理,均不再生成导入名单)
|
||||
status_text = df_source[STATUS_COL].astype(str).str.strip().str.lower()
|
||||
mask = (
|
||||
(df_source[REGION_COL] == TARGET_REGION) &
|
||||
(df_source[TYPE_COL] == operation_type) &
|
||||
(df_source[STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
|
||||
)
|
||||
df_filtered = df_source[mask].copy()
|
||||
if df_filtered.empty:
|
||||
print(f"没有找到【{operation_type}】的数据({TARGET_REGION}区域,办理状态为空)")
|
||||
return
|
||||
|
||||
# 3. 获取日期
|
||||
today, first_day = _get_dates()
|
||||
print(f"今日日期:{today.strftime('%Y-%m-%d')}")
|
||||
print(f"本月1日:{first_day.strftime('%Y-%m-%d')}(首次参加/养老/失业/医疗/生育参保时间)")
|
||||
print(f"工伤参保时间:{today.strftime('%Y-%m-%d')}(当日)")
|
||||
|
||||
# 4. 按参保单位分组生成
|
||||
template_file = find_template_file()
|
||||
output_dir = get_output_dir(operation_type)
|
||||
print(f"输出目录:{output_dir}")
|
||||
store_col = COLUMN_MAP['单位名称']
|
||||
for store_name, group in df_filtered.groupby(store_col):
|
||||
print(f" 正在处理:{store_name},共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[COLUMN_MAP['社保号']]
|
||||
unit_full_name = first_row[COLUMN_MAP['参保单位全称']]
|
||||
|
||||
# 5. 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'证件号码': _to_text(row[COLUMN_MAP['证件号码']]),
|
||||
'姓名': row[COLUMN_MAP['姓名']],
|
||||
'民族': translate_nation(row[COLUMN_MAP['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': _clean_value(row[COLUMN_MAP['月基本工资额']]),
|
||||
'工种': DEFAULT_VALUES['工种'],
|
||||
'个人身份': DEFAULT_VALUES['个人身份'],
|
||||
'户口性质': translate_residence(row[COLUMN_MAP['户口性质']]),
|
||||
'联系电话': _to_text(row[COLUMN_MAP['联系电话']]),
|
||||
'文化程度': translate_education(row[COLUMN_MAP['文化程度']]),
|
||||
'养老保险参保时间': first_day,
|
||||
'失业保险参保时间': first_day,
|
||||
'医疗保险参保时间': first_day,
|
||||
'工伤保险参保时间': today,
|
||||
'生育保险参保时间': first_day,
|
||||
'证件类型': DEFAULT_VALUES['证件类型'],
|
||||
'国籍': DEFAULT_VALUES['国籍'],
|
||||
'备注': DEFAULT_VALUES['备注'],
|
||||
'专职技能': DEFAULT_VALUES['专职技能'],
|
||||
'技能等级': DEFAULT_VALUES['技能等级'],
|
||||
}
|
||||
records.append(rec)
|
||||
|
||||
# 6. 写入模板并另存
|
||||
output_path = os.path.join(output_dir, f"{_safe_name(store_name)}增员导入名单.xls")
|
||||
_write_template(template_file, output_path, unit_no, unit_full_name, records)
|
||||
print(f" 已生成:{output_path}")
|
||||
|
||||
print(f"所有【{operation_type}】导入名单生成完成!")
|
||||
|
||||
|
||||
# ==================== 12. 主入口(日期规则) ====================
|
||||
if __name__ == "__main__":
|
||||
process_add_members('转移参保')
|
||||
process_add_members('新参保')
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: generate_stop.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保停保导入名单制作 —— 单文件自包含版(影刀直接运行)
|
||||
与 generate_add.py(增员)同套实现方式:xlrd 读取 + xlutils 复制模板,保留下拉字典与样式。
|
||||
1. 读取《XX月社保变更及增减名单》中【停保名单】sheet(表头在第3行),
|
||||
筛选【区域=重庆】的记录(身份证/社保编号按文本读取,防丢精度)
|
||||
2. 按【参保单位】分组,复制《减员模版.xls》(保留下拉字典 二级代码),
|
||||
写入 B1(单位社保号)/D1(单位全称) 及 B4 起的数据行,逐单位另存为
|
||||
《XX减员导入名单.xls》至 BASE_DIR/停保-减员(与增员按单位命名一致)
|
||||
3. 填写标准:减少时间=当天、减少原因=在职人员主动解除劳动合同、
|
||||
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职
|
||||
(固定 28 号执行,可调用 process_stop_members() 强制)
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl xlrd xlwt xlutils
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
|
||||
|
||||
运行:python generate_stop.py
|
||||
(如需强制生成:python 中调用 generate_stop.process_stop_members())
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import math
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行 ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
import xlrd
|
||||
import xlwt
|
||||
from xlutils.copy import copy as xl_copy
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pandas openpyxl xlrd xlwt xlutils\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
|
||||
SOURCE_GLOB = "*社保*.xlsx"
|
||||
# 停保导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
|
||||
TEMPLATE_FILE = "减员模版.xls"
|
||||
# 输出子目录(BASE_DIR/停保-减员),存放各单位停保导入名单(与增员的「新参保-增员/转移参保-增员」并列)
|
||||
OUTPUT_DIR_NAME = "停保-减员"
|
||||
# 目标区域
|
||||
TARGET_REGION = "重庆"
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
# 停保名单 sheet 名按月变化(如 202609停保名单),按关键字匹配
|
||||
SHEET_KEY = "停保名单"
|
||||
# 源表表头在第3行
|
||||
SOURCE_HEADER_ROW = 3
|
||||
# 源表筛选列:区域(筛选重庆)
|
||||
REGION_COL = "区域"
|
||||
# 用于分组的列(参保单位,按单位存储/命名,与增员一致)
|
||||
GROUP_COL = "参保单位"
|
||||
|
||||
# ==================== 3. 源表列名 ↔ 模板列名映射 ====================
|
||||
# 键为模板列含义,值为源表列名
|
||||
COLUMN_MAP = {
|
||||
'个人编号': '社保编号', # 模板列 → 源表「社保编号」
|
||||
'证件号码': '身份证号码', # 模板列 → 源表「身份证号码」
|
||||
'姓名': '停保人姓名', # 模板列 → 源表「停保人姓名」
|
||||
'单位社保号': '单位社保号', # 用于 B1 单元格
|
||||
'单位名称': '参保单位', # 用于分组、文件名 和 D1 单元格
|
||||
}
|
||||
|
||||
# ==================== 4. 固定默认值 ====================
|
||||
DEFAULT_VALUES = {
|
||||
# 减少原因(固定)
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
# 五个险种减少标志(固定为"1 减少")
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
# 失业原因(固定,取值须与模板下拉「二级代码」一致:数字3后两个空格)
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
|
||||
# ==================== 5. 减员模版配置(表头 B2:L2,数据从第4行起) ====================
|
||||
TPL_DATA_START_ROW = 4 # 数据从第4行开始
|
||||
# 模板表头(B2:L2,共11列,顺序固定)
|
||||
TPL_COLS = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
# 需按日期写入的模板列(减少时间=当天)
|
||||
DATE_COLS = {'减少时间'}
|
||||
|
||||
|
||||
# ==================== 6. 通用辅助 ====================
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」,
|
||||
避免「某某店」拼成「某某店店…」,也避免「某某店店」被全剥成「某某」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _get_today():
|
||||
"""返回当日日期(停保减少时间 = 制作当天)。"""
|
||||
return datetime.now()
|
||||
|
||||
|
||||
def find_source_file():
|
||||
"""定位源表(*社保*.xlsx,排除 Excel 临时文件 ~$,取最新)。"""
|
||||
candidates = [
|
||||
p for p in glob(os.path.join(BASE_DIR, SOURCE_GLOB))
|
||||
if not os.path.basename(p).startswith("~$")
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到源表(匹配 {SOURCE_GLOB}),请先准备《社保变更及增减名单》。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_template_file():
|
||||
"""定位《减员模版.xls》(优先精确名,其次按 *减员模版*.xls 匹配)。"""
|
||||
exact = os.path.join(BASE_DIR, TEMPLATE_FILE)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(BASE_DIR, "*减员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到《{TEMPLATE_FILE}》,请先准备停保导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_source_sheet(source_file):
|
||||
"""按关键字匹配源表【停保名单】sheet(sheet 名按月变化,如 202609停保名单)。"""
|
||||
xl = pd.ExcelFile(source_file)
|
||||
for name in xl.sheet_names:
|
||||
if SHEET_KEY in name:
|
||||
return name
|
||||
raise ValueError(
|
||||
f"源表 {os.path.basename(source_file)} 中未找到包含「{SHEET_KEY}」的 sheet,"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
|
||||
|
||||
def get_output_dir():
|
||||
"""输出目录(BASE_DIR/减员),不存在则自动创建。"""
|
||||
out_dir = os.path.join(BASE_DIR, OUTPUT_DIR_NAME)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
# ==================== 7. 模板写入(xlrd 读取 + xlutils 复制,保留下拉字典) ====================
|
||||
def _write_template(template_file, output_path, unit_no, unit_name, records):
|
||||
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
|
||||
|
||||
- 使用 xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,
|
||||
保留「二级代码」下拉字典与数据有效性;
|
||||
- B1=单位社保号,D1=单位全称;数据从模板第4行起,按 TPL_COLS 顺序写入 B~L 列;
|
||||
- 减少时间以 yyyy/m/d 文本写入(如 2026/9/10,当天);
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 单位社保号
|
||||
ws.write(0, 3, unit_name) # D1 单位全称
|
||||
for i, rec in enumerate(records):
|
||||
r = TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
|
||||
for c, col in enumerate(TPL_COLS):
|
||||
val = rec.get(col)
|
||||
if col in DATE_COLS and val is not None:
|
||||
# yyyy/m/d 文本格式(不补零),如 2026/9/10
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}") # 列 c+1:B=1 ... L=11
|
||||
else:
|
||||
ws.write(r, c + 1, _clean_value(val))
|
||||
# 清空模板原数据区(第4行起)未被覆盖的多余示例行
|
||||
for r in range(TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(TPL_COLS) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
# ==================== 8. 主流程 ====================
|
||||
def process_stop_members():
|
||||
"""
|
||||
生成停保导入名单
|
||||
规则:区域=重庆;按单位社保号分组;减少时间=当天;减少原因=在职人员主动解除劳动合同;
|
||||
五个险种减少标志=1 减少;失业原因=3 劳动者自愿辞职
|
||||
"""
|
||||
# 1. 读取源表【停保名单】sheet(表头在第3行,全列按文本读,保住身份证/社保编号完整值)
|
||||
source_file = find_source_file()
|
||||
sheet_name = find_source_sheet(source_file)
|
||||
print(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file,
|
||||
sheet_name=sheet_name,
|
||||
header=SOURCE_HEADER_ROW - 1,
|
||||
dtype=str
|
||||
)
|
||||
|
||||
# 2. 筛选:区域=重庆
|
||||
df_filtered = df_source[df_source[REGION_COL] == TARGET_REGION].copy()
|
||||
if df_filtered.empty:
|
||||
print(f"没有找到【{TARGET_REGION}】区域的停保数据")
|
||||
return
|
||||
print(f"共找到 {len(df_filtered)} 条 {TARGET_REGION} 区域停保记录")
|
||||
|
||||
# 3. 获取当天日期(减少时间 = 当天)
|
||||
today = _get_today()
|
||||
print(f"制作日期:{today.strftime('%Y-%m-%d')}")
|
||||
print(f"减少时间:{today.strftime('%Y-%m-%d')}(当日)")
|
||||
|
||||
# 4. 按单位社保号分组生成
|
||||
template_file = find_template_file()
|
||||
output_dir = get_output_dir()
|
||||
print(f"输出目录:{output_dir}")
|
||||
for group_key, group in df_filtered.groupby(GROUP_COL):
|
||||
print(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[COLUMN_MAP['单位社保号']] # 单位社保号 → B1
|
||||
unit_name = first_row[COLUMN_MAP['单位名称']] # 参保单位 → D1
|
||||
|
||||
# 5. 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'个人编号': _clean_value(row[COLUMN_MAP['个人编号']]),
|
||||
'证件号码': _clean_value(row[COLUMN_MAP['证件号码']]),
|
||||
'姓名': _clean_value(row[COLUMN_MAP['姓名']]),
|
||||
'减少时间': today,
|
||||
'减少原因': DEFAULT_VALUES['减少原因'],
|
||||
'养老保险减少标志': DEFAULT_VALUES['养老保险减少标志'],
|
||||
'失业保险减少标志': DEFAULT_VALUES['失业保险减少标志'],
|
||||
'医疗保险减少标志': DEFAULT_VALUES['医疗保险减少标志'],
|
||||
'工伤保险减少标志': DEFAULT_VALUES['工伤保险减少标志'],
|
||||
'生育保险减少标志': DEFAULT_VALUES['生育保险减少标志'],
|
||||
'失业原因': DEFAULT_VALUES['失业原因'],
|
||||
}
|
||||
records.append(rec)
|
||||
|
||||
# 6. 写入模板并另存
|
||||
output_path = os.path.join(output_dir, f"{_safe_name(group_key)}减员导入名单.xls")
|
||||
_write_template(template_file, output_path, unit_no, unit_name, records)
|
||||
print(f" 已生成:{output_path}")
|
||||
|
||||
print(f"所有停保导入名单生成完成!共 {len(df_filtered[GROUP_COL].unique())} 个单位")
|
||||
|
||||
|
||||
# ==================== 9. 主入口(固定28号执行) ====================
|
||||
if __name__ == "__main__":
|
||||
process_stop_members()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""临时验证:技师岗/黄泥磅 是否在考勤方案列表中存在。验证后删除。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import (
|
||||
HR_BASE_URL, build_hr_session, hr_request_json, fetch_cur_user_info, _clean,
|
||||
)
|
||||
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
BASE = {
|
||||
"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": "0", "sortType": "desc",
|
||||
"sortName": "t.operate_time", "pageNo": "1", "pageSize": "50",
|
||||
}
|
||||
|
||||
|
||||
def probe(label, **overrides):
|
||||
params = dict(BASE)
|
||||
params.update(overrides)
|
||||
d = hr_request_json(session, "POST", TEAM_LIST_URL, params, "考勤方案列表")
|
||||
data = d.get("data") or {}
|
||||
lst = data.get("list") or []
|
||||
print(f"--- {label}: total={data.get('total')}")
|
||||
for x in lst:
|
||||
print(" ", _clean(x.get("teamName")))
|
||||
|
||||
|
||||
session = build_hr_session()
|
||||
fetch_cur_user_info(session)
|
||||
|
||||
probe("team_name=技师岗", team_name="技师岗")
|
||||
probe("team_name=黄泥磅", team_name="黄泥磅")
|
||||
probe("team_name=技师", team_name="技师")
|
||||
@@ -0,0 +1,608 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_rest_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查2「出勤及排休天数验证」(影刀单文件,自包含)。
|
||||
根据排班方案关联的应勤天方案:
|
||||
实际出勤天不能超过应勤天;
|
||||
正休不能超过标准“当月天数-应勤天”。
|
||||
命中任一即输出异常名单。
|
||||
|
||||
数据来源:
|
||||
1) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表。
|
||||
用到的封存字段:
|
||||
kq_stat_cal_ext19 实际出勤天日
|
||||
kq_stat_cal_ext9 休息天(正休)
|
||||
2) 排班数据:rf_p_kq_count_SelectBanci(不传工号 = 全集团批量返回),每条记录
|
||||
带逐日 {日期}_team_name(班组/方案名,如"集团本部职能(单双休+法定)");
|
||||
一个员工当月取「出现次数最多的 team_name」(换方案口径)。
|
||||
3) 应勤天(aa.md 三连接口,全量缓存避免逐人查询):
|
||||
a) 查询所有考勤方案 rf_p_kq_team_ajax_list → 每个 team 的 teamId/teamName;
|
||||
b) 按 teamId 查方案扩展表 rf_s_kq_team_extend_table_select → ext_minyq_plan_id;
|
||||
c) 按 teamId 查应勤天方案 rf_s_kq_team_minyq_plan_up_query_all(组织级全量方案,
|
||||
任意 teamId 返回一致,只查一次缓存),按 minyq_plan_id == ext_minyq_plan_id
|
||||
过滤,取 month_XX 当月应勤天。
|
||||
员工 排班 team_name ↔ 考勤方案 teamName 精确匹配。
|
||||
「排班方案 → 当月应勤天」映射结果做 1 天文件缓存:当天首次运行拉取并落盘,
|
||||
同一天后续运行直接读缓存;次日自动失效重新拉取,避免方案改动后误用旧数据。
|
||||
4) 技师(排班方案名含「技师岗」):固定按 8 天休息,不查询应勤天方案。
|
||||
|
||||
输出:
|
||||
出勤排休验证异常_{月份}_{时间戳}.xlsx 异常名单(含 应勤天/实际出勤天/正休/标准 便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json),
|
||||
本模块运行时直连 排班接口 + 应勤天方案接口 拉取实时数据。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_arc_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_arc_cache_dir 应勤天方案缓存目录(默认 %LOCALAPPDATA%\\37duAutomation\\cache)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from collections import Counter
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理 + HR 会话,本模块复用)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import ( # noqa: E402
|
||||
SHARED_HR_COOKIE_FILE, HR_BASE_URL, GET_CUR_USER_INFO_URL,
|
||||
PAGE_MAX_SIZE, HRSessionExpiredError, _APP_DATA_DIR,
|
||||
build_hr_session, hr_request_json, fetch_cur_user_info,
|
||||
_relogin_get_user_id, _clean, enrich_dept_fields, load_seal_rows,
|
||||
)
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_arc_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 应勤天方案缓存:排班方案 → 当月应勤天 映射结果缓存 1 天(当天复用,次日失效重拉)。
|
||||
# 与共享登录态同放 AppData 根(%LOCALAPPDATA%\37duAutomation\cache),不污染报告输出目录。
|
||||
TEAM_PLAN_CACHE_DIR = os.getenv("monthly_arc_cache_dir") or os.path.join(_APP_DATA_DIR, "cache")
|
||||
|
||||
# 排班接口(aa.json 样例:一条记录 = 一个员工在查询范围内的全部排班,逐日带 {日期}_team_name)
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
SHIFT_SQL_ID = "kq_count_SelectBanci"
|
||||
|
||||
# 考勤方案列表接口(aa.md:查询所有考勤方案,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
|
||||
|
||||
# 方案查询接口(aa.md:按 teamId 查扩展表,取 ext_minyq_plan_id)
|
||||
TEAM_EXTEND_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_team_extend_table_select/redApiExec.mc"
|
||||
|
||||
# 应勤天方案接口(aa.md:按 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 = "排班方案未匹配应勤天"
|
||||
|
||||
# 封存字段(aa.md 列定义)
|
||||
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 _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ==================== 考勤方案 → 应勤天接口(aa.md 三连接口) ====================
|
||||
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]:
|
||||
"""分页抓取全部考勤方案(aa.md: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:
|
||||
logger.warning("考勤方案登录态过期,自动补登录后续抓")
|
||||
session, _ = _relogin_get_user_id()
|
||||
data = fetch_team_page(session, page_no)
|
||||
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})。
|
||||
|
||||
流程(aa.md):
|
||||
1) 应勤天方案按任意 teamId 查一次全量缓存(组织级方案一致),按 minyq_plan_id 索引;
|
||||
2) 逐个 teamId 查方案扩展表拿 ext_minyq_plan_id,再取对应方案当月应勤天。
|
||||
"""
|
||||
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:
|
||||
logger.warning("方案查询登录态过期,自动补登录后续抓")
|
||||
session, _ = _relogin_get_user_id()
|
||||
ext_plan_id = fetch_team_extend(session, team_id)
|
||||
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:
|
||||
logger.warning("排班登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_shift_page(session, user_id, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
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) -> List[dict]:
|
||||
"""执行检查2「出勤及排休天数验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
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)
|
||||
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.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
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. 拉取全部考勤方案 → 应勤天(aa.md 三连接口,全量缓存避免逐人查询;
|
||||
# 映射结果带 1 天文件缓存,当天首次运行拉取,后续运行直接读缓存)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId")) # 登录态校验 + 取 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}天(当月{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)
|
||||
|
||||
# 5. 导出异常名单
|
||||
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")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_arc_month") or sys_argv_if(2)
|
||||
try:
|
||||
rows = run_attendance_rest_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查2 出勤及排休天数验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常条数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("检查2执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,366 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: full_attendance_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查5「全勤验证」(影刀单文件,自包含)。
|
||||
月中晋升职能或管理岗,或存在迟到早退异常仍被标记全勤的,输出异常名单。
|
||||
|
||||
判定口径(对应需求文档 aa.md 检查⑤):
|
||||
规则A「月中途晋升,不享受全勤」:
|
||||
调动台账月中途(检查月内)从 门店服务序列/门店技师序列 调动到
|
||||
职能系专业序列/职能系管理序列/经营系管理序列 的,且封存「是否全勤」=1 → 异常;
|
||||
规则B「存在考勤异常,不享受全勤」:
|
||||
封存存在迟到或早退异常次数(迟到次数+早退次数>0)、且「是否全勤」=1 → 异常。
|
||||
|
||||
数据来源:
|
||||
1) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
检查5用到的封存字段(aa.md 列定义):
|
||||
kq_stat_cal_ext43 是否全勤
|
||||
迟到:kq_stat_cal_ext60/61/62(30分钟内/30~60/60~120)
|
||||
早退:kq_stat_cal_ext51/52/53(30分钟内/30~60/60~120)
|
||||
2) 调动台账:由「37du调动台账导出」共享指令(纯接口版 transfer_roster_export_api.py,
|
||||
模板=排班异常识别导出)导出到固定路径,本模块只读取。表头在第 2 行(header=1)。
|
||||
检查5用到的台账列:工号 / 调动时间 / 原职位序列 / 现职位序列。
|
||||
|
||||
输出:
|
||||
全勤验证异常_{月份}_{时间戳}.xlsx 异常名单(含异常明细便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du调动台账导出」(模板=排班异常识别导出,
|
||||
调动时间范围 = 检查月月初 ~ 检查月月末)导出调动台账到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_fa_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_fa_transfer_path 调动台账文件路径
|
||||
(默认 D:\\资料\\人资\\排班异常识别\\调动台账.xlsx)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import enrich_dept_fields, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_fa_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
# 调动台账固定路径:由「37du调动台账导出」共享指令导出(模板=排班异常识别导出)
|
||||
DEFAULT_TRANSFER_PATH = (os.getenv("monthly_fa_transfer_path")
|
||||
or r"D:\资料\人资\考勤月报封存检查\调动台账.xlsx")
|
||||
|
||||
# 异常类型(对应需求文档检查5 规则A/B)
|
||||
ABNORMAL_TYPE_PROMOTION = "月中途晋升,不享受全勤"
|
||||
ABNORMAL_TYPE_LATE_EARLY = "存在考勤异常,不享受全勤"
|
||||
|
||||
# 调动识别:原职位序列命中「门店系」(晋升起点)
|
||||
PRE_SEQ_KEYWORDS = ("门店服务序列", "门店技师序列")
|
||||
# 现职位序列命中「职能/经营系管理、专业」(晋升终点)
|
||||
NOW_SEQ_KEYWORDS = ("职能系专业序列", "职能系管理序列", "经营系管理序列")
|
||||
|
||||
# 封存记录工号字段 & 是否全勤 / 迟到 / 早退字段(aa.md 列定义)
|
||||
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")
|
||||
|
||||
# 调动台账列(与「37du调动台账导出」指令导出的列名一致)
|
||||
TRANSFER_CODE_COL = "工号"
|
||||
TRANSFER_DATE_COL = "调动时间"
|
||||
TRANSFER_PRE_SEQ_COL = "原职位序列"
|
||||
TRANSFER_NOW_SEQ_COL = "现职位序列"
|
||||
|
||||
# 输出列(对应需求文档检查5输出字段,附 异常明细 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"异常明细",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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 _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 _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 _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]:
|
||||
"""读取调动台账(37du调动台账导出,表头在第 2 行 header=1),返回记录行列表。"""
|
||||
transfer_path = transfer_path or DEFAULT_TRANSFER_PATH
|
||||
if not os.path.exists(transfer_path):
|
||||
raise RuntimeError(
|
||||
f"未找到调动台账文件:{transfer_path}\n"
|
||||
"请先在影刀流程中拖入「37du调动台账导出」指令导出调动台账"
|
||||
"(模板=排班异常识别导出,调动时间范围=检查月月初~月末),再运行本流程;"
|
||||
"或通过 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(transfer_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查5「全勤验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账文件路径,默认 DEFAULT_TRANSFER_PATH。
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
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}"
|
||||
logger.info("===== 检查5「全勤验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
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 # 无封存记录(未封存场景由检查4负责),跳过
|
||||
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("检查5 规则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("检查5 规则B 命中异常 %d 人(有迟到早退且全勤=1)", late_early_cnt)
|
||||
|
||||
# 5. 导出异常名单
|
||||
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")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:
|
||||
transfer_path(调动台账文件路径)、month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
transfer_path = args.get("transfer_path") or (
|
||||
os.getenv("monthly_fa_transfer_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_fa_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_full_attendance_check(transfer_path, month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查5 全勤验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("检查5执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
import sys
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,387 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: latest_seal_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查3「封存值是否为最新值」(影刀单文件,自包含)。
|
||||
考勤月报封存页面「对比」检索对比差异值是否全部为空,若有异常值则输出异常名单。
|
||||
|
||||
判定口径(对应需求文档 aa.md 检查③):
|
||||
对比「考勤封存值」与「实时统计值」两套数据的考勤指标字段,逐字段比较数值;
|
||||
任一字段存在差异(非空差异)→ 异常,异常类型「考勤封存非最新值,请重新封存」。
|
||||
|
||||
数据来源:
|
||||
1) 封存值(对比左列):考勤月报封存记录,由 seal_data_export.py 导出并预处理
|
||||
(所属单位白名单筛选),保存为固定路径 考勤封存数据_{月份}.xlsx,
|
||||
本模块只读取该预处理封存表,不再直连接口。
|
||||
2) 实时值(对比右列):POST https://hr.37du.co/RedseaPlatform/getPageAjax/
|
||||
kq_count_leave_StatV2/CoreRequest.mc
|
||||
参数 begin/end 日期范围 + staff_ids 留空 = 全集团批量实时统计(count=8215),
|
||||
按所属单位白名单筛选后与本表逐员工比对。
|
||||
两接口返回均为 kq_stat_* 系列字段,同一员工以 staff_id(辅以工号)匹配。
|
||||
|
||||
对比字段(页面「对比」展示字段,中文标签 → 接口字段,来源 aa.md 封存页列定义):
|
||||
实际出勤天日 ext19 / _在职应勤工作日 month_yq_work_day_in / 休息天 ext9 /
|
||||
旷工天数 ext39 / 漏打卡次数 ext8 / _特别福利假天 leave_day_num23 /
|
||||
_年度福利假天 leave_day_num24 / 年假天 leave_day_num1 / _病假天 leave_day_num4 /
|
||||
_产假天 leave_day_num5 / _事假天 leave_day_num9 / _普通事假天 leave_day_num16 /
|
||||
_特殊事假天 leave_day_num17 / _小时特假小时 leave_hour_num18 /
|
||||
_普通事假(晚/高峰)天 leave_day_num19 / _普通事假(早/中)天 leave_day_num20 /
|
||||
_工作日加班转补贴小时 ps_bt_hour / 法定节假日加班转补贴天 ext69 /
|
||||
休息日加班转补贴天 ext44 / 当月未休调休天 ext63 / 迟到 ext60/61/62 /
|
||||
早退 ext51/52/53 / 连班次数 ext40 / 是否未休小时特假 ext42 / 是否全勤 ext43。
|
||||
|
||||
输出:
|
||||
封存值校验异常_{月份}_{时间戳}.xlsx 异常名单(含异常明细:差异字段清单便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_ls_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理、HR 会话/接口工具)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import (
|
||||
build_hr_session, enrich_dept_fields, fetch_cur_user_info,
|
||||
hr_request_json, load_seal_rows,
|
||||
SEAL_UNIT_WHITELIST, _clean,
|
||||
)
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_ls_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 实时统计接口(对比右侧):不传 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])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
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) -> List[dict]:
|
||||
"""执行检查3「封存值是否为最新值」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
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)
|
||||
logger.info("===== 检查3「封存值是否为最新值」月份:%s(%s ~ %s) =====", ym, begin, end)
|
||||
|
||||
# 1. 读取预处理封存表(封存值,已按所属单位白名单筛选)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
logger.info("封存值加载完成,共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 拉取当月实时统计值(StatV2 全集团批量)→ 白名单筛选 → 按员工建立索引
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
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)
|
||||
|
||||
# 4. 导出异常名单
|
||||
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")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_ls_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_latest_seal_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查3 封存值校验完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("检查3执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,232 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: monthly_report_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-21
|
||||
@UpdateTime: 2026-09-21
|
||||
@Description: 考勤月报封存检查 - 汇总执行与单工作簿输出(影刀单文件,自包含)。
|
||||
依次运行检查1~检查6,将各异常名单合并写入一个 Excel 工作簿(每个检查一个 sheet),
|
||||
并生成「汇总」sheet 概览各检查异常人数。各检查模块仍保留独立输出文件,便于单独排查。
|
||||
|
||||
运行前置:需先运行「seal_data_export.py」导出当月预处理封存表,并完成
|
||||
「37du花名册导出」「37du调动台账导出」(统一输出到 D:\\资料\\人资\\考勤月报封存检查)。
|
||||
|
||||
输出:
|
||||
考勤月报封存检查_{月份}_{时间戳}.xlsx 单工作簿(汇总 + 检查1~6 共 7 个 sheet)
|
||||
|
||||
环境变量(可选):
|
||||
monthly_report_save_dir 汇总工作簿输出目录(默认 D:\\资料\\人资\\考勤月报封存检查)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Callable, Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 同目录模块引入(各检查模块,复用其 run_* 与输出列定义) ====================
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from working_days_shift_check import ( # noqa: E402
|
||||
run_working_days_shift_check, OUTPUT_COLUMNS as COL_CHECK1,
|
||||
)
|
||||
from attendance_rest_check import ( # noqa: E402
|
||||
run_attendance_rest_check, OUTPUT_COLUMNS as COL_CHECK2,
|
||||
)
|
||||
from latest_seal_check import ( # noqa: E402
|
||||
run_latest_seal_check, OUTPUT_COLUMNS as COL_CHECK3,
|
||||
)
|
||||
from full_attendance_check import ( # noqa: E402
|
||||
run_full_attendance_check, OUTPUT_COLUMNS as COL_CHECK4,
|
||||
)
|
||||
from unsealed_check import ( # noqa: E402
|
||||
run_unsealed_check, OUTPUT_COLUMNS as COL_CHECK5,
|
||||
)
|
||||
from overtime_compensation_check import ( # noqa: E402
|
||||
run_overtime_compensation_check, OUTPUT_COLUMNS as COL_CHECK6,
|
||||
)
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_report_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 检查元信息:(编号, sheet 名, 异常类型标签, run 函数, 输出列)
|
||||
CHECK_META: List[Tuple[str, str, str, Callable, List[str]]] = [
|
||||
("检查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 sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def run_all_checks(month: str = None) -> Dict[str, object]:
|
||||
"""依次运行检查1~6,返回各检查异常名单行列表(每项含编号/sheet/类型/行列表)。"""
|
||||
ym = _normalize_month(month)
|
||||
logger.info("===== 考勤月报封存检查(汇总)月份:%s =====", ym)
|
||||
results: List[dict] = []
|
||||
total = 0
|
||||
for no, sheet_name, label, run_fn, _cols in CHECK_META:
|
||||
try:
|
||||
rows = run_fn(month=ym)
|
||||
except Exception as e:
|
||||
logger.error("%s 执行失败:%s\n%s", no, e, traceback.format_exc())
|
||||
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}
|
||||
|
||||
|
||||
def write_workbook(result: Dict[str, object]) -> str:
|
||||
"""将各检查异常名单写入单工作簿(汇总 + 每检查一个 sheet)。"""
|
||||
ym = result["ym"]
|
||||
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
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_report_month") or (sys_argv_if(2))
|
||||
try:
|
||||
result = run_all_checks(month)
|
||||
save_path = write_workbook(result)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤月报封存检查汇总完成】")
|
||||
logger.info(" 检查月份:%s | 异常总人数:%d", result["ym"], result["total"])
|
||||
logger.info(" 汇总工作簿:%s", save_path)
|
||||
logger.info(" 各检查异常人数:%s", "、".join(
|
||||
f"{it['no']}:{len(it['rows'])}" for it in result["results"]))
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": result["total"],
|
||||
"detail": {it["no"]: len(it["rows"]) for it in result["results"]},
|
||||
"path": save_path}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("汇总检查执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,301 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: overtime_compensation_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-18
|
||||
@Description: 考勤月报封存检查 - 检查6「延时加班验证」(影刀单文件,自包含)。
|
||||
经营系管理岗不享受延时加班:识别职位序列为「经营系管理序列」的员工,若考勤封存页面
|
||||
字段「_工作日加班转补贴小时」(kq_stat_ps_bt_hour)为非零值,则输出异常名单,
|
||||
异常类型 = 「经营系管理岗不应享受延时加班,请核对」。
|
||||
|
||||
数据来源:
|
||||
1) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
2) 职位序列(识别经营系管理序列):花名册「员工基础信息」模板导出(37du花名册导出,
|
||||
纯接口版 roster_export_api.py),其中含「职位序列」列(pt_staff_stru.first_type_id),
|
||||
本模块按工号 join 取职位序列。花名册路径默认与检查5一致,可独立配置。
|
||||
|
||||
判定口径(对应需求文档 XQ0011 检查6):
|
||||
- 逐条封存记录,按工号从花名册取职位序列;
|
||||
- 职位序列命中「经营系管理序列」且「_工作日加班转补贴小时」非零(>0)→ 异常;
|
||||
- 花名册查不到职位序列的员工跳过(无法判断序列,不误报)。
|
||||
|
||||
输出:
|
||||
延时加班异常_{月份}_{时间戳}.xlsx 异常名单(含延时加班补贴小时便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du花名册导出」(模板=员工基础信息)导出花名册到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_otc_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_otc_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import enrich_dept_fields, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_otc_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
# 花名册固定路径:由「37du花名册导出」共享指令导出(模板=员工基础信息,含职位序列列)
|
||||
DEFAULT_ROSTER_PATH = os.getenv("monthly_otc_roster_path") or r"D:\资料\人资\考勤月报封存检查\员工花名册.xlsx"
|
||||
|
||||
# 异常类型(对应需求文档检查6)
|
||||
ABNORMAL_TYPE = "经营系管理岗不应享受延时加班,请核对"
|
||||
|
||||
# 命中职位序列(经营系管理序列不享受延时加班)
|
||||
TARGET_SEQUENCES: Tuple[str, ...] = ("经营系管理序列",)
|
||||
|
||||
# 封存记录工号字段 & 加班转补贴小时字段(aa.md:_工作日加班转补贴小时)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_OT_HOUR_FIELD = "kq_stat_ps_bt_hour"
|
||||
|
||||
# 花名册字段(与「37du花名册导出」指令导出的列名一致,员工基础信息模板含职位序列列)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_SEQ_COL = "职位序列"
|
||||
|
||||
# 输出列(对应需求文档检查6输出字段,附 延时加班补贴小时 便于排查)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"延时加班补贴小时",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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 _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]:
|
||||
"""读取花名册,建立 工号→职位序列 映射(同一工号多行取第一个非空序列)。"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先在影刀流程中拖入「37du花名册导出」指令导出花名册"
|
||||
"(模板=员工基础信息,需包含「职位序列」列),再运行本流程;"
|
||||
"或通过 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(roster_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查6「延时加班验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径,默认 DEFAULT_ROSTER_PATH。
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
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}"
|
||||
logger.info("===== 检查6「延时加班验证」月份:%s =====", ym)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
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)
|
||||
|
||||
# 4. 导出异常名单
|
||||
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")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:
|
||||
roster_path(花名册文件路径)、month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
roster_path = args.get("roster_path") or (
|
||||
os.getenv("monthly_otc_roster_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_otc_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_overtime_compensation_check(roster_path, month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查6 延时加班验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("检查6执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
import sys
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,531 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: seal_data_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-07
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 封存数据导出与预处理模块(影刀单文件,自包含)。
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1/检查5 等各检查模块不再直连接口,
|
||||
一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
所属单位白名单(预处理口径,需调整时只改 SEAL_UNIT_WHITELIST 一处):
|
||||
财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部
|
||||
|
||||
数据来源(接口直取,对应 aa.md / aa.json):
|
||||
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
- 每员工一条封存记录,所属单位字段 BELONG_UNIT_ORG_NAME(aa.md 列:所属单位)。
|
||||
|
||||
输出:
|
||||
考勤封存数据_{月份}.xlsx 预处理后的封存表(固定路径,覆盖式保存,仅含白名单单位员工,
|
||||
中文表头,供人工复核 & 各检查模块读取复用)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from functools import lru_cache
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
_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')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_UNIT_WHITELIST: Tuple[str, ...] = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 花名册(员工基础信息导出)路径 & 列(供:①剔除名单 ②异常名单 1-5 级部门回填)
|
||||
ROSTER_DEFAULT_PATH = os.getenv("monthly_seal_roster_path") or r"D:\资料\人资\考勤月报封存检查\员工花名册.xlsx"
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_DEPT_COLS = ("一级部门", "二级部门", "三级部门", "四级部门", "五级部门")
|
||||
# 一级部门等于该值的员工不参与本检查(花名册口径,整月剔除)
|
||||
EXCLUDE_FIRST_DEPT = "职业技术培训学校"
|
||||
# 一级部门为空 = 直属单位根节点的高管(未挂具体部门树),不参与本检查
|
||||
EXCLUDE_EMPTY_FIRST_DEPT = True
|
||||
|
||||
# 中文导出列 → 接口字段(来源: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 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
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 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 _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(aa.md: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:
|
||||
logger.warning("考勤封存登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
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 _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 _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 _seal_path(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(SEAL_UNIT_FIELD)) 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 ROSTER_DEFAULT_PATH)
|
||||
return dept_map
|
||||
|
||||
|
||||
def load_excluded_codes(roster_path: str = None) -> Set[str]:
|
||||
"""一级部门 = 职业技术培训学校 的剔除工号集合。"""
|
||||
_, excluded = _load_roster_maps(roster_path or ROSTER_DEFAULT_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) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
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(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) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
path = _seal_path(ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先运行「seal_data_export.py」导出并预处理当月封存数据(所属单位白名单筛选),"
|
||||
"再运行各检查模块。")
|
||||
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
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_seal_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = export_seal_data(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【封存数据导出与预处理完成】")
|
||||
logger.info(" 月份:%s | 白名单单位封存人数:%d", _normalize_month(month), len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("封存数据导出失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,324 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: unsealed_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查5「未封存名单」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有
|
||||
考勤月报封存记录;有在职记录但无封存记录者输出异常名单,异常类型 = 「考勤月报未封存,请处理」。
|
||||
|
||||
数据来源:
|
||||
1) 在职记录(花名册):由「37du花名册导出」共享指令导出到固定路径,本脚本只读取。
|
||||
导出参数:在职状态 = 在职 + 离职(离职需设置离职时间范围 = 检查月月初 至今天),
|
||||
模板 = 员工基础信息。这样才能把「检查月内仍在职 / 检查月内离职」的人全部覆盖到。
|
||||
口径与封存表保持一致:仅检查所属单位白名单单位员工
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部)。
|
||||
2) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
|
||||
判定口径(对应需求文档 XQ0011 检查5):
|
||||
- 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」:
|
||||
在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。
|
||||
- 仅统计所属单位在白名单内的员工;
|
||||
- 有在职记录但工号不在当月封存记录集合里 → 异常。
|
||||
|
||||
输出:
|
||||
未封存名单_{月份}_{时间戳}.xlsx 异常名单(含 37工号/姓名/月报检查月份/异常类型/所属单位/一~五级部门)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du花名册导出」指令导出花名册到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_unsealed_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_unsealed_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional, Set, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import ( # noqa: E402
|
||||
SEAL_UNIT_WHITELIST, enrich_dept_fields, load_excluded_codes, load_seal_rows,
|
||||
)
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_unsealed_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
# 花名册固定路径:由「37du花名册导出」共享指令导出(在职 + 离职,离职时间范围 = 检查月月初至今)
|
||||
DEFAULT_ROSTER_PATH = os.getenv("monthly_unsealed_roster_path") or r"D:\资料\人资\考勤月报封存检查\员工花名册.xlsx"
|
||||
|
||||
# 异常类型(对应需求文档检查5)
|
||||
ABNORMAL_TYPE = "考勤月报未封存,请处理"
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 花名册字段(与「37du花名册导出」指令导出的列名一致)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_DEPT_COLS = ["一级部门", "二级部门", "三级部门", "四级部门", "五级部门"]
|
||||
ROSTER_JOIN_COL = "入职时间"
|
||||
ROSTER_LEAVE_COL = "离职时间"
|
||||
|
||||
# 输出列(对应需求文档检查5输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
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 _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 _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 _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":
|
||||
"""读取花名册(由「37du花名册导出」指令导出,表头在第 1 行)。"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先在影刀流程中拖入「37du花名册导出」指令导出花名册"
|
||||
f"(在职状态=在职+离职,离职时间范围=检查月月初至今,模板=员工基础信息),再运行本流程;"
|
||||
"或通过 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(roster_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查5「未封存名单」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径,默认 DEFAULT_ROSTER_PATH。
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
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}"
|
||||
logger.info("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读花名册(在职记录)
|
||||
df = _load_roster(roster_path)
|
||||
|
||||
# 2. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
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))
|
||||
|
||||
# 4. 导出异常名单
|
||||
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")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:
|
||||
roster_path(花名册文件路径)、month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
roster_path = args.get("roster_path") or (
|
||||
os.getenv("monthly_unsealed_roster_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_unsealed_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_unsealed_check(roster_path, month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查5 考勤月报未封存名单完成】")
|
||||
logger.info(" 检查月份:%s | 未封存人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("检查5执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
import sys
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,288 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: working_days_shift_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
|
||||
|
||||
数据来源(预处理封存表,由 seal_data_export.py 导出并预处理):
|
||||
- 先运行 seal_data_export.py:拉取当月全集团考勤封存数据(接口
|
||||
POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc,
|
||||
sqlId = kq_count_leave_wage_SelectV2),并做预处理:所属单位仅保留白名单单位
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx。
|
||||
- 本模块只读取该预处理封存表,不再直连接口。
|
||||
- 每员工一条封存记录,检查1用到的字段(aa.md 列定义):
|
||||
base_code 工号 / staff_name 姓名
|
||||
join_date 入职日期 / leaveOffice_date 离职时间(算在职天数)
|
||||
kq_stat_month_yq_work_day_in 在职应勤工作日
|
||||
kq_stat_cal_ext9 休息天(考勤日报休息日天数总和)
|
||||
BELONG_UNIT_ORG_NAME 所属单位 / DEPT_ORG_ONE~FIVE 一级~五级部门
|
||||
|
||||
判断口径(对应需求文档 XQ0011 检查1):
|
||||
- 在职天数:由封存「入职/离职时间」计算员工当月应在职的自然天数;
|
||||
- 在职应勤工作日 + 休息天:直接取封存字段 kq_stat_month_yq_work_day_in / kq_stat_cal_ext9;
|
||||
- 差值 = 在职天数 - (应勤工作日 + 休息天);差值非 0 视为异常,异常类型 = 「当月在职天数有差缺排班」。
|
||||
样例:37035483 8-3 离职,在职天数 3;应勤 3、休息 0 → 差值 0 正常。
|
||||
|
||||
在职天数口径(统一采用「月初1日~末日」与「入职日起~离职日止」闭区间交集的自然天数,含首尾)
|
||||
- 全月在职:月初1日即已在职且当月末在职 → 在职天数 = 当月自然天数;
|
||||
- 月初1日在职、当月内离职:在职天数 = 离职日 - 1号 + 1 → 覆盖需求「离职时间 - 1号」;
|
||||
- 月初1日尚未入职、月末在职:在职天数 = 末日 - 入职日 + 1 → 覆盖需求「末日 - 入职时间」;
|
||||
- 当月在册(月初未入职且月内离职):在职天数 = 离职日 - 入职日 + 1 → 覆盖需求「离职 - 入职」;
|
||||
- 月初1日与末日均在职但有入离职异动:在职天数 = 自然天数 - 异动缺勤段。
|
||||
(注:口径与封存样例一致,均含入职/离职当天。若贵司某类口径不含离职/入职当天,请调 _working_days。)
|
||||
|
||||
输出:
|
||||
在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含在职天数/应勤/休息/差值便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json,仅供导出模块使用)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import enrich_dept_fields, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_wd_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 异常类型(对应需求文档检查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:休息天(考勤日报休息日天数总和)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_DEPT_FIELDS = ["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"] # 一~五级部门
|
||||
|
||||
# 输出列(对应需求文档检查1输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"在职天数", "应勤工作日", "休息天", "差值",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
return s
|
||||
|
||||
|
||||
def _text(v) -> str:
|
||||
t = _clean(v)
|
||||
if t.endswith(".0"):
|
||||
t = t[:-2]
|
||||
return t
|
||||
|
||||
|
||||
def _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return None
|
||||
s = s[:10]
|
||||
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 _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 _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) -> List[dict]:
|
||||
"""执行检查1「在职天数是否均排班验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
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}"
|
||||
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map = _build_seal_map(seal_rows)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
# 2. 逐人检查
|
||||
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))
|
||||
|
||||
# 3. 导出异常名单
|
||||
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")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_wd_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_working_days_shift_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查1 在职天数是否均排班验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
logger.error("检查1执行失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,9 @@
|
||||
# XQ0012 EHR预支及支付报酬自动发起ERP付款申请 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0012 EHR预支及支付报酬自动发起ERP付款申请/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
@@ -0,0 +1,10 @@
|
||||
# XQ0013 社保费用申报导出并汇总 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0013 社保费用申报导出并汇总/`
|
||||
- 状态:**已实现(影刀客户端内部实现,源码不在本项目中,本目录仅占位)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `export_calc.py`:社保费用申报导出
|
||||
- `summary.py`:汇总结算
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""验证码采集探针:只截图 + 尝试刷新,绝不提交登录。用完可删。"""
|
||||
import sys
|
||||
import time
|
||||
import hashlib
|
||||
import os
|
||||
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0014 社保系统增减员办理")
|
||||
import sb_login
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'debug_captcha')
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
co = ChromiumOptions()
|
||||
co.auto_port(True)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(sb_login.APPLY_URL)
|
||||
time.sleep(2)
|
||||
sb_login._dismiss_notice(page)
|
||||
tab = sb_login._open_sso_tab(page)
|
||||
if tab is None:
|
||||
print("PROBE: 未进入 SSO 登录页")
|
||||
sys.exit(1)
|
||||
sb_login._wait_sso_ready(tab)
|
||||
legal = tab.ele('tag:div@@text()=法人用户', timeout=10)
|
||||
if legal:
|
||||
legal.click()
|
||||
time.sleep(1)
|
||||
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=3)
|
||||
print("PROBE: 当前激活tab =", active.text.strip() if active else None)
|
||||
|
||||
for i in range(5):
|
||||
img, code_input = sb_login._find_captcha(tab)
|
||||
if not img:
|
||||
print("PROBE: 找不到验证码图")
|
||||
break
|
||||
data = sb_login._read_img_bytes(img)
|
||||
h = hashlib.md5(data).hexdigest()[:10]
|
||||
path = os.path.join(OUT, f"probe_{i}_{h}.png")
|
||||
with open(path, 'wb') as f:
|
||||
f.write(data)
|
||||
print(f"PROBE: 第{i+1}张 md5={h} size={len(data)} -> {os.path.basename(path)}")
|
||||
if i < 4:
|
||||
ok = sb_login._refresh_captcha(tab, img)
|
||||
print(f"PROBE: 刷新{'成功' if ok else '失败'}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
print("PROBE: 采集完成(未提交登录)")
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""探针:打开 SSO 登录页(法人用户 tab),dump 所有输入框的真实属性,
|
||||
用于修正 sb_login.py 的选择器。用完可删。"""
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0014 社保系统增减员办理")
|
||||
import sb_login
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
co = ChromiumOptions()
|
||||
co.auto_port(True)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(sb_login.APPLY_URL)
|
||||
time.sleep(2)
|
||||
sb_login._dismiss_notice(page)
|
||||
tab = sb_login._open_sso_tab(page)
|
||||
if tab is None:
|
||||
print("PROBE: 未进入 SSO 登录页")
|
||||
sys.exit(1)
|
||||
print("PROBE: SSO URL =", tab.url)
|
||||
sb_login._wait_sso_ready(tab)
|
||||
# 点法人用户 tab(精确文本匹配,避免命中包含该文字的外层容器 div)
|
||||
legal = tab.ele('tag:div@@text()=法人用户', timeout=10)
|
||||
print("PROBE: 法人用户tab元素 =", legal, "| tag:", legal.tag if legal else None,
|
||||
"| class:", (legal.attr('class') if legal else None))
|
||||
if legal:
|
||||
legal.click()
|
||||
time.sleep(1.5)
|
||||
active_btn = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=3)
|
||||
print("PROBE: 当前激活tab =", active_btn.text.strip() if active_btn else None)
|
||||
# dump 当前激活面板内的所有输入框
|
||||
panel = tab.ele('css:.ant-tabs-tabpane-active', timeout=5)
|
||||
inputs = panel.eles('tag:input') if panel else tab.eles('tag:input')
|
||||
print(f"PROBE: 共 {len(inputs)} 个 input")
|
||||
for i, ip in enumerate(inputs):
|
||||
try:
|
||||
print(f"[{i}] type={ip.attr('type')} placeholder={ip.attr('placeholder')!r} "
|
||||
f"id={ip.attr('id')!r} name={ip.attr('name')!r} class={(ip.attr('class') or '')[:60]!r}")
|
||||
except Exception as e:
|
||||
print(f"[{i}] 读取失败: {e}")
|
||||
# 顺带 dump 按钮
|
||||
for i, b in enumerate(panel.eles('tag:button') if panel else tab.eles('tag:button')):
|
||||
try:
|
||||
print(f"BTN[{i}] type={b.attr('type')} class={(b.attr('class') or '')[:50]!r} text={b.text.strip()!r}")
|
||||
except Exception as e:
|
||||
print(f"BTN[{i}] 读取失败: {e}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,622 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: check_review.py
|
||||
@Description: XQ0014 重庆社保系统增减员办理(核查-回盘)—— 单文件自包含版
|
||||
增员申报(import_add.py)提交后,平台审核存在滞后。本脚本对源名单中
|
||||
「办理状态=待审核」的人员所在参保单位,逐个登录重庆人社政务平台核查审核结论:
|
||||
|
||||
流程(每个参保单位):
|
||||
1. 登录(复用同目录 sb_login,法人用户 + 图形验证码)
|
||||
2. 单位办事 → 城保参保单位人员增加 → 在线办理(与增员同一入口)
|
||||
3. 左侧菜单点「已申报查询」→ 读表格第一条「当前状态」
|
||||
非「已办结」→ 跳过该单位(审核还没走完)
|
||||
4. 「已办结」→ 点「查看」,监听 queryYsbWs04orWs01 接口拿查询参数
|
||||
(asl001/aaa121/aab001),再用页内 XHR 重放接口翻页取全量(防分页漏数据)
|
||||
5. 按 aac002 证件号码匹配本单位「待审核」人员,回写源名单:
|
||||
- 审核通过 → 办理状态 = 参保成功
|
||||
- 不通过 + 400系统错误 → 先记录不动状态,全部单位核查完后统一清空办理状态
|
||||
(回到待办,之后重新执行8号需求制作名单完成新增)
|
||||
- 不通过 + 其它原因 → 办理状态 = 参保失败,审核意见追加写备注(不覆盖)
|
||||
6. 回盘打印:每个账号核查完都下载回盘表到 DISK_DIR
|
||||
(人员增减申请回盘表_单位_下载日期.xlsx),核对养老/失业/医疗/工伤/生育
|
||||
五项参保状态:全「参保缴费」→ 备注追加个人编号;否则备注追加个人编号 +
|
||||
异常字段名及内容(都是追加,不覆盖)
|
||||
7. 台账回写:与 import_add 同一套 JSON 缓存 + 运行结束统一回写 Excel 机制
|
||||
|
||||
依赖(与 import_add 相同):pandas openpyxl DrissionPage python-dotenv ddddocr
|
||||
运行:python check_review.py
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, parse_qsl, urlencode
|
||||
|
||||
# ---- 单文件运行支持:本目录加入 sys.path,复用同目录 import_add / sb_login ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}")
|
||||
|
||||
import import_add # 同目录:复用名单/台账读取、登录后页面导航、回写缓存机制
|
||||
import sb_login
|
||||
|
||||
# ==================== 1. 配置 ====================
|
||||
CHECK_STATUS = "待审核" # 核查范围:办理状态为该值的人员
|
||||
DONE_STATUS = "已办结" # 已申报查询里第一条的该状态才继续查看
|
||||
PASS_STATUS = "参保成功" # 审核通过 → 办理状态
|
||||
FAIL_STATUS = "参保失败" # 审核不通过(非系统错误)→ 办理状态
|
||||
ERR_400_KEYWORD = "status 400" # aae111 含该关键字 = 系统错误,需重新增员
|
||||
MENU_QUERY = "已申报查询" # 业务页左侧菜单
|
||||
API_KEYWORD = "queryYsbWs04orWs01" # 已申报明细查询接口(监听 + 重放)
|
||||
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
|
||||
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001") # 单位信息接口(页面加载完成标志)
|
||||
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
|
||||
"onlineoffice/OdCommon") # 左侧菜单页(刷新/直跳即可回到菜单)
|
||||
PAGE_SIZE = 10 # 重放接口每页条数(与平台默认一致,翻页取全量)
|
||||
MAX_PAGES = 50 # 重放翻页上限(防死循环)
|
||||
CHECK_LIMIT = None # 每次运行最多核查的单位数(None=不限制)
|
||||
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空办理状态回待办(重新走8号+增员)
|
||||
|
||||
# ---- 回盘打印下载与核对 ----
|
||||
DISK_DIR = r"D:\资料\人资\社保系统增减员办理\回盘打印\新参保-增员" # 回盘文件保存目录
|
||||
REPLAY_PREFIX = "人员增减申请回盘表" # 保存文件名:前缀_单位_日期.xlsx
|
||||
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
|
||||
"工伤参保状态", "生育参保状态"] # 需核对的三险五项状态列
|
||||
INS_OK = "参保缴费" # 正常状态值
|
||||
|
||||
|
||||
# ==================== 2. 核查任务读取 ====================
|
||||
def load_check_tasks(exclude_ids=frozenset()):
|
||||
"""读取源名单,筛选 办理状态=待审核 的行,按参保单位分组。
|
||||
|
||||
返回 [{unit, count, cids(set)}];同时把源文件信息写回 import_add 全局
|
||||
(flush_writeback 依赖 SOURCE_FILE_USED / SOURCE_SHEET_USED)。
|
||||
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
|
||||
"""
|
||||
source_file = import_add._latest_file(import_add.SOURCE_DIR, import_add.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = import_add._pick_sheet(xl, f"{now:%Y%m}参保名单", "参保名单")
|
||||
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
import_add.SOURCE_FILE_USED, import_add.SOURCE_SHEET_USED = source_file, sheet_name
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
|
||||
status = df[import_add.STATUS_COL].astype(str).str.strip()
|
||||
mask = (
|
||||
(df[import_add.REGION_COL].astype(str).str.strip() == import_add.REGION)
|
||||
& (df[import_add.TYPE_COL].astype(str).str.strip() == import_add.OPERATION_TYPE)
|
||||
& (status == CHECK_STATUS)
|
||||
)
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [import_add._norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: import_add._id_hit(import_add._norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
|
||||
if sub.empty:
|
||||
print(f"没有筛选到数据({import_add.REGION} ∩ {import_add.OPERATION_TYPE} ∩ 办理状态={CHECK_STATUS})")
|
||||
return []
|
||||
|
||||
tasks = []
|
||||
for unit, g in sub.groupby(sub[import_add.UNIT_COL].astype(str).str.strip()):
|
||||
cids = {import_add._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda t: t['unit'])
|
||||
print(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / {len(tasks)} 个参保单位(办理状态={CHECK_STATUS})")
|
||||
return tasks
|
||||
|
||||
|
||||
# ==================== 3. 网页操作 ====================
|
||||
def _open_query_menu(tab):
|
||||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||||
import_add._click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
|
||||
f'左侧菜单「{MENU_QUERY}」')
|
||||
import_add._dismiss_popups(tab)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
for tb in tab.eles('tag:table'):
|
||||
try:
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
except Exception:
|
||||
continue
|
||||
if '当前状态' in ths and '操作' in ths:
|
||||
return tb
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(f"点击「{MENU_QUERY}」后未出现申报记录表")
|
||||
|
||||
|
||||
def _read_first_row(table):
|
||||
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
|
||||
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
|
||||
or table.ele('css:tbody tr', timeout=1)
|
||||
if row is None:
|
||||
return None, None
|
||||
ths = [th.text.strip() for th in table.eles('tag:th')]
|
||||
i_status = ths.index('当前状态')
|
||||
tds = [td.text.strip() for td in row.eles('tag:td')]
|
||||
status = tds[i_status] if len(tds) > i_status else ''
|
||||
view = None
|
||||
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
|
||||
try:
|
||||
view = row.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
view = None
|
||||
if view:
|
||||
break
|
||||
return status, view
|
||||
|
||||
|
||||
def _capture_query_url(page, tab, view):
|
||||
"""点「查看」并监听明细查询接口,返回请求 URL。
|
||||
明细可能在当前 tab 打开也可能新开 tab:两个方向都轮询监听。"""
|
||||
before = set(page.tab_ids)
|
||||
tab.listen.start(API_KEYWORD)
|
||||
new_tabs = []
|
||||
packet = None
|
||||
try:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
view.click(by_js=True)
|
||||
deadline = time.time() + 25
|
||||
while time.time() < deadline and packet is None:
|
||||
# 新开 tab 也挂上监听(明细页可能新 tab 加载接口)
|
||||
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
|
||||
new_tabs.append(tid)
|
||||
try:
|
||||
page.get_tab(tid).listen.start(API_KEYWORD)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
packet = tab.listen.wait(count=1, timeout=2)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet is None:
|
||||
for tid in new_tabs:
|
||||
try:
|
||||
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet:
|
||||
break
|
||||
finally:
|
||||
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
|
||||
try:
|
||||
t.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if not packet:
|
||||
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
|
||||
url = packet.request.url
|
||||
print(f" 已捕获明细接口:{url[:100]}...")
|
||||
return url
|
||||
|
||||
|
||||
def _fetch_via_xhr(tab, url):
|
||||
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
|
||||
js = ("const xhr=new XMLHttpRequest();"
|
||||
"xhr.open('GET',arguments[0],false);"
|
||||
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
|
||||
"xhr.send();return xhr.responseText;")
|
||||
return tab.run_js(js, url)
|
||||
|
||||
|
||||
def _wait_unit_loaded(tab, unit_name, timeout=40):
|
||||
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
|
||||
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
|
||||
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
|
||||
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
raw = _fetch_via_xhr(tab, API_UNIT_INFO)
|
||||
data = (json.loads(raw).get('data') or [None])[0]
|
||||
if data and data.get('aab001'):
|
||||
print(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
|
||||
return data
|
||||
except Exception:
|
||||
pass
|
||||
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
|
||||
try:
|
||||
if tab.ele(f'text:{unit_name}', timeout=0.5):
|
||||
print(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
|
||||
return {}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def _replay_query_all(tab, captured_url):
|
||||
"""用捕获的请求参数重放接口翻页,取全量明细行。
|
||||
返回 [{name, cid, conclusion, opinion}, ...](字段取 aac003/aac002/aae110s/aae111)。"""
|
||||
parsed = urlparse(captured_url)
|
||||
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
||||
if k != 'pageIndex']
|
||||
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
rows, total = [], None
|
||||
for idx in range(MAX_PAGES):
|
||||
params = base_params + [('pageIndex', json.dumps(
|
||||
{"pageIndex": idx, "pageSize": PAGE_SIZE}, separators=(',', ':')))]
|
||||
full = f"{root}?{urlencode(params)}"
|
||||
raw = _fetch_via_xhr(tab, full)
|
||||
if not raw:
|
||||
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
|
||||
payload = json.loads(raw)
|
||||
data = payload.get('data') or {}
|
||||
items = data.get('data') or []
|
||||
if total is None:
|
||||
total = data.get('total')
|
||||
rows.extend(items)
|
||||
print(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
|
||||
if not items or (total is not None and len(rows) >= total):
|
||||
break
|
||||
results = []
|
||||
for it in rows:
|
||||
results.append({
|
||||
"name": str(it.get('aac003') or '').strip(),
|
||||
"cid": import_add._norm_id(it.get('aac002')),
|
||||
"conclusion": str(it.get('aae110s') or '').strip(),
|
||||
"opinion": str(it.get('aae111') or '').strip(),
|
||||
})
|
||||
# 平台登记的参保单位全称(aab004),用于回盘文件命名
|
||||
unit_full = ""
|
||||
for it in rows:
|
||||
v = str(it.get('aab004') or '').strip()
|
||||
if v:
|
||||
unit_full = v
|
||||
break
|
||||
return results, unit_full
|
||||
|
||||
|
||||
# ==================== 4. 结论回写 ====================
|
||||
def build_writeback(results, task_cids, unit_name):
|
||||
"""按回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
|
||||
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。
|
||||
400系统错误不立即清状态:先记录,运行结束后统一清空办理状态回待办再新增。"""
|
||||
status_map, remark_map, redo400, logs = {}, {}, [], []
|
||||
for r in results:
|
||||
if not r['cid'] or r['cid'] not in task_cids:
|
||||
continue
|
||||
concl, opinion = r['conclusion'], r['opinion']
|
||||
line = f" {r['name']}({r['cid']}):{concl}"
|
||||
if concl == '审核通过':
|
||||
status_map[r['cid']] = PASS_STATUS
|
||||
line += f" → 办理状态={PASS_STATUS}"
|
||||
elif concl == '不通过':
|
||||
if ERR_400_KEYWORD in opinion:
|
||||
# 系统错误:仅记录,运行结束后统一清空办理状态回待办重新增员
|
||||
if RUN_400_CLEAR:
|
||||
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
|
||||
line += " → 400系统错误,已记录(结束后统一清状态回待办重新增员)"
|
||||
else:
|
||||
status_map[r['cid']] = FAIL_STATUS
|
||||
remark_map[r['cid']] = opinion or '审核不通过'
|
||||
line += f" → 办理状态={FAIL_STATUS},备注追加:{opinion[:60]}"
|
||||
else:
|
||||
line += " → 非终态结论,跳过"
|
||||
logs.append(line)
|
||||
return status_map, remark_map, redo400, logs
|
||||
|
||||
|
||||
# ==================== 4b. 回盘打印下载与核对 ====================
|
||||
def _clean_cell(v):
|
||||
"""单元格值转干净字符串:浮点整数去掉 .0,其余去首尾空白。"""
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return str(int(v))
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def _download_huipan(page, biz_tab, unit):
|
||||
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
|
||||
返回保存的文件 Path。"""
|
||||
save_dir = Path(DISK_DIR)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = save_dir / f"{REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
|
||||
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
|
||||
try:
|
||||
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」')
|
||||
except Exception:
|
||||
# 点「查看」后会跳到明细详情页,左侧菜单不可见:直跳 OdCommon 菜单页即可
|
||||
try:
|
||||
print(" 当前页看不到左侧菜单,直跳菜单页...")
|
||||
biz_tab.get(MENU_PAGE_URL)
|
||||
time.sleep(2)
|
||||
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(菜单页)')
|
||||
except Exception:
|
||||
# 直跳也不行:重开业务页再点(最后兜底)
|
||||
biz_tab = import_add._open_business_page(page, sb_login.LAST_SESSION['tab'])
|
||||
import_add._dismiss_popups(biz_tab)
|
||||
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
|
||||
import_add._dismiss_popups(biz_tab)
|
||||
|
||||
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接/文本)
|
||||
btn = None
|
||||
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印',
|
||||
'tag:span@@text()=回盘打印'):
|
||||
try:
|
||||
btn = biz_tab.ele(sel, timeout=2)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if btn is None:
|
||||
raise RuntimeError("未找到页内「回盘打印」按钮")
|
||||
|
||||
biz_tab.set.download_path(str(save_dir))
|
||||
before = {f.name for f in save_dir.iterdir() if f.is_file()}
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
|
||||
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
|
||||
new_file, last_size, stable = None, -1, 0
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
|
||||
and f.suffix.lower() not in ('.crdownload', '.tmp')]
|
||||
if not files:
|
||||
stable, last_size = 0, -1
|
||||
continue
|
||||
f = max(files, key=lambda x: x.stat().st_mtime)
|
||||
size = f.stat().st_size
|
||||
if size > 0 and size == last_size:
|
||||
stable += 1
|
||||
if stable >= 2:
|
||||
new_file = f
|
||||
break
|
||||
else:
|
||||
stable = 0
|
||||
last_size = size
|
||||
if new_file is None:
|
||||
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件")
|
||||
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
|
||||
return target
|
||||
|
||||
|
||||
def _verify_huipan(filepath, task_cids):
|
||||
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
|
||||
同人多条记录:取参保缴费数量最多的那条(并列取先出现的)。
|
||||
返回 (remark_map, logs)。"""
|
||||
df = pd.read_excel(filepath, header=1)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
need = ['个人编号', '身份证号'] + INS_STATUSES
|
||||
missing = [c for c in need if c not in df.columns]
|
||||
if missing:
|
||||
raise RuntimeError(f"回盘表缺少列:{missing}")
|
||||
remarks, logs = {}, []
|
||||
for cid in task_cids:
|
||||
rows = df[df['身份证号'].map(
|
||||
lambda v: import_add._id_hit(import_add._norm_id(_clean_cell(v)), [cid]))]
|
||||
if rows.empty:
|
||||
remarks[cid] = "未查询到回盘记录"
|
||||
logs.append(f" 证件{cid}:回盘表中未找到记录 → 备注追加「未查询到回盘记录」")
|
||||
continue
|
||||
# 同人多条记录:取参保缴费数量最多的那条(并列取先出现的)
|
||||
best_row, best_ok = None, -1
|
||||
for _, row in rows.iterrows():
|
||||
ok = sum(1 for c in INS_STATUSES if _clean_cell(row[c]) == INS_OK)
|
||||
if ok > best_ok:
|
||||
best_row, best_ok = row, ok
|
||||
target = best_row
|
||||
bh = _clean_cell(target['个人编号'])
|
||||
if best_ok == len(INS_STATUSES):
|
||||
# 五项全参保缴费 = 正常,备注只追加个人编号
|
||||
remarks[cid] = f"个人编号:{bh}"
|
||||
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
|
||||
else:
|
||||
# 有不是参保缴费的:记录个人编号 + 异常字段名和对应内容
|
||||
bad = [f"{c}:{_clean_cell(target[c])}"
|
||||
for c in INS_STATUSES if _clean_cell(target[c]) != INS_OK]
|
||||
remarks[cid] = f"个人编号:{bh};" + "、".join(bad)
|
||||
logs.append(f" 证件{cid}:参保状态异常 → {';'.join(bad)}(个人编号 {bh})→ 备注追加")
|
||||
return remarks, logs
|
||||
|
||||
|
||||
def _do_huipan(page, biz_tab, task, res, unit_full="", fail_cids=()):
|
||||
"""每个账号核查完都执行:下载回盘记录 + 核对参保状态 + 备注追加(含与核查备注合并)。
|
||||
文件名单位优先用平台 aab004 全称,未取到(未办结跳过等)退回源名单参保单位名。
|
||||
fail_cids:审核不通过(参保失败)人员,平台无其回盘记录,跳过「未查询到回盘记录」回写。"""
|
||||
name_for_file = (unit_full or task['unit']).strip()
|
||||
if unit_full and unit_full != task['unit']:
|
||||
print(f" 使用平台单位全称命名:{unit_full}")
|
||||
print(" 开始回盘打印下载...")
|
||||
hp_file = _download_huipan(page, biz_tab, name_for_file)
|
||||
print(f" 回盘文件已保存:{hp_file}")
|
||||
hp_remarks, hp_logs = _verify_huipan(hp_file, task['cids'])
|
||||
for line in hp_logs:
|
||||
print(line)
|
||||
for cid in fail_cids:
|
||||
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
|
||||
hp_remarks.pop(cid)
|
||||
print(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
|
||||
# 与核查阶段已生成的备注合并(writeback_source 按证件号覆盖,需手动拼接)
|
||||
for cid in list(hp_remarks):
|
||||
old = import_add._PENDING_REMARK.get(cid)
|
||||
if old:
|
||||
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
|
||||
if hp_remarks:
|
||||
import_add.writeback_source({}, hp_remarks)
|
||||
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
|
||||
|
||||
|
||||
# ==================== 5. 单个单位完整核查 ====================
|
||||
def do_unit_check(task):
|
||||
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
|
||||
page = sb_login.LAST_SESSION.get('page')
|
||||
work_tab = sb_login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "checked": 0, "passed": 0, "failed": 0,
|
||||
"redo400": [], "skipped": False}
|
||||
try:
|
||||
import_add._shot(work_tab, "c1_workbench")
|
||||
biz_tab = import_add._open_business_page(page, work_tab)
|
||||
import_add._dismiss_popups(biz_tab)
|
||||
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据
|
||||
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is None:
|
||||
# 页面没加载出单位:重开一次业务页再等
|
||||
print(" 单位信息未加载,重开业务页重试...")
|
||||
biz_tab = import_add._open_business_page(page, work_tab)
|
||||
import_add._dismiss_popups(biz_tab)
|
||||
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is None:
|
||||
res.update(success=True, skipped=True,
|
||||
message="单位信息未加载(getAab001无数据),跳过")
|
||||
return res
|
||||
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
|
||||
fail_cids = set() # 审核不通过(参保失败)人员:平台无回盘记录,回盘阶段跳过其未查询备注
|
||||
_shot_c(biz_tab, "c2_biz_page")
|
||||
|
||||
table = _open_query_menu(biz_tab)
|
||||
_shot_c(biz_tab, "c3_query_list")
|
||||
status, view = _read_first_row(table)
|
||||
if not status:
|
||||
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
|
||||
elif status != DONE_STATUS:
|
||||
res.update(success=True, skipped=True,
|
||||
message=f"第一条状态「{status}」非{DONE_STATUS},跳过")
|
||||
else:
|
||||
print(f" 第一条状态:{status},点击查看读取审核结论")
|
||||
url = _capture_query_url(page, biz_tab, view)
|
||||
results, detail_full = _replay_query_all(biz_tab, url)
|
||||
unit_full = unit_full or detail_full
|
||||
_shot_c(biz_tab, "c4_detail_fetched")
|
||||
if not results:
|
||||
res.update(success=True, message="明细接口返回 0 条,跳过")
|
||||
else:
|
||||
status_map, remark_map, redo400, logs = build_writeback(
|
||||
results, task['cids'], task['unit'])
|
||||
fail_cids = {cid for cid, st in status_map.items() if st == FAIL_STATUS}
|
||||
for line in logs:
|
||||
print(line)
|
||||
if status_map or remark_map:
|
||||
import_add.writeback_source(status_map, remark_map)
|
||||
n_match = len([r for r in results if r['cid'] in task['cids']])
|
||||
n_pass = len([v for v in status_map.values() if v == PASS_STATUS])
|
||||
n_fail = len([v for v in status_map.values() if v == FAIL_STATUS])
|
||||
res.update(
|
||||
success=True,
|
||||
checked=n_match,
|
||||
passed=n_pass,
|
||||
failed=n_fail,
|
||||
redo400=redo400,
|
||||
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
|
||||
f"400系统错误{len(redo400)}(结束后统一清状态)"))
|
||||
|
||||
# 回盘打印:每个账号核查完都要下载回盘记录并核对参保状态(无论是否已办结)
|
||||
try:
|
||||
_do_huipan(page, biz_tab, task, res, unit_full, fail_cids)
|
||||
except Exception as e:
|
||||
res["huipan"] = f"回盘打印失败:{e}"
|
||||
print(f" 回盘打印失败:{e}")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"核查异常:{e}"
|
||||
return res
|
||||
|
||||
|
||||
def _shot_c(tab, name):
|
||||
"""核查流程调试截图(沿用 import_add 的 DEBUG_MODE 开关,前缀 c 区分)。"""
|
||||
import_add._shot(tab, name)
|
||||
|
||||
|
||||
# ==================== 6. 逐单位登录 + 核查 ====================
|
||||
def process_units(tasks, accounts):
|
||||
"""逐参保单位:登录 → 已申报查询核查 → 回写。每账号办完清 cookies 关浏览器。"""
|
||||
results = []
|
||||
for i, task in enumerate(tasks, 1):
|
||||
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人待审核)==========")
|
||||
acc = accounts.get(task['unit'])
|
||||
try:
|
||||
login_res = sb_login.main({"username": acc["username"], "password": acc["password"]})
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
print(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_unit_check(task)
|
||||
print(f"核查结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False, "message": login_res.get("message", "")})
|
||||
finally:
|
||||
sb_login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 7. 主流程 ====================
|
||||
def run():
|
||||
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
|
||||
recovered_ids = import_add._load_ckpt()
|
||||
tasks = load_check_tasks(exclude_ids=recovered_ids)
|
||||
if recovered_ids:
|
||||
print("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
import_add.flush_writeback()
|
||||
except Exception as e:
|
||||
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not tasks:
|
||||
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
|
||||
|
||||
accounts = import_add.load_accounts([t['unit'] for t in tasks])
|
||||
# 预检:账号齐备才继续(与增员一致的严格预检)
|
||||
errors = []
|
||||
for t in tasks:
|
||||
acc = accounts.get(t['unit'])
|
||||
if acc is None:
|
||||
errors.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errors.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errors:
|
||||
print("\n预检未通过:")
|
||||
for e in errors:
|
||||
print(f" - {e}")
|
||||
return {"success": False, "message": "预检未通过,详见日志", "total": len(tasks), "done": 0}
|
||||
|
||||
todo = tasks[:CHECK_LIMIT]
|
||||
results = process_units(todo, accounts)
|
||||
# 400系统错误:核查时只记录,全部单位核查完后统一清空办理状态回待办(重新走8号+增员)
|
||||
redo_all = [p for r in results for p in (r.get("redo400") or [])]
|
||||
if redo_all:
|
||||
import_add.writeback_source({p['cid']: "" for p in redo_all}, {})
|
||||
print(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理状态回待办,"
|
||||
f"请重新执行8号需求制作名单后增员:")
|
||||
for p in redo_all:
|
||||
print(f" - {p['name']}({p['cid']}){p['unit']}")
|
||||
try:
|
||||
import_add.flush_writeback()
|
||||
except Exception as e:
|
||||
print(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
skip = [r for r in ok if r.get("skipped")]
|
||||
print(f"\n========== 汇总 ==========")
|
||||
print(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
print(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
return {"success": not fail, "message": f"完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
|
||||
"total": len(results), "done": len(ok) - len(skip)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(run())
|
||||
@@ -0,0 +1,894 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: import_add.py
|
||||
@Description: XQ0014 重庆社保系统增减员办理(新参保-增员)—— 单文件自包含版
|
||||
与 XQ0008 联动:消费 8 号需求产出的《XX增员导入名单.xls》,逐参保单位登录
|
||||
重庆人社政务平台(法人用户)完成增员导入。
|
||||
|
||||
流程:
|
||||
1. 读取最新《XXXX年X月社保变更及增减名单及人数统计.xlsx》(文件名年月动态,取最新)
|
||||
→ sheet「YYYYMM参保名单」(年月动态,表头第3行,H-AV 共41列)
|
||||
2. 筛选:区域(Y列)=重庆 ∩ 参保类型(H列)=新参保 ∩ 办理状态(AP列)非空,按参保单位分组
|
||||
3. 匹配 XQ0008 产出:新参保-增员/{参保单位}增员导入名单.xls(文件名规则同 generate_add)
|
||||
4. 取账号:最新《*社保户头管理台账*.xlsx》→ sheet「YYYY年M月缴费比例」(年月动态,
|
||||
表头1-2行合并)→ 数据行筛选 城市(D列)=重庆 ∩ 是否在用(E列)=是,
|
||||
参保户头(B列)=参保单位 匹配:
|
||||
用户名 = I列(统一社会信用代码) 优先,为空回退 K列(政务平台用户名),都空→预检报错
|
||||
密码 = L列(政务平台密码),为空→预检报错
|
||||
5. 预检汇总:所有单位「导入文件 + 账号 + 密码」齐备才继续,否则列出全部问题后停止
|
||||
6. 逐参保单位登录政务平台(调用同目录 sb_login,每个单位登录一次,
|
||||
不做 cookies 缓存——平台 cookies 极易失效,账号多各自缓存也无意义)
|
||||
登录后的网页导入操作步骤
|
||||
|
||||
依赖安装:
|
||||
pip install pandas openpyxl DrissionPage python-dotenv ddddocr
|
||||
|
||||
环境变量(可选):
|
||||
cq_social_change_dir = 名单/产出根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
|
||||
cq_social_ledger_dir = 台账目录(默认 D:\\资料\\人资\\社保系统增减员办理)
|
||||
|
||||
运行:python import_add.py
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from glob import glob
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行并 import 同目录 sb_login ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}")
|
||||
|
||||
# ==================== 1. 路径与筛选配置 ====================
|
||||
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or r"D:\资料\人资\社保系统增减员办理"
|
||||
IMPORT_DIR_NAME = "新参保-增员" # XQ0008 产出目录(按参保类型分文件夹)
|
||||
SOURCE_GLOB = "*社保*.xlsx" # 源名单文件(年月动态,取最新)
|
||||
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账文件(可能加前后缀,取最新)
|
||||
|
||||
REGION = "重庆" # 区域(Y列)筛选值
|
||||
OPERATION_TYPE = "新参保" # 参保类型(H列)筛选值
|
||||
TYPE_COL, REGION_COL, STATUS_COL, UNIT_COL = "参保类型", "区域", "办理状态", "参保单位"
|
||||
|
||||
# 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过):
|
||||
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
|
||||
|
||||
DO_LOGIN = True # 预检通过后是否执行逐单位登录(网页操作步骤未补充前可置 False 只做预检)
|
||||
RUN_LIMIT = None # 每次运行最多办理的单位数(None=不限制,一次跑完剩余全部;已办单位自动跳过)
|
||||
DEBUG_MODE = False # 调试模式开关:开启后才保存页面截图(debug_shots\)和验证码截图(debug_captcha\),日常运行关闭
|
||||
os.environ['sb_captcha_debug'] = '1' if DEBUG_MODE else '0' # 同步给 sb_login:控制验证码调试图是否落盘
|
||||
|
||||
# 记录本次使用的源名单(供网页操作后回写台账)
|
||||
SOURCE_FILE_USED, SOURCE_SHEET_USED = None, None
|
||||
|
||||
|
||||
# ==================== 2. 通用辅助 ====================
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名(与 XQ0008 generate_add.py 规则一致,保证产出文件名可复现)。"""
|
||||
if value is None or not str(value).strip():
|
||||
return "未知单位"
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _to_text(value):
|
||||
"""None/NaN → '',其余转去空白字符串(台账号/密码列用)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _latest_file(directory, pattern):
|
||||
"""目录内按模式取最新文件(排除 Excel 临时文件 ~$)。"""
|
||||
candidates = [p for p in glob(os.path.join(directory, pattern))
|
||||
if not os.path.basename(p).startswith("~$")]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(f"在 {directory} 下未找到匹配 {pattern} 的文件")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _pick_sheet(xl, exact_name, keyword, pattern=None):
|
||||
"""优先精确 sheet 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
if exact_name in names:
|
||||
return exact_name
|
||||
if pattern:
|
||||
hits = [(int(m.group(1)), int(m.group(2)), n)
|
||||
for n in names if (m := re.match(pattern, n))]
|
||||
if hits:
|
||||
return max(hits)[2]
|
||||
for n in names:
|
||||
if keyword in n:
|
||||
return n
|
||||
raise ValueError(f"未找到目标 sheet(精确={exact_name},关键字={keyword}),"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
|
||||
|
||||
# ==================== 3. 源名单读取与筛选 ====================
|
||||
def _norm_id(v):
|
||||
"""身份证号规范化:去空格、转大写;数值型(Excel 把纯数字身份证存成数值)转整数字符串。"""
|
||||
if v is None:
|
||||
return ''
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
v = int(v)
|
||||
return str(v).strip().upper()
|
||||
|
||||
|
||||
def _id_hit(cid, ref_ids):
|
||||
"""身份证匹配:规范化后精确匹配(去空格、转大写)。
|
||||
不做前缀/模糊匹配:同一批人同区县同出生日期时前 15 位可能撞车,误匹配会回写错行。"""
|
||||
return bool(cid) and cid in ref_ids
|
||||
|
||||
|
||||
def load_units(exclude_ids=frozenset()):
|
||||
"""读取源名单并筛选,返回 [(参保单位, 人数), ...](按单位分组)。
|
||||
|
||||
exclude_ids:需排除的身份证号集合(上次运行已回写办理状态的人员,防重复申报)。
|
||||
"""
|
||||
global SOURCE_FILE_USED, SOURCE_SHEET_USED
|
||||
source_file = _latest_file(SOURCE_DIR, SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = _pick_sheet(xl, f"{now:%Y%m}参保名单", "参保名单")
|
||||
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
SOURCE_FILE_USED, SOURCE_SHEET_USED = source_file, sheet_name
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
|
||||
# 增员只办「办理状态为空/NULL」的行:待审核=已提交社保局,参保失败=已在其它流程处理,均跳过
|
||||
status_text = df[STATUS_COL].astype(str).str.strip().str.lower()
|
||||
mask = (
|
||||
(df[REGION_COL].astype(str).str.strip() == REGION)
|
||||
& (df[TYPE_COL].astype(str).str.strip() == OPERATION_TYPE)
|
||||
& (df[STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
|
||||
)
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [_norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: _id_hit(_norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报)")
|
||||
if sub.empty:
|
||||
print(f"没有筛选到数据({REGION} ∩ {OPERATION_TYPE} ∩ 办理状态为空)")
|
||||
return []
|
||||
grouped = sub.groupby(sub[UNIT_COL].astype(str).str.strip()).size()
|
||||
units = sorted(grouped.items(), key=lambda t: t[0])
|
||||
print(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
|
||||
return units
|
||||
|
||||
|
||||
# ==================== 4. 台账取号 ====================
|
||||
def load_accounts(unit_names):
|
||||
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
|
||||
|
||||
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
|
||||
取不到的单位不在返回值中(由预检统一报错)。
|
||||
"""
|
||||
ledger_file = _latest_file(LEDGER_DIR, LEDGER_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(ledger_file)
|
||||
sheet_name = _pick_sheet(xl, f"{now.year}年{now.month}月缴费比例", "缴费比例",
|
||||
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
|
||||
print(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
|
||||
|
||||
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
|
||||
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
|
||||
df = df[df[LEDGER_COL["户头"]].notna()].copy()
|
||||
for c in LEDGER_COL.values():
|
||||
df[c] = df[c].map(_to_text)
|
||||
|
||||
pool = df[(df[LEDGER_COL["城市"]] == REGION) & (df[LEDGER_COL["在用"]] == "是")]
|
||||
accounts = {}
|
||||
for name in unit_names:
|
||||
hit = pool[pool[LEDGER_COL["户头"]] == name]
|
||||
if hit.empty:
|
||||
continue # 预检阶段统一报「台账未匹配」
|
||||
row = hit.iloc[0]
|
||||
credit, plat_user, plat_pwd = (
|
||||
row[LEDGER_COL["信用代码"]], row[LEDGER_COL["平台用户名"]], row[LEDGER_COL["平台密码"]])
|
||||
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
|
||||
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
|
||||
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
|
||||
return accounts
|
||||
|
||||
|
||||
# ==================== 5. 预检 ====================
|
||||
def precheck(units, accounts):
|
||||
"""预检:核对每个单位的导入文件与账号。返回待办列表 [{unit, count, file, username, password}]。"""
|
||||
import_dir = os.path.join(SOURCE_DIR, IMPORT_DIR_NAME)
|
||||
tasks, errors = [], []
|
||||
print("\n========== 预检 ==========")
|
||||
for unit, count in units:
|
||||
file_path = os.path.join(import_dir, f"{_safe_name(unit)}增员导入名单.xls")
|
||||
acc = accounts.get(unit)
|
||||
problems = []
|
||||
if not os.path.isfile(file_path):
|
||||
problems.append(f"缺导入文件({IMPORT_DIR_NAME}\\{os.path.basename(file_path)})")
|
||||
if acc is None:
|
||||
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
|
||||
else:
|
||||
if not acc["username"]:
|
||||
problems.append("账号缺失(I列信用代码与K列平台用户名均为空)")
|
||||
if not acc["password"]:
|
||||
problems.append("密码缺失(L列平台密码为空)")
|
||||
if problems:
|
||||
errors.append(f"[{unit}] " + ";".join(problems))
|
||||
print(f" ✗ {unit}({count}人):{';'.join(problems)}")
|
||||
else:
|
||||
tasks.append({"unit": unit, "count": count, "file": file_path,
|
||||
"username": acc["username"], "password": acc["password"]})
|
||||
print(f" ✓ {unit}({count}人)账号={acc['username']}"
|
||||
f"({acc['username_src']})文件={os.path.basename(file_path)}")
|
||||
if errors:
|
||||
print(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
|
||||
for e in errors:
|
||||
print(f" - {e}")
|
||||
return None
|
||||
print(f"预检通过:{len(tasks)} 个单位待办理\n")
|
||||
return tasks
|
||||
|
||||
|
||||
# ==================== 6. 网页操作:城保参保单位人员增加 ====================
|
||||
BUSINESS_ITEM = "城保参保单位人员增加" # 单位办事列表里的业务名称
|
||||
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
|
||||
DEBUG_SHOT_DIR = _HERE / "debug_shots"
|
||||
|
||||
|
||||
def _shot(tab, name):
|
||||
"""调试截图:仅 DEBUG_MODE 开启时保存页面截图并打印当前 URL,便于事后定位哪一步页面状态异常。"""
|
||||
if not DEBUG_MODE:
|
||||
return
|
||||
try:
|
||||
DEBUG_SHOT_DIR.mkdir(exist_ok=True)
|
||||
ts = datetime.now().strftime("%H%M%S")
|
||||
tab.get_screenshot(path=str(DEBUG_SHOT_DIR), name=f"{ts}_{name}.png")
|
||||
print(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
|
||||
except Exception as e:
|
||||
print(f" [截图失败] {name}: {e}")
|
||||
|
||||
|
||||
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
|
||||
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
|
||||
last_err = None
|
||||
for sel in selectors:
|
||||
try:
|
||||
ele = tab.ele(sel, timeout=timeout)
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
continue
|
||||
if ele:
|
||||
ele.click()
|
||||
return ele
|
||||
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
|
||||
|
||||
|
||||
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
|
||||
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=timeout)
|
||||
if ele:
|
||||
return ele
|
||||
raise RuntimeError(f"网页操作失败:找不到{desc}")
|
||||
|
||||
|
||||
def _wait_modal(tab, keyword, timeout=60):
|
||||
"""等待某 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for m in tab.eles('css:.ant-modal-body'):
|
||||
if keyword in (m.text or ''):
|
||||
return m
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _dismiss_popups(tab, rounds=5):
|
||||
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
|
||||
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
|
||||
for _ in range(rounds):
|
||||
hit = False
|
||||
for t in texts:
|
||||
try:
|
||||
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
print(f" 关闭弹窗:{t}")
|
||||
hit = True
|
||||
time.sleep(1.2)
|
||||
except Exception:
|
||||
pass
|
||||
if not hit:
|
||||
break
|
||||
|
||||
|
||||
def _open_business_page(page, work_tab):
|
||||
"""工作台 → 单位办事 → 「城保参保单位人员增加」在线办理。返回承载业务页的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
|
||||
time.sleep(2.5)
|
||||
# 列表项:h4 标题定位 → 上溯到 li.ant-list-item → 点其「在线办理」
|
||||
h4 = _find_any(work_tab, [f'tag:h4@@text()={BUSINESS_ITEM}'], f'业务入口「{BUSINESS_ITEM}」')
|
||||
li = h4
|
||||
for _ in range(6):
|
||||
li = li.parent()
|
||||
if li is None:
|
||||
break
|
||||
if li.tag == 'li':
|
||||
break
|
||||
act = li.ele('text=在线办理', timeout=3) if li is not None else None
|
||||
if act is None:
|
||||
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
|
||||
act.click()
|
||||
# 业务页可能新开 tab 或当前页跳转:轮询识别出现上传控件(input[type=file])的页面
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
|
||||
for tid in cand_tids:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
if t.ele('#customized_form_controls_data', timeout=0.5):
|
||||
return t
|
||||
except Exception:
|
||||
continue
|
||||
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
|
||||
|
||||
|
||||
def _wait_import_result(tab, timeout=90):
|
||||
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示(modal/toast,不限语言)。
|
||||
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
# 1) modal:含「导入完成」即成功;其它任何非加载中文本都视为失败提示(如 Required request part ... 报错)
|
||||
for m in tab.eles('css:.ant-modal-body'):
|
||||
t = (m.text or '').strip()
|
||||
if '导入完成' in t:
|
||||
return "ok", m
|
||||
if t and not any(k in t for k in ('提交中', '导入中', '加载中')):
|
||||
return "fail", t
|
||||
# 2) 顶部 toast 小提示(几秒即消失,需轮询抓),任何非空文本都记录
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
return "fail", t
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.4)
|
||||
return "timeout", None
|
||||
|
||||
|
||||
def _wait_unit_ready(tab, timeout=5):
|
||||
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。
|
||||
|
||||
单位信息由上传文件解析而来,显示在 borderless 下拉框里:
|
||||
可能先以 placeholder 形式出现(如「20389605,重庆XX有限公司」),也可能直接是选中值。
|
||||
必须等文本内容真正渲染出来(非空)才算就绪,仅元素挂载不算。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for sel in tab.eles('css:.ant-select-borderless'):
|
||||
for kind in ('css:.ant-select-selection-placeholder',
|
||||
'css:.ant-select-selection-item'):
|
||||
ele = sel.ele(kind, timeout=1)
|
||||
# 元素存在且文本可见(如「20389605,重庆XX有限公司」)才代表单位信息已显示
|
||||
if ele and (ele.text or '').strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def _upload_import(tab, xls_path, max_rounds=3):
|
||||
"""上传名单 xls 并点「导入」,带失败探针与重试:
|
||||
每轮都重新选文件(重新触发页面解析单位信息),就绪后再点导入。
|
||||
返回 (导入成功人数, 导入失败人数)。"""
|
||||
last_err = "导入超时无响应"
|
||||
for rnd in range(1, max_rounds + 1):
|
||||
inp = _find_any(tab, ['#customized_form_controls_data',
|
||||
'css:input[type="file"]'], '文件上传控件')
|
||||
inp.input(xls_path) # DrissionPage 对 file input 直接写路径即上传
|
||||
# 等单位信息出现(placeholder 或选中值),未就绪点导入会报 aab001 缺失
|
||||
if not _wait_unit_ready(tab, timeout=40):
|
||||
print(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
|
||||
time.sleep(1.0) # 就绪后再留缓冲,避免点太快
|
||||
_shot(tab, "03_file_selected")
|
||||
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
|
||||
state, payload = _wait_import_result(tab, timeout=90)
|
||||
if state == "ok":
|
||||
_shot(tab, "04_import_result")
|
||||
text = payload.text or ''
|
||||
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
|
||||
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
|
||||
total = int(m_ok.group(1)) if m_ok else 0
|
||||
failed = int(m_fail.group(1)) if m_fail else 0
|
||||
print(f" 导入完成:成功 {total} 人,失败 {failed} 人")
|
||||
if total == 0:
|
||||
raise RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
|
||||
for t in ('确 定', '确定'):
|
||||
try:
|
||||
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
btn.click()
|
||||
break
|
||||
time.sleep(1.5)
|
||||
return total, failed
|
||||
# 失败/超时:记录提示,重试
|
||||
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
|
||||
print(f" 第 {rnd} 轮导入未成功:{str(last_err)[:120]}")
|
||||
time.sleep(2 + rnd) # 失败后多等一会,避免连点触发风控
|
||||
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
|
||||
|
||||
|
||||
def _read_failed_rows(tab):
|
||||
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。
|
||||
按表头(含「证件号码」+「详细信息」列)定位表格,避免抓到左侧导航等其它 tab 组件的面板。"""
|
||||
try:
|
||||
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
|
||||
except Exception:
|
||||
tab_btn = None
|
||||
if not tab_btn:
|
||||
return []
|
||||
tab_btn.click()
|
||||
time.sleep(2)
|
||||
rows = []
|
||||
try:
|
||||
for tb in tab.eles('tag:table'):
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
if '证件号码' in ths and '详细信息' in ths:
|
||||
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
|
||||
for tr in tb.eles('css:tbody tr'):
|
||||
tds = [td.text.strip() for td in tr.eles('tag:td')]
|
||||
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
|
||||
detail = tds[i_detail]
|
||||
# 备注只保留冒号后的内容(去掉"校验通过业务校验失败:"这类前缀)
|
||||
for sep in (':', ':'):
|
||||
if sep in detail:
|
||||
detail = detail.split(sep, 1)[1].strip()
|
||||
break
|
||||
rows.append((tds[i_id], detail))
|
||||
break
|
||||
except Exception as e:
|
||||
print(f" 读取校验未通过表格异常:{e}")
|
||||
_shot(tab, "05_check_failed_tab")
|
||||
return rows
|
||||
|
||||
|
||||
def _wait_pdf_ready(tab, timeout=60):
|
||||
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
|
||||
last, stable_since = None, None
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
canvases = tab.eles('css:.react-pdf__Page__canvas')
|
||||
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
|
||||
except Exception:
|
||||
sig = None
|
||||
if sig and sig[0] > 0:
|
||||
if sig == last:
|
||||
if stable_since and time.time() - stable_since >= 2:
|
||||
return True
|
||||
else:
|
||||
stable_since = time.time()
|
||||
last = sig
|
||||
time.sleep(1)
|
||||
print(" 警告:等待 PDF 渲染超时,继续尝试提交")
|
||||
return False
|
||||
|
||||
|
||||
def _goto_submit_page(tab, tries=3):
|
||||
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
|
||||
for i in range(tries):
|
||||
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline:
|
||||
if tab.ele('tag:button@@text()=提 交', timeout=1):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
print(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _click_submit(tab, tries=3):
|
||||
"""点「提 交」,验证「已知晓」确认弹窗出现;第一次可能因按钮未就绪失效,重试。
|
||||
期间打印页面 toast 提示,便于诊断失败原因。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
deadline = time.time() + 10
|
||||
while time.time() < deadline:
|
||||
if tab.ele('tag:button@@text()=已知晓', timeout=1):
|
||||
return True
|
||||
try:
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
print(f" 提交提示:{t[:100]}")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
print(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _confirm_submit(tab, tries=3):
|
||||
"""点「已知晓」→ 等「您已成功提交」弹窗;未出现则重点已知晓。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=已知晓', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
if _wait_modal(tab, '您已成功提交', timeout=60):
|
||||
return True
|
||||
print(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
|
||||
return False
|
||||
|
||||
|
||||
def _predeclare_and_submit(page, tab):
|
||||
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交(带重试)→ 已知晓 → 等成功。"""
|
||||
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
|
||||
if _wait_modal(tab, '预申报成功', timeout=60) is None:
|
||||
raise RuntimeError("预申报后未出现成功弹窗")
|
||||
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
|
||||
# 等申报页就绪:提示弹窗或「全部提交」按钮任一出现即继续(替代固定 sleep,省 ~8s 空等)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
|
||||
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
|
||||
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
_dismiss_popups(tab) # 系统提示「我已知晓」+ 操作说明「我知道了」
|
||||
_shot(tab, "06_declare_page")
|
||||
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
|
||||
_wait_pdf_ready(tab)
|
||||
_shot(tab, "07_pdf_ready")
|
||||
if not _goto_submit_page(tab):
|
||||
_shot(tab, "08_no_submit_btn")
|
||||
raise RuntimeError("点击下一步后未出现「提 交」按钮")
|
||||
_shot(tab, "08_submit_page")
|
||||
if not _click_submit(tab):
|
||||
_shot(tab, "09_submit_no_confirm")
|
||||
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
|
||||
if not _confirm_submit(tab):
|
||||
_shot(tab, "10_confirm_no_success")
|
||||
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
|
||||
_shot(tab, "11_submit_success")
|
||||
print(" 提交成功")
|
||||
|
||||
|
||||
def _collect_review_rows(tab):
|
||||
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
|
||||
results = {}
|
||||
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
|
||||
try:
|
||||
tds = [td.text.strip() for td in tr.eles('tag:td')]
|
||||
except Exception:
|
||||
continue
|
||||
# 明细表结构:业务流水号/业务类型/姓名/证件号码/审核结论/审核意见/操作
|
||||
# 证件号码可能是 15/18 位,尾号可为 X,不能只 isdigit
|
||||
cid = tds[3] if len(tds) > 3 else ''
|
||||
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
|
||||
results[cid] = (tds[4], tds[0])
|
||||
return results
|
||||
|
||||
|
||||
def _open_query_page(page, tab, timeout=25):
|
||||
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
|
||||
for tid in tids:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
|
||||
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
|
||||
_shot(t, "12_query_list")
|
||||
return t
|
||||
except Exception:
|
||||
continue
|
||||
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
|
||||
|
||||
|
||||
def _query_review_results(page, tab):
|
||||
"""进入申报查询列表 → 打开序号1记录的「查看」→ 读明细表审核结论。
|
||||
返回 {证件号码: (审核结论, 业务流水号)}。"""
|
||||
qtab = _open_query_page(page, tab)
|
||||
for attempt in range(3):
|
||||
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
|
||||
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
|
||||
if view:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
pass
|
||||
# 等明细表出现(含 18 位证件号码的行)
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
results = _collect_review_rows(qtab)
|
||||
if results:
|
||||
_shot(qtab, "13_review_detail")
|
||||
return results
|
||||
print(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
|
||||
_shot(qtab, "13_review_detail_miss")
|
||||
time.sleep(1.5)
|
||||
raise RuntimeError("未读取到审核结论明细表")
|
||||
|
||||
|
||||
# ==================== 6b. 台账回写(JSON 缓存防崩溃,运行结束统一回写 Excel 一次) ====================
|
||||
# 每个账号办完:回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel);
|
||||
# 运行结束时 flush_writeback 统一写 Excel 一次,保存成功校验后删除缓存;
|
||||
# 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单。
|
||||
_PENDING_STATUS, _PENDING_REMARK = {}, {}
|
||||
_CKPT_FILE = _HERE / "writeback_pending.json"
|
||||
|
||||
|
||||
def _save_ckpt():
|
||||
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
|
||||
import json
|
||||
data = [{"id": cid, "status": _PENDING_STATUS.get(cid, ""),
|
||||
"remark": _PENDING_REMARK.get(cid, "")}
|
||||
for cid in dict.fromkeys(list(_PENDING_STATUS) + list(_PENDING_REMARK))]
|
||||
tmp = _CKPT_FILE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(_CKPT_FILE)
|
||||
|
||||
|
||||
def _load_ckpt():
|
||||
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
|
||||
recovered = set()
|
||||
if not _CKPT_FILE.exists():
|
||||
return recovered
|
||||
try:
|
||||
import json
|
||||
for it in json.loads(_CKPT_FILE.read_text(encoding="utf-8")):
|
||||
cid = it.get("id")
|
||||
if it.get("status"):
|
||||
_PENDING_STATUS[cid] = it["status"]
|
||||
if it.get("remark"):
|
||||
_PENDING_REMARK[cid] = it["remark"]
|
||||
if cid:
|
||||
recovered.add(cid)
|
||||
return recovered
|
||||
except Exception as e:
|
||||
print(f" 恢复回写缓存失败:{e}")
|
||||
return recovered
|
||||
|
||||
|
||||
def writeback_source(status_map, remark_map):
|
||||
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel):
|
||||
status_map {身份证: 办理状态};remark_map {身份证: 备注}。"""
|
||||
_PENDING_STATUS.update(status_map or {})
|
||||
_PENDING_REMARK.update(remark_map or {})
|
||||
try:
|
||||
_save_ckpt()
|
||||
except Exception as e:
|
||||
print(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
|
||||
|
||||
|
||||
def flush_writeback():
|
||||
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
|
||||
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
|
||||
if not (_PENDING_STATUS or _PENDING_REMARK):
|
||||
return
|
||||
if not SOURCE_FILE_USED:
|
||||
raise RuntimeError("无源名单文件记录,无法回写")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(SOURCE_FILE_USED)
|
||||
ws = wb[SOURCE_SHEET_USED]
|
||||
# 表头第3行定位列号
|
||||
hdr = {}
|
||||
for c in ws[3]:
|
||||
if c.value is not None:
|
||||
hdr[str(c.value).strip()] = c.column
|
||||
col_id = hdr.get('身份证号码')
|
||||
col_status = hdr.get('办理状态')
|
||||
col_remark = hdr.get('备注')
|
||||
if not col_id or not col_status:
|
||||
raise RuntimeError(f"源名单缺少身份证号码/办理状态列,无法回写")
|
||||
changed = 0
|
||||
pending_ids = set(_PENDING_STATUS) | set(_PENDING_REMARK)
|
||||
ref = [_norm_id(x) for x in pending_ids]
|
||||
for row in ws.iter_rows(min_row=4):
|
||||
cid = _norm_id(row[col_id - 1].value)
|
||||
if cid and _id_hit(cid, ref):
|
||||
r = row[0].row
|
||||
if cid in _PENDING_STATUS:
|
||||
ws.cell(row=r, column=col_status, value=_PENDING_STATUS[cid])
|
||||
if cid in _PENDING_REMARK and col_remark:
|
||||
# 备注追加不覆盖:读取原单元格内容,新备注换行追加在后面(已存在则不重复追加)
|
||||
cell = ws.cell(row=r, column=col_remark)
|
||||
old = str(cell.value or '').strip()
|
||||
new = str(_PENDING_REMARK[cid]).strip()
|
||||
if new in old:
|
||||
pass # 重查场景:备注已写过,跳过防重复
|
||||
else:
|
||||
cell.value = f"{old}\n{new}" if old else new
|
||||
changed += 1
|
||||
try:
|
||||
wb.save(SOURCE_FILE_USED)
|
||||
except PermissionError:
|
||||
# 缓存保留,下次启动自动恢复回写
|
||||
raise RuntimeError("源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
|
||||
_PENDING_STATUS.clear()
|
||||
_PENDING_REMARK.clear()
|
||||
if _CKPT_FILE.exists():
|
||||
_CKPT_FILE.unlink()
|
||||
print(f" 源名单回写完成:更新 {changed} 行 → {os.path.basename(SOURCE_FILE_USED)}(缓存已清除)")
|
||||
print(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
|
||||
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
|
||||
|
||||
|
||||
# ==================== 6c. 单个单位完整网页操作 ====================
|
||||
def do_web_import(task):
|
||||
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。
|
||||
返回结果 dict(JSON 安全)。"""
|
||||
import sb_login
|
||||
page = sb_login.LAST_SESSION.get('page')
|
||||
work_tab = sb_login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "imported": 0, "failed": [], "review": {}}
|
||||
try:
|
||||
_shot(work_tab, "01_workbench")
|
||||
biz_tab = _open_business_page(page, work_tab)
|
||||
_shot(biz_tab, "02_biz_upload_page")
|
||||
|
||||
# 1) 上传导入
|
||||
total, _failed_cnt = _upload_import(biz_tab, task['file'])
|
||||
res['imported'] = total
|
||||
|
||||
# 2) 校验未通过:回写 参保失败 + 备注(详细信息)
|
||||
# 账目规则:弹窗「成功N人」+「校验未通过人员」= 名单人数,不平账中止防止漏人导致下次重复申报
|
||||
fail_rows = _read_failed_rows(biz_tab)
|
||||
res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows]
|
||||
expected = task.get('count', 0)
|
||||
if expected and total + len(fail_rows) != expected:
|
||||
raise RuntimeError(
|
||||
f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人,"
|
||||
f"中止该单位(防漏人/重复申报),请人工核对")
|
||||
if fail_rows:
|
||||
writeback_source({cid: "参保失败" for cid, _ in fail_rows},
|
||||
{cid: d for cid, d in fail_rows})
|
||||
passed = total
|
||||
|
||||
# 3) 全员未通过 → 跳过申报
|
||||
if passed <= 0:
|
||||
print(" 校验通过人数为 0,跳过申报")
|
||||
res.update(success=True, message=f"导入{total}人,全部校验未通过,已回写未申报")
|
||||
return res
|
||||
|
||||
# 4) 预申报 → 正式提交 → 查询审核结论回写
|
||||
_predeclare_and_submit(page, biz_tab)
|
||||
review = _query_review_results(page, biz_tab)
|
||||
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
|
||||
for cid, (c, sn) in review.items()]
|
||||
if review:
|
||||
writeback_source({cid: concl for cid, (concl, _) in review.items()}, {})
|
||||
res.update(success=True,
|
||||
message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"网页操作异常:{e}"
|
||||
return res
|
||||
|
||||
|
||||
# ==================== 7. 逐单位登录 + 网页操作 ====================
|
||||
def process_units(tasks):
|
||||
"""逐参保单位:登录政务平台 → 完整网页导入申报 → 回写。
|
||||
每个账号办完(无论成败)都清 cookies 关浏览器,下个账号全新开始。
|
||||
回写策略:单位内累积到内存并写 JSON 缓存(防崩溃),运行结束统一回写 Excel 一次。"""
|
||||
import sb_login
|
||||
results = []
|
||||
for i, task in enumerate(tasks, 1):
|
||||
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人)==========")
|
||||
print(f"导入文件:{task['file']}")
|
||||
try:
|
||||
login_res = sb_login.main({"username": task["username"], "password": task["password"]})
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
print(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_web_import(task)
|
||||
print(f"办理结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False,
|
||||
"message": login_res.get("message", "")})
|
||||
finally:
|
||||
# 账号隔离:清 cookies + 关浏览器,再进入下一单位
|
||||
sb_login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 8. 主流程 ====================
|
||||
def run():
|
||||
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录(+导入)→ 统一回写。
|
||||
返回 JSON 安全 dict。"""
|
||||
recovered_ids = _load_ckpt()
|
||||
units = load_units(exclude_ids=recovered_ids)
|
||||
# 崩溃恢复:上次运行残留的回写缓存统一落盘(排除逻辑已在 load_units 中生效,
|
||||
# 即使下面回写失败,这些人也不会被当成待办重复申报)
|
||||
if recovered_ids:
|
||||
print("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
flush_writeback()
|
||||
except Exception as e:
|
||||
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not units:
|
||||
return {"success": True, "message": "无待办数据", "total": 0, "done": 0}
|
||||
|
||||
accounts = load_accounts([u for u, _ in units])
|
||||
tasks = precheck(units, accounts)
|
||||
if tasks is None:
|
||||
return {"success": False, "message": "预检未通过,详见日志", "total": len(units), "done": 0}
|
||||
|
||||
if not DO_LOGIN:
|
||||
print("DO_LOGIN=False,仅完成预检,跳过登录")
|
||||
return {"success": True, "message": "预检通过(未登录)", "total": len(tasks), "done": 0}
|
||||
|
||||
results = process_units(tasks[:RUN_LIMIT])
|
||||
# 运行结束:本次累积的回写内容统一写 Excel 一次(失败则 JSON 缓存保留,下次启动恢复)
|
||||
try:
|
||||
flush_writeback()
|
||||
except Exception as e:
|
||||
print(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
print(f"\n========== 汇总 ==========")
|
||||
print(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
print(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
|
||||
"total": len(results), "done": len(ok)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(run())
|
||||
@@ -0,0 +1,597 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: sb_login.py
|
||||
@Description: 重庆人社网上服务大厅(政务平台)法人登录模块 —— XQ0014 专用(不共享)。
|
||||
每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务。
|
||||
不做 cookies 缓存:政务平台 cookies 极易失效,缓存无意义;账号多,各自缓存也冗余,
|
||||
统一每次现场真登录(浏览器走完整 SSO 流程 + ddddocr 识别图形验证码)。
|
||||
|
||||
登录流程(与 aa.md 步骤一致):
|
||||
1. 打开办事大厅页面 → 等待登录入口出现;
|
||||
2. 点击「登录」→ 跳转新 tab 到 SSO(authcq.cqdcg.com:1443/sso/login);
|
||||
3. 切换「法人用户」tab;
|
||||
4. 输入账号(统一社会信用代码或政务平台用户名)+ 密码;
|
||||
5. 元素截图截取图形验证码(base64 内嵌 PNG)→ ddddocr 识别 → 输入验证码;
|
||||
6. 点击「登 录」→ 等待跳回办事大厅域名即成功;
|
||||
7. 识别失败自动刷新验证码重试(验证码 5 次/轮 × 流程 3 轮)。
|
||||
|
||||
配置(可选,仅作为 main() 未传账号时的默认值):
|
||||
sb_login_username=默认账号;sb_login_password=默认密码
|
||||
sb_captcha_debug_dir=(可选)验证码调试图片输出目录;不设置则不落盘
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv ddddocr
|
||||
|
||||
入口:
|
||||
main(args) 影刀指令/流程调用入口,args 传 {"username": 账号, "password": 密码},
|
||||
返回 JSON 安全 dict {success, username, message}
|
||||
python sb_login.py 独立运行(用 .env 默认账号做登录自测)
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import random
|
||||
import base64
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 默认账号只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文;
|
||||
# XQ0014 主流程会按参保单位从台账取号后通过 main(args) 传入,这里仅作独立运行兜底。
|
||||
if os.path.exists(os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.env')):
|
||||
load_dotenv(os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.env'))
|
||||
load_dotenv()
|
||||
|
||||
APPLY_URL = 'https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/arrondi/ApplyOnline'
|
||||
SSO_KEYWORD = 'authcq.cqdcg.com:1443/sso/login'
|
||||
HOME_KEYWORD = 'ggfw.rlsbj.cq.gov.cn'
|
||||
WORK_KEYWORD = 'onlineoffice/index' # 登录成功后新开的工作台 tab
|
||||
|
||||
# 验证码调试图片:默认落盘到本目录 debug_captcha\(排查识别率用),可用 sb_captcha_debug_dir 覆盖
|
||||
# 落盘开关:环境变量 sb_captcha_debug(1/0),默认关闭;由 import_add 的 DEBUG_MODE 统一控制
|
||||
CAPTCHA_DEBUG_DIR = os.getenv('sb_captcha_debug_dir', '').strip() or os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), 'debug_captcha')
|
||||
CAPTCHA_DEBUG = os.getenv('sb_captcha_debug', '0').strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
|
||||
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
|
||||
FLOW_RETRY = 3 # 整个登录流程最大轮数
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
HEADLESS = False
|
||||
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== 验证码识别(元素截图 + ddddocr) ==================
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景的导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _dump_debug_captcha(img_bytes, text):
|
||||
"""可选:落盘验证码调试图片(仅 CAPTCHA_DEBUG 开启时),便于分析识别失败样本。"""
|
||||
if not CAPTCHA_DEBUG or not CAPTCHA_DEBUG_DIR:
|
||||
return
|
||||
try:
|
||||
ensure_dir(CAPTCHA_DEBUG_DIR)
|
||||
path = os.path.join(CAPTCHA_DEBUG_DIR, f"captcha_{int(time.time() * 1000)}_{text or 'unknown'}.png")
|
||||
with open(path, 'wb') as f:
|
||||
f.write(img_bytes)
|
||||
except Exception as e:
|
||||
print(f"保存调试图片失败:{e}")
|
||||
|
||||
|
||||
def _find_input(tab, selectors):
|
||||
"""按候选选择器顺序查找输入框。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(tab):
|
||||
"""定位验证码图片 + 输入框。
|
||||
|
||||
从验证码输入框的容器往上找(DOM 结构:div.normalCode > span包input + img.code),
|
||||
避免命中页面其它 base64 图标(用户实测:img[src^=data:image] 会抓到 icon)。
|
||||
"""
|
||||
code_input = tab.ele('css:input[placeholder*="图形验证码"]', timeout=TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(2) # div.normalCode 容器
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
# 兜底:激活面板内第一个 base64 图
|
||||
img = tab.ele('css:.ant-tabs-tabpane-active img[src^="data:image"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""验证码图转 bytes:优先直接解码 base64 src(像素无损、无 DPR 缩放),失败退回元素截图。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _dismiss_notice(page):
|
||||
"""关闭首页/工作台弹窗(「温馨提示」我知道了、授权提示同意等),避免遮挡操作。"""
|
||||
candidates = [
|
||||
'tag:button@@text()=我知道了',
|
||||
'tag:button@@text()=知道了',
|
||||
'tag:button@@text()=同意',
|
||||
'tag:button@@text()=确定',
|
||||
]
|
||||
for _ in range(3):
|
||||
btn = None
|
||||
for sel in candidates:
|
||||
try:
|
||||
btn = page.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if not btn:
|
||||
return
|
||||
try:
|
||||
btn.click()
|
||||
print(f"已关闭弹窗(点击:{btn.text.strip()})")
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _sso_form_ready(t):
|
||||
"""判断某 tab 是否已是渲染完成的 SSO 登录页:URL 在 SSO 且「法人用户」tab 已出现。
|
||||
注意用 text()= 精确匹配——text(): 模糊匹配会命中包含该文字的外层容器 div(如 #user-sso-pc)。"""
|
||||
try:
|
||||
if SSO_KEYWORD not in t.url:
|
||||
return False
|
||||
return bool(t.ele('tag:div@@text()=法人用户', timeout=0.5))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_sso_ready(tab):
|
||||
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作。"""
|
||||
last_url = None
|
||||
for _ in range(60): # 最多等 30 秒
|
||||
try:
|
||||
url = tab.url
|
||||
except Exception:
|
||||
return False
|
||||
stable = (url == last_url)
|
||||
last_url = url
|
||||
if _sso_form_ready(tab) and stable:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
|
||||
return True
|
||||
|
||||
|
||||
def _is_work_tab(t):
|
||||
"""是否登录完成的工作台页(onlineoffice/index)。
|
||||
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页(zwykb 授权页、
|
||||
ggfw 回调页)的 redirectUrl 查询参数里也含 ggfw/onlinehall 字样,用包含匹配会误判。"""
|
||||
try:
|
||||
u = (t.url or '').strip()
|
||||
except Exception:
|
||||
return False
|
||||
return u.startswith('https://' + HOME_KEYWORD) and WORK_KEYWORD in u
|
||||
|
||||
|
||||
def _open_sso_tab(page):
|
||||
"""点击首页「登录」,等待新 tab 打开、跳转链结束且登录表单渲染完成后返回。
|
||||
返回 (tab, already_logged):
|
||||
already_logged=False → SSO 登录页(需填表)
|
||||
already_logged=True → SSO 会话有效直接跳回大厅(登录成功,无需填表)"""
|
||||
_dismiss_notice(page)
|
||||
# 登录入口:loginBox 内的第一个 <a>(「登录」,无 href)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
login_link = page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
# 可能残留上一账号登录态(首页已免登录):清除 cookies 后刷新重试一次
|
||||
print("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试")
|
||||
try:
|
||||
page.clear_cache(cookies=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.run_js("document.cookie.split(';').forEach(c=>{"
|
||||
"document.cookie=c.trim().split('=')[0]+"
|
||||
"'=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'});")
|
||||
except Exception:
|
||||
pass
|
||||
page.get(APPLY_URL)
|
||||
time.sleep(2)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT) \
|
||||
or page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
# 首页已是登录态(无登录入口):提示需清登录态,由调用方处理
|
||||
print("找不到登录入口(首页可能已是登录态)")
|
||||
return None, False
|
||||
before_ids = set(page.tab_ids)
|
||||
login_link.click()
|
||||
# 点击「登录」后是中转跳转链:轮询所有新开 tab,直到某个 tab 的 URL 稳定停在
|
||||
# SSO 且「法人用户」登录表单真实渲染出来(避免拿到闪现中的中转页就操作);
|
||||
# 若 SSO 会话仍有效(同账号二次登录),新 tab 会直接跳回大厅页 → 视为已登录
|
||||
tab = None
|
||||
for _ in range(90): # 最多等 45 秒
|
||||
time.sleep(0.5)
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
print(f"SSO 会话有效,已直接登录:{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t)
|
||||
return t, True
|
||||
if _sso_form_ready(t):
|
||||
tab = t
|
||||
break
|
||||
if tab:
|
||||
break
|
||||
if tab is None:
|
||||
# 部分场景可能不新开 tab 而是当前页跳转
|
||||
if _sso_form_ready(page):
|
||||
return page, False
|
||||
print("点击登录后未检测到就绪的 SSO 登录页")
|
||||
return None, False
|
||||
_close_extra_tabs(page, before_ids, tab)
|
||||
return tab, False
|
||||
|
||||
|
||||
def _close_extra_tabs(page, before_ids, keep_tab):
|
||||
"""关掉一次「点登录」产生的多余新开 tab(中转页等),保持会话干净。"""
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids and i != keep_tab.tab_id]:
|
||||
try:
|
||||
page.get_tab(tid).close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _wait_sso_ready(tab):
|
||||
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作,
|
||||
避免跳转/React 重渲染过程中拿到元素随即失效(元素对象已失效)。"""
|
||||
last_url = None
|
||||
for _ in range(60): # 最多等 30 秒
|
||||
try:
|
||||
url = tab.url
|
||||
except Exception:
|
||||
return False
|
||||
stable = (url == last_url)
|
||||
last_url = url
|
||||
if _sso_form_ready(tab) and stable:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(tab, page, username, password, retry_index):
|
||||
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。
|
||||
所有动作间加随机延时,模拟人工节奏,降低脚本特征。"""
|
||||
_wait_sso_ready(tab)
|
||||
# 法人用户 tab:精确文本匹配(text(): 模糊会命中包含文字的外层容器,如 #user-sso-pc)
|
||||
legal_tab = tab.ele('tag:div@@text()=法人用户', timeout=TIMEOUT)
|
||||
if legal_tab:
|
||||
legal_tab.click()
|
||||
_human_pause(0.3, 0.8)
|
||||
# 校验确实切到法人用户面板(没点上会把账号填进个人用户表单)
|
||||
for _ in range(3):
|
||||
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=2)
|
||||
if active and active.text.strip() == '法人用户':
|
||||
break
|
||||
if legal_tab:
|
||||
try:
|
||||
legal_tab.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
# 账号(统一社会信用代码)+ 密码
|
||||
# SSO 法人用户表单真实结构(2026-09 探针实测):
|
||||
# 账号框 id=identifier placeholder「请输入统一社会信用代码」
|
||||
user_input = _find_input(tab, [
|
||||
'css:input[placeholder*="统一社会信用代码"]',
|
||||
'css:input[placeholder*="社会信用代码"]',
|
||||
'css:#identifier',
|
||||
])
|
||||
if not user_input:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(tab, ['css:#password', 'css:input[type="password"]'])
|
||||
if not pwd_input:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
|
||||
# 图形验证码:base64 内嵌图(从验证码输入框容器定位,避免抓到页面其它图标)
|
||||
for attempt in range(RETRY_MAX):
|
||||
print(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
|
||||
img, code_input = _find_captcha(tab)
|
||||
if not img or not code_input:
|
||||
print("找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
print("验证码图数据为空")
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
print(f"ddddocr 识别异常:{e}")
|
||||
return False
|
||||
print(f" 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(tab, img)
|
||||
continue
|
||||
code = code.upper() # 页面显示为大写,按大写提交
|
||||
_dump_debug_captcha(img_bytes, code)
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
# 提交:登录按钮(button[type=submit],文案「登 录」)
|
||||
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
|
||||
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
|
||||
if not btn:
|
||||
print("找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6) # 点提交前再停顿一下
|
||||
btn.click()
|
||||
|
||||
# 等待结果:SSO tab 跳回大厅 / 新开 onlineoffice 工作台 tab = 成功;错误提示 = 刷新重试
|
||||
ok, work_tab = _wait_login_result(tab, page)
|
||||
if ok:
|
||||
_try_login_once.work_tab = work_tab # 供 _do_login 保存会话
|
||||
return True
|
||||
_refresh_captcha(tab, img)
|
||||
return False
|
||||
|
||||
|
||||
def _wait_login_result(tab, page):
|
||||
"""提交后轮询判定登录结果。返回 (ok, work_tab)。"""
|
||||
before_ids = set(page.tab_ids)
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
# 成功标志 1:登录后新开的 onlineoffice 工作台 tab
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
print(f"登录成功(新开工作台 tab):{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t) # 工作台可能闪现授权/提示弹窗
|
||||
return True, t
|
||||
# 成功标志 2:SSO tab 自身跳到工作台页(origin 前缀匹配,防 redirectUrl 参数误判)
|
||||
try:
|
||||
url = (tab.url or '').strip()
|
||||
except Exception:
|
||||
url = ''
|
||||
if url.startswith('https://' + HOME_KEYWORD) and SSO_KEYWORD not in url and WORK_KEYWORD in url:
|
||||
print(f"登录成功,已跳转:{url}")
|
||||
_dismiss_notice(tab)
|
||||
return True, tab
|
||||
# ant-message 错误提示(验证码错误/账号密码错误等)
|
||||
try:
|
||||
err = tab.ele('css:.ant-message-error', timeout=0.5)
|
||||
if err:
|
||||
print(f"登录失败提示:{err.text}")
|
||||
return False, None
|
||||
except Exception:
|
||||
pass
|
||||
print("等待登录结果超时")
|
||||
return False, None
|
||||
|
||||
|
||||
def _refresh_captcha(tab, img):
|
||||
"""点击验证码图片刷新,校验 base64 src 是否真的变化(连续点 2 次)。"""
|
||||
try:
|
||||
old = img.attr('src') or ''
|
||||
except Exception:
|
||||
old = ''
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
# 刷新是异步的:轮询 src 变化(最多 3 秒)
|
||||
for _p in range(10):
|
||||
time.sleep(0.3)
|
||||
try:
|
||||
new = img.attr('src') or ''
|
||||
except Exception:
|
||||
new = old
|
||||
if new and new != old:
|
||||
return True
|
||||
# src 还没变,再点一次
|
||||
print("警告:验证码图片刷新后未变化")
|
||||
return False
|
||||
|
||||
|
||||
LAST_SESSION = {'page': None, 'tab': None} # 登录成功后保留的浏览器会话(供后续网页操作使用)
|
||||
|
||||
|
||||
def _teardown(page):
|
||||
"""清 cookies/本地存储后关浏览器(账号切换彻底隔离,避免残留登录态)。"""
|
||||
if page is None:
|
||||
return
|
||||
try:
|
||||
page.clear_cache(cookies=True, local_storage=True, session_storage=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.clear_cache()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def close_session():
|
||||
"""清 cookies 并关闭当前保留的登录会话(每个账号业务办完后必须调用)。"""
|
||||
_teardown(LAST_SESSION['page'])
|
||||
LAST_SESSION['page'] = None
|
||||
LAST_SESSION['tab'] = None
|
||||
|
||||
|
||||
def _do_login(username, password):
|
||||
"""打开浏览器现场完成登录(含图形验证码)。不做任何 cookies 缓存。
|
||||
成功保留浏览器会话(工作台 tab 供后续导入操作),失败关闭浏览器。
|
||||
返回 (ok, work_tab)。"""
|
||||
# 账号切换隔离:先关掉上一账号的浏览器会话(auto_port 临时目录本就不互通,双保险)
|
||||
close_session()
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
# auto_port:每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
|
||||
co.auto_port(True)
|
||||
co.set_argument('--start-maximized') # 浏览器启动即全屏(最大化),避免小窗口下元素被折叠/遮挡
|
||||
page = ChromiumPage(co)
|
||||
work_tab_holder = {'tab': None}
|
||||
|
||||
def _finish(ok):
|
||||
if ok:
|
||||
LAST_SESSION['page'] = page
|
||||
LAST_SESSION['tab'] = work_tab_holder['tab']
|
||||
return True, work_tab_holder['tab']
|
||||
_teardown(page)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
page.get(APPLY_URL)
|
||||
_human_pause(1.0, 2.5)
|
||||
|
||||
tab = None
|
||||
for retry in range(FLOW_RETRY):
|
||||
try:
|
||||
_dismiss_notice(page)
|
||||
# 登录 tab 跨轮次复用:只在丢失/失效时才重新点「登录」,
|
||||
# 避免每轮重开浏览器 tab 越积越多(手动只点一次,代码不能反复点)
|
||||
if tab is not None:
|
||||
try:
|
||||
if SSO_KEYWORD not in tab.url:
|
||||
tab = None # 已跳走(登录成功或会话变化),需重新进入
|
||||
except Exception:
|
||||
tab = None # tab 已关闭/失效
|
||||
if tab is None:
|
||||
tab, already = _open_sso_tab(page)
|
||||
if tab is None:
|
||||
print(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)")
|
||||
time.sleep(2)
|
||||
continue
|
||||
if already:
|
||||
# 同账号 SSO 会话仍有效:免验证码直接登录成功
|
||||
work_tab_holder['tab'] = tab
|
||||
return _finish(True)
|
||||
if _try_login_once(tab, page, username, password, retry + 1):
|
||||
work_tab_holder['tab'] = getattr(_try_login_once, 'work_tab', None) or tab
|
||||
return _finish(True)
|
||||
# 登录失败:复用同一 tab 刷新重来,不再重复点「登录」
|
||||
try:
|
||||
tab.refresh()
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 元素失效/页面刷新等异常:不中断整体流程,进入下一轮
|
||||
print(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}")
|
||||
time.sleep(1)
|
||||
print("登录失败(验证码识别未通过或流程异常)")
|
||||
return _finish(False)
|
||||
except Exception:
|
||||
# 整体异常也要保证清理(失败场景不留会话)
|
||||
_teardown(page)
|
||||
raise
|
||||
|
||||
|
||||
def ensure_login(username=None, password=None):
|
||||
"""
|
||||
以指定账号现场登录政务平台(无缓存,每次真登录)。
|
||||
返回 JSON 安全 dict:{success, username, message}
|
||||
"""
|
||||
_set_login_state(False)
|
||||
|
||||
# 未传账号时回落到 .env 默认账号(独立运行自测场景)
|
||||
username = (username or os.getenv('sb_login_username', '') or '').strip()
|
||||
password = (password or os.getenv('sb_login_password', '') or '').strip()
|
||||
if not (username and password):
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录账号/密码缺失(main 未传参且 .env 未配置 sb_login_username / sb_login_password)"}
|
||||
|
||||
ok, _work_tab = _do_login(username, password)
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "username": username, "message": "登录成功"}
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录失败(验证码识别未通过或流程异常)"}
|
||||
|
||||
|
||||
# ================== 调用入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀指令/流程调用入口。
|
||||
args: dict,{"username": 账号(必填,统一社会信用代码或政务平台用户名),
|
||||
"password": 密码(必填)}
|
||||
返回: dict {success, username, message}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
try:
|
||||
return ensure_login(args.get("username"), args.get("password"))
|
||||
except Exception as e:
|
||||
_set_login_state(False)
|
||||
return {"success": False, "username": args.get("username", ''),
|
||||
"message": f"登录过程异常:{e}"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({})
|
||||
print("最终结果:", result)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
# XQ0016 社保转移告知书制作与下发 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0016 社保转移告知书制作与下发/`
|
||||
- 状态:**已由 XQ0015 覆盖实现,本目录为归档占位**
|
||||
|
||||
## 说明
|
||||
- 实现脚本:`XQ0015/notice_mail_merge.py`
|
||||
- 该脚本一次处理「参保 / 参保异常 / 社保转移」三类告知书模板,社保转移告知书由同一模块生成,**本目录无需再放代码**。
|
||||
|
||||
## 如需独立拆出
|
||||
将本类告知书的生成逻辑单独拆为 `XQ0016/<业务名>.py`,并移除 `XQ0015/notice_mail_merge.py` 中对社保转移的处理分支。
|
||||
@@ -0,0 +1,9 @@
|
||||
# XQ0017 入职人事手续办理 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0017 入职人事手续办理/`
|
||||
- 状态:**取消(不再实现)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
@@ -0,0 +1,13 @@
|
||||
# XQ0018 调动人事手续跟进 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0018 调动人事手续跟进/`
|
||||
- 状态:**取消(不再实现)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
|
||||
## 参考
|
||||
- 调动台账导出可参考 `XQ0001/transfer_roster_export.py`
|
||||
- 店长/人事查询可参考 `app/service/hrbp/ehr/roster/roster_query.py`
|
||||
@@ -0,0 +1,12 @@
|
||||
# XQ0019 离职人事手续跟进与检查 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0019 离职人事手续跟进与检查/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
|
||||
## 参考
|
||||
- 离职电子签审核见 `XQ0020/resign_e_sign_approval.py`
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,964 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: material_summary_export.py
|
||||
@Description: 需求31 - 金蝶 K3Cloud ERP「物料收发汇总表」自动导出。
|
||||
搜索打开报表 → 设置组织/日期/仓库编码 → 查询 → 引出所有页 → 下载保存。
|
||||
|
||||
调用关系:复用 share/erp_login.py 登录 ERP(新旧系统通用)。
|
||||
运行方式:直接运行本文件(参数全部在代码内定义,无需命令行传参)。
|
||||
|
||||
业务配置说明(改下面配置块即可):
|
||||
ERP 'new' 新版 / 'old' 旧版 / 完整登录页 URL
|
||||
登录账号密码 统一放项目根目录 .env(erp_login_username / erp_login_password),
|
||||
erp_login 自动读取,代码中不存明文
|
||||
ORG_NAME 查询组织(确保过滤界面组织为该值,否则自动重新选择)
|
||||
STOCK_CODES 仓库编码列表,每个占一行过滤条件(或关系),可单选可多选
|
||||
DATE_OPTIONS 日期选项列表(多选,逐个导出),每项支持:
|
||||
'60D'/'30D'/'15D'/'7D'/'3D' 今天往前推 N 天
|
||||
'2026-01-01~2026-09-15' 字符串自定义起止(~ , ,空格分隔均可)
|
||||
('2026-01-01', '2026-09-15') 元组自定义起止
|
||||
SAVE_DIR 保存目录,None 时自动创建:桌面/采购计划报表_YYYY-MM-DD
|
||||
FOLDER_NAME 文件夹命名(采购计划报表+日期)
|
||||
FILE_PREFIX 导出文件命名前缀(物料收发汇总表_60D.xlsx)
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import shutil
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from DrissionPage.common import Keys
|
||||
|
||||
try: # 浏览器断连等致命异常需上抛,避免被通用容错吞掉空转
|
||||
from DrissionPage.errors import PageDisconnectedError
|
||||
except Exception:
|
||||
PageDisconnectedError = None
|
||||
|
||||
# ================== 业务配置(直接在此修改) ==================
|
||||
ERP = 'new' # 新版 criterion.erp.37du.co
|
||||
# 登录账号密码统一放根目录 .env:erp_login_username / erp_login_password
|
||||
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织
|
||||
STOCK_CODES = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201'] # 仓库编码(可多选,或关系)
|
||||
DATE_OPTIONS = ['60D', '30D', '15D', '7D', '3D'] # 多选逐个导出;可混入自定义 '2026-01-01~2026-09-15' 或 ('开始','结束')
|
||||
SAVE_DIR = None # None → 桌面/采购计划报表_日期
|
||||
FOLDER_NAME = '采购计划报表' # 文件夹命名前缀
|
||||
FILE_PREFIX = '物料收发汇总表' # 导出文件命名前缀
|
||||
|
||||
# ================== 运行参数 ==================
|
||||
RETRY_MAX = 3 # 每个日期选项最大重试次数(项目规范)
|
||||
TIMEOUT = 15 # 元素查找超时(秒)
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'share'))
|
||||
from erp_login import erp_login # noqa: E402
|
||||
|
||||
|
||||
# ================== 工具函数 ==================
|
||||
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=TIMEOUT, by_js=False):
|
||||
"""点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。
|
||||
by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。"""
|
||||
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:
|
||||
el.input(Keys.ENTER)
|
||||
except Exception:
|
||||
_press_enter(page)
|
||||
|
||||
|
||||
def _resolve_dates(option):
|
||||
"""解析单个日期选项 → (开始日期, 结束日期, 文件标签)。
|
||||
支持:
|
||||
'60D' 今天往前推 N 天(60/30/15/7/3)
|
||||
('2026-01-01', '2026-09-15') 元组/列表自定义起止
|
||||
'2026-01-01~2026-09-15' 字符串自定义起止(~ , ,空格分隔均可)
|
||||
DATE_OPTIONS 传列表即可多选,逐个导出。"""
|
||||
if isinstance(option, (list, tuple)):
|
||||
if len(option) == 2:
|
||||
begin, end = str(option[0]), str(option[1])
|
||||
return begin, end, f'{begin}_{end}'
|
||||
raise ValueError(f'自定义日期需为(开始, 结束)两项: {option!r}')
|
||||
s = str(option).strip()
|
||||
for sep in ('~', ',', ',', ' '):
|
||||
if sep in s:
|
||||
parts = [p.strip() for p in s.split(sep) if p.strip()]
|
||||
if len(parts) == 2:
|
||||
return parts[0], parts[1], f'{parts[0]}_{parts[1]}'
|
||||
raise ValueError(f'自定义日期需为 开始~结束 两项: {option!r}')
|
||||
days = int(s.rstrip('Dd'))
|
||||
end = datetime.now().date()
|
||||
begin = end - timedelta(days=days)
|
||||
return begin.isoformat(), end.isoformat(), str(option)
|
||||
|
||||
|
||||
def _wait_window_title(page, keyword, timeout=TIMEOUT):
|
||||
"""等待出现标题包含关键字的窗口,返回 True/False。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
t = page.ele('css:.k-window-title', timeout=1)
|
||||
if t and keyword in t.text:
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 报表操作 ==================
|
||||
def _open_report(page):
|
||||
"""点击全局搜索 → 输入「物料收发汇总表」→ 回车 → 等待过滤界面出现。"""
|
||||
if not _click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
print('[物料收发汇总表] 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
print('[物料收发汇总表] 找不到搜索输入框')
|
||||
return False
|
||||
sbox.clear()
|
||||
sbox.input('物料收发汇总表')
|
||||
time.sleep(0.3)
|
||||
_press_enter(page)
|
||||
time.sleep(1.5)
|
||||
|
||||
# 等待过滤界面(含组织字段 FSTOCKORGID)出现,限定在 .k-window 弹窗内
|
||||
end = time.time() + 40
|
||||
while time.time() < end:
|
||||
if _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1):
|
||||
print('[物料收发汇总表] 报表过滤界面已打开')
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
# 兜底:点击搜索结果中的「物料收发汇总表」菜单项
|
||||
print('[物料收发汇总表] 未自动打开,尝试点击搜索结果')
|
||||
els = page.eles('xpath://*[contains(text(), "物料收发汇总表")]')
|
||||
for el in els:
|
||||
try:
|
||||
if el.states.is_displayed and not el.closest('css:.k-window-titlebar'):
|
||||
el.click()
|
||||
time.sleep(2)
|
||||
if _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1):
|
||||
print('[物料收发汇总表] 报表过滤界面已打开')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _close_window_by_title(page, title, timeout=3):
|
||||
"""物理点击关闭标题包含关键字的 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 _open_filter(page):
|
||||
"""确保过滤界面打开(按用户明确指令):
|
||||
1. 先关闭「文件下载」窗口(K3 下载完成后残留、挡在最上层)
|
||||
2. 若过滤窗口已开(.k-window 内组织字段可见)→ 直接复用
|
||||
3. 未开 → 点主报表「过滤」按钮重开
|
||||
其余残留窗口(仓库列表等)不主动关,已通过视口判断排除干扰。
|
||||
注意:过滤按钮真实 id 为 BILLMENU_TOOLBAR-tbnFilter(tbnFilter,非 tbFilter)。"""
|
||||
_close_window_by_title(page, '文件下载')
|
||||
if _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=2):
|
||||
return True
|
||||
# 点「过滤」重开(by_js 避免 K3 菜单物理点击选中文字)
|
||||
if _click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbnFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return _ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=5)
|
||||
return False
|
||||
|
||||
|
||||
def _set_org(page, org):
|
||||
"""确保过滤界面组织为指定值;不是则打开多选列表重新选择(只保留目标组织)。
|
||||
探针确认的结构:li.k-item > input.k-checkboxItem[name=组织名] + button.k-checkbox-button。"""
|
||||
# 统一限定在 .k-window 内,避免读到主界面残留的同 id 节点
|
||||
disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=TIMEOUT)
|
||||
if disp:
|
||||
title = disp.attr('title') or ''
|
||||
if title.strip() == org:
|
||||
print(f'[物料收发汇总表] 组织已是: {org}')
|
||||
return True
|
||||
|
||||
if not _click_visible(page, 'css:.k-window [id*="FSTOCKORGID-EDITOR"] .kd-editor-btn'):
|
||||
print('[物料收发汇总表] 找不到组织下拉按钮')
|
||||
return False
|
||||
time.sleep(1)
|
||||
# 组织多选列表弹层(_dataListdiv)独立挂载,不限定窗口;
|
||||
# 页面可能残留上次中断留下的隐藏弹层,必须取当前可见的那一个
|
||||
dl = None
|
||||
for cand in page.eles('css:[id*="FSTOCKORGID-EDITOR_dataListdiv"]', timeout=TIMEOUT):
|
||||
try:
|
||||
if cand.states.is_displayed:
|
||||
dl = cand
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl is None:
|
||||
print('[物料收发汇总表] 组织多选列表未出现')
|
||||
return False
|
||||
|
||||
# 输入关键字过滤列表(需回车才会过滤出结果)
|
||||
sbox = dl.ele('css:.kd-list-search-container input', timeout=5)
|
||||
if sbox:
|
||||
sbox.clear()
|
||||
sbox.input(org.split(' ', 1)[-1])
|
||||
_press_enter_in(sbox, page)
|
||||
time.sleep(1)
|
||||
|
||||
def _visible_lis():
|
||||
"""仅返回当前可见的选项行(过滤后隐藏行无位置尺寸,不可操作)。"""
|
||||
out = []
|
||||
for li in dl.eles('css:li.k-item'):
|
||||
try:
|
||||
if li.states.is_displayed:
|
||||
out.append(li)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
def _toggle(li, want):
|
||||
"""want=True 勾选 / False 取消勾选;实际发生点击返回 True。"""
|
||||
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
|
||||
btn = li.ele('css:button.k-checkbox-button', timeout=0.5)
|
||||
if not chk or not btn:
|
||||
return False
|
||||
name = chk.attr('name') or ''
|
||||
try:
|
||||
checked = bool(chk.run_js('return this.checked;'))
|
||||
except Exception:
|
||||
return False
|
||||
if want == checked:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 勾选目标项
|
||||
target_found = False
|
||||
for li in _visible_lis():
|
||||
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
|
||||
if chk and org in (chk.attr('name') or ''):
|
||||
target_found = True
|
||||
_toggle(li, True)
|
||||
|
||||
# 清空搜索恢复全量列表,取消其它已勾选项
|
||||
if sbox:
|
||||
sbox.clear()
|
||||
_press_enter_in(sbox, page)
|
||||
time.sleep(1)
|
||||
for li in _visible_lis():
|
||||
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
|
||||
if chk and org not in (chk.attr('name') or ''):
|
||||
_toggle(li, False)
|
||||
|
||||
if not target_found:
|
||||
print(f'[物料收发汇总表] 组织中未找到: {org}')
|
||||
return False
|
||||
|
||||
# 点弹层底部「确定」:只点一次。先弹层内找,找不到再全局找可见的兜底
|
||||
ok = _click_visible(dl, 'css:.kd-multiSelectOK')
|
||||
if not ok:
|
||||
ok = _click_visible(page, 'css:.kd-multiSelectOK')
|
||||
if not ok:
|
||||
print('[物料收发汇总表] 找不到组织多选确定按钮')
|
||||
return False
|
||||
time.sleep(1)
|
||||
# 回读确认设置生效,防止点了确定但值没落上(限定 .k-window 内)
|
||||
disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=TIMEOUT)
|
||||
if disp and (disp.attr('title') or '').strip() == org:
|
||||
print(f'[物料收发汇总表] 组织已设置为: {org}')
|
||||
return True
|
||||
print(f'[物料收发汇总表] 组织设置未生效,回读不一致: {org}')
|
||||
return False
|
||||
|
||||
|
||||
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 _set_datepicker(page, key, date):
|
||||
"""在 .k-window 过滤窗口内定位日期字段的 Kendo datepicker 并设值。
|
||||
key: 'FBEGINDATE' / 'FENDDATE'。
|
||||
K3 必须「触发日历组件」才会刷新绑定的过滤值(直接调控件 value() 无效):
|
||||
方式一 真实输入日期文本 + 回车提交(Kendo 解析输入并触发 change)
|
||||
方式二 打开日历面板 → 导航到目标月份 → 点选目标日期(触发 Kendo select,
|
||||
K3 绑定必然刷新)
|
||||
每次设值后回读 input 显示值验证;失败返回 False 由外层重试,绝不假成功。"""
|
||||
end = time.time() + TIMEOUT
|
||||
last = ''
|
||||
while time.time() < end:
|
||||
for el in page.eles(f'css:.k-window [id*="{key}-EDITOR_c"]', timeout=2):
|
||||
# 只处理真正持有 kendoDatePicker 控件的节点
|
||||
try:
|
||||
if not el.run_js(
|
||||
"return !!(window.jQuery && window.jQuery(this).data('kendoDatePicker'));"):
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# ---- 方式一:真实输入 + 回车 ----
|
||||
try:
|
||||
el.click()
|
||||
time.sleep(0.15)
|
||||
el.clear()
|
||||
el.input(date)
|
||||
time.sleep(0.2)
|
||||
_press_enter_in(el, page)
|
||||
time.sleep(0.3)
|
||||
val = el.run_js("return this.value || '';")
|
||||
if date in str(val):
|
||||
print(f'[物料收发汇总表] {key} 输入+回车生效(input显示 {val})')
|
||||
return True
|
||||
last = f'输入+回车 input={val!r}'
|
||||
except Exception as e:
|
||||
last = f'输入+回车异常: {e}'
|
||||
|
||||
# ---- 方式二:打开日历点选目标日期(触发组件刷新)----
|
||||
try:
|
||||
r = el.run_js("""
|
||||
var k = window.jQuery && window.jQuery(this).data('kendoDatePicker');
|
||||
if (!k) { return JSON.stringify({ok:false, why:'nok'}); }
|
||||
var y = +arguments[0], m = +arguments[1], d = +arguments[2];
|
||||
var dt = new Date(y, m - 1, d);
|
||||
k.open();
|
||||
if (k.calendar) { k.calendar.navigate(dt); }
|
||||
var cal = (k.calendar && k.calendar.element())
|
||||
|| window.jQuery('.k-calendar:visible').last();
|
||||
var hit = null;
|
||||
cal.find('td').each(function () {
|
||||
var $td = window.jQuery(this);
|
||||
if ($td.hasClass('k-other-month') || $td.hasClass('k-state-other-month')) return;
|
||||
var $a = $td.find('a.k-link');
|
||||
var txt = $a.length ? $a.text() : $td.text();
|
||||
if (parseInt(txt, 10) === d) hit = $a.length ? $a : $td;
|
||||
});
|
||||
if (hit) { hit.click(); }
|
||||
var v = k.value(), s = '';
|
||||
if (v) {
|
||||
var mo = v.getMonth() + 1, da = v.getDate();
|
||||
s = v.getFullYear() + '-' + (mo < 10 ? '0' + mo : mo)
|
||||
+ '-' + (da < 10 ? '0' + da : da);
|
||||
}
|
||||
return JSON.stringify({ok: !!hit, set: s, input: this.value || ''});
|
||||
""", *date.split('-'))
|
||||
try:
|
||||
r = json.loads(r) if isinstance(r, str) else r
|
||||
except Exception:
|
||||
r = {'ok': False}
|
||||
if r.get('ok') and date in (r.get('set') or ''):
|
||||
print(f'[物料收发汇总表] {key} 日历点选生效(input显示 {r.get("input")})')
|
||||
return True
|
||||
last = f'日历点选 {r}'
|
||||
except Exception as e:
|
||||
last = f'日历点选异常: {e}'
|
||||
time.sleep(0.5)
|
||||
print(f'[物料收发汇总表] {key} 日期设置失败,最后回读: {last}')
|
||||
return False
|
||||
|
||||
|
||||
def _set_date(page, begin, end):
|
||||
"""设置起始/结束日期(Kendo datepicker),限定在 .k-window 过滤窗口内。"""
|
||||
if not _set_datepicker(page, 'FBEGINDATE', begin):
|
||||
print('[物料收发汇总表] 起始日期设置失败')
|
||||
return False
|
||||
if not _set_datepicker(page, 'FENDDATE', end):
|
||||
print('[物料收发汇总表] 结束日期设置失败')
|
||||
return False
|
||||
print(f'[物料收发汇总表] 日期: {begin} ~ {end}')
|
||||
return True
|
||||
|
||||
|
||||
def _click_add_row(page):
|
||||
"""点击仓库过滤面板「新增行」(aa.md L126: <li class="k-link kdFilterAdd">新增行</li>)。
|
||||
全局 li.k-link.kdFilterAdd 会同时匹配「主报表过滤」+「仓库过滤」两个面板,
|
||||
原实现总点到主过滤那个(其行数不增加导致误判失败)。因此必须限定在仓库过滤
|
||||
容器(id 含 FBeginStockId_Filter)内定位。物理点击只会选中文字,改用 JS click 触发。"""
|
||||
for css in (
|
||||
'xpath://li[contains(@class,"kdFilterAdd") and ancestor::div[contains(@id,"FBeginStockId_Filter")]]',
|
||||
'css:[id*="FBeginStockId_Filter-FBATCHFILTERGRID_ENTRYBAR-tbAddRow"]',
|
||||
):
|
||||
# 直接取单个元素命中即点,避免 eles 遍历整页拖慢
|
||||
el = page.ele(css, timeout=2)
|
||||
if el is not None:
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
el.click(by_js=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _row_tr(v):
|
||||
"""上溯到包含该值输入框的条件行 <tr>(一个过滤条件一行,内含逻辑/字段/比较/值)。"""
|
||||
node = v
|
||||
for _ in range(8):
|
||||
try:
|
||||
node = node.parent()
|
||||
except Exception:
|
||||
break
|
||||
if node is not None and node.tag == 'tr':
|
||||
return node
|
||||
return None
|
||||
|
||||
|
||||
def _ensure_logic_or(page, v):
|
||||
"""把指定值输入框所在行的逻辑下拉制为「或者」(OR)。
|
||||
多个仓库编码之间需为或关系;行内逻辑下拉类名含 _PART_Logic_listbox,选项 并且/或者。"""
|
||||
tr = _row_tr(v)
|
||||
if tr is None:
|
||||
return False
|
||||
lg = tr.ele('css:span[role="listbox"][aria-owns*="_PART_Logic_listbox"]', timeout=2)
|
||||
if lg is None:
|
||||
return False
|
||||
try:
|
||||
cur = lg.ele('css:.k-input', timeout=1)
|
||||
if cur and cur.text.strip() == '或者':
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
lg.ele('css:.k-select', timeout=2).click()
|
||||
time.sleep(0.3)
|
||||
lb = page.ele('#' + lg.attr('aria-owns'), timeout=2)
|
||||
if lb is None:
|
||||
return False
|
||||
for it in lb.eles('css:li', timeout=2):
|
||||
try:
|
||||
if it.text.strip() == '或者':
|
||||
it.click()
|
||||
time.sleep(0.2)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception as e:
|
||||
print(f'[物料收发汇总表] 设置逻辑为或者失败: {e}')
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _diag_stock_btn(page):
|
||||
"""仓库搜索按钮找不到时输出诊断信息,定位是过滤窗口没开还是按钮不可见。"""
|
||||
try:
|
||||
wins = [t.text for t in page.eles('css:.k-window-title') if t.states.is_displayed]
|
||||
print(f' [诊断] 当前可见窗口标题: {wins}')
|
||||
c = page.ele('css:[id*="FBEGINSTOCKID-EDITOR"]', timeout=1)
|
||||
print(f' [诊断] FBEGINSTOCKID-EDITOR 容器存在={bool(c)}'
|
||||
f' 可见={c.states.is_displayed if c else "-"}')
|
||||
btns = page.eles('css:[id*="FBEGINSTOCKID"] .kd-editor-btn')
|
||||
vis = 0
|
||||
for b in btns:
|
||||
try:
|
||||
if b.states.is_displayed:
|
||||
vis += 1
|
||||
except Exception:
|
||||
pass
|
||||
print(f' [诊断] FBEGINSTOCKID 内 .kd-editor-btn 总数={len(btns)} 可见={vis}')
|
||||
org_css = 'css:.k-window [id*="FSTOCKORGID"]'
|
||||
print(f' [诊断] 过滤窗口内(.k-window) FSTOCKORGID 可见节点: '
|
||||
f'{_ele_visible(page, org_css, timeout=1)}')
|
||||
except Exception as e:
|
||||
print(f' [诊断] 异常: {e}')
|
||||
|
||||
|
||||
def _submit_query(page, with_date=None):
|
||||
"""点主过滤界面「确定」触发查询。with_date 传 (begin, end) 时先重设日期防覆盖。
|
||||
注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库过滤面板的 FBeginStockId_Filter-FBTNOK_c,
|
||||
用 :not 排除 + .k-window 限定,防止误点(含主界面残留节点)。
|
||||
不再用 FSTOCKORGID 判断「界面关闭」:主表单存在同 id 可见节点会永远误判未关闭,
|
||||
查询是否真被受理交给 _wait_progress(「查询进度」窗口是最可靠信号)。"""
|
||||
if with_date:
|
||||
if not _set_date(page, *with_date):
|
||||
print('[物料收发汇总表] 提交前日期重设失败')
|
||||
return False
|
||||
if not _click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
print('[物料收发汇总表] 找不到主过滤界面确定按钮')
|
||||
return False
|
||||
print('[物料收发汇总表] 已提交查询')
|
||||
return True
|
||||
|
||||
|
||||
def _set_stock_codes(page, codes, begin, end):
|
||||
"""仓库编码:点搜索 → 点过滤 → 逐行新增输入(或关系)→ 确定 → 退出 → 主界面确定触发查询。
|
||||
每行结构(aa.md L127):括号 + 逻辑(或) + 字段(基本信息-编码) + 比较(等于) + 值(输入后回车查询)。
|
||||
新增行后填仓库编码(一行一个),并把每行逻辑设为「或者」(OR) 保证多仓库为或关系。
|
||||
提交查询(点主过滤确定)前重设一次日期:仓库面板操作过程可能把过滤条件重置为默认。"""
|
||||
if not codes:
|
||||
return False
|
||||
# 1. 点仓库编码搜索按钮,打开仓库列表窗口(限定 .k-window 过滤窗口内)
|
||||
if not _click_visible(page, 'css:.k-window [id*="FBEGINSTOCKID-EDITOR"] .kd-editor-btn'):
|
||||
print('[物料收发汇总表] 找不到仓库编码搜索按钮')
|
||||
_diag_stock_btn(page)
|
||||
return False
|
||||
time.sleep(1.5)
|
||||
# 2. 点「过滤」打开过滤面板
|
||||
if not _click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbFilter"]'):
|
||||
print('[物料收发汇总表] 找不到过滤按钮')
|
||||
return False
|
||||
time.sleep(1)
|
||||
|
||||
# 3. 逐行新增输入仓库编码,并将每行逻辑设为「或者」
|
||||
val_css = 'css:[id*="FBeginStockId_Filter-FFILTERGRID"] input[placeholder*="请输入关键字"]'
|
||||
for i, code in enumerate(codes):
|
||||
# 快捷过滤网格初始为空(无默认行),每行都得先「新增行」再填值
|
||||
vs = page.eles(val_css)
|
||||
if len(vs) <= i:
|
||||
added = False
|
||||
for _ in range(3):
|
||||
if _click_add_row(page):
|
||||
time.sleep(0.8)
|
||||
if len(page.eles(val_css)) > i:
|
||||
added = True
|
||||
break
|
||||
if not added:
|
||||
print(f'[物料收发汇总表] 点击新增行失败(第{i + 1}行,当前值输入框{len(vs)}个)')
|
||||
return False
|
||||
vs = page.eles(val_css)
|
||||
print(f'[物料收发汇总表] 当前过滤值输入框数: {len(vs)}')
|
||||
v = vs[i] if len(vs) > i else None
|
||||
if not v:
|
||||
print(f'[物料收发汇总表] 找不到第{i + 1}行过滤值输入框')
|
||||
return False
|
||||
v.clear()
|
||||
v.input(code)
|
||||
_press_enter_in(v, page) # 回车直接发给输入框,触发查询确认
|
||||
time.sleep(0.8)
|
||||
_ensure_logic_or(page, v) # 保证该行逻辑为「或者」
|
||||
print(f'[物料收发汇总表] 仓库条件行{i + 1}: {code}(逻辑或)')
|
||||
|
||||
# 4. 过滤面板内「确定」
|
||||
if not _click_visible(page, 'css:[id*="FBeginStockId_Filter-FBTNOK_c"]'):
|
||||
print('[物料收发汇总表] 找不到过滤面板确定按钮')
|
||||
return False
|
||||
time.sleep(0.8)
|
||||
# 5. 「退出」关闭仓库过滤窗口
|
||||
_click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbClose"]', timeout=8)
|
||||
time.sleep(0.8)
|
||||
# 6. 提交查询(提交前重设日期防仓库面板操作覆盖)
|
||||
return _submit_query(page, (begin, end))
|
||||
|
||||
|
||||
def _wait_progress(page, timeout=300):
|
||||
"""等待「查询进度」窗口出现并消失(遍历所有窗口标题)。
|
||||
- 进度窗口出现但超时不消失 → 返回 False(查询失败/卡死,防止把旧报表当本次结果)
|
||||
- 全程未出现进度窗口 → 报表网格已渲染且连续 3 秒稳定视为快速完成(兜底)
|
||||
- 进度窗口消失后需连续 3 秒无进度窗口才算结束(防分阶段查询误判)
|
||||
不用 FSTOCKORGID 判定界面关闭:主表单存在同 id 可见节点,不可靠。"""
|
||||
end = time.time() + timeout
|
||||
appeared = False
|
||||
stable = 0
|
||||
while time.time() < end:
|
||||
in_progress = any('查询进度' in x for x in _visible_titles(page))
|
||||
if in_progress:
|
||||
if not appeared:
|
||||
appeared = True
|
||||
print('[物料收发汇总表] 查询进度中,等待完成...')
|
||||
stable = 0
|
||||
elif appeared:
|
||||
stable += 1
|
||||
if stable >= 3:
|
||||
print('[物料收发汇总表] 查询完成')
|
||||
time.sleep(2) # 缓冲:数据渲染
|
||||
return True
|
||||
else:
|
||||
# 进度窗口未出现:网格已渲染且稳定视为快速完成(兜底)
|
||||
if _ele_visible(page, 'css:.k-grid', timeout=1):
|
||||
stable += 1
|
||||
if stable >= 3:
|
||||
print('[物料收发汇总表] 查询完成(进度窗口未出现)')
|
||||
return True
|
||||
else:
|
||||
stable = 0
|
||||
time.sleep(1)
|
||||
print('[物料收发汇总表] 查询进度超时未结束'
|
||||
if appeared else '[物料收发汇总表] 未检测到查询进度且报表未渲染')
|
||||
return False
|
||||
|
||||
|
||||
def _export_all_pages(page):
|
||||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 引出所有页。
|
||||
结论(现场症状):物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||||
让子菜单展开后用 move_to+click 点中「引出所有页」;不点 span 文本,避免全选。
|
||||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。"""
|
||||
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-tbParamList"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbParamList"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
print('[物料收发汇总表] 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
print('[物料收发汇总表] 点选项失败')
|
||||
return False
|
||||
time.sleep(1.2)
|
||||
|
||||
# 2. 定位「引出」(splitbutton)
|
||||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbSplitExport"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbSplitExport"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
print('[物料收发汇总表] 找不到导出(引出)按钮')
|
||||
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-tbButtonExportAllPage"]', 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-tbButtonExportAllPage"]', 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:
|
||||
print('[物料收发汇总表] 找不到引出所有页')
|
||||
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:
|
||||
print('[物料收发汇总表] 点击引出所有页失败')
|
||||
return False
|
||||
print('[物料收发汇总表] 已触发引出所有页')
|
||||
return True
|
||||
|
||||
|
||||
def _download_file(page, save_dir, new_name):
|
||||
"""点「下载」按钮 → 等文件落盘到保存目录。
|
||||
做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录),
|
||||
然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。"""
|
||||
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:
|
||||
print(f'[物料收发汇总表] 设置下载目录异常: {e}')
|
||||
before = set(save_dir.glob('*')) if save_dir.exists() else set()
|
||||
before_names = {b.name for b in before} # 一次性算好,避免每秒循环重复生成
|
||||
|
||||
# 找可见的「下载」按钮
|
||||
dl = None
|
||||
end = time.time() + TIMEOUT
|
||||
while time.time() < end:
|
||||
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
dl = el
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
if not dl:
|
||||
print('[物料收发汇总表] 找不到下载按钮')
|
||||
return False
|
||||
print('[物料收发汇总表] 点击下载按钮...')
|
||||
try:
|
||||
dl.click()
|
||||
except Exception:
|
||||
dl.click(by_js=True)
|
||||
|
||||
# 等新文件出现且大小连续两次不变(下载完成)
|
||||
print('[物料收发汇总表] 等待文件下载完成...')
|
||||
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_dir / new_name
|
||||
if f != dst:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
try:
|
||||
shutil.move(str(f), str(dst))
|
||||
except Exception:
|
||||
dst = f
|
||||
print(f'[物料收发汇总表] 已保存: {dst}')
|
||||
_close_window_by_title(page, '文件下载') # 只关下载窗口,其余残留不主动关
|
||||
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_dir / new_name
|
||||
if dst != f:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
try:
|
||||
shutil.move(str(f), str(dst))
|
||||
except Exception:
|
||||
dst = f
|
||||
print(f'[物料收发汇总表] 已保存: {dst}')
|
||||
_close_window_by_title(page, '文件下载') # 只关下载窗口,其余残留不主动关
|
||||
return True
|
||||
print('[物料收发汇总表] 下载失败/超时')
|
||||
return False
|
||||
|
||||
|
||||
# ================== 单次导出 ==================
|
||||
def _reset_filter_state(page):
|
||||
"""重试前清理脏界面状态:若查询正在进行先等其结束(ESC 会打断正常查询),
|
||||
再按 ESC 关闭残留的组织下拉/过滤窗口,兜底点各面板「取消」按钮。"""
|
||||
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 _run_once(page, begin, end, codes, save_dir, new_name, first):
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if first:
|
||||
# 首档:完整设置 组织 → 仓库(内部提交前重设日期并触发查询)
|
||||
if not _set_org(page, ORG_NAME):
|
||||
return False
|
||||
if not _set_stock_codes(page, codes, begin, end):
|
||||
return False
|
||||
else:
|
||||
# 后续档:组织/仓库等条件 K3 已保留,只需改日期后提交查询
|
||||
if not _set_date(page, begin, end):
|
||||
return False
|
||||
if not _submit_query(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
if not _export_all_pages(page):
|
||||
return False
|
||||
return _download_file(page, save_dir, new_name)
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def main():
|
||||
save_dir = Path(SAVE_DIR) if SAVE_DIR else (
|
||||
Path(_get_desktop()) / f'{FOLDER_NAME}_{datetime.now():%Y-%m-%d}')
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
print(f'[物料收发汇总表] 保存目录: {save_dir}')
|
||||
|
||||
ok, page = erp_login(ERP)
|
||||
if not ok:
|
||||
print('[物料收发汇总表] ERP 登录失败,终止')
|
||||
return 1
|
||||
try:
|
||||
try:
|
||||
page.set.window.max()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
if not _open_report(page):
|
||||
print('[物料收发汇总表] 打开报表失败,终止')
|
||||
return 1
|
||||
|
||||
failed = []
|
||||
for i, option in enumerate(DATE_OPTIONS):
|
||||
begin, end, label = _resolve_dates(option)
|
||||
new_name = f'{FILE_PREFIX}_{label}.xlsx'
|
||||
success = False
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
print(f'[物料收发汇总表] [{label}] 第 {attempt}/{RETRY_MAX} 次: {begin} ~ {end}')
|
||||
if _run_once(page, begin, end, STOCK_CODES, save_dir, new_name,
|
||||
first=(i == 0)):
|
||||
success = True
|
||||
break
|
||||
_reset_filter_state(page) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
if not success:
|
||||
print(f'[物料收发汇总表] [{label}] 重试 {RETRY_MAX} 次均失败,继续下一个日期选项')
|
||||
failed.append(label)
|
||||
time.sleep(1)
|
||||
if failed:
|
||||
print(f'[物料收发汇总表] 以下日期选项导出失败: {"、".join(failed)}')
|
||||
return 1
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
print('[物料收发汇总表] 全部导出完成')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,109 @@
|
||||
"""物料收发汇总表 合并工具(XQ0031)。
|
||||
|
||||
将同目录(默认桌面最新「采购计划报表_日期」文件夹)下导出的各档报表
|
||||
(物料收发汇总表_60D.xlsx / _30D.xlsx / 自定义日期区间 ...)合并为一个汇总文件:
|
||||
- 每个报表第 4 行是表头;合并时在第 4 行表头第一列新增「时间区间」字段
|
||||
- 数据行第一列填入报表标签(60D / 30D / 日期区间 ...)
|
||||
- 汇总结果输出到同目录,命名:物料收发汇总表_YYYY-MM-DD.xlsx
|
||||
|
||||
自包含:仅依赖 openpyxl,无外部参数依赖。
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
# 合并目录:None → 自动取桌面最新「采购计划报表_*」目录;也可直接写绝对路径
|
||||
MERGE_DIR = None
|
||||
# 输出文件名:None → 物料收发汇总表_<目录日期>.xlsx
|
||||
OUT_NAME = None
|
||||
|
||||
|
||||
def _save_dir() -> Path:
|
||||
if MERGE_DIR:
|
||||
return Path(MERGE_DIR)
|
||||
desk = Path.home() / 'Desktop'
|
||||
cands = sorted(desk.glob('采购计划报表_*'),
|
||||
key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
if not cands:
|
||||
raise SystemExit(f'未找到桌面目录: {desk}/采购计划报表_*')
|
||||
return cands[0]
|
||||
|
||||
|
||||
def _label(name: str):
|
||||
"""从文件名提取报表标签:物料收发汇总表_60D.xlsx → 60D;
|
||||
物料收发汇总表_2026-07-01_2026-07-31.xlsx → 2026-07-01_2026-07-31。"""
|
||||
m = re.match(r'^物料收发汇总表_(.+)\.xlsx$', name)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def _read_report(path: Path):
|
||||
"""读取单个报表:表头位于第 4 行,数据从第 5 行起。
|
||||
每表最后一行是汇总行,明确跳过;再叠加空行过滤做兜底。返回 (表头, 数据行列表)。"""
|
||||
wb = openpyxl.load_workbook(path, data_only=True)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
header = [ws.cell(4, c).value for c in range(1, ws.max_column + 1)]
|
||||
rows = []
|
||||
# 跳过最后一行汇总行
|
||||
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):
|
||||
rows.append(row)
|
||||
return header, rows
|
||||
|
||||
|
||||
def merge() -> Path:
|
||||
save_dir = _save_dir()
|
||||
|
||||
date_tag = ''
|
||||
m = re.search(r'(\d{4}-\d{2}-\d{2})', save_dir.name)
|
||||
date_tag = m.group(1) if m else datetime.now().strftime('%Y-%m-%d')
|
||||
out = save_dir / (OUT_NAME or f'物料收发汇总表_{date_tag}.xlsx')
|
||||
|
||||
files = sorted(p for p in save_dir.glob('物料收发汇总表_*.xlsx')
|
||||
if _label(p.name) and p.name != out.name)
|
||||
if not files:
|
||||
raise SystemExit(f'目录下没有可合并的报表: {save_dir}')
|
||||
|
||||
header = None
|
||||
all_rows, labels = [], []
|
||||
for f in files:
|
||||
label = _label(f.name)
|
||||
h, rows = _read_report(f)
|
||||
if header is None:
|
||||
header = h
|
||||
elif h != header:
|
||||
print(f'[跳过] 表头不一致: {f.name}')
|
||||
continue
|
||||
all_rows.extend([[label] + row for row in rows])
|
||||
labels.append(label)
|
||||
print(f'[{label}] 数据 {len(rows)} 行 <- {f.name}')
|
||||
|
||||
if not all_rows:
|
||||
raise SystemExit('没有可合并的数据')
|
||||
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)
|
||||
print(f'已生成: {out}(共 {len(all_rows)} 条数据,{len(labels)} 个报表)')
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
merge()
|
||||
@@ -0,0 +1,653 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: purchase_order_list_export.py
|
||||
@Description: 需求32 - 金蝶 K3Cloud ERP「采购订单列表」自动导出。
|
||||
全局搜索「采购订单列表」→ 选中编号 CGDDLB 项 → 点快捷方案「默认方案(个人)」→
|
||||
等查询完成 → 选项 → 引出 → 按列表引出数据 → 下载保存到桌面(与需求31同目录)。
|
||||
|
||||
调用关系:复用 share/erp_login.py 登录 ERP(新旧系统通用)。
|
||||
运行方式:直接运行本文件(参数全部在代码内定义,无需命令行传参)。
|
||||
|
||||
业务配置说明(改下面配置块即可):
|
||||
ERP 'new' 新版 / 'old' 旧版 / 完整登录页 URL
|
||||
登录账号密码 统一放项目根目录 .env(erp_login_username / erp_login_password),
|
||||
erp_login 自动读取,代码中不存明文
|
||||
REPORT_KEYWORD 全局搜索关键字(采购订单列表)
|
||||
REPORT_NUMBER 搜索结果编号(CGDDLB,选中该项进入列表)
|
||||
SCHEME_NAME 要选中的快捷方案名(精确匹配:默认方案(个人))
|
||||
SAVE_DIR 保存目录,None 时与需求31同目录:桌面/采购计划报表_YYYY-MM-DD
|
||||
FOLDER_NAME 文件夹命名(采购计划报表+日期,与需求31一致)
|
||||
FILE_PREFIX 导出文件命名前缀(采购订单列表_日期.xlsx)
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
try: # 浏览器断连等致命异常需上抛,避免被通用容错吞掉空转
|
||||
from DrissionPage.errors import PageDisconnectedError
|
||||
except Exception:
|
||||
PageDisconnectedError = None
|
||||
|
||||
# ================== 业务配置(直接在此修改) ==================
|
||||
ERP = 'new' # 新版 criterion.erp.37du.co
|
||||
# 登录账号密码统一放根目录 .env:erp_login_username / erp_login_password
|
||||
REPORT_KEYWORD = '采购订单列表' # 全局搜索关键字
|
||||
REPORT_NUMBER = 'CGDDLB' # 搜索结果编号(列表项唯一标识)
|
||||
SCHEME_NAME = '默认方案(个人)' # 快捷方案条要选中的方案(精确匹配,避免命中「采购订单宽表默认方案」)
|
||||
SAVE_DIR = None # None → 与需求31同目录:桌面/采购计划报表_日期
|
||||
FOLDER_NAME = '采购计划报表' # 文件夹命名前缀(与需求31一致)
|
||||
FILE_PREFIX = '采购订单列表' # 导出文件命名前缀(采购订单列表_日期.xlsx)
|
||||
|
||||
# ================== 运行参数 ==================
|
||||
RETRY_MAX = 3 # 单次导出最大重试次数(项目规范)
|
||||
TIMEOUT = 15 # 元素查找超时(秒)
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'share'))
|
||||
from erp_login import erp_login # noqa: E402
|
||||
|
||||
|
||||
# ================== 工具函数 ==================
|
||||
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=TIMEOUT, by_js=False):
|
||||
"""点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。
|
||||
by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。"""
|
||||
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 _close_window_by_title(page, title, timeout=3):
|
||||
"""物理点击关闭标题包含关键字的 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 _diag_search(page):
|
||||
"""探针:搜索失败时打印当前页面/下拉状态,定位是下拉没出来还是选择器不匹配。"""
|
||||
try:
|
||||
print(f'[采购订单列表] [探针] 当前 URL: {(page.url or "")[:120]}')
|
||||
except Exception as e:
|
||||
print(f'[采购订单列表] [探针] 读 URL 异常: {e}')
|
||||
try:
|
||||
items = page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2)
|
||||
print(f'[采购订单列表] [探针] 下拉结果项数量: {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)
|
||||
print(f'[采购订单列表] [探针] 第{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:
|
||||
print(f'[采购订单列表] [探针] 枚举下拉异常: {e}')
|
||||
filter_visible = _ele_visible(
|
||||
page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=1)
|
||||
print(f'[采购订单列表] [探针] 过滤按钮可见: {filter_visible}')
|
||||
|
||||
|
||||
def _open_report(page):
|
||||
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
|
||||
注意:不能按回车——K3 全局搜索回车会默认直接进入第一个结果,下拉随即关闭,
|
||||
无法精确选中 CGDDLB 项。输入后等待联想下拉,再点对应项。"""
|
||||
if not _click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
print('[采购订单列表] 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
print('[采购订单列表] 找不到搜索输入框')
|
||||
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 _ele_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=2):
|
||||
print('[采购订单列表] 已打开列表(CGDDLB)')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
print(f'[采购订单列表] 未找到编号 {REPORT_NUMBER} 的搜索结果项')
|
||||
_diag_search(page) # 探针:输出诊断信息
|
||||
return False
|
||||
|
||||
|
||||
def _open_filter(page):
|
||||
"""确保过滤窗口打开:已开则复用,未开则点「过滤」按钮(by_js 触发菜单项)。"""
|
||||
if _ele_visible(page, 'css:.k-window [id*="_Filter-FSCHEMELIST"]', timeout=2):
|
||||
return True
|
||||
if _click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return _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() + 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 ''):
|
||||
print(f'[采购订单列表] 方案已是: {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 _ele_visible(page, 'css:.SelectedSchemeItemControlTemplate', timeout=2):
|
||||
print(f'[采购订单列表] 已选择方案: {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 _ele_visible(page, 'css:.SelectedSchemeItemControlTemplate',
|
||||
timeout=2):
|
||||
print(f'[采购订单列表] 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
print(f'[采购订单列表] 过滤窗口方案树中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _submit_filter(page):
|
||||
"""点过滤窗口「确定」触发查询。注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库等其它
|
||||
过滤面板的同 id 按钮,用 :not + .k-window 限定,防止误点。"""
|
||||
if not _click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
print('[采购订单列表] 找不到过滤窗口确定按钮')
|
||||
return False
|
||||
print('[采购订单列表] 已提交过滤查询')
|
||||
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=300):
|
||||
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
|
||||
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。"""
|
||||
_, init_cnt = _read_rowcount(page)
|
||||
print(f'[采购订单列表] 当前条数: {init_cnt if init_cnt >= 0 else "无"},等待查询刷新...')
|
||||
saw_reset = init_cnt < 0 # 初始无条数视为已重置
|
||||
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:
|
||||
print(f'[采购订单列表] 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
print('[采购订单列表] 等待查询完成超时(行数未刷新)')
|
||||
return False
|
||||
|
||||
|
||||
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:
|
||||
print('[采购订单列表] 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
print('[采购订单列表] 点选项失败')
|
||||
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:
|
||||
print('[采购订单列表] 找不到导出(引出)按钮')
|
||||
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:
|
||||
print('[采购订单列表] 找不到按列表引出数据')
|
||||
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:
|
||||
print('[采购订单列表] 点击按列表引出数据失败')
|
||||
return False
|
||||
print('[采购订单列表] 已触发按列表引出数据')
|
||||
return True
|
||||
|
||||
|
||||
def _download_file(page, save_dir, new_name):
|
||||
"""点「下载」按钮 → 等文件落盘到保存目录。
|
||||
做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录),
|
||||
然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。"""
|
||||
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:
|
||||
print(f'[采购订单列表] 设置下载目录异常: {e}')
|
||||
before = set(save_dir.glob('*')) if save_dir.exists() else set()
|
||||
before_names = {b.name for b in before} # 一次性算好,避免每秒循环重复生成
|
||||
|
||||
# 找可见的「下载」按钮
|
||||
dl = None
|
||||
end = time.time() + TIMEOUT
|
||||
while time.time() < end:
|
||||
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
dl = el
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
if not dl:
|
||||
print('[采购订单列表] 找不到下载按钮')
|
||||
return False
|
||||
print('[采购订单列表] 点击下载按钮...')
|
||||
try:
|
||||
dl.click()
|
||||
except Exception:
|
||||
dl.click(by_js=True)
|
||||
|
||||
# 等新文件出现且大小连续两次不变(下载完成)
|
||||
print('[采购订单列表] 等待文件下载完成...')
|
||||
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_dir / new_name
|
||||
if f != dst:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
try:
|
||||
shutil.move(str(f), str(dst))
|
||||
except Exception:
|
||||
dst = f
|
||||
print(f'[采购订单列表] 已保存: {dst}')
|
||||
_close_window_by_title(page, '文件下载') # 只关下载窗口,其余残留不主动关
|
||||
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_dir / new_name
|
||||
if dst != f:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
try:
|
||||
shutil.move(str(f), str(dst))
|
||||
except Exception:
|
||||
dst = f
|
||||
print(f'[采购订单列表] 已保存: {dst}')
|
||||
_close_window_by_title(page, '文件下载') # 只关下载窗口,其余残留不主动关
|
||||
return True
|
||||
print('[采购订单列表] 下载失败/超时')
|
||||
return False
|
||||
|
||||
|
||||
# ================== 单次导出 ==================
|
||||
def _reset_filter_state(page):
|
||||
"""重试前清理脏界面状态:按 ESC 关闭残留的弹层/过滤窗口,兜底点各面板「取消」按钮。"""
|
||||
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 _click_quick_scheme(page, scheme):
|
||||
"""直接点击列表页顶部快捷方案条中的目标方案,无需打开过滤窗口。
|
||||
结构:div[filter-role="filterschemecontent"] > div.SchemeItemControlTemplate(含方案名,
|
||||
选中的为 SelectedSchemeItemControlTemplate)。
|
||||
注意:K3 控件用 by_js click 可能不触发,优先真实鼠标点击。"""
|
||||
ac = page.actions
|
||||
end = time.time() + 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:
|
||||
print(f'[采购订单列表] 快捷方案已是: {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 ''):
|
||||
print(f'[采购订单列表] 已点选快捷方案: {txt}')
|
||||
return True
|
||||
# 未确认选中:返回 False 走过滤窗口回退,防止把旧数据当本次结果
|
||||
print(f'[采购订单列表] 点击快捷方案未确认选中: {txt}')
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
print(f'[采购订单列表] 快捷方案条中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _run_once(page):
|
||||
"""直接点快捷方案「默认方案(个人)」→ 等查询 → 引出所有页 → 下载。
|
||||
快捷方案条不存在时回退到过滤窗口选方案。"""
|
||||
if _click_quick_scheme(page, SCHEME_NAME):
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
else:
|
||||
# 回退:过滤窗口选方案
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if not _select_scheme(page, SCHEME_NAME):
|
||||
return False
|
||||
if not _submit_filter(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
if not _export_all_pages(page):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def main():
|
||||
save_dir = Path(SAVE_DIR) if SAVE_DIR else (
|
||||
Path(_get_desktop()) / f'{FOLDER_NAME}_{datetime.now():%Y-%m-%d}')
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
new_name = f'{FILE_PREFIX}_{datetime.now():%Y-%m-%d}.xlsx'
|
||||
print(f'[采购订单列表] 保存目录: {save_dir}')
|
||||
print(f'[采购订单列表] 导出文件: {new_name}')
|
||||
|
||||
ok, page = erp_login(ERP)
|
||||
if not ok:
|
||||
print('[采购订单列表] ERP 登录失败,终止')
|
||||
return 1
|
||||
try:
|
||||
try:
|
||||
page.set.window.max()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
if not _open_report(page):
|
||||
print('[采购订单列表] 打开列表失败,终止')
|
||||
return 1
|
||||
|
||||
success = False
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
print(f'[采购订单列表] 第 {attempt}/{RETRY_MAX} 次导出')
|
||||
if _run_once(page):
|
||||
success = _download_file(page, save_dir, new_name)
|
||||
if success:
|
||||
break
|
||||
_reset_filter_state(page) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
if not success:
|
||||
print(f'[采购订单列表] 重试 {RETRY_MAX} 次均失败')
|
||||
return 1
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
print('[采购订单列表] 导出完成')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user