#!/usr/bin/env python """ scripts/reconcile_legacy_stp_jobs.py 用途:Phase 4-2 —— 历史 STP Job(如 928、929)批量对账恢复管理脚本。 依赖:backend 虚拟环境 + backend.app Flask app;严格复用 services.shipping_notice.reconciliation_service.reconcile_and_progress 主入口; 禁止脚本内直写 SQL、直改 duplicate_status、或写独立业务规则。 逻辑: 1. 解析 CLI 参数:--user-id(管理员)、--case-nos(空格分隔、或 - 读 stdin)、 --user-action(auto/create_revision/…,默认 auto)、--dry-run、--legacy-job-id(可选) --replay-mode(可选,legacy_job_id 与 case_no 不匹配时强制重放) 2. push Flask app context、初始化 SQLAlchemy。 3. 对每个 case_no: - 生成客户端 operation_id(uuid4,脚本自产出;同时记录日志与 stdout) - 调 reconcile_and_progress(user_id, case_no, operation_id, user_action=…, is_admin=True, legacy_job_id=…, replay_mode=…) - 捕获 AppError/ConflictError/ValidationError → 不中断批处理, 仅记录错误行,退出码为成功数!=总数量时返回 2 4. 输出结构化摘要(总数量 / 成功 / failed_technical / duplicate_decision_required / ownership_anomaly_rejected / reused_existing / stp_enqueued / idempotent_replay) 禁止事项(严格 fail-closed): • 禁止绕过权限:必须显式 --user-id 且后台校验为管理员。 • 禁止直写数据库:所有 Case/Job/Candidate 修改都通过 reconciliation_service。 • 禁止与 reconcile_and_progress 不同的业务规则。 """ from __future__ import annotations import argparse import json import logging import sys import uuid from dataclasses import asdict, dataclass, field from typing import Any LOGGER = logging.getLogger('reconcile_legacy_stp_jobs') _OUTCOME_ORDER = [ 'reused_existing', 'stp_enqueued', 'resume_result', 'duplicate_decision_required', 'ownership_anomaly_rejected', 'idempotent_replay', 'ERROR_VALIDATION', 'ERROR_CONFLICT', 'ERROR_APP', 'ERROR_UNEXPECTED', ] @dataclass class RunSummary: total: int = 0 dry_run: bool = False by_outcome: dict[str, int] = field( default_factory=lambda: {k: 0 for k in _OUTCOME_ORDER}, ) cases: list[dict[str, Any]] = field(default_factory=list) def bump(self, outcome: str) -> None: if outcome not in self.by_outcome: self.by_outcome[outcome] = 0 self.by_outcome[outcome] += 1 @property def error_count(self) -> int: return sum(v for k, v in self.by_outcome.items() if k.startswith('ERROR_')) @property def success_count(self) -> int: return self.total - self.error_count def _build_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( 'Reconcile legacy Shipping STP Jobs (e.g. 928/929) via the unified ' 'reconciliation_service — never write raw SQL.' ), ) parser.add_argument( '--user-id', type=int, required=True, help='Admin user id. Must be an existing admin (service-side checks role).', ) parser.add_argument( '--user-action', choices=['auto', 'reuse_existing', 'create_revision', 'force_create', 'adjudicate'], default='auto', help='Reconcile user_action passed to reconcile_and_progress.', ) case_src = parser.add_mutually_exclusive_group(required=True) case_src.add_argument( '--case-nos', nargs='+', metavar='CASE_NO', help='One or more review case_no to process.', ) case_src.add_argument( '--read-case-nos-from-stdin', action='store_true', help='Read case_no from STDIN (one per line, blank/comments ignored).', ) parser.add_argument( '--legacy-job-id', type=int, default=None, help='(Admin-only) Attach a specific failed/dead STP Job.id as legacy_job_id.', ) parser.add_argument( '--replay-mode', action='store_true', help='Allow --legacy_job_id to reference a Job whose reference_key != case_no.', ) parser.add_argument( '--expected-case-version', type=int, default=None, help='Optional expected_case_version guard.', ) parser.add_argument( '--dry-run', action='store_true', help='Validate + print plan; do NOT actually call reconcile_and_progress.', ) parser.add_argument( '--json-output', action='store_true', help='Print a JSON summary to stdout at the end.', ) parser.add_argument( '-v', '--verbose', action='count', default=0, help='Increase logging verbosity (-v: INFO, -vv: DEBUG).', ) return parser def _read_case_nos_from_stdin() -> list[str]: raw = sys.stdin.read().splitlines() out: list[str] = [] for line in raw: s = line.strip() if not s or s.startswith('#'): continue out.append(s) return out def _process_one( *, user_id: int, case_no: str, user_action: str, expected_case_version: int | None, legacy_job_id: int | None, replay_mode: bool, ): """ 对单个 case_no 调 reconcile_and_progress;返回 (outcome, result_or_none, error_dict_or_none)。 所有业务路径都通过 reconciliation_service;禁止写任何 SQL。 """ from app import create_app, db # type: ignore # noqa: F401 — 仅在 app context 中引用 from app.core.errors import AppError, ConflictError, ValidationError # noqa: F401 from app.services.shipping_notice.reconciliation_service import reconcile_and_progress # noqa: F401 op_id = str(uuid.uuid4()) kwargs: dict[str, Any] = { 'user_id': int(user_id), 'case_no': str(case_no).strip(), 'operation_id': op_id, 'user_action': user_action, # type: ignore[arg-type] 'expected_case_version': expected_case_version, 'source_content_hash': None, 'is_admin': True, 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), 'replay_mode': bool(replay_mode), } try: result = reconcile_and_progress(**kwargs) except ValidationError as exc: return 'ERROR_VALIDATION', None, { 'code': getattr(exc, 'code', None), 'message': str(getattr(exc, 'message', None) or str(exc)), 'details': getattr(exc, 'details', None), } except ConflictError as exc: return 'ERROR_CONFLICT', None, { 'code': getattr(exc, 'code', None), 'message': str(getattr(exc, 'message', None) or str(exc)), 'details': getattr(exc, 'details', None), } except AppError as exc: return 'ERROR_APP', None, { 'code': getattr(exc, 'code', None), 'message': str(getattr(exc, 'message', None) or str(exc)), } except Exception as exc: # noqa: BLE001 LOGGER.exception('unexpected error processing case_no=%s', case_no) return 'ERROR_UNEXPECTED', None, { 'type': type(exc).__name__, 'message': str(exc), } return str(result.outcome), result, None def _main(argv: list[str] | None = None) -> int: parser = _build_arg_parser() args = parser.parse_args(argv) level = logging.WARNING if args.verbose == 1: level = logging.INFO elif args.verbose >= 2: level = logging.DEBUG logging.basicConfig( level=level, format='%(asctime)s %(levelname)s %(name)s: %(message)s', ) # 在函数内部 import app,便于从 backend/ 根用 python ../scripts/… 运行 from app import create_app # type: ignore app = create_app() with app.app_context(): # 保证 session 已绑定;脚本内绝不直接操作 db.session。 from app import db # type: ignore _ = db.session if args.read_case_nos_from_stdin: case_nos = _read_case_nos_from_stdin() else: case_nos = [ str(c).strip() for c in (args.case_nos or []) if str(c).strip() ] if not case_nos: print('ERROR: no case_no provided.', file=sys.stderr) return 2 summary = RunSummary(total=len(case_nos), dry_run=bool(args.dry_run)) for case_no in case_nos: operation_id = str(uuid.uuid4()) # dry-run 时也产出 operation_id 用于审计 if args.dry_run: LOGGER.info( '[DRY-RUN] case_no=%s user_action=%s user_id=%s operation_id=%s ' 'legacy_job_id=%s replay_mode=%s', case_no, args.user_action, args.user_id, operation_id, args.legacy_job_id, args.replay_mode, ) summary.bump('resume_result') summary.cases.append({ 'case_no': case_no, 'operation_id': operation_id, 'outcome': 'DRY_RUN_PLANNED', 'user_action': args.user_action, 'legacy_job_id': args.legacy_job_id, 'replay_mode': bool(args.replay_mode), }) continue outcome, result, err = _process_one( user_id=int(args.user_id), case_no=case_no, user_action=str(args.user_action), expected_case_version=args.expected_case_version, legacy_job_id=args.legacy_job_id, replay_mode=bool(args.replay_mode), ) summary.bump(outcome) case_row: dict[str, Any] = { 'case_no': case_no, 'outcome': outcome, 'user_action': args.user_action, } if result is not None: case_row.update({ 'operation_id': getattr(result, 'operation_id', None), 'idempotency_key': getattr(result, 'idempotency_key', None), 'match': dict(getattr(result, 'match') or {}), 'task_no': getattr(result, 'task_no', None), 'job_id': getattr(result, 'job_id', None), 'message': getattr(result, 'message', None), }) m = getattr(result, 'match', None) if hasattr(result, 'match') else None if isinstance(m, dict): case_row.update({ 'match_level': m.get('match_level'), 'confidence': m.get('confidence'), 'matched_task_no': m.get('task_no'), }) if err is not None: case_row['error'] = err if args.verbose: LOGGER.info('case=%s outcome=%s', case_no, outcome) summary.cases.append(case_row) # ===== 输出 ===== if args.json_output: print(json.dumps(asdict(summary), ensure_ascii=False, indent=2, default=str)) else: # 人类可读摘要 print('==== Reconcile Legacy STP Jobs Summary ====') print(f'total : {summary.total}') print(f'dry_run : {summary.dry_run}') for k in _OUTCOME_ORDER: c = summary.by_outcome.get(k, 0) if c: print(f' {k:<32s}: {c}') print(f'success : {summary.success_count}') print(f'errors : {summary.error_count}') if summary.total == 0: return 0 if summary.error_count > 0: return 2 return 0 if __name__ == '__main__': raise SystemExit(_main())