Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/data/resume_state.py
T

95 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""断点续传状态(单次等待出表 5 分钟,超时先停,下次运行接着等/下载)。
平台是「先登记一条记录(downloadLink 为空)→ 文件生成完再回填」,高峰期出表可能十几分钟
到几小时。本模块只记「本次提交了但还没拿到文件」的任务,避免下次运行重复提交生成任务:
键:<公司id>/<任务类型>(payment / profit)
值:{"from","to","ids":[记录id...],"since":"提交时间","updated":"最后更新时间"}
区间变了视为新任务(覆盖旧键);下载成功后由调用方 clear() 清键。
状态文件落在 %LOCALAPPDATA%\\37duAutomation\\,不进用户财务目录。
"""
import json
import os
import time
from .. import config
def _key(company, kind):
return f'{company}/{kind}'
def _as_int(value):
try:
return int(value)
except (TypeError, ValueError):
return None
def _load_all():
try:
with open(config.PENDING_STATE_PATH, encoding='utf-8') as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def _dump_all(data):
path = config.PENDING_STATE_PATH
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp, path)
def load(company, kind, d_from, d_to):
"""取该区间未完成的任务;没记录或区间不一致 → None。"""
item = _load_all().get(_key(company, kind))
if not isinstance(item, dict):
return None
if item.get('from') != d_from or item.get('to') != d_to:
return None
ids = [_as_int(i) for i in (item.get('ids') or [])]
item['ids'] = [i for i in ids if i is not None]
return item
def save(company, kind, d_from, d_to, ids=None, since=None):
"""登记/更新待续任务;ids 是本次跟踪的记录 id(平台未登记时可为空)。"""
data = _load_all()
item = data.get(_key(company, kind))
if not isinstance(item, dict):
item = {}
item.update({
'from': d_from,
'to': d_to,
'ids': sorted({i for i in (_as_int(x) for x in (ids or [])) if i is not None}),
'updated': time.strftime('%Y-%m-%d %H:%M:%S'),
})
if since:
item['since'] = str(since)
data[_key(company, kind)] = item
try:
_dump_all(data)
except OSError as e:
config.log(f'待续状态写入失败(忽略,不影响本次流程):{e}', 'WARN')
return item
def clear(company, kind):
"""任务已完成(文件已下载)→ 清键;没有其它待续任务时直接删文件。"""
data = _load_all()
if data.pop(_key(company, kind), None) is None:
return
try:
if data:
_dump_all(data)
elif os.path.exists(config.PENDING_STATE_PATH):
os.remove(config.PENDING_STATE_PATH)
except OSError as e:
config.log(f'待续状态清理失败(忽略):{e}', 'WARN')