feat(equipment-acceptance): 设备验收预警
This commit is contained in:
1 parent
239d373503
commit
86fc8a2c06
48 files changed
+6196
-82
No files matched your search
+1
-1
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
@@ -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 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""设备验收预警同步快照与 Chat Agent。
|
||||
|
||||
Revision ID: ea8c0a1b2c3d
|
||||
Revises: 9e5045511198
|
||||
Create Date: 2026-10-08 15:30:00.000000
|
||||
|
||||
用途:一次建好设备验收快照、预警配置、发送记录,并注册 Chat Agent。
|
||||
依赖:users、agents 表已存在。不改合同付款表。
|
||||
逻辑:主表按流程实例 request_id 唯一;节点和操作人随主表级联删除。
|
||||
发送记录按验收单和档位唯一,收件人明细 recipients_json 建表时一并创建。
|
||||
无法验收说明 cannot_accept_note 来自 ycsm。配置表只插入 id=1,天数 30/37/44/51,岗位先空着。
|
||||
发送时刻不在配置表。Agent 按 agent_code 复用已有实例;没有则插入。降级不删除 Agent。
|
||||
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
revision = "ea8c0a1b2c3d"
|
||||
down_revision = "9e5045511198"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""建快照、节点、操作人、发送记录和配置,并注册设备验收 Agent。"""
|
||||
op.create_table(
|
||||
"equipment_acceptance_orders",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("acceptance_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("purchase_order_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("contract_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("timer_started_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("dwell_days", sa.Integer(), nullable=True),
|
||||
sa.Column(
|
||||
"can_accept",
|
||||
sa.Integer(),
|
||||
nullable=True,
|
||||
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
|
||||
),
|
||||
sa.Column(
|
||||
"is_returned",
|
||||
sa.Integer(),
|
||||
nullable=True,
|
||||
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
|
||||
),
|
||||
sa.Column(
|
||||
"cannot_accept_note",
|
||||
sa.Text(),
|
||||
nullable=True,
|
||||
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
|
||||
),
|
||||
sa.Column("flow_status_raw", sa.Integer(), nullable=True),
|
||||
sa.Column("finished_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("request_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("request_match_count", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("owner_oa_id", sa.BigInteger(), nullable=True),
|
||||
sa.Column("owner_name", sa.String(length=200), nullable=True),
|
||||
sa.Column("owner_job_num", sa.String(length=64), nullable=True),
|
||||
sa.Column("equip_oa_id", sa.BigInteger(), nullable=True),
|
||||
sa.Column("equip_name", sa.String(length=200), nullable=True),
|
||||
sa.Column("equip_job_num", sa.String(length=64), nullable=True),
|
||||
sa.Column("applicant_oa_id", sa.BigInteger(), nullable=True),
|
||||
sa.Column("applicant_name", sa.String(length=200), nullable=True),
|
||||
sa.Column("applicant_job_num", sa.String(length=64), nullable=True),
|
||||
sa.Column("monitor_status", sa.String(length=40), nullable=False),
|
||||
sa.Column("present_in_source", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||
sa.Column("synced_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_equipment_acceptance_orders_status",
|
||||
"equipment_acceptance_orders",
|
||||
["monitor_status"],
|
||||
)
|
||||
op.create_table(
|
||||
"equipment_acceptance_nodes",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("order_id", sa.Integer(), nullable=False),
|
||||
sa.Column("node_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("node_name", sa.String(length=200), nullable=True),
|
||||
sa.Column("node_type", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(["order_id"], ["equipment_acceptance_orders.id"], ondelete="CASCADE"),
|
||||
sa.UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
|
||||
)
|
||||
op.create_index("ix_equipment_acceptance_nodes_order", "equipment_acceptance_nodes", ["order_id"])
|
||||
op.create_table(
|
||||
"equipment_acceptance_operators",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("order_id", sa.Integer(), nullable=False),
|
||||
sa.Column("node_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("handler_name", sa.String(length=200), nullable=True),
|
||||
sa.Column("handler_job_num", sa.String(length=64), nullable=True),
|
||||
sa.ForeignKeyConstraint(["order_id"], ["equipment_acceptance_orders.id"], ondelete="CASCADE"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_equipment_acceptance_operators_order",
|
||||
"equipment_acceptance_operators",
|
||||
["order_id"],
|
||||
)
|
||||
op.create_table(
|
||||
"equipment_acceptance_send_records",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("order_id", sa.Integer(), nullable=True),
|
||||
sa.Column("acceptance_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("purchase_order_no", sa.String(length=128), nullable=True),
|
||||
sa.Column("tier", sa.Integer(), nullable=False),
|
||||
sa.Column("threshold_days", sa.Integer(), nullable=False),
|
||||
sa.Column("to_text", sa.Text(), nullable=True),
|
||||
sa.Column("cc_text", sa.Text(), nullable=True),
|
||||
sa.Column("recipients_json", sa.JSON(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["order_id"],
|
||||
["equipment_acceptance_orders.id"],
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"order_id",
|
||||
"tier",
|
||||
name="uq_equipment_acceptance_send_records_order_tier",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_equipment_acceptance_send_records_created",
|
||||
"equipment_acceptance_send_records",
|
||||
["created_at"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_equipment_acceptance_send_records_status",
|
||||
"equipment_acceptance_send_records",
|
||||
["status"],
|
||||
)
|
||||
op.create_table(
|
||||
"equipment_acceptance_settings",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("day_1", sa.Integer(), nullable=False, server_default="30"),
|
||||
sa.Column("day_2", sa.Integer(), nullable=False, server_default="37"),
|
||||
sa.Column("day_3", sa.Integer(), nullable=False, server_default="44"),
|
||||
sa.Column("day_4", sa.Integer(), nullable=False, server_default="51"),
|
||||
sa.Column("buyer_manager_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("coo_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("executive_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("updated_by", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(["buyer_manager_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||
sa.ForeignKeyConstraint(["coo_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||
sa.ForeignKeyConstraint(["executive_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||
)
|
||||
op.execute(
|
||||
"INSERT INTO equipment_acceptance_settings (id, day_1, day_2, day_3, day_4) "
|
||||
"VALUES (1, 30, 37, 44, 51)"
|
||||
)
|
||||
_seed_equipment_acceptance_agent()
|
||||
|
||||
|
||||
def _resync_agents_id_sequence() -> None:
|
||||
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
op.execute(
|
||||
"""
|
||||
SELECT setval(
|
||||
pg_get_serial_sequence('public.agents', 'id'),
|
||||
COALESCE((SELECT MAX(id) FROM public.agents), 1),
|
||||
true
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _seed_equipment_acceptance_agent() -> None:
|
||||
"""插入或复用设备验收预警 Agent。已有同编码实例时只更新入口配置。"""
|
||||
conn = op.get_bind()
|
||||
agent_id = conn.execute(
|
||||
text(
|
||||
"SELECT id FROM agents WHERE agent_code = :code "
|
||||
"ORDER BY id ASC LIMIT 1"
|
||||
),
|
||||
{"code": "equipment_acceptance"},
|
||||
).scalar()
|
||||
if agent_id is not None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE agents
|
||||
SET is_active = true,
|
||||
name = :name,
|
||||
description = :description,
|
||||
runtime_provider = 'builtin',
|
||||
conversation_mode = 'task_chat',
|
||||
dify_app_type = 'chatflow',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = :agent_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"agent_id": agent_id,
|
||||
"name": "设备验收预警",
|
||||
"description": "查看资产验收单停留天数,并从 E10 同步当前节点与操作人。",
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
_resync_agents_id_sequence()
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO agents (
|
||||
name, description, type, is_active, is_aggregate,
|
||||
agent_code, runtime_provider, conversation_mode, dify_app_type,
|
||||
suggested_questions_style, sort_order, created_at, updated_at
|
||||
) VALUES (
|
||||
:name, :description, 'api', true, false,
|
||||
:code, 'builtin', 'task_chat', 'chatflow',
|
||||
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"name": "设备验收预警",
|
||||
"description": "查看资产验收单停留天数,并从 E10 同步当前节点与操作人。",
|
||||
"code": "equipment_acceptance",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""删除验收快照、配置和发送记录。不删除已创建的 Agent,以免误伤运营配置。"""
|
||||
op.drop_index("ix_equipment_acceptance_send_records_status", table_name="equipment_acceptance_send_records")
|
||||
op.drop_index("ix_equipment_acceptance_send_records_created", table_name="equipment_acceptance_send_records")
|
||||
op.drop_table("equipment_acceptance_send_records")
|
||||
op.drop_table("equipment_acceptance_settings")
|
||||
op.drop_index("ix_equipment_acceptance_operators_order", table_name="equipment_acceptance_operators")
|
||||
op.drop_table("equipment_acceptance_operators")
|
||||
op.drop_index("ix_equipment_acceptance_nodes_order", table_name="equipment_acceptance_nodes")
|
||||
op.drop_table("equipment_acceptance_nodes")
|
||||
op.drop_index("ix_equipment_acceptance_orders_status", table_name="equipment_acceptance_orders")
|
||||
op.drop_table("equipment_acceptance_orders")
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
backend/tests/test_equipment_acceptance_alert_plan.py
|
||||
|
||||
用途:设备验收四档跨档和收件人组装的纯函数测试。
|
||||
依赖:alert_plan。不连接数据库,不访问 OA,不发企业微信。
|
||||
逻辑:超过阈值才进档。解析失败留在原角色上,不改发给别人。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.alert_plan import (
|
||||
assemble_tier,
|
||||
due_tiers,
|
||||
make_person,
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
)
|
||||
|
||||
_DAYS = (30, 37, 44, 51)
|
||||
|
||||
|
||||
def test_due_tiers_use_strictly_greater_than_threshold():
|
||||
"""刚好等于 30 天还不发。超过 51 天才四档都到。"""
|
||||
assert due_tiers(None, _DAYS) == []
|
||||
assert due_tiers(30, _DAYS) == []
|
||||
assert due_tiers(31, _DAYS) == [1]
|
||||
assert due_tiers(51, _DAYS) == [1, 2, 3]
|
||||
assert due_tiers(52, _DAYS) == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_tier_one_keeps_missing_supervisor_as_failure():
|
||||
"""直接主管缺失时整档仍可发给处理人和采购担当,不把申请人改成主送。"""
|
||||
handler = resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name="吴敏",
|
||||
job_num="10086",
|
||||
user=SimpleNamespace(id=7, wecom_userid="wx-handler", real_name="吴敏"),
|
||||
missing_job_error="吴敏没有工号",
|
||||
oa_employee_id=11,
|
||||
)
|
||||
supervisor = make_person(slot="cc", label="直接主管", name="吴敏", error="吴敏没有直接主管")
|
||||
applicant = resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name="赵琴",
|
||||
job_num="20001",
|
||||
user=SimpleNamespace(id=8, wecom_userid="wx-buyer", real_name="赵琴"),
|
||||
missing_job_error="没有申请人工号",
|
||||
)
|
||||
draft = assemble_tier(tier=1, threshold_days=30, to_people=[handler], cc_people=[supervisor, applicant])
|
||||
assert draft["status"] == "pending"
|
||||
assert draft["to_text"] == "吴敏"
|
||||
assert draft["cc_text"] == "赵琴"
|
||||
assert "吴敏没有直接主管" in draft["error_message"]
|
||||
assert all(item["label"] != "采购担当" or item["slot"] == "cc" for item in draft["recipients"])
|
||||
|
||||
|
||||
def test_duplicate_person_stays_only_on_the_primary_list():
|
||||
"""同一个人既是主送又是抄送时只留主送。"""
|
||||
person = resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name="吴敏",
|
||||
job_num="10086",
|
||||
user=SimpleNamespace(id=7, wecom_userid="wx-handler", real_name="吴敏"),
|
||||
missing_job_error="吴敏没有工号",
|
||||
)
|
||||
copied = dict(person)
|
||||
copied["slot"] = "cc"
|
||||
copied["label"] = "直接主管"
|
||||
draft = assemble_tier(tier=1, threshold_days=30, to_people=[person], cc_people=[copied])
|
||||
assert draft["to_text"] == "吴敏"
|
||||
assert draft["cc_text"] is None
|
||||
assert len(draft["recipients"]) == 1
|
||||
|
||||
|
||||
def test_unbound_wecom_and_missing_role_stay_failed():
|
||||
"""没绑企微、没选 COO 都记失败,不写死姓名。"""
|
||||
unbound = resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name="吴敏",
|
||||
job_num="10086",
|
||||
user=SimpleNamespace(id=7, wecom_userid="", real_name="吴敏"),
|
||||
missing_job_error="吴敏没有工号",
|
||||
)
|
||||
assert unbound["error"] == "未绑定企业微信"
|
||||
missing = resolve_configured_user(slot="to", label="COO", user=None, missing_error="未配置COO")
|
||||
draft = assemble_tier(tier=3, threshold_days=44, to_people=[missing], cc_people=[unbound])
|
||||
assert draft["status"] == "failed"
|
||||
assert draft["to_text"] is None
|
||||
assert "未配置COO" in draft["error_message"]
|
||||
assert "未绑定企业微信" in draft["error_message"]
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
tests/test_equipment_acceptance_config.py
|
||||
|
||||
用途:锁定设备验收预警四档天数的保存前校验。
|
||||
依赖:config_service.validate_reminder_days、ValidationError。
|
||||
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.equipment_acceptance.config_service import validate_reminder_days
|
||||
|
||||
|
||||
def test_default_reminder_days_pass():
|
||||
"""冻结默认值可以保存。"""
|
||||
assert validate_reminder_days([30, 37, 44, 51]) == (30, 37, 44, 51)
|
||||
|
||||
|
||||
def test_days_must_increase():
|
||||
"""后一档不大于前一档时拒绝,避免两档在同一天触发。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_reminder_days([30, 30, 44, 51])
|
||||
assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID"
|
||||
|
||||
|
||||
def test_days_reject_bool_and_wrong_length():
|
||||
"""布尔值在 Python 里也是 int,不能当成 1 天;档数必须是四档。"""
|
||||
with pytest.raises(ValidationError):
|
||||
validate_reminder_days([True, 37, 44, 51])
|
||||
with pytest.raises(ValidationError):
|
||||
validate_reminder_days([30, 37, 44])
|
||||
@@ -0,0 +1,257 @@
|
||||
"""
|
||||
backend/tests/test_equipment_acceptance_snapshot.py
|
||||
|
||||
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
||||
依赖:snapshot_rules、source_group、query_sql。不连接 OA,也不启动 Flask。
|
||||
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
EXCLUDED,
|
||||
NOT_STARTED,
|
||||
STOPPED_ARCHIVED,
|
||||
STOPPED_CANNOT_ACCEPT,
|
||||
STOPPED_FORCE_FINISHED,
|
||||
STOPPED_RETURNED,
|
||||
STOPPED_REVOKED,
|
||||
STOPPED_VOIDED,
|
||||
WATCHING,
|
||||
can_accept_from_oa,
|
||||
classify_monitor_status,
|
||||
dwell_days,
|
||||
is_returned_from_oa,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import group_acceptance_rows
|
||||
|
||||
|
||||
def test_oa_yes_no_is_flipped_before_storage():
|
||||
"""OA 0 是、1 否。验收空值保持空;退回空值收成否。其他值不猜测。"""
|
||||
assert can_accept_from_oa(0) == 1
|
||||
assert can_accept_from_oa(1) == 0
|
||||
assert can_accept_from_oa(None) is None
|
||||
assert can_accept_from_oa(2) == 2
|
||||
assert is_returned_from_oa(0) == 1
|
||||
assert is_returned_from_oa(1) == 0
|
||||
assert is_returned_from_oa(None) == 0
|
||||
assert is_returned_from_oa(2) == 2
|
||||
|
||||
|
||||
def test_returned_yes_stops_even_while_approving():
|
||||
"""is_returned=1 是退回,审批中也停表。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=1, flow_status=1, timer_started=True
|
||||
)
|
||||
assert status == STOPPED_RETURNED
|
||||
|
||||
|
||||
def test_cannot_accept_stops_and_null_can_accept_is_not_watching():
|
||||
"""can_accept=0 是不可以,停表;空值不是可以验收。"""
|
||||
stopped = classify_monitor_status(
|
||||
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
excluded = classify_monitor_status(
|
||||
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
assert stopped == STOPPED_CANNOT_ACCEPT
|
||||
assert excluded == EXCLUDED
|
||||
|
||||
|
||||
def test_not_returned_and_can_accept_watches():
|
||||
"""未退回且可以验收、审批中、已有计时起点时继续计时。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
assert status == WATCHING
|
||||
|
||||
|
||||
def test_terminal_flow_status_stops():
|
||||
"""3/4/5 分别停表。7、8、99、-99 都是撤销,没有计时起点也不再提醒。"""
|
||||
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=3, timer_started=True) == STOPPED_ARCHIVED
|
||||
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=4, timer_started=True) == STOPPED_FORCE_FINISHED
|
||||
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=5, timer_started=True) == STOPPED_VOIDED
|
||||
for flow_status in (7, 8, 99, -99):
|
||||
assert classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=flow_status, timer_started=True
|
||||
) == STOPPED_REVOKED
|
||||
assert classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=flow_status, timer_started=False
|
||||
) == STOPPED_REVOKED
|
||||
|
||||
|
||||
def test_missing_timer_is_not_started_when_no_stop_reason():
|
||||
"""没有计时起点且没有停表原因时是未开始。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=1, timer_started=False
|
||||
)
|
||||
assert status == NOT_STARTED
|
||||
|
||||
|
||||
def test_unknown_returned_is_excluded():
|
||||
"""0、1 以外的退回值既不判退回也不当未退回。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=2, flow_status=1, timer_started=True
|
||||
)
|
||||
assert status == EXCLUDED
|
||||
|
||||
|
||||
def test_dwell_days_freeze_on_archive_date():
|
||||
"""归档后的天数截止到归档日,不随同步日继续增加。"""
|
||||
days = dwell_days(
|
||||
timer_started_at=datetime(2026, 9, 1, 8, 0, 0),
|
||||
flow_status=3,
|
||||
finished_at=datetime(2026, 9, 11, 18, 0, 0),
|
||||
as_of=date(2026, 10, 8),
|
||||
)
|
||||
assert days == 10
|
||||
|
||||
|
||||
def test_dwell_days_use_sync_date_while_watching():
|
||||
"""计时中按同步日减起点的自然日。"""
|
||||
days = dwell_days(
|
||||
timer_started_at=date(2026, 10, 1),
|
||||
flow_status=1,
|
||||
finished_at=None,
|
||||
as_of=date(2026, 10, 8),
|
||||
)
|
||||
assert days == 7
|
||||
|
||||
|
||||
def test_group_splits_requests_and_dedupes_operators():
|
||||
"""不同 requestid 各成一张单。同一节点同一人只留一行,即使源行带了不同的 isremark。没有 requestid 的行跳过。"""
|
||||
drafts, skipped = group_acceptance_rows(
|
||||
[
|
||||
{
|
||||
"ysddh": "YS-1",
|
||||
"cgdh": "CG-1",
|
||||
"htbh": "HT-1",
|
||||
"sbsyrjssj": "2026-10-01 09:00:00",
|
||||
"sfkyzcys": 0,
|
||||
"ycsm": " 到货规格与请购不符 ",
|
||||
"sfzfth": None,
|
||||
"requestid": 10,
|
||||
"flowstatus": 3,
|
||||
"nodeid": 1,
|
||||
"nodename": "旧节点",
|
||||
"userid": 7,
|
||||
"isremark": 2,
|
||||
},
|
||||
{
|
||||
"ysddh": "YS-2",
|
||||
"requestid": 20,
|
||||
"flowstatus": 1,
|
||||
"nodeid": 2,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 8,
|
||||
"isremark": 0,
|
||||
"handler_name": "吴敏",
|
||||
"handler_job_num": "10086",
|
||||
},
|
||||
{
|
||||
"requestid": 20,
|
||||
"flowstatus": 1,
|
||||
"nodeid": 2,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 9,
|
||||
"isremark": 2,
|
||||
},
|
||||
{
|
||||
"requestid": 20,
|
||||
"flowstatus": 1,
|
||||
"nodeid": 2,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 8,
|
||||
"isremark": 9,
|
||||
"handler_name": "吴敏",
|
||||
"handler_job_num": "10086",
|
||||
},
|
||||
{"ysddh": "NO-REQUEST"},
|
||||
]
|
||||
)
|
||||
assert skipped == 1
|
||||
by_request = {draft.request_id: draft for draft in drafts}
|
||||
assert set(by_request) == {10, 20}
|
||||
assert by_request[10].acceptance_no == "YS-1"
|
||||
assert by_request[10].contract_no == "HT-1"
|
||||
assert by_request[10].can_accept == 1
|
||||
assert by_request[10].cannot_accept_note == "到货规格与请购不符"
|
||||
assert by_request[10].is_returned == 0
|
||||
assert by_request[10].flow_status_raw == 3
|
||||
current = by_request[20]
|
||||
assert current.request_match_count == 1
|
||||
assert current.flow_status_raw == 1
|
||||
assert [node.node_name for node in current.nodes] == ["使用部门担当"]
|
||||
assert sorted(item.user_id for item in current.operators) == [8, 9]
|
||||
assert not hasattr(current.operators[0], "isremark")
|
||||
|
||||
|
||||
def test_sql_uses_dictionary_catalogs_and_does_not_select_isremark():
|
||||
"""实例同时有字典库时用 weaver_wfc / weaver_wfp,SQL 不查询 isremark。"""
|
||||
catalogs = resolve_catalogs({"ecology10", "eteams", "weaver_wfc", "weaver_wfp"})
|
||||
sql = build_acceptance_sql(catalogs)
|
||||
assert catalogs.request == "weaver_wfc"
|
||||
assert catalogs.node == "weaver_wfp"
|
||||
assert "[weaver_wfc].[dbo].[wfc_operate]" in sql
|
||||
assert "[weaver_wfp].[dbo].[wfp_node]" in sql
|
||||
assert "isremark" not in sql.lower()
|
||||
assert "ycsm" in sql
|
||||
assert "workflow_requestbase" not in sql
|
||||
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
||||
assert "d.dataid = f.FORM_DATA_ID" in sql
|
||||
assert "lcbh" not in sql
|
||||
assert "htbh1" not in sql
|
||||
assert "ysrq" not in sql
|
||||
assert "requestmark" not in sql
|
||||
assert "operateround" not in sql.lower()
|
||||
assert "optgroupid" not in sql.lower()
|
||||
assert "batch_number" not in sql.lower()
|
||||
assert "operate_log_id" not in sql.lower()
|
||||
|
||||
|
||||
def test_sql_falls_back_when_dictionary_catalog_is_absent():
|
||||
"""看不到 weaver_wfc 时,流程表改用 ecology10。人员库缺失则失败。"""
|
||||
catalogs = resolve_catalogs({"ecology10", "eteams"})
|
||||
assert catalogs.request == "ecology10"
|
||||
assert catalogs.node == "ecology10"
|
||||
with pytest.raises(ValueError):
|
||||
resolve_catalogs({"ecology10"})
|
||||
|
||||
|
||||
def test_sql_rejects_unsafe_catalog_override():
|
||||
"""库名覆盖值不能带分号或空格。"""
|
||||
with pytest.raises(ValueError):
|
||||
resolve_catalogs({"ecology10", "eteams"}, request="weaver_wfc;drop")
|
||||
|
||||
|
||||
def test_send_record_payload_keeps_written_names():
|
||||
"""发送记录接口用写入时的单号和主送抄送,不回读当前岗位。"""
|
||||
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
|
||||
from app.services.equipment_acceptance.send_record_service import send_record_payload
|
||||
|
||||
row = EquipmentAcceptanceSendRecord(
|
||||
id=3,
|
||||
order_id=9,
|
||||
acceptance_no="YS-1",
|
||||
purchase_order_no="CG-1",
|
||||
tier=2,
|
||||
threshold_days=37,
|
||||
to_text="经副理甲",
|
||||
cc_text="COO、采购经副理",
|
||||
status="sent",
|
||||
sent_at=datetime(2026, 10, 9, 10, 0, 0),
|
||||
error_message=None,
|
||||
created_at=datetime(2026, 10, 9, 9, 0, 0),
|
||||
)
|
||||
payload = send_record_payload(row)
|
||||
assert payload["acceptance_no"] == "YS-1"
|
||||
assert payload["to_text"] == "经副理甲"
|
||||
assert payload["cc_text"] == "COO、采购经副理"
|
||||
assert payload["threshold_days"] == 37
|
||||
assert payload["status"] == "sent"
|
||||
assert payload["sent_at"]
|
||||
+3
-3
@@ -21,9 +21,9 @@
|
||||
|
||||
## 设备验收预警(2026-09)
|
||||
|
||||
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。退回或无法验收后再次进入且重新可以验收,按新周期从 0 计时。
|
||||
- 超过 30/37/44/51 天各发一次企业微信。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、廖总可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。
|
||||
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。当前节点表未提供,到位前不实现。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。
|
||||
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
|
||||
- 超过 30/37/44/51 天各发一次企业微信。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。
|
||||
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。
|
||||
|
||||
## 合同付款预警 Agent(2026-08)
|
||||
|
||||
|
||||
@@ -5,4 +5,4 @@
|
||||
| **需求说明** | 产品、业务、研发 | [demand.md](demand.md) |
|
||||
| **数据设计** | 研发 | [technical.md](technical.md) |
|
||||
|
||||
**状态**:规则已冻结(2026-09-29)。主表为 E10 `ft_gdzcysdv2`(2026-10-07)。当前节点表未提供,到位前不实现同步、计时和推送。见 [funclist.md](../../funclist.md)「设备验收预警」。
|
||||
**状态**:规则已冻结(2026-09-29)。只读同步、Chat 作业面、每日扫描和周五企业微信已实现(2026-10-12)。入口与合同付款预警相同,内置 Agent `equipment_acceptance`。页签有停留情况、发送记录和预警配置。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。见 [funclist.md](../../funclist.md)「设备验收预警」。
|
||||
@@ -0,0 +1,311 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>设备验收预警 · 配置效果图</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #142033;
|
||||
--muted: #64748b;
|
||||
--line: #dce4ef;
|
||||
--rail: #c9d4e3;
|
||||
--paper: #ffffff;
|
||||
--page: #f3f6fa;
|
||||
--brand: #1d4e89;
|
||||
--chip: #eef3f8;
|
||||
--soft: #f7f9fc;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: var(--page);
|
||||
color: var(--ink);
|
||||
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
.page { max-width: 1080px; margin: 0 auto; padding: 18px 20px 40px; }
|
||||
h1 { margin: 0; font-size: 20px; letter-spacing: 0; }
|
||||
.tabs { display: flex; gap: 4px; margin-top: 14px; border-bottom: 1px solid var(--line); }
|
||||
.tabs span {
|
||||
margin-bottom: -1px;
|
||||
padding: 8px 12px 10px;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--muted);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.tabs .on { border-color: var(--brand); color: var(--brand); }
|
||||
.lead { margin: 14px 0 12px; color: var(--muted); font-size: 13px; }
|
||||
.sheet {
|
||||
background: var(--paper);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 1px 2px rgba(20, 32, 51, 0.04);
|
||||
}
|
||||
.sheet-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 18px 22px 8px;
|
||||
}
|
||||
.sheet-head h2 { margin: 0; font-size: 15px; }
|
||||
.sheet-head p { margin: 4px 0 0; color: var(--muted); font-size: 12px; }
|
||||
.rounds { padding: 6px 8px 8px; }
|
||||
.round {
|
||||
display: grid;
|
||||
grid-template-columns: 168px minmax(0, 1fr);
|
||||
gap: 8px 18px;
|
||||
margin: 0 14px;
|
||||
padding: 16px 0 16px 28px;
|
||||
border-left: 2px solid var(--rail);
|
||||
position: relative;
|
||||
}
|
||||
.round:last-child { border-left-color: transparent; }
|
||||
.round::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: -7px;
|
||||
top: 24px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 2px solid #fff;
|
||||
border-radius: 50%;
|
||||
background: var(--brand);
|
||||
box-shadow: 0 0 0 1px var(--rail);
|
||||
}
|
||||
.when { display: flex; flex-direction: column; gap: 8px; }
|
||||
.when b { font-size: 12px; color: var(--muted); font-weight: 700; }
|
||||
.day {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.day input {
|
||||
width: 72px;
|
||||
height: 40px;
|
||||
border: 1px solid #d5dee8;
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
color: var(--ink);
|
||||
font: 650 22px/1 "Segoe UI", "PingFang SC", sans-serif;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: center;
|
||||
}
|
||||
.people { display: flex; flex-direction: column; gap: 8px; padding-top: 2px; }
|
||||
.line { display: flex; align-items: flex-start; gap: 10px; min-height: 32px; }
|
||||
.tag {
|
||||
flex: 0 0 36px;
|
||||
margin-top: 6px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.plain {
|
||||
margin-top: 5px;
|
||||
font-size: 14px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.note { margin-top: 6px; color: #94a3b8; font-size: 12px; }
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.chip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 32px;
|
||||
padding: 4px 8px 4px 4px;
|
||||
border-radius: 999px;
|
||||
background: var(--chip);
|
||||
}
|
||||
.avatar {
|
||||
display: grid;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
place-items: center;
|
||||
border-radius: 50%;
|
||||
background: #d7e4f2;
|
||||
color: var(--brand);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.who { display: flex; flex-direction: column; line-height: 1.15; }
|
||||
.who strong { font-size: 13px; }
|
||||
.who span { color: var(--muted); font-size: 11px; }
|
||||
.role-name { color: var(--muted); font-size: 12px; }
|
||||
button.link {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--brand);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.ghost {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-top: 4px;
|
||||
padding: 14px 22px;
|
||||
border-top: 1px solid var(--line);
|
||||
background: #fafbfd;
|
||||
border-radius: 0 0 16px 16px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
button.save {
|
||||
height: 36px;
|
||||
padding: 0 16px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mark {
|
||||
margin: 10px 2px 0;
|
||||
color: #8b97a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<h1>设备验收预警</h1>
|
||||
<div class="tabs">
|
||||
<span>停留情况</span>
|
||||
<span>发送记录</span>
|
||||
<span class="on">预警配置</span>
|
||||
</div>
|
||||
<p class="lead">四轮天数须逐轮增大。保存后只影响以后新产生的预警。发送时刻在排程里改。</p>
|
||||
|
||||
<section class="sheet">
|
||||
<div class="sheet-head">
|
||||
<div>
|
||||
<h2>升级轮次</h2>
|
||||
<p>左边改超过多少天。右边是这一轮的主送和抄送。COO、采购经副理、总经理各选一次,用到的轮次都显示同一个人。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounds">
|
||||
<article class="round">
|
||||
<div class="when">
|
||||
<b>第 1 轮</b>
|
||||
<label class="day">超过 <input value="30" /> 天</label>
|
||||
</div>
|
||||
<div class="people">
|
||||
<div class="line"><span class="tag">主送</span><span class="plain">当前节点处理人</span></div>
|
||||
<div class="line"><span class="tag">抄送</span><span class="plain">其直接主管、采购担当</span></div>
|
||||
<span class="note">随当前单据变化,这里不选人</span>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article class="round">
|
||||
<div class="when">
|
||||
<b>第 2 轮</b>
|
||||
<label class="day">超过 <input value="37" /> 天</label>
|
||||
</div>
|
||||
<div class="people">
|
||||
<div class="line"><span class="tag">主送</span><span class="plain">当前节点处理人的经副理</span></div>
|
||||
<div class="line">
|
||||
<span class="tag">抄送</span>
|
||||
<div class="chips">
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · COO</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
<button class="ghost" type="button">清除</button>
|
||||
</div>
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · 采购经副理</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
<button class="ghost" type="button">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article class="round">
|
||||
<div class="when">
|
||||
<b>第 3 轮</b>
|
||||
<label class="day">超过 <input value="44" /> 天</label>
|
||||
</div>
|
||||
<div class="people">
|
||||
<div class="line">
|
||||
<span class="tag">主送</span>
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · COO</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
<button class="ghost" type="button">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="line">
|
||||
<span class="tag">抄送</span>
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · 采购经副理</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
<button class="ghost" type="button">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article class="round">
|
||||
<div class="when">
|
||||
<b>第 4 轮</b>
|
||||
<label class="day">超过 <input value="51" /> 天</label>
|
||||
</div>
|
||||
<div class="people">
|
||||
<div class="line">
|
||||
<span class="tag">主送</span>
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · 总经理</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
<button class="ghost" type="button">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="line">
|
||||
<span class="tag">抄送</span>
|
||||
<div class="chips">
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · COO</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
</div>
|
||||
<div class="chip">
|
||||
<span class="avatar">S</span>
|
||||
<span class="who"><strong>sophie</strong><span>26030025 · 采购经副理</span></span>
|
||||
<button class="link" type="button">更换</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="foot">
|
||||
<span>已发送记录保持不变</span>
|
||||
<button class="save" type="button">保存配置</button>
|
||||
</div>
|
||||
</section>
|
||||
<p class="mark">效果图,尚未接到现有页面。</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,8 +1,8 @@
|
||||
# 设备验收预警需求说明
|
||||
|
||||
> **版本**:V1.0
|
||||
> **更新日期**:2026-10-07
|
||||
> **状态**:规则已冻结。验收单主表已明确为 E10 `ecology10.dbo.ft_gdzcysdv2`,当前节点表未提供。节点表到位前不写同步、计时和推送。数据设计见 [technical.md](technical.md)。
|
||||
> **更新日期**:2026-10-08
|
||||
> **状态**:规则已冻结。只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。发送时刻不在配置页,默认排程每天 06:00 扫描、每周五 18:00 发送。数据设计见 [technical.md](technical.md)。
|
||||
> **适用范围**:OA 资产验收单停留预警、企业微信通知、固定岗位配置
|
||||
|
||||
## 1. 背景与目标
|
||||
@@ -17,14 +17,15 @@
|
||||
|
||||
- 监控对象、计时起点、自然日累计、停表与再进入规则。
|
||||
- 四档升级的主送、抄送,以及当前节点处理人、上级、申请人的取人规则。
|
||||
- 采购经副理、COO、廖总三个固定岗位可在管理界面配置,禁止在代码中写死姓名或账号。
|
||||
- 采购经副理、COO、总经理三个固定岗位可在管理界面配置,禁止在代码中写死姓名或账号。
|
||||
- 企业微信为唯一通知渠道。每日扫描只生成待发送记录;发送时刻可配置,初始为每周五 18:00,按收件人汇总一条。
|
||||
- 数据来源见第 7 节。缺字段的单据跳过并留下原因。
|
||||
|
||||
停留列表已接到对话页:内置 Chat Agent `equipment_acceptance`,与合同付款预警一样替换消息列表和输入框。
|
||||
|
||||
### 2.2 本期不做
|
||||
|
||||
- 不写同步、计时、推送、配置界面和数据表。当前节点表到位后再开。
|
||||
- 不做聊天工作台,不接 Dify。
|
||||
- 不接 Dify 对话。
|
||||
- 不撤回已发送的企业微信。停表只取消尚未发出的预警。
|
||||
- 「使用部门担当」之前的节点(ERP 触发、申请人确认、直属上级)不参与计时。
|
||||
|
||||
@@ -44,9 +45,9 @@
|
||||
|
||||
- 归档
|
||||
- 退回、撤回、作废
|
||||
- 验收单上为无法验收(无法验收说明从验收单抓取,只作留痕,不单独触发通知)
|
||||
- 验收单上为无法验收(说明正文是 `ycsm`,只作留痕,不单独触发通知)
|
||||
|
||||
已确认:同一流程因退回或无法验收退出监控后,若再次进入「使用部门担当」且重新满足「未归档、有效、可以验收」,按**新周期从 0 计时**。上一周期已发过的档位不占用新周期,四档可以再各发一次。撤回、作废、归档后的同一请求不再恢复旧周期。
|
||||
已确认:退回或无法验收后再进入,「使用部门担当」的计时起点 `sbsyrjssj` 不会改写,签核天数仍按第一次写入的时间计算,不从 0 重计,也不另找起点。四档按这一段累计天数各发一次,不因再进入而重发。`sfzfth` 不考虑从退回(`0`)改回正常(`1` 或空);不靠这个变化恢复计时。撤回、作废、归档后的同一请求不再恢复。
|
||||
|
||||
## 5. 升级与收件人
|
||||
|
||||
@@ -57,13 +58,13 @@
|
||||
| 超过 30 天 | 当前节点处理人(担当) | 其直接主管、采购担当 |
|
||||
| 超过 37 天 | 当前节点处理人的经副理 | COO、采购经副理 |
|
||||
| 超过 44 天 | COO | 采购经副理 |
|
||||
| 超过 51 天 | 廖总对应岗位 | COO、采购经副理 |
|
||||
| 超过 51 天 | 总经理 | COO、采购经副理 |
|
||||
|
||||
人员解析:
|
||||
|
||||
- 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。
|
||||
- 采购担当取该流程的**申请人**。
|
||||
- 采购经副理、COO、廖总是固定岗位。配置初始值分别为赵琴、COO、廖总,必须能在管理界面修改。代码与环境文件不得写死这三个人的姓名或账号。
|
||||
- 采购经副理、COO、总经理是固定岗位。配置初始值分别为赵琴、COO、廖总,必须能在管理界面修改。代码与环境文件不得写死这三个人的姓名或账号。
|
||||
- 当前节点有多名处理人时,主送这些处理人;直接主管、经副理按各处理人展开后去重。
|
||||
- 收件人解析失败(无上级、未绑定企业微信)时,该条保持失败可追查,不改发给别人。
|
||||
|
||||
@@ -75,22 +76,24 @@
|
||||
|
||||
权威设计见 [technical.md](technical.md)。摘要如下:
|
||||
|
||||
- 连接只用 `.env.shared` 的 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`,库为 `ecology10`。
|
||||
- 连接只用 `.env.shared` 的 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`。验收单在 `ecology10`,流程实例字典库为 `weaver_wfc`,节点定义字典库为 `weaver_wfp`。
|
||||
- 验收单主表是 `ecology10.dbo.ft_gdzcysdv2`。验收单单号 `ysddh`,采购单号 `cgdh`。计时起点 `sbsyrjssj` 只在第一次进入「使用部门担当」时写入,之后不改。
|
||||
- `sybmdd`(使用部门担当)、`sbglry`(设备管理人员)存人员 ID,关联 `eteams.dbo.employee.ID`,用工号 `JOB_NUM` 匹配 HXOPS 用户。
|
||||
- `sfkyzcys` 是是否可以正常验收:**0 是可以,1 是不可以**,与常见 0/1 相反。空值不纳入监控。
|
||||
- 当前节点和当前处理人在另一张表,表名与字段后续补充。未归档、归档仍依赖该表。表未到之前不实现。
|
||||
- `sfkyzcys` 是是否可以正常验收:**0 是可以,1 是不可以**,与常见 0/1 相反。空值不纳入监控。无法验收说明正文是 `ycsm`,只留痕,不单独触发停表。
|
||||
- `sfzfth`:**0 是退回,1 和空都是流程正常。** 空值不当成退回。作废不看这一列。
|
||||
- 未归档、归档、作废、撤销看 `wfc_requestbase.flowstatus`(`1` 审批中,`3` 正常归档,`5` 已作废)。`7`、`8`、`99`、`-99` 都按撤销处理,停表且不再提醒。当前节点看 `weaver_wfc.dbo.wfc_currentnode.nodeid`,名称关联 `weaver_wfp.dbo.wfp_node`。`lastnodeid` 是最后操作节点,不当作当前节点。申请人 `sqr` 已确认是人员 ID。
|
||||
- 当前处理人在 `weaver_wfc.dbo.wfc_operate`。`userid` 是操作人,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一人只留一行。每日扫描按这些人展开四档收件人。
|
||||
|
||||
直接主管、经副理按当前处理人查上级,不从主表取。采购经副理、COO、廖总不从单据取,只读界面配置。
|
||||
直接主管取当前处理人的 `employee.SUPERIOR`。经副理用该人的 `employee.DEPARTMENT` 查 `eteams.dbo.hrm_matrix_condition_data`,人在 `eteams.dbo.hrm_matrix_value_data.relate_id`。不查 E8 矩阵。采购经副理、COO、总经理不从矩阵取,只读界面配置。
|
||||
|
||||
## 8. 验收标准(视图到位后的实现对照)
|
||||
|
||||
| 编号 | 条件 | 期望 |
|
||||
| --- | --- | --- |
|
||||
| AC-01 | 尚未进入「使用部门担当」 | 不计时、不产生预警 |
|
||||
| AC-02 | 进入该节点后第 30/37/44/51 个自然日 | 各档只产生一次待发送,收件人符合第 5 节 |
|
||||
| AC-02 | 签核天数超过 30/37/44/51 | 各档只产生一次待发送,刚好等于还不发。收件人符合第 5 节 |
|
||||
| AC-03 | 进入后更换后续节点 | 累计天数不重置 |
|
||||
| AC-04 | 归档、退回、撤回、作废或无法验收 | 立即停表,取消未发送预警,已发送消息保留 |
|
||||
| AC-05 | 退回或无法验收后再次进入「使用部门担当」且重新可以验收 | 新周期从 0 计时,四档可再各发一次 |
|
||||
| AC-05 | 退回或无法验收后再次进入 | 签核天数仍从原 `sbsyrjssj` 计算。不把 `sfzfth` 从 `0` 改回正常当作恢复 |
|
||||
| AC-06 | 发送时刻 | 默认每周五 18:00 按收件人汇总;时刻可配置 |
|
||||
| AC-07 | 修改采购经副理、COO、廖总配置 | 此后新产生的预警使用新人员,不改历史已发送记录 |
|
||||
| AC-07 | 修改采购经副理、COO、总经理配置 | 此后新产生的预警使用新人员,不改历史已发送记录 |
|
||||
+4
-4
@@ -178,7 +178,7 @@
|
||||
<label class="rung"><span class="k">第 1 档</span><span class="num"><input id="cfgDay0" type="number" min="1" value="30" /><em>天</em></span><small id="rungWho0">当前处理人</small></label>
|
||||
<label class="rung"><span class="k">第 2 档</span><span class="num"><input id="cfgDay1" type="number" min="1" value="37" /><em>天</em></span><small id="rungWho1">经副理</small></label>
|
||||
<label class="rung"><span class="k">第 3 档</span><span class="num"><input id="cfgDay2" type="number" min="1" value="44" /><em>天</em></span><small id="rungWho2">COO</small></label>
|
||||
<label class="rung"><span class="k">第 4 档</span><span class="num"><input id="cfgDay3" type="number" min="1" value="51" /><em>天</em></span><small id="rungWho3">廖总</small></label>
|
||||
<label class="rung"><span class="k">第 4 档</span><span class="num"><input id="cfgDay3" type="number" min="1" value="51" /><em>天</em></span><small id="rungWho3">总经理</small></label>
|
||||
</div>
|
||||
<div class="cfg-split">
|
||||
<article class="card">
|
||||
@@ -186,7 +186,7 @@
|
||||
<div class="bd roles">
|
||||
<label class="role"><span>采购经副理</span><input id="cfgBuyer" /></label>
|
||||
<label class="role"><span>COO</span><input id="cfgCoo" /></label>
|
||||
<label class="role"><span>廖总对应岗位</span><input id="cfgBoss" /></label>
|
||||
<label class="role"><span>总经理</span><input id="cfgBoss" /></label>
|
||||
<label class="role"><span>发送时刻</span><select id="cfgWhen"><option>每周五 18:00</option><option>每周一 09:00</option><option>每天 09:00</option></select></label>
|
||||
</div>
|
||||
<div class="card-foot"><span class="muted">已发送记录保持不变</span><button class="btn primary" id="saveCfg">保存配置</button></div>
|
||||
@@ -223,9 +223,9 @@
|
||||
{ id:'YS-2026-0160', po:'CG-2026-0886', applicant:'孙浩', node:'公用主管', handlers:['吴敏','林可'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-30', days:31, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'当前节点两名处理人,直接主管相同,抄送去重为钱伟。' },
|
||||
{ id:'YS-2026-0188', po:'CG-2026-0910', applicant:'刘洋', node:'品质担当', handlers:['郑凯'], supervisor:'', deputy:'孙经理', entered:'2026-08-28', days:33, cycle:1, state:'watching', sent:[], fail:'直接主管缺失', stop:'', note:'第 1 档无法解析直接主管,保持失败,不改发。' },
|
||||
{ id:'YS-2026-0172', po:'CG-2026-0933', applicant:'陈静', node:'品质担当', handlers:['郑凯'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-10', days:20, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'未超过第 1 档,只监控不发。' },
|
||||
{ id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-26', days:4, cycle:2, state:'watching', sent:[], fail:'', stop:'', note:'上一周期因无法验收停表。再次进入后从 0 计时,四档可再发。' },
|
||||
{ id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-10', days:60, cycle:1, state:'watching', sent:[0,1,2,3], fail:'', stop:'', note:'无法验收后再进入,签核天数仍从第一次写入的计时起点计算,不从 0 重计。' },
|
||||
{ id:'YS-2026-0071', po:'CG-2026-0550', applicant:'吴芳', node:'品质经理', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-01', days:40, cycle:1, state:'stopped', sent:[0], fail:'', stop:'无法验收', note:'无法验收说明:到货规格与请购不符。未发送的后续档已取消。' },
|
||||
{ id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。若再次进入使用部门担当,按新周期从 0 计。' },
|
||||
{ id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。再进入仍用第一次的计时起点,不按 sfzfth 改回正常来恢复。' },
|
||||
{ id:'YS-2026-0201', po:'CG-2026-1008', applicant:'韩冰', node:'直属上级', handlers:['—'], supervisor:'', deputy:'', entered:'', days:0, cycle:0, state:'out', sent:[], fail:'', stop:'', note:'尚未进入使用部门担当,不计时。' }
|
||||
];
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# 设备验收预警设计
|
||||
|
||||
> **版本**:V1.0
|
||||
> **更新日期**:2026-10-07
|
||||
> **状态**:主数据表已明确;当前节点表未提供。节点表到位前不写同步、计时和推送。
|
||||
> **版本**:V1.19
|
||||
> **更新日期**:2026-10-12
|
||||
> **状态**:只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同:内置 Agent `equipment_acceptance`。当前处理人取当前节点上的 `wfc_operate.userid`,不查询、不保存 `isremark`。发送时刻不在配置表,默认排程是每天 06:00 扫描、每周五 18:00 发送,可在排程页改 Cron。
|
||||
> **业务规则**:[demand.md](demand.md)。本文只说明数据从哪读、人员怎么对上、哪些事实还缺。
|
||||
|
||||
## 1. 结论
|
||||
|
||||
验收单主数据读 OA E10 的 `ecology10.dbo.ft_gdzcysdv2`。人员 ID 到 `eteams.dbo.employee` 取出工号,再用工号对上 HXOPS 用户。流程现在停在哪个节点、当前处理人是谁,来自另一张表,表名和字段以后补充。那张表没到之前,不能判断未归档、当前节点和当前处理人,因此仍不实现扫描和推送。
|
||||
验收单主数据读 OA E10 的 `ecology10.dbo.ft_gdzcysdv2`。人员 ID 到 `eteams.dbo.employee` 取出工号,再用工号对上 HXOPS 用户。流程是否归档、作废、撤销,读 `wfc_requestbase.flowstatus`。当前节点读 `wfc_currentnode.nodeid`,再关联 `wfp_node.nodename`。`lastnodeid` 是最后操作节点,不拿来当当前节点。当前处理人读 `wfc_operate.userid`,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一节点同一人只留一行。每日扫描按这些处理人展开四档收件人。
|
||||
|
||||
## 2. 连接
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
| `OA_E10_SQLSERVER_USERNAME` | 只读账号 |
|
||||
| `OA_E10_SQLSERVER_PASSWORD` | 只读密码 |
|
||||
|
||||
库名固定为 `ecology10`。人员表在同一实例的 `eteams` 库。本功能要求上述三个变量已配置,不回退到 E9 的 `OA_SQLSERVER_*`。
|
||||
验收单在 `ecology10`,人员表在同一实例的 `eteams`。流程字典写明:`wfc_requestbase`、`wfc_currentnode`、`wfc_operate` 所属库 `weaver_wfc`,`wfp_node` 所属库 `weaver_wfp`。现场曾在 `ecology10` 的 `INFORMATION_SCHEMA` 查出 `wfc_requestbase` 的列,查询时先按字典库名,账号看不到 `weaver_wfc` / `weaver_wfp` 时再改用 `ecology10` 里的同名表。本功能要求上述三个变量已配置,不回退到 E8 的 `OA_SQLSERVER_*`。
|
||||
|
||||
## 3. 验收单主表
|
||||
|
||||
@@ -27,36 +27,36 @@
|
||||
|
||||
| 字段 | 含义 | 在预警里的用法 |
|
||||
| ------------- | -------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `lcbh` | 流程编号 | 流程标识。和后续节点表关联时优先用它。 |
|
||||
| `ysddh` | 验收单单号 | 台账、详情、企业微信上的验收单单号。 |
|
||||
| `cgdh` | 采购单号 | 台账上的采购单号。 |
|
||||
| `htbh` | 合同编号 | 合同编号。与 `htbh1` 的分工未说明,两列都保留,不合并。 |
|
||||
| `htbh1` | 合同编号 | 同上。 |
|
||||
| `ysrq` | 验收日期 | 单据上的验收日期,不是计时起点。 |
|
||||
| `htbh` | 合同编号 | 只保存这一列。表上没有第二合同编号。 |
|
||||
| `sbsyrjssj` | 设备使用人员计时时间 | 计时起点。第一次进入「使用部门担当」时写入,之后不改。为空表示还没开始计时。 |
|
||||
| `sybmdd` | 使用部门担当 | 人员 ID,关联 `eteams.dbo.employee.ID`。 |
|
||||
| `sbglry` | 设备管理人员 | 人员 ID,关联方式同 `sybmdd`。 |
|
||||
| `sqr` | 申请人 | 预警规则里的采购担当。样例中是与 `sybmdd` 相同形态的长整型,按 `employee.ID` 关联。 |
|
||||
| `sqr` | 申请人 | 预警规则里的采购担当。已确认是人员 ID,关联 `eteams.dbo.employee.ID`。 |
|
||||
| `syry` | 使用人员 | 样例中同样是长整型 ID,按 `employee.ID` 关联。 |
|
||||
| `gzglry` | 固资管理人员 | 人员字段。样例多为空;非空时按同一 ID 关联。 |
|
||||
| `dx` | 使用人员1 | 同上。 |
|
||||
| `agent` | 资管经办人 | 同上。 |
|
||||
| `sfzfth` | 是否作废退回 | 作废或退回时停表。样例里见过空值和 `0`,枚举含义未给出,实现前要确认哪个值表示作废或退回。 |
|
||||
| `sfkyzcys` | 是否可以正常验收 | **0 表示可以,1 表示不可以。** 与常见的 0=否、1=是相反。空值不当成可以验收。 |
|
||||
| `sfzfth` | 是否作废退回 | OA 上 **0 是退回,1 和空都是流程正常。** 落库 `is_returned` 翻转成 0 否、1 是,空收成 0。作废不看这一列,作废看 `flowstatus = 5`。 |
|
||||
| `sfkyzcys` | 是否可以正常验收 | OA 上 **0 表示可以,1 表示不可以。** 落库 `can_accept` 翻转成 0 否、1 是。空值保持空,不当成可以验收。 |
|
||||
| `ycsm` | 无法验收说明 | 说明正文。落库 `cannot_accept_note`。只留痕,不单独触发停表。停表仍看 `sfkyzcys = 1`。 |
|
||||
|
||||
`sfkyzcys` 只表达能不能正常验收,不是无法验收说明正文。说明原文仍未出现在已给字段里。
|
||||
`sfkyzcys` 只表达能不能正常验收。说明正文是 `ycsm`。
|
||||
|
||||
已确认按 ID 关联人员的是 `sybmdd`、`sbglry`。`sqr`、`syry` 在样例结果里是同类长整型,设计上人员列统一走 `employee.ID`。若核对后某列不是人员 ID,只改该列,不改工号匹配方式。
|
||||
已确认按 ID 关联人员的是 `sybmdd`、`sbglry`、`sqr`。`syry`、`gzglry`、`dx`、`agent` 在样例结果里是同类长整型,设计上人员列统一走 `employee.ID`。若核对后某列不是人员 ID,只改该列,不改工号匹配方式。
|
||||
|
||||
## 4. 人员怎么对上系统用户
|
||||
|
||||
`eteams.dbo.employee` 至少使用这三列:
|
||||
`eteams.dbo.employee` 使用这些列:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| ------------ | ----------------------------------------------------- |
|
||||
| `ID` | 与验收单人员字段关联 |
|
||||
| `USERNAME` | 显示姓名。只用于展示,不作为匹配键。 |
|
||||
| `JOB_NUM` | 工号。对应 HXOPS 用户表的工号,工号在系统用户中唯一。 |
|
||||
| `ID` | 与验收单人员字段、操作人 `userid` 关联 |
|
||||
| `USERNAME` | 显示姓名。只用于展示,不作为匹配键。 |
|
||||
| `JOB_NUM` | 工号。对应 HXOPS 用户表的工号,工号在系统用户中唯一。 |
|
||||
| `DEPARTMENT` | 部门 ID。只用来查经副理 |
|
||||
| `SUPERIOR` | 直接主管的人员 ID。再关联本表 `ID` |
|
||||
|
||||
关联顺序:
|
||||
|
||||
@@ -67,33 +67,172 @@
|
||||
|
||||
对不上时该条保持失败,可追查,不改发给别人。失败包括:人员 ID 为空、`employee` 无此 ID、`JOB_NUM` 为空、工号在 HXOPS 无用户、用户未绑定企业微信。
|
||||
|
||||
直接主管、经副理不在这两张表里。仍按需求:取当前节点处理人的上级。上级来源等节点表补充后再定,不从 `ft_gdzcysdv2` 臆造。
|
||||
直接主管取当前处理人在 `employee.SUPERIOR` 上的人员 ID,不查矩阵。经副理才查 E10 矩阵,见第 4.1 节。不从 `ft_gdzcysdv2` 臆造,也不查 E8 的 `Matrixtable_3`。
|
||||
|
||||
采购经副理、COO、廖总只读界面配置,不从这两张表取。
|
||||
采购经副理、COO、总经理只读界面配置,不从矩阵表取。
|
||||
|
||||
## 4.1 直接主管与经副理
|
||||
|
||||
按当前处理人查,不按申请人查,也不查 E8。
|
||||
|
||||
1. 当前处理人是 `wfc_operate.userid`,等于 `eteams.dbo.employee.ID`。
|
||||
2. 直接主管是该员工的 `SUPERIOR`。这是人员 ID,再关联 `employee.ID` 取姓名和工号。空或关联不上就记失败,不改发给别人。
|
||||
3. 经副理用该员工的 `DEPARTMENT`(部门 ID)查 E10 部门矩阵。人员在 `hrm_matrix_value_data.relate_id`,再同样关联 `employee`。不要把这个 ID 当成企微 userid,也不要对 `HrmResource.id`。
|
||||
|
||||
多名当前处理人时,各自取 `SUPERIOR` 和经副理,然后去重。
|
||||
|
||||
三个固定值已确认。`tenant_key` 为 `temkc46eme`。矩阵 `id` `1115770797884751874` 是苏州和信的「HXJM-审批矩阵」,取自 `eteams.dbo.hrm_matrix.id`。经副理取值配置 `id` `1115771897387991041` 取自 `eteams.dbo.hrm_matrix_value_config`:`config_name` 为「经副理」,且 `matrix_id` 为上面这个矩阵。该配置 `config_type` 是 `resource`,`single_type = 1`(单选)。查人仍用 `hrm_matrix_value_data.relate_id`,不要把配置表的 `id` 当成人员 ID。`delete_type = 0` 为正常。同一矩阵下还有总经理等其他取值配置,不拿来当经副理。
|
||||
|
||||
矩阵 id 和经副理配置 id 按下面两条查出,不在代码里另找别的矩阵:
|
||||
|
||||
```sql
|
||||
-- 苏州和信「HXJM-审批矩阵」的 id。
|
||||
SELECT id
|
||||
FROM eteams.dbo.hrm_matrix
|
||||
WHERE tenant_key = 'temkc46eme'
|
||||
AND matrix_name = N'HXJM-审批矩阵'
|
||||
AND delete_type = 0
|
||||
AND enable_status = 1;
|
||||
-- 结果:1115770797884751874
|
||||
|
||||
-- 该矩阵下 config_name 为「经副理」的取值配置 id。
|
||||
SELECT id
|
||||
FROM eteams.dbo.hrm_matrix_value_config
|
||||
WHERE tenant_key = 'temkc46eme'
|
||||
AND matrix_id = 1115770797884751874
|
||||
AND config_name = N'经副理'
|
||||
AND delete_type = 0;
|
||||
-- 结果:1115771897387991041
|
||||
```
|
||||
|
||||
已用 `employee.DEPARTMENT = 1115763045510725632` 核对:`hrm_matrix_value_data.matrix_data_id` 没有这个值。因此这张矩阵不能把 `matrix_data_id` 直接当成部门 ID。部门 ID 改到条件表 `hrm_matrix_condition_data.relate_id` 里按字符串匹配,先取出矩阵数据行,再取值:
|
||||
|
||||
```sql
|
||||
-- 经副理。表都在 eteams.dbo,不能省库名。
|
||||
-- 返回的 relate_id 是人员 ID,再关联 eteams.dbo.employee.ID,不要当成企微 userid。
|
||||
-- :department_id 取当前处理人的 employee.DEPARTMENT,必须按字符串比较。
|
||||
-- 已用部门 1115763045510725632 跑通,返回一名经副理。
|
||||
SELECT v.relate_id
|
||||
FROM eteams.dbo.hrm_matrix_value_data AS v
|
||||
WHERE v.tenant_key = 'temkc46eme' -- 租户
|
||||
AND v.matrix_id = 1115770797884751874 -- hrm_matrix:苏州和信「HXJM-审批矩阵」的 id
|
||||
AND v.matrix_value_config_id = 1115771897387991041 -- hrm_matrix_value_config:该矩阵下 config_name 为「经副理」的 id,不是人员 ID
|
||||
AND v.delete_type = 0 -- 0 正常,1/2/3 都是删除
|
||||
AND v.matrix_data_id IN (
|
||||
-- 部门 ID 不在 matrix_data_id 上。先从条件表找出矩阵数据行。
|
||||
SELECT c.matrix_data_id
|
||||
FROM eteams.dbo.hrm_matrix_condition_data AS c
|
||||
WHERE c.tenant_key = 'temkc46eme'
|
||||
AND c.matrix_id = 1115770797884751874
|
||||
AND c.delete_type = 0
|
||||
AND c.relate_id = :department_id -- 字符串,例如 '1115763045510725632'
|
||||
)
|
||||
```
|
||||
|
||||
条件配置 id 还没限定。若同一部门对出多行,再按 `matrix_condition_config_id` 收窄。
|
||||
|
||||
## 5. 计时与停表在现有字段上怎么落
|
||||
|
||||
计时起点用 `sbsyrjssj`。已确认它只在第一次进入「使用部门担当」时写入一次,之后不改写。从该时间起到当前按自然日累计,换节点不重置。字段为空的单据视为尚未开始计时,不产生预警。
|
||||
|
||||
`sfzfth` 表示作废或退回,命中后停表并取消未发送预警。具体取值等枚举确认。
|
||||
退回只看 `sfzfth`。OA 取值是 0=是、1=否。落库列 `is_returned` 先翻转成标准布尔:0 否,1 是。已确认取值:
|
||||
|
||||
是否可以正常验收看 `sfkyzcys`,取值与常见布尔相反:
|
||||
| OA `sfzfth` | 本地 `is_returned` | 含义 | 预警 |
|
||||
| --- | --- | --- | --- |
|
||||
| `0` | `1` | 是,退回 | 立即停表,取消尚未发出的预警。不考虑从 `0` 改回 `1` 或空。 |
|
||||
| `1` | `0` | 否,流程正常 | 不因本字段停表 |
|
||||
| 空 | `0` | 否,流程正常 | 与 OA `1` 相同,不当成退回 |
|
||||
|
||||
| 值 | 含义 | 预警 |
|
||||
字段中文名是「是否作废退回」,已确认的取值只区分退回和正常。作废、撤销仍看下一节的 `flowstatus`,不用 `sfzfth` 代替。出现 `0`、`1`、空以外的值时,不判退回,也不当正常,先记下来待确认。
|
||||
|
||||
不考虑 `sfzfth` 从 `0` 改回 `1` 或空。不把这种改写当作恢复计时或新周期。
|
||||
|
||||
是否可以正常验收看 `sfkyzcys`。OA 取值与常见布尔相反:0=是、1=否。落库列 `can_accept` 翻转成 0 否、1 是。空值不翻转成否。
|
||||
|
||||
| OA `sfkyzcys` | 本地 `can_accept` | 含义 | 预警 |
|
||||
| --- | --- | --- | --- |
|
||||
| `0` | `1` | 是,可以正常验收 | 其他条件也满足时继续计时 |
|
||||
| `1` | `0` | 否,不可以正常验收 | 立即停表,取消尚未发出的预警 |
|
||||
| 空 | 空 | 未标明 | 不纳入监控,不按「可以验收」处理 |
|
||||
|
||||
退回或无法验收后再进入,`sbsyrjssj` 仍是第一次写入的时间,签核天数就按它计算,不从 0 重计。不读取、不保存 `wfc_operate.operateround`。
|
||||
|
||||
## 5.1 流程实例与节点定义
|
||||
|
||||
OA 数据字典:
|
||||
|
||||
| 表 | 中文名 | 字典所属库 | 用途 |
|
||||
| --- | --- | --- | --- |
|
||||
| `wfc_requestbase` | 流程实例基本信息表 | `weaver_wfc` | 一条流程一行。状态、编号、最后操作节点。 |
|
||||
| `wfc_currentnode` | 流程当前节点表 | `weaver_wfc` | 流程当前停在哪个节点。没有处理人。 |
|
||||
| `wfp_node` | 工作流节点基础信息表 | `weaver_wfp` | 节点定义。用 `id` 取出节点名称和节点类型。 |
|
||||
|
||||
`wfc_currentnode` 字段:
|
||||
|
||||
| 字段 | 字典含义 | 用法 |
|
||||
| --- | --- | --- |
|
||||
| `0` | 可以正常验收 | 其他条件也满足时继续计时 |
|
||||
| `1` | 不可以正常验收 | 立即停表,取消尚未发出的预警 |
|
||||
| 空 | 未标明 | 不纳入监控,不按「可以验收」处理 |
|
||||
| `requestid` | 流程实例 id。来源说明写着 `wfc_operate` | 等于 `wfc_requestbase.requestid` |
|
||||
| `nodeid` | 数据所在节点 ID。来源说明写着 `wfc_operate` | 等于 `wfp_node.id`,这是当前节点 |
|
||||
| `nodetype` | 节点类型 | 本表字典没有 0–9。类型以 `wfp_node.nodetype` 为准 |
|
||||
| `delete_type` | 是否删除 | 只取 `0` |
|
||||
| `operate_log_id` | 批次号 | 不查询、不保存 |
|
||||
| `creator` | 数据插入人 | 不是当前处理人 |
|
||||
|
||||
下面几件事这张主表给不了,都等节点表:
|
||||
关联:
|
||||
|
||||
- 当前节点名称
|
||||
- 当前节点处理人(担当、直接主管、经副理都从这里取,不固定成 `sybmdd`)
|
||||
- 是否未归档、是否已归档
|
||||
- 无法验收说明正文
|
||||
- 撤回与归档的发生时间
|
||||
1. `ft_gdzcysdv2.FORM_DATA_ID` = `wfc_form_data.dataid`,且 `wfc_form_data.delete_type = 0`。验收单上没有流程编号列,不读 `requestmark`。
|
||||
2. `wfc_form_data.requestid` = `wfc_requestbase.requestid`。本地快照按这个 `requestid` 唯一。归档看 `flowstatus = 3`,不看验收日期。
|
||||
3. `wfc_requestbase.requestid` = `wfc_currentnode.requestid`,且 `wfc_currentnode.delete_type = 0`。
|
||||
4. `wfc_currentnode.nodeid` = `wfp_node.id`。展示名称用 `wfp_node.nodename`。
|
||||
5. 分流时一条流程可以有多行当前节点。这些行都保留,节点名称分别列出。计时仍按整单累计,不按节点重置。
|
||||
|
||||
退回或无法验收后再次进入,仍按需求从 0 重计一个新周期。`sbsyrjssj` 不会被改写,所以新周期不能靠这个字段变空或变新时间来识别,需要节点表上的再次进入标记。
|
||||
`wfc_requestbase.lastnodeid` 仍是「最后操作节点 ID」,只表示刚办过的节点。当前节点以 `wfc_currentnode.nodeid` 为准。
|
||||
|
||||
`wfp_node.nodetype`:0 发起,1 审批,2 确认,3 结束,4 子流程节点,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅。`nodeattr`:0 一般节点,1 分流点,2 分流中间点,3 合流点。`wfc_requestbase.lastnodetype` 只标了「最后操作流程节点类型」,字典没有给出 0–9。不把 `nodetype` 的枚举直接套到 `lastnodetype`。
|
||||
|
||||
流程状态以 `flowstatus` 为准。同表的 `status` 是最长 1000 的文本,没有枚举,不拿来判断停表。
|
||||
|
||||
| `flowstatus` | 字典含义 | 预警 |
|
||||
| --- | --- | --- |
|
||||
| `0` | 草稿 | 不监控 |
|
||||
| `1` | 审批中 | 其他条件也满足时可以计时 |
|
||||
| `3` | 正常归档 | 停表,不恢复旧周期 |
|
||||
| `4` | 强制结束 | 流程已结束。业务未单列这一项,先按停表、不恢复处理 |
|
||||
| `5` | 已作废 | 停表,不恢复旧周期 |
|
||||
| `6` | 待提交 | 不按审批中处理 |
|
||||
| `7` | 暂停 | 已确认与撤销相同:停表,不再提醒,不恢复旧周期 |
|
||||
| `8` | 撤销 | 停表,不再提醒,不恢复旧周期 |
|
||||
| `99`、`-99` | `99` 为业务确认值;`-99` 是字典截断处 | 与撤销相同:停表,不再提醒 |
|
||||
|
||||
字典没有值为「退回」的流程状态。退回后 `flowstatus` 仍可能是 `1`(审批中)。退回以验收单 `sfzfth = 0` 为准,不从 `flowstatus` 推断。
|
||||
|
||||
`finishdatetime` 是流程归档时间。字典另有拼写 `finshdatetime`(少一个 i),含义写成「流程归档时间、作废时间」。现场列清单里是 `finishdatetime`。查询只用 `finishdatetime`,不查 `finshdatetime`。
|
||||
|
||||
`lastoperator` 是最后操作人,`wfc_currentnode.creator` 是插行的人,都不是当前待办人。`delete_type` 是记录是否删除,不是作废。作废看 `flowstatus = 5`。
|
||||
|
||||
## 5.2 流程操作人
|
||||
|
||||
表:`weaver_wfc.dbo.wfc_operate`,中文名「流程操作人表」。当前处理人在这张表。
|
||||
|
||||
| 字段 | 字典含义 | 用法 |
|
||||
| --- | --- | --- |
|
||||
| `requestid` | 流程实例 id | 等于 `wfc_currentnode.requestid` |
|
||||
| `nodeid` | 数据所在节点 ID | 等于 `wfc_currentnode.nodeid`。只取当前节点上的操作人 |
|
||||
| `userid` | 操作人 id | 当前处理人。关联 `eteams.dbo.employee.ID` |
|
||||
| `processuser` | 实际操作人 ID | 已经代办或实际点过的人。待办人取 `userid`,不取这一列 |
|
||||
| `usertype` | 人员类型 | 字典没有取值。先按 `userid` 关联员工,关联不上记失败 |
|
||||
| `isremark` | 操作状态 | 不查询、不保存。当前处理人就是当前节点上的 `userid` |
|
||||
| `preisremark` | 插入时的操作状态,插入后不变更 | 不查询、不保存 |
|
||||
| `operatedatetime` | 操作日期时间 | 已办才会有操作时间。不能单靠它为空就把抄送、转发都算成待办 |
|
||||
| `showorder` | 未操作者的显示顺序 | 说明表里包含未操作的人 |
|
||||
| `operateround` | 节点第几次到达 | 不查询、不保存 |
|
||||
| `isbereject` | 是否退回操作 | 字典没有 0/1。退回仍以 `sfzfth = 0` 为准 |
|
||||
| `isprocessing` | 执行中时,流程不出现在待办、已办 | 字典没有哪个值表示执行中。该状态的行不发预警 |
|
||||
| `delete_type` | 是否删除 | 只取 `0` |
|
||||
| `optgroupid` | 操作者批次 | 不查询、不保存 |
|
||||
| `batch_number` | 批次号 | 不查询、不保存。与 `wfc_currentnode.operate_log_id` 一样不参与预警 |
|
||||
|
||||
当前节点上的 `userid` 都是当前处理人。同一人只留一行。直接主管、经副理按各人展开后去重。会签关系 `signorder` 的取值未给,不改变「这些人都要通知」。
|
||||
|
||||
## 6. 查询形态
|
||||
|
||||
@@ -101,13 +240,13 @@
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
f.lcbh,
|
||||
f.ysddh,
|
||||
f.cgdh,
|
||||
f.ysrq,
|
||||
f.htbh,
|
||||
f.sbsyrjssj,
|
||||
f.sfzfth,
|
||||
f.sfkyzcys,
|
||||
f.ycsm,
|
||||
f.sybmdd,
|
||||
owner.USERNAME AS owner_name,
|
||||
owner.JOB_NUM AS owner_job_num,
|
||||
@@ -116,14 +255,40 @@ SELECT
|
||||
equip.JOB_NUM AS equip_job_num,
|
||||
f.sqr,
|
||||
applicant.USERNAME AS applicant_name,
|
||||
applicant.JOB_NUM AS applicant_job_num
|
||||
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 ecology10.dbo.ft_gdzcysdv2 AS f
|
||||
LEFT JOIN eteams.dbo.employee AS owner ON owner.ID = f.sybmdd
|
||||
LEFT JOIN eteams.dbo.employee AS equip ON equip.ID = f.sbglry
|
||||
LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr;
|
||||
LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_form_data AS d
|
||||
ON d.dataid = f.FORM_DATA_ID
|
||||
AND d.delete_type = 0
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_requestbase AS r
|
||||
ON r.requestid = d.requestid
|
||||
AND r.delete_type = 0
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_currentnode AS c
|
||||
ON c.requestid = r.requestid
|
||||
AND c.delete_type = 0
|
||||
LEFT JOIN weaver_wfp.dbo.wfp_node AS n
|
||||
ON n.id = c.nodeid
|
||||
AND n.delete_type = 0
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_operate AS op
|
||||
ON op.requestid = c.requestid
|
||||
AND op.nodeid = c.nodeid
|
||||
AND op.delete_type = 0
|
||||
LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid;
|
||||
```
|
||||
|
||||
`syry`、`gzglry`、`dx`、`agent` 需要展示或发通知时,按同样方式再关联 `employee`。当前节点表补充后,用 `lcbh` 与主表拼接,不在应用里先全量拉人再在内存里对 ID。
|
||||
验收单上没有流程编号、第二合同编号和验收日期,这三列不查询、也不写入本地表。归档只看 `flowstatus = 3`。不查询 `isremark`。当前节点上的 `userid` 就是当前处理人,同一人只留一行。一条流程有多个当前节点、每个节点有多名操作人时,这个查询会返回多行。库名按第 2 节:看不到 `weaver_wfc` / `weaver_wfp` 时改为 `ecology10`。`syry`、`gzglry`、`dx`、`agent` 需要展示或发通知时,按同样方式再关联 `employee`。不在应用里先全量拉人再在内存里对 ID。
|
||||
|
||||
## 7. 和需求规则的对照
|
||||
|
||||
@@ -131,17 +296,143 @@ LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr;
|
||||
| ---------------------- | -------------------------- | --------------------------- |
|
||||
| 验收单单号 | `ysddh` | 无 |
|
||||
| 采购单号 | `cgdh` | 无 |
|
||||
| 流程编号 | `lcbh` | 无 |
|
||||
| 计时起点 | `sbsyrjssj`,只写一次、不覆盖 | 无。再次进入的新周期另要标记。 |
|
||||
| 一张流程的身份 | `wfc_requestbase.requestid` | 不保存流程编号。验收日期不参与归档。 |
|
||||
| 计时起点 | `sbsyrjssj`,只写一次、不覆盖 | 再进入也用这个时间,不从 0 重计。 |
|
||||
| 使用部门担当 | `sybmdd` → `employee` | 无 |
|
||||
| 申请人(采购担当) | `sqr` → `employee` | 关联方式按样例采用,待核对 |
|
||||
| 作废、退回 | `sfzfth` | 枚举未给 |
|
||||
| 当前节点、当前处理人 | 另一张表 | 表名和字段未给 |
|
||||
| 未归档、归档 | 另一张表 | 同上 |
|
||||
| 可以正常验收 | `sfkyzcys`:`0` 可以,`1` 不可以 | 空值不监控。说明正文仍缺。 |
|
||||
| 直接主管、经副理 | 当前处理人的上级 | 节点表到位后再定来源 |
|
||||
| 固定岗位三人 | 界面配置 | 不读 OA |
|
||||
| 申请人(采购担当) | `sqr` → `employee` | 已确认是人员 ID |
|
||||
| 作废 | `flowstatus = 5` | 不看 `sfzfth` |
|
||||
| 撤销 | `flowstatus` 为 `7`、`8`、`99`、`-99` | 都停表且不再提醒。本地状态 `stopped_revoked` |
|
||||
| 退回 | OA `sfzfth = 0`,本地 `is_returned = 1` | `1` 和空都是未退回,本地写成 `0`。 |
|
||||
| 归档、未归档 | `flowstatus`:`3` 正常归档,`1` 审批中 | `4` 强制结束先按结束。 |
|
||||
| 当前节点名称 | `wfc_currentnode.nodeid` → `wfp_node.nodename` | 分流时可能多行,都保留。`lastnodeid` 不是当前节点 |
|
||||
| 当前处理人 | `wfc_operate.userid`,对齐当前 `requestid` + `nodeid` | 不使用 `isremark`。同一人只留一行 |
|
||||
| 可以正常验收 | OA `sfkyzcys`:`0` 可以,`1` 不可以。本地 `can_accept` 为 `1` 可以、`0` 不可以 | 空值不监控,也不写成 0。说明正文是 `ycsm`。 |
|
||||
| 直接主管 | 当前处理人的 `employee.SUPERIOR` | 人员 ID,再关联 `employee` |
|
||||
| 经副理 | `eteams.dbo.hrm_matrix_value_data.relate_id`。部门 ID 在 `eteams.dbo.hrm_matrix_condition_data.relate_id` | 查询已用部门 `1115763045510725632` 跑通。`matrix_data_id` 不是部门 ID |
|
||||
| 再次进入 | 仍用第一次的 `sbsyrjssj` | 不从 0 重计。不看 `sfzfth` 是否从 `0` 改回正常。不用 `operateround`。 |
|
||||
| 固定岗位三人 | 界面配置 | 不读 OA |
|
||||
|
||||
## 8. 仍不实现的部分
|
||||
## 8. 已实现的同步
|
||||
|
||||
节点表、`sfzfth` 枚举、无法验收说明正文未齐之前,不写同步、计时引擎、企业微信发送、配置落库和数据表。原型继续用样例数据,不接这张表。实现 `sfkyzcys` 时禁止按「1 为是」处理。
|
||||
平台管理员调用 `POST /api/equipment-acceptance/sync`。连接只用 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`,不回退 E8 的 `OA_SQLSERVER_*`。库名先按字典;实例里没有 `weaver_wfc` 或 `weaver_wfp` 时,流程表和节点表改用 `ecology10`。人员库只认 `eteams`。
|
||||
|
||||
本地表保存 OA 同步快照,另有一张发送记录表。一张验收单在 `equipment_acceptance_orders` 里一行,当前节点和操作人在另外两张表。每次同步按 `request_id` 更新主表,并整批替换该单的节点和操作人。主表删除时,节点和操作人随外键级联删除,发送记录只把 `order_id` 置空并保留单号快照。不保存流程编号、第二合同编号和验收日期。归档看 `flow_status_raw = 3`,不看验收日期。每日扫描写入发送记录;停表时取消还没发出的行。
|
||||
|
||||
### 8.1 `equipment_acceptance_orders`
|
||||
|
||||
一张验收单的最近一次同步结果。`request_id` 唯一。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `request_id` | OA 流程实例 ID,来自 `wfc_requestbase.requestid`。一张流程一行 |
|
||||
| `acceptance_no` | 验收单单号,来自 `ysddh` |
|
||||
| `purchase_order_no` | 采购单号,来自 `cgdh` |
|
||||
| `contract_no` | 合同编号,来自 `htbh` |
|
||||
| `timer_started_at` | 计时起点,来自 `sbsyrjssj`。空表示还没开始计时 |
|
||||
| `dwell_days` | 签核天数。归档、强制结束、作废且有 `finished_at` 时停在结束日,否则算到同步日 |
|
||||
| `can_accept` | 是否可以正常验收。**0 否,1 是,空表示未标明。** 由 OA `sfkyzcys` 翻转而来,OA 是 0 是、1 否。空不写成 0 |
|
||||
| `cannot_accept_note` | 无法验收说明正文,来自 `ycsm`。空表示没有说明。不参与停表判断 |
|
||||
| `is_returned` | 是否退回。**0 否,1 是。** 由 OA `sfzfth` 翻转而来,OA 是 0 是、1 否。OA 的 1 和空都收成 0 |
|
||||
| `flow_status_raw` | `wfc_requestbase.flowstatus` 原值。1 审批中,3 正常归档,4 强制结束,5 已作废 |
|
||||
| `finished_at` | 流程结束时间,来自 `finishdatetime`。不拿它判断是否归档 |
|
||||
| `request_match_count` | 这一行对应的流程实例数,现在固定为 1 |
|
||||
| `owner_oa_id` / `owner_name` / `owner_job_num` | 使用部门担当。人员 ID 来自 `sybmdd`,姓名和工号来自 `employee` |
|
||||
| `equip_oa_id` / `equip_name` / `equip_job_num` | 设备管理人员,来自 `sbglry` |
|
||||
| `applicant_oa_id` / `applicant_name` / `applicant_job_num` | 申请人(采购担当),来自 `sqr` |
|
||||
| `monitor_status` | 监控状态,取值见下表 |
|
||||
| `present_in_source` | 这次同步是否还能在 OA 里看到这张单。看不到时保留上次内容,只把本列改成否 |
|
||||
| `synced_at` | 最近一次同步时间 |
|
||||
| `created_at` / `updated_at` | 本地创建、更新时间 |
|
||||
|
||||
`monitor_status`:
|
||||
|
||||
| 值 | 含义 |
|
||||
| --- | --- |
|
||||
| `watching` | 进行中。审批中、可以验收、未退回、已有计时起点 |
|
||||
| `not_started` | 未开始。没有计时起点,且没有更优先的停表原因 |
|
||||
| `stopped_returned` | 已退回。`is_returned = 1` |
|
||||
| `stopped_cannot_accept` | 无法验收。`can_accept = 0` |
|
||||
| `stopped_archived` | 已归档。`flow_status_raw = 3`,之后不再追踪预警 |
|
||||
| `stopped_force_finished` | 已强制结束。`flow_status_raw = 4` |
|
||||
| `stopped_voided` | 已作废。`flow_status_raw = 5` |
|
||||
| `stopped_revoked` | 已撤销,不再提醒。`flow_status_raw` 为 `7`、`8`、`99` 或 `-99` |
|
||||
| `excluded` | 不在监控范围。不含上面的撤销取值 |
|
||||
|
||||
退回、无法验收先于作废、归档、强制结束和撤销。撤销即使没有计时起点也记为 `stopped_revoked`,不记成未开始。归档、强制结束、作废、撤销且有 `finished_at` 时,签核天数截止到该日。`optgroupid`、`batch_number`、`operate_log_id` 不查询、不保存。
|
||||
|
||||
### 8.2 `equipment_acceptance_nodes`
|
||||
|
||||
这张单当前停在哪些节点。同一张单可以有多行,分流时每个当前节点一行。同一张单里 `order_id` + `node_id` 不重复。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `order_id` | 对应 `equipment_acceptance_orders.id` |
|
||||
| `node_id` | OA 当前节点 ID,来自 `wfc_currentnode.nodeid` |
|
||||
| `node_name` | 节点名称,来自 `wfp_node.nodename` |
|
||||
| `node_type` | 节点类型原值,来自 `wfp_node.nodetype`。0 发起,1 审批,2 确认,3 结束,4 子流程,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅 |
|
||||
|
||||
`lastnodeid` 不写入本表。
|
||||
|
||||
### 8.3 `equipment_acceptance_operators`
|
||||
|
||||
当前节点上的操作人。同一节点同一人只留一行。不保存 `isremark`。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `order_id` | 对应 `equipment_acceptance_orders.id` |
|
||||
| `node_id` | 这个人所属的当前节点 |
|
||||
| `user_id` | OA 操作人 ID,来自 `wfc_operate.userid` |
|
||||
| `handler_name` | 操作人姓名 |
|
||||
| `handler_job_num` | 操作人工号 |
|
||||
|
||||
扫描按这张表的当前处理人展开直接主管和经副理。直接主管、经副理不在本表,查询时再读 E10。
|
||||
|
||||
`GET /api/equipment-acceptance/orders` 分页列表。`focus` 取 `watching`、`overdue`、`stopped`、`not_started`;`overdue` 是计时中且签核天数超过配置里的第 1 档,默认 30。响应里的 `summary` 始终统计全部单据。`GET /api/equipment-acceptance/orders/<id>` 含当前节点操作人。人员主键以字符串返回。平台管理员,或被授予启用中 Agent 的用户,可以打开列表和详情。同步仍只给平台管理员。停留列表四张汇总卡是进行中、已逾期、不再提醒、未开始。计时中且超过 30 天显示已逾期,未超过显示未超时。停留列表不显示第几档。
|
||||
|
||||
### 8.4 `equipment_acceptance_send_records`
|
||||
|
||||
一张验收单某一档的发送记录。同一张单同一档只有一行。待发送和解析失败的行每次扫描按当前处理人和当前岗位重算;已发送、已取消的姓名不再改写。Chat 页签「发送记录」读 `GET /api/equipment-acceptance/sends`。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `order_id` | 对应 `equipment_acceptance_orders.id`。验收单被删时置空 |
|
||||
| `acceptance_no` / `purchase_order_no` | 写入时的验收单单号、采购单号 |
|
||||
| `tier` | 第几档,1 到 4 |
|
||||
| `threshold_days` | 这一档当时的天数,例如 30 |
|
||||
| `to_text` / `cc_text` | 解析成功的主送、抄送姓名,用顿号拼接 |
|
||||
| `recipients_json` | 每个席位的角色、姓名、系统用户、企微 userid、OA 人员 ID 和失败原因 |
|
||||
| `status` | `pending` 待发送,`sent` 已发送,`failed` 解析或发送失败,`cancelled` 已取消 |
|
||||
| `sent_at` | 发出时间。只有 `sent` 才有 |
|
||||
| `error_message` | 解析失败或企业微信发送失败的原因。能发出的人仍会发送 |
|
||||
| `created_at` | 记录生成时间 |
|
||||
|
||||
页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。
|
||||
|
||||
`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。
|
||||
|
||||
## 9. 扫描与发送
|
||||
|
||||
每天 06:00(Asia/Shanghai)排程 `equipment-acceptance-alert-scan` 先同步 E10,再按签核天数生成待发送。超过配置天数才进档,刚好等于还不发。默认 30/37/44/51。同一张单每一档只生成一次;已发送和已取消不重算、不重发。
|
||||
|
||||
收件人:
|
||||
|
||||
- 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。
|
||||
- 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。
|
||||
- 超过第 3 档:主送 COO,抄送采购经副理。
|
||||
- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。
|
||||
|
||||
人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。
|
||||
|
||||
每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号合并成一条文本卡片,标题「设备验收停留提醒」,事件 `equipment_acceptance_warning`。卡片过长时先留 12 行,其余写成「另有 N 条」。发送成功改为已发送。有人失败则整档改为失败,并附上「企业微信发送失败」;下次扫描会按当前处理人重算并回到待发送。已发出的企业微信不撤回。
|
||||
|
||||
停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。
|
||||
|
||||
管理员在发送记录页可以立即「扫描预警」和「发送预警」,对应 `POST /api/equipment-acceptance/alerts/scan` 和 `POST /api/equipment-acceptance/alerts/send`。两个排程启动时写入,已有同编号时不覆盖。Cron 在排程页改,不在预警配置页。
|
||||
|
||||
不查询、不保存 `isremark`。不接 Dify。不给「使用部门担当」之前的节点单独计时。读 OA `sfkyzcys`、`sfzfth` 时仍是 0 表示是、1 表示否,禁止把 OA 原值直接写进 `can_accept`、`is_returned`。`ycsm` 只保存说明,不拿它判断能不能验收。
|
||||
|
||||
数据库升到迁移 `ea8c0a1b2c3d` 后,快照、配置和带收件人明细的发送记录一次建好,扫描才能落库。
|
||||
+6
-2
@@ -45,8 +45,12 @@
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。退回或无法验收后再次进入且重新可以验收时,按新周期从 0 计时。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
||||
| 四档企业微信升级 | 待当前节点表 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、廖总为可配置固定岗位。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。主表已明确为 E10 `ft_gdzcysdv2`,当前节点表未提供,到位前不写同步、计时和推送。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
||||
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
|
||||
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
||||
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,采购经副理、COO、总经理选择系统用户。发送时刻不在此页,以后由排程 Cron 配置,默认每周五 18:00。 |
|
||||
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果和发送时间。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
|
||||
| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人汇总一条企业微信。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||
|
||||
## 知识库同步状态校验
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、EquipmentAcceptanceChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
|
||||
* 货代会话主区域:有会话即全屏批次进度中心(常驻),无会话为欢迎页+输入框;会话标题取自侧栏历史并传给中心;
|
||||
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框。
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、设备验收预警、立账凭证 Agent 用作业面替换消息列表与输入框。
|
||||
|
||||
*/
|
||||
|
||||
@@ -47,7 +47,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
|
||||
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isEquipmentAcceptanceAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
import {
|
||||
SHIPPING_WORKFLOW_KEY,
|
||||
@@ -79,6 +79,10 @@ const ContractPaymentChatPanel = defineRecoverableAsyncComponent(
|
||||
() => import('@/features/contract-payment/components/ContractPaymentChatPanel.vue'),
|
||||
);
|
||||
|
||||
const EquipmentAcceptanceChatPanel = defineRecoverableAsyncComponent(
|
||||
() => import('@/features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue'),
|
||||
);
|
||||
|
||||
const VoucherCheckChatPanel = defineRecoverableAsyncComponent(
|
||||
() => import('@/features/voucher-check/components/VoucherCheckChatPanel.vue'),
|
||||
);
|
||||
@@ -130,11 +134,14 @@ const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAge
|
||||
/** 合同付款预警 Agent:主区嵌台账 Tab,隐藏对话输入与历史。 */
|
||||
const isContractPaymentAgentPage = computed(() => isContractPaymentAgent(page.currentAgent));
|
||||
|
||||
/** 设备验收预警 Agent:主区嵌停留列表,隐藏对话输入与历史。 */
|
||||
const isEquipmentAcceptanceAgentPage = computed(() => isEquipmentAcceptanceAgent(page.currentAgent));
|
||||
|
||||
/** 立账凭证 Agent:主区嵌检核任务 / 企微发送记录 Tab,隐藏对话输入与历史。 */
|
||||
const isVoucherCheckAgentPage = computed(() => isVoucherCheckAgent(page.currentAgent));
|
||||
|
||||
/** builtin 作业面 Agent 共用:隐藏新会话、历史列表与输入框。 */
|
||||
const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isVoucherCheckAgentPage.value);
|
||||
const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isEquipmentAcceptanceAgentPage.value || isVoucherCheckAgentPage.value);
|
||||
|
||||
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
|
||||
const transferFlowActive = ref(false);
|
||||
@@ -489,6 +496,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<ContractPaymentChatPanel v-else-if="isContractPaymentAgentPage" />
|
||||
|
||||
<EquipmentAcceptanceChatPanel v-else-if="isEquipmentAcceptanceAgentPage" />
|
||||
|
||||
<VoucherCheckChatPanel v-else-if="isVoucherCheckAgentPage" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* features/equipment-acceptance/api/equipment-acceptance.api.ts
|
||||
* 用途:设备验收预警同步列表、详情和手动同步。
|
||||
* 依赖:统一 requestJson;后端 /api/equipment-acceptance。
|
||||
* 逻辑:Chat 作业面调用。同步只读 E10。配置只保存天数和系统用户,不保存发送时刻。
|
||||
* 发送记录只读已落库的行,扫描尚未写入时列表为空。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
export interface EquipmentAcceptanceNode {
|
||||
node_id?: string | null;
|
||||
node_name?: string | null;
|
||||
node_type?: number | null;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceOperator {
|
||||
node_id?: string | null;
|
||||
user_id?: string | null;
|
||||
handler_name?: string | null;
|
||||
handler_job_num?: string | null;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceOrder {
|
||||
id: number;
|
||||
acceptance_no?: string | null;
|
||||
purchase_order_no?: string | null;
|
||||
contract_no?: string | null;
|
||||
timer_started_at?: string | null;
|
||||
dwell_days?: number | null;
|
||||
can_accept?: number | null;
|
||||
cannot_accept_note?: string | null;
|
||||
is_returned?: number | null;
|
||||
flow_status_raw?: number | null;
|
||||
finished_at?: string | null;
|
||||
request_id?: string | null;
|
||||
request_match_count: number;
|
||||
owner_name?: string | null;
|
||||
owner_job_num?: string | null;
|
||||
applicant_name?: string | null;
|
||||
applicant_job_num?: string | null;
|
||||
monitor_status: string;
|
||||
overdue?: boolean;
|
||||
present_in_source: boolean;
|
||||
synced_at?: string | null;
|
||||
nodes: EquipmentAcceptanceNode[];
|
||||
operators: EquipmentAcceptanceOperator[];
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceSummary {
|
||||
watching: number;
|
||||
overdue: number;
|
||||
stopped: number;
|
||||
not_started: number;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceListResponse {
|
||||
items: EquipmentAcceptanceOrder[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
pages: number;
|
||||
summary?: EquipmentAcceptanceSummary;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceSyncResult {
|
||||
upserted: number;
|
||||
skipped_without_request_id: number;
|
||||
absent: number;
|
||||
by_status: Record<string, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询已同步的验收单。
|
||||
* 核心逻辑:focus 对应原型分组。空或 all 不过滤。
|
||||
* @param params.focus - watching、overdue、stopped、not_started
|
||||
* @param params.page - 页码,从 1 开始
|
||||
* @param params.pageSize - 每页条数
|
||||
* @returns 分页快照和全部单据汇总
|
||||
*/
|
||||
export function listEquipmentAcceptanceOrders(params?: {
|
||||
focus?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}) {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.focus && params.focus !== 'all') query.set('focus', params.focus);
|
||||
if (params?.page) query.set('page', String(params.page));
|
||||
if (params?.pageSize) query.set('page_size', String(params.pageSize));
|
||||
const suffix = query.toString() ? `?${query.toString()}` : '';
|
||||
return requestJson<EquipmentAcceptanceListResponse>(`/api/equipment-acceptance/orders${suffix}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取一张验收单的节点和操作人。
|
||||
* @param orderId - 本地快照主键
|
||||
* @returns 快照详情
|
||||
*/
|
||||
export function getEquipmentAcceptanceOrder(orderId: number) {
|
||||
return requestJson<EquipmentAcceptanceOrder>(`/api/equipment-acceptance/orders/${orderId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 E10 拉取验收单并更新本地快照。仅平台管理员可调用。
|
||||
* @returns 本次写入、跳过和未见条数
|
||||
*/
|
||||
export function syncEquipmentAcceptance() {
|
||||
return requestJson<EquipmentAcceptanceSyncResult>('/api/equipment-acceptance/sync', { method: 'POST' });
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceScanResult {
|
||||
created: number;
|
||||
updated: number;
|
||||
cancelled: number;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceSendResult {
|
||||
sent: number;
|
||||
failed: number;
|
||||
records_sent: number;
|
||||
records_failed: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员立即同步 E10 并生成待发送记录。
|
||||
* @returns 新增、更新和取消条数
|
||||
*/
|
||||
export function scanEquipmentAcceptanceAlerts() {
|
||||
return requestJson<EquipmentAcceptanceScanResult>('/api/equipment-acceptance/alerts/scan', { method: 'POST' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员立即把待发送记录按收件人发到企业微信。
|
||||
* @returns 成功和失败的收件人数
|
||||
*/
|
||||
export function sendEquipmentAcceptanceAlerts() {
|
||||
return requestJson<EquipmentAcceptanceSendResult>('/api/equipment-acceptance/alerts/send', { method: 'POST' });
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceSendRecord {
|
||||
id: number;
|
||||
order_id?: number | null;
|
||||
acceptance_no?: string | null;
|
||||
purchase_order_no?: string | null;
|
||||
tier: number;
|
||||
threshold_days: number;
|
||||
to_text?: string | null;
|
||||
cc_text?: string | null;
|
||||
status: string;
|
||||
sent_at?: string | null;
|
||||
error_message?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceSendListResponse {
|
||||
items: EquipmentAcceptanceSendRecord[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页读取发送记录。
|
||||
* 核心逻辑:按创建时间倒序。还没有扫描写入时 items 为空。
|
||||
* @param params.page - 从 1 开始
|
||||
* @param params.pageSize - 每页条数
|
||||
* @returns 当前页记录和总数
|
||||
*/
|
||||
export function listEquipmentAcceptanceSends(params?: { page?: number; pageSize?: number }) {
|
||||
const search = new URLSearchParams();
|
||||
if (params?.page) search.set('page', String(params.page));
|
||||
if (params?.pageSize) search.set('page_size', String(params.pageSize));
|
||||
const suffix = search.toString() ? `?${search.toString()}` : '';
|
||||
return requestJson<EquipmentAcceptanceSendListResponse>(`/api/equipment-acceptance/sends${suffix}`);
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceConfigUser {
|
||||
id: number;
|
||||
username: string;
|
||||
real_name?: string | null;
|
||||
employee_id?: string | null;
|
||||
department?: string | null;
|
||||
wecom_bound?: boolean;
|
||||
}
|
||||
|
||||
export interface EquipmentAcceptanceConfig {
|
||||
days: number[];
|
||||
buyer_manager_user_id?: number | null;
|
||||
coo_user_id?: number | null;
|
||||
executive_user_id?: number | null;
|
||||
selected_users: EquipmentAcceptanceConfigUser[];
|
||||
users: EquipmentAcceptanceConfigUser[];
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取四档天数和三个固定岗位。管理员响应里带候选人。
|
||||
* @returns 当前配置
|
||||
*/
|
||||
export function getEquipmentAcceptanceConfig() {
|
||||
return requestJson<EquipmentAcceptanceConfig>('/api/equipment-acceptance/config');
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存四档天数和三个岗位的系统用户。仅平台管理员。
|
||||
* 核心逻辑:岗位传用户主键或 null,不传姓名。
|
||||
* @param payload.days - 四个逐档增大的天数
|
||||
* @param payload.buyerManagerUserId - 采购经副理
|
||||
* @param payload.cooUserId - COO
|
||||
* @param payload.executiveUserId - 廖总对应岗位
|
||||
* @returns 保存后的配置
|
||||
*/
|
||||
export function saveEquipmentAcceptanceConfig(payload: {
|
||||
days: number[];
|
||||
buyerManagerUserId: number | null;
|
||||
cooUserId: number | null;
|
||||
executiveUserId: number | null;
|
||||
}) {
|
||||
return requestJson<EquipmentAcceptanceConfig>('/api/equipment-acceptance/config', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
days: payload.days,
|
||||
buyer_manager_user_id: payload.buyerManagerUserId,
|
||||
coo_user_id: payload.cooUserId,
|
||||
executive_user_id: payload.executiveUserId,
|
||||
}),
|
||||
});
|
||||
}
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
<!--
|
||||
features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue
|
||||
用途:设备验收预警 Chat 主区:停留列表、详情、发送记录、预警配置,以及管理员同步、扫描和发送。
|
||||
依赖:停留列表、详情、发送记录、配置页、auth.store、equipment-acceptance.api、DeleteConfirmDialog、vue-router query。
|
||||
逻辑:由 ChatViewContent 在 agent_code=equipment_acceptance 时替换消息列表与输入框。
|
||||
view=config 打开预警配置;view=sends 打开发送记录;orderId 只在停留列表下钻。
|
||||
同步只在停留列表。扫描和发送只在发送记录,且仅平台管理员可见。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
scanEquipmentAcceptanceAlerts,
|
||||
sendEquipmentAcceptanceAlerts,
|
||||
syncEquipmentAcceptance,
|
||||
} from '../api/equipment-acceptance.api';
|
||||
import EquipmentAcceptanceConfigPage from '../views/EquipmentAcceptanceConfigPage.vue';
|
||||
import EquipmentAcceptanceDetailPage from '../views/EquipmentAcceptanceDetailPage.vue';
|
||||
import EquipmentAcceptancePage from '../views/EquipmentAcceptancePage.vue';
|
||||
import EquipmentAcceptanceSendsPage from '../views/EquipmentAcceptanceSendsPage.vue';
|
||||
|
||||
type WorkspaceView = 'ledger' | 'sends' | 'config';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const msg = useMessage();
|
||||
const syncing = ref(false);
|
||||
const alertRunning = ref(false);
|
||||
const pendingAlert = ref<'scan' | 'send' | null>(null);
|
||||
const listPage = ref<{ reload: () => Promise<void> } | null>(null);
|
||||
const sendsPage = ref<{ reload: () => Promise<void> } | null>(null);
|
||||
|
||||
const isAdmin = computed(() => Boolean(auth.isAdmin));
|
||||
const activeView = computed<WorkspaceView>(() => {
|
||||
if (route.query.view === 'config') return 'config';
|
||||
if (route.query.view === 'sends') return 'sends';
|
||||
return 'ledger';
|
||||
});
|
||||
const showAlertConfirm = computed({
|
||||
get: () => pendingAlert.value !== null,
|
||||
set: (open: boolean) => {
|
||||
if (!open) pendingAlert.value = null;
|
||||
},
|
||||
});
|
||||
const alertConfirmCopy = computed(() => (
|
||||
pendingAlert.value === 'send'
|
||||
? { title: t('admin.equipmentAcceptance.sendAlerts'), message: t('admin.equipmentAcceptance.sendConfirm') }
|
||||
: { title: t('admin.equipmentAcceptance.scanAlerts'), message: t('admin.equipmentAcceptance.scanConfirm') }
|
||||
));
|
||||
const detailId = computed(() => {
|
||||
if (activeView.value !== 'ledger') return null;
|
||||
const raw = Number(route.query.orderId);
|
||||
return Number.isInteger(raw) && raw > 0 ? raw : null;
|
||||
});
|
||||
const tabs = computed(() => ([
|
||||
{ key: 'ledger' as const, label: t('admin.equipmentAcceptance.tabLedger') },
|
||||
{ key: 'sends' as const, label: t('admin.equipmentAcceptance.tabSends') },
|
||||
{ key: 'config' as const, label: t('admin.equipmentAcceptance.tabConfig') },
|
||||
]));
|
||||
|
||||
/**
|
||||
* 把当前 Tab 和详情写入 Chat 路由。
|
||||
* 核心逻辑:配置和发送记录清掉 orderId。停留列表不写 view,避免旧链接被改掉。
|
||||
* @param view - ledger、sends 或 config
|
||||
* @param orderId - 本地快照主键,空表示列表
|
||||
*/
|
||||
async function syncQuery(view: WorkspaceView, orderId: number | null): Promise<void> {
|
||||
const query = { ...route.query };
|
||||
if (view === 'config' || view === 'sends') {
|
||||
query.view = view;
|
||||
delete query.orderId;
|
||||
} else {
|
||||
delete query.view;
|
||||
if (orderId) query.orderId = String(orderId);
|
||||
else delete query.orderId;
|
||||
}
|
||||
const sameView = String(route.query.view || '') === String(query.view || '');
|
||||
const sameOrder = String(route.query.orderId || '') === String(query.orderId || '');
|
||||
if (sameView && sameOrder) return;
|
||||
await router.replace({ params: { ...route.params }, query });
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换停留列表、发送记录和预警配置。
|
||||
* @param view - 目标 Tab
|
||||
*/
|
||||
function selectView(view: WorkspaceView): void {
|
||||
void syncQuery(view, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员在发送记录页立即扫描或发送。
|
||||
* 核心逻辑:公共确认框点确定后才调用。先取出动作再关掉弹窗,避免关闭时把待执行动作清掉。
|
||||
*/
|
||||
function confirmAlertAction(): void {
|
||||
const action = pendingAlert.value;
|
||||
pendingAlert.value = null;
|
||||
if (action) void runAlertAction(action);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行已经确认的扫描或发送。
|
||||
* 核心逻辑:扫描会同步 E10;发送把待发送记录推到企业微信。
|
||||
* @param action - scan 或 send
|
||||
*/
|
||||
async function runAlertAction(action: 'scan' | 'send'): Promise<void> {
|
||||
if (alertRunning.value) return;
|
||||
alertRunning.value = true;
|
||||
try {
|
||||
if (action === 'scan') {
|
||||
const result = await scanEquipmentAcceptanceAlerts();
|
||||
msg.success(t('admin.equipmentAcceptance.scanDone', {
|
||||
created: result.created,
|
||||
updated: result.updated,
|
||||
cancelled: result.cancelled,
|
||||
}));
|
||||
} else {
|
||||
const result = await sendEquipmentAcceptanceAlerts();
|
||||
msg.success(t('admin.equipmentAcceptance.sendDone', {
|
||||
sent: result.sent,
|
||||
failed: result.failed,
|
||||
}));
|
||||
}
|
||||
await sendsPage.value?.reload();
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
|
||||
} finally {
|
||||
alertRunning.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员从 E10 同步后刷新列表。
|
||||
* 核心逻辑:成功提示写入、跳过和本次未见条数。失败展示业务错误。
|
||||
*/
|
||||
async function runSync(): Promise<void> {
|
||||
if (syncing.value) return;
|
||||
syncing.value = true;
|
||||
try {
|
||||
const result = await syncEquipmentAcceptance();
|
||||
msg.success(t('admin.equipmentAcceptance.syncDone', {
|
||||
upserted: result.upserted,
|
||||
skipped: result.skipped_without_request_id,
|
||||
absent: result.absent,
|
||||
}));
|
||||
await listPage.value?.reload();
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
|
||||
} finally {
|
||||
syncing.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-[var(--surface-muted,#f4f7fb)]">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 px-5 pt-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-lg font-bold text-primary md:text-xl">{{ t('admin.equipmentAcceptance.title') }}</h1>
|
||||
</div>
|
||||
<div v-if="isAdmin && activeView === 'sends'" class="flex flex-wrap items-center gap-2">
|
||||
<button class="btn-secondary-ds" type="button" :disabled="alertRunning" @click="pendingAlert = 'scan'">
|
||||
{{ t('admin.equipmentAcceptance.scanAlerts') }}
|
||||
</button>
|
||||
<button class="btn-secondary-ds" type="button" :disabled="alertRunning" @click="pendingAlert = 'send'">
|
||||
{{ t('admin.equipmentAcceptance.sendAlerts') }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="isAdmin && activeView === 'ledger' && !detailId"
|
||||
class="btn-secondary-ds"
|
||||
type="button"
|
||||
:disabled="syncing"
|
||||
@click="runSync"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" aria-hidden="true" />{{ t('admin.equipmentAcceptance.sync') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-2 flex gap-0 border-b border-default px-5">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
type="button"
|
||||
class="mb-[-1px] border-b-2 px-3 py-2 text-sm font-bold"
|
||||
:class="activeView === tab.key
|
||||
? 'border-brand-500 text-brand-600'
|
||||
: 'border-transparent text-muted hover:text-secondary'"
|
||||
@click="selectView(tab.key)"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</div>
|
||||
<EquipmentAcceptanceDetailPage
|
||||
v-if="detailId"
|
||||
:order-id="detailId"
|
||||
@back="syncQuery('ledger', null)"
|
||||
/>
|
||||
<EquipmentAcceptanceConfigPage
|
||||
v-else-if="activeView === 'config'"
|
||||
:editable="isAdmin"
|
||||
/>
|
||||
<EquipmentAcceptanceSendsPage v-else-if="activeView === 'sends'" ref="sendsPage" />
|
||||
<EquipmentAcceptancePage
|
||||
v-else
|
||||
ref="listPage"
|
||||
@open-detail="syncQuery('ledger', $event)"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-if="isAdmin"
|
||||
v-model="showAlertConfirm"
|
||||
:title="alertConfirmCopy.title"
|
||||
:message="alertConfirmCopy.message"
|
||||
confirm-tone="primary"
|
||||
@confirm="confirmAlertAction"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,272 @@
|
||||
<!--
|
||||
features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue
|
||||
用途:设备验收预警配置页。编辑四档天数,并为三个固定岗位选择系统用户。
|
||||
依赖:equipment-acceptance.api、UserPickerDialog、userPicker.utils、vue-i18n。
|
||||
逻辑:由 Chat 作业面的「预警配置」Tab 嵌入。姓名只用于展示。
|
||||
发送时刻不在本页,由排程 Cron 配置。非管理员只能查看。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import UserPickerDialog from '@/shared/components/UserPickerDialog.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { userPickerLabel } from '@/shared/utils/userPicker.utils';
|
||||
import type { UserPickerPerson } from '@/shared/types/userPicker.types';
|
||||
import {
|
||||
getEquipmentAcceptanceConfig,
|
||||
saveEquipmentAcceptanceConfig,
|
||||
} from '../api/equipment-acceptance.api';
|
||||
|
||||
const props = defineProps<{
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
type RoleKey = 'buyer_manager' | 'coo' | 'executive';
|
||||
|
||||
const ROLE_FIELDS: RoleKey[] = ['buyer_manager', 'coo', 'executive'];
|
||||
const TIER_WHO = ['tierWho1', 'tierWho2', 'tierWho3', 'tierWho4'] as const;
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const days = ref<number[]>([30, 37, 44, 51]);
|
||||
const roleIds = ref<Record<RoleKey, number | null>>({
|
||||
buyer_manager: null,
|
||||
coo: null,
|
||||
executive: null,
|
||||
});
|
||||
const candidates = ref<UserPickerPerson[]>([]);
|
||||
const knownUsers = ref<UserPickerPerson[]>([]);
|
||||
const pickerOpen = ref(false);
|
||||
const pickerRole = ref<RoleKey | null>(null);
|
||||
|
||||
const people = computed(() => {
|
||||
const map = new Map<number, UserPickerPerson>();
|
||||
for (const user of candidates.value) map.set(user.id, user);
|
||||
for (const user of knownUsers.value) map.set(user.id, user);
|
||||
return map;
|
||||
});
|
||||
|
||||
const pickerSelectedIds = computed(() => {
|
||||
const id = pickerRole.value ? roleIds.value[pickerRole.value] : null;
|
||||
return id ? [id] : [];
|
||||
});
|
||||
|
||||
const ruleRows = computed(() => ([
|
||||
{ to: 'ruleTo1', cc: 'ruleCc1' },
|
||||
{ to: 'ruleTo2', cc: 'ruleCc2' },
|
||||
{ to: 'ruleTo3', cc: 'ruleCc3' },
|
||||
{ to: 'ruleTo4', cc: 'ruleCc4' },
|
||||
]));
|
||||
|
||||
/**
|
||||
* 读取当前配置。管理员响应里包含候选人。
|
||||
* 核心逻辑:失败时保留页面上的默认天数,并用统一错误提示。
|
||||
*/
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await getEquipmentAcceptanceConfig();
|
||||
days.value = result.days?.length === 4 ? [...result.days] : [30, 37, 44, 51];
|
||||
roleIds.value = {
|
||||
buyer_manager: result.buyer_manager_user_id ?? null,
|
||||
coo: result.coo_user_id ?? null,
|
||||
executive: result.executive_user_id ?? null,
|
||||
};
|
||||
candidates.value = result.users || [];
|
||||
knownUsers.value = result.selected_users || [];
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.configLoadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开某个岗位的选人弹窗。每个岗位只保留最后选中的一人。
|
||||
* @param role - buyer_manager、coo、executive
|
||||
*/
|
||||
function openPicker(role: RoleKey): void {
|
||||
if (!props.editable) return;
|
||||
pickerRole.value = role;
|
||||
pickerOpen.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把弹窗结果写回当前岗位。选了多人时只留最后一人。
|
||||
* @param ids - 弹窗确定时的用户主键
|
||||
*/
|
||||
function applyPicker(ids: number[]): void {
|
||||
const role = pickerRole.value;
|
||||
if (!role) return;
|
||||
roleIds.value[role] = ids[ids.length - 1] ?? null;
|
||||
pickerRole.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空一个岗位,保存后表示该岗位未配置。
|
||||
* @param role - 岗位键
|
||||
*/
|
||||
function clearRole(role: RoleKey): void {
|
||||
roleIds.value[role] = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存天数和三个岗位。天数须逐档增大。
|
||||
* 核心逻辑:先在页面拦住空值和倒序,服务端再校验用户是否存在。
|
||||
*/
|
||||
async function save(): Promise<void> {
|
||||
if (!props.editable || saving.value) return;
|
||||
const nextDays = days.value.map((day) => Number(day));
|
||||
const [first, second, third, fourth] = nextDays;
|
||||
const increases = first !== undefined && second !== undefined && third !== undefined && fourth !== undefined
|
||||
&& first < second && second < third && third < fourth;
|
||||
if (nextDays.some((day) => !Number.isInteger(day) || day < 1) || !increases) {
|
||||
msg.error(t('admin.equipmentAcceptance.configDaysInvalid'));
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const result = await saveEquipmentAcceptanceConfig({
|
||||
days: nextDays,
|
||||
buyerManagerUserId: roleIds.value.buyer_manager,
|
||||
cooUserId: roleIds.value.coo,
|
||||
executiveUserId: roleIds.value.executive,
|
||||
});
|
||||
days.value = [...result.days];
|
||||
knownUsers.value = result.selected_users || [];
|
||||
candidates.value = result.users || [];
|
||||
msg.success(t('admin.equipmentAcceptance.configSaved'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.configSaveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 岗位上已选用户的展示名。没有选择时返回空串,模板改显示未选择。
|
||||
* @param role - 岗位键
|
||||
* @returns 姓名,有工号时附在后面
|
||||
*/
|
||||
function roleLabel(role: RoleKey): string {
|
||||
const id = roleIds.value[role];
|
||||
if (!id) return '';
|
||||
return userPickerLabel(people.value.get(id), id);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="min-h-0 flex-1 overflow-auto px-5 pb-6 pt-3">
|
||||
<p class="mb-3 text-sm text-[#64748b]">{{ t('admin.equipmentAcceptance.configLead') }}</p>
|
||||
<p v-if="loading" class="text-sm text-[#64748b]">{{ t('admin.equipmentAcceptance.loading') }}</p>
|
||||
<template v-else>
|
||||
<div class="grid grid-cols-4 gap-3">
|
||||
<label
|
||||
v-for="(who, index) in TIER_WHO"
|
||||
:key="who"
|
||||
class="rounded-xl border border-[#dce4ef] border-t-[3px] bg-white px-3 py-3"
|
||||
:class="index === 0 ? 'border-t-[#93c5fd]' : index === 1 ? 'border-t-[#2563eb]' : index === 2 ? 'border-t-[#d97706]' : 'border-t-[#dc2626]'"
|
||||
>
|
||||
<span class="block text-xs font-bold text-[#64748b]">{{ t(`admin.equipmentAcceptance.tier${index + 1}`) }}</span>
|
||||
<span class="mt-2 flex items-center gap-2">
|
||||
<input
|
||||
v-model.number="days[index]"
|
||||
class="h-11 w-16 rounded-lg border border-[#d7dee8] bg-[#f8fafc] text-center text-xl font-bold text-[#142033] disabled:opacity-70"
|
||||
type="number"
|
||||
min="1"
|
||||
:disabled="!editable"
|
||||
/>
|
||||
<span class="text-sm font-semibold text-[#94a3b8]">{{ t('admin.equipmentAcceptance.dayUnit') }}</span>
|
||||
</span>
|
||||
<span class="mt-2 block text-xs font-bold text-[#334155]">{{ t(`admin.equipmentAcceptance.${who}`) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 grid gap-3 lg:grid-cols-2">
|
||||
<article class="rounded-xl border border-[#dce4ef] bg-white">
|
||||
<h2 class="px-4 pt-4 text-sm font-bold text-[#142033]">{{ t('admin.equipmentAcceptance.fixedRoles') }}</h2>
|
||||
<div class="px-4 pb-2">
|
||||
<div
|
||||
v-for="role in ROLE_FIELDS"
|
||||
:key="role"
|
||||
class="grid grid-cols-[108px_minmax(0,1fr)] items-center gap-3 border-b border-[#dce4ef] py-3 last:border-b-0"
|
||||
>
|
||||
<span class="text-sm font-bold text-[#334155]">{{ t(`admin.equipmentAcceptance.role.${role}`) }}</span>
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<span v-if="roleLabel(role)" class="truncate text-sm text-[#142033]">{{ roleLabel(role) }}</span>
|
||||
<span v-else class="text-sm text-[#94a3b8]">{{ t('admin.equipmentAcceptance.roleEmpty') }}</span>
|
||||
<button
|
||||
v-if="editable"
|
||||
class="ml-auto rounded-lg border border-[#bfdbfe] bg-[#eaf2ff] px-2.5 py-1 text-xs font-bold text-[#1d4ed8]"
|
||||
type="button"
|
||||
@click="openPicker(role)"
|
||||
>
|
||||
{{ t('admin.equipmentAcceptance.selectUser') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="editable && roleIds[role]"
|
||||
class="text-xs font-bold text-[#64748b]"
|
||||
type="button"
|
||||
@click="clearRole(role)"
|
||||
>
|
||||
{{ t('admin.equipmentAcceptance.clearUser') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-3 border-t border-[#dce4ef] bg-[#fafbfd] px-4 py-3">
|
||||
<span class="text-xs text-[#64748b]">{{ editable ? t('admin.equipmentAcceptance.configSaveHint') : t('admin.equipmentAcceptance.configReadOnly') }}</span>
|
||||
<button
|
||||
v-if="editable"
|
||||
class="rounded-lg bg-[#2563eb] px-3 py-1.5 text-xs font-bold text-white disabled:opacity-50"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ t('admin.equipmentAcceptance.saveConfig') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article class="overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
|
||||
<div class="px-4 pt-4">
|
||||
<h2 class="text-sm font-bold text-[#142033]">{{ t('admin.equipmentAcceptance.rulesTitle') }}</h2>
|
||||
<p class="mt-1 text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.rulesLead') }}</p>
|
||||
</div>
|
||||
<table class="mt-3 w-full border-collapse text-left text-xs">
|
||||
<thead class="bg-[#f8fbff] text-[#64748b]">
|
||||
<tr>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleTier') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleTo') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleCc') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, index) in ruleRows" :key="row.to" class="border-t border-[#dce4ef]">
|
||||
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ t('admin.equipmentAcceptance.ruleOver', { days: days[index] || '—' }) }}</td>
|
||||
<td class="px-3 py-2.5">{{ t(`admin.equipmentAcceptance.${row.to}`) }}</td>
|
||||
<td class="px-3 py-2.5">{{ t(`admin.equipmentAcceptance.${row.cc}`) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<UserPickerDialog
|
||||
v-model="pickerOpen"
|
||||
:users="candidates"
|
||||
:selected-ids="pickerSelectedIds"
|
||||
:title="t('admin.equipmentAcceptance.selectUser')"
|
||||
:subtitle="t('admin.equipmentAcceptance.configPickOne')"
|
||||
@confirm="applyPicker"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,314 @@
|
||||
<!--
|
||||
features/equipment-acceptance/views/EquipmentAcceptanceDetailPage.vue
|
||||
用途:一张验收单的详情卡片,展示状态徽章、停留进度、当前节点和操作人。
|
||||
依赖:equipment-acceptance.api、vue-i18n、统一消息提示。
|
||||
逻辑:由 Chat 作业面在选中某行后展示。操作人只显示姓名和工号。
|
||||
进度条只按签核天数画到 30/37/44/51,不表示已经发送。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getEquipmentAcceptanceOrder,
|
||||
type EquipmentAcceptanceOrder,
|
||||
} from '../api/equipment-acceptance.api';
|
||||
|
||||
const props = defineProps<{
|
||||
orderId: number;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: [];
|
||||
}>();
|
||||
|
||||
type BadgeTone = 'red' | 'green' | 'gray';
|
||||
|
||||
const STOPPED_STATUSES = new Set([
|
||||
'stopped_returned',
|
||||
'stopped_cannot_accept',
|
||||
'stopped_archived',
|
||||
'stopped_force_finished',
|
||||
'stopped_voided',
|
||||
'stopped_revoked',
|
||||
]);
|
||||
|
||||
const FLOW_STATUS_KEYS: Record<number, string> = {
|
||||
0: 'draft',
|
||||
1: 'approving',
|
||||
3: 'archived',
|
||||
4: 'forceFinished',
|
||||
5: 'voided',
|
||||
6: 'pendingSubmit',
|
||||
7: 'withdrawn',
|
||||
8: 'withdrawn',
|
||||
99: 'withdrawn',
|
||||
[-99]: 'withdrawn',
|
||||
};
|
||||
|
||||
const REMINDER_DAYS = [30, 37, 44, 51];
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const loading = ref(false);
|
||||
const order = ref<EquipmentAcceptanceOrder | null>(null);
|
||||
|
||||
/**
|
||||
* 读取当前验收单详情。
|
||||
* 核心逻辑:orderId 变化时重新请求。失败清空详情,避免上一张单残留。
|
||||
*/
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
order.value = await getEquipmentAcceptanceOrder(props.orderId);
|
||||
} catch (error) {
|
||||
order.value = null;
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.detailLoadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只取日期部分。没有值时显示横线。
|
||||
* @param value - 接口时间字符串
|
||||
* @returns 日期文本
|
||||
*/
|
||||
function dateText(value?: string | null): string {
|
||||
if (!value) return '—';
|
||||
return value.slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 0/1 写成否/是。可以验收为空时显示未标明,退回在同步时已把空收成否。
|
||||
* @param value - 标准 0 否、1 是
|
||||
* @param emptyLabel - 空值文案
|
||||
* @returns 展示文案
|
||||
*/
|
||||
function yesNo(value: number | null | undefined, emptyLabel: string): string {
|
||||
if (value === 1) return t('common.yes');
|
||||
if (value === 0) return t('common.no');
|
||||
return emptyLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把流程状态原值写成名称。7、8、99、-99 都显示为撤销,字典没有的数字仍显示原值。
|
||||
* @param value - flowstatus
|
||||
* @returns 流程状态文案
|
||||
*/
|
||||
function flowText(value?: number | null): string {
|
||||
if (value === undefined || value === null) return '—';
|
||||
const key = FLOW_STATUS_KEYS[value];
|
||||
return key ? t(`admin.equipmentAcceptance.flowStatusName.${key}`) : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未开始或没有天数时显示横线,其余显示「N 天」。
|
||||
* @param item - 当前验收单
|
||||
* @returns 签核天数文案
|
||||
*/
|
||||
function dwellText(item: EquipmentAcceptanceOrder): string {
|
||||
if (item.monitor_status === 'not_started' || item.dwell_days == null) return '—';
|
||||
return t('admin.equipmentAcceptance.daysValue', { days: item.dwell_days });
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前节点名称。没有节点时为空,模板改显示横线。
|
||||
* @param item - 当前验收单
|
||||
* @returns 节点名称列表
|
||||
*/
|
||||
function nodeNames(item: EquipmentAcceptanceOrder): string[] {
|
||||
return (item.nodes || []).map((node) => node.node_name).filter((name): name is string => Boolean(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前处理人去重后拼成一行。
|
||||
* @param item - 当前验收单
|
||||
* @returns 处理人姓名
|
||||
*/
|
||||
function handlerNames(item: EquipmentAcceptanceOrder): string {
|
||||
const names = Array.from(new Set(
|
||||
(item.operators || []).map((person) => person.handler_name).filter((name): name is string => Boolean(name)),
|
||||
));
|
||||
return names.length ? names.join('、') : '—';
|
||||
}
|
||||
|
||||
/**
|
||||
* 与列表相同的徽章颜色。红是已逾期,绿是不再提醒,灰是未开始和未超时。
|
||||
* @param item - 当前验收单
|
||||
* @returns 文案和颜色
|
||||
*/
|
||||
function statusBadge(item: EquipmentAcceptanceOrder): { label: string; tone: BadgeTone } {
|
||||
if (item.monitor_status === 'watching' && item.overdue) {
|
||||
return { label: t('admin.equipmentAcceptance.badgeOverdue'), tone: 'red' };
|
||||
}
|
||||
if (item.monitor_status === 'watching') {
|
||||
return { label: t('admin.equipmentAcceptance.badgeOnTime'), tone: 'gray' };
|
||||
}
|
||||
return {
|
||||
label: t(`admin.equipmentAcceptance.statusLabel.${item.monitor_status}`),
|
||||
tone: STOPPED_STATUSES.has(item.monitor_status) ? 'green' : 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 徽章底色。
|
||||
* @param tone - 徽章颜色
|
||||
* @returns Tailwind 类名
|
||||
*/
|
||||
function badgeClass(tone: BadgeTone): string {
|
||||
if (tone === 'red') return 'bg-[#fff0ef] text-[#b42318]';
|
||||
if (tone === 'green') return 'bg-[#eafaf1] text-[#067647]';
|
||||
return 'bg-[#edf1f6] text-[#475569]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按签核天数在 0 到第 4 档之间画进度。没有天数时不画。
|
||||
* 核心逻辑:刻度至少到 60 天,避免 51 天贴在条的尽头。
|
||||
*/
|
||||
const track = computed(() => {
|
||||
const days = order.value?.dwell_days;
|
||||
if (order.value?.monitor_status === 'not_started' || days == null) return null;
|
||||
const lastMark = REMINDER_DAYS[REMINDER_DAYS.length - 1] ?? 51;
|
||||
const scale = Math.max(60, lastMark + 9, days);
|
||||
return {
|
||||
width: `${Math.min(100, Math.round((days / scale) * 100))}%`,
|
||||
marks: [0, ...REMINDER_DAYS, scale].map((day) => ({
|
||||
day,
|
||||
left: `${(day / scale) * 100}%`,
|
||||
label: day === scale ? t('admin.equipmentAcceptance.daysValue', { days: scale }) : String(day),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
|
||||
watch(() => props.orderId, () => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="min-h-0 flex-1 overflow-auto px-5 pb-6 pt-3">
|
||||
<button
|
||||
class="mb-3 rounded-lg border border-[#dce4ef] bg-white px-3 py-1.5 text-xs font-bold text-[#142033]"
|
||||
type="button"
|
||||
@click="emit('back')"
|
||||
>
|
||||
{{ t('admin.equipmentAcceptance.back') }}
|
||||
</button>
|
||||
<p v-if="loading && !order" class="text-sm text-[#64748b]">{{ t('admin.equipmentAcceptance.loading') }}</p>
|
||||
<article v-else-if="order" class="overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
|
||||
<div class="flex items-start justify-between gap-3 px-4 pt-4">
|
||||
<h2 class="text-lg font-bold text-[#142033]">{{ order.acceptance_no || '—' }}</h2>
|
||||
<span
|
||||
class="inline-flex shrink-0 rounded-full px-2 py-0.5 text-[11px] font-extrabold"
|
||||
:class="badgeClass(statusBadge(order).tone)"
|
||||
>
|
||||
{{ statusBadge(order).label }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="track" class="px-7 pt-5">
|
||||
<div class="h-2 overflow-hidden rounded-full bg-[#e7edf5]">
|
||||
<i class="block h-full rounded-full bg-gradient-to-r from-[#93c5fd] to-[#2563eb]" :style="{ width: track.width }"></i>
|
||||
</div>
|
||||
<div class="relative mt-1 h-4 text-[11px] text-[#64748b]">
|
||||
<span
|
||||
v-for="mark in track.marks"
|
||||
:key="mark.day"
|
||||
class="absolute -translate-x-1/2 whitespace-nowrap"
|
||||
:style="{ left: mark.left }"
|
||||
>
|
||||
{{ mark.label }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-1.5 px-4 pb-1 pt-4">
|
||||
<span
|
||||
v-for="(name, index) in nodeNames(order)"
|
||||
:key="`${name}-${index}`"
|
||||
class="rounded-full bg-[#dbeafe] px-2 py-1 text-[11px] font-extrabold text-[#1d4ed8]"
|
||||
>
|
||||
{{ name }}
|
||||
</span>
|
||||
<span v-if="!nodeNames(order).length" class="text-sm text-[#64748b]">—</span>
|
||||
</div>
|
||||
|
||||
<dl class="mt-3 grid border-t border-[#dce4ef] px-4 sm:grid-cols-2">
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.purchaseOrderNo') }}</dt>
|
||||
<dd class="text-[#142033]">{{ order.purchase_order_no || '—' }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.applicant') }}</dt>
|
||||
<dd class="text-[#142033]">{{ order.applicant_name || '—' }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.dwellDays') }}</dt>
|
||||
<dd class="text-[#142033]">{{ dwellText(order) }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.timerStart') }}</dt>
|
||||
<dd class="text-[#142033]">{{ dateText(order.timer_started_at) }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:col-span-2">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.currentHandlers') }}</dt>
|
||||
<dd class="text-[#142033]">{{ handlerNames(order) }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.canAccept') }}</dt>
|
||||
<dd class="text-[#142033]">{{ yesNo(order.can_accept, t('admin.equipmentAcceptance.unspecified')) }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:col-span-2">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.cannotAcceptNote') }}</dt>
|
||||
<dd class="whitespace-pre-wrap text-[#142033]">{{ order.cannot_accept_note || '—' }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.returnFlag') }}</dt>
|
||||
<dd class="text-[#142033]">{{ yesNo(order.is_returned, t('common.no')) }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.flowStatus') }}</dt>
|
||||
<dd class="text-[#142033]">{{ flowText(order.flow_status_raw) }}</dd>
|
||||
</div>
|
||||
<div class="grid grid-cols-[108px_minmax(0,1fr)] gap-2 border-b border-[#dce4ef] py-2.5 text-xs sm:pl-4">
|
||||
<dt class="font-bold text-[#64748b]">{{ t('admin.equipmentAcceptance.finishedAt') }}</dt>
|
||||
<dd class="text-[#142033]">{{ dateText(order.finished_at) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div class="px-4 pb-4 pt-4">
|
||||
<h3 class="text-sm font-bold text-[#142033]">{{ t('admin.equipmentAcceptance.operators') }}</h3>
|
||||
<p class="mt-1 text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.operatorsNote') }}</p>
|
||||
<div class="mt-3 overflow-auto rounded-xl border border-[#dce4ef]">
|
||||
<table class="w-full min-w-[640px] border-collapse text-left text-xs">
|
||||
<thead class="bg-[#f8fbff] text-[#64748b]">
|
||||
<tr>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.operatorName') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.jobNum') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(item, index) in order.operators"
|
||||
:key="`${item.user_id}-${item.node_id}-${index}`"
|
||||
class="border-t border-[#dce4ef]"
|
||||
>
|
||||
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ item.handler_name || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ item.handler_job_num || '—' }}</td>
|
||||
</tr>
|
||||
<tr v-if="!order.operators.length">
|
||||
<td colspan="2" class="px-3 py-6 text-center text-[#64748b]">—</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,264 @@
|
||||
<!--
|
||||
features/equipment-acceptance/views/EquipmentAcceptancePage.vue
|
||||
用途:设备验收预警停留列表,对齐原型的汇总卡、分组筛选和状态徽章。
|
||||
依赖:equipment-acceptance.api、PaginationBar、统一消息提示、vue-i18n。
|
||||
逻辑:由 Chat 作业面嵌入。点「查看详情」交给父级下钻。
|
||||
已逾期只看接口给出的 overdue。发送结果在「发送记录」页,这里不显示第几档。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
listEquipmentAcceptanceOrders,
|
||||
type EquipmentAcceptanceOrder,
|
||||
type EquipmentAcceptanceSummary,
|
||||
} from '../api/equipment-acceptance.api';
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-detail': [orderId: number];
|
||||
}>();
|
||||
|
||||
type FocusKey = 'all' | 'watching' | 'overdue' | 'stopped' | 'not_started';
|
||||
type BadgeTone = 'red' | 'green' | 'gray';
|
||||
|
||||
const STOPPED_STATUSES = new Set([
|
||||
'stopped_returned',
|
||||
'stopped_cannot_accept',
|
||||
'stopped_archived',
|
||||
'stopped_force_finished',
|
||||
'stopped_voided',
|
||||
'stopped_revoked',
|
||||
]);
|
||||
|
||||
const filters: Array<{ key: FocusKey; label: string }> = [
|
||||
{ key: 'all', label: 'filterAll' },
|
||||
{ key: 'watching', label: 'filterWatching' },
|
||||
{ key: 'overdue', label: 'filterOverdue' },
|
||||
{ key: 'stopped', label: 'filterStopped' },
|
||||
{ key: 'not_started', label: 'filterNotStarted' },
|
||||
];
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const loading = ref(false);
|
||||
const orders = ref<EquipmentAcceptanceOrder[]>([]);
|
||||
const focus = ref<FocusKey>('all');
|
||||
const page = ref(1);
|
||||
const pageSize = ref(20);
|
||||
const total = ref(0);
|
||||
const pages = ref(1);
|
||||
const summary = ref<EquipmentAcceptanceSummary>({
|
||||
watching: 0,
|
||||
overdue: 0,
|
||||
stopped: 0,
|
||||
not_started: 0,
|
||||
});
|
||||
|
||||
/**
|
||||
* 加载当前分组的验收单,并刷新全部单据的汇总数字。
|
||||
* 核心逻辑:汇总不受当前筛选影响,由接口的 summary 给出。
|
||||
* @param resetPage - 为 true 时回到第一页,用于更换筛选。
|
||||
*/
|
||||
async function load(resetPage = false): Promise<void> {
|
||||
if (resetPage) page.value = 1;
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await listEquipmentAcceptanceOrders({
|
||||
focus: focus.value,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
});
|
||||
orders.value = result.items || [];
|
||||
total.value = result.total || 0;
|
||||
pages.value = result.pages || 1;
|
||||
if (result.summary) summary.value = result.summary;
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换原型分组并回到第一页。
|
||||
* @param next - all、watching、overdue、stopped、not_started
|
||||
*/
|
||||
function selectFocus(next: FocusKey): void {
|
||||
if (focus.value === next) return;
|
||||
focus.value = next;
|
||||
void load(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把节点名称拼成一格。没有节点时显示横线。
|
||||
* @param order - 列表行
|
||||
* @returns 节点名称
|
||||
*/
|
||||
function nodeNames(order: EquipmentAcceptanceOrder): string {
|
||||
const names = (order.nodes || []).map((node) => node.node_name).filter((name): name is string => Boolean(name));
|
||||
return names.length ? names.join('、') : '—';
|
||||
}
|
||||
|
||||
/**
|
||||
* 把当前处理人姓名去重后拼成一格。这些人不一定是未办。
|
||||
* @param order - 列表行
|
||||
* @returns 处理人姓名
|
||||
*/
|
||||
function handlerNames(order: EquipmentAcceptanceOrder): string {
|
||||
const names = Array.from(new Set(
|
||||
(order.operators || []).map((item) => item.handler_name).filter((name): name is string => Boolean(name)),
|
||||
));
|
||||
return names.length ? names.join('、') : '—';
|
||||
}
|
||||
|
||||
/**
|
||||
* 只取日期部分展示计时起点。
|
||||
* @param value - 接口返回的时间字符串
|
||||
* @returns 日期或横线
|
||||
*/
|
||||
function dateText(value?: string | null): string {
|
||||
if (!value) return '—';
|
||||
return value.slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未开始或没有天数时显示横线,其余显示「N 天」。
|
||||
* @param order - 列表行
|
||||
* @returns 签核天数文案
|
||||
*/
|
||||
function dwellText(order: EquipmentAcceptanceOrder): string {
|
||||
if (order.monitor_status === 'not_started' || order.dwell_days == null) return '—';
|
||||
return t('admin.equipmentAcceptance.daysValue', { days: order.dwell_days });
|
||||
}
|
||||
|
||||
/**
|
||||
* 按监控状态收成徽章。已逾期用红色,表示还要提醒。不再提醒用绿色,未开始和未超时用灰色。
|
||||
* @param order - 列表行
|
||||
* @returns 文案和颜色
|
||||
*/
|
||||
function statusBadge(order: EquipmentAcceptanceOrder): { label: string; tone: BadgeTone } {
|
||||
if (order.monitor_status === 'watching' && order.overdue) {
|
||||
return { label: t('admin.equipmentAcceptance.badgeOverdue'), tone: 'red' };
|
||||
}
|
||||
if (order.monitor_status === 'watching') {
|
||||
return { label: t('admin.equipmentAcceptance.badgeOnTime'), tone: 'gray' };
|
||||
}
|
||||
return {
|
||||
label: t(`admin.equipmentAcceptance.statusLabel.${order.monitor_status}`),
|
||||
tone: STOPPED_STATUSES.has(order.monitor_status) ? 'green' : 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 徽章底色。红是已逾期,绿是不再提醒,灰是未超时、未开始和不在监控范围。
|
||||
* @param tone - 徽章颜色
|
||||
* @returns Tailwind 类名
|
||||
*/
|
||||
function badgeClass(tone: BadgeTone): string {
|
||||
if (tone === 'red') return 'bg-[#fff0ef] text-[#b42318]';
|
||||
if (tone === 'green') return 'bg-[#eafaf1] text-[#067647]';
|
||||
return 'bg-[#edf1f6] text-[#475569]';
|
||||
}
|
||||
|
||||
defineExpose({ reload: () => load(false) });
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex min-h-0 flex-1 flex-col gap-3 px-5 pb-4 pt-3">
|
||||
<div class="grid grid-cols-4 gap-3">
|
||||
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
|
||||
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.watching }}</b>
|
||||
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.kpiWatching') }}</span>
|
||||
</article>
|
||||
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
|
||||
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.overdue }}</b>
|
||||
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.kpiOverdue') }}</span>
|
||||
</article>
|
||||
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
|
||||
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.stopped }}</b>
|
||||
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.kpiStopped') }}</span>
|
||||
</article>
|
||||
<article class="rounded-xl border border-[#dce4ef] bg-white px-4 py-3.5">
|
||||
<b class="block text-[26px] font-bold leading-none text-[#142033]">{{ summary.not_started }}</b>
|
||||
<span class="mt-1 block text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.filterNotStarted') }}</span>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
|
||||
<div class="flex flex-wrap gap-2 p-3">
|
||||
<button
|
||||
v-for="item in filters"
|
||||
:key="item.key"
|
||||
type="button"
|
||||
class="rounded-full border px-2.5 py-1 text-xs font-bold"
|
||||
:class="focus === item.key
|
||||
? 'border-[#bfdbfe] bg-[#eaf2ff] text-[#1d4ed8]'
|
||||
: 'border-[#dce4ef] bg-white text-[#475569]'"
|
||||
@click="selectFocus(item.key)"
|
||||
>
|
||||
{{ t(`admin.equipmentAcceptance.${item.label}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-auto">
|
||||
<table class="min-w-[960px] w-full border-collapse text-left text-xs">
|
||||
<thead class="sticky top-0 bg-[#f8fbff] text-[#64748b]">
|
||||
<tr>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.acceptanceNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.purchaseOrderNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.applicant') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.currentNodes') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.currentHandlers') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.timerStart') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.dwellDays') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.status') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in orders" :key="item.id" class="border-b border-[#dce4ef] hover:bg-[#f3f7ff]">
|
||||
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ item.acceptance_no || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ item.purchase_order_no || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ item.applicant_name || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ nodeNames(item) }}</td>
|
||||
<td class="px-3 py-2.5">{{ handlerNames(item) }}</td>
|
||||
<td class="px-3 py-2.5">{{ dateText(item.timer_started_at) }}</td>
|
||||
<td class="px-3 py-2.5">{{ dwellText(item) }}</td>
|
||||
<td class="px-3 py-2.5">
|
||||
<span
|
||||
class="inline-flex rounded-full px-2 py-0.5 text-[11px] font-extrabold"
|
||||
:class="badgeClass(statusBadge(item).tone)"
|
||||
>
|
||||
{{ statusBadge(item).label }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-3 py-2.5">
|
||||
<button class="font-extrabold text-[#175cd3]" type="button" @click="emit('open-detail', item.id)">
|
||||
{{ t('admin.equipmentAcceptance.detail') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && !orders.length">
|
||||
<td colspan="9" class="px-3 py-9 text-center text-[#64748b]">{{ t('admin.equipmentAcceptance.empty') }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<PaginationBar
|
||||
class="shrink-0"
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
:pages="pages"
|
||||
@update:page="() => load()"
|
||||
@update:page-size="() => load()"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,137 @@
|
||||
<!--
|
||||
features/equipment-acceptance/views/EquipmentAcceptanceSendsPage.vue
|
||||
用途:设备验收预警发送记录页,列出每张验收单某一档的主送、抄送和结果。
|
||||
依赖:equipment-acceptance.api、PaginationBar、统一消息提示、vue-i18n。
|
||||
逻辑:由 Chat 作业面的「发送记录」Tab 嵌入。只读已落库记录。扫描尚未写入时显示空状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import {
|
||||
listEquipmentAcceptanceSends,
|
||||
type EquipmentAcceptanceSendRecord,
|
||||
} from '../api/equipment-acceptance.api';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const records = ref<EquipmentAcceptanceSendRecord[]>([]);
|
||||
const loading = ref(false);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(20);
|
||||
const total = ref(0);
|
||||
const pages = ref(1);
|
||||
|
||||
/**
|
||||
* 拉取当前页发送记录。
|
||||
* 核心逻辑:失败时清空表格并提示。空列表留给模板显示「还没有发送记录」。
|
||||
*/
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await listEquipmentAcceptanceSends({ page: page.value, pageSize: pageSize.value });
|
||||
records.value = result.items || [];
|
||||
total.value = result.total || 0;
|
||||
pages.value = Math.max(1, Math.ceil(total.value / pageSize.value));
|
||||
} catch (error) {
|
||||
records.value = [];
|
||||
total.value = 0;
|
||||
pages.value = 1;
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.sendsFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮次列写成「超过 N 天」。
|
||||
* @param item - 一条发送记录
|
||||
* @returns 轮次文案
|
||||
*/
|
||||
function tierText(item: EquipmentAcceptanceSendRecord): string {
|
||||
return t('admin.equipmentAcceptance.ruleOver', { days: item.threshold_days });
|
||||
}
|
||||
|
||||
/**
|
||||
* 结果用已知状态文案。未知状态保留原值。
|
||||
* @param status - pending、sent、failed、cancelled
|
||||
* @returns 结果文案
|
||||
*/
|
||||
function statusText(status: string): string {
|
||||
const key = `admin.equipmentAcceptance.sendStatus.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已发送显示本地时间,待发送没有时间时显示横线。
|
||||
* @param value - 接口返回的发送时间
|
||||
* @returns 时间或横线
|
||||
*/
|
||||
function sentText(value?: string | null): string {
|
||||
if (!value) return '—';
|
||||
const text = formatLocalDateTime(value);
|
||||
return text === '-' ? '—' : text;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
|
||||
defineExpose({ reload: load });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex min-h-0 flex-1 flex-col gap-3 px-5 pb-4 pt-3">
|
||||
<p class="text-xs text-[#64748b]">{{ t('admin.equipmentAcceptance.sendsLead') }}</p>
|
||||
<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-[#dce4ef] bg-white">
|
||||
<div class="min-h-0 flex-1 overflow-auto">
|
||||
<table class="min-w-[960px] w-full border-collapse text-left text-xs">
|
||||
<thead class="sticky top-0 bg-[#f8fbff] text-[#64748b]">
|
||||
<tr>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.acceptanceNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.purchaseOrderNo') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleTier') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleTo') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.ruleCc') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.sendResult') }}</th>
|
||||
<th class="px-3 py-2.5 font-bold">{{ t('admin.equipmentAcceptance.sentAt') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in records" :key="item.id" class="border-b border-[#dce4ef]">
|
||||
<td class="px-3 py-2.5 font-bold text-[#142033]">{{ item.acceptance_no || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ item.purchase_order_no || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ tierText(item) }}</td>
|
||||
<td class="px-3 py-2.5">{{ item.to_text || '—' }}</td>
|
||||
<td class="px-3 py-2.5">{{ item.cc_text || '—' }}</td>
|
||||
<td class="px-3 py-2.5">
|
||||
{{ statusText(item.status) }}
|
||||
<span v-if="item.error_message" class="mt-1 block text-[#b42318]">
|
||||
{{ item.error_message }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-3 py-2.5">{{ sentText(item.sent_at) }}</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && !records.length">
|
||||
<td colspan="7" class="px-3 py-10 text-center text-[#64748b]">
|
||||
{{ t('admin.equipmentAcceptance.sendsEmpty') }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<PaginationBar
|
||||
class="shrink-0"
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
:pages="pages"
|
||||
@update:page="() => load()"
|
||||
@update:page-size="() => load()"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -5731,5 +5731,131 @@
|
||||
"prevPage": "Previous page",
|
||||
"nextPage": "Next page"
|
||||
}
|
||||
},
|
||||
"equipmentAcceptance": {
|
||||
"title": "Equipment acceptance warning",
|
||||
"sync": "Sync OA data",
|
||||
"syncDone": "Synced {upserted}, skipped {skipped}, missing this time {absent}",
|
||||
"syncFailed": "Failed to sync equipment acceptance data",
|
||||
"tabLedger": "Waiting orders",
|
||||
"tabSends": "Send records",
|
||||
"tabConfig": "Alert settings",
|
||||
"sendsLead": "The daily scan creates records waiting to be sent. They appear here after the Friday 18:00 summary goes out to each recipient. Names stay as they were at send time.",
|
||||
"sendsEmpty": "No send records yet",
|
||||
"sendsFailed": "Failed to load send records",
|
||||
"scanAlerts": "Scan alerts",
|
||||
"sendAlerts": "Send alerts",
|
||||
"scanConfirm": "This syncs from E10 and creates records waiting to be sent.",
|
||||
"sendConfirm": "This sends the waiting records to WeCom, one message per recipient.",
|
||||
"scanDone": "Added {created}, updated {updated}, cancelled {cancelled}",
|
||||
"sendDone": "Sent to {sent} people, {failed} failed",
|
||||
"sendResult": "Result",
|
||||
"sentAt": "Sent at",
|
||||
"sendStatus": {
|
||||
"pending": "Waiting to send",
|
||||
"sent": "Sent",
|
||||
"failed": "Failed",
|
||||
"cancelled": "Cancelled"
|
||||
},
|
||||
"configLead": "Each tier must be longer than the one before it. Saving affects only alerts created later. The send time is set on the schedule.",
|
||||
"tier1": "Tier 1",
|
||||
"tier2": "Tier 2",
|
||||
"tier3": "Tier 3",
|
||||
"tier4": "Tier 4",
|
||||
"tierWho1": "Current handler",
|
||||
"tierWho2": "Deputy manager",
|
||||
"tierWho3": "COO",
|
||||
"tierWho4": "General manager",
|
||||
"dayUnit": "days",
|
||||
"fixedRoles": "Fixed roles",
|
||||
"role": {
|
||||
"buyer_manager": "Procurement deputy manager",
|
||||
"coo": "COO",
|
||||
"executive": "General manager"
|
||||
},
|
||||
"roleEmpty": "Not selected",
|
||||
"selectUser": "Select",
|
||||
"clearUser": "Clear",
|
||||
"configPickOne": "Each role keeps one person. The name is for display; the saved value is the system user.",
|
||||
"rulesTitle": "Recipient rules",
|
||||
"rulesLead": "Who receives each tier stays fixed. Only the day thresholds change.",
|
||||
"ruleTier": "Round",
|
||||
"ruleTo": "To",
|
||||
"ruleCc": "Cc",
|
||||
"ruleOver": "Over {days} days",
|
||||
"ruleTo1": "Current handler",
|
||||
"ruleCc1": "Their supervisor and the applicant",
|
||||
"ruleTo2": "The handler's deputy manager",
|
||||
"ruleCc2": "COO and procurement deputy manager",
|
||||
"ruleTo3": "COO",
|
||||
"ruleCc3": "Procurement deputy manager",
|
||||
"ruleTo4": "General manager",
|
||||
"ruleCc4": "COO and procurement deputy manager",
|
||||
"saveConfig": "Save settings",
|
||||
"configSaveHint": "Sent alerts stay unchanged",
|
||||
"configSaved": "Alert settings saved",
|
||||
"configLoadFailed": "Failed to load alert settings",
|
||||
"configSaveFailed": "Failed to save alert settings",
|
||||
"configDaysInvalid": "Each tier must be longer than the previous one",
|
||||
"configReadOnly": "Only an administrator can change these settings",
|
||||
"loadFailed": "Failed to load acceptance orders",
|
||||
"detailLoadFailed": "Failed to load the acceptance order",
|
||||
"loading": "Loading",
|
||||
"empty": "No acceptance orders have been synced yet",
|
||||
"kpiWatching": "In progress",
|
||||
"kpiOverdue": "Overdue",
|
||||
"kpiStopped": "No further reminders",
|
||||
"filterAll": "All",
|
||||
"filterWatching": "In progress",
|
||||
"filterOverdue": "Overdue",
|
||||
"filterStopped": "No further reminders",
|
||||
"filterNotStarted": "Not started",
|
||||
"badgeOverdue": "Overdue",
|
||||
"badgeOnTime": "Not yet due",
|
||||
"currentHandlers": "Current handlers",
|
||||
"daysValue": "{days} days",
|
||||
"statusAll": "All statuses",
|
||||
"status": "Status",
|
||||
"acceptanceNo": "Acceptance no.",
|
||||
"purchaseOrderNo": "Purchase order no.",
|
||||
"applicant": "Applicant",
|
||||
"currentNodes": "Current nodes",
|
||||
"operators": "Operators",
|
||||
"operatorsNote": "Operators on the current node. Each person is listed once.",
|
||||
"timerStart": "Timer start",
|
||||
"dwellDays": "Days in approval",
|
||||
"actions": "Actions",
|
||||
"detail": "View details",
|
||||
"back": "Back to dwell list",
|
||||
"canAccept": "Can accept",
|
||||
"cannotAcceptNote": "Reason it cannot be accepted",
|
||||
"cannotAcceptNote": "Reason it cannot be accepted",
|
||||
"returnFlag": "Returned",
|
||||
"unspecified": "Not specified",
|
||||
"flowStatus": "Flow status",
|
||||
"finishedAt": "Finished at",
|
||||
"operatorName": "Name",
|
||||
"jobNum": "Employee no.",
|
||||
"flowStatusName": {
|
||||
"draft": "Draft",
|
||||
"approving": "Approving",
|
||||
"archived": "Archived",
|
||||
"forceFinished": "Force-finished",
|
||||
"voided": "Voided",
|
||||
"pendingSubmit": "Pending submit",
|
||||
"paused": "Paused",
|
||||
"withdrawn": "Withdrawn"
|
||||
},
|
||||
"statusLabel": {
|
||||
"watching": "In progress",
|
||||
"not_started": "Not started",
|
||||
"stopped_returned": "Returned, no further reminders",
|
||||
"stopped_cannot_accept": "Cannot accept, no further reminders",
|
||||
"stopped_archived": "Archived, no further reminders",
|
||||
"stopped_force_finished": "Force-finished, no further reminders",
|
||||
"stopped_voided": "Voided, no further reminders",
|
||||
"stopped_revoked": "Revoked, no further reminders",
|
||||
"excluded": "Outside monitoring"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,6 +564,13 @@
|
||||
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "Failed to upload the purchase-order PDF to the DMS PO-order folder.",
|
||||
"VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "E10 OpenAPI authorization or token refresh failed.",
|
||||
"VOUCHER_CHECK_OA_E10_SQL_FAILED": "Failed to query the E10 sales-release table.",
|
||||
"EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "E10 database settings for equipment-acceptance sync are incomplete.",
|
||||
"EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "Failed to query E10 equipment-acceptance data.",
|
||||
"EQUIPMENT_ACCEPTANCE_NOT_FOUND": "The equipment-acceptance sync record does not exist.",
|
||||
"EQUIPMENT_ACCEPTANCE_FORBIDDEN": "You do not have access to the equipment acceptance warning.",
|
||||
"EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "Only an administrator can sync equipment acceptance data.",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "Each tier must be longer than the previous one, and each role must be an existing system user.",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "Only an administrator can change equipment acceptance alert settings.",
|
||||
"VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "Failed to download the sales-release PDF from E10.",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "Sales-release data is invalid. Provide a valid invoice number and delivery number.",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "Some sales-release PDFs failed to fetch.",
|
||||
|
||||
@@ -5731,5 +5731,131 @@
|
||||
"prevPage": "หน้าก่อนหน้า",
|
||||
"nextPage": "หน้าถัดไป"
|
||||
}
|
||||
},
|
||||
"equipmentAcceptance": {
|
||||
"title": "การเตือนตรวจรับอุปกรณ์",
|
||||
"sync": "ซิงก์ข้อมูล OA",
|
||||
"syncDone": "ซิงก์แล้ว {upserted} รายการ ข้าม {skipped} รายการ ไม่พบในรอบนี้ {absent} รายการ",
|
||||
"syncFailed": "ซิงก์ข้อมูลตรวจรับอุปกรณ์ไม่สำเร็จ",
|
||||
"tabLedger": "รายการค้าง",
|
||||
"tabSends": "บันทึกการส่ง",
|
||||
"tabConfig": "ตั้งค่าการเตือน",
|
||||
"sendsLead": "การสแกนรายวันสร้างรายการที่รอส่ง หลังสรุปส่งทุกวันศุกร์ 18:00 ตามผู้รับแล้ว จะแสดงที่นี่ ชื่อคงตามตอนที่ส่ง",
|
||||
"sendsEmpty": "ยังไม่มีบันทึกการส่ง",
|
||||
"sendsFailed": "โหลดบันทึกการส่งไม่สำเร็จ",
|
||||
"scanAlerts": "สแกนการเตือน",
|
||||
"sendAlerts": "ส่งการเตือน",
|
||||
"scanConfirm": "ระบบจะซิงก์จาก E10 และสร้างรายการที่รอส่ง",
|
||||
"sendConfirm": "ระบบจะส่งรายการที่รอส่งไป WeCom คนละหนึ่งข้อความ",
|
||||
"scanDone": "เพิ่ม {created} รายการ อัปเดต {updated} รายการ ยกเลิก {cancelled} รายการ",
|
||||
"sendDone": "ส่งถึง {sent} คน ไม่สำเร็จ {failed} คน",
|
||||
"sendResult": "ผลลัพธ์",
|
||||
"sentAt": "เวลาที่ส่ง",
|
||||
"sendStatus": {
|
||||
"pending": "รอส่ง",
|
||||
"sent": "ส่งแล้ว",
|
||||
"failed": "ส่งไม่สำเร็จ",
|
||||
"cancelled": "ยกเลิกแล้ว"
|
||||
},
|
||||
"configLead": "จำนวนวันแต่ละขั้นต้องมากขึ้นตามลำดับ การบันทึกมีผลเฉพาะการเตือนที่เกิดภายหลัง เวลาส่งตั้งในตารางงาน",
|
||||
"tier1": "ขั้นที่ 1",
|
||||
"tier2": "ขั้นที่ 2",
|
||||
"tier3": "ขั้นที่ 3",
|
||||
"tier4": "ขั้นที่ 4",
|
||||
"tierWho1": "ผู้ดำเนินการปัจจุบัน",
|
||||
"tierWho2": "รองผู้จัดการ",
|
||||
"tierWho3": "COO",
|
||||
"tierWho4": "ผู้จัดการทั่วไป",
|
||||
"dayUnit": "วัน",
|
||||
"fixedRoles": "ตำแหน่งคงที่",
|
||||
"role": {
|
||||
"buyer_manager": "รองผู้จัดการจัดซื้อ",
|
||||
"coo": "COO",
|
||||
"executive": "ผู้จัดการทั่วไป"
|
||||
},
|
||||
"roleEmpty": "ยังไม่ได้เลือก",
|
||||
"selectUser": "เลือก",
|
||||
"clearUser": "ล้าง",
|
||||
"configPickOne": "แต่ละตำแหน่งเก็บไว้คนเดียว ชื่อใช้แสดงผล ค่าที่บันทึกคือผู้ใช้ระบบ",
|
||||
"rulesTitle": "กฎผู้รับ",
|
||||
"rulesLead": "ผู้รับแต่ละขั้นไม่เปลี่ยนตามจำนวนวัน เปลี่ยนได้เฉพาะเกณฑ์วัน",
|
||||
"ruleTier": "รอบ",
|
||||
"ruleTo": "ผู้รับหลัก",
|
||||
"ruleCc": "สำเนา",
|
||||
"ruleOver": "เกิน {days} วัน",
|
||||
"ruleTo1": "ผู้ดำเนินการปัจจุบัน",
|
||||
"ruleCc1": "หัวหน้าตรงและผู้ขอ",
|
||||
"ruleTo2": "รองผู้จัดการของผู้ดำเนินการ",
|
||||
"ruleCc2": "COO และรองผู้จัดการจัดซื้อ",
|
||||
"ruleTo3": "COO",
|
||||
"ruleCc3": "รองผู้จัดการจัดซื้อ",
|
||||
"ruleTo4": "ผู้จัดการทั่วไป",
|
||||
"ruleCc4": "COO และรองผู้จัดการจัดซื้อ",
|
||||
"saveConfig": "บันทึกการตั้งค่า",
|
||||
"configSaveHint": "รายการที่ส่งแล้วไม่เปลี่ยน",
|
||||
"configSaved": "บันทึกการตั้งค่าแล้ว",
|
||||
"configLoadFailed": "โหลดการตั้งค่าไม่สำเร็จ",
|
||||
"configSaveFailed": "บันทึกการตั้งค่าไม่สำเร็จ",
|
||||
"configDaysInvalid": "จำนวนวันแต่ละขั้นต้องมากขึ้นตามลำดับ",
|
||||
"configReadOnly": "เฉพาะผู้ดูแลระบบที่แก้ไขการตั้งค่าได้",
|
||||
"loadFailed": "โหลดรายการใบตรวจรับไม่สำเร็จ",
|
||||
"detailLoadFailed": "โหลดรายละเอียดใบตรวจรับไม่สำเร็จ",
|
||||
"loading": "กำลังโหลด",
|
||||
"empty": "ยังไม่มีใบตรวจรับที่ซิงก์มา",
|
||||
"kpiWatching": "กำลังดำเนินการ",
|
||||
"kpiOverdue": "เกินกำหนด",
|
||||
"kpiStopped": "ไม่แจ้งเตือนอีก",
|
||||
"filterAll": "ทั้งหมด",
|
||||
"filterWatching": "กำลังดำเนินการ",
|
||||
"filterOverdue": "เกินกำหนด",
|
||||
"filterStopped": "ไม่แจ้งเตือนอีก",
|
||||
"filterNotStarted": "ยังไม่เริ่ม",
|
||||
"badgeOverdue": "เกินกำหนด",
|
||||
"badgeOnTime": "ยังไม่เกินกำหนด",
|
||||
"currentHandlers": "ผู้ดำเนินการปัจจุบัน",
|
||||
"daysValue": "{days} วัน",
|
||||
"statusAll": "ทุกสถานะ",
|
||||
"status": "สถานะ",
|
||||
"acceptanceNo": "เลขที่ใบตรวจรับ",
|
||||
"purchaseOrderNo": "เลขที่ใบสั่งซื้อ",
|
||||
"applicant": "ผู้ขอ",
|
||||
"currentNodes": "โหนดปัจจุบัน",
|
||||
"operators": "ผู้ดำเนินการ",
|
||||
"operatorsNote": "ผู้ดำเนินการบนโหนดปัจจุบัน แต่ละคนแสดงหนึ่งแถว",
|
||||
"timerStart": "จุดเริ่มนับเวลา",
|
||||
"dwellDays": "จำนวนวันอนุมัติ",
|
||||
"actions": "การทำงาน",
|
||||
"detail": "ดูรายละเอียด",
|
||||
"back": "กลับไปรายการค้าง",
|
||||
"canAccept": "ตรวจรับได้",
|
||||
"cannotAcceptNote": "เหตุผลที่ตรวจรับไม่ได้",
|
||||
"cannotAcceptNote": "คำอธิบายที่ตรวจรับไม่ได้",
|
||||
"returnFlag": "ถูกส่งกลับ",
|
||||
"unspecified": "ยังไม่ระบุ",
|
||||
"flowStatus": "สถานะกระบวนการ",
|
||||
"finishedAt": "เวลาสิ้นสุด",
|
||||
"operatorName": "ชื่อ",
|
||||
"jobNum": "รหัสพนักงาน",
|
||||
"flowStatusName": {
|
||||
"draft": "ร่าง",
|
||||
"approving": "กำลังอนุมัติ",
|
||||
"archived": "จัดเก็บแล้ว",
|
||||
"forceFinished": "บังคับจบ",
|
||||
"voided": "ยกเลิกเอกสารแล้ว",
|
||||
"pendingSubmit": "รอส่ง",
|
||||
"paused": "หยุดชั่วคราว",
|
||||
"withdrawn": "ถอนกลับ"
|
||||
},
|
||||
"statusLabel": {
|
||||
"watching": "กำลังดำเนินการ",
|
||||
"not_started": "ยังไม่เริ่ม",
|
||||
"stopped_returned": "ส่งกลับแล้ว ไม่แจ้งเตือนอีก",
|
||||
"stopped_cannot_accept": "ตรวจรับไม่ได้ ไม่แจ้งเตือนอีก",
|
||||
"stopped_archived": "จัดเก็บแล้ว ไม่แจ้งเตือนอีก",
|
||||
"stopped_force_finished": "บังคับจบแล้ว ไม่แจ้งเตือนอีก",
|
||||
"stopped_voided": "ยกเลิกแล้ว ไม่แจ้งเตือนอีก",
|
||||
"stopped_revoked": "เพิกถอนแล้ว ไม่แจ้งเตือนอีก",
|
||||
"excluded": "อยู่นอกขอบเขตติดตาม"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,6 +564,13 @@
|
||||
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "อัปโหลดไฟล์ PDF ใบสั่งซื้อไปยังโฟลเดอร์ PO订单 ในคลังเอกสารไม่สำเร็จ",
|
||||
"VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "การอนุญาตหรือรีเฟรชโทเค็น E10 OpenAPI ล้มเหลว",
|
||||
"VOUCHER_CHECK_OA_E10_SQL_FAILED": "ค้นตารางใบอนุญาตปล่อยสินค้าใน E10 ไม่สำเร็จ",
|
||||
"EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "การตั้งค่าฐานข้อมูล E10 สำหรับซิงก์การตรวจรับอุปกรณ์ไม่ครบ",
|
||||
"EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "ค้นข้อมูลการตรวจรับอุปกรณ์ใน E10 ไม่สำเร็จ",
|
||||
"EQUIPMENT_ACCEPTANCE_NOT_FOUND": "ไม่พบรายการซิงก์การตรวจรับอุปกรณ์",
|
||||
"EQUIPMENT_ACCEPTANCE_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการเตือนตรวจรับอุปกรณ์",
|
||||
"EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ข้อมูลตรวจรับอุปกรณ์ได้",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "จำนวนวันแต่ละขั้นต้องมากขึ้นตามลำดับ และตำแหน่งต้องเป็นผู้ใช้ระบบที่มีอยู่",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบที่แก้ไขการตั้งค่าการเตือนตรวจรับอุปกรณ์ได้",
|
||||
"VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "ดาวน์โหลด PDF ใบอนุญาตปล่อยสินค้าจาก E10 ไม่สำเร็จ",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "ข้อมูลใบอนุญาตปล่อยสินค้าไม่ถูกต้อง กรุณาระบุเลขที่ใบแจ้งหนี้และเลขที่ใบส่งที่ถูกต้อง",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "ดึง PDF ใบอนุญาตปล่อยสินค้าบางไฟล์ไม่สำเร็จ",
|
||||
|
||||
@@ -5764,5 +5764,131 @@
|
||||
"prevPage": "上一页",
|
||||
"nextPage": "下一页"
|
||||
}
|
||||
},
|
||||
"equipmentAcceptance": {
|
||||
"title": "设备验收预警",
|
||||
"sync": "同步 OA 数据",
|
||||
"syncDone": "已同步 {upserted} 张,跳过 {skipped} 张,本次未见 {absent} 张",
|
||||
"syncFailed": "同步设备验收数据失败",
|
||||
"tabLedger": "停留情况",
|
||||
"tabSends": "发送记录",
|
||||
"tabConfig": "预警配置",
|
||||
"sendsLead": "每日扫描生成待发送。默认每周五 18:00 按收件人汇总发出后记在这里。已发送的姓名保持发送当时的人。",
|
||||
"sendsEmpty": "还没有发送记录",
|
||||
"sendsFailed": "读取发送记录失败",
|
||||
"scanAlerts": "扫描预警",
|
||||
"sendAlerts": "发送预警",
|
||||
"scanConfirm": "将从 E10 同步,并生成待发送记录。",
|
||||
"sendConfirm": "将把待发送记录按收件人发到企业微信。",
|
||||
"scanDone": "新增 {created} 条,更新 {updated} 条,取消 {cancelled} 条",
|
||||
"sendDone": "已向 {sent} 人发送,{failed} 人失败",
|
||||
"sendResult": "结果",
|
||||
"sentAt": "发送时间",
|
||||
"sendStatus": {
|
||||
"pending": "待发送",
|
||||
"sent": "已发送",
|
||||
"failed": "发送失败",
|
||||
"cancelled": "已取消"
|
||||
},
|
||||
"configLead": "四档天数须逐档增大。保存后只影响以后新产生的预警。发送时刻在排程里配置。",
|
||||
"tier1": "第 1 档",
|
||||
"tier2": "第 2 档",
|
||||
"tier3": "第 3 档",
|
||||
"tier4": "第 4 档",
|
||||
"tierWho1": "当前处理人",
|
||||
"tierWho2": "经副理",
|
||||
"tierWho3": "COO",
|
||||
"tierWho4": "总经理",
|
||||
"dayUnit": "天",
|
||||
"fixedRoles": "固定岗位",
|
||||
"role": {
|
||||
"buyer_manager": "采购经副理",
|
||||
"coo": "COO",
|
||||
"executive": "总经理"
|
||||
},
|
||||
"roleEmpty": "未选择",
|
||||
"selectUser": "选择",
|
||||
"clearUser": "清除",
|
||||
"configPickOne": "每个岗位只保留一人。姓名用于显示,保存的是系统用户。",
|
||||
"rulesTitle": "取人规则",
|
||||
"rulesLead": "主送对象不随天数改,只改超过多少天才触发。",
|
||||
"ruleTier": "轮次",
|
||||
"ruleTo": "主送",
|
||||
"ruleCc": "抄送",
|
||||
"ruleOver": "超过 {days} 天",
|
||||
"ruleTo1": "当前节点处理人",
|
||||
"ruleCc1": "其直接主管、采购担当",
|
||||
"ruleTo2": "当前节点处理人的经副理",
|
||||
"ruleCc2": "COO、采购经副理",
|
||||
"ruleTo3": "COO",
|
||||
"ruleCc3": "采购经副理",
|
||||
"ruleTo4": "总经理",
|
||||
"ruleCc4": "COO、采购经副理",
|
||||
"saveConfig": "保存配置",
|
||||
"configSaveHint": "已发送记录保持不变",
|
||||
"configSaved": "预警配置已保存",
|
||||
"configLoadFailed": "预警配置加载失败",
|
||||
"configSaveFailed": "预警配置保存失败",
|
||||
"configDaysInvalid": "四档天数须逐档增大",
|
||||
"configReadOnly": "只有管理员可以修改配置",
|
||||
"loadFailed": "验收单列表加载失败",
|
||||
"detailLoadFailed": "验收单详情加载失败",
|
||||
"loading": "正在加载",
|
||||
"empty": "还没有同步到验收单",
|
||||
"kpiWatching": "进行中",
|
||||
"kpiOverdue": "已逾期",
|
||||
"kpiStopped": "不再提醒",
|
||||
"filterAll": "全部",
|
||||
"filterWatching": "进行中",
|
||||
"filterOverdue": "已逾期",
|
||||
"filterStopped": "不再提醒",
|
||||
"filterNotStarted": "未开始",
|
||||
"badgeOverdue": "已逾期",
|
||||
"badgeOnTime": "未超时",
|
||||
"currentHandlers": "当前处理人",
|
||||
"daysValue": "{days} 天",
|
||||
"statusAll": "全部状态",
|
||||
"status": "状态",
|
||||
"acceptanceNo": "验收单单号",
|
||||
"purchaseOrderNo": "采购单号",
|
||||
"applicant": "申请人",
|
||||
"currentNodes": "当前节点",
|
||||
"operators": "操作人",
|
||||
"operatorsNote": "当前节点上的操作人。同一人只保留一行。",
|
||||
"timerStart": "计时起点",
|
||||
"dwellDays": "签核天数",
|
||||
"actions": "操作",
|
||||
"detail": "查看详情",
|
||||
"back": "返回停留情况",
|
||||
"canAccept": "是否可以验收",
|
||||
"cannotAcceptNote": "无法验收说明",
|
||||
"cannotAcceptNote": "无法验收说明",
|
||||
"returnFlag": "是否退回",
|
||||
"unspecified": "未标明",
|
||||
"flowStatus": "流程状态",
|
||||
"finishedAt": "结束时间",
|
||||
"operatorName": "姓名",
|
||||
"jobNum": "工号",
|
||||
"flowStatusName": {
|
||||
"draft": "草稿",
|
||||
"approving": "审批中",
|
||||
"archived": "正常归档",
|
||||
"forceFinished": "强制结束",
|
||||
"voided": "已作废",
|
||||
"pendingSubmit": "待提交",
|
||||
"paused": "暂停",
|
||||
"withdrawn": "撤销"
|
||||
},
|
||||
"statusLabel": {
|
||||
"watching": "进行中",
|
||||
"not_started": "未开始",
|
||||
"stopped_returned": "已退回,不再提醒",
|
||||
"stopped_cannot_accept": "无法验收,不再提醒",
|
||||
"stopped_archived": "已归档,不再提醒",
|
||||
"stopped_force_finished": "已强制结束,不再提醒",
|
||||
"stopped_voided": "已作废,不再提醒",
|
||||
"stopped_revoked": "已撤销,不再提醒",
|
||||
"excluded": "不在监控范围"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,6 +564,13 @@
|
||||
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "采购单 PDF 上传到文档库「PO订单」目录失败。",
|
||||
"VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "E10 OpenAPI 授权或刷新 token 失败。",
|
||||
"VOUCHER_CHECK_OA_E10_SQL_FAILED": "查询 E10 销货放行单库表失败。",
|
||||
"EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "设备验收同步的 E10 数据库配置不完整。",
|
||||
"EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "查询 E10 设备验收数据失败。",
|
||||
"EQUIPMENT_ACCEPTANCE_NOT_FOUND": "设备验收同步记录不存在。",
|
||||
"EQUIPMENT_ACCEPTANCE_FORBIDDEN": "你没有设备验收预警的访问权限。",
|
||||
"EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "仅管理员可同步设备验收数据。",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "四档天数须逐档增大,岗位必须选择已有的系统用户。",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "仅管理员可修改设备验收预警配置。",
|
||||
"VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "从 E10 下载销货放行单 PDF 失败。",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "销货放行单数据无效:请提供合法的发票号和销货单号。",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "销货放行单拉取部分失败。",
|
||||
|
||||
@@ -5731,5 +5731,131 @@
|
||||
"prevPage": "上一頁",
|
||||
"nextPage": "下一頁"
|
||||
}
|
||||
},
|
||||
"equipmentAcceptance": {
|
||||
"title": "設備驗收預警",
|
||||
"sync": "同步 OA 資料",
|
||||
"syncDone": "已同步 {upserted} 張,略過 {skipped} 張,本次未見 {absent} 張",
|
||||
"syncFailed": "同步設備驗收資料失敗",
|
||||
"tabLedger": "停留情況",
|
||||
"tabSends": "發送記錄",
|
||||
"tabConfig": "預警配置",
|
||||
"sendsLead": "每日掃描產生待發送。預設每週五 18:00 按收件人彙總發出後記在這裡。已發送的姓名保持發送當時的人。",
|
||||
"sendsEmpty": "還沒有發送記錄",
|
||||
"sendsFailed": "讀取發送記錄失敗",
|
||||
"scanAlerts": "掃描預警",
|
||||
"sendAlerts": "發送預警",
|
||||
"scanConfirm": "將從 E10 同步,並產生待發送記錄。",
|
||||
"sendConfirm": "將把待發送記錄按收件人發到企業微信。",
|
||||
"scanDone": "新增 {created} 條,更新 {updated} 條,取消 {cancelled} 條",
|
||||
"sendDone": "已向 {sent} 人發送,{failed} 人失敗",
|
||||
"sendResult": "結果",
|
||||
"sentAt": "發送時間",
|
||||
"sendStatus": {
|
||||
"pending": "待發送",
|
||||
"sent": "已發送",
|
||||
"failed": "發送失敗",
|
||||
"cancelled": "已取消"
|
||||
},
|
||||
"configLead": "四檔天數須逐檔增大。儲存後只影響以後新產生的預警。發送時刻在排程裡配置。",
|
||||
"tier1": "第 1 檔",
|
||||
"tier2": "第 2 檔",
|
||||
"tier3": "第 3 檔",
|
||||
"tier4": "第 4 檔",
|
||||
"tierWho1": "目前處理人",
|
||||
"tierWho2": "經副理",
|
||||
"tierWho3": "COO",
|
||||
"tierWho4": "總經理",
|
||||
"dayUnit": "天",
|
||||
"fixedRoles": "固定崗位",
|
||||
"role": {
|
||||
"buyer_manager": "採購經副理",
|
||||
"coo": "COO",
|
||||
"executive": "總經理"
|
||||
},
|
||||
"roleEmpty": "未選擇",
|
||||
"selectUser": "選擇",
|
||||
"clearUser": "清除",
|
||||
"configPickOne": "每個崗位只保留一人。姓名用來顯示,儲存的是系統使用者。",
|
||||
"rulesTitle": "取人規則",
|
||||
"rulesLead": "主送對象不隨天數改,只改超過多少天才觸發。",
|
||||
"ruleTier": "輪次",
|
||||
"ruleTo": "主送",
|
||||
"ruleCc": "抄送",
|
||||
"ruleOver": "超過 {days} 天",
|
||||
"ruleTo1": "目前節點處理人",
|
||||
"ruleCc1": "其直接主管、採購擔當",
|
||||
"ruleTo2": "目前節點處理人的經副理",
|
||||
"ruleCc2": "COO、採購經副理",
|
||||
"ruleTo3": "COO",
|
||||
"ruleCc3": "採購經副理",
|
||||
"ruleTo4": "總經理",
|
||||
"ruleCc4": "COO、採購經副理",
|
||||
"saveConfig": "儲存配置",
|
||||
"configSaveHint": "已發送紀錄保持不變",
|
||||
"configSaved": "預警配置已儲存",
|
||||
"configLoadFailed": "預警配置載入失敗",
|
||||
"configSaveFailed": "預警配置儲存失敗",
|
||||
"configDaysInvalid": "四檔天數須逐檔增大",
|
||||
"configReadOnly": "只有管理員可以修改配置",
|
||||
"loadFailed": "驗收單列表載入失敗",
|
||||
"detailLoadFailed": "驗收單詳情載入失敗",
|
||||
"loading": "正在載入",
|
||||
"empty": "還沒有同步到驗收單",
|
||||
"kpiWatching": "進行中",
|
||||
"kpiOverdue": "已逾期",
|
||||
"kpiStopped": "不再提醒",
|
||||
"filterAll": "全部",
|
||||
"filterWatching": "進行中",
|
||||
"filterOverdue": "已逾期",
|
||||
"filterStopped": "不再提醒",
|
||||
"filterNotStarted": "未開始",
|
||||
"badgeOverdue": "已逾期",
|
||||
"badgeOnTime": "未超時",
|
||||
"currentHandlers": "目前處理人",
|
||||
"daysValue": "{days} 天",
|
||||
"statusAll": "全部狀態",
|
||||
"status": "狀態",
|
||||
"acceptanceNo": "驗收單單號",
|
||||
"purchaseOrderNo": "採購單號",
|
||||
"applicant": "申請人",
|
||||
"currentNodes": "目前節點",
|
||||
"operators": "操作人",
|
||||
"operatorsNote": "目前節點上的操作人。同一人只保留一行。",
|
||||
"timerStart": "計時起點",
|
||||
"dwellDays": "簽核天數",
|
||||
"actions": "操作",
|
||||
"detail": "查看詳情",
|
||||
"back": "返回停留情況",
|
||||
"canAccept": "是否可以驗收",
|
||||
"cannotAcceptNote": "無法驗收說明",
|
||||
"cannotAcceptNote": "無法驗收說明",
|
||||
"returnFlag": "是否退回",
|
||||
"unspecified": "未標明",
|
||||
"flowStatus": "流程狀態",
|
||||
"finishedAt": "結束時間",
|
||||
"operatorName": "姓名",
|
||||
"jobNum": "工號",
|
||||
"flowStatusName": {
|
||||
"draft": "草稿",
|
||||
"approving": "審批中",
|
||||
"archived": "正常歸檔",
|
||||
"forceFinished": "強制結束",
|
||||
"voided": "已作廢",
|
||||
"pendingSubmit": "待提交",
|
||||
"paused": "暫停",
|
||||
"withdrawn": "撤銷"
|
||||
},
|
||||
"statusLabel": {
|
||||
"watching": "進行中",
|
||||
"not_started": "未開始",
|
||||
"stopped_returned": "已退回,不再提醒",
|
||||
"stopped_cannot_accept": "無法驗收,不再提醒",
|
||||
"stopped_archived": "已歸檔,不再提醒",
|
||||
"stopped_force_finished": "已強制結束,不再提醒",
|
||||
"stopped_voided": "已作廢,不再提醒",
|
||||
"stopped_revoked": "已撤銷,不再提醒",
|
||||
"excluded": "不在監控範圍"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,6 +564,13 @@
|
||||
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "採購單 PDF 上傳到文件庫「PO訂單」目錄失敗。",
|
||||
"VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "E10 OpenAPI 授權或刷新 token 失敗。",
|
||||
"VOUCHER_CHECK_OA_E10_SQL_FAILED": "查詢 E10 銷貨放行單庫表失敗。",
|
||||
"EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "設備驗收同步的 E10 資料庫設定不完整。",
|
||||
"EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "查詢 E10 設備驗收資料失敗。",
|
||||
"EQUIPMENT_ACCEPTANCE_NOT_FOUND": "設備驗收同步記錄不存在。",
|
||||
"EQUIPMENT_ACCEPTANCE_FORBIDDEN": "你沒有設備驗收預警的存取權限。",
|
||||
"EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "僅管理員可同步設備驗收資料。",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "四檔天數須逐檔增大,崗位必須選擇已有的系統使用者。",
|
||||
"EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "僅管理員可修改設備驗收預警配置。",
|
||||
"VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "從 E10 下載銷貨放行單 PDF 失敗。",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "銷貨放行單資料無效:請提供合法的發票號和銷貨單號。",
|
||||
"VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "銷貨放行單拉取部分失敗。",
|
||||
|
||||
@@ -11,6 +11,7 @@ export const AGENT_CODE_SHIPPING_NOTICE = 'shipping_notice';
|
||||
export const AGENT_CODE_FILE_CHECK = 'file_check';
|
||||
export const AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review';
|
||||
export const AGENT_CODE_CONTRACT_PAYMENT = 'contract_payment';
|
||||
export const AGENT_CODE_EQUIPMENT_ACCEPTANCE = 'equipment_acceptance';
|
||||
export const AGENT_CODE_VOUCHER_CHECK = 'voucher_check';
|
||||
export const AGENT_CODE_IN_TRANSIT_TRANSFER = 'in_transit_transfer';
|
||||
|
||||
@@ -244,6 +245,11 @@ export function isContractPaymentAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_CONTRACT_PAYMENT;
|
||||
}
|
||||
|
||||
/** 是否为设备验收预警 Agent(agent_code=equipment_acceptance)。 */
|
||||
export function isEquipmentAcceptanceAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_EQUIPMENT_ACCEPTANCE;
|
||||
}
|
||||
|
||||
/** 是否为立账凭证检核 Agent(agent_code=voucher_check)。 */
|
||||
export function isVoucherCheckAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_VOUCHER_CHECK;
|
||||
|
||||
Reference in new issue
Block a user