Merge branch 'feature/equipment-acceptance-sync' into dev

This commit is contained in:
sophie committed 2026-10-12 14:06:36 +08:00
commit 91a4bcbb8b
48 files changed
+6196 -82

No files matched your search

+5
View File
@@ -122,6 +122,11 @@ def create_app(config_name='default'):
ensure_default_contract_payment_schedules()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
try:
from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules
ensure_default_equipment_acceptance_schedules()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc)
try:
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
ensure_default_order_delivery_schedules()
+2
View File
@@ -49,6 +49,7 @@ def register_blueprints(app: Flask) -> None:
)
from app.api.files import files_bp
from app.api.contract_payment import contract_payment_bp
from app.api.equipment_acceptance import equipment_acceptance_bp
from app.api.order_delivery_reply import order_delivery_reply_bp
from app.api.in_transit_transfer import in_transit_transfer_bp
from app.api.integration_connector import integration_connector_bp
@@ -81,6 +82,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
app.register_blueprint(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
@@ -0,0 +1,183 @@
"""
backend/app/api/equipment_acceptance/__init__.py
用途:设备验收预警的 Chat 作业面接口。
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录和配置;同步、扫描、发送和保存配置仅平台管理员。
"""
from __future__ import annotations
from flask import Blueprint, g, request
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError
from app.core.response import ok
from app.models import Agent
from app.services.equipment_acceptance.config_service import (
get_acceptance_config,
save_acceptance_config,
)
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
from app.services.equipment_acceptance.send_record_service import list_send_records
from app.services.equipment_acceptance.sync_service import (
get_acceptance_order,
list_acceptance_orders,
sync_acceptance_snapshots,
)
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
def _require_user():
"""
读取当前登录用户。
Returns:
已认证用户。
Raises:
UnauthorizedError: 没有有效登录身份。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _user_has_equipment_acceptance_agent(user) -> bool:
"""
判断用户是否持有启用中的设备验收预警 Agent。
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions。
"""
agent = Agent.query.filter_by(agent_code=EQUIPMENT_ACCEPTANCE_AGENT_CODE, is_active=True).first()
return bool(agent is not None and agent in user.agents)
def _require_equipment_acceptance_access():
"""
确保当前用户可以打开设备验收预警作业面。
核心逻辑:平台管理员放行;普通用户必须被授予启用中的 equipment_acceptance Agent。
Returns:
已认证且有权查看的用户。
Raises:
UnauthorizedError: 没有有效登录身份。
ForbiddenError: 已登录但没有该 Agent。
"""
user = _require_user()
if user.is_platform_admin() or _user_has_equipment_acceptance_agent(user):
return user
raise ForbiddenError(
"Equipment acceptance agent permission required",
code="EQUIPMENT_ACCEPTANCE.FORBIDDEN",
)
def _require_equipment_acceptance_admin():
"""
确保当前用户可以触发 E10 同步。
核心逻辑:先确认能看作业面,再要求平台管理员。同步会读取外部库并改写本地快照。
Returns:
已认证的管理员。
Raises:
ForbiddenError: 不是平台管理员。
"""
user = _require_equipment_acceptance_access()
if not user.is_platform_admin():
raise ForbiddenError(
"Admin privilege required for equipment acceptance sync",
code="EQUIPMENT_ACCEPTANCE.ADMIN_REQUIRED",
)
return user
@equipment_acceptance_bp.route("/sync", methods=["POST"])
def sync_equipment_acceptance():
"""从 E10 拉取验收单并写入本地快照。仅平台管理员。"""
_require_equipment_acceptance_admin()
return ok(sync_acceptance_snapshots(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/orders", methods=["GET"])
def list_equipment_acceptance_orders():
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
_require_equipment_acceptance_access()
page = _int_arg("page", 1)
page_size = _int_arg("page_size", 20)
payload = list_acceptance_orders(
monitor_status=request.args.get("monitor_status"),
focus=request.args.get("focus"),
page=page,
page_size=page_size,
)
return ok(payload, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/config", methods=["GET"])
def get_equipment_acceptance_config():
"""读取四档天数和三个固定岗位。候选人名单只给平台管理员。"""
user = _require_equipment_acceptance_access()
payload = get_acceptance_config(include_candidates=user.is_platform_admin())
return ok(payload, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/config", methods=["PUT"])
def save_equipment_acceptance_config():
"""保存四档天数和三个固定岗位。仅平台管理员。发送时刻不在本接口。"""
user = _require_equipment_acceptance_access()
if not user.is_platform_admin():
raise ForbiddenError(
"Admin privilege required for equipment acceptance settings",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_ADMIN_REQUIRED",
)
payload = request.get_json(silent=True) or {}
saved = save_acceptance_config(payload, updated_by=user.id)
return ok(saved, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
def scan_equipment_acceptance_alerts():
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
_require_equipment_acceptance_admin()
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
def send_equipment_acceptance_alerts():
"""管理员立即把待发送记录按收件人发到企业微信。"""
_require_equipment_acceptance_admin()
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/sends", methods=["GET"])
def list_equipment_acceptance_sends():
"""分页查看发送记录。扫描写入后这里才有行。"""
_require_equipment_acceptance_access()
payload = list_send_records(page=_int_arg("page", 1), page_size=_int_arg("page_size", 20))
return ok(payload, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/orders/<int:order_id>", methods=["GET"])
def get_equipment_acceptance_order(order_id: int):
"""查看一张验收单的节点和操作人原值。"""
_require_equipment_acceptance_access()
return ok(get_acceptance_order(order_id), request_id=getattr(g, "request_id", None))
def _int_arg(name: str, default: int) -> int:
"""读取正整数查询参数,非法时用默认值。"""
raw = request.args.get(name)
if raw is None or str(raw).strip() == "":
return default
try:
return int(raw)
except (TypeError, ValueError):
return default
+1 -1
View File
@@ -499,7 +499,7 @@ class Config:
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
+13 -1
View File
@@ -2,7 +2,7 @@
backend/app/models/__init__.py
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
"""
@@ -238,6 +238,13 @@ from app.models.contract_payment import (
ContractPaymentSyncState,
ContractPaymentVendorRequest,
)
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.order_delivery_reply import (
OrderDeliveryAuditEvent,
OrderDeliveryBatch,
@@ -434,6 +441,11 @@ __all__ = [
'ContractPaymentAlert',
'ContractPaymentAlertBatch',
'ContractPaymentSyncState',
'EquipmentAcceptanceOrder',
'EquipmentAcceptanceNode',
'EquipmentAcceptanceOperator',
'EquipmentAcceptanceSetting',
'EquipmentAcceptanceSendRecord',
'TransferRun',
'TransferSourceJob',
'TransferMatching',
+156
View File
@@ -0,0 +1,156 @@
"""
backend/app/models/equipment_acceptance.py
用途:设备验收预警的本地同步快照和可改配置。
依赖:models.base.Base、users。
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
配置表只存四档天数和三个固定岗位的系统用户。发送时刻不在这张表。
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
不保存流程编号、第二合同编号、验收日期和 isremark。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class EquipmentAcceptanceOrder(Base):
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
__tablename__ = "equipment_acceptance_orders"
__table_args__ = (
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
)
id: Mapped[int] = mapped_column(primary_key=True)
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
can_accept: Mapped[Optional[int]] = mapped_column(
nullable=True,
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
)
cannot_accept_note: Mapped[Optional[str]] = mapped_column(
Text,
nullable=True,
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
)
is_returned: Mapped[Optional[int]] = mapped_column(
nullable=True,
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
)
flow_status_raw: Mapped[Optional[int]] = mapped_column(nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
request_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
request_match_count: Mapped[int] = mapped_column(nullable=False, default=0)
owner_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
owner_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
owner_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
equip_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
equip_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
equip_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
applicant_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
applicant_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
applicant_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
monitor_status: Mapped[str] = mapped_column(String(40), nullable=False)
present_in_source: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class EquipmentAcceptanceNode(Base):
"""同步时看到的当前节点。一条流程可以有多行。"""
__tablename__ = "equipment_acceptance_nodes"
__table_args__ = (
UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
Index("ix_equipment_acceptance_nodes_order", "order_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
)
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
node_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
node_type: Mapped[Optional[int]] = mapped_column(nullable=True)
class EquipmentAcceptanceOperator(Base):
"""当前节点上的操作人。同一节点同一人只留一行。不保存 isremark。"""
__tablename__ = "equipment_acceptance_operators"
__table_args__ = (
Index("ix_equipment_acceptance_operators_order", "order_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
)
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
handler_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
handler_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
class EquipmentAcceptanceSetting(Base):
"""预警配置。全表只使用 id=1 这一行。岗位存系统用户主键,姓名不入库。"""
__tablename__ = "equipment_acceptance_settings"
id: Mapped[int] = mapped_column(primary_key=True)
day_1: Mapped[int] = mapped_column(nullable=False, default=30)
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
coo_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
executive_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(nullable=True)
class EquipmentAcceptanceSendRecord(Base):
"""一张验收单某一档的发送记录。同一张单同一档只留一行。已发送后不改收件人。"""
__tablename__ = "equipment_acceptance_send_records"
__table_args__ = (
UniqueConstraint("order_id", "tier", name="uq_equipment_acceptance_send_records_order_tier"),
Index("ix_equipment_acceptance_send_records_created", "created_at"),
Index("ix_equipment_acceptance_send_records_status", "status"),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("equipment_acceptance_orders.id", ondelete="SET NULL"), nullable=True
)
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
tier: Mapped[int] = mapped_column(nullable=False)
threshold_days: Mapped[int] = mapped_column(nullable=False)
to_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
cc_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
recipients_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
@@ -0,0 +1,7 @@
"""
backend/app/services/equipment_acceptance/__init__.py
用途:设备验收预警同步包。
依赖:snapshot_rules、source_group、query_sql、sync_service。
逻辑:本包只做 OA 只读同步和本地快照,不发送企业微信。
"""
@@ -0,0 +1,233 @@
"""
backend/app/services/equipment_acceptance/alert_plan.py
用途:判断验收单跨了哪几档,并把主送、抄送收成一条待发送。
依赖:无。不读数据库,不访问 OA,不发企业微信。
逻辑:扫描服务先解析出人员,再调用本模块去重和定状态。超过天数才进档,等于阈值不算。
"""
from __future__ import annotations
from typing import Any
def due_tiers(dwell_days: int | None, thresholds: tuple[int, int, int, int]) -> list[int]:
"""
按累计天数给出已经跨过的档位。
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
Args:
dwell_days: 签核自然日。没有计时起点时为空。
thresholds: 四个天数,对应第 1 到第 4 档。
Returns:
档位号 1 到 4 的列表。没有跨档时为空。
"""
if dwell_days is None:
return []
return [index + 1 for index, day in enumerate(thresholds) if dwell_days > day]
def make_person(
*,
slot: str,
label: str,
name: str | None = None,
user_id: int | None = None,
wecom_userid: str | None = None,
oa_employee_id: int | None = None,
error: str | None = None,
) -> dict[str, Any]:
"""
收成一名收件人。
核心逻辑:解析失败时留下 error,不改成别的人。
Args:
slot: to 主送,cc 抄送。
label: 角色名称,例如当前处理人、直接主管。
name: 展示姓名。
user_id: 系统用户主键。对不上时为空。
wecom_userid: 已绑定的企业微信 userid。
oa_employee_id: E10 employee.ID。
error: 解析失败原因。成功时为空。
Returns:
写入 recipients_json 的字典。
"""
return {
"slot": slot,
"label": label,
"name": name,
"user_id": user_id,
"wecom_userid": wecom_userid or None,
"oa_employee_id": oa_employee_id,
"error": error,
}
def resolve_account(
*,
slot: str,
label: str,
name: str | None,
job_num: str | None,
user: Any,
missing_job_error: str,
oa_employee_id: int | None = None,
) -> dict[str, Any]:
"""
用工号对上系统用户,并要求已绑定企业微信。
核心逻辑:没有工号、对不上用户、没绑企微都记失败,不换成别人。
Args:
slot: to 或 cc。
label: 角色名称。
name: OA 或快照上的姓名。
job_num: employee.JOB_NUM,对应 users.employee_id。
user: 已按工号找到的用户。需要 id、wecom_userid,姓名优先 real_name。
missing_job_error: 没有工号时的失败原因。
oa_employee_id: E10 人员 ID。
Returns:
一名收件人。
"""
if not str(job_num or "").strip():
return make_person(
slot=slot,
label=label,
name=name,
oa_employee_id=oa_employee_id,
error=missing_job_error,
)
if user is None:
return make_person(
slot=slot,
label=label,
name=name,
oa_employee_id=oa_employee_id,
error="未对上系统用户",
)
display = _user_name(user) or name
wecom = str(getattr(user, "wecom_userid", None) or "").strip()
if not wecom:
return make_person(
slot=slot,
label=label,
name=display,
user_id=getattr(user, "id", None),
oa_employee_id=oa_employee_id,
error="未绑定企业微信",
)
return make_person(
slot=slot,
label=label,
name=display,
user_id=getattr(user, "id", None),
wecom_userid=wecom,
oa_employee_id=oa_employee_id,
)
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
"""
把预警配置里的固定岗位收成收件人。
核心逻辑:没选人或没绑企微都记失败。不使用代码里的姓名兜底。
Args:
slot: to 或 cc。
label: 采购经副理、COO 或总经理。
user: 配置指向的系统用户。空表示未选。
missing_error: 未选人时的失败原因。
Returns:
一名收件人。
"""
if user is None:
return make_person(slot=slot, label=label, error=missing_error)
return resolve_account(
slot=slot,
label=label,
name=_user_name(user),
job_num="configured",
user=user,
missing_job_error=missing_error,
)
def assemble_tier(
*,
tier: int,
threshold_days: int,
to_people: list[dict[str, Any]],
cc_people: list[dict[str, Any]],
) -> dict[str, Any]:
"""
把一档的主送和抄送收成一条发送记录草稿。
核心逻辑:同一人同时出现在主送和抄送时只留主送。至少有一名可发的人则为待发送,否则整档失败。
失败原因留在记录上,不把名额转给别人。
Args:
tier: 1 到 4。
threshold_days: 这一档的天数。
to_people: 主送。
cc_people: 抄送。
Returns:
tier、threshold_days、to_text、cc_text、recipients、status、error_message。
"""
primary = _dedupe(to_people)
copied = _drop_already_primary(_dedupe(cc_people), primary)
recipients = primary + copied
errors = [item["error"] for item in recipients if item.get("error")]
ready = any(item.get("wecom_userid") and not item.get("error") for item in recipients)
return {
"tier": tier,
"threshold_days": threshold_days,
"to_text": _names(primary) or None,
"cc_text": _names(copied) or None,
"recipients": recipients,
"status": "pending" if ready else "failed",
"error_message": ";".join(errors) or None,
}
def _dedupe(people: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""同一系统用户或同一 OA 人员只留第一次。解析失败的行各自保留。"""
seen: set[tuple[Any, ...]] = set()
kept: list[dict[str, Any]] = []
for person in people:
if person.get("user_id"):
key: tuple[Any, ...] = ("user", person["user_id"])
elif person.get("oa_employee_id") and not person.get("error"):
key = ("oa", person["oa_employee_id"])
else:
key = ("error", person.get("label"), person.get("name"), person.get("error"))
if key in seen:
continue
seen.add(key)
kept.append(person)
return kept
def _drop_already_primary(copied: list[dict[str, Any]], primary: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""抄送里已经是主送的人不再重复。"""
keys = {_identity(person) for person in primary}
return [person for person in copied if _identity(person) not in keys]
def _identity(person: dict[str, Any]) -> tuple[Any, ...]:
"""用系统用户或 OA 人员识别同一个人。失败行用原因区分。"""
if person.get("user_id"):
return ("user", person["user_id"])
if person.get("oa_employee_id") and not person.get("error"):
return ("oa", person["oa_employee_id"])
return ("error", person.get("label"), person.get("name"), person.get("error"))
def _names(people: list[dict[str, Any]]) -> str:
"""只拼接解析成功的姓名。"""
return "、".join(str(person["name"]) for person in people if person.get("name") and not person.get("error"))
def _user_name(user: Any) -> str | None:
"""系统用户展示名:真实姓名优先,其次用户名。"""
real_name = str(getattr(user, "real_name", None) or "").strip()
if real_name:
return real_name
username = str(getattr(user, "username", None) or "").strip()
return username or None
@@ -0,0 +1,481 @@
"""
backend/app/services/equipment_acceptance/alert_service.py
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
依赖:同步服务、OA 人员目录、alert_plan、发送记录模型、企微通知。
逻辑:扫描先同步 E10,再按停留天数跨档。停表取消未发送记录。已发送的不重发、不改收件人。
"""
from __future__ import annotations
import logging
from datetime import datetime
from typing import Any
from app.extensions import db
from app.models.equipment_acceptance import (
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.user import User
from app.services.equipment_acceptance.alert_plan import (
assemble_tier,
due_tiers,
make_person,
resolve_account,
resolve_configured_user,
)
from app.services.equipment_acceptance.config_service import reminder_days
from app.services.equipment_acceptance.snapshot_rules import WATCHING
_LOGGER = logging.getLogger(__name__)
_SETTING_ID = 1
_EVENT = "equipment_acceptance_warning"
_UNSENT = ("pending", "failed")
def generate_alerts() -> dict[str, Any]:
"""
同步 E10 后生成或更新待发送记录。
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
Returns:
sync 摘要,以及 created、updated、cancelled 条数。
"""
from app.services.equipment_acceptance.sync_service import sync_acceptance_snapshots
sync_result = sync_acceptance_snapshots()
summary = refresh_pending_alerts()
# 同步提交时已经取消的未发送,刷新阶段不会再数到,这里加回去。
summary["cancelled"] += int(sync_result.get("cancelled") or 0)
summary["sync"] = sync_result
return summary
def refresh_pending_alerts(
*,
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None = None,
) -> dict[str, Any]:
"""
按本地快照刷新待发送记录。
核心逻辑:计时中的单据跨过哪一档就保留哪一档。已发送和已取消不改。
未计时或已停表的单据,把还没发出的记录改成已取消。
Args:
directory: 测试注入的人员目录和经副理。空则查询 E10。
Returns:
created、updated、cancelled。
"""
orders = db.session.query(EquipmentAcceptanceOrder).all()
operators = _operators_by_order([order.id for order in orders])
people, deputies = directory if directory is not None else _load_directory(orders, operators)
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
roles = _configured_users()
thresholds = reminder_days()
existing = {
(row.order_id, row.tier): row
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
if row.order_id is not None
}
created = 0
updated = 0
cancelled = 0
for order in orders:
if order.monitor_status != WATCHING:
cancelled += cancel_unsent(order.id)
continue
for draft in _drafts(order, operators.get(order.id, []), people, deputies, users_by_job, roles, thresholds):
current = existing.get((order.id, draft["tier"]))
if current is not None and current.status in ("sent", "cancelled"):
continue
if current is None:
current = EquipmentAcceptanceSendRecord(
order_id=order.id,
tier=draft["tier"],
threshold_days=draft["threshold_days"],
status=draft["status"],
created_at=datetime.utcnow(),
)
db.session.add(current)
existing[(order.id, draft["tier"])] = current
created += 1
else:
updated += 1
_apply_draft(current, order, draft)
db.session.commit()
return {"created": created, "updated": updated, "cancelled": cancelled}
def cancel_unsent(order_id: int) -> int:
"""
取消一张验收单上还没发出的预警。
核心逻辑:待发送和解析失败都还没出企业微信,停表后改成已取消。已发送的保留。
Args:
order_id: 本地验收单主键。
Returns:
改成已取消的行数。
"""
rows = (
db.session.query(EquipmentAcceptanceSendRecord)
.filter(
EquipmentAcceptanceSendRecord.order_id == order_id,
EquipmentAcceptanceSendRecord.status.in_(_UNSENT),
EquipmentAcceptanceSendRecord.sent_at.is_(None),
)
.all()
)
for row in rows:
row.status = "cancelled"
return len(rows)
def send_pending_alerts() -> dict[str, Any]:
"""
把待发送记录按收件人合并成一条企业微信。
核心逻辑:同一个人本轮只收一条。解析失败的人不改发给别人。已取消和已发送不参与。
Returns:
成功人数、失败人数,以及对应的记录条数。
"""
from app.models import Agent
from app.services.integrations.wecom.notify import send_wecom_event_message
rows = (
db.session.query(EquipmentAcceptanceSendRecord)
.filter(EquipmentAcceptanceSendRecord.status == "pending")
.all()
)
orders = {
order.id: order
for order in db.session.query(EquipmentAcceptanceOrder)
.filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id]))
.all()
} if rows else {}
users = _users_by_id(_recipient_user_ids(rows))
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
for row in rows:
for person in list(row.recipients_json or []):
wecom_id = str(person.get("wecom_userid") or "").strip()
if person.get("error") or not wecom_id:
continue
buckets.setdefault(wecom_id, []).append((row, person))
agent = db.session.query(Agent).filter_by(agent_code="equipment_acceptance", is_active=True).first()
jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace"
jump_params = {"view": "sends"} if agent is not None else None
sent_ids: set[str] = set()
failed_ids: set[str] = set()
for wecom_id, entries in buckets.items():
user = _audit_user(entries, users)
try:
result = send_wecom_event_message(
event_type=_EVENT,
user=user,
title="设备验收停留提醒",
content=_message(entries, orders),
jump_path=jump_path,
jump_params=jump_params,
wecom_userid=wecom_id,
)
ok = bool(result.get("ok"))
except Exception:
_LOGGER.warning("equipment acceptance wecom send failed")
ok = False
(sent_ids if ok else failed_ids).add(wecom_id)
records_sent = 0
records_failed = 0
now = datetime.utcnow()
for row in rows:
ready = {
str(person.get("wecom_userid") or "").strip()
for person in list(row.recipients_json or [])
if person.get("wecom_userid") and not person.get("error")
}
ready.discard("")
if not ready:
continue
if ready & failed_ids:
row.status = "failed"
row.error_message = _join_error(row.error_message, "企业微信发送失败")
records_failed += 1
elif ready <= sent_ids:
row.status = "sent"
row.sent_at = now
records_sent += 1
db.session.commit()
return {
"sent": len(sent_ids),
"failed": len(failed_ids),
"records_sent": records_sent,
"records_failed": records_failed,
}
def _drafts(
order: EquipmentAcceptanceOrder,
operators: list[EquipmentAcceptanceOperator],
people: dict[int, dict[str, Any]],
deputies: dict[str, list[dict[str, Any]]],
users_by_job: dict[str, User],
roles: dict[str, User | None],
thresholds: tuple[int, int, int, int],
) -> list[dict[str, Any]]:
"""按当前处理人展开四档里已经跨过的档。"""
due = due_tiers(order.dwell_days, thresholds)
if not due:
return []
handlers: list[dict[str, Any]] = []
supervisors: list[dict[str, Any]] = []
deputy_people: list[dict[str, Any]] = []
if not operators:
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
for operator in operators:
fact = people.get(operator.user_id) or {}
name = fact.get("name") or operator.handler_name
job_num = fact.get("job_num") or operator.handler_job_num
shown = name or "处理人"
handlers.append(resolve_account(
slot="to",
label="当前处理人",
name=name,
job_num=job_num,
user=users_by_job.get(str(job_num or "")),
missing_job_error=f"{shown}没有工号",
oa_employee_id=operator.user_id,
))
superior_id = fact.get("superior_id")
if superior_id is None:
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
else:
supervisors.append(resolve_account(
slot="cc",
label="直接主管",
name=fact.get("superior_name"),
job_num=fact.get("superior_job_num"),
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
missing_job_error=f"{shown}的直接主管没有工号",
oa_employee_id=superior_id,
))
found = deputies.get(str(fact.get("department_id") or ""), [])
if not found:
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
else:
for item in found:
deputy_people.append(resolve_account(
slot="to",
label="经副理",
name=item.get("name"),
job_num=item.get("job_num"),
user=users_by_job.get(str(item.get("job_num") or "")),
missing_job_error=f"{shown}的经副理没有工号",
oa_employee_id=item.get("oa_id"),
))
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
applicant = resolve_account(
slot="cc",
label="采购担当",
name=(applicant_fact or {}).get("name") or order.applicant_name,
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
missing_job_error="没有申请人工号",
oa_employee_id=order.applicant_oa_id,
)
drafts: list[dict[str, Any]] = []
if 1 in due:
drafts.append(assemble_tier(
tier=1,
threshold_days=thresholds[0],
to_people=handlers,
cc_people=[*supervisors, applicant],
))
if 2 in due:
drafts.append(assemble_tier(
tier=2,
threshold_days=thresholds[1],
to_people=deputy_people,
cc_people=[
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
],
))
if 3 in due:
drafts.append(assemble_tier(
tier=3,
threshold_days=thresholds[2],
to_people=[resolve_configured_user(slot="to", label="COO", user=roles.get("coo"), missing_error="未配置COO")],
cc_people=[resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理")],
))
if 4 in due:
drafts.append(assemble_tier(
tier=4,
threshold_days=thresholds[3],
to_people=[resolve_configured_user(slot="to", label="总经理", user=roles.get("executive"), missing_error="未配置总经理")],
cc_people=[
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
],
))
return drafts
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
row.acceptance_no = order.acceptance_no
row.purchase_order_no = order.purchase_order_no
row.threshold_days = draft["threshold_days"]
row.to_text = draft["to_text"]
row.cc_text = draft["cc_text"]
row.recipients_json = draft["recipients"]
row.status = draft["status"]
row.error_message = draft["error_message"]
def _load_directory(
orders: list[EquipmentAcceptanceOrder],
operators: dict[int, list[EquipmentAcceptanceOperator]],
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
ids: set[int] = set()
for group in operators.values():
for operator in group:
if operator.user_id:
ids.add(operator.user_id)
for order in orders:
if order.monitor_status == WATCHING and order.applicant_oa_id:
ids.add(order.applicant_oa_id)
return fetch_alert_directory(sorted(ids))
def _job_numbers(
orders: list[EquipmentAcceptanceOrder],
operators: dict[int, list[EquipmentAcceptanceOperator]],
people: dict[int, dict[str, Any]],
deputies: dict[str, list[dict[str, Any]]],
) -> set[str]:
"""收集要对系统用户的工号。"""
found: set[str] = set()
for order in orders:
if order.applicant_job_num:
found.add(order.applicant_job_num)
for group in operators.values():
for operator in group:
if operator.handler_job_num:
found.add(operator.handler_job_num)
for fact in people.values():
if fact.get("job_num"):
found.add(str(fact["job_num"]))
if fact.get("superior_job_num"):
found.add(str(fact["superior_job_num"]))
for group in deputies.values():
for item in group:
if item.get("job_num"):
found.add(str(item["job_num"]))
return found
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
"""用工号索引系统用户。"""
if not job_nums:
return {}
rows = db.session.query(User).filter(User.employee_id.in_(job_nums)).all()
return {str(row.employee_id): row for row in rows if row.employee_id}
def _configured_users() -> dict[str, User | None]:
"""读取三个固定岗位。没选时对应值是空。"""
setting = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
ids = []
if setting is not None:
ids = [item for item in (setting.buyer_manager_user_id, setting.coo_user_id, setting.executive_user_id) if item]
found = _users_by_id(ids)
if setting is None:
return {"buyer": None, "coo": None, "executive": None}
return {
"buyer": found.get(setting.buyer_manager_user_id or 0),
"coo": found.get(setting.coo_user_id or 0),
"executive": found.get(setting.executive_user_id or 0),
}
def _users_by_id(user_ids: list[int]) -> dict[int, User]:
"""按主键取出系统用户。"""
if not user_ids:
return {}
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
return {row.id: row for row in rows}
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
"""取出这些验收单的当前处理人。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
rows = (
db.session.query(EquipmentAcceptanceOperator)
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _recipient_user_ids(rows: list[EquipmentAcceptanceSendRecord]) -> list[int]:
"""从待发送收件人里取出系统用户主键。"""
found: list[int] = []
for row in rows:
for person in list(row.recipients_json or []):
if person.get("user_id"):
found.append(int(person["user_id"]))
return found
def _audit_user(
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
users: dict[int, User],
) -> User | None:
"""取这名收件人在系统里的账号,供企微审计。没有账号时仍按企微 userid 发送。"""
for _row, person in entries:
user_id = person.get("user_id")
if user_id and int(user_id) in users:
return users[int(user_id)]
return None
def _message(
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
orders: dict[int, EquipmentAcceptanceOrder],
) -> str:
"""拼一名收件人本轮要看的验收单。过长时截断。"""
lines: list[str] = []
seen: set[int] = set()
for row, person in entries:
if row.id in seen:
continue
seen.add(row.id)
order = orders.get(row.order_id or 0)
days = "—" if order is None or order.dwell_days is None else str(order.dwell_days)
role = "主送" if person.get("slot") == "to" else "抄送"
lines.append(
f"{role} {row.acceptance_no or '—'},采购单 {row.purchase_order_no or '—'},"
f"停留 {days} 天,超过 {row.threshold_days} 天"
)
text = "\n".join(lines[:12])
if len(lines) > 12:
text = f"{text}\n另有 {len(lines) - 12} 条"
return text[:500]
def _join_error(current: str | None, extra: str) -> str:
"""把新的失败原因接在原有原因后面。相同句子不重复。"""
parts = [part for part in (current, extra) if part]
unique: list[str] = []
for part in parts:
if part not in unique:
unique.append(part)
return ";".join(unique)
@@ -0,0 +1,204 @@
"""
backend/app/services/equipment_acceptance/config_service.py
用途:读写设备验收预警配置:四档天数和三个固定岗位。
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
没有配置行时按冻结默认值 30/37/44/51 返回,不把姓名写进代码。
"""
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 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、三个岗位用户主键、已选用户、候选人和更新时间。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
selected_ids = _selected_ids(row)
return {
"days": list(_days_of(row)),
"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]:
"""
保存四档天数和三个岗位用户。
核心逻辑:天数必须逐档增大。岗位为空表示未选;有值时必须是已存在的系统用户。
保存后只影响以后的预警,这里不改历史发送记录。
Args:
payload: days 为四个整数;三个岗位字段为用户主键或空。
updated_by: 操作人的系统用户主键。
Returns:
与读取接口相同的配置,并带候选人。
Raises:
ValidationError: 天数不合法,或岗位用户不存在。
"""
days = validate_reminder_days(payload.get("days"))
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.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),
}
@@ -0,0 +1,279 @@
"""
backend/app/services/equipment_acceptance/oa_repository.py
用途:只读拉取 E10 验收单、当前节点、操作人,以及直接主管和经副理。
依赖:pyodbc、settings、query_sql。不调用 E8 的 OA_SQLSERVER_* 连接。
逻辑:先探测实例上的库名,再执行联表查询。经副理矩阵固定在 eteams。查询失败不把连接串写入日志。
"""
from __future__ import annotations
import logging
from typing import Any
from app.core.errors import ServiceUnavailableError, ValidationError
from app.services.equipment_acceptance.query_sql import _qualified, build_acceptance_sql, resolve_catalogs
from app.services.equipment_acceptance.snapshot_rules import as_int
from app.services.equipment_acceptance.settings import (
EquipmentAcceptanceSqlSettings,
load_equipment_acceptance_sql_settings,
)
_LOGGER = logging.getLogger(__name__)
# 苏州和信「HXJM-审批矩阵」。取值配置是该矩阵下 config_name 为「经副理」的 id。
_MATRIX_TENANT = "temkc46eme"
_MATRIX_ID = 1115770797884751874
_DEPUTY_CONFIG_ID = 1115771897387991041
_MATRIX_CATALOG = "eteams"
_PREFERRED_DRIVERS = (
"ODBC Driver 18 for SQL Server",
"ODBC Driver 17 for SQL Server",
"SQL Server",
)
def fetch_acceptance_rows() -> list[dict[str, Any]]:
"""
从 E10 拉验收单联表结果。
核心逻辑:连接 ecology10 所在实例,按实际库名组装 SQL。不查询 isremark。
Returns:
字段名为小写别名的字典行。
Raises:
ValidationError: 连接配置不完整,或库名非法。
ServiceUnavailableError: 驱动、连接或查询失败。
"""
settings = load_equipment_acceptance_sql_settings()
connection = _open_connection(settings)
try:
cursor = connection.cursor()
cursor.execute("SELECT name FROM sys.databases")
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
try:
catalogs = resolve_catalogs(
names,
form=settings.form_catalog or None,
employee=settings.employee_catalog or None,
request=settings.request_catalog or None,
node=settings.node_catalog or None,
)
except ValueError as exc:
raise ValidationError(
"设备验收同步找不到要查询的数据库",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"reason": str(exc)},
) from exc
_LOGGER.info(
"equipment acceptance catalogs form=%s employee=%s request=%s node=%s",
catalogs.form,
catalogs.employee,
catalogs.request,
catalogs.node,
)
cursor.execute(build_acceptance_sql(catalogs))
columns = [str(col[0]).lower() for col in cursor.description]
return [
{columns[index]: raw[index] for index in range(len(columns))}
for raw in cursor.fetchall()
]
except (ValidationError, ServiceUnavailableError):
raise
except Exception as exc:
_LOGGER.warning("equipment acceptance sql failed error=%s", type(exc).__name__)
raise ServiceUnavailableError(
"查询 E10 设备验收数据失败",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
finally:
connection.close()
def _open_connection(settings: EquipmentAcceptanceSqlSettings):
"""
打开 E10 只读连接。初始库固定为 ecology10,跨库表名在 SQL 里写全。
Raises:
ServiceUnavailableError: 没有 pyodbc、没有 ODBC 驱动或连接失败。
"""
try:
import pyodbc
except ImportError as exc:
raise ServiceUnavailableError(
"未安装 pyodbc,无法连接 E10 SQL Server",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
driver = _pick_driver(pyodbc, settings.driver)
database = settings.form_catalog or "ecology10"
conn_str = (
f"DRIVER={{{driver}}};"
f"SERVER={settings.host},{settings.port};"
f"DATABASE={database};"
f"UID={settings.username};"
f"PWD={settings.password};"
)
if driver != "SQL Server":
conn_str += f"Encrypt={settings.encrypt};TrustServerCertificate={settings.trust_cert};"
try:
return pyodbc.connect(conn_str, timeout=settings.timeout)
except Exception as exc:
_LOGGER.warning("equipment acceptance connect failed error=%s", type(exc).__name__)
raise ServiceUnavailableError(
"连接 E10 SQL Server 失败",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
"""
读取处理人的直接主管,并按部门查出经副理。
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
人员 ID 必须是整数。没有人员时不连库。
Args:
employee_ids: 当前处理人和申请人的 employee.ID。
Returns:
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
Raises:
ValidationError: 库名不合法。
ServiceUnavailableError: 连接或查询失败。
"""
ids = sorted({int(item) for item in employee_ids})
if not ids:
return {}, {}
settings = load_equipment_acceptance_sql_settings()
connection = _open_connection(settings)
try:
cursor = connection.cursor()
cursor.execute("SELECT name FROM sys.databases")
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
catalogs = resolve_catalogs(
names,
form=settings.form_catalog or None,
employee=settings.employee_catalog or None,
request=settings.request_catalog or None,
node=settings.node_catalog or None,
)
employee = _qualified(catalogs.employee, "employee")
people = _load_people(cursor, employee, ids)
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
deputies = _load_deputies(cursor, employee, departments)
return people, deputies
except (ValidationError, ServiceUnavailableError):
raise
except Exception as exc:
_LOGGER.warning("equipment acceptance directory sql failed error=%s", type(exc).__name__)
raise ServiceUnavailableError(
"查询 E10 直接主管和经副理失败",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
) from exc
finally:
connection.close()
def _load_people(cursor: Any, employee: str, employee_ids: list[int]) -> dict[int, dict[str, Any]]:
"""按人员 ID 取出姓名、工号、直接主管和部门。"""
found: dict[int, dict[str, Any]] = {}
for chunk in _chunks(employee_ids):
marks = ",".join("?" for _ in chunk)
cursor.execute(
f"""
SELECT e.ID, e.USERNAME, e.JOB_NUM, e.SUPERIOR, e.DEPARTMENT,
sup.USERNAME, sup.JOB_NUM
FROM {employee} AS e
LEFT JOIN {employee} AS sup ON sup.ID = e.SUPERIOR
WHERE e.ID IN ({marks})
""",
chunk,
)
for raw in cursor.fetchall():
oa_id = as_int(raw[0])
if oa_id is None:
continue
department = _clean(raw[4])
found[oa_id] = {
"oa_id": oa_id,
"name": _clean(raw[1]),
"job_num": _clean(raw[2]),
"superior_id": as_int(raw[3]),
"department_id": department,
"superior_name": _clean(raw[5]),
"superior_job_num": _clean(raw[6]),
}
return found
def _load_deputies(cursor: Any, employee: str, department_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
"""按部门 ID 字符串查出经副理。部门不在矩阵里时不产生人员。"""
found: dict[str, list[dict[str, Any]]] = {}
if not department_ids:
return found
matrix_condition = _qualified(_MATRIX_CATALOG, "hrm_matrix_condition_data")
matrix_value = _qualified(_MATRIX_CATALOG, "hrm_matrix_value_data")
for chunk in _chunks(department_ids):
marks = ",".join("?" for _ in chunk)
params: list[Any] = [_DEPUTY_CONFIG_ID, _MATRIX_TENANT, _MATRIX_ID, *_chunk_params(chunk)]
cursor.execute(
f"""
SELECT c.relate_id, v.relate_id, emp.USERNAME, emp.JOB_NUM
FROM {matrix_condition} AS c
INNER JOIN {matrix_value} AS v
ON v.matrix_data_id = c.matrix_data_id
AND v.tenant_key = c.tenant_key
AND v.matrix_id = c.matrix_id
AND v.delete_type = 0
AND v.matrix_value_config_id = ?
LEFT JOIN {employee} AS emp ON emp.ID = v.relate_id
WHERE c.tenant_key = ?
AND c.matrix_id = ?
AND c.delete_type = 0
AND c.relate_id IN ({marks})
""",
params,
)
for raw in cursor.fetchall():
department_id = _clean(raw[0])
person_id = as_int(raw[1])
if not department_id or person_id is None:
continue
found.setdefault(department_id, []).append({
"oa_id": person_id,
"name": _clean(raw[2]),
"job_num": _clean(raw[3]),
})
return found
def _chunk_params(chunk: list[Any]) -> list[Any]:
"""部门 ID 按原字符串传给条件表。"""
return list(chunk)
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
"""把 IN 列表拆开,避免一条 SQL 的参数过多。"""
return [values[index:index + size] for index in range(0, len(values), size)]
def _clean(value: Any) -> str | None:
"""去掉空白。数字部门 ID 也收成字符串,供矩阵条件表比较。"""
if value is None:
return None
text = str(value).strip()
return text or None
def _pick_driver(pyodbc: Any, configured: str) -> str:
"""选用已配置且本机存在的 ODBC 驱动,否则按 18、17、SQL Server 的顺序挑。"""
available = list(pyodbc.drivers())
if configured and configured in available:
return configured
for name in _PREFERRED_DRIVERS:
if name in available:
return name
if not available:
raise ServiceUnavailableError(
"未找到 SQL Server ODBC 驱动",
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
)
return available[-1]
@@ -0,0 +1,167 @@
"""
backend/app/services/equipment_acceptance/query_sql.py
用途:决定 E10 各表所在库,并组装只读联表 SQL。
依赖:无 Flask。库名只允许字母、数字和下划线。
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_FORM_CATALOG = "ecology10"
_EMPLOYEE_CATALOG = "eteams"
_REQUEST_CATALOG = "weaver_wfc"
_NODE_CATALOG = "weaver_wfp"
@dataclass(frozen=True)
class AcceptanceCatalogs:
"""一次同步使用的四个库名。"""
form: str
employee: str
request: str
node: str
def resolve_catalogs(
database_names: set[str],
*,
form: str | None = None,
employee: str | None = None,
request: str | None = None,
node: str | None = None,
) -> AcceptanceCatalogs:
"""
按数据字典和实例上实际存在的库选择库名。
核心逻辑:显式传入的库名优先。否则流程库优先 weaver_wfc、节点库优先 weaver_wfp,
实例里没有这两个库时用 ecology10。人员库只认 eteams,不猜测到别的库。
Args:
database_names: sys.databases 里的库名。
form: 验收单库覆盖值。
employee: 人员库覆盖值。
request: 流程库覆盖值。
node: 节点定义库覆盖值。
Returns:
AcceptanceCatalogs。
Raises:
ValueError: 库名非法,或人员库、回退后的流程库仍然不存在。
"""
present = {name.lower(): name for name in database_names if name}
return AcceptanceCatalogs(
form=_pick(form, _FORM_CATALOG, present, allow_fallback=_FORM_CATALOG),
employee=_pick(employee, _EMPLOYEE_CATALOG, present, allow_fallback=None),
request=_pick(request, _REQUEST_CATALOG, present, allow_fallback=_FORM_CATALOG),
node=_pick(node, _NODE_CATALOG, present, allow_fallback=_FORM_CATALOG),
)
def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
"""
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
delete_type 只取 0。当前处理人就是这些 userid。
Args:
catalogs: 已解析的库名。
Returns:
一条 SELECT。
Raises:
ValueError: 库名不是合法标识符。
"""
form = _qualified(catalogs.form, "ft_gdzcysdv2")
employee = _qualified(catalogs.employee, "employee")
form_data = _qualified(catalogs.request, "wfc_form_data")
request = _qualified(catalogs.request, "wfc_requestbase")
current = _qualified(catalogs.request, "wfc_currentnode")
node = _qualified(catalogs.node, "wfp_node")
operate = _qualified(catalogs.request, "wfc_operate")
return f"""
SELECT
f.ysddh,
f.cgdh,
f.htbh,
f.sbsyrjssj,
f.sfzfth,
f.sfkyzcys,
f.ycsm,
f.sybmdd,
owner.USERNAME AS owner_name,
owner.JOB_NUM AS owner_job_num,
f.sbglry,
equip.USERNAME AS equip_name,
equip.JOB_NUM AS equip_job_num,
f.sqr,
applicant.USERNAME AS applicant_name,
applicant.JOB_NUM AS applicant_job_num,
r.requestid,
r.flowstatus,
r.finishdatetime,
c.nodeid,
n.nodename,
n.nodetype,
op.userid,
handler.USERNAME AS handler_name,
handler.JOB_NUM AS handler_job_num
FROM {form} AS f
LEFT JOIN {employee} AS owner ON owner.ID = f.sybmdd
LEFT JOIN {employee} AS equip ON equip.ID = f.sbglry
LEFT JOIN {employee} AS applicant ON applicant.ID = f.sqr
LEFT JOIN {form_data} AS d
ON d.dataid = f.FORM_DATA_ID
AND d.delete_type = 0
LEFT JOIN {request} AS r
ON r.requestid = d.requestid
AND r.delete_type = 0
LEFT JOIN {current} AS c
ON c.requestid = r.requestid
AND c.delete_type = 0
LEFT JOIN {node} AS n
ON n.id = c.nodeid
AND n.delete_type = 0
LEFT JOIN {operate} AS op
ON op.requestid = c.requestid
AND op.nodeid = c.nodeid
AND op.delete_type = 0
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
WHERE ISNULL(f.delete_type, 0) = 0
AND r.requestid IS NOT NULL
""".strip()
def _pick(
override: str | None,
preferred: str,
present: dict[str, str],
*,
allow_fallback: str | None,
) -> str:
"""选择一个实际可用的库名。覆盖值不要求已经出现在探测结果里。"""
if override and override.strip():
return _ident(override.strip())
if preferred.lower() in present:
return _ident(present[preferred.lower()])
if allow_fallback and allow_fallback.lower() in present:
return _ident(present[allow_fallback.lower()])
raise ValueError(f"缺少数据库 {preferred}")
def _qualified(catalog: str, table: str) -> str:
"""返回 [库].[dbo].[表]。"""
return f"[{_ident(catalog)}].[dbo].[{_ident(table)}]"
def _ident(name: str) -> str:
"""拒绝不是普通标识符的库名或表名。"""
if not _IDENT.match(name):
raise ValueError(f"非法 SQL 标识符: {name}")
return name
@@ -0,0 +1,74 @@
"""
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
@@ -0,0 +1,71 @@
"""
backend/app/services/equipment_acceptance/send_record_service.py
用途:分页读取设备验收预警的发送记录。
依赖:extensions.db、EquipmentAcceptanceSendRecord、utc_iso。
逻辑:由 GET /api/equipment-acceptance/sends 调用。待发送由扫描写入,本模块只读取。
"""
from __future__ import annotations
from typing import Any
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
"""
按创建时间倒序分页列出发送记录。
核心逻辑:只读已落库的记录。扫描还没跑过时列表为空。
Args:
page: 从 1 开始。
page_size: 每页条数,上限 100。
Returns:
items、total、page、page_size。
"""
page = max(1, page)
page_size = min(100, max(1, page_size))
query = db.session.query(EquipmentAcceptanceSendRecord)
total = query.count()
rows = (
query.order_by(EquipmentAcceptanceSendRecord.created_at.desc(), EquipmentAcceptanceSendRecord.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"items": [send_record_payload(row) for row in rows],
"total": total,
"page": page,
"page_size": page_size,
}
def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
"""
把一条发送记录收成接口数据。
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。
Args:
row: 本地发送记录。
Returns:
页签表格用的字段。
"""
return {
"id": row.id,
"order_id": row.order_id,
"acceptance_no": row.acceptance_no,
"purchase_order_no": row.purchase_order_no,
"tier": row.tier,
"threshold_days": row.threshold_days,
"to_text": row.to_text,
"cc_text": row.cc_text,
"recipients": list(row.recipients_json or []),
"status": row.status,
"sent_at": utc_iso(row.sent_at),
"error_message": row.error_message,
"created_at": utc_iso(row.created_at),
}
@@ -0,0 +1,116 @@
"""
backend/app/services/equipment_acceptance/settings.py
用途:读取设备验收同步要用的 E10 SQL Server 连接。
依赖:Flask current_app、环境变量 OA_E10_SQLSERVER_HOST / USERNAME / PASSWORD。
逻辑:主机、账号、密码不回退到 E8 的 OA_SQLSERVER_*。库名由查询时再探测。
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from flask import current_app, has_app_context
from app.core.errors import ValidationError
@dataclass(frozen=True)
class EquipmentAcceptanceSqlSettings:
"""E10 只读连接。repr 不包含密码。"""
host: str
port: str
username: str
password: str
driver: str
encrypt: str
trust_cert: str
timeout: int
form_catalog: str
employee_catalog: str
request_catalog: str
node_catalog: str
def __repr__(self) -> str:
return (
"EquipmentAcceptanceSqlSettings("
f"host={self.host!r}, port={self.port!r}, username={self.username!r}, "
f"form_catalog={self.form_catalog!r}, employee_catalog={self.employee_catalog!r}, "
f"request_catalog={self.request_catalog!r}, node_catalog={self.node_catalog!r})"
)
def load_equipment_acceptance_sql_settings() -> EquipmentAcceptanceSqlSettings:
"""
读取同步连接配置。
核心逻辑:三个必填变量只认 OA_E10_SQLSERVER_*。库名覆盖可空,空则交给实例探测。
Returns:
EquipmentAcceptanceSqlSettings。
Raises:
ValidationError: 主机、账号或密码缺失。
"""
host = _cfg("OA_E10_SQLSERVER_HOST")
username = _cfg("OA_E10_SQLSERVER_USERNAME")
password = _cfg_raw("OA_E10_SQLSERVER_PASSWORD")
missing = [
key
for key, value in (
("OA_E10_SQLSERVER_HOST", host),
("OA_E10_SQLSERVER_USERNAME", username),
("OA_E10_SQLSERVER_PASSWORD", password),
)
if not str(value or "").strip()
]
if missing:
raise ValidationError(
"设备验收同步的 E10 数据库配置不完整",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"missing": missing},
)
return EquipmentAcceptanceSqlSettings(
host=host,
port=_cfg("OA_E10_SQLSERVER_PORT") or "1433",
username=username,
password=password,
driver=_cfg("OA_E10_SQLSERVER_DRIVER"),
encrypt=(_cfg("OA_E10_SQLSERVER_ENCRYPT") or "no").lower(),
trust_cert=(_cfg("OA_E10_SQLSERVER_TRUST_CERT") or "yes").lower(),
timeout=_as_int(_cfg("OA_E10_SQLSERVER_TIMEOUT") or "60", 60),
form_catalog=_cfg("EQUIPMENT_ACCEPTANCE_FORM_CATALOG"),
employee_catalog=_cfg("EQUIPMENT_ACCEPTANCE_EMPLOYEE_CATALOG"),
request_catalog=_cfg("EQUIPMENT_ACCEPTANCE_REQUEST_CATALOG"),
node_catalog=_cfg("EQUIPMENT_ACCEPTANCE_NODE_CATALOG"),
)
def _cfg(key: str) -> str:
"""优先 Flask config,再读环境变量,并去掉首尾空白。"""
if has_app_context():
value = current_app.config.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return str(os.getenv(key) or "").strip()
def _cfg_raw(key: str) -> str:
"""读取密码,保留中间空格。"""
if has_app_context():
value = current_app.config.get(key)
if value is not None and str(value) != "":
return str(value)
env = os.getenv(key)
if env is not None and env != "":
return env
return ""
def _as_int(raw: str, default: int) -> int:
"""超时秒数,非法时用默认值。"""
try:
return max(1, int(str(raw).strip() or default))
except (TypeError, ValueError):
return default
@@ -0,0 +1,243 @@
"""
backend/app/services/equipment_acceptance/snapshot_rules.py
用途:把 OA 原值收成同步快照上的监控状态和签核天数。
依赖:无。不读数据库,也不使用 isremark。
逻辑:同步服务对每一张验收单调用本模块。OA 的 0=是、1=否先翻成标准 0=否、1=是。
flowstatus 为 7、8、99、-99 时记为已撤销,不再提醒。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
NOT_STARTED = "not_started"
WATCHING = "watching"
STOPPED_CANNOT_ACCEPT = "stopped_cannot_accept"
STOPPED_RETURNED = "stopped_returned"
STOPPED_ARCHIVED = "stopped_archived"
STOPPED_FORCE_FINISHED = "stopped_force_finished"
STOPPED_VOIDED = "stopped_voided"
STOPPED_REVOKED = "stopped_revoked"
EXCLUDED = "excluded"
MONITOR_STATUSES = (
NOT_STARTED,
WATCHING,
STOPPED_CANNOT_ACCEPT,
STOPPED_RETURNED,
STOPPED_ARCHIVED,
STOPPED_FORCE_FINISHED,
STOPPED_VOIDED,
STOPPED_REVOKED,
EXCLUDED,
)
# 需求冻结的第 1 档是超过 30 天。列表上的「已逾期」按这一档判断,还没有发送记录。
FIRST_REMINDER_DAY = 30
_FLOW_APPROVING = 1
_FLOW_ARCHIVED = 3
_FLOW_FORCE_FINISHED = 4
_FLOW_VOIDED = 5
# 7、8、99 已确认按撤销停表。字典截断值是 -99,一并按撤销处理。
_REVOKED_FLOW = {7, 8, 99, -99}
_TERMINAL_FLOW = {_FLOW_ARCHIVED, _FLOW_FORCE_FINISHED, _FLOW_VOIDED, *_REVOKED_FLOW}
def as_int(value: Any) -> int | None:
"""
把 OA 数字收成 int。空值保持空。
核心逻辑:布尔值不是业务枚举;0 是有效取值,不能当成空。
Args:
value: 查询结果里的数字、数字字符串或空。
Returns:
整数或 None。
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
if value != value:
return None
return int(value)
text = str(value).strip()
if not text:
return None
try:
return int(text)
except ValueError:
try:
number = float(text)
except ValueError:
return None
return int(number)
def as_date(value: Any) -> date | None:
"""
把 OA 日期收成 date。
核心逻辑:datetime 取日期部分;常见字符串只认日期前 10 位。
Args:
value: datetime、date 或字符串。
Returns:
date 或 None。
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
text = str(value).strip()
if len(text) < 10:
return None
try:
return date.fromisoformat(text[:10])
except ValueError:
return None
def as_datetime(value: Any) -> datetime | None:
"""
把 OA 时间收成去掉时区的 datetime,供本地快照保存。
Args:
value: datetime 或可解析字符串。
Returns:
naive datetime 或 None。
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, datetime):
return value.replace(tzinfo=None)
if isinstance(value, date):
return datetime(value.year, value.month, value.day)
text = str(value).strip().replace("T", " ")
if not text:
return None
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
return datetime.strptime(text[:26], fmt)
except ValueError:
continue
parsed = as_date(text)
if parsed is None:
return None
return datetime(parsed.year, parsed.month, parsed.day)
def can_accept_from_oa(value: int | None) -> int | None:
"""
把 OA「是否可以正常验收」翻成标准布尔。
核心逻辑:OA sfkyzcys 是 0=是、1=否。本地 can_accept 用 0=否、1=是。
空值表示未标明,保持空,不收成否。0、1 以外的值原样留下,交给状态判断排除。
Args:
value: sfkyzcys 的整数。0 可以,1 不可以。
Returns:
1 表示可以验收,0 表示不可以,空保持空。
"""
# [STEP] OA 0=是、1=否,与本地 0=否、1=是对调。空不是「否」。
if value == 0:
return 1
if value == 1:
return 0
return value
def is_returned_from_oa(value: int | None) -> int | None:
"""
把 OA「是否退回」翻成标准布尔。
核心逻辑:OA sfzfth 是 0=是(退回),1=否(正常)。本地 is_returned 用 0=否、1=是。
空和 1 都已确认是未退回,所以空收成 0。0、1、空以外的值原样留下。
Args:
value: sfzfth 的整数。0 退回,1 和空为正常。
Returns:
1 表示已退回,0 表示未退回。
"""
# [STEP] OA 0=是、1=否,翻成 0=否、1=是。空按已确认口径当作未退回。
if value == 0:
return 1
if value in (1, None):
return 0
return value
def classify_monitor_status(
*,
can_accept: int | None,
is_returned: int | None,
flow_status: int | None,
timer_started: bool,
) -> str:
"""
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
审批中、可以验收、未退回、已有计时起点才是计时中。
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
Args:
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
is_returned: 本地是否退回。0 否,1 是。
flow_status: wfc_requestbase.flowstatus。
timer_started: sbsyrjssj 是否有值。
Returns:
MONITOR_STATUSES 中的一个代码。
"""
# [STEP 1] 表单上的停表原因优先于流程是否已经结束
if is_returned == 1:
return STOPPED_RETURNED
if can_accept == 0:
return STOPPED_CANNOT_ACCEPT
if flow_status == _FLOW_VOIDED:
return STOPPED_VOIDED
if flow_status == _FLOW_ARCHIVED:
return STOPPED_ARCHIVED
if flow_status == _FLOW_FORCE_FINISHED:
return STOPPED_FORCE_FINISHED
if flow_status in _REVOKED_FLOW:
return STOPPED_REVOKED
if not timer_started:
return NOT_STARTED
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
return WATCHING
return EXCLUDED
def dwell_days(
*,
timer_started_at: datetime | date | None,
flow_status: int | None,
finished_at: datetime | date | None,
as_of: date,
) -> int | None:
"""
计算同步日看到的签核自然日。
核心逻辑:起点为空则没有天数。归档、强制结束、作废、撤销且有结束时间时,
截止到结束日,避免停表后每次同步继续加天。退回和无法验收没有结束时间,截止到同步日。
Args:
timer_started_at: sbsyrjssj。
flow_status: 流程状态原值。
finished_at: finishdatetime。
as_of: 同步当日,使用 Asia/Shanghai 的日期。
Returns:
非负天数;没有起点时为 None。
"""
start = as_date(timer_started_at)
if start is None:
return None
end = as_of
if flow_status in _TERMINAL_FLOW:
finished = as_date(finished_at)
if finished is not None:
end = finished if finished < as_of else as_of
if end < start:
return 0
return (end - start).days
@@ -0,0 +1,162 @@
"""
backend/app/services/equipment_acceptance/source_group.py
用途:把验收单联表的扁平行收成一张单一条草稿。
依赖:snapshot_rules。
逻辑:同步服务先分组再落库。是否可以验收、是否退回在这里从 OA 的 0=是、1=否
翻成标准 0=否、1=是。无法验收说明取 ycsm,不参与停表。操作人按节点和人员去重,不读 isremark。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from app.services.equipment_acceptance.snapshot_rules import (
as_datetime,
as_int,
can_accept_from_oa,
is_returned_from_oa,
)
@dataclass
class OperatorDraft:
"""当前节点上的一名操作人。不带操作状态。"""
node_id: int
user_id: int
handler_name: str | None
handler_job_num: str | None
@dataclass
class NodeDraft:
"""一条当前节点。"""
node_id: int
node_name: str | None
node_type: int | None
@dataclass
class AcceptanceDraft:
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
request_id: int
acceptance_no: str | None
purchase_order_no: str | None
contract_no: str | None
timer_started_at: datetime | None
can_accept: int | None
cannot_accept_note: str | None
is_returned: int | None
flow_status_raw: int | None
finished_at: datetime | None
request_match_count: int
owner_oa_id: int | None
owner_name: str | None
owner_job_num: str | None
equip_oa_id: int | None
equip_name: str | None
equip_job_num: str | None
applicant_oa_id: int | None
applicant_name: str | None
applicant_job_num: str | None
nodes: list[NodeDraft] = field(default_factory=list)
operators: list[OperatorDraft] = field(default_factory=list)
def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
"""
按流程实例 requestid 合并联表结果。
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
不读取流程编号、第二合同编号和验收日期。
Args:
rows: 查询别名组成的字典行。
Returns:
(草稿列表, 因缺少 requestid 而跳过的行数)。
"""
skipped = 0
buckets: dict[int, list[dict[str, Any]]] = {}
for row in rows:
request_id = as_int(row.get("requestid"))
if request_id is None:
skipped += 1
continue
buckets.setdefault(request_id, []).append(row)
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
"""同一流程实例的多行收成一条草稿。"""
header = items[0]
return AcceptanceDraft(
request_id=request_id,
acceptance_no=_text(header.get("ysddh")),
purchase_order_no=_text(header.get("cgdh")),
contract_no=_text(header.get("htbh")),
timer_started_at=as_datetime(header.get("sbsyrjssj")),
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
cannot_accept_note=_text(header.get("ycsm")),
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
flow_status_raw=as_int(header.get("flowstatus")),
finished_at=as_datetime(header.get("finishdatetime")),
request_match_count=1,
nodes=_nodes(items),
operators=_operators(items),
owner_oa_id=as_int(header.get("sybmdd")),
owner_name=_text(header.get("owner_name")),
owner_job_num=_text(header.get("owner_job_num")),
equip_oa_id=as_int(header.get("sbglry")),
equip_name=_text(header.get("equip_name")),
equip_job_num=_text(header.get("equip_job_num")),
applicant_oa_id=as_int(header.get("sqr")),
applicant_name=_text(header.get("applicant_name")),
applicant_job_num=_text(header.get("applicant_job_num")),
)
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
"""按节点 ID 去重,保留节点名称。"""
found: dict[int, NodeDraft] = {}
for row in rows:
node_id = as_int(row.get("nodeid"))
if node_id is None or node_id in found:
continue
found[node_id] = NodeDraft(
node_id=node_id,
node_name=_text(row.get("nodename")),
node_type=as_int(row.get("nodetype")),
)
return list(found.values())
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
"""按节点和人员去重。不读 isremark,同一人只留一行。"""
found: dict[tuple[int, int], OperatorDraft] = {}
for row in rows:
node_id = as_int(row.get("nodeid"))
user_id = as_int(row.get("userid"))
if node_id is None or user_id is None:
continue
key = (node_id, user_id)
if key in found:
continue
found[key] = OperatorDraft(
node_id=node_id,
user_id=user_id,
handler_name=_text(row.get("handler_name")),
handler_job_num=_text(row.get("handler_job_num")),
)
return list(found.values())
def _text(value: Any) -> str | None:
"""去空白;空串视为没有值。"""
if value is None:
return None
text = str(value).strip()
return text or None
@@ -0,0 +1,412 @@
"""
backend/app/services/equipment_acceptance/sync_service.py
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
停表时取消该单未发送的预警。操作人不保存 isremark。
"""
from __future__ import annotations
from collections import Counter
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
from app.core.errors import NotFoundError, ValidationError
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
)
from app.services.equipment_acceptance.config_service import first_reminder_day
from app.services.equipment_acceptance.snapshot_rules import (
MONITOR_STATUSES,
classify_monitor_status,
dwell_days,
)
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
_SHANGHAI = ZoneInfo("Asia/Shanghai")
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
_STOPPED_STATUSES = (
"stopped_returned",
"stopped_cannot_accept",
"stopped_archived",
"stopped_force_finished",
"stopped_voided",
"stopped_revoked",
)
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
"""
同步验收单快照。
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
Args:
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
Returns:
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
"""
if rows is None:
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
rows = fetch_acceptance_rows()
drafts, skipped = group_acceptance_rows(rows)
as_of = datetime.now(_SHANGHAI).date()
counts: Counter[str] = Counter()
request_ids: list[int] = []
cancelled = 0
for draft in drafts:
order, cancelled_now = _upsert_order(draft, as_of=as_of)
request_ids.append(order.request_id)
counts[order.monitor_status] += 1
cancelled += cancelled_now
absent = _mark_absent(request_ids)
db.session.commit()
return {
"upserted": len(drafts),
"skipped_without_request_id": skipped,
"absent": absent,
"cancelled": cancelled,
"by_status": dict(counts),
}
def list_acceptance_orders(
*,
monitor_status: str | None,
focus: str | None,
page: int,
page_size: int,
) -> dict[str, Any]:
"""
分页列出本地快照。
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
Args:
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
focus: watching、overdue、stopped、not_started 或空。
page: 从 1 开始。
page_size: 每页条数,上限 100。
Returns:
items、total、page、page_size、summary。
Raises:
ValidationError: focus 或监控状态不是已定义值。
"""
status = _clean_status(monitor_status)
ledger_focus = _clean_focus(focus)
reminder_day = first_reminder_day()
page = max(1, page)
page_size = min(100, max(1, page_size))
query = db.session.query(EquipmentAcceptanceOrder)
if ledger_focus:
query = _apply_focus(query, ledger_focus, reminder_day)
elif status:
query = query.filter(EquipmentAcceptanceOrder.monitor_status == status)
total = query.count()
orders = (
query.order_by(EquipmentAcceptanceOrder.synced_at.desc(), EquipmentAcceptanceOrder.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
order_ids = [order.id for order in orders]
nodes = _nodes_by_order(order_ids)
operators = _operators_by_order(order_ids)
pages = (total + page_size - 1) // page_size if total else 1
return {
"items": [
_order_payload(order, nodes.get(order.id, []), operators.get(order.id, []), reminder_day)
for order in orders
],
"total": total,
"page": page,
"page_size": page_size,
"pages": pages,
"summary": _ledger_summary(reminder_day),
}
def get_acceptance_order(order_id: int) -> dict[str, Any]:
"""
读取一张验收单快照,含当前节点和操作人原值。
Args:
order_id: 本地主键。
Returns:
快照详情。
Raises:
NotFoundError: 记录不存在。
"""
order = db.session.get(EquipmentAcceptanceOrder, order_id)
if order is None:
raise NotFoundError("设备验收同步记录不存在", code="EQUIPMENT_ACCEPTANCE.NOT_FOUND")
return _order_payload(
order,
_nodes_by_order([order.id]).get(order.id, []),
_operators_by_order([order.id]).get(order.id, []),
first_reminder_day(),
)
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
"""
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
Returns:
更新后的验收单,以及本次改成已取消的发送记录条数。
"""
order = (
db.session.query(EquipmentAcceptanceOrder)
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
.one_or_none()
)
now = datetime.utcnow()
if order is None:
order = EquipmentAcceptanceOrder(
request_id=draft.request_id,
monitor_status="excluded",
synced_at=now,
created_at=now,
updated_at=now,
)
db.session.add(order)
db.session.flush()
order.acceptance_no = draft.acceptance_no
order.purchase_order_no = draft.purchase_order_no
order.contract_no = draft.contract_no
order.timer_started_at = draft.timer_started_at
order.can_accept = draft.can_accept
order.cannot_accept_note = draft.cannot_accept_note
order.is_returned = draft.is_returned
order.flow_status_raw = draft.flow_status_raw
order.finished_at = draft.finished_at
order.request_id = draft.request_id
order.request_match_count = draft.request_match_count
order.owner_oa_id = draft.owner_oa_id
order.owner_name = draft.owner_name
order.owner_job_num = draft.owner_job_num
order.equip_oa_id = draft.equip_oa_id
order.equip_name = draft.equip_name
order.equip_job_num = draft.equip_job_num
order.applicant_oa_id = draft.applicant_oa_id
order.applicant_name = draft.applicant_name
order.applicant_job_num = draft.applicant_job_num
order.monitor_status = classify_monitor_status(
can_accept=draft.can_accept,
is_returned=draft.is_returned,
flow_status=draft.flow_status_raw,
timer_started=draft.timer_started_at is not None,
)
order.dwell_days = dwell_days(
timer_started_at=draft.timer_started_at,
flow_status=draft.flow_status_raw,
finished_at=draft.finished_at,
as_of=as_of,
)
order.present_in_source = True
order.synced_at = now
order.updated_at = now
cancelled = 0
if order.monitor_status != "watching":
from app.services.equipment_acceptance.alert_service import cancel_unsent
cancelled = cancel_unsent(order.id)
# [STEP] 先从会话里删掉旧子行,再插入本次节点和操作人,避免批量 delete 后旧对象被重新写回
for node in db.session.query(EquipmentAcceptanceNode).filter(EquipmentAcceptanceNode.order_id == order.id).all():
db.session.delete(node)
for operator in (
db.session.query(EquipmentAcceptanceOperator)
.filter(EquipmentAcceptanceOperator.order_id == order.id)
.all()
):
db.session.delete(operator)
db.session.flush()
for node in draft.nodes:
db.session.add(
EquipmentAcceptanceNode(
order_id=order.id,
node_id=node.node_id,
node_name=node.node_name,
node_type=node.node_type,
)
)
for operator in draft.operators:
db.session.add(
EquipmentAcceptanceOperator(
order_id=order.id,
node_id=operator.node_id,
user_id=operator.user_id,
handler_name=operator.handler_name,
handler_job_num=operator.handler_job_num,
)
)
return order, cancelled
def _mark_absent(request_ids: list[int]) -> int:
"""把这次没拉到的单据标成源里不存在。"""
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
if request_ids:
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
def _clean_focus(focus: str | None) -> str | None:
"""空白视为全部。未知分组拒绝,避免把原型筛选项写错后悄悄查出空表。"""
value = str(focus or "").strip()
if not value or value == "all":
return None
if value not in _LEDGER_FOCUSES:
raise ValidationError(
"未知的设备验收列表分组",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"focus": value},
)
return value
def _apply_focus(query, focus: str, reminder_day: int):
"""按停留列表分组过滤。已逾期只含计时中且超过当前第 1 档的单据。"""
if focus == "watching":
return query.filter(EquipmentAcceptanceOrder.monitor_status == "watching")
if focus == "not_started":
return query.filter(EquipmentAcceptanceOrder.monitor_status == "not_started")
if focus == "stopped":
return query.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES))
return query.filter(
EquipmentAcceptanceOrder.monitor_status == "watching",
EquipmentAcceptanceOrder.dwell_days > reminder_day,
)
def _ledger_summary(reminder_day: int) -> dict[str, int]:
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
base = db.session.query(EquipmentAcceptanceOrder)
return {
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
"overdue": base.filter(
EquipmentAcceptanceOrder.monitor_status == "watching",
EquipmentAcceptanceOrder.dwell_days > reminder_day,
).count(),
"stopped": base.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES)).count(),
"not_started": base.filter(EquipmentAcceptanceOrder.monitor_status == "not_started").count(),
}
def _clean_status(monitor_status: str | None) -> str | None:
"""空白过滤视为不筛选。未知状态拒绝,避免把撤回等未定义值写进查询。"""
status = str(monitor_status or "").strip()
if not status:
return None
if status not in MONITOR_STATUSES:
raise ValidationError(
"未知的设备验收监控状态",
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
details={"monitor_status": status},
)
return status
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
"""一次取出当前页的节点,避免逐单查询。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
rows = (
db.session.query(EquipmentAcceptanceNode)
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
.order_by(EquipmentAcceptanceNode.id.asc())
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
"""一次取出当前页的操作人,避免逐单查询。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
rows = (
db.session.query(EquipmentAcceptanceOperator)
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
.order_by(EquipmentAcceptanceOperator.id.asc())
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _order_payload(
order: EquipmentAcceptanceOrder,
nodes: list[EquipmentAcceptanceNode],
operators: list[EquipmentAcceptanceOperator],
reminder_day: int,
) -> dict[str, Any]:
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
payload: dict[str, Any] = {
"id": order.id,
"acceptance_no": order.acceptance_no,
"purchase_order_no": order.purchase_order_no,
"contract_no": order.contract_no,
"timer_started_at": utc_iso(order.timer_started_at),
"dwell_days": order.dwell_days,
"can_accept": order.can_accept,
"cannot_accept_note": order.cannot_accept_note,
"is_returned": order.is_returned,
"flow_status_raw": order.flow_status_raw,
"finished_at": utc_iso(order.finished_at),
"request_id": _id_text(order.request_id),
"request_match_count": order.request_match_count,
"owner_oa_id": _id_text(order.owner_oa_id),
"owner_name": order.owner_name,
"owner_job_num": order.owner_job_num,
"equip_oa_id": _id_text(order.equip_oa_id),
"equip_name": order.equip_name,
"equip_job_num": order.equip_job_num,
"applicant_oa_id": _id_text(order.applicant_oa_id),
"applicant_name": order.applicant_name,
"applicant_job_num": order.applicant_job_num,
"monitor_status": order.monitor_status,
"overdue": order.monitor_status == "watching" and (order.dwell_days or 0) > reminder_day,
"present_in_source": order.present_in_source,
"synced_at": utc_iso(order.synced_at),
"nodes": [
{
"node_id": _id_text(node.node_id),
"node_name": node.node_name,
"node_type": node.node_type,
}
for node in nodes
],
"operators": [
{
"node_id": _id_text(item.node_id),
"user_id": _id_text(item.user_id),
"handler_name": item.handler_name,
"handler_job_num": item.handler_job_num,
}
for item in operators
],
}
return payload
def _id_text(value: int | None) -> str | None:
"""OA 长整型主键序列化成字符串。"""
if value is None:
return None
return str(value)
@@ -0,0 +1,60 @@
"""
backend/app/services/schedule/equipment_acceptance_job.py
用途:把设备验收预警扫描和周五发送接到平台排程。
依赖:equipment_acceptance.alert_service、ScheduleTask、ScheduleRun。
逻辑:日批先同步再写待发送。周五任务只发送,不再同步。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_equipment_acceptance_alert_scan_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行设备验收每日扫描。
核心逻辑:同步 E10 后生成待发送,不发企业微信。
Args:
task: 当前排程。
run: 本次执行记录。
Returns:
排程审计七元组。成功数是新增加更新,跳过数是停表取消的条数。
"""
from app.services.equipment_acceptance.alert_service import generate_alerts
summary = generate_alerts()
created = int(summary.get("created") or 0)
updated = int(summary.get("updated") or 0)
cancelled = int(summary.get("cancelled") or 0)
handled = created + updated
return handled + cancelled, handled, 0, cancelled, [summary], [], [
{"step": "equipment_acceptance_alert_scan", "status": "success", "detail": summary}
]
def run_equipment_acceptance_alert_weekly_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行周五设备验收企业微信汇总。
核心逻辑:按收件人各发一条。失败人数记入排程的失败计数。
Args:
task: 当前排程。
run: 本次执行记录。
Returns:
排程审计七元组。
"""
from app.services.equipment_acceptance.alert_service import send_pending_alerts
summary = send_pending_alerts()
sent = int(summary.get("sent") or 0)
failed = int(summary.get("failed") or 0)
status = "success" if not failed else "partial"
return sent + failed, sent, failed, 0, [summary], [], [
{"step": "equipment_acceptance_alert_weekly", "status": status, "detail": summary}
]
@@ -156,6 +156,10 @@ def _register_builtin_platform_jobs() -> None:
run_contract_payment_sync_schedule,
run_contract_payment_weekly_alert_schedule,
)
from app.services.schedule.equipment_acceptance_job import (
run_equipment_acceptance_alert_scan_schedule,
run_equipment_acceptance_alert_weekly_schedule,
)
from app.services.schedule.lean_training_job import run_lean_training_reminder_schedule, run_lean_training_video_push_schedule
register_platform_job(PlatformJobDefinition(
@@ -268,6 +272,20 @@ def _register_builtin_platform_jobs() -> None:
key="contract-payment-alert-weekly", label="合同付款预警周汇总", handler=run_contract_payment_weekly_alert_schedule,
description="每周五 18:00 按收件人发送一条付款预警汇总及 Excel 明细。", category="contract_payment",
))
register_platform_job(PlatformJobDefinition(
key="equipment-acceptance-alert-scan",
label="设备验收预警扫描",
handler=run_equipment_acceptance_alert_scan_schedule,
description="每日同步 E10 验收单,并按停留天数生成待发送记录。",
category="equipment_acceptance",
))
register_platform_job(PlatformJobDefinition(
key="equipment-acceptance-alert-weekly",
label="设备验收预警发送",
handler=run_equipment_acceptance_alert_weekly_schedule,
description="每周五 18:00 按收件人发送一条设备验收停留提醒。",
category="equipment_acceptance",
))
register_platform_job(PlatformJobDefinition(
key="contract-payment-sync",