75 lines
2.6 KiB
Python
75 lines
2.6 KiB
Python
"""
|
||
backend/app/services/equipment_acceptance/schedule_seed.py
|
||
|
||
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
|
||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
||
"""
|
||
|
||
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-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
|
||
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
|
||
)
|
||
|
||
|
||
def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
|
||
"""
|
||
幂等创建设备验收每日扫描和周五发送两个排程。
|
||
|
||
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
|
||
Args:
|
||
commit: 为 False 时只 flush,交给外层事务提交。
|
||
Returns:
|
||
新建的排程。没有可当负责人的用户时返回空列表。
|
||
"""
|
||
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
|