feat: 新增社保减员核查脚本及相关配置优化

- 新增停保核查脚本 check_review_stop.py
- 优化社保增减员路径配置,合并台账目录
- 调整商户分组名称为综合门店
- 新增 Chrome 密码设置配置,关闭保存密码弹窗
- 优化源文件筛选规则,收紧为社保变更文件
- 新增 VC 运行库复制到构建脚本,解决 DLL 加载问题
- 升级通联数据导出插件版本至 1.0.12,更新描述
This commit is contained in:
2026-09-30 09:39:12 +08:00
parent bf4f72cb01
commit 6afae1f67f
20 changed files with 2436 additions and 340 deletions
+361 -202
View File
@@ -1,208 +1,367 @@
{
"code": 200,
"msg": "Success",
"data": [
{
"store_id": 36,
"open_store_id": "00162",
"brand_id": 1,
"brand_name": "金色印象",
"store_name": "加州CEO会馆",
"store_address": null,
"store_phone": null,
"store_longitude": null,
"store_latitude": null,
"center_name": "金色印象事业部",
"part_name": "第三片区",
"store_manager": "黄凤",
"store_manager_phone": null,
"store_visible": true,
"store_key": "95682799-5af7-4ff6-8e15-695eaa7fb12a",
"store_photo": null,
"store_no": null,
"extra": null,
"hr_json_extra": {
"beginDate": "2022-01-21 00:00:00",
"branchLeaderCode": "37027103",
"branchLeaderId": "e1360067-9871-451d-97d3-b168df74ce82",
"branchLeaderName": "李燕",
"cantCode": "500000",
"cantName": "重庆市",
"costOrgCode": null,
"costOrgId": null,
"costOrgName": null,
"country": "",
"createTime": "2022-01-21 15:03:58",
"endDate": null,
"extendItems": [
{
"columnComment": "发薪日",
"columnName": "ext_payday",
"columnValue": "11"
},
{
"columnComment": "办公详细地址",
"columnName": "ext_office_address",
"columnValue": ""
},
{
"columnComment": "负责人编码",
"columnName": "ext_principal_num",
"columnValue": ""
}
],
"foundDate": "2022-01-21",
"foundReason": null,
"globalOrder": "1106109101110101",
"hrbpCode": null,
"hrbpId": null,
"hrbpLeaderCode": null,
"hrbpLeaderId": null,
"hrbpLeaderName": null,
"hrbpName": null,
"inUse": "1",
"kqCommissionerCode": null,
"kqCommissionerId": null,
"kqCommissionerName": null,
"manageOrgCode": null,
"manageOrgName": null,
"manageStaff": null,
"manageStaffCode": null,
"manageStaffId": null,
"manageStruId": null,
"officeAddress": "1",
"operateTime": "2026-08-03 09:19:01",
"orgCode": "00162",
"orgFullPath": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第三片区-加州CEO会馆",
"orgId": "2acb10bd-cbdb-4ebf-86a3-980de8b35dca",
"orgName": "加州CEO会馆",
"orgTypeCode": "49",
"orgTypeName": "会馆",
"parentOrgCode": "00144",
"parentOrgId": "33562286-627b-4f33-8dbc-53947be08f05",
"parentOrgName": "第三片区",
"principalStaff": "黄凤",
"principalStaffCode": "37000189",
"principalStaffId": "4b5105b8-7a9f-11ec-b449-000c296f9469",
"remarks": null,
"salaryCommissionerCode": null,
"salaryCommissionerId": null,
"salaryCommissionerName": null,
"shortName": "加州CEO会馆",
"struOrder": 101.0,
"unitOrgCode": "00738",
"unitOrgId": "0bcdee12-e592-11ee-b449-000c296f9469",
"unitOrgName": "金色印象事业部"
"code": "10000",
"msg": null,
"subCode": "200",
"subMsg": "",
"data": {
"bws071": null,
"bws072": null,
"aab003": null,
"aab001": "20445751",
"aab004": null,
"aaa121": "Z1002",
"aac002": "510222197804160909",
"aac003": "孙智慧",
"aac005": null,
"aac007": null,
"aab120": null,
"aab121": null,
"aab122": null,
"aac020": null,
"aca111": null,
"aac060": null,
"aac009": null,
"aae005": null,
"aac011": null,
"aai030": null,
"aaj030": null,
"aak030": null,
"aal030": null,
"aam034": null,
"aai031": null,
"aae013": null,
"aab020": null,
"aac014": null,
"aac001": "2061656779",
"aad030": "2026/6/29",
"aad013": "在职人员主动解除劳动合同",
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": "3 劳动者自愿辞职",
"aae201": null,
"aab084": null,
"aab085": null,
"aab086": null,
"aae202": null,
"aae500": null,
"aae501": null,
"aae036": null,
"aae100": null,
"itmes": [
{
"bws071": null,
"bws072": null,
"aab003": null,
"aab001": null,
"aab004": null,
"aaa121": null,
"aac002": null,
"aac003": null,
"aac005": null,
"aac007": null,
"aab120": null,
"aab121": null,
"aab122": null,
"aac020": null,
"aca111": null,
"aac060": null,
"aac009": null,
"aae005": null,
"aac011": null,
"aai030": null,
"aaj030": null,
"aak030": null,
"aal030": null,
"aam034": null,
"aai031": null,
"aae013": null,
"aab020": null,
"aac014": null,
"aac001": "2061656779",
"aad030": "2026/6/29",
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aae201": null,
"aab084": null,
"aab085": null,
"aab086": null,
"aae202": null,
"aae500": null,
"aae501": null,
"aae036": null,
"aae100": null,
"itmes": null,
"xh": "1",
"sxjg": null,
"aae140": "养老保险",
"aae035": null,
"asl001": null,
"aac004": null,
"aac091": null,
"aae038": null,
"aae040": null,
"aae041": null
},
"crm_json_extra": {
"host": "https://api.shuhe.crm.waf.37du.co",
"shop_id": "10085",
"shop_key": "fT3vJb1SmF7RfHBQ4NWds9fJYl7gywMi",
"sign_key": "EQO2dQLKw9UAshwYRbzlKRB51MYdEEeW"
{
"bws071": null,
"bws072": null,
"aab003": null,
"aab001": null,
"aab004": null,
"aaa121": null,
"aac002": null,
"aac003": null,
"aac005": null,
"aac007": null,
"aab120": null,
"aab121": null,
"aab122": null,
"aac020": null,
"aca111": null,
"aac060": null,
"aac009": null,
"aae005": null,
"aac011": null,
"aai030": null,
"aaj030": null,
"aak030": null,
"aal030": null,
"aam034": null,
"aai031": null,
"aae013": null,
"aab020": null,
"aac014": null,
"aac001": "2061656779",
"aad030": "2026/6/29",
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aae201": null,
"aab084": null,
"aab085": null,
"aab086": null,
"aae202": null,
"aae500": null,
"aae501": null,
"aae036": null,
"aae100": null,
"itmes": null,
"xh": "2",
"sxjg": null,
"aae140": "失业保险",
"aae035": null,
"asl001": null,
"aac004": null,
"aac091": null,
"aae038": null,
"aae040": null,
"aae041": null
},
"created_at": "2025-07-20T18:43:49.549716",
"updated_at": "2026-09-22T11:14:08.172785"
},
{
"store_id": 71,
"open_store_id": "00615",
"brand_id": 1,
"brand_name": "金色印象",
"store_name": "爱琴海行政会馆",
"store_address": null,
"store_phone": null,
"store_longitude": null,
"store_latitude": null,
"center_name": "金色印象事业部",
"part_name": "第一片区",
"store_manager": "吴俊良",
"store_manager_phone": null,
"store_visible": true,
"store_key": "5d771409-0f4a-458a-ae2d-fb862af7f652",
"store_photo": null,
"store_no": null,
"extra": null,
"hr_json_extra": {
"beginDate": "2023-10-12 00:00:00",
"branchLeaderCode": "37027103",
"branchLeaderId": "e1360067-9871-451d-97d3-b168df74ce82",
"branchLeaderName": "李燕",
"cantCode": "",
"cantName": "",
"costOrgCode": null,
"costOrgId": null,
"costOrgName": null,
"country": "",
"createTime": "2023-10-12 16:50:45",
"endDate": null,
"extendItems": [
{
"columnComment": "发薪日",
"columnName": "ext_payday",
"columnValue": "11"
},
{
"columnComment": "办公详细地址",
"columnName": "ext_office_address",
"columnValue": ""
},
{
"columnComment": "负责人编码",
"columnName": "ext_principal_num",
"columnValue": ""
}
],
"foundDate": "2023-10-12",
"foundReason": null,
"globalOrder": "1106109103109104",
"hrbpCode": null,
"hrbpId": null,
"hrbpLeaderCode": null,
"hrbpLeaderId": null,
"hrbpLeaderName": null,
"hrbpName": null,
"inUse": "1",
"kqCommissionerCode": null,
"kqCommissionerId": null,
"kqCommissionerName": null,
"manageOrgCode": null,
"manageOrgName": null,
"manageStaff": null,
"manageStaffCode": null,
"manageStaffId": null,
"manageStruId": null,
"officeAddress": "1",
"operateTime": "2026-08-03 09:19:01",
"orgCode": "00615",
"orgFullPath": "集团-金色印象事业部-第一大区-金色印象渝北经营中心-第一片区-爱琴海行政会馆",
"orgId": "6e8c42f6-68dc-11ee-b449-000c296f9469",
"orgName": "爱琴海行政会馆",
"orgTypeCode": "49",
"orgTypeName": "会馆",
"parentOrgCode": "00150",
"parentOrgId": "c4e6c766-c59d-4cf3-a99f-33aa2496eb35",
"parentOrgName": "第一片区",
"principalStaff": "吴俊良",
"principalStaffCode": "37000565",
"principalStaffId": "51711788-7a9f-11ec-b449-000c296f9469",
"remarks": null,
"salaryCommissionerCode": null,
"salaryCommissionerId": null,
"salaryCommissionerName": null,
"shortName": "爱琴海行政会馆",
"struOrder": 104.0,
"unitOrgCode": "00738",
"unitOrgId": "0bcdee12-e592-11ee-b449-000c296f9469",
"unitOrgName": "金色印象事业部"
{
"bws071": null,
"bws072": null,
"aab003": null,
"aab001": null,
"aab004": null,
"aaa121": null,
"aac002": null,
"aac003": null,
"aac005": null,
"aac007": null,
"aab120": null,
"aab121": null,
"aab122": null,
"aac020": null,
"aca111": null,
"aac060": null,
"aac009": null,
"aae005": null,
"aac011": null,
"aai030": null,
"aaj030": null,
"aak030": null,
"aal030": null,
"aam034": null,
"aai031": null,
"aae013": null,
"aab020": null,
"aac014": null,
"aac001": "2061656779",
"aad030": "2026/6/29",
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aae201": null,
"aab084": null,
"aab085": null,
"aab086": null,
"aae202": null,
"aae500": null,
"aae501": null,
"aae036": null,
"aae100": null,
"itmes": null,
"xh": "3",
"sxjg": null,
"aae140": "医疗保险",
"aae035": null,
"asl001": null,
"aac004": null,
"aac091": null,
"aae038": null,
"aae040": null,
"aae041": null
},
"crm_json_extra": {
"host": "https://api.shuhe.crm.waf.37du.co",
"shop_id": "2010247",
"shop_key": "2UHRmwKS2qTes7dY7czK39241WLQccwe",
"sign_key": "nYXTVTgfgKmNm9uxFRWvY82PRLQFqC7q"
{
"bws071": null,
"bws072": null,
"aab003": null,
"aab001": null,
"aab004": null,
"aaa121": null,
"aac002": null,
"aac003": null,
"aac005": null,
"aac007": null,
"aab120": null,
"aab121": null,
"aab122": null,
"aac020": null,
"aca111": null,
"aac060": null,
"aac009": null,
"aae005": null,
"aac011": null,
"aai030": null,
"aaj030": null,
"aak030": null,
"aal030": null,
"aam034": null,
"aai031": null,
"aae013": null,
"aab020": null,
"aac014": null,
"aac001": "2061656779",
"aad030": "2026/6/29",
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aae201": null,
"aab084": null,
"aab085": null,
"aab086": null,
"aae202": null,
"aae500": null,
"aae501": null,
"aae036": null,
"aae100": null,
"itmes": null,
"xh": "4",
"sxjg": null,
"aae140": "工伤保险",
"aae035": null,
"asl001": null,
"aac004": null,
"aac091": null,
"aae038": null,
"aae040": null,
"aae041": null
},
"created_at": "2025-07-20T18:43:49.685611",
"updated_at": "2026-09-22T11:14:18.896622"
}
]
{
"bws071": null,
"bws072": null,
"aab003": null,
"aab001": null,
"aab004": null,
"aaa121": null,
"aac002": null,
"aac003": null,
"aac005": null,
"aac007": null,
"aab120": null,
"aab121": null,
"aab122": null,
"aac020": null,
"aca111": null,
"aac060": null,
"aac009": null,
"aae005": null,
"aac011": null,
"aai030": null,
"aaj030": null,
"aak030": null,
"aal030": null,
"aam034": null,
"aai031": null,
"aae013": null,
"aab020": null,
"aac014": null,
"aac001": "2061656779",
"aad030": "2026/6/29",
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aae201": null,
"aab084": null,
"aab085": null,
"aab086": null,
"aae202": null,
"aae500": null,
"aae501": null,
"aae036": null,
"aae100": null,
"itmes": null,
"xh": "5",
"sxjg": null,
"aae140": "生育保险",
"aae035": null,
"asl001": null,
"aac004": null,
"aac091": null,
"aae038": null,
"aae040": null,
"aae041": null
}
],
"xh": null,
"sxjg": null,
"aae140": null,
"aae035": null,
"asl001": "10047223466559",
"aac004": null,
"aac091": null,
"aae038": null,
"aae040": null,
"aae041": null
}
}
+40 -73
View File
File diff suppressed because one or more lines are too long
@@ -145,6 +145,22 @@ if (Test-Path $PyWin32Sys) {
Write-Host "pywin32 DLLs copied to interpreter root"
}
# copy VC++ runtime DLLs next to the interpreter: onnxruntime/opencv .pyd
# depends on msvcp140.dll / msvcp140_1.dll etc. On machines without VC++
# 2015-2022 Redistributable the plugin fails with "DLL load failed while
# importing onnxruntime_pybind11_state" (1.1.1 只拷了 3 个,漏了 msvcp140_1.dll,
# 无 VC 运行库的客户机必现). VC++ redist DLLs are redistributable (MS license).
foreach ($dll in (Get-ChildItem -Path $env:SystemRoot\System32 -Filter "*.dll" |
Where-Object { $_.Name -match '^(msvcp140|vcruntime140)' })) {
Copy-Item $dll.FullName -Destination $PyDir -Force
Write-Host " VC runtime: $($dll.Name)"
}
$VcCount = (Get-ChildItem -Path $PyDir -Filter "*.dll" |
Where-Object { $_.Name -match '^(msvcp140|vcruntime140)' }).Count
if ($VcCount -lt 3) {
throw "VC++ runtime DLLs incomplete ($VcCount): install VC++ 2015-2022 Redistributable x64 on this build machine first"
}
# ---------- 3. webhost runtime subset ----------
$Wb = Join-Path $Repo "desktop\webhost\backend"
$EnvWb = Join-Path $PyDir "webhost\backend"
@@ -188,6 +204,7 @@ Write-Host "=== smoke test ===" -ForegroundColor Cyan
if ($LASTEXITCODE -ne 0) { throw "core deps import failed" }
& $PyExe -c "import DrissionPage; print(' DrissionPage', DrissionPage.__version__)" | Out-Host
& $PyExe -c "import ddddocr; print(' ddddocr ok')" | Out-Host
& $PyExe -c "import onnxruntime; print(' onnxruntime', onnxruntime.__version__)" | Out-Host
& $PyExe -c "import win32com.client; print(' win32com ok')" | Out-Host
Push-Location $PyDir
try {
@@ -50,7 +50,7 @@ pip install pandas openpyxl xlrd xlwt xlutils
| 变量 | 必填 | 说明 |
| ---------------------- | -- | ----------------------------------------- |
| `cq_social_change_dir` | 否 | 资料根目录,默认 `D:\资料\人资\重庆社保增减员导入名单制作`(增/停保共用) |
| `cq_social_change_dir` | 否 | 资料根目录,默认 `D:\资料\人资\重庆社保增减员办理`(增/停保共用,台账已合并同目录) |
## 4. 代码结构
@@ -138,9 +138,9 @@ pip install pandas openpyxl xlrd xlwt xlutils
## 6. 数据流
```
cq_social_change_dir(环境变量 / 默认 D:\资料\人资\重庆社保增减员导入名单制作)
cq_social_change_dir(环境变量 / 默认 D:\资料\人资\重庆社保增减员办理)
↓
find_source_file(*社保*.xlsx 取最新) + find_template_file(增员/减员模版.xls)
find_source_file(*社保变更*.xlsx 取最新) + find_template_file(增员/减员模版.xls)
→ find_source_sheet(匹配 参保名单 / 停保名单,header 第3行)
→ pd.read_excel(增员按列 str:身份证/电话;停保全列 dtype=str)
→ 筛选 区域=重庆(增员再按参保类型)→ groupby(参保单位)
@@ -35,7 +35,7 @@
| 增员导入模板 | 《增员模版.xls》(`.xls` 老格式,含 Sheet2 下拉字典) | 增员名单底稿 |
| 减员导入模板 | 《减员模版.xls》(含二级代码下拉字典) | 停保名单底稿 |
> 资料根目录:默认 `D:\资料\人资\重庆社保增减员导入名单制作`,可用环境变量 `cq_social_change_dir` 覆盖。
> 资料根目录:默认 `D:\资料\人资\重庆社保增减员办理`(与台账《社保户头管理台账》合并同目录),可用环境变量 `cq_social_change_dir` 覆盖。
## 4. 填表规则(业务口径)
@@ -12,7 +12,7 @@
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月;
- 交易查询 xlsx 下载后自动按商户分组拆成 3 个工作簿:金色印象门店(5 家门店商户)、
- 交易查询 xlsx 下载后自动按商户分组拆成 3 个工作簿:综合门店(5 家门店商户)、
品牌管理公司(重庆金色印象品牌管理有限公司)、其他账号(其余商户),原全量文件保留。
"""
import os
@@ -63,10 +63,10 @@ def _build_tasks(mode, day_date, month_date):
class TongLianExportPlugin(ScenePlugin):
id = "xq0045_xq0046"
name = "金色印象通联数据导出"
version = "1.0.11"
version = "1.0.12"
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
"账号全量数据导出(含全部商户),服务端生成文件直存本地,"
"并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿")
"并按商户分组自动拆分为综合门店/品牌管理公司/其他账号 3 个工作簿")
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
uses_month = False
capabilities = ["xq0045_xq0046"]
@@ -156,7 +156,7 @@ class TongLianExportPlugin(ScenePlugin):
ctx.log(" 开始下载导出文件…")
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
saved.append(path)
# 按商户分组拆分(金色印象门店/品牌管理公司/其他账号),失败不影响原始文件
# 按商户分组拆分(综合门店/品牌管理公司/其他账号),失败不影响原始文件
try:
ctx.log(" 按商户分组拆分为 3 个工作簿…")
saved.extend(xlsx_split.split_trx_file(path))
@@ -24,11 +24,11 @@ EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
EXPORT_ALL = 'all' # 导出全部(默认用这个)
# ==================== 交易查询结果按商户分组拆分 ====================
# 交易查询 xlsx 下载后自动拆成 3 个工作簿:命中组1 → 金色印象门店,命中组2 → 品牌管理公司,
# 交易查询 xlsx 下载后自动拆成 3 个工作簿:命中组1 → 综合门店,命中组2 → 品牌管理公司,
# 其余全部 → 其他账号;匹配规则=商户名称精确匹配(仅统一全角括号与首尾空白)。
# 每个拆分工作簿保留原文件两个 sheet(sheet1 交易明细 + 汇总),各自按本表商户名称列过滤。
SPLIT_GROUPS = [
("金色印象门店", [
("综合门店", [
"南岸区金色印象足浴馆227601",
"南岸区子石印象足浴馆(个体工商户)329909",
"九龙坡区金印养生足浴馆600402",
@@ -2,8 +2,8 @@
"schema_version": 1,
"id": "xq0045_xq0046",
"name": "金色印象通联数据导出",
"version": "1.0.11",
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿",
"version": "1.0.12",
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为综合门店/品牌管理公司/其他账号 3 个工作簿",
"category": "报表",
"icon": "",
"platform": "",
+4 -4
View File
@@ -12,7 +12,7 @@
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月;
- 交易查询 xlsx 下载后自动按商户分组拆成 3 个工作簿:金色印象门店(5 家门店商户)、
- 交易查询 xlsx 下载后自动按商户分组拆成 3 个工作簿:综合门店(5 家门店商户)、
品牌管理公司(重庆金色印象品牌管理有限公司)、其他账号(其余商户),原全量文件保留。
"""
import os
@@ -63,10 +63,10 @@ def _build_tasks(mode, day_date, month_date):
class TongLianExportPlugin(ScenePlugin):
id = "xq0045_xq0046"
name = "金色印象通联数据导出"
version = "1.0.11"
version = "1.0.12"
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
"账号全量数据导出(含全部商户),服务端生成文件直存本地,"
"并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿")
"并按商户分组自动拆分为综合门店/品牌管理公司/其他账号 3 个工作簿")
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
uses_month = False
capabilities = ["xq0045_xq0046"]
@@ -156,7 +156,7 @@ class TongLianExportPlugin(ScenePlugin):
ctx.log(" 开始下载导出文件…")
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
saved.append(path)
# 按商户分组拆分(金色印象门店/品牌管理公司/其他账号),失败不影响原始文件
# 按商户分组拆分(综合门店/品牌管理公司/其他账号),失败不影响原始文件
try:
ctx.log(" 按商户分组拆分为 3 个工作簿…")
saved.extend(xlsx_split.split_trx_file(path))
+2 -2
View File
@@ -24,11 +24,11 @@ EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
EXPORT_ALL = 'all' # 导出全部(默认用这个)
# ==================== 交易查询结果按商户分组拆分 ====================
# 交易查询 xlsx 下载后自动拆成 3 个工作簿:命中组1 → 金色印象门店,命中组2 → 品牌管理公司,
# 交易查询 xlsx 下载后自动拆成 3 个工作簿:命中组1 → 综合门店,命中组2 → 品牌管理公司,
# 其余全部 → 其他账号;匹配规则=商户名称精确匹配(仅统一全角括号与首尾空白)。
# 每个拆分工作簿保留原文件两个 sheet(sheet1 交易明细 + 汇总),各自按本表商户名称列过滤。
SPLIT_GROUPS = [
("金色印象门店", [
("综合门店", [
"南岸区金色印象足浴馆227601",
"南岸区子石印象足浴馆(个体工商户)329909",
"九龙坡区金印养生足浴馆600402",
+2 -2
View File
@@ -2,8 +2,8 @@
"schema_version": 1,
"id": "xq0045_xq0046",
"name": "金色印象通联数据导出",
"version": "1.0.11",
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿",
"version": "1.0.12",
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为综合门店/品牌管理公司/其他账号 3 个工作簿",
"category": "报表",
"icon": "",
"platform": "",
@@ -25,7 +25,7 @@
pip install pandas openpyxl xlrd xlwt xlutils
环境变量(.env 文件或系统变量,可选):
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员办理)
运行:python generate_add.py
(如需强制生成指定类型:python 中调用 generate_add.process_add_members('新参保'))
@@ -58,9 +58,10 @@ except ImportError as _import_err:
)
# ==================== 1. 文件路径配置 ====================
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员办理"
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
SOURCE_GLOB = "*社保*.xlsx"
# (收紧为 *社保变更*,避免误命中同目录的《社保户头管理台账.xlsx》)
SOURCE_GLOB = "*社保变更*.xlsx"
# 增员导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
TEMPLATE_FILE = "增员模版.xls"
# 输出子目录(按参保类型分文件夹:新参保 / 转移参保 各存一份,避免混放)
@@ -5,13 +5,15 @@
@CreateTime: 2026-09-05
@Description: XQ0008 重庆社保停保导入名单制作 —— 单文件自包含版(影刀直接运行)
与 generate_add.py(增员)同套实现方式:xlrd 读取 + xlutils 复制模板,保留下拉字典与样式。
1. 读取《XX月社保变更及增减名单》中【停保名单】sheet(表头在第3行),
筛选【区域=重庆】的记录(身份证/社保编号按文本读取,防丢精度)
1. 读取《XX月社保变更及增减名单》中【当前月份停保名单】sheet(如 202609停保名单,
表头在第3行),筛选【类型=停保/转移停保】∩【区域=重庆】∩【办理停保为空】的记录
(身份证/社保编号按文本读取,防丢精度)
2. 按【参保单位】分组,复制《减员模版.xls》(保留下拉字典 二级代码),
写入 B1(单位社保号)/D1(单位全称) 及 B4 起的数据行,逐单位另存为
《XX减员导入名单.xls》至 BASE_DIR/停保-减员(与增员按单位命名一致)
3. 填写标准:减少时间=当天、减少原因=在职人员主动解除劳动合同、
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职
3. 填写标准:减少时间=离职日期(离职日期为当月日期时取离职日期,否则取当天)、
减少原因=在职人员主动解除劳动合同、五个险种减少标志=1 减少、
失业原因=3 劳动者自愿辞职
(固定 28 号执行,可调用 process_stop_members() 强制)
@Version: 1.0.0
@@ -19,13 +21,14 @@
pip install pandas openpyxl xlrd xlwt xlutils
环境变量(.env 文件或系统变量,可选):
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员办理)
运行:python generate_stop.py
(如需强制生成:python 中调用 generate_stop.process_stop_members())
"""
import os
import re
import sys
import math
from datetime import datetime
@@ -52,9 +55,10 @@ except ImportError as _import_err:
)
# ==================== 1. 文件路径配置 ====================
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员办理"
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
SOURCE_GLOB = "*社保*.xlsx"
# (收紧为 *社保变更*,避免误命中同目录的《社保户头管理台账.xlsx》)
SOURCE_GLOB = "*社保变更*.xlsx"
# 停保导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
TEMPLATE_FILE = "减员模版.xls"
# 输出子目录(BASE_DIR/停保-减员),存放各单位停保导入名单(与增员的「新参保-增员/转移参保-增员」并列)
@@ -63,12 +67,20 @@ OUTPUT_DIR_NAME = "停保-减员"
TARGET_REGION = "重庆"
# ==================== 2. 源表结构配置 ====================
# 停保名单 sheet 名按月变化(如 202609停保名单),按关键字匹配
# 停保名单 sheet 名按月变化(如 202609停保名单),优先精确匹配当前月
SHEET_KEY = "停保名单"
# 源表表头在第3行
SOURCE_HEADER_ROW = 3
# 源表筛选列:类型(第一道筛选,只保留 停保/转移停保)
TYPE_COL = "类型"
# 类型列保留的取值
KEEP_TYPES = ("停保", "转移停保")
# 源表筛选列:区域(筛选重庆)
REGION_COL = "区域"
# 离职日期列(当月日期 → 减少时间=离职日期,否则=当天)
LEAVE_DATE_COL = "离职日期"
# 源表筛选列:办理停保(只处理为空的行,非空=已办理过,排除)
PROCESSED_COL = "办理停保"
# 用于分组的列(参保单位,按单位存储/命名,与增员一致)
GROUP_COL = "参保单位"
@@ -79,7 +91,8 @@ COLUMN_MAP = {
'证件号码': '身份证号码', # 模板列 → 源表「身份证号码」
'姓名': '停保人姓名', # 模板列 → 源表「停保人姓名」
'单位社保号': '单位社保号', # 用于 B1 单元格
'单位名称': '参保单位', # 用于分组、文件名 和 D1 单元格
'单位名称': '参保单位', # 用于分组、文件名
'单位全称': '单位全称', # 用于 D1 单元格
}
# ==================== 4. 固定默认值 ====================
@@ -104,7 +117,7 @@ TPL_COLS = [
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
'工伤保险减少标志', '生育保险减少标志', '失业原因',
]
# 需按日期写入的模板列(减少时间=当天)
# 需按日期写入的模板列(减少时间=离职日期[当月]或当天)
DATE_COLS = {'减少时间'}
@@ -135,10 +148,23 @@ def _safe_name(value):
def _get_today():
"""返回当日日期(停保减少时间 = 制作当天)。"""
"""返回当日日期(减少时间兜底值)。"""
return datetime.now()
def _resolve_reduce_time(raw, today):
"""减少时间取值规则:离职日期为当月日期 → 减少时间=离职日期;
为空/「/」占位/无法识别/非当月 → 减少时间=当天。
返回 (日期, 是否取自离职日期)。"""
try:
dt = pd.to_datetime(raw, errors='coerce')
except (TypeError, ValueError):
dt = pd.NaT
if pd.notna(dt) and dt.year == today.year and dt.month == today.month:
return dt, True
return today, False
def find_source_file():
"""定位源表(*社保*.xlsx,排除 Excel 临时文件 ~$,取最新)。"""
candidates = [
@@ -164,11 +190,22 @@ def find_template_file():
def find_source_sheet(source_file):
"""按关键字匹配源表【停保名单】sheet(sheet 名按月变化,如 202609停保名单)。"""
"""定位源表【停保名单】sheet(sheet 名按月变化,如 202609停保名单):
优先精确匹配当前月「YYYYMM停保名单」,其次正则匹配取年月最新,最后关键字兜底。
(sheet 名可能带尾部空格,统一 strip 后比对,返回原名供 pandas 读取)"""
xl = pd.ExcelFile(source_file)
for name in xl.sheet_names:
if SHEET_KEY in name:
return name
names = [n.strip() for n in xl.sheet_names]
exact = f"{datetime.now():%Y%m}{SHEET_KEY}"
if exact in names:
return next(orig for orig, n in zip(xl.sheet_names, names) if n == exact)
hits = [(int(m.group(1)), int(m.group(2)), orig)
for orig, n in zip(xl.sheet_names, names)
if (m := re.match(r"(20\d{2})(1[0-2]|[1-9])停保名单", n))]
if hits:
return max(hits)[2]
for orig, n in zip(xl.sheet_names, names):
if SHEET_KEY in n:
return orig
raise ValueError(
f"源表 {os.path.basename(source_file)} 中未找到包含「{SHEET_KEY}」的 sheet,"
f"实际 sheets:{xl.sheet_names}")
@@ -182,13 +219,13 @@ def get_output_dir():
# ==================== 7. 模板写入(xlrd 读取 + xlutils 复制,保留下拉字典) ====================
def _write_template(template_file, output_path, unit_no, unit_name, records):
def _write_template(template_file, output_path, unit_no, unit_full_name, records):
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
- 使用 xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,
保留「二级代码」下拉字典与数据有效性;
- B1=单位社保号,D1=单位全称;数据从模板第4行起,按 TPL_COLS 顺序写入 B~L 列;
- 减少时间以 yyyy/m/d 文本写入(如 2026/9/10,当天);
- B1=单位社保号,D1=单位全称(工商注册全称);数据从模板第4行起,按 TPL_COLS 顺序写入 B~L 列;
- 减少时间以 yyyy/m/d 文本写入(如 2026/9/10,离职日期或当天);
- 模板原数据区中未被覆盖的多余示例行清空。
"""
rb = xlrd.open_workbook(template_file, formatting_info=True)
@@ -196,7 +233,7 @@ def _write_template(template_file, output_path, unit_no, unit_name, records):
wb = xl_copy(rb)
ws = wb.get_sheet(0) # 批量导入
ws.write(0, 1, unit_no) # B1 单位社保号
ws.write(0, 3, unit_name) # D1 单位全称
ws.write(0, 3, unit_full_name) # D1 单位全称
for i, rec in enumerate(records):
r = TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
for c, col in enumerate(TPL_COLS):
@@ -218,10 +255,11 @@ def _write_template(template_file, output_path, unit_no, unit_name, records):
def process_stop_members():
"""
生成停保导入名单
规则:区域=重庆;按单位社保号分组;减少时间=当天;减少原因=在职人员主动解除劳动合同;
规则:类型 ∈ {停保, 转移停保};区域=重庆;办理停保为空;按参保单位分组;
减少时间=离职日期(当月日期)否则=当天;减少原因=在职人员主动解除劳动合同;
五个险种减少标志=1 减少;失业原因=3 劳动者自愿辞职
"""
# 1. 读取源表【停保名单】sheet(表头在第3行,全列按文本读,保住身份证/社保编号完整值)
# 1. 读取源表【当前月份停保名单】sheet(表头在第3行,全列按文本读,保住身份证/社保编号完整值)
source_file = find_source_file()
sheet_name = find_source_sheet(source_file)
print(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
@@ -232,36 +270,47 @@ def process_stop_members():
dtype=str
)
# 2. 筛选:区域=重庆
df_filtered = df_source[df_source[REGION_COL] == TARGET_REGION].copy()
# 2. 筛选:类型 ∈ {停保, 转移停保} ∩ 区域=重庆 ∩ 办理停保为空(非空=已办理过,排除)
type_mask = df_source[TYPE_COL].astype(str).str.strip().isin(KEEP_TYPES)
region_mask = df_source[REGION_COL].astype(str).str.strip() == TARGET_REGION
proc_empty = df_source[PROCESSED_COL].isna() | (
df_source[PROCESSED_COL].astype(str).str.strip() == '')
base_mask = type_mask & region_mask
df_filtered = df_source[base_mask & proc_empty].copy()
if df_filtered.empty:
print(f"没有找到【{TARGET_REGION}】区域的停保数据")
print(f"没有筛选到数据(类型 ∈ {'/'.join(KEEP_TYPES)} ∩ 区域={TARGET_REGION} ∩ 办理停保为空)")
return
print(f"共找到 {len(df_filtered)} 条 {TARGET_REGION} 区域停保记录")
n_processed = int((base_mask & ~proc_empty).sum())
print(f"共筛选到 {len(df_filtered)} 条记录"
f"(类型分布:{df_filtered[TYPE_COL].str.strip().value_counts().to_dict()})"
f";办理停保非空排除 {n_processed} 条")
# 3. 获取当天日期(减少时间 = 当天)
# 3. 获取当天日期(减少时间兜底值;离职日期为当月日期时用离职日期)
today = _get_today()
print(f"制作日期:{today.strftime('%Y-%m-%d')}")
print(f"减少时间:{today.strftime('%Y-%m-%d')}(当日)")
n_leave_date = 0 # 减少时间取自离职日期的人数统计
# 4. 按单位社保号分组生成
# 4. 按参保单位分组生成
template_file = find_template_file()
output_dir = get_output_dir()
print(f"输出目录:{output_dir}")
for group_key, group in df_filtered.groupby(GROUP_COL):
print(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
first_row = group.iloc[0]
unit_no = first_row[COLUMN_MAP['单位社保号']] # 单位社保号 → B1
unit_name = first_row[COLUMN_MAP['单位名称']] # 参保单位 → D1
unit_no = first_row[COLUMN_MAP['单位社保号']] # 单位社保号 → B1
unit_full_name = first_row[COLUMN_MAP['单位全称']] # 单位全称 → D1
# 5. 逐行生成数据(键 = 模板列名)
records = []
for _, row in group.iterrows():
reduce_time, from_leave = _resolve_reduce_time(row[LEAVE_DATE_COL], today)
if from_leave:
n_leave_date += 1
rec = {
'个人编号': _clean_value(row[COLUMN_MAP['个人编号']]),
'证件号码': _clean_value(row[COLUMN_MAP['证件号码']]),
'姓名': _clean_value(row[COLUMN_MAP['姓名']]),
'减少时间': today,
'减少时间': reduce_time,
'减少原因': DEFAULT_VALUES['减少原因'],
'养老保险减少标志': DEFAULT_VALUES['养老保险减少标志'],
'失业保险减少标志': DEFAULT_VALUES['失业保险减少标志'],
@@ -274,10 +323,12 @@ def process_stop_members():
# 6. 写入模板并另存
output_path = os.path.join(output_dir, f"{_safe_name(group_key)}减员导入名单.xls")
_write_template(template_file, output_path, unit_no, unit_name, records)
_write_template(template_file, output_path, unit_no, unit_full_name, records)
print(f" 已生成:{output_path}")
print(f"所有停保导入名单生成完成!共 {len(df_filtered[GROUP_COL].unique())} 个单位")
print(f"减少时间取值:{n_leave_date} 人取离职日期,"
f"{len(df_filtered) - n_leave_date} 人取当天({today.strftime('%Y-%m-%d')})")
# ==================== 9. 主入口(固定28号执行) ====================
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 984 KiB

@@ -68,7 +68,7 @@ CHECK_LIMIT = None # 每次运行最多核查的单位数(No
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空办理状态回待办(重新走8号+增员)
# ---- 回盘打印下载与核对 ----
DISK_DIR = r"D:\资料\人资\社保系统增减员办理\回盘打印\新参保-增员" # 回盘文件保存目录
DISK_DIR = r"D:\资料\人资\重庆社保增减员办理\回盘打印\新参保-增员" # 回盘文件保存目录
REPLAY_PREFIX = "人员增减申请回盘表" # 保存文件名:前缀_单位_日期.xlsx
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
"工伤参保状态", "生育参保状态"] # 需核对的三险五项状态列
@@ -345,10 +345,11 @@ def _download_huipan(page, biz_tab, unit):
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
import_add._dismiss_popups(biz_tab)
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接/文本)
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接)。
# 不放 tag:span 候选:左侧菜单项是 li>span 结构,内容区未渲染时会误抓
# 菜单 span 重点一次菜单,下载不触发(减员版实测踩过的坑)
btn = None
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印',
'tag:span@@text()=回盘打印'):
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印'):
try:
btn = biz_tab.ele(sel, timeout=2)
except Exception:
@@ -0,0 +1,674 @@
# -*- coding: utf-8 -*-
"""
@FileName: check_review_stop.py
@Description: XQ0014 重庆社保系统增减员办理(核查-回盘·减员)—— 单文件自包含版
减员申报(import_stop.py)提交后,平台审核存在滞后。本脚本对源名单中
「办理停保=待审核」的人员所在参保单位,逐个登录重庆人社政务平台核查审核结论。
整体流程与 check_review.py(增员核查)一致,差异点:
1. 名单口径:sheet「YYYYMM停保名单」∩ 类型∈{停保,转移停保} ∩ 办理停保=待审核,
回写列「办理停保」(停保成功/停保失败)
2. 业务入口:城保参保单位人员减少;进业务页后有一次仅有右上角 X 按钮的
「提示信息」弹窗需先关闭(import_stop._close_tip_modal)
3. 明细接口与增员同一个(queryYsbWs04orWs01,已实测减员可用),返回行内直接带
aac001=个人编号、aad030=减少时间 → 审核通过人员的备注回写直接取接口数据
(个人编号+减少时间),无需依赖回盘表核对
4. 回盘打印:每个账号核查完仍下载回盘表到 DISK_DIR 留档(减员办结后五项参保
状态口径未定,不做状态核对回写)
流程(每个参保单位):
1. 登录(复用同目录 sb_login,法人用户 + 图形验证码)
2. 单位办事 → 城保参保单位人员减少 → 在线办理(关「提示信息」弹窗)
3. 左侧菜单点「已申报查询」→ 读表格第一条「当前状态」
非「已办结」→ 跳过该单位(审核还没走完)
4. 「已办结」→ 点「查看」,监听 queryYsbWs04orWs01 接口拿查询参数,
再用页内 XHR 重放接口翻页取全量(防分页漏数据)
5. 按 aac002 证件号码匹配本单位「待审核」人员,回写源名单「办理停保」列:
- 审核通过 → 停保成功,备注追加 个人编号/减少时间(接口直取)
- 不通过 + 400系统错误 → 先记录不动状态,全部单位核查完后统一清空办理停保
(回到待办,之后重新执行8号需求制作名单完成减员)
- 不通过 + 其它原因 → 停保失败,审核意见追加写备注(不覆盖)
6. 回盘打印:每个账号核查完下载回盘表(人员增减申请回盘表_单位_下载日期.xlsx)留档
7. 台账回写:复用 import_stop 的 JSON 缓存 + 运行结束统一回写 Excel 机制
(缓存文件 writeback_pending_stop.json,与增员互不干扰)
依赖(与 import_stop 相同):pandas openpyxl DrissionPage python-dotenv ddddocr
运行:python check_review_stop.py
"""
import os
import sys
import json
import time
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse, parse_qsl, urlencode
# ---- 单文件运行支持:本目录加入 sys.path,复用同目录 import_stop / sb_login ----
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
try:
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
f"缺失依赖详情: {_import_err}")
import import_stop # 同目录:复用停保名单/台账读取、提示弹窗关闭、回写缓存机制
import sb_login
# ==================== 1. 配置 ====================
CHECK_STATUS = "待审核" # 核查范围:办理停保为该值的人员
DONE_STATUS = "已办结" # 已申报查询里第一条的该状态才继续查看
PASS_STATUS = "停保成功" # 审核通过 → 办理停保
FAIL_STATUS = "停保失败" # 审核不通过(非系统错误)→ 办理停保
ERR_400_KEYWORD = "status 400" # aae111 含该关键字 = 系统错误,需重新减员
MENU_QUERY = "已申报查询" # 业务页左侧菜单
API_KEYWORD = "queryYsbWs04orWs01" # 已申报明细查询接口(与增员同一个,减员实测可用)
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001") # 单位信息接口(页面加载完成标志)
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
"onlineoffice/OdCommon") # 左侧菜单页(明细详情页看不到菜单时直跳)
PAGE_SIZE = 10 # 重放接口每页条数(与平台默认一致,翻页取全量)
MAX_PAGES = 50 # 重放翻页上限(防死循环)
CHECK_LIMIT = None # 每次运行最多核查的单位数(None=不限制)
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空办理停保回待办(重新走8号+减员)
# ---- 回盘打印下载(仅留档,不做状态核对——减员办结后五项状态口径未定,
# 备注回写的个人编号/减少时间由明细接口直取,见 build_writeback)----
DISK_DIR = r"D:\资料\人资\重庆社保增减员办理\回盘打印\停保-减员" # 回盘文件保存目录
REPLAY_PREFIX = "人员增减申请回盘表" # 保存文件名:前缀_单位_日期.xlsx
# ==================== 2. 核查任务读取 ====================
def load_check_tasks(exclude_ids=frozenset()):
"""读取停保名单,筛选 办理停保=待审核 的行,按参保单位分组。
返回 [{unit, count, cids(set)}];同时把源文件信息写回 import_stop 全局
(flush_writeback 依赖 SOURCE_FILE_USED / SOURCE_SHEET_USED)。
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
"""
source_file = import_stop._latest_file(import_stop.SOURCE_DIR, import_stop.SOURCE_GLOB)
now = datetime.now()
xl = pd.ExcelFile(source_file)
sheet_name = import_stop._pick_sheet(xl, f"{now:%Y%m}停保名单", "停保名单",
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
import_stop.SOURCE_FILE_USED, import_stop.SOURCE_SHEET_USED = source_file, sheet_name
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
status = df[import_stop.STATUS_COL].astype(str).str.strip()
mask = (
(df[import_stop.REGION_COL].astype(str).str.strip() == import_stop.REGION)
& (df[import_stop.TYPE_COL].astype(str).str.strip().isin(import_stop.KEEP_TYPES))
& (status == CHECK_STATUS)
)
sub = df[mask].copy()
if exclude_ids and '身份证号码' in sub.columns:
before = len(sub)
ref = [import_stop._norm_id(x) for x in exclude_ids]
sub = sub[~sub['身份证号码'].map(lambda v: import_stop._id_hit(import_stop._norm_id(v), ref))]
dropped = before - len(sub)
if dropped:
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
if sub.empty:
print(f"没有筛选到数据({import_stop.REGION} ∩ {'/'.join(import_stop.KEEP_TYPES)} "
f"∩ 办理停保={CHECK_STATUS})")
return []
tasks = []
for unit, g in sub.groupby(sub[import_stop.UNIT_COL].astype(str).str.strip()):
cids = {import_stop._norm_id(v) for v in g['身份证号码']}
cids.discard('')
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
tasks.sort(key=lambda t: t['unit'])
print(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / {len(tasks)} 个参保单位(办理停保={CHECK_STATUS})")
return tasks
# ==================== 3. 网页操作 ====================
def _open_query_menu(tab):
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
_dismiss_guide(tab) # 新手引导浮层会吞菜单点击
import_stop._click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
f'左侧菜单「{MENU_QUERY}」')
import_stop._dismiss_popups(tab)
deadline = time.time() + 15
while time.time() < deadline:
for tb in tab.eles('tag:table'):
try:
ths = [th.text.strip() for th in tb.eles('tag:th')]
except Exception:
continue
if '当前状态' in ths and '操作' in ths:
return tb
time.sleep(0.5)
raise RuntimeError(f"点击「{MENU_QUERY}」后未出现申报记录表")
def _read_first_row(table):
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
or table.ele('css:tbody tr', timeout=1)
if row is None:
return None, None
ths = [th.text.strip() for th in table.eles('tag:th')]
i_status = ths.index('当前状态')
tds = [td.text.strip() for td in row.eles('tag:td')]
status = tds[i_status] if len(tds) > i_status else ''
view = None
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
try:
view = row.ele(sel, timeout=1)
except Exception:
view = None
if view:
break
return status, view
def _capture_query_url(page, tab, view):
"""点「查看」并监听明细查询接口,返回请求 URL。
明细可能在当前 tab 打开也可能新开 tab:两个方向都轮询监听。"""
before = set(page.tab_ids)
tab.listen.start(API_KEYWORD)
new_tabs = []
packet = None
try:
try:
view.click()
except Exception:
view.click(by_js=True)
deadline = time.time() + 25
while time.time() < deadline and packet is None:
# 新开 tab 也挂上监听(明细页可能新 tab 加载接口)
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
new_tabs.append(tid)
try:
page.get_tab(tid).listen.start(API_KEYWORD)
except Exception:
pass
try:
packet = tab.listen.wait(count=1, timeout=2)
except Exception:
packet = None
if packet is None:
for tid in new_tabs:
try:
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
except Exception:
packet = None
if packet:
break
finally:
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
try:
t.listen.stop()
except Exception:
pass
if not packet:
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
url = packet.request.url
print(f" 已捕获明细接口:{url[:100]}...")
return url
def _fetch_via_xhr(tab, url):
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
js = ("const xhr=new XMLHttpRequest();"
"xhr.open('GET',arguments[0],false);"
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
"xhr.send();return xhr.responseText;")
return tab.run_js(js, url)
def _dismiss_warm_tip(tab):
"""关「温馨提示」弹窗(如:统一社会信用代码,调用单位信息接口失败!),
点页脚「关 闭」按钮。返回是否处理过。"""
try:
for t in tab.eles('css:.ant-modal-title'):
if '温馨提示' not in (t.text or ''):
continue
p = t
for _ in range(4):
p = p.parent()
if p is None:
break
cls = p.attr('class') or ''
if 'ant-modal' in cls and 'ant-modal-content' not in cls \
and 'ant-modal-header' not in cls:
btn = p.ele('css:.ant-modal-footer button', timeout=1)
if btn:
try:
btn.click()
except Exception:
btn.click(by_js=True)
time.sleep(0.6)
return True
break
except Exception:
pass
return False
def _reopen_biz(page):
"""统一自愈入口:重走业务入口(与回盘打印「重开业务页」同一操作)——
打开业务页 → 关「提示信息」弹窗 → 跳过新手引导 → 关残留弹窗。
用于单位信息接口失败等页面卡死场景,代替裸刷新。返回新 biz_tab。"""
tab = import_stop._open_business_page(page, sb_login.LAST_SESSION['tab'])
import_stop._close_tip_modal(tab)
_dismiss_guide(tab)
import_stop._dismiss_popups(tab)
return tab
def _wait_unit_loaded(tab, unit_name, timeout=40):
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
期间弹「温馨提示:调用单位信息接口失败」→ 关闭并立即返回 None,由调用方
统一重走业务入口(_reopen_biz)自愈。
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
if _dismiss_warm_tip(tab):
print(" 单位信息接口调用失败(温馨提示),关闭后重走业务入口")
return None
try:
raw = _fetch_via_xhr(tab, API_UNIT_INFO)
data = (json.loads(raw).get('data') or [None])[0]
if data and data.get('aab001'):
print(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
return data
except Exception:
pass
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
try:
if tab.ele(f'text:{unit_name}', timeout=0.5):
print(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
return {}
except Exception:
pass
time.sleep(1)
return None
def _replay_query_all(tab, captured_url):
"""用捕获的请求参数重放接口翻页,取全量明细行(与增员同一接口)。
返回 (results, unit_full);results 字段取 aac003/aac002/aae110s/aae111,
另取 aac001=个人编号、aad030=减少时间(审核通过人员备注回写用)。"""
parsed = urlparse(captured_url)
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
if k != 'pageIndex']
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
rows, total = [], None
for idx in range(MAX_PAGES):
params = base_params + [('pageIndex', json.dumps(
{"pageIndex": idx, "pageSize": PAGE_SIZE}, separators=(',', ':')))]
full = f"{root}?{urlencode(params)}"
raw = _fetch_via_xhr(tab, full)
if not raw:
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
payload = json.loads(raw)
data = payload.get('data') or {}
items = data.get('data') or []
if total is None:
total = data.get('total')
rows.extend(items)
print(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
if not items or (total is not None and len(rows) >= total):
break
results = []
for it in rows:
results.append({
"name": str(it.get('aac003') or '').strip(),
"cid": import_stop._norm_id(it.get('aac002')),
"conclusion": str(it.get('aae110s') or '').strip(),
"opinion": str(it.get('aae111') or '').strip(),
"pid": str(it.get('aac001') or '').strip(), # 个人编号
"stop_date": str(it.get('aad030') or '').strip(), # 减少时间
})
# 平台登记的参保单位全称(aab004),用于回盘文件命名
unit_full = ""
for it in rows:
v = str(it.get('aab004') or '').strip()
if v:
unit_full = v
break
return results, unit_full
# ==================== 4. 结论回写 ====================
def build_writeback(results, task_cids, unit_name):
"""按减员回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。
审核通过的备注直接取接口个人编号+减少时间(不依赖回盘表核对)。
400系统错误不立即清状态:先记录,运行结束后统一清空办理停保回待办再减员。"""
status_map, remark_map, redo400, logs = {}, {}, [], []
for r in results:
if not r['cid'] or r['cid'] not in task_cids:
continue
concl, opinion = r['conclusion'], r['opinion']
line = f" {r['name']}({r['cid']}):{concl}"
if concl == '审核通过':
status_map[r['cid']] = PASS_STATUS
info = ";".join(x for x in (
f"个人编号:{r['pid']}" if r['pid'] else "",
f"减少时间:{r['stop_date']}" if r['stop_date'] else "") if x)
remark_map[r['cid']] = info or PASS_STATUS
line += f" → 办理停保={PASS_STATUS},备注追加:{info[:60]}"
elif concl == '不通过':
if ERR_400_KEYWORD in opinion:
# 系统错误:仅记录,运行结束后统一清空办理停保回待办重新减员
if RUN_400_CLEAR:
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
line += " → 400系统错误,已记录(结束后统一清状态回待办重新减员)"
else:
status_map[r['cid']] = FAIL_STATUS
remark_map[r['cid']] = opinion or '审核不通过'
line += f" → 办理停保={FAIL_STATUS},备注追加:{opinion[:60]}"
else:
line += " → 非终态结论,跳过"
logs.append(line)
return status_map, remark_map, redo400, logs
# ==================== 4b. 回盘打印下载(留档) ====================
def _dismiss_guide(tab):
"""关闭新手引导浮层(点「跳过全部」,无则点「下一步」翻完)。
该浮层带遮罩会吞掉左侧菜单点击——实测直跳菜单页后不先跳过引导,
点「回盘打印」菜单无效,内容区一直停在预申报页。"""
for _ in range(4): # 引导最多 3~4 步,点完自然消失
hit = False
for sel in ('text=跳过全部', 'text=下一步'):
try:
e = tab.ele(sel, timeout=1)
except Exception:
e = None
if not e:
continue
try:
if e.states.has_rect:
e.click()
hit = True
time.sleep(0.6)
break
except Exception:
pass
if not hit:
return
def _find_huipan_btn(tab, wait):
"""找内容区可见的「回盘打印」提交按钮(aa.md 实测:<button type="submit">)。
只认 button/a——左侧菜单项是 li>span 结构,span 一律排除,
否则内容区未渲染时会误抓菜单 span 再点一次菜单,下载不触发。"""
deadline = time.time() + wait
while time.time() < deadline:
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印'):
try:
cand = tab.ele(sel, timeout=1)
except Exception:
cand = None
if cand:
try:
if cand.states.has_rect:
return cand
except Exception:
return cand # 状态取不到时退回原行为
time.sleep(0.5)
return None
def _dump_download_debug(tab, tag):
"""回盘打印失败时自动保存现场(截图+HTML 到脚本旁 _debug/),便于对齐真实页面结构。"""
try:
dbg = _HERE / "_debug"
dbg.mkdir(exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
tab.get_screenshot(path=str(dbg), name=f"huipan_{tag}_{ts}.png")
(dbg / f"huipan_{tag}_{ts}.html").write_text(tab.html, encoding='utf-8')
print(f" 已保存现场:{dbg / f'huipan_{tag}_{ts}.png'}(含同名 html)")
except Exception:
pass
def _download_huipan(page, biz_tab, unit):
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
返回保存的文件 Path。"""
save_dir = Path(DISK_DIR)
save_dir.mkdir(parents=True, exist_ok=True)
target = save_dir / f"{REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
# 三种进入方式逐个尝试;每次点完菜单都验证内容区按钮真的出现,
# 没出现(如被引导浮层吞了点击)视为本次无效,换下一种方式
btn = None
for name, goto in (("当前页", None), ("菜单页", MENU_PAGE_URL), ("重开业务页", "__REOPEN__")):
try:
if goto == "__REOPEN__":
biz_tab = _reopen_biz(page) # 统一自愈入口(与单位信息失败恢复一致)
elif goto:
print(f" 当前页进不去回盘打印,直跳{name}...")
biz_tab.get(goto)
time.sleep(2)
_dismiss_warm_tip(biz_tab) # 接口失败类温馨提示先关掉
_dismiss_guide(biz_tab) # 新手引导浮层会吞菜单点击,必须先跳过
import_stop._dismiss_popups(biz_tab)
import_stop._click_any(biz_tab, menu_sel, f'左侧菜单「回盘打印」({name})')
btn = _find_huipan_btn(biz_tab, 8)
if btn:
break
print(f" ({name})菜单已点但回盘打印内容未出现,换下一种方式")
except Exception as e:
print(f" ({name})方式失败:{e}")
if btn is None:
_dump_download_debug(biz_tab, 'nobutton')
raise RuntimeError("三种方式均未进入回盘打印页(已保存现场)")
biz_tab.set.download_path(str(save_dir))
before = {f.name for f in save_dir.iterdir() if f.is_file()}
try:
btn.click()
except Exception:
btn.click(by_js=True)
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
new_file, last_size, stable = None, -1, 0
deadline = time.time() + 90
while time.time() < deadline:
time.sleep(1)
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
and f.suffix.lower() not in ('.crdownload', '.tmp')]
if not files:
stable, last_size = 0, -1
continue
f = max(files, key=lambda x: x.stat().st_mtime)
size = f.stat().st_size
if size > 0 and size == last_size:
stable += 1
if stable >= 2:
new_file = f
break
else:
stable = 0
last_size = size
if new_file is None:
_dump_download_debug(biz_tab, 'nodownload')
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件(已保存现场)")
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
return target
# ==================== 5. 单个单位完整核查 ====================
def do_unit_check(task):
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
page = sb_login.LAST_SESSION.get('page')
work_tab = sb_login.LAST_SESSION.get('tab')
if page is None or work_tab is None:
return {"success": False, "message": "无有效登录会话"}
res = {"success": False, "checked": 0, "passed": 0, "failed": 0,
"redo400": [], "skipped": False}
try:
import_stop._shot(work_tab, "s1_workbench")
biz_tab = import_stop._open_business_page(page, work_tab)
import_stop._close_tip_modal(biz_tab) # 减员特有:进业务页先关「提示信息」弹窗
import_stop._dismiss_popups(biz_tab)
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据。
# 接口偶发失败会弹「温馨提示:调用单位信息接口失败」,此时统一重走业务入口自愈
# (_reopen_biz,与回盘打印「重开业务页」同一操作),最多 3 次
unit_info = None
for attempt in range(1, 4):
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
if unit_info is not None:
break
print(f" 单位信息未加载(第 {attempt} 次),重走业务入口...")
if attempt < 3:
biz_tab = _reopen_biz(page)
if unit_info is None:
res.update(success=True, skipped=True,
message="单位信息未加载(getAab001无数据),跳过")
return res
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
_shot_s(biz_tab, "s2_biz_page")
table = _open_query_menu(biz_tab)
_shot_s(biz_tab, "s3_query_list")
status, view = _read_first_row(table)
if not status:
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
elif status != DONE_STATUS:
res.update(success=True, skipped=True,
message=f"第一条状态「{status}」非{DONE_STATUS},跳过")
else:
print(f" 第一条状态:{status},点击查看读取审核结论")
url = _capture_query_url(page, biz_tab, view)
results, detail_full = _replay_query_all(biz_tab, url)
unit_full = unit_full or detail_full
_shot_s(biz_tab, "s4_detail_fetched")
if not results:
res.update(success=True, message="明细接口返回 0 条,跳过")
else:
status_map, remark_map, redo400, logs = build_writeback(
results, task['cids'], task['unit'])
for line in logs:
print(line)
if status_map or remark_map:
import_stop.writeback_source(status_map, remark_map)
n_match = len([r for r in results if r['cid'] in task['cids']])
n_pass = len([v for v in status_map.values() if v == PASS_STATUS])
n_fail = len([v for v in status_map.values() if v == FAIL_STATUS])
res.update(
success=True,
checked=n_match,
passed=n_pass,
failed=n_fail,
redo400=redo400,
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
f"400系统错误{len(redo400)}(结束后统一清状态)"))
# 回盘打印:每个账号核查完都下载回盘表留档(无论是否已办结;
# 减员备注回写用接口个人编号/减少时间,见 build_writeback)
try:
name_for_file = (unit_full or task['unit']).strip()
if unit_full and unit_full != task['unit']:
print(f" 使用平台单位全称命名:{unit_full}")
print(" 开始回盘打印下载...")
hp_file = _download_huipan(page, biz_tab, name_for_file)
print(f" 回盘文件已保存:{hp_file}")
res["huipan"] = f"回盘已下载留档:{hp_file.name}"
except Exception as e:
res["huipan"] = f"回盘打印失败:{e}"
print(f" 回盘打印失败:{e}")
return res
except Exception as e:
res["message"] = f"核查异常:{e}"
return res
def _shot_s(tab, name):
"""核查流程调试截图(沿用 import_stop 的 DEBUG_MODE 开关,前缀 s 区分)。"""
import_stop._shot(tab, name)
# ==================== 6. 逐单位登录 + 核查 ====================
def process_units(tasks, accounts):
"""逐参保单位:登录 → 已申报查询核查 → 回盘下载。每账号办完清 cookies 关浏览器。"""
results = []
for i, task in enumerate(tasks, 1):
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人待审核)==========")
acc = accounts.get(task['unit'])
try:
login_res = sb_login.main({"username": acc["username"], "password": acc["password"]})
except Exception as e:
login_res = {"success": False, "message": f"登录调用异常:{e}"}
print(f"登录结果:{login_res.get('message')}")
try:
if login_res.get("success"):
web_res = do_unit_check(task)
print(f"核查结果:{web_res.get('message')}")
results.append({**task, **web_res})
else:
results.append({**task, "success": False, "message": login_res.get("message", "")})
finally:
sb_login.close_session()
return results
# ==================== 7. 主流程 ====================
def run():
"""主流程:恢复缓存 → 读待审核停保名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
recovered_ids = import_stop._load_ckpt()
tasks = load_check_tasks(exclude_ids=recovered_ids)
if recovered_ids:
print("\n检测到上次未回写的内容,先统一回写:")
try:
import_stop.flush_writeback()
except Exception as e:
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
if not tasks:
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
accounts = import_stop.load_accounts([t['unit'] for t in tasks])
# 预检:账号齐备才继续(与减员导入一致的严格预检)
errors = []
for t in tasks:
acc = accounts.get(t['unit'])
if acc is None:
errors.append(f"[{t['unit']}] 台账未匹配")
elif not acc['username'] or not acc['password']:
errors.append(f"[{t['unit']}] 账号或密码缺失")
if errors:
print("\n预检未通过:")
for e in errors:
print(f" - {e}")
return {"success": False, "message": "预检未通过,详见日志", "total": len(tasks), "done": 0}
todo = tasks[:CHECK_LIMIT]
results = process_units(todo, accounts)
# 400系统错误:核查时只记录,全部单位核查完后统一清空办理停保回待办(重新走8号+减员)
redo_all = [p for r in results for p in (r.get("redo400") or [])]
if redo_all:
import_stop.writeback_source({p['cid']: "" for p in redo_all}, {})
print(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理停保回待办,"
f"请重新执行8号需求制作名单后减员:")
for p in redo_all:
print(f" - {p['name']}({p['cid']}){p['unit']}")
try:
import_stop.flush_writeback()
except Exception as e:
print(f"回写失败:{e}")
ok = [r for r in results if r["success"]]
fail = [r for r in results if not r["success"]]
skip = [r for r in ok if r.get("skipped")]
print(f"\n========== 汇总 ==========")
print(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家")
for r in fail:
print(f" ✗ {r['unit']}:{r.get('message', '')}")
return {"success": not fail, "message": f"完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
"total": len(results), "done": len(ok) - len(skip)}
if __name__ == "__main__":
print(run())
@@ -24,8 +24,8 @@
pip install pandas openpyxl DrissionPage python-dotenv ddddocr
环境变量(可选):
cq_social_change_dir = 名单/产出根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
cq_social_ledger_dir = 台账目录(默认 D:\\资料\\人资\\社保系统增减员办理)
cq_social_change_dir = 名单/台账/产出根目录(默认 D:\\资料\\人资\\重庆社保增减员办理)
cq_social_ledger_dir = 台账目录(默认同 cq_social_change_dir)
运行:python import_add.py
"""
@@ -51,10 +51,11 @@ except ImportError as _import_err:
f"缺失依赖详情: {_import_err}")
# ==================== 1. 路径与筛选配置 ====================
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or r"D:\资料\人资\社保系统增减员办理"
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员办理"
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or SOURCE_DIR # 台账与名单已合并同目录
IMPORT_DIR_NAME = "新参保-增员" # XQ0008 产出目录(按参保类型分文件夹)
SOURCE_GLOB = "*社保*.xlsx" # 源名单文件(年月动态,取最新)
# 源名单文件(年月动态,取最新;收紧为 *社保变更*,避免误命中同目录的《社保户头管理台账.xlsx》)
SOURCE_GLOB = "*社保变更*.xlsx"
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账文件(可能加前后缀,取最新)
REGION = "重庆" # 区域(Y列)筛选值
@@ -0,0 +1,980 @@
# -*- coding: utf-8 -*-
"""
@FileName: import_stop.py
@Description: XQ0014 重庆社保系统增减员办理(停保-减员)—— 单文件自包含版
与 XQ0008 generate_stop.py 联动:消费 8 号需求产出的《XX减员导入名单.xls》,逐参保单位登录
重庆人社政务平台(法人用户)完成减员导入申报。整体流程与 import_add.py(增员)一致,
差异点:业务入口/筛选条件/回写列不同,且进业务页后、「去查看」后各有一次仅有右上角
X 按钮的「提示信息」弹窗需要先关闭。
流程:
1. 读取最新《XXXX年X月社保变更及增减名单及人数统计.xlsx》(文件名年月动态,取最新)
→ sheet「YYYYMM停保名单」(年月动态,表头第3行)
2. 筛选:区域(G列)=重庆 ∩ 类型(K列)∈{停保,转移停保} ∩ 办理停保(AA列)为空,按参保单位分组
3. 匹配 XQ0008 产出:停保-减员/{参保单位}减员导入名单.xls(文件名规则同 generate_stop)
4. 取账号:最新《*社保户头管理台账*.xlsx》→ sheet「YYYY年M月缴费比例」(年月动态)→
城市=重庆 ∩ 是否在用=是,参保户头=参保单位 匹配:
用户名 = I列(统一社会信用代码) 优先,为空回退 K列(政务平台用户名),都空→预检报错
密码 = L列(政务平台密码),为空→预检报错
5. 预检汇总:所有单位「导入文件 + 账号 + 密码」齐备才继续,否则列出全部问题后停止
6. 逐参保单位登录政务平台(调用同目录 sb_login,每个单位登录一次,不做 cookies 缓存)
网页办理「城保参保单位人员减少」:
进业务页 → 关「提示信息」弹窗(仅 X 按钮)→ 上传导入 → 校验未通过回写(备注列)
→ 预申报 → 去申报 → 我已知晓/我知道了 → 全部提交 → 下一步 → 提交 → 去查看
→ 再关「提示信息」→ 查询列表「查看」→ 明细表审核结论按证件号码回写「办理停保」列
依赖安装:
pip install pandas openpyxl DrissionPage python-dotenv ddddocr
环境变量(可选):
cq_social_change_dir = 名单/台账/产出根目录(默认 D:\\资料\\人资\\重庆社保增减员办理)
cq_social_ledger_dir = 台账目录(默认同 cq_social_change_dir)
运行:python import_stop.py
"""
import os
import re
import sys
import time
from glob import glob
from datetime import datetime
from pathlib import Path
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行并 import 同目录 sb_login ----
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
try:
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
f"缺失依赖详情: {_import_err}")
# ==================== 1. 路径与筛选配置 ====================
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员办理"
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or SOURCE_DIR # 台账与名单已合并同目录
IMPORT_DIR_NAME = "停保-减员" # XQ0008 产出目录(减员名单专用文件夹)
# 源名单文件(年月动态,取最新;收紧为 *社保变更*,避免误命中同目录的《社保户头管理台账.xlsx》)
SOURCE_GLOB = "*社保变更*.xlsx"
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账文件(可能加前后缀,取最新)
REGION = "重庆" # 区域(G列)筛选值
KEEP_TYPES = ("停保", "转移停保") # 类型(K列)筛选值(减员两类都办)
TYPE_COL, REGION_COL, STATUS_COL, UNIT_COL = "类型", "区域", "办理停保", "参保单位"
# 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过):
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
DO_LOGIN = True # 预检通过后是否执行逐单位登录(可置 False 只做预检)
RUN_LIMIT = None # 每次运行最多办理的单位数(None=不限制;已办单位自动跳过)
DEBUG_MODE = False # 调试模式开关:开启后才保存页面截图(debug_shots\),日常运行关闭
os.environ['sb_captcha_debug'] = '1' if DEBUG_MODE else '0' # 同步给 sb_login:控制验证码调试图是否落盘
# 记录本次使用的源名单(供网页操作后回写台账)
SOURCE_FILE_USED, SOURCE_SHEET_USED = None, None
# ==================== 2. 通用辅助 ====================
def _safe_name(value):
"""单位名转安全文件名(与 XQ0008 generate_stop.py 规则一致,保证产出文件名可复现)。"""
if value is None or not str(value).strip():
return "未知单位"
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
if name.endswith("店"):
name = name[:-1]
return name
def _to_text(value):
"""None/NaN → '',其余转去空白字符串(台账号/密码列用)。"""
if value is None:
return ""
try:
if pd.isna(value):
return ""
except (TypeError, ValueError):
pass
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value).strip()
def _latest_file(directory, pattern):
"""目录内按模式取最新文件(排除 Excel 临时文件 ~$)。"""
candidates = [p for p in glob(os.path.join(directory, pattern))
if not os.path.basename(p).startswith("~$")]
if not candidates:
raise FileNotFoundError(f"在 {directory} 下未找到匹配 {pattern} 的文件")
return max(candidates, key=os.path.getmtime)
def _pick_sheet(xl, exact_name, keyword, pattern=None):
"""优先精确 sheet 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
names = [n.strip() for n in xl.sheet_names]
if exact_name in names:
return exact_name
if pattern:
hits = [(int(m.group(1)), int(m.group(2)), n)
for n in names if (m := re.match(pattern, n))]
if hits:
return max(hits)[2]
for n in names:
if keyword in n:
return n
raise ValueError(f"未找到目标 sheet(精确={exact_name},关键字={keyword}),"
f"实际 sheets:{xl.sheet_names}")
# ==================== 3. 源名单读取与筛选 ====================
def _norm_id(v):
"""身份证号规范化:去空格、转大写;数值型(Excel 把纯数字身份证存成数值)转整数字符串。"""
if v is None:
return ''
if isinstance(v, float) and v.is_integer():
v = int(v)
return str(v).strip().upper()
def _id_hit(cid, ref_ids):
"""身份证匹配:规范化后精确匹配(去空格、转大写)。
不做前缀/模糊匹配:同一批人同区县同出生日期时前 15 位可能撞车,误匹配会回写错行。"""
return bool(cid) and cid in ref_ids
def load_units(exclude_ids=frozenset()):
"""读取停保名单并筛选,返回 [(参保单位, 人数), ...](按单位分组)。
exclude_ids:需排除的身份证号集合(上次运行已回写办理停保的人员,防重复申报)。
"""
global SOURCE_FILE_USED, SOURCE_SHEET_USED
source_file = _latest_file(SOURCE_DIR, SOURCE_GLOB)
now = datetime.now()
xl = pd.ExcelFile(source_file)
sheet_name = _pick_sheet(xl, f"{now:%Y%m}停保名单", "停保名单",
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
SOURCE_FILE_USED, SOURCE_SHEET_USED = source_file, sheet_name
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
# 减员只办「办理停保为空/NULL」的行:待审核=已提交社保局,停保失败=已在其它流程处理,均跳过
status_text = df[STATUS_COL].astype(str).str.strip().str.lower()
mask = (
(df[REGION_COL].astype(str).str.strip() == REGION)
& (df[TYPE_COL].astype(str).str.strip().isin(KEEP_TYPES))
& (df[STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
)
sub = df[mask].copy()
if exclude_ids and '身份证号码' in sub.columns:
before = len(sub)
ref = [_norm_id(x) for x in exclude_ids]
sub = sub[~sub['身份证号码'].map(lambda v: _id_hit(_norm_id(v), ref))]
dropped = before - len(sub)
if dropped:
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报)")
if sub.empty:
print(f"没有筛选到数据({REGION} ∩ {'/'.join(KEEP_TYPES)} ∩ 办理停保为空)")
return []
grouped = sub.groupby(sub[UNIT_COL].astype(str).str.strip()).size()
units = sorted(grouped.items(), key=lambda t: t[0])
print(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
return units
# ==================== 4. 台账取号 ====================
def load_accounts(unit_names):
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
取不到的单位不在返回值中(由预检统一报错)。
"""
ledger_file = _latest_file(LEDGER_DIR, LEDGER_GLOB)
now = datetime.now()
xl = pd.ExcelFile(ledger_file)
sheet_name = _pick_sheet(xl, f"{now.year}年{now.month}月缴费比例", "缴费比例",
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
print(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
df = df[df[LEDGER_COL["户头"]].notna()].copy()
for c in LEDGER_COL.values():
df[c] = df[c].map(_to_text)
pool = df[(df[LEDGER_COL["城市"]] == REGION) & (df[LEDGER_COL["在用"]] == "是")]
accounts = {}
for name in unit_names:
hit = pool[pool[LEDGER_COL["户头"]] == name]
if hit.empty:
continue # 预检阶段统一报「台账未匹配」
row = hit.iloc[0]
credit, plat_user, plat_pwd = (
row[LEDGER_COL["信用代码"]], row[LEDGER_COL["平台用户名"]], row[LEDGER_COL["平台密码"]])
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
return accounts
# ==================== 5. 预检 ====================
def precheck(units, accounts):
"""预检:核对每个单位的导入文件与账号。返回待办列表 [{unit, count, file, username, password}]。"""
import_dir = os.path.join(SOURCE_DIR, IMPORT_DIR_NAME)
tasks, errors = [], []
print("\n========== 预检 ==========")
for unit, count in units:
file_path = os.path.join(import_dir, f"{_safe_name(unit)}减员导入名单.xls")
acc = accounts.get(unit)
problems = []
if not os.path.isfile(file_path):
problems.append(f"缺导入文件({IMPORT_DIR_NAME}\\{os.path.basename(file_path)})")
if acc is None:
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
else:
if not acc["username"]:
problems.append("账号缺失(I列信用代码与K列平台用户名均为空)")
if not acc["password"]:
problems.append("密码缺失(L列平台密码为空)")
if problems:
errors.append(f"[{unit}] " + ";".join(problems))
print(f" ✗ {unit}({count}人):{';'.join(problems)}")
else:
tasks.append({"unit": unit, "count": count, "file": file_path,
"username": acc["username"], "password": acc["password"]})
print(f" ✓ {unit}({count}人)账号={acc['username']}"
f"({acc['username_src']})文件={os.path.basename(file_path)}")
if errors:
print(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
for e in errors:
print(f" - {e}")
return None
print(f"预检通过:{len(tasks)} 个单位待办理\n")
return tasks
# ==================== 6. 网页操作:城保参保单位人员减少 ====================
BUSINESS_ITEM = "城保参保单位人员减少" # 单位办事列表里的业务名称
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
DEBUG_SHOT_DIR = _HERE / "debug_shots"
def _shot(tab, name):
"""调试截图:仅 DEBUG_MODE 开启时保存页面截图并打印当前 URL,便于事后定位哪一步页面状态异常。"""
if not DEBUG_MODE:
return
try:
DEBUG_SHOT_DIR.mkdir(exist_ok=True)
ts = datetime.now().strftime("%H%M%S")
tab.get_screenshot(path=str(DEBUG_SHOT_DIR), name=f"{ts}_{name}.png")
print(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
except Exception as e:
print(f" [截图失败] {name}: {e}")
def _title_is_tip(m):
"""弹窗标题是否含「提示信息」。"""
try:
t = m.ele('css:.ant-modal-title', timeout=0.2)
return bool(t and '提示信息' in (t.text or ''))
except Exception:
return False
def _find_tip_modal_by_title(tab):
"""按标题「提示信息」定位弹窗:一次查询所有标题元素再上溯到 .ant-modal。
不逐弹窗做 ele() 探测——页面隐藏残留弹窗多时,每个 miss 都吃超时,扫一圈
可达数十秒。返回该 ant-modal 元素;不存在返回 None。"""
try:
for t in tab.eles('css:.ant-modal-title'):
if '提示信息' not in (t.text or ''):
continue
p = t
for _ in range(4):
p = p.parent()
if p is None:
break
cls = p.attr('class') or ''
if 'ant-modal' in cls and 'ant-modal-content' not in cls \
and 'ant-modal-header' not in cls:
return p
except Exception:
pass
return None
def _remove_tip_modals(tab):
"""把「提示信息」类弹窗残留节点连 wrap 一起从 DOM 移除(标题含「提示信息」
或仅有 X 一个按钮;导入结果等弹窗都有操作按钮,不受影响)。antd 关弹窗只
隐藏不删节点,残留正文会干扰探针,页面重渲染还会在隐藏 wrap 里重建节点,
故必须连 wrap 删除。单次 JS 全量清理,无逐元素往返开销。"""
try:
tab.run_js(
"document.querySelectorAll('.ant-modal').forEach(function(m){"
" var t = m.querySelector('.ant-modal-title');"
" var onlyX = m.querySelector('button.ant-modal-close') &&"
" m.querySelectorAll('button').length === 1;"
" if ((t && t.textContent.indexOf('提示信息') !== -1) || onlyX) {"
" var w = m.closest('.ant-modal-wrap') || m; w.remove();"
" }"
"});")
except Exception:
pass
def _close_tip_modal(tab):
"""关闭「提示信息」弹窗(减员流程特有:进业务页后、「去查看」后各弹一次)。
该弹窗只有右上角 X 按钮,真实鼠标点击关闭(本站 JS 合成 click 无效),关一次
即可:残留节点连 wrap 删除兜底;即使再复活,导入结果探针也会跳过「提示信息」
弹窗正文、优先识别「导入完成」成功标志,不会误判。未弹出返回 False。"""
m = _find_tip_modal_by_title(tab)
if m is None:
return False
x = m.ele('css:button.ant-modal-close', timeout=1)
if x:
try:
# 仅可见弹窗才做真实点击;隐藏残留(无位置)点不动,静默走下方 JS 清理
if x.states.has_rect:
x.click() # 真实鼠标点击
print(" 关闭「提示信息」弹窗")
time.sleep(0.8)
except Exception:
pass # 点击失败(隐藏/遮挡)→ JS 清理兜底,不刷错误日志
_remove_tip_modals(tab) # 残留节点连 wrap 删除兜底
return True
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
last_err = None
for sel in selectors:
try:
ele = tab.ele(sel, timeout=timeout)
except Exception as e:
last_err = e
continue
if ele:
ele.click()
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
for sel in selectors:
ele = tab.ele(sel, timeout=timeout)
if ele:
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}")
def _wait_modal(tab, keyword, timeout=60):
"""等待某个可见 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for m in tab.eles('css:.ant-modal-body'):
if keyword in (m.text or ''):
return m
except Exception:
pass
time.sleep(0.5)
return None
def _dismiss_popups(tab, rounds=5):
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
for _ in range(rounds):
hit = False
for t in texts:
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
except Exception:
btn = None
if btn:
try:
btn.click()
print(f" 关闭弹窗:{t}")
hit = True
time.sleep(1.2)
except Exception:
pass
if not hit:
break
def _open_business_page(page, work_tab):
"""工作台 → 单位办事 → 「城保参保单位人员减少」在线办理。返回承载业务页的 tab。"""
before = set(page.tab_ids)
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
time.sleep(2.5)
# 列表项:h4 标题定位 → 上溯到 li.ant-list-item → 点其「在线办理」
h4 = _find_any(work_tab, [f'tag:h4@@text()={BUSINESS_ITEM}'], f'业务入口「{BUSINESS_ITEM}」')
li = h4
for _ in range(6):
li = li.parent()
if li is None:
break
if li.tag == 'li':
break
act = li.ele('text=在线办理', timeout=3) if li is not None else None
if act is None:
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
act.click()
# 业务页可能新开 tab 或当前页跳转:轮询识别出现上传控件(input[type=file])的页面
deadline = time.time() + 30
while time.time() < deadline:
time.sleep(1)
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
for tid in cand_tids:
try:
t = page.get_tab(tid)
if t.ele('#customized_form_controls_data', timeout=0.5):
return t
except Exception:
continue
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
def _body_in_tip_modal(m):
"""modal-body 是否属于标题为「提示信息」的说明弹窗(说明性内容,非导入结果)。"""
p = m
for _ in range(3):
try:
p = p.parent()
except Exception:
return False
if p is None:
return False
if _title_is_tip(p):
return True
return False
def _wait_import_result(tab, timeout=90):
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示(modal/toast,不限语言)。
成功弹窗标题为「系统提示」,可能与残留/复活的「提示信息」说明弹窗同时存在,
故先全局扫「导入完成」成功标志(不受其它弹窗正文干扰),找不到才判定失败。
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
bodies = tab.eles('css:.ant-modal-body')
# 1) 第一遍只认「导入完成」成功标志(页面可能同时残留其它说明弹窗)
for m in bodies:
if '导入完成' in (m.text or ''):
return "ok", m
# 2) 第二遍:其它任何非加载中、非「提示信息」说明弹窗的文本都视为失败提示
for m in bodies:
t = (m.text or '').strip()
if t and not any(k in t for k in ('提交中', '导入中', '加载中')) \
and not _body_in_tip_modal(m):
return "fail", t
# 3) 顶部 toast 小提示(几秒即消失,需轮询抓),任何非空文本都记录
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
return "fail", t
except Exception:
pass
time.sleep(0.4)
return "timeout", None
def _wait_unit_ready(tab, timeout=5):
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。
单位信息由上传文件解析而来,显示在 borderless 下拉框里:
可能先以 placeholder 形式出现(如「20337008,重庆XX有限公司」),也可能直接是选中值。
必须等文本内容真正渲染出来(非空)才算就绪,仅元素挂载不算。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for sel in tab.eles('css:.ant-select-borderless'):
for kind in ('css:.ant-select-selection-placeholder',
'css:.ant-select-selection-item'):
ele = sel.ele(kind, timeout=1)
# 元素存在且文本可见(如「20337008,重庆XX有限公司」)才代表单位信息已显示
if ele and (ele.text or '').strip():
return True
except Exception:
pass
time.sleep(0.5)
return False
def _upload_import(tab, xls_path, max_rounds=3):
"""上传名单 xls 并点「导入」,带失败探针与重试:
每轮都重新选文件(重新触发页面解析单位信息),就绪后再点导入。
返回 (导入成功人数, 导入失败人数)。"""
last_err = "导入超时无响应"
for rnd in range(1, max_rounds + 1):
inp = _find_any(tab, ['#customized_form_controls_data',
'css:input[type="file"]'], '文件上传控件')
inp.input(xls_path) # DrissionPage 对 file input 直接写路径即上传
# 等单位信息出现(placeholder 或选中值),未就绪点导入会报 aab001 缺失
_t0 = time.time()
if not _wait_unit_ready(tab, timeout=40):
print(f" 警告:{time.time() - _t0:.0f}s 内单位信息未出现,本轮仍尝试导入")
else:
print(f" 单位信息已就绪(等待 {time.time() - _t0:.0f}s)")
time.sleep(1.0) # 就绪后再留缓冲,避免点太快
_shot(tab, "03_file_selected")
_close_tip_modal(tab) # 点导入前再兜底清一次「提示信息」,防止残留遮挡导入按钮
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
_t1 = time.time()
state, payload = _wait_import_result(tab, timeout=90)
if state == "ok":
_shot(tab, "04_import_result")
text = payload.text or ''
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
total = int(m_ok.group(1)) if m_ok else 0
failed = int(m_fail.group(1)) if m_fail else 0
print(f" 导入完成:成功 {total} 人,失败 {failed} 人")
if total == 0:
raise RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
for t in ('确 定', '确定'):
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
except Exception:
btn = None
if btn:
btn.click()
break
time.sleep(1.5)
return total, failed
# 失败/超时:记录提示,重试
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
print(f" 第 {rnd} 轮导入未成功(等待 {time.time() - _t1:.0f}s):{str(last_err)[:120]}")
time.sleep(2 + rnd) # 失败后多等一会,避免连点触发风控
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
def _read_failed_rows(tab):
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。
按表头(含「证件号码」+「详细信息」列)定位表格,避免抓到左侧导航等其它 tab 组件的面板。"""
try:
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
except Exception:
tab_btn = None
if not tab_btn:
return []
tab_btn.click()
time.sleep(2)
rows = []
try:
for tb in tab.eles('tag:table'):
ths = [th.text.strip() for th in tb.eles('tag:th')]
if '证件号码' in ths and '详细信息' in ths:
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
for tr in tb.eles('css:tbody tr'):
tds = [td.text.strip() for td in tr.eles('tag:td')]
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
detail = tds[i_detail]
# 备注只保留冒号后的内容(去掉"校验通过业务校验失败:"这类前缀)
for sep in (':', ':'):
if sep in detail:
detail = detail.split(sep, 1)[1].strip()
break
rows.append((tds[i_id], detail))
break
except Exception as e:
print(f" 读取校验未通过表格异常:{e}")
_shot(tab, "05_check_failed_tab")
return rows
def _wait_pdf_ready(tab, timeout=60):
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
last, stable_since = None, None
deadline = time.time() + timeout
while time.time() < deadline:
try:
canvases = tab.eles('css:.react-pdf__Page__canvas')
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
except Exception:
sig = None
if sig and sig[0] > 0:
if sig == last:
if stable_since and time.time() - stable_since >= 2:
return True
else:
stable_since = time.time()
last = sig
time.sleep(1)
print(" 警告:等待 PDF 渲染超时,继续尝试提交")
return False
def _goto_submit_page(tab, tries=3):
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
for i in range(tries):
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
deadline = time.time() + 12
while time.time() < deadline:
if tab.ele('tag:button@@text()=提 交', timeout=1):
return True
time.sleep(0.5)
print(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
time.sleep(1.5)
return False
def _click_submit(tab, tries=3):
"""点「提 交」,验证「您已成功提交」弹窗出现(减员流程无「已知晓」确认环节,
成功弹窗自带「确 定/去查看」按钮,与增员流程不同)。第一次可能因按钮未就绪
失效,重试。期间打印页面 toast 提示,便于诊断失败原因。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
if _wait_modal(tab, '您已成功提交', timeout=30):
return True
try:
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
print(f" 提交提示:{t[:100]}")
except Exception:
pass
print(f" 第 {i + 1} 次提交未出现「您已成功提交」弹窗,重试")
time.sleep(1.5)
return False
def _predeclare_and_submit(page, tab):
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交(带重试)→ 等成功弹窗。"""
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
if _wait_modal(tab, '预申报成功', timeout=60) is None:
raise RuntimeError("预申报后未出现成功弹窗")
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
# 等申报页就绪:提示弹窗或「全部提交」按钮任一出现即继续(替代固定 sleep,省 ~8s 空等)
deadline = time.time() + 15
while time.time() < deadline:
try:
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
break
except Exception:
pass
time.sleep(0.3)
_dismiss_popups(tab) # 系统提示「我已知晓」+ 操作说明「我知道了」
_shot(tab, "06_declare_page")
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
_wait_pdf_ready(tab)
_shot(tab, "07_pdf_ready")
if not _goto_submit_page(tab):
_shot(tab, "08_no_submit_btn")
raise RuntimeError("点击下一步后未出现「提 交」按钮")
_shot(tab, "08_submit_page")
if not _click_submit(tab):
_shot(tab, "09_submit_no_success")
raise RuntimeError("点击提交后未出现「您已成功提交」弹窗(提交可能未完成)")
_shot(tab, "11_submit_success")
print(" 提交成功")
def _collect_review_rows(tab):
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
results = {}
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
try:
tds = [td.text.strip() for td in tr.eles('tag:td')]
except Exception:
continue
# 明细表结构:业务流水号/业务类型/姓名/证件号码/审核结论/审核意见/操作
# 证件号码可能是 15/18 位,尾号可为 X,不能只 isdigit
cid = tds[3] if len(tds) > 3 else ''
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
results[cid] = (tds[4], tds[0])
return results
def _open_query_page(page, tab, timeout=25):
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
before = set(page.tab_ids)
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(1)
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
for tid in tids:
try:
t = page.get_tab(tid)
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
_shot(t, "12_query_list")
return t
except Exception:
continue
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
def _query_review_results(page, tab):
"""进入申报查询列表 → 关「提示信息」弹窗 → 打开序号1记录的「查看」→ 读明细表审核结论。
返回 {证件号码: (审核结论, 业务流水号)}。"""
qtab = _open_query_page(page, tab)
_close_tip_modal(qtab) # 去查看后会再弹一次「提示信息」,需先关闭
for attempt in range(3):
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
if view:
try:
view.click()
except Exception:
pass
# 等明细表出现(含 18 位证件号码的行)
deadline = time.time() + 12
while time.time() < deadline:
time.sleep(1)
results = _collect_review_rows(qtab)
if results:
_shot(qtab, "13_review_detail")
return results
print(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
_shot(qtab, "13_review_detail_miss")
time.sleep(1.5)
raise RuntimeError("未读取到审核结论明细表")
# ==================== 6b. 名单回写(JSON 缓存防崩溃,运行结束统一回写 Excel 一次) ====================
# 每个账号办完:回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel);
# 运行结束时 flush_writeback 统一写 Excel 一次,保存成功校验后删除缓存;
# 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单。
# 注意:缓存文件与 import_add.py(增员)分开,两脚本各自独立回写互不干扰。
_PENDING_STATUS, _PENDING_REMARK = {}, {}
_CKPT_FILE = _HERE / "writeback_pending_stop.json"
def _save_ckpt():
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
import json
data = [{"id": cid, "status": _PENDING_STATUS.get(cid, ""),
"remark": _PENDING_REMARK.get(cid, "")}
for cid in dict.fromkeys(list(_PENDING_STATUS) + list(_PENDING_REMARK))]
tmp = _CKPT_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(_CKPT_FILE)
def _load_ckpt():
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
recovered = set()
if not _CKPT_FILE.exists():
return recovered
try:
import json
for it in json.loads(_CKPT_FILE.read_text(encoding="utf-8")):
cid = it.get("id")
if it.get("status"):
_PENDING_STATUS[cid] = it["status"]
if it.get("remark"):
_PENDING_REMARK[cid] = it["remark"]
if cid:
recovered.add(cid)
return recovered
except Exception as e:
print(f" 恢复回写缓存失败:{e}")
return recovered
def writeback_source(status_map, remark_map):
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel):
status_map {身份证: 办理停保结论};remark_map {身份证: 备注}。"""
_PENDING_STATUS.update(status_map or {})
_PENDING_REMARK.update(remark_map or {})
try:
_save_ckpt()
except Exception as e:
print(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
def flush_writeback():
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
if not (_PENDING_STATUS or _PENDING_REMARK):
return
if not SOURCE_FILE_USED:
raise RuntimeError("无源名单文件记录,无法回写")
from openpyxl import load_workbook
wb = load_workbook(SOURCE_FILE_USED)
ws = wb[SOURCE_SHEET_USED]
# 表头第3行定位列号
hdr = {}
for c in ws[3]:
if c.value is not None:
hdr[str(c.value).strip()] = c.column
col_id = hdr.get('身份证号码')
col_status = hdr.get('办理停保') # 减员回写列:办理停保(区别于增员的办理状态)
col_remark = hdr.get('备注')
if not col_id or not col_status:
raise RuntimeError("源名单缺少身份证号码/办理停保列,无法回写")
changed = 0
pending_ids = set(_PENDING_STATUS) | set(_PENDING_REMARK)
ref = [_norm_id(x) for x in pending_ids]
for row in ws.iter_rows(min_row=4):
cid = _norm_id(row[col_id - 1].value)
if cid and _id_hit(cid, ref):
r = row[0].row
if cid in _PENDING_STATUS:
ws.cell(row=r, column=col_status, value=_PENDING_STATUS[cid])
if cid in _PENDING_REMARK and col_remark:
# 备注追加不覆盖:读取原单元格内容,新备注换行追加在后面(已存在则不重复追加)
cell = ws.cell(row=r, column=col_remark)
old = str(cell.value or '').strip()
new = str(_PENDING_REMARK[cid]).strip()
if new in old:
pass # 重查场景:备注已写过,跳过防重复
else:
cell.value = f"{old}\n{new}" if old else new
changed += 1
try:
wb.save(SOURCE_FILE_USED)
except PermissionError:
# 缓存保留,下次启动自动恢复回写
raise RuntimeError("源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
_PENDING_STATUS.clear()
_PENDING_REMARK.clear()
if _CKPT_FILE.exists():
_CKPT_FILE.unlink()
print(f" 源名单回写完成:更新 {changed} 行 → {os.path.basename(SOURCE_FILE_USED)}(缓存已清除)")
print(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
# ==================== 6c. 单个单位完整网页操作 ====================
def do_web_import(task):
"""登录后的完整业务流程:进业务页 → 关提示弹窗 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。
返回结果 dict(JSON 安全)。"""
import sb_login
page = sb_login.LAST_SESSION.get('page')
work_tab = sb_login.LAST_SESSION.get('tab')
if page is None or work_tab is None:
return {"success": False, "message": "无有效登录会话"}
res = {"success": False, "imported": 0, "failed": [], "review": {}}
try:
_shot(work_tab, "01_workbench")
biz_tab = _open_business_page(page, work_tab)
_close_tip_modal(biz_tab) # 进业务页先关「提示信息」弹窗(仅 X 按钮)
_shot(biz_tab, "02_biz_upload_page")
# 1) 上传导入
total, _failed_cnt = _upload_import(biz_tab, task['file'])
res['imported'] = total
# 2) 校验未通过:回写 停保失败 + 备注(详细信息)
# 账目规则:弹窗「成功N人」+「校验未通过人员」= 名单人数,不平账中止防止漏人导致下次重复申报
fail_rows = _read_failed_rows(biz_tab)
res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows]
expected = task.get('count', 0)
if expected and total + len(fail_rows) != expected:
raise RuntimeError(
f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人,"
f"中止该单位(防漏人/重复申报),请人工核对")
if fail_rows:
writeback_source({cid: "停保失败" for cid, _ in fail_rows},
{cid: d for cid, d in fail_rows})
passed = total
# 3) 全员未通过 → 跳过申报
if passed <= 0:
print(" 校验通过人数为 0,跳过申报")
res.update(success=True, message=f"导入{total}人,全部校验未通过,已回写未申报")
return res
# 4) 预申报 → 正式提交 → 查询审核结论回写「办理停保」列
_predeclare_and_submit(page, biz_tab)
review = _query_review_results(page, biz_tab)
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
for cid, (c, sn) in review.items()]
if review:
writeback_source({cid: concl for cid, (concl, _) in review.items()}, {})
res.update(success=True,
message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人")
return res
except Exception as e:
res["message"] = f"网页操作异常:{e}"
return res
# ==================== 7. 逐单位登录 + 网页操作 ====================
def process_units(tasks):
"""逐参保单位:登录政务平台 → 完整网页导入申报 → 回写。
每个账号办完(无论成败)都清 cookies 关浏览器,下个账号全新开始。
回写策略:单位内累积到内存并写 JSON 缓存(防崩溃),运行结束统一回写 Excel 一次。"""
import sb_login
results = []
for i, task in enumerate(tasks, 1):
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人)==========")
print(f"导入文件:{task['file']}")
try:
login_res = sb_login.main({"username": task["username"], "password": task["password"]})
except Exception as e:
login_res = {"success": False, "message": f"登录调用异常:{e}"}
print(f"登录结果:{login_res.get('message')}")
try:
if login_res.get("success"):
web_res = do_web_import(task)
print(f"办理结果:{web_res.get('message')}")
results.append({**task, **web_res})
else:
results.append({**task, "success": False,
"message": login_res.get("message", "")})
finally:
# 账号隔离:清 cookies + 关浏览器,再进入下一单位
sb_login.close_session()
return results
# ==================== 8. 主流程 ====================
def run():
"""主流程:恢复缓存 → 读停保名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录(+导入)→ 统一回写。
返回 JSON 安全 dict。"""
recovered_ids = _load_ckpt()
units = load_units(exclude_ids=recovered_ids)
# 崩溃恢复:上次运行残留的回写缓存统一落盘(排除逻辑已在 load_units 中生效,
# 即使下面回写失败,这些人也不会被当成待办重复申报)
if recovered_ids:
print("\n检测到上次未回写的内容,先统一回写:")
try:
flush_writeback()
except Exception as e:
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
if not units:
return {"success": True, "message": "无待办数据", "total": 0, "done": 0}
accounts = load_accounts([u for u, _ in units])
tasks = precheck(units, accounts)
if tasks is None:
return {"success": False, "message": "预检未通过,详见日志", "total": len(units), "done": 0}
if not DO_LOGIN:
print("DO_LOGIN=False,仅完成预检,跳过登录")
return {"success": True, "message": "预检通过(未登录)", "total": len(tasks), "done": 0}
results = process_units(tasks[:RUN_LIMIT])
# 运行结束:本次累积的回写内容统一写 Excel 一次(失败则 JSON 缓存保留,下次启动恢复)
try:
flush_writeback()
except Exception as e:
print(f"回写失败:{e}")
ok = [r for r in results if r["success"]]
fail = [r for r in results if not r["success"]]
print(f"\n========== 汇总 ==========")
print(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
for r in fail:
print(f" ✗ {r['unit']}:{r.get('message', '')}")
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
"total": len(results), "done": len(ok)}
if __name__ == "__main__":
print(run())
@@ -493,7 +493,10 @@ def _do_login(username, password):
co.headless()
# auto_port:每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
co.auto_port(True)
co.set_argument('--start-maximized') # 浏览器启动即全屏(最大化),避免小窗口下元素被折叠/遮挡
co.set_argument('--start-maximized') # 浏览器启动即全屏(最大化),避免小窗口下元素被折叠/遮挡
# 关闭 Chrome「保存密码」弹窗(登录提交后必弹,遮挡页面且无需保存)
co.set_pref('credentials_enable_service', False)
co.set_pref('profile.password_manager_enabled', False)
page = ChromiumPage(co)
work_tab_holder = {'tab': None}