Files
37duAutomation/plugins/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/data/opm_client.py
T
puddy 3a72637aa3 fix(xq0033): 积分上传防重复加分并按工号核对结果(1.0.18)
- 上传前:该积分日期当天已有写入记录时先判断本批是否已导过,避免重复加分

- 上传后无回执:查「积分列表」明细按工号核对,能确认即判成功,不必重传同一份文件;任一环节取不到(接口异常/无权限/字段缺失)自动降级回重传确认
2026-11-06 15:52:01 +08:00

393 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0033 插件 - OPM 平台(opm.jsyxapp.com)自包含客户端。
- 登录:GET /login 建立会话 → POST /operation/login(明文表单)→ POST /operation/user 校验 code=="S0";
- 上传:常驻会话 multipart 提交「积分导入(考勤导入)」「积分删除(考勤删除)」;
- 账号密码由界面配置注入(fields.opm_username / opm_password),不读取其它模块的会话文件。
"""
import io
import time
from datetime import date, datetime
import openpyxl
import requests
from .. import config
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
FORM_CT = "application/x-www-form-urlencoded;charset=UTF-8"
FILE_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
LOGIN_ROUND_MAX = 3
TIMEOUT = 15
COL_EMP_NO = 2 # B 工号
COL_NAME = 10 # J 姓名
COL_DATE = 11 # K 积分日期
class OPMLoginError(RuntimeError):
"""OPM 登录失败(账号密码缺失/被拒绝/网络异常)。"""
# ==================== 读取工作簿积分表 ====================
def _parse_date(v):
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:
config.logger.warning("OPM 推送:工作表「%s」不存在,跳过", sheet_name)
return []
ws = wb[sheet_name]
rows = []
skipped = 0
for row in ws.iter_rows(min_row=config.IMP_DATA_START,
min_col=1, max_col=COL_DATE, values_only=True):
if len(row) < COL_DATE:
continue
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 not emp_no:
continue
if d is None:
skipped += 1
continue
rows.append((emp_no, name, d))
if skipped:
config.logger.warning("OPM 推送:「%s」%d 行积分日期无法解析已跳过", sheet_name, skipped)
return rows
finally:
wb.close()
def build_kaoqin_bytes(rows):
"""[(工号,姓名,日期)] → kaoqin.xlsx 字节(三列,与官方模板一致)。"""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Sheet1"
ws.append(["工号", "姓名", "积分日期"])
for i, (emp_no, name, d) in enumerate(rows, start=2):
ws.cell(row=i, column=1, value=emp_no)
ws.cell(row=i, column=2, value=name)
ws.cell(row=i, column=3, value=d)
ws.cell(row=i, column=3).number_format = "yyyy/m/d"
buf = io.BytesIO()
wb.save(buf)
return buf.getvalue()
# ==================== 响应诊断 ====================
def _body_text(resp, limit=300):
"""取响应体文本片段(诊断「响应非 JSON」到底返回了什么)。"""
body = resp.content or b""
if not body:
return ""
txt = None
for enc in ("utf-8", "gbk"):
try:
txt = body.decode(enc)
break
except UnicodeDecodeError:
continue
if txt is None:
txt = body.decode("utf-8", "replace")
txt = " ".join(txt.split())
return txt[:limit] + ("…" if len(txt) > limit else "")
def _looks_like_login_page(txt):
low = (txt or "").lower()
return "<html" in low or "<!doctype" in low or ("<form" in low and "password" in low)
def _fmt_msg(msg, limit=500):
"""服务端 message 多为多行逐行提示,压成单行,保留更多内容。"""
txt = ";".join(x.strip() for x in str(msg or "").splitlines() if x.strip())
return txt[:limit] + ("…" if len(txt) > limit else "")
_TOTAL_KEYS = ("total", "totalcount", "totalnum", "totalsize", "recordstotal", "records")
def _extract_total(data):
"""从分页响应里取总条数(字段名各版本不一,按常见命名递归查找)。"""
if isinstance(data, dict):
for k, v in data.items():
if str(k).lower() in _TOTAL_KEYS and isinstance(v, (int, float)) \
and not isinstance(v, bool):
return int(v)
for v in data.values():
if isinstance(v, (dict, list)):
got = _extract_total(v)
if got is not None:
return got
elif isinstance(data, list):
for v in data:
got = _extract_total(v)
if got is not None:
return got
return None
# ==================== 客户端 ====================
class OPMClient:
"""OPM 登录 + 考勤积分上传(积分导入 / 积分删除)。"""
def __init__(self, login_url=None, username="", password=""):
self.login_url = (login_url or config.DEFAULT_OPM_URL).strip()
self.base_url = self.login_url.split("/login")[0].rstrip("/")
self.username = (username or "").strip()
self.password = (password or "").strip() # 防误存首尾空格导致密码不正确
self.import_url = self.base_url + config.OPM_IMPORT_PATH
self.delete_url = self.base_url + config.OPM_DELETE_PATH
self.validate_url = self.base_url + "/operation/user"
self.list_url = self.base_url + config.OPM_LIST_PATH
self.session = None
def _new_session(self):
s = requests.Session()
s.headers.update({"User-Agent": UA, "Referer": self.login_url,
"Origin": self.base_url})
s.get(self.login_url, timeout=TIMEOUT)
return s
def _warm_up(self, session):
"""对齐浏览器上下文:正式上传都在「积分列表」页发起,登录后先 GET 一次该页。"""
try:
session.get(self.base_url + "/point/list", timeout=TIMEOUT)
except Exception:
pass
def is_session_valid(self, session=None):
session = session or self.session
if session is None:
return False
try:
resp = session.post(self.validate_url, data={}, timeout=TIMEOUT)
if resp.status_code != 200:
return False
data = resp.json()
return isinstance(data, dict) and data.get("code") == "S0"
except Exception:
return False
def login(self):
"""完整接口登录(最多 LOGIN_ROUND_MAX 轮);成功返回已校验的会话。"""
if not (self.username and self.password):
raise OPMLoginError("OPM 账号或密码未配置,请在插件配置中填写后重试")
last_msg = ""
for rnd in range(1, LOGIN_ROUND_MAX + 1):
config.logger.info("第 %d/%d 次尝试登录 OPM 系统……", rnd, LOGIN_ROUND_MAX)
try:
session = self._new_session()
except Exception as e:
last_msg = f"建立会话异常:{e}"
time.sleep(1)
continue
try:
resp = session.post(
self.base_url + "/operation/login",
data={"username": self.username, "password": self.password},
headers={"Content-Type": FORM_CT, "Referer": self.login_url,
"Origin": self.base_url,
"Accept": "application/json, text/plain, */*"},
timeout=TIMEOUT)
except Exception as e:
last_msg = f"提交登录异常:{e}"
time.sleep(1)
continue
if resp.status_code != 200:
last_msg = f"登录接口 HTTP {resp.status_code}"
time.sleep(1)
continue
try:
data = resp.json()
except Exception:
last_msg = "登录响应非 JSON"
time.sleep(1)
continue
if not (isinstance(data, dict) and data.get("code") == "S0"):
msg = data.get("message") if isinstance(data, dict) else resp.text[:200]
raise OPMLoginError(f"OPM 登录被拒绝(账号或密码错误?):{msg}")
if self.is_session_valid(session):
self.session = session
self._warm_up(session)
config.logger.info("OPM 系统登录成功")
return session
last_msg = "登录接口返回成功但会话校验未通过"
time.sleep(1)
raise OPMLoginError(f"OPM 登录失败(已尝试 {LOGIN_ROUND_MAX} 次):{last_msg}")
def ensure_session(self):
if self.session is not None and self.is_session_valid():
return self.session
return self.login()
def _list_params(self, day, update_day=None, page_size=1, page_num=1):
"""「积分列表」查询参数:按积分日期单日 + 更新人(默认当前账号)+ 更新日当天。
锁定的是「本账号今天写入该日期的记录」,所以核对结果只反映本插件的写入。
"""
upd = update_day or date.today()
params = {
"pageNum": page_num,
"pageSize": page_size,
"startDate": day.strftime("%Y-%m-%d"),
"endDate": day.strftime("%Y-%m-%d"),
"updateTimeStart": f"{upd:%Y-%m-%d} 00:00:00",
"updateTimeEnd": f"{upd:%Y-%m-%d} 23:59:59",
}
user = config.OPM_LIST_UPDATE_USER or self.username
if user:
params["updateUser"] = user
if config.OPM_LIST_HIERARCHY_IDS:
params["hierarchyIds"] = config.OPM_LIST_HIERARCHY_IDS
return params
def _query_list(self, day, update_day=None, page_size=1, page_num=1, timeout=None):
"""请求一次「积分列表」,返回 (params, data);失败返回 (params, None)。"""
params = self._list_params(day, update_day, page_size, page_num)
try:
resp = self.session.get(self.list_url, params=params,
headers={"Referer": self.base_url + "/point/list",
"Accept": "application/json, text/plain, */*"},
timeout=timeout or config.OPM_QUERY_TIMEOUT)
if resp.status_code != 200:
config.logger.debug("积分列表查询 HTTP %s", resp.status_code)
return params, None
data = resp.json()
except Exception as e:
config.logger.debug("积分列表查询异常:%s", e)
return params, None
if isinstance(data, dict) and data.get("code") not in (None, "S0"):
config.logger.debug("积分列表查询返回非 S0:%s", _body_text(resp, 200))
return params, None
return params, data
def count_points(self, day, update_day=None):
"""查「积分列表」某积分日期的记录条数(只取 total,不拉明细)。
取不到 total 时返回 None,调用方据此降级回重传确认。
"""
if self.session is None:
return None
params, data = self._query_list(day, update_day, config.OPM_LIST_PAGE_SIZE, 1)
if data is None:
return None
total = _extract_total(data)
config.logger.debug("积分列表查询:积分日期 %s,更新人 %s,更新日 %s,该日期现有 %s 条积分记录",
params["startDate"], params.get("updateUser", ""),
params["updateTimeStart"][:10], total)
return total
def fetch_day_point_codes(self, day, update_day=None):
"""查某积分日期「本账号今天写入」的全部积分明细 → (total, {工号: {积分项名称}})。
OPM 对每个员工每个积分日期可能生成多条明细(实测「有效出勤」+「遵章守纪」,
1 人 1 天 1~2 条),所以按条数核对会把「只写进去一部分人」误判成成功;
这里拉到明细后按工号核对,才能确认本批每个人到底有没有写进去。
取不到(接口异常/无权限/字段缺失)时返回 (None, None),调用方降级回重传确认。
"""
if self.session is None:
return None, None
codes, total, fetched, page = {}, None, 0, 1
while page <= config.OPM_LIST_MAX_PAGES:
params, data = self._query_list(day, update_day,
config.OPM_LIST_DETAIL_PAGE_SIZE, page,
config.OPM_DETAIL_TIMEOUT)
if data is None:
return None, None
body = data.get("data") if isinstance(data, dict) else None
if not isinstance(body, dict):
return None, None
total = _extract_total(body)
rows = None
for key in ("list", "records", "rows", "content"):
if isinstance(body.get(key), list):
rows = body[key]
break
if rows is None:
return None, None
for rec in rows:
if not isinstance(rec, dict):
continue
code = str(rec.get("staffNo") or rec.get("staffCode") or "").strip()
if not code:
continue
codes.setdefault(code, set()).add(str(rec.get("pointTypeName") or ""))
fetched += len(rows)
if not rows or (total is not None and fetched >= total):
break
page += 1
config.logger.debug("积分明细核对:积分日期 %s,明细 %s 条,涉及 %d 人",
params["startDate"], total, len(codes))
return (total if total is not None else fetched), codes
def upload(self, url, file_bytes, filename):
"""上传单个文件,返回 {success, message, kind}。
kind 用于上层判断该不该重登/重传:
ok 服务端明确成功
benign 服务端提示「已存在/未生成出勤积分」等,目标状态已达成(算成功)
notfound 会话失效(拿到登录页/HTML),必须重登后再试
unknown 响应非 JSON 或空响应,无法确认结果,需重传确认
http HTTP 非 200
error 服务端明确失败
"""
try:
resp = self.session.post(
url, files={"file": (filename, file_bytes, FILE_MIME)},
headers={"Referer": self.base_url + "/point/list"}, timeout=config.OPM_TIMEOUT)
except Exception as e:
return {"success": False, "kind": "error", "message": f"上传异常:{e}"}
if resp.status_code != 200:
snippet = _body_text(resp, 200)
msg = f"HTTP {resp.status_code}" + (f"({snippet})" if snippet else "")
return {"success": False,
"kind": "notfound" if resp.status_code in (401, 403) else "http",
"message": msg}
try:
data = resp.json()
except Exception:
snippet = _body_text(resp)
if not snippet:
return {"success": False, "kind": "unknown",
"message": "系统没有返回任何内容(HTTP 200 空响应)"}
kind = "notfound" if _looks_like_login_page(snippet) else "unknown"
ctype = resp.headers.get("content-type", "")
return {"success": False, "kind": kind,
"message": f"响应非 JSON(HTTP 200,{ctype or '无 content-type'}):{snippet}"}
if not isinstance(data, dict):
return {"success": False, "kind": "unknown",
"message": f"响应格式异常:{_body_text(resp, 150)}"}
ok = data.get("status") is True or data.get("code") == "S0"
msg = _fmt_msg(data.get("message"))
if ok:
return {"success": True, "kind": "ok", "message": msg}
if msg and any(k in msg for k in config.OPM_BENIGN_MSGS):
# 逐行提示里既有「已存在/未生成」又有「失败/不存在」等硬错误时不能算成功
if not any(k in msg for k in config.OPM_FATAL_MSGS):
return {"success": True, "kind": "benign",
"message": f"系统提示这些人的积分已存在或无需处理(目标状态已达成):{msg}"}
return {"success": False, "kind": "error",
"message": msg or "系统没有说明失败原因"}