# -*- coding: utf-8 -*- """ @FileName: store_point_api.py @Description: 门店/运营管理平台(OPM,opm.jsyxapp.com)积分批量导入/删除纯接口实现, 与「37du门店登录(接口版)」store_login_api.py 配套使用。 登录态复用 store_cookies.json(失效时自动调用 store_login_api 补登), 全程 requests 完成,不打开浏览器。 接口逆向(chunk-6e4bc3f7.js 组件 data + chunk-a8477964.js API 模块 + 2026-10-19 实测验证): 页面「积分记录 /point/list」上的「批量添加/删除」弹层包含: 1. 积分导入 -> POST /operation/point/list/importPoints multipart:file = Excel(字段名固定 file,accept .xls/.xlsx) 2. 积分模板 -> GET /operation/static/jifen.xlsx (模板下载,非接口) 3. 积分删除 -> POST /operation/point/list/importDelPoints multipart:file = Excel + remark = 必填备注 (前端 beforeDelUpload 弹窗强制填写备注后才允许上传) 4. 积分作废 -> POST /operation/point/list/importInvalidPoints (同类文件) 同域其它导入端点(考勤导入/删除,chunk-a8477964 同时定义): 5. 考勤积分导入 -> POST /operation/point/list/importAttendance(模板 /operation/static/kaoqin.xlsx) 6. 考勤积分删除 -> POST /operation/point/list/importAttendanceDel Excel 模板结构(/operation/static/jifen.xlsx,积分导入/删除/作废同用): 列1 工号 | 列2 姓名 | 列3 积分日期 | 列4 积分类别 | 列5 积分条例 | 列6 数量(选填)| 列7 分值(选填)| 列8 事件描述(必填) (积分日期需可被服务端解析;条例不匹配则该行不导入,导入后触发积分流程审批) kaoqin.xlsx 模板:列1 工号 | 列2 姓名 | 列3 积分日期 响应统一:{"code":"S0","message":"导入成功","status":true} 成功; {"code":"E500","message":"第2行积分类型不能为空","status":false} 失败(HTTP 200,按 code/status 判定)。 实测:无效文件上传后服务端返回行级校验错误(如「第2行积分类型不能为空」/「无效id」), 证明端点、multipart 字段名(file)、remark 字段均与逆向一致。 入口: import_points(xlsx_path) 积分导入,返回 dict {success, message, data} delete_points(xlsx_path, remark) 积分删除(remark 必填),返回 dict {success, message, data} python store_point_api.py 独立运行(示例:对给定文件执行导入/删除) 依赖:requests python-dotenv openpyxl(读文件内容生成 multipart;模板文件用 openpyxl 组织数据) """ import io import os import json import requests from dotenv import load_dotenv # ================== 共享路径(与 store_login_api.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') COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'store_cookies.json') _ROOT_ENV_FILE = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), '.env') def _load_env(): """统一加载配置:只读项目根 .env,缺失时再兼容当前工作目录 .env。""" if os.path.exists(_ROOT_ENV_FILE): load_dotenv(_ROOT_ENV_FILE) load_dotenv() _load_env() # ================== 接口常量 ================== _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_POINTS_URL = BASE_URL + '/operation/point/list/importPoints' # 积分导入 DELETE_POINTS_URL = BASE_URL + '/operation/point/list/importDelPoints' # 积分删除 # 逆向过程中一并确认的同域端点(备用,当前主函数不调用) _IMPORT_ATTENDANCE_URL = BASE_URL + '/operation/point/list/importAttendance' _DELETE_ATTENDANCE_URL = BASE_URL + '/operation/point/list/importAttendanceDel' _CANCEL_POINTS_URL = BASE_URL + '/operation/point/list/importInvalidPoints' TEMPLATE_URL = BASE_URL + '/operation/static/jifen.xlsx' # 积分模板下载 UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "Chrome/154.0.0.0 Safari/537.36") TIMEOUT = 30 # multipart 固定文件名与 MIME(服务端按 .xls/.xlsx 解析,字段名必须 file) _FILE_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' _RETRY_MAX = 3 # 登录态失效自动补登上限 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(): """由 store_cookies.json 构建已登录 requests.Session。""" cookies = _load_cookies() if not cookies: return None 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): """会话校验:POST /operation/user 返回 code=="S0" 视为有效(与 store_login_api 同款)。""" try: resp = session.post(BASE_URL + '/operation/user', data={}, timeout=15) if resp.status_code != 200: return False data = resp.json() return isinstance(data, dict) and data.get('code') == 'S0' except Exception: return False def _ensure_session(): """返回有效登录会话;cookies 缺失/失效时调用 store_login_api 补登(最多 _RETRY_MAX 次)。""" for _ in range(_RETRY_MAX): s = _make_session() if s is not None and _is_session_valid(s): return s # 补登:复用 store_login_api(其内部会校验缓存并落盘新 cookies) try: 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 def _read_file_bytes(file_path): """读取 xls/xlsx 文件字节;.xlsx 允许传入 openpyxl.Workbook 对象(内部序列化)。""" if hasattr(file_path, 'save'): # openpyxl Workbook 对象 buf = io.BytesIO() file_path.save(buf) return buf.getvalue(), 'points.xlsx' if not os.path.exists(file_path): raise FileNotFoundError(f'积分文件不存在:{file_path}') name = os.path.basename(file_path) return open(file_path, 'rb').read(), name def _upload(session, url, file_path, remark=None): """统一 multipart 上传(走已登录 session):field=file(+ 可选 remark),返回服务端 JSON dict。""" data, name = _read_file_bytes(file_path) form = {'remark': remark} if remark else {} files = {'file': (name, data, _FILE_MIME)} resp = session.post(url, files=files, data=form or None, headers={'Referer': BASE_URL + '/point/list'}, timeout=TIMEOUT) if resp.status_code != 200: return {'code': f'HTTP{resp.status_code}', 'message': f'接口状态码异常:{resp.status_code}', 'status': False} try: return resp.json() except Exception: return {'code': 'EJSON', 'message': '响应非 JSON', 'status': False} def _call(endpoint, file_path, remark=None): """执行上传并统一解析结果;会话失效时自动补登重试一次。""" for attempt in range(_RETRY_MAX): session = _ensure_session() if session is None: return {'success': False, 'message': '无法获取有效登录态(补登失败)'} resp_json = _upload(session, endpoint, file_path, remark) if resp_json.get('code') == 'E401': # 会话失效:强制补登后重试 try: import store_login_api store_login_api.main({'force': True}) except Exception: pass continue ok = resp_json.get('status') is True or resp_json.get('code') == 'S0' return {'success': bool(ok), 'message': resp_json.get('message') or ('' if ok else '导入失败'), 'data': resp_json.get('data')} return {'success': False, 'message': '接口调用失败(重试耗尽)'} # ================== 对外主函数 ================== def import_points(file_path): """积分导入:上传 jifen.xlsx 模板格式的 Excel。 file_path: 本地 xls/xlsx 路径,或 openpyxl.Workbook 对象。 返回 dict {success, message, data}。""" return _call(IMPORT_POINTS_URL, file_path) def delete_points(file_path, remark): """积分删除:上传 jifen.xlsx 模板格式的 Excel + 必填备注。 remark: 备注字符串(服务端必填,前端弹窗强制输入)。 返回 dict {success, message, data}。""" remark = (remark or '').strip() if not remark: return {'success': False, 'message': '积分删除必须填写备注(remark)'} return _call(DELETE_POINTS_URL, file_path, remark) def download_template(save_path=None): """下载积分导入模板(/operation/static/jifen.xlsx)到本地。 save_path 缺省保存到当前目录 jifen.xlsx;返回保存路径。""" resp = requests.get(TEMPLATE_URL, headers={'User-Agent': UA}, timeout=TIMEOUT) if resp.status_code != 200: raise RuntimeError(f'模板下载失败:HTTP {resp.status_code}') save_path = save_path or os.path.join(os.getcwd(), 'jifen.xlsx') with open(save_path, 'wb') as f: f.write(resp.content) return save_path # ================== 独立运行示例 ================== if __name__ == '__main__': print('store_point_api 用法示例:') print(' from store_point_api import import_points, delete_points') print(' import_points("员工出勤及遵章积分导入1019.xlsx") # 积分导入') print(' delete_points("员工出勤及遵章积分导入1019.xlsx", "备注") # 积分删除')