Merge branch 'dev' into hugo-auto-transfer

This commit is contained in:
hugo committed 2026-10-15 13:16:47 +08:00
commit fc42bb14c9
76 files changed
+6065 -1759

No files matched your search

@@ -3,12 +3,14 @@ backend/app/api/equipment_acceptance/__init__.py
用途:设备验收预警的 Chat 作业面接口。
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录和配置;同步、扫描、发送和保存配置仅平台管理员。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
"""
from __future__ import annotations
from flask import Blueprint, g, request
from io import BytesIO
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError
@@ -19,7 +21,7 @@ from app.services.equipment_acceptance.config_service import (
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.send_record_service import get_send_file, list_send_files, list_send_records
from app.services.equipment_acceptance.sync_service import (
get_acceptance_order,
list_acceptance_orders,
@@ -157,6 +159,26 @@ def send_equipment_acceptance_alerts():
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
def list_equipment_acceptance_send_files():
"""列出最近按收件人归档的 Excel。不含文件字节。"""
_require_equipment_acceptance_access()
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
def download_equipment_acceptance_send_file(file_id: int):
"""下载一份当时发给收件人的设备验收预警 Excel。"""
_require_equipment_acceptance_access()
row = get_send_file(file_id)
return send_file(
BytesIO(row.excel_file_data),
as_attachment=True,
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@equipment_acceptance_bp.route("/sends", methods=["GET"])
def list_equipment_acceptance_sends():
"""分页查看发送记录。扫描写入后这里才有行。"""
+29 -1
View File
@@ -16,7 +16,11 @@ backend/app/api/order_delivery_reply.py
from __future__ import annotations
from flask import Blueprint, g, request
from datetime import datetime
from io import BytesIO
from zoneinfo import ZoneInfo
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
@@ -28,6 +32,8 @@ from app.services.order_delivery_reply.sync_service import OrderDeliverySyncServ
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def _utc_to_shanghai(value) -> str | None:
"""
@@ -121,6 +127,28 @@ def list_lines():
return ok(data, request_id=getattr(g, "request_id", None))
@order_delivery_reply_bp.get("/lines/export")
def export_lines():
"""
导出当前筛选下的全部订单行 Excel(不分页)。
用途与触发时机:工作台工具栏「导出 Excel」按钮;查询参数与列表一致
(keyword/order_date/status),导出全部命中行(服务层 EXPORT_MAX_ROWS 兜底)。
参数与输出约束:要求 order_delivery_reply.access 及以上;返回 xlsx 文件流(attachment,
文件名带北京时间日期)。
"""
_require_access()
content = query_service.export_lines(request.args.to_dict(flat=True))
filename = f"订单交期回复_{datetime.now(ZoneInfo('Asia/Shanghai')):%Y%m%d}.xlsx"
return send_file(
BytesIO(content),
as_attachment=True,
download_name=filename,
mimetype=XLSX_MIME_TYPE,
)
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
def get_line(order_no: str, line_no: int):
"""
+2
View File
@@ -244,6 +244,7 @@ from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
@@ -447,6 +448,7 @@ __all__ = [
'EquipmentAcceptanceNode',
'EquipmentAcceptanceOperator',
'EquipmentAcceptanceSetting',
'EquipmentAcceptanceSendFile',
'EquipmentAcceptanceSendRecord',
'TransferRun',
'TransferSourceJob',
+27 -2
View File
@@ -4,8 +4,9 @@ backend/app/models/equipment_acceptance.py
用途:设备验收预警的本地同步快照和可改配置。
依赖:models.base.Base、users。
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
配置表只存四档天数和三个固定岗位的系统用户。发送时刻不在这张表。
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
不保存流程编号、第二合同编号、验收日期和 isremark。
"""
@@ -14,7 +15,7 @@ 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 import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
@@ -116,6 +117,7 @@ class EquipmentAcceptanceSetting(Base):
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)
round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
@@ -154,3 +156,26 @@ class EquipmentAcceptanceSendRecord(Base):
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)
class EquipmentAcceptanceSendFile(Base):
"""一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。"""
__tablename__ = "equipment_acceptance_send_files"
__table_args__ = (
Index("ix_equipment_acceptance_send_files_created", "created_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
recipient_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent")
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
@@ -0,0 +1,90 @@
"""
backend/app/services/equipment_acceptance/alert_notice.py
用途:把一名收件人的待发送记录收成企微汇总文案和 Excel 明细。
依赖:openpyxl。
逻辑:发送服务按企业微信账号调用。卡片只写张数,逐张明细进工作簿。不写主送、抄送。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from openpyxl.styles import Font
NOTICE_HEADERS = (
"验收单号",
"采购单号",
"申请人",
"轮次",
"停留天数",
"当前节点",
"当前处理人",
"通知身份",
)
NOTICE_FILE_NAME = "设备验收停留提醒.xlsx"
def summary_message(lines: list[dict[str, Any]]) -> str:
"""
拼一名收件人的文字卡片。第一行写已逾期的验收单张数,不列单号。
核心逻辑:一张发送记录算一张。同一轮次的张数写在一起,顺序跟传入的明细一致。
Args:
lines: 已按发送记录去重的明细。每项含 threshold_days。
Returns:
卡片正文。没有明细时仍返回可发送的空汇总。
"""
counts: dict[int, int] = {}
order: list[int] = []
for line in lines:
day = int(line.get("threshold_days") or 0)
if day not in counts:
order.append(day)
counts[day] = 0
counts[day] += 1
detail = ",".join(f"超过 {day} 天 {counts[day]} 张" for day in order) or "无"
return f"共 {len(lines)} 张验收单已逾期。\n{detail}。\n明细见下一条文件。"
def build_notice_workbook(lines: list[dict[str, Any]]) -> bytes:
"""
生成这名收件人的验收停留明细。
核心逻辑:一行对应一张发送记录。通知身份写他为什么收到,不写主送或抄送。
Args:
lines: 验收单号、采购单号、申请人、轮次天数、停留天数、当前节点、当前处理人和通知身份。
Returns:
xlsx 字节。
"""
workbook = Workbook()
sheet = workbook.active
sheet.title = "停留提醒"
sheet.append(list(NOTICE_HEADERS))
for cell in sheet[1]:
cell.font = Font(bold=True)
for line in lines:
dwell = line.get("dwell_days")
sheet.append([
_cell(line.get("acceptance_no")),
_cell(line.get("purchase_order_no")),
_cell(line.get("applicant")),
f"超过 {int(line.get('threshold_days') or 0)} 天",
"—" if dwell is None or dwell == "" else dwell,
_cell(line.get("node_name")),
_cell(line.get("handlers")),
_cell(line.get("identity")),
])
sheet.freeze_panes = "A2"
sheet.auto_filter.ref = sheet.dimensions
output = BytesIO()
workbook.save(output)
return output.getvalue()
def _cell(value: Any) -> str:
"""空值写成横线,避免 Excel 里出现空白列。"""
text = str(value or "").strip()
return text or "—"
@@ -11,20 +11,31 @@ from __future__ import annotations
from typing import Any
def due_tiers(dwell_days: int | None, thresholds: tuple[int, int, int, int]) -> list[int]:
def due_tiers(
dwell_days: int | None,
thresholds: tuple[int, int, int, int],
*,
max_tier: int = 4,
) -> list[int]:
"""
按累计天数给出已经跨过的档位。
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
第 4 轮关闭时最高只到第 3 档,超过第 4 档天数也不产生总经理那一轮。
Args:
dwell_days: 签核自然日。没有计时起点时为空。
thresholds: 四个天数,对应第 1 到第 4 档。
max_tier: 允许的最高档,1 到 4。第 4 轮未启用时传 3。
Returns:
档位号 1 到 4 的列表。没有跨档时为空。
档位号列表。没有跨档时为空。
"""
if dwell_days is None:
return []
return [index + 1 for index, day in enumerate(thresholds) if dwell_days > day]
return [
index + 1
for index, day in enumerate(thresholds)
if dwell_days > day and index + 1 <= max_tier
]
def make_person(
@@ -2,8 +2,9 @@
backend/app/services/equipment_acceptance/alert_service.py
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
依赖:同步服务、OA 人员目录、alert_plan、发送记录模型、企微通知。
逻辑:扫描先同步 E10,再按停留天数跨档。停表取消未发送记录。已发送的不重发、不改收件人。
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
"""
from __future__ import annotations
@@ -11,15 +12,23 @@ from __future__ import annotations
import logging
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
from app.extensions import db
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.user import User
from app.services.equipment_acceptance.alert_notice import (
NOTICE_FILE_NAME,
build_notice_workbook,
summary_message,
)
from app.services.equipment_acceptance.alert_plan import (
assemble_tier,
due_tiers,
@@ -27,7 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
resolve_account,
resolve_configured_user,
)
from app.services.equipment_acceptance.config_service import reminder_days
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
from app.services.equipment_acceptance.snapshot_rules import WATCHING
_LOGGER = logging.getLogger(__name__)
@@ -61,7 +70,7 @@ def refresh_pending_alerts(
"""
按本地快照刷新待发送记录。
核心逻辑:计时中的单据跨过哪一档就保留哪一档。已发送和已取消不改。
核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。
未计时或已停表的单据,把还没发出的记录改成已取消。
Args:
directory: 测试注入的人员目录和经副理。空则查询 E10。
@@ -74,6 +83,7 @@ def refresh_pending_alerts(
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
roles = _configured_users()
thresholds = reminder_days()
max_tier = 4 if is_round_4_enabled() else 3
existing = {
(row.order_id, row.tier): row
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
@@ -86,7 +96,16 @@ def refresh_pending_alerts(
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):
for draft in _drafts(
order,
operators.get(order.id, []),
people,
deputies,
users_by_job,
roles,
thresholds,
max_tier=max_tier,
):
current = existing.get((order.id, draft["tier"]))
if current is not None and current.status in ("sent", "cancelled"):
continue
@@ -136,24 +155,37 @@ def send_pending_alerts() -> dict[str, Any]:
"""
把待发送记录按收件人合并成一条企业微信。
核心逻辑:同一个人本轮只收一条。解析失败的人不改发给别人。已取消和已发送不参与。
核心逻辑:同一个人本轮只收一条汇总卡片和一份 Excel。卡片只写张数,明细在文件里。
解析失败的人不改发给别人。已取消和已发送不参与。
第 4 轮关闭时,已生成的待发送第 4 轮也不发出,避免通知总经理。
卡片或附件任一失败都记失败原因,并打一条 warning 日志。
每位收件人的 Excel 都写入 equipment_acceptance_send_files,发送失败也保留。
Returns:
成功人数、失败人数,以及对应的记录条数。
"""
from app.models import Agent
from app.services.integrations.wecom.notify import send_wecom_event_message
from app.services.integrations.wecom.notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
)
rows = (
db.session.query(EquipmentAcceptanceSendRecord)
.filter(EquipmentAcceptanceSendRecord.status == "pending")
.all()
)
if not is_round_4_enabled():
rows = [row for row in rows if row.tier != 4]
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 {}
order_ids = [row.order_id for row in rows if row.order_id]
nodes = _nodes_by_order(order_ids)
operators = _operators_by_order(order_ids)
users = _users_by_id(_recipient_user_ids(rows))
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
for row in rows:
@@ -166,24 +198,58 @@ def send_pending_alerts() -> dict[str, Any]:
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()
failed_reasons: dict[str, str] = {}
for wecom_id, entries in buckets.items():
user = _audit_user(entries, users)
lines = _notice_lines(entries, orders, nodes, operators)
workbook = build_notice_workbook(lines)
archived = _archive_send_file(user, entries, workbook)
failure = ""
try:
result = send_wecom_event_message(
event_type=_EVENT,
user=user,
title="设备验收停留提醒",
content=_message(entries, orders),
content=summary_message(lines),
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)
_LOGGER.exception("equipment acceptance wecom send failed")
failure = "企业微信发送异常"
result = {}
if not failure and not result.get("ok"):
failure = _wecom_failure_text(result)
_LOGGER.warning(
"equipment acceptance wecom send failed reason=%s trace_id=%s detail=%s",
result.get("reason"),
result.get("trace_id"),
failure,
)
if not failure:
try:
media_id = upload_wecom_temp_media(workbook, archived.excel_file_name or NOTICE_FILE_NAME)
file_result = send_wecom_file_message(wecom_id, media_id)
except Exception:
_LOGGER.exception("equipment acceptance wecom file upload failed")
failure = "企业微信附件上传失败"
file_result = {}
if not failure and file_result.get("errcode") != 0:
failure = _file_failure_text(file_result)
_LOGGER.warning(
"equipment acceptance wecom file failed errcode=%s errmsg=%s",
file_result.get("errcode"),
failure,
)
if failure:
failed_reasons[wecom_id] = failure
archived.status = "failed"
archived.error_message = failure
else:
sent_ids.add(wecom_id)
archived.status = "sent"
archived.sent_at = datetime.utcnow()
records_sent = 0
records_failed = 0
now = datetime.utcnow()
@@ -196,9 +262,10 @@ def send_pending_alerts() -> dict[str, Any]:
ready.discard("")
if not ready:
continue
if ready & failed_ids:
hit = [failed_reasons[item] for item in ready if item in failed_reasons]
if hit:
row.status = "failed"
row.error_message = _join_error(row.error_message, "企业微信发送失败")
row.error_message = _join_error(row.error_message, ";".join(dict.fromkeys(hit)))
records_failed += 1
elif ready <= sent_ids:
row.status = "sent"
@@ -207,7 +274,7 @@ def send_pending_alerts() -> dict[str, Any]:
db.session.commit()
return {
"sent": len(sent_ids),
"failed": len(failed_ids),
"failed": len(failed_reasons),
"records_sent": records_sent,
"records_failed": records_failed,
}
@@ -221,9 +288,11 @@ def _drafts(
users_by_job: dict[str, User],
roles: dict[str, User | None],
thresholds: tuple[int, int, int, int],
*,
max_tier: int = 4,
) -> list[dict[str, Any]]:
"""按当前处理人展开四档里已经跨过的档。"""
due = due_tiers(order.dwell_days, thresholds)
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
if not due:
return []
handlers: list[dict[str, Any]] = []
@@ -410,6 +479,21 @@ def _users_by_id(user_ids: list[int]) -> dict[int, User]:
return {row.id: row for row in rows}
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))
.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:
@@ -447,28 +531,145 @@ def _audit_user(
return None
def _message(
def _archive_send_file(
user: User | None,
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
workbook: bytes,
) -> EquipmentAcceptanceSendFile:
"""
把这次准备发给一名收件人的 Excel 先落库。
核心逻辑:发送成功或失败都保留同一份字节,并记下里面的发送记录,供表格列下载。不保存企微 userid。
Args:
user: 系统用户。对不上账号时只留姓名。
entries: 这名收件人的发送记录和席位,用来取展示名。
workbook: xlsx 字节。
Returns:
已加入当前事务、尚未提交的文件行。
"""
now = datetime.utcnow()
name = _recipient_display_name(user, entries)
row = EquipmentAcceptanceSendFile(
recipient_user_id=None if user is None else user.id,
recipient_name=name or None,
excel_file_name=_archive_file_name(name, now),
excel_file_data=workbook,
excel_file_size=len(workbook),
send_record_ids=[row.id for row, _person in entries if row.id],
status="pending",
created_at=now,
)
db.session.add(row)
return row
def _recipient_display_name(
user: User | None,
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
) -> str:
"""优先用系统姓名,没有账号时用收件人席位上的名字。"""
if user is not None:
named = str(user.real_name or user.username or "").strip()
if named:
return named
for _row, person in entries:
named = str(person.get("name") or "").strip()
if named:
return named
return ""
def _archive_file_name(recipient_name: str, moment: datetime) -> str:
"""文件名带上海日期和收件人,避免多次发送都叫同一个名字。"""
local = moment.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Shanghai"))
safe = "".join(char for char in recipient_name if char not in '\\/:*?"<>|').strip() or "收件人"
return f"设备验收停留提醒-{local:%Y%m%d}-{safe}.xlsx"[:255]
def _notice_lines(
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
orders: dict[int, EquipmentAcceptanceOrder],
) -> str:
"""拼一名收件人本轮要看的验收单。过长时截断。"""
lines: list[str] = []
seen: set[int] = set()
nodes: dict[int, list[EquipmentAcceptanceNode]],
operators: dict[int, list[EquipmentAcceptanceOperator]],
) -> list[dict[str, Any]]:
"""
把一名收件人的发送记录收成 Excel 行。
核心逻辑:同一条发送记录只占一行。通知身份用角色名,例如当前处理人、直接主管,不写主送或抄送。
Args:
entries: 这名收件人挂到的发送记录和对应席位。
orders: 验收单主键到快照。
nodes: 验收单主键到当前节点。
operators: 验收单主键到当前处理人。
Returns:
传给汇总文案和 Excel 的明细行。
"""
grouped: dict[int, dict[str, Any]] = {}
order_keys: list[int] = []
for row, person in entries:
if row.id in seen:
continue
seen.add(row.id)
label = str(person.get("label") or "").strip()
bucket = grouped.get(row.id)
if bucket is None:
bucket = {"row": row, "labels": []}
grouped[row.id] = bucket
order_keys.append(row.id)
if label and label not in bucket["labels"]:
bucket["labels"].append(label)
lines: list[dict[str, Any]] = []
for key in order_keys:
row = grouped[key]["row"]
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]
node_names = _unique_text(node.node_name for node in nodes.get(row.order_id or 0, []))
handler_names = _unique_text(operator.handler_name for operator in operators.get(row.order_id or 0, []))
lines.append({
"acceptance_no": row.acceptance_no,
"purchase_order_no": row.purchase_order_no,
"applicant": None if order is None else order.applicant_name,
"threshold_days": row.threshold_days,
"dwell_days": None if order is None else order.dwell_days,
"node_name": "、".join(node_names),
"handlers": "、".join(handler_names),
"identity": "、".join(grouped[key]["labels"]),
})
return lines
def _unique_text(values) -> list[str]:
"""按出现顺序去掉空白和重复名称。"""
found: list[str] = []
for value in values:
text = str(value or "").strip()
if text and text not in found:
found.append(text)
return found
def _file_failure_text(result: dict[str, Any]) -> str:
"""把企微文件消息的返回收成失败原因。不写入 userid。"""
code = result.get("errcode")
message = str(result.get("errmsg") or "").strip()
text = f"企业微信附件发送失败 {code} {message}".strip()
return text[:255]
def _wecom_failure_text(result: dict[str, Any]) -> str:
"""把企微发送结果收成页面和日志都能看的失败原因。不写入 userid。"""
reason = str(result.get("reason") or "")
if reason == "notify_disabled":
return "企业微信通知总开关已关闭"
if reason == "event_disabled":
return "未开启设备验收预警的企业微信事件"
if reason == "user_unbound":
return "收件人未绑定企业微信"
raw = result.get("raw") if isinstance(result.get("raw"), dict) else {}
if reason == "send_failed":
code = raw.get("errcode")
message = str(raw.get("errmsg") or "").strip()
text = f"企业微信返回 {code} {message}".strip()
return text[:255]
if reason == "exception":
return "企业微信发送异常"
return "企业微信发送失败"
def _join_error(current: str | None, extra: str) -> str:
@@ -1,10 +1,10 @@
"""
backend/app/services/equipment_acceptance/config_service.py
用途:读写设备验收预警配置:四档天数和三个固定岗位。
用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
没有配置行时按冻结默认值 30/37/44/51 返回,不把姓名写进代码。
没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。
"""
from __future__ import annotations
@@ -29,6 +29,44 @@ _ROLE_FIELDS = (
_MAX_DAY = 3650
def is_round_4_enabled() -> bool:
"""
读取第 4 轮是否启用。
核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。
Returns:
启用为 True。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
return False
return bool(row.round_4_enabled)
def parse_round_4_enabled(raw: Any) -> bool:
"""
校验第 4 轮开关。
核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。
Args:
raw: 接口里的 round_4_enabled。缺省为 None。
Returns:
是否启用第 4 轮。
Raises:
ValidationError: 传入了布尔以外的值。
"""
if raw is None:
return False
if not isinstance(raw, bool):
raise ValidationError(
"第 4 轮开关必须是是否启用",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
details={"field": "round_4_enabled"},
)
return raw
def reminder_days() -> tuple[int, int, int, int]:
"""
读取四档天数。
@@ -65,12 +103,13 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
Args:
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
Returns:
days、三个岗位用户主键、已选用户、候选人和更新时间。
days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
selected_ids = _selected_ids(row)
return {
"days": list(_days_of(row)),
"round_4_enabled": False if row is None else bool(row.round_4_enabled),
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
"coo_user_id": None if row is None else row.coo_user_id,
"executive_user_id": None if row is None else row.executive_user_id,
@@ -82,12 +121,12 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
"""
保存四档天数和三个岗位用户。
保存四档天数、第 4 轮开关和三个岗位用户。
核心逻辑:天数必须逐档增大。岗位为空表示未选;有值时必须是已存在的系统用户。
保存后只影响以后的预警,这里不改历史发送记录。
核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。
保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。
Args:
payload: days 为四个整数;三个岗位字段为用户主键或空。
payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。
updated_by: 操作人的系统用户主键。
Returns:
与读取接口相同的配置,并带候选人。
@@ -96,12 +135,14 @@ def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[
ValidationError: 天数不合法,或岗位用户不存在。
"""
days = validate_reminder_days(payload.get("days"))
round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled"))
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
db.session.add(row)
row.day_1, row.day_2, row.day_3, row.day_4 = days
row.round_4_enabled = round_4_enabled
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
row.coo_user_id = role_ids["coo_user_id"]
row.executive_user_id = role_ids["executive_user_id"]
@@ -2,17 +2,20 @@
backend/app/services/equipment_acceptance/send_record_service.py
用途:分页读取设备验收预警的发送记录。
依赖:extensions.db、EquipmentAcceptanceSendRecord、utc_iso。
逻辑:由 GET /api/equipment-acceptance/sends 调用。待发送由扫描写入,本模块只读取。
依赖:extensions.db、EquipmentAcceptanceSendRecord、EquipmentAcceptanceSendFile、utc_iso。
逻辑:由发送记录列表和 Excel 下载接口调用。列表按 send_record_ids 把 Excel 挂到对应行,不读文件字节。
"""
from __future__ import annotations
from typing import Any
from sqlalchemy.orm import defer
from app.core.errors import NotFoundError
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
from app.models.equipment_acceptance import EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
@@ -36,21 +39,122 @@ def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
.limit(page_size)
.all()
)
file_rows = _file_rows_for([row.id for row in rows])
return {
"items": [send_record_payload(row) for row in rows],
"items": [
send_record_payload(row, _files_for_record(row.id, file_rows))
for row in rows
],
"total": total,
"page": page,
"page_size": page_size,
}
def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
def list_send_files(*, limit: int = 20) -> list[dict[str, Any]]:
"""
列出最近留下的收件人 Excel,不含文件字节。
核心逻辑:按创建时间倒序。发送失败的文件也返回,方便对照当时准备发出的明细。
Args:
limit: 最多返回条数,上限 50。
Returns:
文件名、收件人、状态和发送时间。
"""
limit = min(50, max(1, limit))
rows = (
db.session.query(EquipmentAcceptanceSendFile)
.order_by(EquipmentAcceptanceSendFile.created_at.desc(), EquipmentAcceptanceSendFile.id.desc())
.limit(limit)
.all()
)
return [send_file_payload(row) for row in rows]
def get_send_file(file_id: int) -> EquipmentAcceptanceSendFile:
"""
取出一份已归档的 Excel。
Args:
file_id: 文件行主键。
Returns:
含字节的文件行。
Raises:
NotFoundError: 记录不存在或没有文件内容。
"""
row = db.session.get(EquipmentAcceptanceSendFile, file_id)
if row is None or not row.excel_file_data:
raise NotFoundError("设备验收预警附件不存在")
return row
def send_file_payload(row: EquipmentAcceptanceSendFile) -> dict[str, Any]:
"""列表用的文件摘要。不返回 Excel 字节。"""
return {
"id": row.id,
"recipient_name": row.recipient_name,
"excel_file_name": row.excel_file_name,
"excel_file_size": row.excel_file_size,
"status": row.status,
"sent_at": utc_iso(row.sent_at),
"created_at": utc_iso(row.created_at),
}
def _file_rows_for(record_ids: list[int]) -> list[EquipmentAcceptanceSendFile]:
"""
取出可能挂在这些发送记录上的 Excel 摘要。
核心逻辑:延迟加载文件字节,只留下文件名和记录编号,避免列表把整份 xlsx 读进内存。
Args:
record_ids: 当前页发送记录主键。为空时不查。
Returns:
归档文件行,不含 excel_file_data。
"""
if not record_ids:
return []
return (
db.session.query(EquipmentAcceptanceSendFile)
.options(defer(EquipmentAcceptanceSendFile.excel_file_data))
.order_by(EquipmentAcceptanceSendFile.id.asc())
.all()
)
def _files_for_record(record_id: int, file_rows: list[EquipmentAcceptanceSendFile]) -> list[dict[str, Any]]:
"""
挑出包含这条发送记录的 Excel。
核心逻辑:send_record_ids 里有这条记录才挂上。没有文件名的不展示。
Args:
record_id: 发送记录主键。
file_rows: 已去掉文件字节的归档行。
Returns:
下载按钮需要的 id 和文件名。
"""
found: list[dict[str, Any]] = []
for row in file_rows:
ids = {int(item) for item in list(row.send_record_ids or []) if item}
if record_id in ids and row.excel_file_name:
found.append({
"id": row.id,
"excel_file_name": row.excel_file_name,
})
return found
def send_record_payload(
row: EquipmentAcceptanceSendRecord,
files: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
把一条发送记录收成接口数据。
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。Excel 只带文件名和主键。
Args:
row: 本地发送记录。
files: 这份记录出现过的归档 Excel。
Returns:
页签表格用的字段。
"""
@@ -68,4 +172,5 @@ def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
"sent_at": utc_iso(row.sent_at),
"error_message": row.error_message,
"created_at": utc_iso(row.created_at),
"files": files or [],
}
@@ -12,8 +12,10 @@ from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from sqlalchemy import Select, func, or_, select
from app.extensions import db
@@ -30,6 +32,18 @@ STATUS_FILTER_VALUES = {"replied", "not_fully_replied"}
DEFAULT_PAGE_SIZE = 50
MAX_PAGE_SIZE = 200
# 导出兜底上限:防止极端筛选全量导出失控(当前数据量 ~1k 行,远低于该值)。
EXPORT_MAX_ROWS = 10000
# 导出表头(与工作台列顺序一致,交期回复批次合并为单列)。
EXPORT_HEADERS = [
"客户编号", "客户简称", "订单日期", "订单单号", "项次", "产品编号", "品名",
"客户产品编号", "数量", "约定交货日", "交期回复状态", "交期回复批次",
"业务员", "部门", "客户订单", "规格", "单位", "通知时间",
]
STATUS_EXPORT_LABELS = {"not_replied": "未回复", "partial_replied": "部分回复", "replied": "已回复"}
def _utc_to_shanghai(value) -> str | None:
"""naive-UTC 时间转北京时间展示串;仅用于序列化,详情见 api 层同名 helper 注释。"""
@@ -278,6 +292,82 @@ def list_lines(params: dict[str, Any]) -> dict[str, Any]:
return {"items": items, "page": page, "page_size": page_size, "total": total or 0}
def export_lines(params: dict[str, Any]) -> bytes:
"""
导出当前筛选下的全部订单行(xlsx 字节流)。
用途与触发时机:GET /api/order-delivery-reply/lines/export;工作台「导出 Excel」按钮。
核心逻辑:[STEP 1] 与 list_lines 同一筛选与默认排序,不分页(EXPORT_MAX_ROWS 兜底防失控);
[STEP 2] 批量预取批次与锁定状态后序列化;
[STEP 3] openpyxl 生成单工作表(中文表头同工作台列顺序,批次合并为「交期·数量」分号串,
行状态转中文)。
Args:
params: keyword / order_date / status(与列表筛选一致)。
Returns:
xlsx 文件字节流。
"""
stmt = _apply_filters(_base_query(), params).order_by(
OrderDeliveryErpLine.order_date.asc(),
OrderDeliveryErpLine.customer_no.asc(),
OrderDeliveryErpLine.order_no.asc(),
OrderDeliveryErpLine.line_no.asc(),
OrderDeliveryErpLine.part_no.asc(),
).limit(EXPORT_MAX_ROWS)
lines = list(db.session.scalars(stmt).all())
line_ids = [line.id for line in lines]
batches_by_line: dict[int, list[OrderDeliveryBatch]] = {}
states_by_line: dict[int, OrderDeliveryLineState] = {}
if line_ids:
for batch in db.session.scalars(
select(OrderDeliveryBatch)
.where(OrderDeliveryBatch.line_id.in_(line_ids))
.order_by(OrderDeliveryBatch.line_id, OrderDeliveryBatch.seq)
).all():
batches_by_line.setdefault(batch.line_id, []).append(batch)
for state in db.session.scalars(
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id.in_(line_ids))
).all():
states_by_line[state.line_id] = state
workbook = Workbook()
sheet = workbook.active
sheet.title = "订单交期回复"
sheet.append(EXPORT_HEADERS)
for line in lines:
item = _serialize_line(line, batches_by_line.get(line.id, []), states_by_line.get(line.id))
batch_text = ";".join(
f"{batch['planned_date']}·{batch['qty']}" for batch in item["batches"] if batch["planned_date"]
)
sheet.append([
item["customer_no"] or "",
item["customer_short_name"] or "",
item["order_date"] or "",
item["order_no"] or "",
item["line_no"],
item["part_no"] or "",
item["part_name"] or "",
item["customer_part_no"] or "",
item["qty"] or "",
item["agreed_date"] or "",
STATUS_EXPORT_LABELS.get(item["status"], item["status"]),
batch_text,
item["salesperson_name"] or item["salesperson_code"] or "",
item["dept_name"] or item["dept_code"] or "",
item["customer_po"] or "",
item["spec"] or "",
item["unit"] or "",
item["notified_at"] or "",
])
buffer = BytesIO()
workbook.save(buffer)
return buffer.getvalue()
def get_line(order_no: str, line_no: int) -> dict[str, Any] | None:
"""
单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。
@@ -11,6 +11,11 @@ backend/app/services/order_delivery_reply/sql.py
# 基础 SELECT:不带分页/排序,同步服务按 oea01 keyset 分页时在外层包装。
# 关联:oea01=oeb01;oeb04=ima01 且 oeb06=ima02;oea03=occ01;oea14=gen01;oea15=gem01。
# 别名与 docs/features/order-delivery-reply/technical-design.md §3.5 标准 SELECT 逐列一致。
# 可选起始日下界(2026-10-09 增补):正式环境经 ORDER_DELIVERY_SYNC_DATE_FROM 注入边界值
# (绑定为 date,oea02 为 Oracle DATE 列),只同步订单日期 ≥ 边界的订单行;
# 未配置边界时服务层不拼接此子句,SQL 本体保持全量口径不变。仅只读 SELECT 约束同上。
ORDER_DELIVERY_DATE_FROM_CLAUSE = "AND a.oea02 >= :order_date_from"
ORDER_DELIVERY_SQL = """
SELECT
a.oea01 AS order_no,
@@ -7,6 +7,9 @@ backend/app/services/order_delivery_reply/sync_service.py
逻辑:按 oea01 keyset 分页拉取合格订单行 → 对 (order_no, line_no) 做 upsert 且只更新 ERP 列白名单
(绝不覆盖批次/锁定)→ 本轮未命中的本地行置 erp_missing=true(不删除)→ 写 sync_runs。
全程模块级锁保证同时只有一个同步;失败保留上次快照并记录错误。
可选起始日下界(2026-10-09):ORDER_DELIVERY_SYNC_DATE_FROM(YYYY-MM-DD,仅正式环境配置)——
只同步订单日期 ≥ 边界的订单行(早于边界的历史行随 erp_missing 语义自动移出工作台);
未配置 = 全量同步(dev/test 现状);配置非法格式 fail-closed 拒绝同步。
"""
from __future__ import annotations
@@ -14,7 +17,7 @@ from __future__ import annotations
import logging
import os
import threading
from datetime import datetime
from datetime import date, datetime
from typing import Any
from sqlalchemy import select, update
@@ -25,10 +28,35 @@ from app.models.order_delivery_reply import (
OrderDeliveryErpLine,
OrderDeliverySyncRun,
)
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_DATE_FROM_CLAUSE, ORDER_DELIVERY_SQL
logger = logging.getLogger(__name__)
def _resolve_sync_date_from() -> date | None:
"""
解析同步起始日下界(环境变量 ORDER_DELIVERY_SYNC_DATE_FROM,YYYY-MM-DD,可选)。
用途与触发时机:run_sync 每轮同步开始时调用;正式环境配置上线日起只同步
订单日期 ≥ 边界的订单行,dev/test 不配置保持全量(需求 2026-10-09)。
约束:配置了但格式非法时 fail-closed 抛 ValueError 拒绝本轮同步——
绝不允许静默回退全量把历史数据抓进正式库。
Returns:
边界日期(含当日);未配置返回 None。
"""
raw = (os.getenv("ORDER_DELIVERY_SYNC_DATE_FROM") or "").strip()
if not raw:
return None
try:
return datetime.strptime(raw, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError(
f"ORDER_DELIVERY_SYNC_DATE_FROM 格式错误(应为 YYYY-MM-DD):{raw!r};"
"已拒绝执行同步以防止误抓边界外的历史数据"
) from exc
# 同步 upsert 只允许更新这些 ERP 快照列;触碰批次/锁定列会覆盖业务回复,禁止扩充业务列进来。
ERP_LINE_COLUMNS = (
"order_date",
@@ -147,27 +175,40 @@ class OrderDeliverySyncService:
return oracledb.connect(user=user, password=password, dsn=dsn)
@classmethod
def _fetch_page(cls, cursor, last_order_no: str | None) -> list[dict[str, Any]]:
def _fetch_page(
cls,
cursor,
last_order_no: str | None,
date_from: date | None = None,
) -> list[dict[str, Any]]:
"""
按 oea01 keyset 分页拉取一页订单行。
Args:
cursor: oracledb 游标。
last_order_no: 上一页最后一条订单单号;None 表示从头发起。
date_from: 起始日下界(含);None 表示不过滤。条件拼在内层视图
(ROWNUM 之前)——若加在外层会先截断再过滤造成每页缺行漏单。
Returns:
本页行字典列表(列为 sql.ORDER_DELIVERY_SQL 的别名)。
"""
# Oracle 空串即 NULL:首页不能带 `order_no > ''`(与 NULL 比较恒 UNKNOWN 会滤掉全部行),
# 因此首页与续页使用两个 SQL 变体。
binds: dict[str, Any] = {}
date_clause = ""
if date_from is not None:
date_clause = f" {ORDER_DELIVERY_DATE_FROM_CLAUSE}"
binds["order_date_from"] = date_from
if last_order_no:
page_sql = (
f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) "
f"SELECT * FROM ({ORDER_DELIVERY_SQL}{date_clause} ORDER BY a.oea01) "
f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}"
)
cursor.execute(page_sql, last_order_no=last_order_no)
binds["last_order_no"] = last_order_no
cursor.execute(page_sql, binds)
else:
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
cursor.execute(page_sql)
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL}{date_clause} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
cursor.execute(page_sql, binds)
columns = [col[0].lower() for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
@@ -230,6 +271,16 @@ class OrderDeliverySyncService:
Returns:
{"run_id", "status", "line_count"};并发冲突返回 status='skipped'。
"""
# 起始日边界先于抢锁解析:配置非法直接抛错(不写 sync_runs),防止误抓边界外历史数据
date_from = _resolve_sync_date_from()
if date_from:
logger.info(
"order-delivery-reply sync date-from boundary: %s (inclusive, order_date >= boundary)",
date_from.isoformat(),
)
else:
logger.info("order-delivery-reply sync date-from boundary: not configured (full sync)")
if not _sync_lock.acquire(blocking=False):
return {"run_id": None, "status": "skipped", "line_count": 0}
@@ -244,7 +295,7 @@ class OrderDeliverySyncService:
with conn.cursor() as cursor:
last_order_no: str | None = None
while True:
page = cls._fetch_page(cursor, last_order_no)
page = cls._fetch_page(cursor, last_order_no, date_from)
if not page:
break
hit_keys |= cls._upsert_page(page, synced_at)