feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 report 层:在参名单更新/变更清单/备份/增减员导入输出。"""
|
||||
@@ -0,0 +1,297 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 钉钉群机器人推送(自 workflows/share/dingtalk_robot.py 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 执行机运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "37du 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法(业务层统一走 report/notify.py,也可直接调用):
|
||||
main("需要推送的通知文本") 即可,标题/颜色/环境等均可选;
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK )
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = '' # 测试环境加签密钥(未配置则不加签)
|
||||
DEV_SERVER_NAME = '小芒 任务调度平台'
|
||||
|
||||
# 环境 → 机器人配置(main 的 env 参数选择;缺省/未知环境回退 prod)
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(Markdown,引用块/加粗/超链接/列表等语法会被钉钉渲染)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
server_name: 页脚署名
|
||||
"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。
|
||||
|
||||
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
|
||||
每批带「第 N/M 批」标题前缀,便于接收方识别。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(长文本)
|
||||
status: info|success|warning|error,决定标题颜色
|
||||
server_name: 页脚署名
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
|
||||
"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # +1 for newline
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
print(f"[INFO] 分批推送 {i}/{total}: {batch_title}")
|
||||
self.send(batch_title, batch_content, status=status,
|
||||
server_name=server_name)
|
||||
|
||||
|
||||
# ==================== 块格式工具:调用方把每条记录格式化为 block 字符串列表,
|
||||
# 这里统一负责分批、加头尾、生成最终待推送的消息文本列表 ====================
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 字符串列表按 batch_size 条一批,生成带批次标题的消息文本列表。
|
||||
|
||||
Args:
|
||||
blocks: 每条记录格式化后的 block 字符串列表(调用方负责格式化业务字段)
|
||||
title_prefix: 批次标题前缀,如 "【请假审批】通过"
|
||||
batch_size: 每批最大条数(默认 10)
|
||||
|
||||
Returns:
|
||||
字符串列表,每项是一条完整的待推送 Markdown 文本,可直接传给 main(text=...)
|
||||
配合 batch=True 发送。
|
||||
"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 推送入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""
|
||||
钉钉群机器人推送入口(与影刀版「37du钉钉群机器人推送」指令同一套签名/分批/页脚逻辑)。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
支持逐条推送多条:text 传「文本列表」时按顺序逐条发送,列表项可为纯文本,
|
||||
也可为字典 {text, title?, status?, batch?} 自定义该条标题、颜色与格式。
|
||||
消息正文一律按 Markdown 渲染(引用块/加粗/超链接/列表等语法直接生效)。
|
||||
|
||||
块格式分组(推荐,调用方不关心分批):
|
||||
text 传字典列表,每项形如 {title, blocks, status?, batch_size?},
|
||||
blocks 为每条记录格式化好的 block 字符串列表。模块自动按 batch_size
|
||||
(默认 10)分批、每批带「第N/M批」标题并逐条推送。示例:
|
||||
main([
|
||||
{"title": "【增员导入】异常名单(2 条)",
|
||||
"blocks": ["**🔹 三十七度‑张三**\n> 工号:...", "..."],
|
||||
"status": "error"},
|
||||
])
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省按 env 选择;显式传入则优先)
|
||||
secret: 加签密钥(缺省按 env 选择;显式传入则优先)
|
||||
server_name: 页脚署名(缺省按 env 选择;显式传入则优先)
|
||||
env: 环境 prod|dev,决定缺省 webhook/secret/server_name(默认 prod)
|
||||
batch: 是否启用分批发送(默认 False)。
|
||||
True: 当内容超长时自动按行拆成多批发送,每批标题带「第N/M批」;
|
||||
False: 单条发送(内容超长可能被钉钉截断或报错)。
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000),
|
||||
仅在 batch=True 时生效。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = webhook or cfg['webhook']
|
||||
secret = secret or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置,请先在 dingtalk_robot.py 中填写'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
# 块格式分组:调用方只传格式化好的 block 列表 + 标题,
|
||||
# 分批、加批次标题、逐条推送全部由本模块负责(调用方不关心批次)
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st,
|
||||
server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,120 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 钉钉群通知(业务消息构建 + 推送,口径与影刀版 add_sub_import 一致)。
|
||||
|
||||
推送内容:
|
||||
1. 汇总一条:调度/筛选结果统计 + HR 导入结果(或人工导入提示)+ 注意事项;
|
||||
2. 增员/减员导入异常名单各一条(接口返回的业务异常明细 + 流程失败单元),
|
||||
名单过长由 dingtalk_robot 按批自动分批(每批 10 条)。
|
||||
消息状态色:全部正常 success(绿);有异常/待确认/注意事项 warning(橙);调度全军覆没 error(红)。
|
||||
推送失败只记 WARN 日志,不影响插件主流程。
|
||||
"""
|
||||
from ..config import DINGTALK_ENV, log
|
||||
from . import dingtalk_robot
|
||||
|
||||
TITLE_SUMMARY = "雇主险增减操作完成"
|
||||
|
||||
|
||||
def _import_issues(import_results):
|
||||
"""从 HR 导入结果中提取异常/流程失败明细,按菜单(增员导入/减员导入)分组。
|
||||
|
||||
Returns:
|
||||
dict: {menu: [{"category", "staff_code", "staff_name",
|
||||
"insurance_name", "message"}, ...]}
|
||||
"""
|
||||
grouped = {}
|
||||
for r in import_results or []:
|
||||
menu = r.get("menu") or "导入"
|
||||
if r.get("error"):
|
||||
# 流程失败(登录/元素/文件缺失等):无业务结果,合并为一条异常上报
|
||||
grouped.setdefault(menu, []).append({
|
||||
"category": r.get("category", ""),
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
continue
|
||||
for exc in r.get("exceptions") or []:
|
||||
grouped.setdefault(menu, []).append({
|
||||
"category": r.get("category", ""),
|
||||
"staff_code": exc.get("staff_code", ""),
|
||||
"staff_name": exc.get("staff_name", ""),
|
||||
"insurance_name": exc.get("insurance_name", ""),
|
||||
"message": exc.get("message", ""),
|
||||
})
|
||||
return grouped
|
||||
|
||||
|
||||
def _build_messages(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
"""构建待推送消息列表(汇总 + 异常名单),块格式交由 dingtalk_robot 分批发送。"""
|
||||
issues = _import_issues(import_results)
|
||||
issue_total = sum(len(v) for v in issues.values())
|
||||
|
||||
# ---- 1. 汇总消息 ----
|
||||
summary_lines = [
|
||||
"**处理类别 {} 个:筛选复制成功 {} 个、调度成功 {} 个**".format(
|
||||
total, filtered, scheduled),
|
||||
]
|
||||
if import_on:
|
||||
summary_lines.extend(import_lines or ["HR 导入未执行(登录态缺失或整体失败,详见注意事项与日志)"])
|
||||
else:
|
||||
summary_lines.append("HR 自动导入未开启:请取各类别文件夹内导入文件,先【减员】后【增员】人工导入")
|
||||
blocks = ["\n\n".join(summary_lines)]
|
||||
if notes:
|
||||
blocks.append("**⚠️ 注意事项({})**\n\n{}".format(
|
||||
len(notes), "\n\n".join("> - {}".format(n) for n in notes)))
|
||||
if scheduled == 0:
|
||||
status = "error"
|
||||
elif notes or issue_total:
|
||||
status = "warning"
|
||||
else:
|
||||
status = "success"
|
||||
messages = [{"title": TITLE_SUMMARY, "blocks": blocks, "status": status}]
|
||||
|
||||
# ---- 2. 增员/减员导入异常名单(各一条独立消息) ----
|
||||
for menu, excs in issues.items():
|
||||
if not excs:
|
||||
continue
|
||||
exc_blocks = []
|
||||
for exc in excs:
|
||||
exc_blocks.append(
|
||||
"**🔹 {} / {}**\n\n"
|
||||
"> 工号:{}\n\n"
|
||||
"> 姓名:{}\n\n"
|
||||
"> 方案:{}\n\n"
|
||||
"> 异常:{}".format(
|
||||
exc.get("category", "") or "-",
|
||||
exc.get("staff_name", "") or "-",
|
||||
exc.get("staff_code", "") or "-",
|
||||
exc.get("staff_name", "") or "-",
|
||||
exc.get("insurance_name", "") or "-",
|
||||
exc.get("message", ""),
|
||||
))
|
||||
messages.append({
|
||||
"title": "【{}】异常名单({} 条)".format(menu, len(excs)),
|
||||
"blocks": exc_blocks,
|
||||
"status": "error",
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
def push_run_result(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
"""把本次运行结果推送到钉钉群(环境取 config.DINGTALK_ENV),失败不影响主流程。
|
||||
|
||||
Args:
|
||||
total/filtered/scheduled: 处理/筛选复制/调度成功的类别数
|
||||
import_on: 是否执行了 HR 自动导入
|
||||
import_lines: hr_import.summarize_results 的可读文本行(未执行时传 [])
|
||||
import_results: hr_import.import_all 的逐单元结果(未执行时传 [])
|
||||
notes: 本次运行的注意事项列表
|
||||
"""
|
||||
try:
|
||||
messages = _build_messages(total, filtered, scheduled, import_on,
|
||||
import_lines, import_results, notes)
|
||||
result = dingtalk_robot.main(messages, env=DINGTALK_ENV)
|
||||
if result.get("success"):
|
||||
log(f"钉钉群通知已推送:{result.get('message', '')}", "INFO")
|
||||
else:
|
||||
log(f"钉钉群通知推送失败:{result.get('message', '')}", "WARN")
|
||||
except Exception as e:
|
||||
log(f"钉钉群通知推送失败(不影响主流程):{e}", "WARN")
|
||||
@@ -0,0 +1,664 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 结果输出层(由影刀版 employer_insurance_schedule.py 阶段3/五点五 与
|
||||
export_change_sheet.py 合并移植)。
|
||||
|
||||
包含:
|
||||
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
|
||||
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
|
||||
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
|
||||
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
|
||||
(值+样式,公式转缓存结果,避免 #REF!)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from copy import copy
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, DATA_START_ROW, BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME,
|
||||
category_import_add_file, category_import_sub_file, category_target_file,
|
||||
category_change_sheet_workbook, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, today_date,
|
||||
to_text, clean_text, to_date,
|
||||
)
|
||||
from ..logic.schedule import _find_special_slots, scheme_with_suffix
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、输出结果(在参名单 + 变更清单 + 备份 + 姓名修正)
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, in_param_sheet,
|
||||
name_corrections=None):
|
||||
"""输出四部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
"""
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
for rec in final_records:
|
||||
emp_ids_to_clear.add(rec["证件号"])
|
||||
emp_ids_to_clear.update(reused_source_employees)
|
||||
|
||||
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
|
||||
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录)
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
special_source_ids = set(s["source_id"] for s in special_slots)
|
||||
special_src_scheme = {s["source_id"]: s["new_scheme"] for s in special_slots}
|
||||
if special_slots:
|
||||
logger.info("特殊情况:离职/参保减少名额被老员工复用,链条末端空闲名额 %d 例(源员工改为空闲方案保留)",
|
||||
len(special_slots))
|
||||
for s in special_slots:
|
||||
logger.info(" 源 %s -> 改为方案 %s", s["source_id"], s["new_scheme"])
|
||||
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
keep_mask = (
|
||||
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
|
||||
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees))) |
|
||||
(in_param_df[emp_id_col].isin(special_source_ids)) # 特殊情况源员工保留(改M列为老员工旧方案)
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
|
||||
# ---------- 3. 构建员工信息字典 ----------
|
||||
biz_dict = {}
|
||||
for idx, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
# ---------- 4. 构建新参保记录(B~N列) ----------
|
||||
new_records = []
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id not in biz_dict:
|
||||
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
|
||||
continue
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": to_text(row_biz.get("工号")), # B列工号必须为文本
|
||||
"C": row_biz.get("年龄"),
|
||||
"D": row_biz.get("性别"),
|
||||
"E": row_biz.get("岗位"),
|
||||
"F": row_biz.get("职位序列"),
|
||||
"G": row_biz.get("参保类型"),
|
||||
"H": row_biz.get("上下班交通方式"),
|
||||
"I": row_biz.get("入职时间"),
|
||||
"J": row_biz.get("姓名"),
|
||||
"K": row_biz.get("证件号"),
|
||||
"L": row_biz.get("工种类别"),
|
||||
"M": row_biz.get("投保方案"),
|
||||
"N": today_date(),
|
||||
})
|
||||
|
||||
# ---------- 5. 打开工作簿 ----------
|
||||
wb = load_workbook(target_file)
|
||||
ws = wb[in_param_sheet]
|
||||
max_row = ws.max_row
|
||||
|
||||
# ---------- 6. 读取现有数据 ----------
|
||||
existing_rows = []
|
||||
for row_idx in range(DATA_START_ROW, max_row + 1):
|
||||
row_data = []
|
||||
for col in range(1, 27):
|
||||
row_data.append(ws.cell(row=row_idx, column=col).value)
|
||||
existing_rows.append({
|
||||
"row_idx": row_idx,
|
||||
"data": row_data,
|
||||
"emp_id": ws.cell(row=row_idx, column=11).value, # K列
|
||||
})
|
||||
|
||||
# ---------- 7. 构建新数据列表 ----------
|
||||
new_rows = []
|
||||
|
||||
# 姓名修正映射(证件号 -> 新姓名),保留行 J列姓名统一改为花名册姓名
|
||||
corr_by_id = {c["emp_id"]: c["new_name"] for c in (name_corrections or [])}
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
row_data = row_info["data"]
|
||||
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),N列投保日期更新为今天
|
||||
if emp_id in special_src_scheme:
|
||||
row_data[12] = special_src_scheme[emp_id]
|
||||
row_data[13] = today_date() # N列 投保日期
|
||||
# 姓名核对修正:J列姓名改为花名册姓名
|
||||
if emp_id in corr_by_id:
|
||||
row_data[9] = corr_by_id[emp_id]
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": emp_id,
|
||||
"action": "keep",
|
||||
})
|
||||
|
||||
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动;特殊情况源员工已保留,此处不清空)
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if (emp_id in emp_ids_to_clear and emp_id not in special_source_ids) or emp_id is None:
|
||||
row_data = row_info["data"].copy()
|
||||
for i in range(1, 14):
|
||||
row_data[i] = None
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": None,
|
||||
"action": "clear",
|
||||
})
|
||||
|
||||
# 7.3 填充新记录到空行
|
||||
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
|
||||
empty_slots.sort(key=lambda x: x["row_idx"])
|
||||
|
||||
def _fill(row_data, rec):
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
|
||||
for rec in new_records:
|
||||
if empty_slots:
|
||||
slot = empty_slots.pop(0)
|
||||
row_data = slot["data"]
|
||||
_fill(row_data, rec)
|
||||
slot["emp_id"] = rec["K"]
|
||||
slot["action"] = "filled"
|
||||
else:
|
||||
# 追加新行(复制上一行样式)
|
||||
row_data = [None] * 26
|
||||
if existing_rows:
|
||||
src_row_idx = existing_rows[-1]["row_idx"]
|
||||
for col in range(1, 27):
|
||||
src_cell = ws.cell(row=src_row_idx, column=col)
|
||||
dst_cell = ws.cell(row=max_row + 1, column=col)
|
||||
if src_cell.has_style:
|
||||
dst_cell.font = copy(src_cell.font)
|
||||
dst_cell.border = copy(src_cell.border)
|
||||
dst_cell.fill = copy(src_cell.fill)
|
||||
dst_cell.number_format = src_cell.number_format
|
||||
dst_cell.alignment = copy(src_cell.alignment)
|
||||
last_row_data = existing_rows[-1]["data"]
|
||||
for i in range(14, 26):
|
||||
row_data[i] = last_row_data[i]
|
||||
_fill(row_data, rec)
|
||||
new_rows.append({
|
||||
"row_idx": None,
|
||||
"data": row_data,
|
||||
"emp_id": rec["K"],
|
||||
"action": "append",
|
||||
})
|
||||
|
||||
# ---------- 8. 更新现有行(B~N列,列号=索引+1;B列工号强制文本) ----------
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is not None:
|
||||
row_idx = row_info["row_idx"]
|
||||
row_data = row_info["data"]
|
||||
for idx in range(1, 14):
|
||||
c = ws.cell(row=row_idx, column=idx + 1)
|
||||
if idx == 1:
|
||||
c.value = to_text(row_data[idx])
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = row_data[idx]
|
||||
|
||||
# ---------- 9. 追加新行 ----------
|
||||
current_row = max_row + 1
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is None:
|
||||
row_idx = current_row
|
||||
row_data = row_info["data"]
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
c = ws.cell(row=row_idx, column=col_idx)
|
||||
if col_idx == 2:
|
||||
c.value = to_text(value)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = value
|
||||
current_row += 1
|
||||
|
||||
# ---------- 9.5 紧凑化:消除中间空行(只搬移 B~O 数据列,公式列 R/S/T/U/V/W 不动) ----------
|
||||
data_values = []
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
has_data = any(
|
||||
ws.cell(row=row_idx, column=c).value not in (None, "")
|
||||
for c in range(2, 16)
|
||||
)
|
||||
if has_data:
|
||||
data_values.append([ws.cell(row=row_idx, column=c).value for c in range(2, 16)])
|
||||
target_row = DATA_START_ROW
|
||||
for vals in data_values:
|
||||
for col, v in enumerate(vals, start=2):
|
||||
cell = ws.cell(row=target_row, column=col)
|
||||
if col == 2: # B列 工号 强制文本
|
||||
cell.value = to_text(v)
|
||||
cell.number_format = "@"
|
||||
elif col == 14: # N列 投保日期 -> 日期类型 + yyyy-mm-dd
|
||||
cell.value = to_date(v)
|
||||
if cell.value is not None:
|
||||
cell.number_format = "yyyy-mm-dd"
|
||||
else:
|
||||
cell.value = v
|
||||
target_row += 1
|
||||
# 清空多出部分的 B~O 列(公式列不动)
|
||||
for row_idx in range(target_row, current_row):
|
||||
for col in range(2, 16):
|
||||
ws.cell(row=row_idx, column=col).value = None
|
||||
|
||||
# ---------- 10. 重新编号A列 ----------
|
||||
seq = 1
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
if ws.cell(row=row_idx, column=11).value is not None:
|
||||
ws.cell(row=row_idx, column=1).value = seq
|
||||
seq += 1
|
||||
else:
|
||||
ws.cell(row=row_idx, column=1).value = None
|
||||
|
||||
# ============================================================
|
||||
# ★★★ 11. 精细更新变更清单 ★★★
|
||||
# ============================================================
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
# 收集所有以类别变更清单前缀开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(change_sheet_prefix) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
|
||||
|
||||
template_name = max(candidates, key=_template_sort_key) if candidates else None
|
||||
|
||||
if template_name is not None:
|
||||
# 复制最近一次的历史模板Sheet(保留公式与样式)
|
||||
source = wb[template_name]
|
||||
target = wb.copy_worksheet(source)
|
||||
target.title = change_sheet_name
|
||||
logger.info("已从模板 [%s] 复制变更清单", template_name)
|
||||
else:
|
||||
# 没有任何历史模板,创建新Sheet(兜底)
|
||||
ws_change = wb.create_sheet(change_sheet_name)
|
||||
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
|
||||
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
|
||||
"工作单位", "", "备注", "批改日期", "新增费用会馆",
|
||||
"姓名", "证件号", "工种类别", "投保方案"]
|
||||
for col_idx, h in enumerate(headers, start=1):
|
||||
ws_change.cell(row=1, column=col_idx).value = h
|
||||
ws_change.cell(row=2, column=1).value = "公式"
|
||||
ws_change = wb[change_sheet_name]
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
|
||||
DEPT_COL_MARK = "费用会馆"
|
||||
dept_col = 15
|
||||
for _col in range(1, 21):
|
||||
if any(DEPT_COL_MARK in str(ws_change.cell(row=_row, column=_col).value or "")
|
||||
for _row in (1, 2)):
|
||||
dept_col = _col
|
||||
break
|
||||
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
|
||||
|
||||
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
|
||||
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
|
||||
|
||||
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
|
||||
max_row_change = ws_change.max_row
|
||||
if max_row_change >= 3:
|
||||
for row in range(3, max_row_change + 1):
|
||||
ws_change.cell(row=row, column=2).value = None # B列
|
||||
ws_change.cell(row=row, column=13).value = None # M列 备注
|
||||
ws_change.cell(row=row, column=14).value = None # N列
|
||||
ws_change.cell(row=row, column=dept_col).value = None # 四级部门列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 收集变更记录
|
||||
records = []
|
||||
|
||||
# 1. 删除记录(特殊情况源员工一并输出"增加老员工旧方案",保证增减平衡)
|
||||
for emp_id in emp_ids_to_clear:
|
||||
if emp_id in final_emp_ids:
|
||||
continue
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row = row_match.iloc[0]
|
||||
name = row.iloc[9]
|
||||
category = row.iloc[11]
|
||||
scheme = row.iloc[12]
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
# 特殊情况:源员工名额被老员工复用且老员工旧名额无人复用 -> 源员工改为该旧方案
|
||||
if emp_id in special_src_scheme:
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": special_src_scheme[emp_id]})
|
||||
else:
|
||||
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
|
||||
"category": "未知", "scheme": "未知"})
|
||||
|
||||
# 2. 增加记录。档次替换仅当「自己的名额档次替换、不涉及其他人」时合并为一条「修改」
|
||||
# 收集「自己的旧名额被他人复用」的员工集合(来源员工ID)
|
||||
reused_by_others = set()
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
reused_by_others.add(_sid)
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
row_biz = biz_dict[emp_id]
|
||||
name = row_biz.get("姓名")
|
||||
category = row_biz.get("工种类别")
|
||||
scheme = row_biz.get("投保方案")
|
||||
else:
|
||||
name = category = scheme = None
|
||||
if emp_id in initial_employee_map:
|
||||
# 原已参保(档次替换):仅"自己的名额档次替换、不涉及其他人"才合并为「修改」
|
||||
pure_self_replace = (
|
||||
rec.get("名额来源") == "全新新增" and
|
||||
emp_id not in reused_by_others
|
||||
)
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
old_scheme = None
|
||||
if not row_match.empty:
|
||||
old_scheme = row_match.iloc[0].iloc[12]
|
||||
if pure_self_replace:
|
||||
remark = None
|
||||
if old_scheme is not None and str(old_scheme).strip() != "" and \
|
||||
scheme is not None and str(scheme).strip() != "":
|
||||
remark = f"由{old_scheme}替换为{scheme}"
|
||||
records.append({"op": "修改", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme, "remark": remark})
|
||||
else:
|
||||
# 涉及其他人的档次替换:正常两条(删除旧方案 + 增加新方案)
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": old_scheme})
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
else:
|
||||
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 O列 填四级部门
|
||||
new_rec = {"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme}
|
||||
if rec.get("名额来源") == "全新新增":
|
||||
biz_row_dept = biz_dict.get(emp_id)
|
||||
dept = clean_text(biz_row_dept.get(biz_dept_col)) if biz_row_dept is not None else None
|
||||
if dept is None:
|
||||
# 四级部门为空:回退填所属单位,并记录日志供人工核对
|
||||
dept = clean_text(biz_row_dept.get("所属单位")) if biz_row_dept is not None else None
|
||||
logger.warning("员工 %s(%s) 花名册四级部门为空,O列回退填所属单位:%s",
|
||||
name, emp_id, dept)
|
||||
new_rec["dept"] = dept
|
||||
records.append(new_rec)
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for rec in records:
|
||||
op = rec.get("op")
|
||||
name = rec.get("name")
|
||||
emp_id = rec.get("emp_id")
|
||||
category = rec.get("category")
|
||||
scheme = rec.get("scheme")
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=13).value = rec.get("remark") # M列 备注
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date() # N列
|
||||
# 四级部门列:仅纯新增名额(全新新增)的「增加」记录才填
|
||||
if op == "增加" and rec.get("dept") is not None:
|
||||
ws_change.cell(row=current_row_change, column=dept_col).value = rec.get("dept")
|
||||
ws_change.cell(row=current_row_change, column=16).value = name # P列
|
||||
ws_change.cell(row=current_row_change, column=17).value = emp_id # Q列
|
||||
ws_change.cell(row=current_row_change, column=18).value = category # R列
|
||||
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
|
||||
current_row_change += 1
|
||||
|
||||
# 3. 姓名修正记录(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
for corr in (name_corrections or []):
|
||||
ws_change.cell(row=current_row_change, column=2).value = "修改"
|
||||
ws_change.cell(row=current_row_change, column=13).value = \
|
||||
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}"
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date()
|
||||
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"]
|
||||
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"]
|
||||
ws_change.cell(row=current_row_change, column=18).value = corr.get("category")
|
||||
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme")
|
||||
current_row_change += 1
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
|
||||
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
|
||||
logger.info("变更清单已精细更新(共 %d 条变更记录,含 %d 条姓名修正)",
|
||||
len(records) + len(name_corrections or []), len(name_corrections or []))
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、生成增员/减员导入文件(HR「待增减人员」页面上传素材)
|
||||
# ============================================================
|
||||
def _write_import_file(template_path, out_path, rows):
|
||||
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。"""
|
||||
if not os.path.isfile(template_path):
|
||||
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
|
||||
wb = load_workbook(template_path)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for i, row_vals in enumerate(rows):
|
||||
excel_row = 4 + i
|
||||
for col_idx, val in enumerate(row_vals, start=1):
|
||||
c = ws.cell(row=excel_row, column=col_idx)
|
||||
if col_idx == 2: # 工号/身份证列强制文本
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
wb.save(out_path)
|
||||
logger.info("已生成导入文件:%s(%d 条)", out_path, len(rows))
|
||||
|
||||
|
||||
def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees):
|
||||
"""生成各类别「商业保险增员导入.xlsx / 商业保险减员导入.xlsx」(HR 上传素材)。
|
||||
|
||||
集合差模型:按「人 + 投保方案」记录级做差:
|
||||
- 减员 = 原参保记录 − 新参保记录
|
||||
- 增员 = 新参保记录 − 原参保记录
|
||||
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
|
||||
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
|
||||
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
|
||||
|
||||
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错。
|
||||
"""
|
||||
# ---------- 1. 原参保记录集合 ----------
|
||||
orig_records = {} # to_text(证件号) -> 方案
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
scheme = row.iloc[12]
|
||||
if pd.isna(scheme) or str(scheme).strip() == "":
|
||||
continue
|
||||
orig_records[to_text(emp_id)] = scheme
|
||||
|
||||
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录 + 特殊情况保留源员工) ----------
|
||||
cleared_ids = set(to_text(e) for e in reused_source_employees)
|
||||
cleared_ids.update(to_text(rec["证件号"]) for rec in final_records)
|
||||
new_records_map = {
|
||||
emp_id: scheme for emp_id, scheme in orig_records.items()
|
||||
if emp_id not in cleared_ids
|
||||
}
|
||||
for rec in final_records:
|
||||
new_records_map[to_text(rec["证件号"])] = rec["投保方案"]
|
||||
# 特殊情况源员工(离职/参保减少名额被复用后保留在参名单,方案改为空闲方案):
|
||||
# 纳入"新参保记录"参与集合差,保证减员/增员对称、不漏人
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
for _s in special_slots:
|
||||
new_records_map[to_text(_s["source_id"])] = _s["new_scheme"]
|
||||
|
||||
# ---------- 3. 记录级集合差:减员名单 ----------
|
||||
sub_ids = [
|
||||
emp_id for emp_id, orig_scheme in orig_records.items()
|
||||
if emp_id not in new_records_map or new_records_map[emp_id] != orig_scheme
|
||||
]
|
||||
|
||||
# ---------- 4. 员工信息查询(biz_df 优先,其次 in_param_df) ----------
|
||||
emp_info = {} # to_text(证件号) -> {"工号": ..., "姓名": ...}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.iloc[1]), "姓名": row.iloc[9]}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.get("工号")), "姓名": row.get("姓名")}
|
||||
|
||||
def _code(emp_id):
|
||||
"""工号/身份证列:优先工号,空则回退证件号。"""
|
||||
return clean_text(emp_info.get(emp_id, {}).get("工号")) or clean_text(emp_id)
|
||||
|
||||
def _name(emp_id):
|
||||
return clean_text(emp_info.get(emp_id, {}).get("姓名"))
|
||||
|
||||
# ---------- 5. 组装行数据 ----------
|
||||
sub_rows, skipped_sub = [], 0
|
||||
for i, emp_id in enumerate(sub_ids, start=1):
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_sub += 1
|
||||
logger.warning("减员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
sub_rows.append([i, _code(emp_id), name, today_date()])
|
||||
|
||||
add_rows, skipped_add, seq = [], 0, 0
|
||||
for rec in final_records:
|
||||
emp_id = to_text(rec["证件号"])
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, rec["投保方案"]), today_date(),
|
||||
rec.get("名额来源") or "新增"])
|
||||
# 特殊情况源员工(保留在参名单,方案改为空闲方案)也需增员(新增该方案),不漏人
|
||||
for _s in special_slots:
|
||||
emp_id = to_text(_s["source_id"])
|
||||
new_scheme = _s["new_scheme"]
|
||||
# 方案未变(极少见边界)则无需增员
|
||||
if emp_id in orig_records and orig_records[emp_id] == new_scheme:
|
||||
continue
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:特殊情况源员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, new_scheme), today_date(),
|
||||
"特殊情况保留名额"])
|
||||
|
||||
# ---------- 6. 写入模板(保留第1~3行,第4行起填数据) ----------
|
||||
_write_import_file(sub_import_template(), category_import_sub_file(category), sub_rows)
|
||||
_write_import_file(add_import_template(), category_import_add_file(category), add_rows)
|
||||
|
||||
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
|
||||
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
|
||||
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、导出变更清单独立工作簿(值 + 样式,公式转缓存结果)
|
||||
# ============================================================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user