246 lines
8.9 KiB
Python
246 lines
8.9 KiB
Python
"""
|
|
backend/app/services/equipment_acceptance/config_service.py
|
|
|
|
用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。
|
|
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
|
|
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
|
|
没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from app.core.errors import ValidationError
|
|
from app.core.response import utc_iso
|
|
from app.extensions import db
|
|
from app.models.equipment_acceptance import EquipmentAcceptanceSetting
|
|
from app.models.user import User
|
|
from app.services.equipment_acceptance.snapshot_rules import FIRST_REMINDER_DAY
|
|
|
|
DEFAULT_REMINDER_DAYS = (FIRST_REMINDER_DAY, 37, 44, 51)
|
|
_SETTING_ID = 1
|
|
_ROLE_FIELDS = (
|
|
"buyer_manager_user_id",
|
|
"coo_user_id",
|
|
"executive_user_id",
|
|
)
|
|
_MAX_DAY = 3650
|
|
|
|
|
|
def is_round_4_enabled() -> bool:
|
|
"""
|
|
读取第 4 轮是否启用。
|
|
|
|
核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。
|
|
Returns:
|
|
启用为 True。
|
|
"""
|
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
|
if row is None:
|
|
return False
|
|
return bool(row.round_4_enabled)
|
|
|
|
|
|
def parse_round_4_enabled(raw: Any) -> bool:
|
|
"""
|
|
校验第 4 轮开关。
|
|
|
|
核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。
|
|
Args:
|
|
raw: 接口里的 round_4_enabled。缺省为 None。
|
|
Returns:
|
|
是否启用第 4 轮。
|
|
|
|
Raises:
|
|
ValidationError: 传入了布尔以外的值。
|
|
"""
|
|
if raw is None:
|
|
return False
|
|
if not isinstance(raw, bool):
|
|
raise ValidationError(
|
|
"第 4 轮开关必须是是否启用",
|
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
|
details={"field": "round_4_enabled"},
|
|
)
|
|
return raw
|
|
|
|
|
|
def reminder_days() -> tuple[int, int, int, int]:
|
|
"""
|
|
读取四档天数。
|
|
|
|
核心逻辑:没有配置行时用冻结默认值。扫描用这四个数判断有没有跨档。
|
|
Returns:
|
|
四个逐档增大的正整数。
|
|
"""
|
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
|
if row is None:
|
|
return DEFAULT_REMINDER_DAYS
|
|
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
|
|
|
|
|
|
def first_reminder_day() -> int:
|
|
"""
|
|
读取第 1 档天数,供停留列表判断已逾期。
|
|
|
|
核心逻辑:没有配置行时用冻结默认值,避免列表在未保存配置前失去阈值。
|
|
Returns:
|
|
正整数天数。
|
|
"""
|
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
|
if row is None:
|
|
return DEFAULT_REMINDER_DAYS[0]
|
|
return int(row.day_1)
|
|
|
|
|
|
def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
|
|
"""
|
|
组装配置页数据。
|
|
|
|
核心逻辑:天数和已选用户谁都能看。候选人名单只给平台管理员,避免把全员目录交给普通用户。
|
|
Args:
|
|
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
|
|
Returns:
|
|
days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。
|
|
"""
|
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
|
selected_ids = _selected_ids(row)
|
|
return {
|
|
"days": list(_days_of(row)),
|
|
"round_4_enabled": False if row is None else bool(row.round_4_enabled),
|
|
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
|
|
"coo_user_id": None if row is None else row.coo_user_id,
|
|
"executive_user_id": None if row is None else row.executive_user_id,
|
|
"selected_users": _briefs(selected_ids),
|
|
"users": _candidate_users() if include_candidates else [],
|
|
"updated_at": None if row is None else utc_iso(row.updated_at),
|
|
}
|
|
|
|
|
|
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
|
|
"""
|
|
保存四档天数、第 4 轮开关和三个岗位用户。
|
|
|
|
核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。
|
|
保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。
|
|
Args:
|
|
payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。
|
|
updated_by: 操作人的系统用户主键。
|
|
Returns:
|
|
与读取接口相同的配置,并带候选人。
|
|
|
|
Raises:
|
|
ValidationError: 天数不合法,或岗位用户不存在。
|
|
"""
|
|
days = validate_reminder_days(payload.get("days"))
|
|
round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled"))
|
|
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
|
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
|
if row is None:
|
|
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
|
|
db.session.add(row)
|
|
row.day_1, row.day_2, row.day_3, row.day_4 = days
|
|
row.round_4_enabled = round_4_enabled
|
|
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
|
|
row.coo_user_id = role_ids["coo_user_id"]
|
|
row.executive_user_id = role_ids["executive_user_id"]
|
|
row.updated_at = datetime.utcnow()
|
|
row.updated_by = updated_by
|
|
db.session.commit()
|
|
return get_acceptance_config(include_candidates=True)
|
|
|
|
|
|
def validate_reminder_days(raw: Any) -> tuple[int, int, int, int]:
|
|
"""
|
|
校验四档天数。
|
|
|
|
核心逻辑:必须是四个逐档增大的正整数。布尔值在 Python 里也是 int,这里明确拒绝。
|
|
Args:
|
|
raw: 接口里的 days。
|
|
Returns:
|
|
四个天数。
|
|
|
|
Raises:
|
|
ValidationError: 不是四个逐档增大的天数。
|
|
"""
|
|
if not isinstance(raw, list) or len(raw) != 4:
|
|
_reject_days()
|
|
parsed: list[int] = []
|
|
for value in raw:
|
|
if isinstance(value, bool) or not isinstance(value, int) or value < 1 or value > _MAX_DAY:
|
|
_reject_days()
|
|
parsed.append(value)
|
|
if not (parsed[0] < parsed[1] < parsed[2] < parsed[3]):
|
|
_reject_days()
|
|
return parsed[0], parsed[1], parsed[2], parsed[3]
|
|
|
|
|
|
def _reject_days() -> None:
|
|
"""四档天数不合法时用同一错误码拒绝。"""
|
|
raise ValidationError(
|
|
"设备验收预警的四档天数须逐档增大",
|
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
|
details={"field": "days"},
|
|
)
|
|
|
|
|
|
def _require_user_id(raw: Any, field: str) -> int | None:
|
|
"""空岗位允许保存。有值时必须指向 users 表里的一行。"""
|
|
if raw is None or raw == "":
|
|
return None
|
|
if isinstance(raw, bool) or not isinstance(raw, int) or raw <= 0:
|
|
raise ValidationError(
|
|
"设备验收预警岗位必须选择系统用户",
|
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
|
details={"field": field},
|
|
)
|
|
if db.session.get(User, raw) is None:
|
|
raise ValidationError(
|
|
"设备验收预警岗位必须选择系统用户",
|
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
|
details={"field": field},
|
|
)
|
|
return raw
|
|
|
|
|
|
def _days_of(row: EquipmentAcceptanceSetting | None) -> tuple[int, int, int, int]:
|
|
"""没有配置行时返回冻结默认值。"""
|
|
if row is None:
|
|
return DEFAULT_REMINDER_DAYS
|
|
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
|
|
|
|
|
|
def _selected_ids(row: EquipmentAcceptanceSetting | None) -> list[int]:
|
|
"""收集三个岗位里已经选中的用户主键,供姓名回显。"""
|
|
if row is None:
|
|
return []
|
|
return [user_id for user_id in (row.buyer_manager_user_id, row.coo_user_id, row.executive_user_id) if user_id]
|
|
|
|
|
|
def _candidate_users() -> list[dict[str, Any]]:
|
|
"""在职用户,带部门和企微绑定标记,供选人弹窗分组。"""
|
|
rows = db.session.query(User).filter(User.status == "active").order_by(User.username).all()
|
|
return [_user_brief(user) for user in rows]
|
|
|
|
|
|
def _briefs(user_ids: list[int]) -> list[dict[str, Any]]:
|
|
"""按主键取出已选用户。停用用户也返回,避免页面上只剩一个数字。"""
|
|
if not user_ids:
|
|
return []
|
|
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
|
return [_user_brief(user) for user in rows]
|
|
|
|
|
|
def _user_brief(user: User) -> dict[str, Any]:
|
|
"""选人组件要的展示字段。姓名只从用户资料来,不另存一份。"""
|
|
return {
|
|
"id": user.id,
|
|
"username": user.username,
|
|
"real_name": user.real_name,
|
|
"employee_id": user.employee_id,
|
|
"department": user.department,
|
|
"wecom_bound": bool(user.wecom_userid),
|
|
}
|