""" services/contract_payment/schedule_seed.py 用途:合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。 依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。 逻辑:幂等创建;owner 优先平台管理员,否则任意用户。 """ from __future__ import annotations from datetime import datetime from app import db from app.models import ScheduleTask from app.services.permission_roles.service import first_schedule_owner_user from app.services.schedule.timezone_util import compute_next_run_at _DEFAULTS = ( ('SCH-CONTRACT-PAYMENT-SYNC', 'contract-payment-sync', '合同付款 OA 同步(日批)', '0 5 * * *'), ('SCH-CONTRACT-PAYMENT-ALERT-SCAN', 'contract-payment-alert-scan', '合同付款预警扫描(日批)', '0 6 * * *'), ('SCH-CONTRACT-PAYMENT-ALERT-WEEKLY', 'contract-payment-alert-weekly', '合同付款预警周汇总(周五 18:00)', '0 18 * * 5'), ) def ensure_default_contract_payment_schedules(*, commit: bool = True): """幂等创建合同付款同步、每日扫描和周五汇总三个默认排程。 Args: commit: 是否提交新建排程;测试或外层事务可传 False。 Returns: 新建的 ScheduleTask 列表;无用户时返回空列表。 """ owner = first_schedule_owner_user() if owner is None: return [] created = [] for schedule_no, platform_path, name, cron in _DEFAULTS: existing = db.session.query(ScheduleTask).filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path)).first() if existing: continue now = datetime.utcnow() task = ScheduleTask( schedule_no=schedule_no, name=name, schedule_type='platform_job', owner_user_id=owner.id, cron_expr=cron, schedule_timezone='Asia/Shanghai', wait_seconds=0, platform_api_path=platform_path, job_params={}, kb_sync_enabled=False, notify_user_ids_json=[], notify_enabled=False, enabled=True, next_run_at=compute_next_run_at(cron, timezone_name='Asia/Shanghai') or now, created_by=owner.id, updated_by=owner.id, created_at=now, updated_at=now, ) db.session.add(task); created.append(task) if commit and created: db.session.commit() elif not commit: db.session.flush() return created