140 lines
5.5 KiB
Python
140 lines
5.5 KiB
Python
|
|
"""用户补充的候选来源。与计划共用文件锁,先保存,再由修订任务发布。"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import datetime as dt
|
|||
|
|
import json
|
|||
|
|
import re
|
|||
|
|
import uuid
|
|||
|
|
from pathlib import Path
|
|||
|
|
from zoneinfo import ZoneInfo
|
|||
|
|
|
|||
|
|
import plan_versions as pv
|
|||
|
|
|
|||
|
|
BJ = ZoneInfo('Asia/Shanghai')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def normalize(value):
|
|||
|
|
value = str(value or '').strip().upper()
|
|||
|
|
if re.fullmatch(r'\d{6}\.(SH|SZ)', value):
|
|||
|
|
value = value[-2:] + value[:6]
|
|||
|
|
elif re.fullmatch(r'\d{6}', value):
|
|||
|
|
value = ('SH' if value.startswith(('60', '68')) else 'SZ') + value
|
|||
|
|
if not re.fullmatch(r'(SH(?:60|68)\d{4}|SZ(?:00|30)\d{4})', value):
|
|||
|
|
raise ValueError('仅支持沪深 A 股,请检查股票代码')
|
|||
|
|
return value
|
|||
|
|
|
|||
|
|
|
|||
|
|
def read(root):
|
|||
|
|
path = Path(root) / 'user_candidates.json'
|
|||
|
|
if not path.exists():
|
|||
|
|
return {'revision': 0, 'rows': []}
|
|||
|
|
state = json.loads(path.read_text())
|
|||
|
|
if not isinstance(state.get('rows'), list) or not isinstance(state.get('revision'), int):
|
|||
|
|
raise ValueError('添加记录暂不可用')
|
|||
|
|
return state
|
|||
|
|
|
|||
|
|
|
|||
|
|
def active(root, now=None):
|
|||
|
|
today = (now or dt.datetime.now(BJ)).astimezone(BJ).date().isoformat()
|
|||
|
|
return [dict(r) for r in read(root)['rows']
|
|||
|
|
if not r.get('removed_at') and r['expires_on'] >= today]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def save(root, payload, actor, now=None):
|
|||
|
|
now = now or dt.datetime.now(BJ)
|
|||
|
|
raw = payload.get('codes')
|
|||
|
|
if isinstance(raw, str):
|
|||
|
|
raw = re.split(r'[\s,,;;]+', raw.strip())
|
|||
|
|
if not isinstance(raw, list) or not 1 <= len(raw) <= 30:
|
|||
|
|
raise ValueError('每次可添加 1 至 30 只股票')
|
|||
|
|
codes = list(dict.fromkeys(normalize(c) for c in raw))
|
|||
|
|
reason = str(payload.get('reason') or '').strip()
|
|||
|
|
if not reason or len(reason) > 300:
|
|||
|
|
raise ValueError('请填写添加理由,最多 300 字')
|
|||
|
|
try:
|
|||
|
|
expires = dt.date.fromisoformat(str(payload.get('expires_on') or ''))
|
|||
|
|
except ValueError as exc:
|
|||
|
|
raise ValueError('请选择关注截止日期') from exc
|
|||
|
|
if not now.astimezone(BJ).date() <= expires <= now.astimezone(BJ).date() + dt.timedelta(days=90):
|
|||
|
|
raise ValueError('关注期限应在今天至未来 90 天内')
|
|||
|
|
with pv.writer(root):
|
|||
|
|
state = read(root)
|
|||
|
|
current = {r['code'] for r in active(root, now)}
|
|||
|
|
added = []
|
|||
|
|
for code in codes:
|
|||
|
|
if code in current:
|
|||
|
|
continue
|
|||
|
|
row = {'id': uuid.uuid4().hex, 'code': code, 'reason': reason,
|
|||
|
|
'expires_on': expires.isoformat(), 'created_at': now.isoformat(),
|
|||
|
|
'created_by': str(actor)[:100]}
|
|||
|
|
state['rows'].append(row)
|
|||
|
|
added.append(row)
|
|||
|
|
if added:
|
|||
|
|
state['revision'] += 1
|
|||
|
|
pv.atomic(Path(root) / 'user_candidates.json', state)
|
|||
|
|
mark_pending(root, [r['code'] for r in added])
|
|||
|
|
return {'ok': True, 'added': len(added), 'existing': len(codes) - len(added),
|
|||
|
|
'revision': state['revision']}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def remove(root, identity, actor, now=None):
|
|||
|
|
now = now or dt.datetime.now(BJ)
|
|||
|
|
with pv.writer(root):
|
|||
|
|
state = read(root)
|
|||
|
|
row = next((r for r in state['rows'] if r['id'] == identity), None)
|
|||
|
|
if row is None:
|
|||
|
|
raise ValueError('添加记录不存在,请刷新后重试')
|
|||
|
|
if not row.get('removed_at'):
|
|||
|
|
row.update(removed_at=now.isoformat(), removed_by=str(actor)[:100])
|
|||
|
|
state['revision'] += 1
|
|||
|
|
pv.atomic(Path(root) / 'user_candidates.json', state)
|
|||
|
|
mark_pending(root, [row['code']])
|
|||
|
|
return {'ok': True, 'revision': state['revision']}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def mark_pending(root, codes):
|
|||
|
|
day = pv.latest_date(root)
|
|||
|
|
if day:
|
|||
|
|
state = pv.health(root, day)
|
|||
|
|
pv.health(root, day, pending_codes=sorted(set(state.get('pending_codes') or []) | set(codes)))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def live_pending(root, published, now=None):
|
|||
|
|
"""写后未发布、删除或到期时,即使后台失败也不能继续消费旧人工来源。"""
|
|||
|
|
current = {r['code']: r['id'] for r in active(root, now)}
|
|||
|
|
frozen = {r['code']: r['id'] for r in published.get('user_candidates', [])}
|
|||
|
|
return sorted(c for c in current.keys() | frozen.keys() if current.get(c) != frozen.get(c))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def listing(root, now=None):
|
|||
|
|
now = now or dt.datetime.now(BJ)
|
|||
|
|
state = read(root)
|
|||
|
|
try:
|
|||
|
|
published = pv.load(root)
|
|||
|
|
except FileNotFoundError:
|
|||
|
|
published = {}
|
|||
|
|
material = {r['code']: r for b in ('main', 'observe') for r in published.get(b, [])}
|
|||
|
|
expected = {r['id'] for r in published.get('user_candidates', [])}
|
|||
|
|
today = now.astimezone(BJ).date().isoformat()
|
|||
|
|
rows = []
|
|||
|
|
for source in reversed(state['rows']):
|
|||
|
|
row = material.get(source['code']) or {}
|
|||
|
|
status = ('removed' if source.get('removed_at') else
|
|||
|
|
'expired' if source['expires_on'] < today else
|
|||
|
|
'pending' if source['id'] not in expected else 'evaluated')
|
|||
|
|
rows.append({**source, 'status': status, 'name': row.get('name'),
|
|||
|
|
'verdict': row.get('verdict'), 'basis': row.get('basis'),
|
|||
|
|
'decision_id': (published.get('decision') or {}).get('id')})
|
|||
|
|
return {'ok': True, 'rows': rows[:300], 'revision': state['revision']}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def refresh_saved():
|
|||
|
|
"""请求结束后尝试发布;失败保留登记和待核验状态,定时修订会重试。"""
|
|||
|
|
import logging
|
|||
|
|
import plan_refresh
|
|||
|
|
try:
|
|||
|
|
return plan_refresh.refresh()
|
|||
|
|
except Exception:
|
|||
|
|
logging.getLogger(__name__).exception('用户候选已保存,计划修订待重试')
|
|||
|
|
return {'status': 'pending'}
|