feat(XQ0008): 新增 HR 接口数据源及花名册 fallback 逻辑,修复 OA 推送附件上传 Content-Type 问题
- 新增 HR 花名册接口拉取逻辑,优先从 HR 接口获取花名册,失败回退源表/本地文件 - 新增推送人映射支持所属单位回退值,新增「水庄大鹅事业部」映射 - 修复 OA 推送附件上传时清除默认 Content-Type,避免 multipart 请求被服务端拒绝 - 优化二级部门解析逻辑,为空时用所属单位替代,避免中断流程 - 新增 store_point_api.py 和 attendance_points_push.py 积分推送模块,新增 store_login_api.py 门店登录模块 - 新增 notice_gen.py 中 HR 接口加密逻辑及多数据源 fallback 处理
This commit is contained in:
@@ -192,14 +192,15 @@ BRANCHES = {
|
||||
ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx" # 员工花名册路径
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]} # 二级部门 -> 固定人事工号(梁敏)
|
||||
|
||||
# 二级部门(经营中心)-> 内置推送人工号(财务专员):优先于花名册人事查找直接命中;
|
||||
# 未覆盖到的经营中心兜底走本文件原逻辑(DEPT2_HR_OVERRIDE 固定人事 + 花名册岗位含「人事」查找)
|
||||
# 推送人映射:键可为「二级部门(经营中心)」或「二级部门为空时的所属单位回退值」(如 水庄大鹅事业部)。
|
||||
# 优先于花名册人事查找(覆盖映射不依赖员工是否在花名册)。
|
||||
DEPT2_PUSH_OVERRIDE = {
|
||||
"金色印象海口经营中心": ["37000700"], # 李明姣 财务专员
|
||||
"金色印象昆明经营中心": ["37002511"], # 陈青 财务专员
|
||||
"金色印象南宁经营中心": ["37009626"], # 石梦 财务专员
|
||||
"金色印象深圳经营中心": ["37018211"], # 倪萍 财务专员
|
||||
"金色印象郑州经营中心": ["37006992"], # 张勤 财务专员
|
||||
"水庄大鹅事业部": ["37036104"], # 所属单位回退值(非二级部门),直接推送 37036104 唐佳膑
|
||||
}
|
||||
OA_GLV_NAME = "messages" # 影刀全局变量名(列表:工作沟通推送数据)
|
||||
|
||||
@@ -666,6 +667,76 @@ def _read_roster_map(roster_path: str) -> dict:
|
||||
wb.close()
|
||||
|
||||
|
||||
# ==================== 花名册数据源:源表「附-在职花名册」→ 本地文件 ====================
|
||||
def _read_roster_from_source_sheet(excel_path: str) -> dict:
|
||||
"""读取数据源 Excel 内嵌「附-在职花名册」sheet 构建 roster_map(与业务同文件同月份,数据可靠)。
|
||||
花名册单独文件缺失/损坏时兜底用,避免接收人解析受限。"""
|
||||
if not excel_path or not os.path.exists(excel_path):
|
||||
return {}
|
||||
try:
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
except Exception as e:
|
||||
logger.warning("源表读取失败,无法用「附-在职花名册」构建花名册:%s", e)
|
||||
return {}
|
||||
try:
|
||||
ws = next((s for s in wb.worksheets if "在职花名册" in s.title), None)
|
||||
if ws is None:
|
||||
return {}
|
||||
rows = list(ws.iter_rows(min_row=1, max_row=1, max_col=60))
|
||||
cols = {}
|
||||
for i, h in enumerate(rows[0]):
|
||||
v = h.value
|
||||
name = str(v).strip() if v is not None else ""
|
||||
if name and name not in cols:
|
||||
cols[name] = i
|
||||
if "工号" not in cols or "姓名" not in cols:
|
||||
logger.warning("「附-在职花名册」缺少工号/姓名列,无法构建花名册")
|
||||
return {}
|
||||
result = {}
|
||||
code_col = cols["工号"]
|
||||
for row in ws.iter_rows(min_row=2, max_col=60):
|
||||
vals = [c.value for c in row]
|
||||
if all(v is None for v in vals):
|
||||
continue
|
||||
code = _norm_code(vals[code_col] if code_col < len(vals) else None)
|
||||
if not code or code == "0":
|
||||
continue
|
||||
|
||||
def _cell(key):
|
||||
i = cols.get(key)
|
||||
return vals[i] if i is not None and i < len(vals) else None
|
||||
|
||||
result[code] = {
|
||||
"姓名": str(_cell("姓名") or ""),
|
||||
"二级部门": str(_cell("二级部门") or ""),
|
||||
"四级部门": str(_cell("四级部门") or ""),
|
||||
"岗位": str(_cell("岗位") or ""),
|
||||
"所属单位": str(_cell("所属单位") or ""),
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _load_roster_map(excel_path: str = None, roster_path: str = None) -> dict:
|
||||
"""加载花名册 roster_map:源表「附-在职花名册」→ 本地 员工花名册.xlsx。
|
||||
全部失败返回 {}(接收人解析受限但不中断流程)。"""
|
||||
excel_path = excel_path or ""
|
||||
roster_path = roster_path or ROSTER_PATH
|
||||
if excel_path:
|
||||
m = _read_roster_from_source_sheet(excel_path)
|
||||
if m:
|
||||
logger.info("花名册经源表「附-在职花名册」获取:共 %d 人", len(m))
|
||||
return m
|
||||
try:
|
||||
m = _read_roster_map(roster_path)
|
||||
logger.info("花名册经本地文件读取:共 %d 人", len(m))
|
||||
return m
|
||||
except Exception as e:
|
||||
logger.warning("本地花名册读取失败,接收人解析受限:%s", e)
|
||||
return {}
|
||||
|
||||
|
||||
def _fill_dept4(rec: dict, roster_map: dict) -> str:
|
||||
"""四级部门:源数据缺失时查花名册(按37工号),仍缺失 fallback 二级部门。"""
|
||||
dept4 = str(rec.get("四级部门") or "").strip()
|
||||
@@ -716,7 +787,7 @@ def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
|
||||
for src, std in TRANSFER_COL_MAP.items():
|
||||
if src in col_idx:
|
||||
rec[std] = _cell(vals, src)
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "备注"):
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "备注", "所属单位"):
|
||||
if key in col_idx:
|
||||
rec[key] = _cell(vals, key)
|
||||
# 参保单位全称:优先「全称」列(转移后单位全称),缺失回退「参保单位全称」列
|
||||
@@ -797,19 +868,20 @@ def _find_store_manager_in_map(roster_map: dict, code: str):
|
||||
|
||||
|
||||
def _find_hr_personnel_in_map(roster_map: dict, code: str, dept2: str = None) -> list:
|
||||
"""查人事/推送人:二级部门命中 DEPT2_PUSH_OVERRIDE(内置推送人)直接返回;
|
||||
"""查人事/推送人:二级部门(含所属单位回退值)命中 DEPT2_PUSH_OVERRIDE 直接返回;
|
||||
其次「石桥铺会馆」固定返回;经营中心下岗位含「人事」全量返回(兜底花名册查找)。
|
||||
覆盖映射不依赖员工是否在花名册。
|
||||
|
||||
dept2: 外部解析出的正确二级部门(经营中心),缺省用员工本人花名册二级部门。
|
||||
dept2: 外部解析出的正确二级部门(经营中心)/所属单位回退值,缺省用员工本人花名册二级部门。
|
||||
"""
|
||||
info = roster_map.get(code)
|
||||
if not info:
|
||||
return []
|
||||
dept2 = dept2 or info["二级部门"]
|
||||
info = roster_map.get(code) or {}
|
||||
dept2 = dept2 or info.get("二级部门") or ""
|
||||
if dept2 in DEPT2_PUSH_OVERRIDE:
|
||||
return list(DEPT2_PUSH_OVERRIDE[dept2])
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
return list(DEPT2_HR_OVERRIDE[dept2])
|
||||
if not info:
|
||||
return []
|
||||
if "经营中心" not in dept2:
|
||||
return []
|
||||
return [c for c, it in roster_map.items() if it["二级部门"] == dept2 and "人事" in it["岗位"]]
|
||||
@@ -898,12 +970,8 @@ def build_work_communication_data(branch: str, output_dir: str = None, ym: tuple
|
||||
# 数据源:按分支关键字查找当月文件(历史月份/缺失均报错)
|
||||
excel_path = _find_current_month_excel(BASE_DIR, excel_keyword)
|
||||
|
||||
# 花名册(二级部门解析/店长人事查找用),读取失败置空(后续靠兜底或跳过)
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,二级部门解析/接收人查找将受限:%s", e)
|
||||
roster_map = {}
|
||||
# 花名册(二级部门解析/店长人事查找用):源表「附-在职花名册」→ 本地文件,失败置空
|
||||
roster_map = _load_roster_map(excel_path, roster_path)
|
||||
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
|
||||
|
||||
# 按分支筛出命中员工(all_records 供参保单位聚合二级部门用)
|
||||
@@ -954,8 +1022,11 @@ def build_work_communication_data(branch: str, output_dir: str = None, ym: tuple
|
||||
continue
|
||||
d2 = _resolve_dept2(r, all_records, roster_map)
|
||||
if not d2:
|
||||
logger.error("员工「%s」无法解析二级部门(参保单位=%s),不推送该员工",
|
||||
r.get("姓名"), _ins_org_of(r))
|
||||
# 二级部门为空时不跳过:用「所属单位」列替代作为推送分组依据
|
||||
d2 = str(r.get("所属单位") or "").strip()
|
||||
if not d2:
|
||||
logger.error("员工「%s」无法解析二级部门且无所属单位,不推送该员工",
|
||||
r.get("姓名"))
|
||||
continue
|
||||
dept2_by_code[c] = d2
|
||||
codes.append(c)
|
||||
@@ -1020,11 +1091,7 @@ def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
|
||||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||||
|
||||
transfer_records, records = [], []
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,二级部门解析将受限:%s", e)
|
||||
roster_map = {}
|
||||
roster_map = _load_roster_map(excel_path, roster_path or ROSTER_PATH)
|
||||
if branch == "转移参保":
|
||||
transfer_records = _read_transfer_records(excel_path, roster_map)
|
||||
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), excel_path)
|
||||
@@ -1060,8 +1127,11 @@ def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
|
||||
for rec in matched:
|
||||
dept2 = _resolve_dept2(rec, all_records, roster_map)
|
||||
if not dept2:
|
||||
logger.error("员工「%s」无法解析二级部门(参保单位=%s),跳过生成",
|
||||
rec.get("姓名"), _ins_org_of(rec))
|
||||
# 二级部门为空时不跳过生成:用「所属单位」列替代作为分组/命名依据
|
||||
dept2 = str(rec.get("所属单位") or "").strip()
|
||||
if not dept2:
|
||||
logger.error("员工「%s」无法解析二级部门且无所属单位,跳过生成",
|
||||
rec.get("姓名"))
|
||||
continue
|
||||
rec["二级部门"] = dept2
|
||||
key = (dept2, _trans_org_of(rec))
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_points_push.py
|
||||
@Description: XQ0033 出勤积分「积分导入/积分删除」表 → OPM 平台(opm.jsyxapp.com)自动推送(独立脚本)。
|
||||
读取 attendance_points_update.py 生成的「员工出勤及遵章积分导入{MMDD}.xlsx」中的
|
||||
「积分导入」「积分删除」表,抽取 工号/姓名/积分日期,按 kaoqin.xlsx 格式
|
||||
构建上传文件,调用考勤积分上传接口推送到 OPM 平台。
|
||||
默认「试运行」:只解析 + 校验会话 + 打印待推送清单,不真传;确认无误后把
|
||||
DRY_RUN 置 False 再跑即正式推送。
|
||||
|
||||
上传端点(逆向自 /point/list 前端 chunk-6e4bc3f7/a8477964 + 实测验证):
|
||||
- 考勤导入 POST /operation/point/list/importAttendance multipart file=<kaoqin.xlsx>
|
||||
- 考勤删除 POST /operation/point/list/importAttendanceDel multipart file=<kaoqin.xlsx>
|
||||
说明:XQ0033 数据只有 工号/姓名/积分日期,恰好是 kaoqin.xlsx 模板三列;
|
||||
普通「积分导入/删除」端点(importPoints/importDelPoints)走 jifen.xlsx 模板,
|
||||
需额外填积分类别/积分条例/事件描述必填列,直接传会被服务端拒绝(实测
|
||||
“第2行积分类型不能为空”)。故出勤积分推送走考勤端点,无需备注。
|
||||
若业务需改走普通积分端点,改 IMPORT_URL/DELETE_URL 并补充 jifen 必填列映射即可。
|
||||
|
||||
登录态:复用 store_login_api.py(37du门店登录(接口版))写入的
|
||||
%LOCALAPPDATA%\\37duAutomation\\.sessions\\store_cookies.json,失效自动补登。
|
||||
|
||||
依赖:pip install requests python-dotenv openpyxl
|
||||
|
||||
运行:
|
||||
python attendance_points_push.py 试运行(默认,不真传)
|
||||
python attendance_points_push.py --push 正式推送(DRY_RUN=False)
|
||||
影刀「调用模块」:main({"push": true|false})
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import glob
|
||||
import argparse
|
||||
from datetime import date, datetime
|
||||
|
||||
import openpyxl
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 配置 ==================
|
||||
# XQ0033 目标目录与文件名前缀(与 attendance_points_update.py 一致)
|
||||
TARGET_DIR = r"D:\资料\人资\门店管理及服务岗出勤积分更新"
|
||||
FILE_PREFIX = "员工出勤及遵章积分导入"
|
||||
# 指定文件(非空则只用该文件,不自动选最新);None 自动取目录最新匹配文件
|
||||
FORCE_FILE = None
|
||||
|
||||
# 默认试运行:True 只解析校验打印清单;False 正式调用上传接口写生产数据
|
||||
DRY_RUN = True
|
||||
|
||||
SHEET_IMPORT = "积分导入"
|
||||
SHEET_DELETE = "积分删除"
|
||||
IMP_DATA_START = 4 # 数据起始行(行3为表头)
|
||||
COL_EMP_NO = 2 # B 工号
|
||||
COL_NAME = 10 # J 姓名
|
||||
COL_DATE = 11 # K 积分日期
|
||||
|
||||
# 考勤积分上传端点(出勤积分走考勤端点,见文件头说明)
|
||||
_LOGIN_PAGE_URL = os.getenv('store_login_url', '').strip() or 'https://opm.jsyxapp.com/login'
|
||||
BASE_URL = _LOGIN_PAGE_URL.split('/login')[0].rstrip('/')
|
||||
IMPORT_URL = BASE_URL + '/operation/point/list/importAttendance'
|
||||
DELETE_URL = BASE_URL + '/operation/point/list/importAttendanceDel'
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/154.0.0.0 Safari/537.36")
|
||||
_FILE_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
TIMEOUT = 30
|
||||
MAX_RETRY = 3
|
||||
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
COOKIE_FILE = os.path.join(_APP_DATA_DIR, '.sessions', 'store_cookies.json')
|
||||
|
||||
|
||||
def _log(msg):
|
||||
print(msg)
|
||||
|
||||
|
||||
# ================== 登录态 ==================
|
||||
def _load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _make_session():
|
||||
cookies = _load_cookies()
|
||||
if not cookies:
|
||||
return None
|
||||
import requests
|
||||
s = requests.Session()
|
||||
s.headers['User-Agent'] = UA
|
||||
for c in cookies:
|
||||
if c.get('domain') and 'jsyxapp.com' in c['domain']:
|
||||
s.cookies.set(c['name'], c['value'], domain=c['domain'], path=c.get('path', '/'))
|
||||
return s
|
||||
|
||||
|
||||
def _is_session_valid(session):
|
||||
import requests
|
||||
try:
|
||||
resp = session.post(BASE_URL + '/operation/user', data={}, timeout=15)
|
||||
return resp.status_code == 200 and (resp.json() or {}).get('code') == 'S0'
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_session():
|
||||
"""返回有效会话;缺失/失效时调用 store_login_api 补登(最多 MAX_RETRY 次)。"""
|
||||
import requests
|
||||
for _ in range(MAX_RETRY):
|
||||
s = _make_session()
|
||||
if s is not None and _is_session_valid(s):
|
||||
return s
|
||||
try:
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import store_login_api
|
||||
result = store_login_api.main({'force': False})
|
||||
if not result.get('success'):
|
||||
raise RuntimeError(result.get('message') or '补登失败')
|
||||
except ImportError:
|
||||
raise RuntimeError('缺少 store_login_api.py 登录模块,且无有效 store_cookies.json 登录态')
|
||||
return None
|
||||
|
||||
|
||||
# ================== 读取 XQ0033 积分表 ==================
|
||||
def _parse_date(v):
|
||||
"""K 列积分日期 → datetime(保留原样),失败返回 None。"""
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, date):
|
||||
return datetime(v.year, v.month, v.day)
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip()
|
||||
try:
|
||||
return datetime.fromisoformat(s[:19])
|
||||
except ValueError:
|
||||
try:
|
||||
return datetime.strptime(s[:10], '%Y-%m-%d')
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def read_point_sheet(path, sheet_name):
|
||||
"""读取积分导入/积分删除表 → [(工号, 姓名, 积分日期 datetime), ...]。
|
||||
跳过工号/日期为空或日期无法解析的行(表头/说明行自然排除)。"""
|
||||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||
try:
|
||||
if sheet_name not in wb.sheetnames:
|
||||
_log(f"[跳过] 工作表「{sheet_name}」不存在")
|
||||
return []
|
||||
ws = wb[sheet_name]
|
||||
rows = []
|
||||
skipped = 0
|
||||
for row in ws.iter_rows(min_row=IMP_DATA_START,
|
||||
min_col=1, max_col=COL_DATE, values_only=True):
|
||||
emp_no = str(row[COL_EMP_NO - 1]).strip() if row[COL_EMP_NO - 1] not in (None, '') else ''
|
||||
name = str(row[COL_NAME - 1]).strip() if row[COL_NAME - 1] not in (None, '') else ''
|
||||
d = _parse_date(row[COL_DATE - 1]) if COL_DATE - 1 < len(row) else None
|
||||
if not emp_no:
|
||||
continue
|
||||
if d is None:
|
||||
skipped += 1
|
||||
continue
|
||||
rows.append((emp_no, name, d))
|
||||
if skipped:
|
||||
_log(f"[警告] 「{sheet_name}」{skipped} 行积分日期无法解析已跳过")
|
||||
return rows
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def build_kaoqin_bytes(rows):
|
||||
"""[(工号,姓名,日期)] → kaoqin.xlsx 模板(工号/姓名/积分日期)字节。"""
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.append(['工号', '姓名', '积分日期'])
|
||||
for emp_no, name, d in rows:
|
||||
ws.append([emp_no, name, d])
|
||||
import io
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
# ================== 上传 ==================
|
||||
def _upload(session, url, file_bytes, filename):
|
||||
import requests
|
||||
resp = session.post(url, files={'file': (filename, file_bytes, _FILE_MIME)},
|
||||
headers={'Referer': BASE_URL + '/point/list'}, timeout=TIMEOUT)
|
||||
if resp.status_code != 200:
|
||||
return {'success': False, 'message': f'HTTP {resp.status_code}'}
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return {'success': False, 'message': '响应非 JSON'}
|
||||
ok = data.get('status') is True or data.get('code') == 'S0'
|
||||
return {'success': bool(ok), 'message': data.get('message') or ('' if ok else '导入失败')}
|
||||
|
||||
|
||||
def _push(session, url, file_bytes, label, push):
|
||||
if not push:
|
||||
return {'success': None, 'message': '试运行:未真传'}
|
||||
return _upload(session, url, file_bytes, f'{label}.xlsx')
|
||||
|
||||
|
||||
# ================== 主流程 ==================
|
||||
def pick_target_file():
|
||||
"""选择推送文件:FORCE_FILE 优先,否则目录最新匹配文件。"""
|
||||
if FORCE_FILE:
|
||||
if not os.path.isfile(FORCE_FILE):
|
||||
raise FileNotFoundError(f'FORCE_FILE 文件不存在:{FORCE_FILE}')
|
||||
return os.path.abspath(FORCE_FILE)
|
||||
if not os.path.isdir(TARGET_DIR):
|
||||
raise FileNotFoundError(f'目标目录不存在:{TARGET_DIR}')
|
||||
files = [f for f in glob.glob(os.path.join(TARGET_DIR, FILE_PREFIX + '*.xlsx'))
|
||||
if not os.path.basename(f).startswith('~$')]
|
||||
if not files:
|
||||
raise FileNotFoundError(f'目录 {TARGET_DIR} 未找到「{FILE_PREFIX}*.xlsx」文件')
|
||||
return max(files, key=os.path.getmtime)
|
||||
|
||||
|
||||
def run(push=None):
|
||||
"""执行推送。push: None→沿用 DRY_RUN;True/False→覆盖。"""
|
||||
if push is None:
|
||||
push = DRY_RUN is False
|
||||
path = pick_target_file()
|
||||
_log(f'推送文件:{path}')
|
||||
_log(f'模式:{"正式推送" if push else "试运行(不真传)"}')
|
||||
|
||||
import_rows = read_point_sheet(path, SHEET_IMPORT)
|
||||
del_rows = read_point_sheet(path, SHEET_DELETE)
|
||||
_log(f'积分导入 {len(import_rows)} 行,积分删除 {len(del_rows)} 行')
|
||||
|
||||
if not import_rows and not del_rows:
|
||||
_log('两表均无有效数据,无可推送')
|
||||
return
|
||||
|
||||
session = None
|
||||
results = {}
|
||||
for label, rows, url in (
|
||||
('积分导入', import_rows, IMPORT_URL),
|
||||
('积分删除', del_rows, DELETE_URL)):
|
||||
if not rows:
|
||||
results[label] = {'success': None, 'message': '无数据,跳过'}
|
||||
continue
|
||||
# 试运行打印清单
|
||||
_log(f'\n--- {label} → {url} ---')
|
||||
for emp_no, name, d in rows[:5]:
|
||||
_log(f' {emp_no} | {name} | {d}')
|
||||
if len(rows) > 5:
|
||||
_log(f' ... 共 {len(rows)} 行,仅预览前 5 行')
|
||||
if not push:
|
||||
results[label] = {'success': None, 'message': '试运行:未真传'}
|
||||
continue
|
||||
if session is None:
|
||||
session = _ensure_session()
|
||||
if session is None:
|
||||
raise RuntimeError('无法获取有效登录态(补登失败)')
|
||||
file_bytes = build_kaoqin_bytes(rows)
|
||||
results[label] = _push(session, url, file_bytes, label, push)
|
||||
|
||||
_log('\n===== 推送结果 =====')
|
||||
for label, res in results.items():
|
||||
_log(f'{label}: {res}')
|
||||
|
||||
if not push:
|
||||
_log('\n[提示] 试运行未调用上传接口。确认清单无误后,用 python attendance_points_push.py --push '
|
||||
'或 main({"push": true}) 正式推送。')
|
||||
return results
|
||||
|
||||
|
||||
def main(args=None):
|
||||
"""影刀「调用模块」入口。args: {"push": true|false}。"""
|
||||
if not args:
|
||||
args = {}
|
||||
try:
|
||||
return run(push=bool(args.get('push', DRY_RUN is False)))
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': f'推送过程异常:{e}'}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description='XQ0033 出勤积分推送 OPM 平台')
|
||||
parser.add_argument('--push', action='store_true', help='正式推送(默认试运行不真传)')
|
||||
parser.add_argument('--file', help='指定推送文件(覆盖 FORCE_FILE)')
|
||||
args = parser.parse_args()
|
||||
if args.file:
|
||||
FORCE_FILE = os.path.abspath(args.file)
|
||||
main({'push': args.push})
|
||||
Reference in New Issue
Block a user