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:
@@ -0,0 +1,58 @@
|
||||
# 内网 37du 库 schema 快照(172.30.30.243,只读导出 2026-10-19 14:23)
|
||||
|
||||
-- ===== accounts =====
|
||||
CREATE TABLE IF NOT EXISTS `accounts` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',\n `account` varchar(64) NOT NULL COMMENT '登录账号(工号,唯一)',\n `password_hash` varchar(128) NOT NULL COMMENT '密码哈希(加盐)',\n `salt` varchar(64) NOT NULL COMMENT '密码盐值',\n `is_admin` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',\n `dept` varchar(64) NOT NULL DEFAULT '' COMMENT '所属部门',\n `nickname` varchar(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',\n `dingtalk_uid` varchar(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',\n `must_change_pwd` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',\n `avatar` varchar(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',\n `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '创建时间',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`id`),\n UNIQUE KEY `uk_account` (`account`),\n KEY `idx_dept` (`dept`)\n) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号'
|
||||
|
||||
-- ===== account_platforms =====
|
||||
CREATE TABLE IF NOT EXISTS `account_platforms` (\n `account` varchar(64) NOT NULL COMMENT '账号(工号)',\n `platform_id` varchar(64) NOT NULL COMMENT '平台ID(hr/oa 等)',\n `granted_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '授权时间',\n PRIMARY KEY (`account`,`platform_id`),\n CONSTRAINT `fk_pl_account` FOREIGN KEY (`account`) REFERENCES `accounts` (`account`) ON DELETE CASCADE\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单'
|
||||
|
||||
-- ===== account_plugins =====
|
||||
CREATE TABLE IF NOT EXISTS `account_plugins` (\n `account` varchar(64) NOT NULL COMMENT '账号(工号)',\n `plugin_id` varchar(64) NOT NULL COMMENT '插件ID',\n `can_download` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',\n `can_run` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',\n `granted_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '授权时间',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`account`,`plugin_id`),\n KEY `idx_plugin` (`plugin_id`),\n CONSTRAINT `fk_ap_account` FOREIGN KEY (`account`) REFERENCES `accounts` (`account`) ON DELETE CASCADE,\n CONSTRAINT `fk_ap_plugin` FOREIGN KEY (`plugin_id`) REFERENCES `plugins` (`id`) ON DELETE CASCADE\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)'
|
||||
|
||||
-- ===== audit_logs =====
|
||||
CREATE TABLE IF NOT EXISTS `audit_logs` (\n `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',\n `account` varchar(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',\n `action` varchar(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',\n `target` varchar(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',\n `detail` text NOT NULL COMMENT '操作详情(JSON 串)',\n `at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '操作时间',\n PRIMARY KEY (`id`),\n KEY `idx_at` (`at`),\n KEY `idx_action` (`action`),\n KEY `idx_account` (`account`)\n) ENGINE=InnoDB AUTO_INCREMENT=447 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志'
|
||||
|
||||
-- ===== auth_fail_counts =====
|
||||
CREATE TABLE IF NOT EXISTS `auth_fail_counts` (\n `account` varchar(64) NOT NULL COMMENT '登录账号(工号,主键)',\n `fails` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '连续失败次数',\n `locked_until` datetime DEFAULT NULL COMMENT '锁定截止时间(NULL=未锁定)',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`account`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录防爆破共享计数(落库,gunicorn 多 worker 通用)'
|
||||
|
||||
-- ===== chrome_releases =====
|
||||
CREATE TABLE IF NOT EXISTS `chrome_releases` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',\n `version` varchar(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',\n `url` text NOT NULL COMMENT '安装包外链下载地址',\n `filename` varchar(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',\n `sha256` char(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',\n `notes` varchar(512) NOT NULL DEFAULT '' COMMENT '说明',\n `enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源'
|
||||
|
||||
-- ===== client_creds =====
|
||||
CREATE TABLE IF NOT EXISTS `client_creds` (\n `account` varchar(64) NOT NULL COMMENT '执行机账号(工号)',\n `pubkey_pem` text NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',\n `creds` mediumtext NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`account`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)'
|
||||
|
||||
-- ===== cloud_tokens =====
|
||||
CREATE TABLE IF NOT EXISTS `cloud_tokens` (\n `token` varchar(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',\n `account` varchar(64) NOT NULL COMMENT '所属账号(工号)',\n `nickname` varchar(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',\n `expires_at` datetime NOT NULL COMMENT '过期时间(签发时间 + 7 天)',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '签发时间',\n PRIMARY KEY (`token`),\n KEY `idx_expires` (`expires_at`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)'
|
||||
|
||||
-- ===== devices =====
|
||||
CREATE TABLE IF NOT EXISTS `devices` (\n `device_id` varchar(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',\n `account` varchar(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',\n `hostname` varchar(128) NOT NULL DEFAULT '' COMMENT '主机名',\n `os` varchar(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',\n `ip` varchar(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',\n `chrome_installed` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',\n `chrome_version` varchar(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',\n `chrome_ok` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',\n `client_version` varchar(32) NOT NULL DEFAULT '' COMMENT '客户端版本',\n `last_seen` datetime NOT NULL DEFAULT current_timestamp() COMMENT '最后在线时间(心跳上报更新)',\n `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '首次上报时间',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`device_id`),\n KEY `idx_account` (`account`),\n KEY `idx_last_seen` (`last_seen`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)'
|
||||
|
||||
-- ===== download_tickets =====
|
||||
CREATE TABLE IF NOT EXISTS `download_tickets` (\n `nonce` varchar(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',\n `filename` varchar(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',\n `sha256` char(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',\n `used` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '签发时间',\n PRIMARY KEY (`nonce`),\n KEY `idx_created` (`created_at`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)'
|
||||
|
||||
-- ===== fileserver_status =====
|
||||
CREATE TABLE IF NOT EXISTS `fileserver_status` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',\n `host` varchar(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',\n `base_url` varchar(255) NOT NULL DEFAULT '' COMMENT '对外下载根',\n `hostname` varchar(128) NOT NULL DEFAULT '' COMMENT '主机名',\n `ip` varchar(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',\n `port` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '服务端口',\n `file_count` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '文件数量',\n `total_size` bigint(20) unsigned NOT NULL DEFAULT 0 COMMENT '文件总字节',\n `version` varchar(64) NOT NULL DEFAULT '' COMMENT '服务版本',\n `uptime_sec` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '进程运行秒数',\n `last_seen` datetime NOT NULL DEFAULT current_timestamp() COMMENT '最后心跳时间(心跳上报更新)',\n `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',\n `last_status_change` datetime NOT NULL DEFAULT current_timestamp() COMMENT '最近一次在线/离线切换时间',\n `offline_notified` tinyint(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '首次上报时间',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`id`),\n UNIQUE KEY `uk_host` (`host`),\n KEY `idx_status` (`status`),\n KEY `idx_last_seen` (`last_seen`)\n) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)'
|
||||
|
||||
-- ===== file_sources =====
|
||||
CREATE TABLE IF NOT EXISTS `file_sources` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',\n `category` varchar(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',\n `version` varchar(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',\n `filename` varchar(255) NOT NULL DEFAULT '' COMMENT '原文件名',\n `url` text NOT NULL COMMENT '内网文件服务器直链',\n `sha256` char(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',\n `notes` varchar(512) NOT NULL DEFAULT '' COMMENT '说明',\n `enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`id`),\n KEY `idx_category` (`category`)\n) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)'
|
||||
|
||||
-- ===== notifications =====
|
||||
CREATE TABLE IF NOT EXISTS `notifications` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '通知ID',\n `title` varchar(200) NOT NULL COMMENT '标题',\n `content` text NOT NULL COMMENT '内容',\n `level` varchar(16) NOT NULL DEFAULT 'info' COMMENT '级别:info/warning/important',\n `target` varchar(16) NOT NULL DEFAULT 'all' COMMENT '范围:all=全部账号 account=指定账号',\n `account` varchar(64) NOT NULL DEFAULT '' COMMENT 'target=account 时的目标账号',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '创建时间',\n `expires_at` datetime DEFAULT NULL COMMENT '过期时间(NULL=长期有效)',\n `active` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',\n PRIMARY KEY (`id`),\n KEY `idx_active` (`active`,`target`,`account`)\n) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='通知(管理端下发,客户端定时拉取)'
|
||||
|
||||
-- ===== plugins =====
|
||||
CREATE TABLE IF NOT EXISTS `plugins` (\n `id` varchar(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',\n `name` varchar(128) NOT NULL COMMENT '插件名称',\n `latest_version` varchar(32) NOT NULL COMMENT '最新版本号',\n `description` varchar(512) NOT NULL DEFAULT '' COMMENT '插件描述',\n `category` varchar(64) NOT NULL DEFAULT '' COMMENT '分类',\n `icon` varchar(255) NOT NULL DEFAULT '' COMMENT '图标标识',\n `status` varchar(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',\n `force_min_version` varchar(32) DEFAULT NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',\n `force_deadline` varchar(32) DEFAULT NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',\n `manifest` text DEFAULT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',\n `created_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '创建时间',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据'
|
||||
|
||||
-- ===== plugin_versions =====
|
||||
CREATE TABLE IF NOT EXISTS `plugin_versions` (\n `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',\n `plugin_id` varchar(64) NOT NULL COMMENT '所属插件ID',\n `version` varchar(32) NOT NULL COMMENT '版本号',\n `filename` varchar(255) NOT NULL COMMENT '包文件名(packages/ 下)',\n `sha256` char(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',\n `size_bytes` bigint(20) unsigned NOT NULL DEFAULT 0 COMMENT '包体积(字节)',\n `uploaded_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '上传时间',\n PRIMARY KEY (`id`),\n UNIQUE KEY `uk_plugin_version` (`plugin_id`,`version`),\n CONSTRAINT `fk_pv_plugin` FOREIGN KEY (`plugin_id`) REFERENCES `plugins` (`id`) ON DELETE CASCADE\n) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本'
|
||||
|
||||
-- ===== runtime_reports =====
|
||||
CREATE TABLE IF NOT EXISTS `runtime_reports` (\n `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',\n `account` varchar(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',\n `device_id` varchar(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',\n `plugin_id` varchar(64) NOT NULL DEFAULT '' COMMENT '插件ID',\n `version` varchar(32) NOT NULL DEFAULT '' COMMENT '插件版本号',\n `status` varchar(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',\n `msg` text NOT NULL COMMENT '结果/错误信息',\n `duration_sec` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',\n `at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '上报时间',\n PRIMARY KEY (`id`),\n KEY `idx_at` (`at`),\n KEY `idx_account_at` (`account`,`at`),\n KEY `idx_plugin_at` (`plugin_id`,`at`),\n KEY `idx_status_at` (`status`,`at`)\n) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报'
|
||||
|
||||
-- ===== schedule_backups =====
|
||||
CREATE TABLE IF NOT EXISTS `schedule_backups` (\n `account` varchar(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',\n `data` mediumtext NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`account`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)'
|
||||
|
||||
-- ===== schema_migrations =====
|
||||
CREATE TABLE IF NOT EXISTS `schema_migrations` (\n `version` varchar(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',\n `applied_at` datetime NOT NULL DEFAULT current_timestamp() COMMENT '迁移执行时间',\n PRIMARY KEY (`version`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本'
|
||||
|
||||
-- ===== system_settings =====
|
||||
CREATE TABLE IF NOT EXISTS `system_settings` (\n `key` varchar(64) NOT NULL COMMENT '配置键',\n `value` text NOT NULL COMMENT '配置值(JSON 文本)',\n `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '更新时间',\n PRIMARY KEY (`key`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置'
|
||||
@@ -48,7 +48,7 @@ class ChongqingSocialChangePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0008"
|
||||
name = "重庆社保增减员办理"
|
||||
version = "1.0.3"
|
||||
version = "1.0.5"
|
||||
description = ("重庆社保增减员全流程(XQ0008 名单制作 + XQ0014 系统办理/核查回盘 + "
|
||||
"XQ0015/XQ0016 告知书制作下发):目录预检、增/减员名单制作、增/减员系统办理、"
|
||||
"增/减员核查回盘、告知书制作与 OA 推送八阶段可选串行。逐参保单位读取台账账号"
|
||||
@@ -142,6 +142,12 @@ class ChongqingSocialChangePlugin(ScenePlugin):
|
||||
|
||||
def _run_notice(self, ctx):
|
||||
"""告知书制作:生成三类告知书 + 构造 OA 推送数据;按开关自动推送。"""
|
||||
# 花名册优先走 HR 接口取数(需已登录 HR);未登录/失效时回退源表「附-在职花名册」/本地文件
|
||||
try:
|
||||
config.set_hr_session(ctx.get_session("hr"))
|
||||
except Exception as e:
|
||||
config.set_hr_session(None)
|
||||
ctx.log(f"HR 登录态不可用,花名册将回退源表/本地文件:{e}", "WARN")
|
||||
result = notice_gen.make_notices()
|
||||
summary_parts = [f"生成 {result['total']} 份告知书(docx+pdf)",
|
||||
f"构造 {result['messages_count']} 条 OA 推送数据"]
|
||||
|
||||
@@ -242,13 +242,15 @@ LEGACY_PLACEHOLDERS = {
|
||||
"{{当前月+1}}": "{{下月}}",
|
||||
"{{费用*2}}": "{{一次性扣款}}",
|
||||
}
|
||||
# 二级部门(经营中心)推送人映射(优先于花名册人事查找)
|
||||
# 推送人映射:键可为「二级部门(经营中心)」或「二级部门为空时的所属单位回退值」(如 水庄大鹅事业部)。
|
||||
# 优先于花名册人事查找(覆盖映射不依赖员工是否在花名册)。
|
||||
DEPT2_PUSH_OVERRIDE = {
|
||||
"金色印象海口经营中心": ["37000700"],
|
||||
"金色印象昆明经营中心": ["37002511"],
|
||||
"金色印象南宁经营中心": ["37009626"],
|
||||
"金色印象深圳经营中心": ["37018211"],
|
||||
"金色印象郑州经营中心": ["37006992"],
|
||||
"水庄大鹅事业部": ["37036104"], # 所属单位回退值(非二级部门),直接推送 37036104 唐佳膑
|
||||
}
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]}
|
||||
CC_RECEIVER_NAME = "周卫"
|
||||
@@ -483,6 +485,19 @@ def get_oa_session():
|
||||
return _oa_session
|
||||
|
||||
|
||||
# ==================== 花名册数据源钩子(run() 注入) ====================
|
||||
_hr_session = None # 底座注入的 HR requests.Session(花名册接口取数用,未登录为 None)
|
||||
|
||||
|
||||
def set_hr_session(session):
|
||||
global _hr_session
|
||||
_hr_session = session
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
return _hr_session
|
||||
|
||||
|
||||
# ==================== 通用辅助 ====================
|
||||
def _to_text(value):
|
||||
"""转可写文本:证件号/电话等长数字统一为字符串,避免丢精度/科学计数。"""
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
OA 工作沟通推送数据:build_work_communication_data 构造后落盘到
|
||||
{输出}/YYYYMM/oa_messages.json;真实 OA 推送由 __init__ 阶段(启用推送开关时)调 oa_push 完成。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
@@ -24,7 +25,7 @@ import random
|
||||
import functools
|
||||
import subprocess
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from .. import config
|
||||
|
||||
@@ -434,6 +435,246 @@ def _read_roster_map(roster_path: str) -> dict:
|
||||
wb.close()
|
||||
|
||||
|
||||
# ==================== 花名册数据源:HR 接口 → 源表「附-在职花名册」→ 本地文件 ====================
|
||||
# HR 花名册直查接口(与共享模块 roster_export_api.py 同款参数,插件自包含复刻)
|
||||
_HR_API_ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
_HR_API_LIST_URL = (f"https://hr.37du.co/RedseaPlatform/hrRoster/"
|
||||
f"{_HR_API_ROSTER_ID}/getCustomCommonList.mc")
|
||||
_HR_API_BASE_PARAMS = {
|
||||
"menuName": "员工花名册", "useSealTreeData": "0", "treePermitType": "permit",
|
||||
"cancelNodeClick": "1", "clickFlag": "true", "in_use": "1", "commonQuery": "",
|
||||
"newCondition": "", "urlConditions": "", "exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base", "rosterId": _HR_API_ROSTER_ID,
|
||||
"includeChildrenSetting": "", "struTreeCode": "cq37du", "djStruTreeCode": "",
|
||||
"djStruId": "", "djOrgName": "", "struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28", "rootId": "cq37du",
|
||||
"isVirtual": "0", "currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform", "qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团", "belongUnitOrgName": "集团", "throughParam": "",
|
||||
"start": "0", "sortType": "", "sortName": "", "pageNo": "1", "pageSize": "15",
|
||||
"dataIds": "", "hideCols": "",
|
||||
}
|
||||
_HR_API_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_HR_API_PAD = '7'
|
||||
_HR_API_SALT = "yyryrtweasdasd"
|
||||
|
||||
|
||||
def _hr_base64_encode(data):
|
||||
"""HR commonQuery 自定义字符表 Base64(与前端/共享模块一致)。"""
|
||||
out = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
if len(chunk) == 1:
|
||||
enc3 = enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
out.append(_HR_API_CHARS[enc1])
|
||||
out.append(_HR_API_CHARS[enc2])
|
||||
out.append(_HR_API_CHARS[enc3])
|
||||
out.append(_HR_API_CHARS[enc4])
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _hr_encode_common_query(query_list):
|
||||
"""把查询条件加密为 commonQuery(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
import urllib.parse
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(",", ":"))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _hr_base64_encode(uri_encoded.encode("utf-8")) + _HR_API_SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
def _hr_in_service_conditions():
|
||||
"""在职人员查询条件:主职 in (1) + 在职状态 in (1)。"""
|
||||
def cond(field, qtype, value, input_type, left="", right="", logic="AND"):
|
||||
return {"queryField": field, "leftBracket": left, "queryType": qtype,
|
||||
"queryValue": value, "queryText": value, "rightBracket": right,
|
||||
"logic": logic, "inputType": input_type}
|
||||
return [
|
||||
cond("`pt_staff_stru.POST_STRU_ID`", "in", "1", "select", left="(", right=")"),
|
||||
cond("`hr_staff_base.person_status`", "in", "1", "multipleSelect", left="(", right=")"),
|
||||
]
|
||||
|
||||
|
||||
def _hr_date_params():
|
||||
"""HR 接口动态日期参数(当月/上月/当年首月)。"""
|
||||
now = datetime.now()
|
||||
last_month = datetime(now.year, now.month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": now.strftime("%Y-%m-%d"),
|
||||
"currentMonth": now.strftime("%Y%m"),
|
||||
"currentMonthBar": now.strftime("%Y-%m"),
|
||||
"lastMonth": last_month.strftime("%Y%m"),
|
||||
"lastMonFirstDay": last_month.strftime("%Y-%m-01"),
|
||||
"lastMonLastDay": last_month.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{now.year}01",
|
||||
"curYearFirstMonBar": f"{now.year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _hr_pick(row: dict, candidates: tuple):
|
||||
"""按候选 key(先精确后包含)从 API 行取字段值。"""
|
||||
low = {str(k).lower(): v for k, v in row.items() if isinstance(k, str)}
|
||||
for cand in candidates:
|
||||
if cand in low:
|
||||
return low[cand]
|
||||
for k, v in low.items():
|
||||
for cand in candidates:
|
||||
if cand in k:
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def _roster_rows_to_map(rows: list) -> dict:
|
||||
"""API 返回行转 roster_map({工号: {姓名, 二级部门, 四级部门, 岗位, 所属单位}})。"""
|
||||
result = {}
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
code = _norm_code(_hr_pick(row, ("base_code", "工号", "staff_code", "code")))
|
||||
if not code:
|
||||
continue
|
||||
result[code] = {
|
||||
"姓名": str(_hr_pick(row, ("staff_name", "姓名", "name")) or ""),
|
||||
"二级部门": str(_hr_pick(row, ("dept_org_two", "二级部门", "dept2", "DEPT_ORG_TWO")) or ""),
|
||||
"四级部门": str(_hr_pick(row, ("dept_org_four", "四级部门", "dept4", "DEPT_ORG_FOUR")) or ""),
|
||||
"岗位": str(_hr_pick(row, ("post_org_name", "岗位", "post", "POST_ORG_NAME")) or ""),
|
||||
"所属单位": str(_hr_pick(row, ("belong_unit_org_name", "所属单位", "BELONG_UNIT_ORG_NAME")) or ""),
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def _fetch_roster_map_via_api(session) -> dict:
|
||||
"""直连 HR 花名册接口拉取在职人员 roster_map;任一环节失败返回 {}(由调用方回退)。"""
|
||||
if session is None:
|
||||
return {}
|
||||
params = {k: str(v) for k, v in _HR_API_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = _hr_encode_common_query(_hr_in_service_conditions())
|
||||
params.update(_hr_date_params())
|
||||
headers = {"X-Requested-With": "XMLHttpRequest"}
|
||||
rows, page_no = [], 1
|
||||
for _ in range(50): # 分页上限
|
||||
params.update({"pageNo": str(page_no), "pageSize": "10000",
|
||||
"start": str((page_no - 1) * 10000),
|
||||
"_t": str(int(time.time() * 1000))})
|
||||
try:
|
||||
resp = session.post(_HR_API_LIST_URL, data=params, headers=headers, timeout=30)
|
||||
except Exception as e:
|
||||
logger.warning("花名册 HR 接口请求失败,回退其他数据源:%s", e)
|
||||
return {}
|
||||
text = (resp.text or "").strip() if resp is not None else ""
|
||||
if not text.startswith(("{", "[")):
|
||||
logger.warning("花名册 HR 接口返回异常/登录态失效,回退其他数据源")
|
||||
return {}
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return {}
|
||||
if str(data.get("state") or "") in ("Nosession", "Login"):
|
||||
logger.warning("花名册 HR 接口会话过期,请在工作台重新登录 HR")
|
||||
return {}
|
||||
jl = data.get("jsonList") or []
|
||||
if not jl:
|
||||
break
|
||||
rows.extend(jl)
|
||||
total = data.get("total")
|
||||
try:
|
||||
total_n = int(total) if total not in (None, "") else len(rows)
|
||||
except (TypeError, ValueError):
|
||||
total_n = len(rows)
|
||||
if len(rows) >= total_n:
|
||||
break
|
||||
page_no += 1
|
||||
if not rows:
|
||||
return {}
|
||||
return _roster_rows_to_map(rows)
|
||||
|
||||
|
||||
def _read_roster_from_source_sheet(excel_path: str) -> dict:
|
||||
"""读取源表内嵌「附-在职花名册」sheet 构建 roster_map(与业务同文件同月份,数据可靠)。"""
|
||||
import openpyxl
|
||||
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:HR 接口 → 源表「附-在职花名册」→ 本地 员工花名册.xlsx。
|
||||
全部失败返回 {}(接收人解析受限但不中断流程)。"""
|
||||
excel_path = excel_path or ""
|
||||
roster_path = roster_path or _roster_path()
|
||||
hr_session = config.get_hr_session()
|
||||
if hr_session is not None:
|
||||
m = _fetch_roster_map_via_api(hr_session)
|
||||
if m:
|
||||
logger.info("花名册经 HR 接口获取:共 %d 人", len(m))
|
||||
return m
|
||||
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()
|
||||
@@ -481,7 +722,7 @@ def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
|
||||
for src, std in config.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)
|
||||
full_key = "全称" if "全称" in col_idx else "参保单位全称"
|
||||
@@ -550,15 +791,16 @@ 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 直接返回;其次石桥铺会馆固定;再兜底岗位含人事。"""
|
||||
info = roster_map.get(code)
|
||||
if not info:
|
||||
return []
|
||||
dept2 = dept2 or info["二级部门"]
|
||||
"""查人事/推送人:二级部门(含所属单位回退值)命中 DEPT2_PUSH_OVERRIDE 直接返回;
|
||||
其次石桥铺会馆固定;再兜底岗位含人事。覆盖映射不依赖员工是否在花名册。"""
|
||||
info = roster_map.get(code) or {}
|
||||
dept2 = dept2 or info.get("二级部门") or ""
|
||||
if dept2 in config.DEPT2_PUSH_OVERRIDE:
|
||||
return list(config.DEPT2_PUSH_OVERRIDE[dept2])
|
||||
if dept2 in config.DEPT2_HR_OVERRIDE:
|
||||
return list(config.DEPT2_HR_OVERRIDE[dept2])
|
||||
if not info:
|
||||
return []
|
||||
if "经营中心" not in dept2:
|
||||
return []
|
||||
return [c for c, it in roster_map.items()
|
||||
@@ -626,11 +868,7 @@ def build_work_communication_data(branch: str, output_dir: str = None, ym: tuple
|
||||
|
||||
logger.info("构造 OA 工作沟通数据:分支=%s(%d-%02d)", branch, y, m)
|
||||
excel_path = _find_current_month_excel(_base_dir())
|
||||
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)
|
||||
|
||||
matched_by_rule = {}
|
||||
@@ -674,8 +912,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)
|
||||
@@ -730,11 +971,7 @@ def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
|
||||
excel_path = _find_current_month_excel(_base_dir())
|
||||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||||
|
||||
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)
|
||||
@@ -766,8 +1003,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))
|
||||
|
||||
@@ -147,13 +147,22 @@ def upload_attachment(session, file_path):
|
||||
|
||||
# 2) 上传二进制
|
||||
uploader_url = f"{config.ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
with open(file_path, "rb") as f:
|
||||
files = {"file": (file_name, f, file_type)}
|
||||
data2 = {"id": "WU_FILE_0", "name": file_name, "type": file_type,
|
||||
"lastModifiedDate": last_modified, "size": file_size}
|
||||
resp2 = _check_response(session.post(uploader_url, data=data2, files=files,
|
||||
timeout=60, headers=_DEFAULT_HEADERS),
|
||||
"附件上传-二进制")
|
||||
# 底座注入的共享会话默认带 Content-Type: application/x-www-form-urlencoded,
|
||||
# 会导致 requests 在 files 上传时不再自动生成 multipart/form-data 边界头,
|
||||
# 服务端(Apache Commons FileUpload)以 InvalidContentTypeException 拒绝。
|
||||
# 上传前临时清除该默认头,让 requests 生成正确的 multipart 请求,随后恢复。
|
||||
saved_ct = session.headers.pop("Content-Type", None)
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
files = {"file": (file_name, f, file_type)}
|
||||
data2 = {"id": "WU_FILE_0", "name": file_name, "type": file_type,
|
||||
"lastModifiedDate": last_modified, "size": file_size}
|
||||
resp2 = _check_response(session.post(uploader_url, data=data2, files=files,
|
||||
timeout=60, headers=_DEFAULT_HEADERS),
|
||||
"附件上传-二进制")
|
||||
finally:
|
||||
if saved_ct is not None:
|
||||
session.headers["Content-Type"] = saved_ct
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0008",
|
||||
"name": "重庆社保增减员办理",
|
||||
"version": "1.0.4",
|
||||
"version": "1.0.5",
|
||||
"description": "重庆社保增减员全流程(XQ0008 名单制作 + XQ0014 系统办理/核查回盘 + XQ0015/XQ0016 告知书制作下发):目录预检、增/减员名单制作、增/减员系统办理、增/减员核查回盘、告知书制作与 OA 推送八阶段可选串行。逐参保单位读取台账账号登录重庆人社政务平台(法人用户+图形验证码识别)完成导入申报、审核结论核查与回盘表核对,回写源名单办理状态/办理停保及备注;生成三类告知书并构造 OA 工作沟通推送,全程 JSON 缓存防崩溃、结束统一落盘。",
|
||||
"category": "社保",
|
||||
"icon": "",
|
||||
|
||||
@@ -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})
|
||||
@@ -0,0 +1,285 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: store_login_api.py
|
||||
@Description: 门店/运营管理平台(OPM,opm.jsyxapp.com)纯接口登录(无浏览器版),
|
||||
「37du门店登录(接口版)」影刀自定义指令模块源码。
|
||||
输出与既有登录指令完全兼容:
|
||||
- 登录态落盘 %LOCALAPPDATA%\\37duAutomation\\.sessions\\store_cookies.json;
|
||||
- cookies 结构一致(name/value/domain/path/expires),业务脚本零改动;
|
||||
- 配置读取一致(根 .env 的 store_login_url / store_login_username /
|
||||
store_login_password);
|
||||
- 对外入口 main(args) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录,不打开浏览器。
|
||||
|
||||
登录链路(逆向自前端 SPA webpack 模块 2836/5a71 + 2026-10-19 实测验证):
|
||||
1. GET /login 建立会话:服务端下发会话 cookie
|
||||
(server_session_<hash>,Secure/HttpOnly;同域任意首个请求即下发,
|
||||
登录后绑定该会话与账号,靠会话 cookie 维持登录态);
|
||||
2. POST /operation/login 提交登录(前端 axios 以 qs 序列化,form-urlencoded 明文提交,
|
||||
密码无任何加密,见 app.js 模块 2836 a() = post("/operation/login", form)):
|
||||
body: username=<urlencoded>&password=<明文密码>
|
||||
成功:{"code":"S0","data":{"userid":"167","username":"陈莲"},"message":"操作成功","status":true}
|
||||
失败(账号/密码错):{"code":"E10002","data":null,"message":"用户名/密码不正确","status":false}
|
||||
3. POST /operation/user 会话校验:返回 code=="S0" 视为登录态有效;
|
||||
未登录返回 {"code":"E401","message":"未登录","status":false}。
|
||||
校验通过后 cookies 落盘 store_cookies.json。
|
||||
|
||||
配置(读根目录 .env:d:\\work\\code\\37duAutomation\\.env,与浏览器版 store_login 一致):
|
||||
store_login_url= 登录页地址(默认 https://opm.jsyxapp.com/login,用于推导接口 base)
|
||||
store_login_username= 用户名(如 陈莲)
|
||||
store_login_password= 密码
|
||||
store_validate_url=(可选)会话校验接口 URL;默认 POST /operation/user
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python store_login_api.py 独立运行(等价 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与既有登录指令统一) ==================
|
||||
_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')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# workflows/ 影刀脚本统一使用项目根 .env(本文件位于 workflows/share/ 下,向上三级为项目根)
|
||||
_ROOT_ENV_FILE = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先共享 .env,再加载项目根 .env,最后兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
if os.path.exists(_ROOT_ENV_FILE):
|
||||
load_dotenv(_ROOT_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
_load_shared_env()
|
||||
LOGIN_PAGE_URL = os.getenv('store_login_url', '').strip() or 'https://opm.jsyxapp.com/login'
|
||||
# 接口 base = 登录页 origin(如 https://opm.jsyxapp.com)
|
||||
BASE_URL = LOGIN_PAGE_URL.split('/login')[0].rstrip('/')
|
||||
LOGIN_POST_URL = BASE_URL + '/operation/login'
|
||||
VALIDATE_URL = os.getenv('store_validate_url', '').strip() or (BASE_URL + '/operation/user')
|
||||
USERNAME = os.getenv('store_login_username', '')
|
||||
PASSWORD = os.getenv('store_login_password', '')
|
||||
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/154.0.0.0 Safari/537.36")
|
||||
FORM_CT = "application/x-www-form-urlencoded;charset=UTF-8"
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 hr/oa 登录指令兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与既有登录指令(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== 会话校验(与浏览器版 store_login 同款逻辑) ==================
|
||||
def _is_store_session_valid(session=None):
|
||||
"""API 轻量校验门店平台登录态:POST /operation/user,
|
||||
返回 code=="S0" 视为 cookies 有效;code=="E401"(未登录) 或其他即失效。
|
||||
session 缺省时从 COOKIE_FILE 读入 cookies 新建会话(复用缓存场景);
|
||||
传入时直接校验该会话(登录后落盘前使用)。"""
|
||||
try:
|
||||
if session is None:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": UA})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "jsyxapp.com" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(VALIDATE_URL, data={}, timeout=TIMEOUT)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return False
|
||||
return isinstance(data, dict) and data.get("code") == "S0"
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程(纯接口) ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(server_session_*/JSESSIONID),登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Referer": LOGIN_PAGE_URL,
|
||||
"Origin": BASE_URL,
|
||||
})
|
||||
s.get(LOGIN_PAGE_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:明文表单提交 /operation/login -> 会话校验 -> 落盘。
|
||||
返回 (ok, message)。账号密码错误等凭据类拒绝不重试,网络类异常按轮重试。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = session.post(
|
||||
LOGIN_POST_URL,
|
||||
data={"username": username, "password": password},
|
||||
headers={
|
||||
"Content-Type": FORM_CT,
|
||||
"Referer": LOGIN_PAGE_URL,
|
||||
"Origin": BASE_URL,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
},
|
||||
timeout=TIMEOUT)
|
||||
except Exception as e:
|
||||
print(f"提交登录异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
if resp.status_code != 200:
|
||||
print(f"登录接口状态码异常:{resp.status_code}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
print("登录响应非 JSON")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
if not (isinstance(data, dict) and data.get("code") == "S0"):
|
||||
# 凭据错误(E10002 用户名/密码不正确)/被拒,重试无意义,直接返回服务端提示
|
||||
msg = data.get("message") if isinstance(data, dict) else str(resp.text[:200])
|
||||
return False, f"登录被拒绝(账号或密码错误?):{msg}"
|
||||
|
||||
# 落盘前先校验本次登录的会话真实可用,确保业务脚本拿到的登录态有效
|
||||
if _is_store_session_valid(session):
|
||||
save_session_cookies(session)
|
||||
return True, "登录成功"
|
||||
print("登录接口返回成功但会话校验未通过")
|
||||
time.sleep(1)
|
||||
return False, "登录失败(重试耗尽或接口异常)"
|
||||
|
||||
|
||||
# ================== 登录主入口(与既有登录指令同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的门店平台登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 注意:模块加载后 USERNAME/PASSWORD 已从 .env 读取,若运行时才补配置需刷新
|
||||
global USERNAME, PASSWORD
|
||||
USERNAME = os.getenv('store_login_username', '')
|
||||
PASSWORD = os.getenv('store_login_password', '')
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(store_login_username / store_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_store_session_valid():
|
||||
print("已通过缓存的 Cookies 复用门店平台登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok, msg = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次落盘 cookies 可用性,确保业务脚本拿到的登录态真实有效
|
||||
if _is_store_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "message": msg, "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37du门店登录(接口版)」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": True})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- 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')
|
||||
_SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
_ROOT_ENV_FILE = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), '.env')
|
||||
|
||||
|
||||
def _load_env():
|
||||
if os.path.exists(_SHARED_ENV_FILE):
|
||||
load_dotenv(_SHARED_ENV_FILE)
|
||||
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", "备注") # 积分删除')
|
||||
Reference in New Issue
Block a user