Files
37duAutomation/plugins/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/data/opm_client.py
T

335 lines
14 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("OPM 登录第 %d/%d 轮", 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 登录失败(重试耗尽或接口异常):{last_msg}")
def ensure_session(self):
if self.session is not None and self.is_session_valid():
return self.session
return self.login()
def count_points(self, day, update_day=None):
"""查「积分列表」某积分日期的记录总数(只取 total,不拉数据)。
上传是按积分日期分批的,所以核对也按积分日期单日查(startDate=endDate=day);
再加更新人(默认当前登录账号)+ 更新日当天,锁定「本账号今天写入该日期的记录」。
取不到 total 时返回 None,调用方据此降级回重传确认。
"""
if self.session is None:
return None
upd = update_day or date.today()
params = {
"pageNum": 1,
"pageSize": config.OPM_LIST_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
try:
resp = self.session.get(self.list_url, params=params,
headers={"Referer": self.base_url + "/point/list",
"Accept": "application/json, text/plain, */*"},
timeout=config.OPM_QUERY_TIMEOUT)
if resp.status_code != 200:
config.logger.debug("积分列表查询 HTTP %s", resp.status_code)
return None
data = resp.json()
except Exception as e:
config.logger.debug("积分列表查询异常:%s", e)
return None
if isinstance(data, dict) and data.get("code") not in (None, "S0"):
config.logger.debug("积分列表查询返回非 S0:%s", _body_text(resp, 200))
return None
total = _extract_total(data)
config.logger.debug("积分列表查询 积分日期 %s total=%s(更新人 %s,更新日 %s)",
params["startDate"], total, params.get("updateUser", ""), upd)
return total
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 "导入失败(服务端未返回原因)"}