chore(order-delivery-reply): 前端页面调整、细节修改、优化逻辑等
This commit is contained in:
1 parent
7fb36b301c
commit
36868f875c
36 files changed
+1577
-376
No files matched your search
@@ -147,8 +147,9 @@ def save_line_batches(order_no: str, line_no: int):
|
||||
用途与触发时机:单行弹窗「回复交期/修改回复」提交;联合回复保存逐行复用同一服务入口。
|
||||
|
||||
参数与输出约束:body {"batches": [{planned_date, qty, remark?}]};交期必填 YYYY-MM-DD、
|
||||
数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;超额(合计>未交)不拦截,
|
||||
由前端标「超」。已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。
|
||||
数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;各批次合计必须等于订单数量,
|
||||
不等返回 422 BATCH_QTY_TOTAL_MISMATCH(2026-09-23 由「超额仅提醒」修订)。
|
||||
已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
@@ -180,7 +181,8 @@ def batch_reply():
|
||||
用途与触发时机:勾选多行 →「+ 联合回复交期」→ 按行填批次 → 保存回复(R-REPLY-02)。
|
||||
|
||||
参数与输出约束:body {"items": [{order_no, line_no, batches: [{planned_date, qty, remark?}]}]},
|
||||
单次 ≤ 200 行;单行失败不回滚其它行,响应按行给 ok/error;
|
||||
单次 ≤ 200 行;每行各批次合计必须等于订单数量(不等该行失败,2026-09-23 修订);
|
||||
单行失败不回滚其它行,响应按行给 ok/error;
|
||||
全部行保存成功 success 才为 true 语义由 data.succeeded/failed 表达。
|
||||
"""
|
||||
user = _require_manage()
|
||||
|
||||
@@ -36,7 +36,7 @@ from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
# 企微事件开关名;与 settings.WECOM_NOTIFY_EVENTS 默认值条目一致(同 contract_payment_warning 命名风格)。
|
||||
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
|
||||
# 工作台跳转路由(前端第 8 步落地,带上该行查询参数直开行)。
|
||||
WORKSPACE_JUMP_PATH = "/workspace/order-delivery-reply"
|
||||
JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏
|
||||
|
||||
|
||||
def _load_line(order_no: str, line_no: int) -> OrderDeliveryErpLine:
|
||||
@@ -94,7 +94,7 @@ def _send_line_notification(line: OrderDeliveryErpLine, recipient: User) -> dict
|
||||
user=recipient,
|
||||
title="订单交期回复",
|
||||
content=f"您有订单号:项次{line.order_no}:{line.line_no}的订单需要填写/确认/查看交期。",
|
||||
jump_path=WORKSPACE_JUMP_PATH,
|
||||
jump_path=JUMP_PATH,
|
||||
jump_params={"order_no": line.order_no, "line_no": line.line_no},
|
||||
)
|
||||
|
||||
|
||||
@@ -76,6 +76,21 @@ def _locked_subquery():
|
||||
)
|
||||
|
||||
|
||||
def _reply_person_subquery(like: str):
|
||||
"""该订单行的交期回复人员(姓名/工号,存于行状态快照)命中关键词的 EXISTS 子查询。"""
|
||||
return (
|
||||
select(OrderDeliveryLineState.line_id)
|
||||
.where(
|
||||
OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id,
|
||||
or_(
|
||||
OrderDeliveryLineState.notified_user_name.ilike(like),
|
||||
OrderDeliveryLineState.notified_employee_id.ilike(like),
|
||||
),
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
def _base_query() -> Select:
|
||||
"""列表基础查询:只取未标 erp_missing 的已同步行(默认列表不展示已不在同步范围的行)。"""
|
||||
return select(OrderDeliveryErpLine).where(OrderDeliveryErpLine.erp_missing.is_(False))
|
||||
@@ -86,7 +101,8 @@ def _apply_filters(stmt: Select, params: dict[str, Any]) -> Select:
|
||||
应用列表筛选(AND 语义)与状态筛选下推。
|
||||
|
||||
核心逻辑:keyword 关键词合并搜索——订单单号/客户订单/客户编号/客户简称/公司全名/
|
||||
产品编号/品名/客户产品编号命中任一字段即返回(OR,工作台单搜索框口径);
|
||||
产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号,
|
||||
2026-09-23 增补,按行状态快照 EXISTS)命中任一字段即返回(OR,工作台单搜索框口径);
|
||||
order_date 精确单日;status=replied → 已锁定,
|
||||
status=not_fully_replied → 未锁定(未回复∪部分回复)。
|
||||
"""
|
||||
@@ -103,6 +119,9 @@ def _apply_filters(stmt: Select, params: dict[str, Any]) -> Select:
|
||||
OrderDeliveryErpLine.part_no.ilike(like),
|
||||
OrderDeliveryErpLine.part_name.ilike(like),
|
||||
OrderDeliveryErpLine.customer_part_no.ilike(like),
|
||||
OrderDeliveryErpLine.salesperson_name.ilike(like),
|
||||
OrderDeliveryErpLine.salesperson_code.ilike(like),
|
||||
_reply_person_subquery(like),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -8,9 +8,11 @@ backend/app/services/order_delivery_reply/reminder_service.py
|
||||
逻辑:[出货提醒] 已锁定(已回复)行的批次 planned_date 落在 [今天, 今天+N] 时,按业务员聚合
|
||||
发一条企微;同一 (行, 交期) 只提醒一次(audit_events action=ship_remind 去重),发送失败
|
||||
不落成功记录,次日扫描自动补发。
|
||||
[未回复提醒] 未锁定行的快照首次入库(created_at)距今 ≥ N 天时再次提醒生管(收件人 =
|
||||
排程任务 notify_user_ids_json),同一行每 N 天最多提醒一次(action=unreplied_remind 去重),
|
||||
多行聚合成一条通知避免刷屏。提醒只读业务数据 + 写审计,绝不改动批次/锁定状态。
|
||||
[未回复提醒] 未锁定行的订单日期(order_date,取 ERP oea02)距今 ≥ N 天时再次提醒生管
|
||||
(收件人 = 任务参数 unreplied_remind_user_ids,留空回退任务通知人),同一行每 N 天最多
|
||||
提醒一次(action=unreplied_remind 去重),多行聚合成一条通知避免刷屏。
|
||||
提醒只读业务数据 + 写审计,绝不改动批次/锁定状态。
|
||||
(2026-09-23 修订:超期锚点由快照首次入库 created_at 改为订单日期,按业务确认以订单日期计超期。)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -33,7 +35,7 @@ from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
# 企微事件开关名:与行级通知共用同一事件(WECOM_NOTIFY_EVENTS 已包含,无需新增配置)。
|
||||
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
|
||||
WORKSPACE_JUMP_PATH = "/workspace/order-delivery-reply"
|
||||
JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏
|
||||
|
||||
# 通知正文最多列出的订单条数;超出的折叠为「…等 N 笔」,避免超出企微卡片描述上限。
|
||||
MAX_LISTED_ORDERS = 8
|
||||
@@ -125,7 +127,7 @@ def _send_remind_card(user: User, content: str, jump_params: dict[str, Any] | No
|
||||
user=user,
|
||||
title="订单交期回复",
|
||||
content=content,
|
||||
jump_path=WORKSPACE_JUMP_PATH,
|
||||
jump_path=JUMP_PATH,
|
||||
jump_params=jump_params,
|
||||
)
|
||||
return {"ok": bool(result.get("ok")), "trace_id": result.get("trace_id"), "reason": result.get("reason")}
|
||||
@@ -222,7 +224,8 @@ def run_ship_reminders(advance_days: int) -> dict[str, Any]:
|
||||
content = (
|
||||
f"您有 {len(bucket['entries'])} 笔订单将在 {advance_days} 天内交货,请及时安排出货:\n{lines_text}"
|
||||
)
|
||||
result = _send_remind_card(user, content)
|
||||
# 卡片带 status=replied:业务员点开直达「已回复」视图(出货提醒行必然已回复锁定)。
|
||||
result = _send_remind_card(user, content, jump_params={"status": "replied"})
|
||||
if result["ok"]:
|
||||
notified_persons += 1
|
||||
notified_lines += len(bucket["line_ids"])
|
||||
@@ -258,10 +261,11 @@ def run_ship_reminders(advance_days: int) -> dict[str, Any]:
|
||||
|
||||
def run_unreplied_reminders(unreplied_days: int, notify_user_ids: list[int]) -> dict[str, Any]:
|
||||
"""
|
||||
未回复再提醒:超 N 天仍未回复的订单行,聚合提醒生管(收件人 = 排程任务通知人配置)。
|
||||
未回复再提醒:订单日期距今超 N 天仍未回复的订单行,聚合提醒生管(收件人 = 排程任务通知人配置)。
|
||||
|
||||
核心逻辑:[STEP 1] 候选 = 未锁定且未标 erp_missing、快照首次入库(created_at)距今
|
||||
≥ unreplied_days 的行;[STEP 2] 同行距上次提醒 ≥ unreplied_days 才再次提醒
|
||||
核心逻辑:[STEP 1] 候选 = 未锁定且未标 erp_missing、订单日期(order_date)距今
|
||||
≥ unreplied_days 的行(订单日期为空不参与提醒);
|
||||
[STEP 2] 同行距上次提醒 ≥ unreplied_days 才再次提醒
|
||||
(audit action=unreplied_remind 的 max(created_at) 控制,未提醒过则立即提醒);
|
||||
[STEP 3] 汇总为一
|
||||
条企微发给每个配置的生管收件人;无收件人时跳过并如实返回。
|
||||
@@ -269,7 +273,7 @@ def run_unreplied_reminders(unreplied_days: int, notify_user_ids: list[int]) ->
|
||||
{"unreplied_days", "due_lines", "notified_recipients", "failed_recipients", "skipped_no_recipient"}。
|
||||
"""
|
||||
today = _business_today()
|
||||
threshold_dt = datetime.utcnow() - timedelta(days=max(0, int(unreplied_days)))
|
||||
threshold_date = today - timedelta(days=max(0, int(unreplied_days)))
|
||||
|
||||
locked_subq = (
|
||||
select(OrderDeliveryLineState.line_id)
|
||||
@@ -283,9 +287,12 @@ def run_unreplied_reminders(unreplied_days: int, notify_user_ids: list[int]) ->
|
||||
.where(
|
||||
OrderDeliveryErpLine.erp_missing.is_(False),
|
||||
~locked_subq,
|
||||
OrderDeliveryErpLine.created_at <= threshold_dt,
|
||||
# 超期锚点 = ERP 订单日期(oea02,2026-09-23 由 created_at 改来,按业务确认口径):
|
||||
# 订单日期距今 ≥ N 天仍未锁定即入选;订单日期为空无法判定,不参与提醒。
|
||||
OrderDeliveryErpLine.order_date.is_not(None),
|
||||
OrderDeliveryErpLine.order_date <= threshold_date,
|
||||
)
|
||||
.order_by(OrderDeliveryErpLine.created_at.asc())
|
||||
.order_by(OrderDeliveryErpLine.order_date.asc())
|
||||
).all()
|
||||
)
|
||||
if not due_lines:
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/app/services/order_delivery_reply/reply_service.py
|
||||
用途:订单交期回复的写路径——单行/联合保存交期批次(未锁定行整表替换)。
|
||||
依赖:models/order_delivery_reply(快照/批次/状态/审计)、extensions.db、core.errors。
|
||||
逻辑:保存与通知是两步(需求 §5):本服务只写批次与 save 审计,不通知、不锁定;
|
||||
已锁定行拒绝写入(409);批次校验(交期必填、数量>0、备注≤200)在此层完成。
|
||||
已锁定行拒绝写入(409);批次校验(交期必填、数量>0、备注≤200、各批次合计必须
|
||||
等于订单数量——2026-09-23 由「超额仅提醒」修订,BATCH_QTY_TOTAL_MISMATCH)在此层完成。
|
||||
后续通知/锁定在 notify_service 中与企微发送同事务实现,禁止在本文件锁定。
|
||||
"""
|
||||
|
||||
@@ -136,9 +137,10 @@ def save_batches(order_no: str, line_no: int, raw_batches: Any, operator_user_id
|
||||
AI/排程不触发本函数(无自动回复语义)。
|
||||
|
||||
核心逻辑:[STEP 1] 校验批次结构(_parse_batches);
|
||||
[STEP 2] get_line_for_write 确认行存在且未锁定;
|
||||
[STEP 2] get_line_for_write 确认行存在且未锁定;数量守恒校验:各批次合计必须
|
||||
等于订单数量(2026-09-23 由「超额仅提醒」修订),不等抛 422 BATCH_QTY_TOTAL_MISMATCH;
|
||||
[STEP 3] 事务内删除旧批次、按序号写入新批次;
|
||||
[STEP 4] 写 action=save 审计(含批次快照,超额不拦截只留痕,展示层标「超」)。
|
||||
[STEP 4] 写 action=save 审计(含批次快照)。
|
||||
保存后行仍为部分回复;通知与锁定走 notify 路径,本函数不触碰 line_states。
|
||||
|
||||
Args:
|
||||
@@ -151,6 +153,16 @@ def save_batches(order_no: str, line_no: int, raw_batches: Any, operator_user_id
|
||||
normalized = _parse_batches(raw_batches)
|
||||
line, _state = get_line_for_write(order_no, line_no)
|
||||
|
||||
# [STEP 2] 数量守恒:各批次合计必须等于订单数量(保存口径 2026-09-23 修订,原允许超额仅提醒);
|
||||
# 校验在任何写操作之前,失败时不落批次也不落审计。
|
||||
total_qty = sum((batch["qty"] for batch in normalized), Decimal(0))
|
||||
order_qty = line.qty if line.qty is not None else Decimal(0)
|
||||
if total_qty != order_qty:
|
||||
raise ValidationError(
|
||||
f"各批次数量合计({total_qty})必须等于订单数量({order_qty}),请调整后重新保存",
|
||||
code="ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH",
|
||||
)
|
||||
|
||||
# [STEP 3] 整表替换:未锁定行的旧批次全部作废,以本次提交为准。
|
||||
db.session.query(OrderDeliveryBatch).filter(OrderDeliveryBatch.line_id == line.id).delete()
|
||||
for seq, batch in enumerate(normalized, start=1):
|
||||
@@ -165,7 +177,6 @@ def save_batches(order_no: str, line_no: int, raw_batches: Any, operator_user_id
|
||||
)
|
||||
)
|
||||
|
||||
total_qty = sum((batch["qty"] for batch in normalized), Decimal(0))
|
||||
db.session.add(
|
||||
OrderDeliveryAuditEvent(
|
||||
line_id=line.id,
|
||||
|
||||
@@ -53,6 +53,44 @@ ERP_LINE_COLUMNS = (
|
||||
|
||||
_FETCH_SIZE = 500
|
||||
|
||||
_thick_init_lock = threading.Lock()
|
||||
_thick_initialized = False
|
||||
|
||||
|
||||
def _ensure_thick_client(oracledb) -> None:
|
||||
"""按 ORACLE_CLIENT_LIB_DIR(或 backend/oracle_client 约定)初始化 thick 模式;幂等且失败不掩埋。"""
|
||||
global _thick_initialized
|
||||
with _thick_init_lock:
|
||||
if _thick_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
|
||||
_thick_initialized = True
|
||||
return
|
||||
candidates = []
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
if env_dir:
|
||||
candidates.append(os.path.normpath(env_dir))
|
||||
backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
candidates.append(os.path.join(backend_dir, "oracle_client"))
|
||||
marker = {"oci.dll", "libclntsh.so", "libclntsh.dylib"}
|
||||
lib_dir = None
|
||||
for root in candidates:
|
||||
if not root or not os.path.isdir(root):
|
||||
continue
|
||||
if marker & {n.lower() for n in os.listdir(root)}:
|
||||
lib_dir = root
|
||||
break
|
||||
sub = [d for d in os.listdir(root) if d.startswith("instantclient_") and os.path.isdir(os.path.join(root, d))]
|
||||
if sub:
|
||||
lib_dir = os.path.join(root, sub[0])
|
||||
break
|
||||
if lib_dir:
|
||||
os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "")
|
||||
if hasattr(os, "add_dll_directory"):
|
||||
os.add_dll_directory(lib_dir)
|
||||
oracledb.init_oracle_client(lib_dir=lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
_thick_initialized = True
|
||||
|
||||
# 进程内互斥:同一 worker 同时只跑一个同步(多 worker 由 sync_runs running 行兜底,一期单机足够)。
|
||||
_sync_lock = threading.Lock()
|
||||
|
||||
@@ -82,8 +120,6 @@ class OrderDeliverySyncService:
|
||||
"""
|
||||
import oracledb
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
user = (
|
||||
os.getenv("ERP_DB_USER")
|
||||
or os.getenv("ERP_USERNAME")
|
||||
@@ -104,8 +140,10 @@ class OrderDeliverySyncService:
|
||||
try:
|
||||
return oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
except oracledb.DatabaseError:
|
||||
# thin 模式连不上时按 Text2SQL 既有路径切 thick(本地 Instant Client)。
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
# thin 模式连不上(topprod 为 11g 必走 thick):用 ORACLE_CLIENT_LIB_DIR 自初始化,
|
||||
# 不再依赖 services/text2sql——worker 进程 sys.path 差异曾致
|
||||
# "No module named app.services.text2sql"(2026-09-22 排程同步失败根因)。
|
||||
_ensure_thick_client(oracledb)
|
||||
return oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -64,11 +64,27 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
def _hxops_users_options() -> list[dict[str, Any]]:
|
||||
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
||||
from app.models import User
|
||||
|
||||
users = User.query.filter(User.status == "active").order_by(User.real_name.asc(), User.id.asc()).all()
|
||||
return [
|
||||
{
|
||||
"label": f"{u.real_name or u.username}({u.employee_id or '-'})",
|
||||
"value": u.id,
|
||||
"description": u.department or None,
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
|
||||
|
||||
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
|
||||
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"agent_apps": _agent_apps_options,
|
||||
"shipping_inventory_sources": _shipping_inventory_sources_options,
|
||||
"shipping_receipt_sources": _shipping_receipt_sources_options,
|
||||
"hxops_users": _hxops_users_options,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -173,15 +173,31 @@ def _register_builtin_platform_jobs() -> None:
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="order-delivery-sync", label="订单交期回复 ERP 同步", handler=run_order_delivery_sync_schedule,
|
||||
description="每天 07:00 全量同步已审核、已核准、未结案的 ERP 销售订单行快照;同步成功后按任务通知配置提醒生管查看回复。",
|
||||
description=(
|
||||
"每天 07:00 全量同步已审核、已核准、未结案的 ERP 销售订单行快照;"
|
||||
"同步成功后按任务参数「同步完成提醒收件人」提醒生管查看回复(未配置时回退本任务通知人)。"
|
||||
),
|
||||
category="order_delivery_reply",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "sync_remind_user_ids",
|
||||
"type": "multi_select",
|
||||
"label": "同步完成提醒收件人(生管)",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "hxops_users",
|
||||
"help": "同步完成提醒的生管收件人,可从全部启用用户中搜索选择;"
|
||||
"与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。",
|
||||
},
|
||||
),
|
||||
defaults={"sync_remind_user_ids": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="order-delivery-remind", label="订单交期回复 提醒", handler=run_order_delivery_remind_schedule,
|
||||
description=(
|
||||
"每天扫描:已回复行按回复交期提前 N 天企微提醒对应业务员出货;"
|
||||
"超 N 天未回复的行再次企微提醒生管(收件人取本任务通知人配置)。"
|
||||
"两类提醒可通过任务参数独立启停。"
|
||||
"超 N 天未回复的行再次企微提醒生管(收件人取任务参数「未回复提醒收件人」,"
|
||||
"未配置时回退本任务通知人)。两类提醒可通过任务参数独立启停。"
|
||||
),
|
||||
category="order_delivery_reply",
|
||||
params_schema=(
|
||||
@@ -199,7 +215,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"label": "出货提醒提前天数",
|
||||
"required": False,
|
||||
"default": DEFAULT_SHIP_ADVANCE_DAYS,
|
||||
"help": "已回复订单的回复交期距今 ≤ 该天数时,企微提醒对应业务员安排出货。",
|
||||
"help": "已回复订单的回复交期距今 ≤ 该天数时,企微提醒对应业务员安排出货。取值 0-3650。",
|
||||
},
|
||||
{
|
||||
"key": "unreplied_remind_enabled",
|
||||
@@ -215,7 +231,17 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"label": "未回复再次提醒天数",
|
||||
"required": False,
|
||||
"default": DEFAULT_UNREPLIED_DAYS,
|
||||
"help": "订单行超过该天数仍未回复交期时再次提醒生管;同一行每达到该天数最多提醒一次。",
|
||||
"help": "订单日期距今超过该天数仍未回复交期时再次提醒生管;同一行每达到该天数最多提醒一次。取值 0-3650。",
|
||||
},
|
||||
{
|
||||
"key": "unreplied_remind_user_ids",
|
||||
"type": "multi_select",
|
||||
"label": "未回复提醒收件人(生管)",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "hxops_users",
|
||||
"help": "超期未回复提醒的生管收件人,可从全部启用用户中搜索选择;"
|
||||
"与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。",
|
||||
},
|
||||
),
|
||||
defaults={
|
||||
@@ -223,6 +249,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"ship_remind_advance_days": DEFAULT_SHIP_ADVANCE_DAYS,
|
||||
"unreplied_remind_enabled": DEFAULT_UNREPLIED_REMIND_ENABLED,
|
||||
"unreplied_remind_days": DEFAULT_UNREPLIED_DAYS,
|
||||
"unreplied_remind_user_ids": [],
|
||||
},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
|
||||
@@ -8,7 +8,10 @@ backend/app/services/schedule/order_delivery_remind_job.py
|
||||
逻辑:从 task.job_params 读取配置(管理端排程表单「任务参数」可改,均有默认值):
|
||||
ship_remind_enabled / unreplied_remind_enabled 布尔开关独立启停两类提醒;
|
||||
ship_remind_advance_days 默认 3、unreplied_remind_days 默认 3。
|
||||
未回复提醒收件人取任务 notify_user_ids_json(notify_enabled 开关控制)。
|
||||
未回复提醒收件人优先取 job_params 的 unreplied_remind_user_ids(管理端「未回复提醒收件人」
|
||||
多选参数,与平台运行结果通知的「通知人」互相独立);未配置时回退任务 notify_user_ids_json
|
||||
兼容旧配置。天数统一钳制在 0-3650,防止表单误填巨大值导致 today+timedelta 溢出
|
||||
(OverflowError: date value out of range,2026-09-22 出货提醒扫描事故根因)。
|
||||
两个扫描互相独立:单个扫描抛错回滚后继续另一个,最终把错误计入 errors
|
||||
(failed_count>0 时平台排程标 partial_failed/failed,不影响数据快照);
|
||||
开关关闭的一侧直接跳过(summary 记 skipped=disabled),不影响另一侧。
|
||||
@@ -29,18 +32,37 @@ SHIP_REMIND_ADVANCE_DAYS_KEY = "ship_remind_advance_days"
|
||||
UNREPLIED_REMIND_DAYS_KEY = "unreplied_remind_days"
|
||||
DEFAULT_SHIP_REMIND_ENABLED = True
|
||||
DEFAULT_UNREPLIED_REMIND_ENABLED = True
|
||||
DEFAULT_UNREPLIED_USER_IDS_KEY = "unreplied_remind_user_ids"
|
||||
DEFAULT_SHIP_ADVANCE_DAYS = 3
|
||||
DEFAULT_UNREPLIED_DAYS = 3
|
||||
# 天数上限(约 10 年):date + timedelta 超过 9999 年会抛 OverflowError: date value out of range。
|
||||
MAX_REMIND_DAYS = 3650
|
||||
|
||||
|
||||
def _read_days(task: ScheduleTask, key: str, default: int) -> int:
|
||||
"""读取 job_params 中的天数配置;非法值回退默认(参数类型已由契约层校验)。"""
|
||||
"""读取 job_params 中的天数配置;非法值回退默认,并钳制到 [0, MAX_REMIND_DAYS]。
|
||||
|
||||
上限原因:today + timedelta(days=N) 在 N 巨大时溢出抛
|
||||
OverflowError: date value out of range(2026-09-22 出货提醒扫描失败根因)。
|
||||
"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
try:
|
||||
value = int(params.get(key, default))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return value if value >= 0 else default
|
||||
return min(max(value, 0), MAX_REMIND_DAYS)
|
||||
|
||||
|
||||
def _read_unreplied_recipients(task: ScheduleTask) -> list[int]:
|
||||
"""读取未回复提醒的生管收件人:优先任务参数多选名单,留空回退任务通知人(旧配置兼容)。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
raw = params.get(DEFAULT_UNREPLIED_USER_IDS_KEY)
|
||||
ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else []
|
||||
if ids:
|
||||
return ids
|
||||
if task.notify_enabled:
|
||||
return [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
|
||||
return []
|
||||
|
||||
|
||||
def _read_bool(task: ScheduleTask, key: str, default: bool) -> bool:
|
||||
@@ -95,11 +117,11 @@ def run_order_delivery_remind_schedule(task: ScheduleTask, run: ScheduleRun) ->
|
||||
else:
|
||||
ship_result = {"skipped": "disabled", "advance_days": advance_days}
|
||||
|
||||
notify_user_ids = [int(uid) for uid in (task.notify_user_ids_json or []) if uid] if task.notify_enabled else []
|
||||
unreplied_recipients = _read_unreplied_recipients(task)
|
||||
if unreplied_enabled:
|
||||
unreplied_result = _run_scan(errors, "未回复提醒", lambda: run_unreplied_reminders(unreplied_days, notify_user_ids))
|
||||
unreplied_result = _run_scan(errors, "未回复提醒", lambda: run_unreplied_reminders(unreplied_days, unreplied_recipients))
|
||||
if unreplied_result.get("skipped_no_recipient"):
|
||||
errors.append("存在超期未回复订单,但该排程未配置生管通知人(通知开关关闭或名单为空),未发送提醒")
|
||||
errors.append("存在超期未回复订单,但未配置「未回复提醒收件人」(且任务通知人未配置或开关关闭),未发送提醒")
|
||||
else:
|
||||
unreplied_result = {"skipped": "disabled", "unreplied_days": unreplied_days}
|
||||
|
||||
@@ -120,6 +142,7 @@ def run_order_delivery_remind_schedule(task: ScheduleTask, run: ScheduleRun) ->
|
||||
"unreplied_remind_enabled": unreplied_enabled,
|
||||
"advance_days": advance_days,
|
||||
"unreplied_days": unreplied_days,
|
||||
"unreplied_recipients": unreplied_recipients,
|
||||
}
|
||||
step_logs = [{"step": "order_delivery_remind", "status": "success" if failed == 0 else "partial", "detail": summary}]
|
||||
return (total, success, failed, skipped, [summary], errors, step_logs)
|
||||
@@ -5,8 +5,9 @@ backend/app/services/schedule/order_delivery_reply_job.py
|
||||
依赖:services/order_delivery_reply/sync_service(同步本体)、notify_service(企微事件类型与跳转路径)、
|
||||
wecom_notify.send_wecom_event_message、ScheduleTask/ScheduleRun。
|
||||
逻辑:排程 worker 每天 07:00(Asia/Shanghai)触发 handler,内部以 trigger='scheduled'
|
||||
复用与手动刷新完全相同的 run_sync;同步成功后按任务「通知开关 + 通知人」配置
|
||||
(notify_enabled / notify_user_ids_json,管理端排程表单现成字段)给生管发提醒,
|
||||
复用与手动刷新完全相同的 run_sync;同步成功后按任务参数 sync_remind_user_ids
|
||||
(管理端「同步完成提醒收件人」多选,与运行结果通知的「通知人」互相独立;
|
||||
留空回退 notify_user_ids_json 兼容旧配置)给生管发提醒,
|
||||
并把 domain_notification_managed 写入 run 摘要,抑制通用「排程执行结果」通知避免重复;
|
||||
通知失败不改变同步结果(同步已成功落库,仅记录失败原因)。
|
||||
同步失败向上抛出,由平台排程标记本次运行失败并保留上次快照(sync_runs 已各自留痕)。
|
||||
@@ -21,25 +22,38 @@ from app.models import ScheduleRun, ScheduleTask, User
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
SYNC_REMIND_USER_IDS_KEY = "sync_remind_user_ids"
|
||||
|
||||
|
||||
def _read_sync_remind_recipients(task: ScheduleTask) -> list[int]:
|
||||
"""同步完成提醒收件人:优先任务参数 sync_remind_user_ids,留空回退任务通知人(旧配置兼容)。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
raw = params.get(SYNC_REMIND_USER_IDS_KEY)
|
||||
ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else []
|
||||
if ids:
|
||||
return ids
|
||||
if task.notify_enabled:
|
||||
return [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
|
||||
return []
|
||||
|
||||
|
||||
def _notify_production_after_sync(task: ScheduleTask, line_count: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
同步成功后提醒生管查看订单交期回复(通知人 = 排程任务配置的 notify_user_ids_json)。
|
||||
同步成功后提醒生管查看订单交期回复(收件人 = 任务参数 sync_remind_user_ids,回退通知人)。
|
||||
|
||||
Args:
|
||||
task: 触发本次同步的排程任务(读取 notify_enabled 与通知人列表)。
|
||||
task: 触发本次同步的排程任务。
|
||||
line_count: 本次同步的订单行数量,用于通知文案。
|
||||
Returns:
|
||||
逐人发送结果列表 [{user_id, ok, reason?}];未配置通知人时返回空列表。
|
||||
逐人发送结果列表 [{user_id, ok, reason?}];未配置收件人时返回空列表。
|
||||
"""
|
||||
from app.services.order_delivery_reply.notify_service import (
|
||||
WECOM_EVENT_TYPE,
|
||||
WORKSPACE_JUMP_PATH,
|
||||
JUMP_PATH,
|
||||
)
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
if not task.notify_enabled:
|
||||
return []
|
||||
user_ids = [int(uid) for uid in (task.notify_user_ids_json or []) if uid]
|
||||
user_ids = _read_sync_remind_recipients(task)
|
||||
if not user_ids:
|
||||
return []
|
||||
|
||||
@@ -51,7 +65,9 @@ def _notify_production_after_sync(task: ScheduleTask, line_count: int) -> list[d
|
||||
user=user,
|
||||
title="订单交期回复",
|
||||
content=f"今日订单交期数据已同步完成(共 {line_count} 行),请及时查看并回复交期。",
|
||||
jump_path=WORKSPACE_JUMP_PATH,
|
||||
jump_path=JUMP_PATH,
|
||||
# 卡片带 status=not_fully_replied:生管点开直达「未完全回复」视图(待回复行)。
|
||||
jump_params={"status": "not_fully_replied"},
|
||||
)
|
||||
entry: dict[str, Any] = {"user_id": user.id, "ok": bool(result.get("ok"))}
|
||||
if not entry["ok"]:
|
||||
@@ -77,8 +93,10 @@ def run_order_delivery_sync_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
count = int(summary.get("line_count") or 0)
|
||||
|
||||
# [STEP 2] 域内已自行通知生管:写入标记,抑制通用「排程执行结果」企微通知避免双重打扰。
|
||||
run.response_summary_json = {"domain_notification_managed": True}
|
||||
db.session.commit()
|
||||
# 直调(run=None,脚本/测试)时跳过 run 摘要写入。
|
||||
if run is not None:
|
||||
run.response_summary_json = {"domain_notification_managed": True}
|
||||
db.session.commit()
|
||||
|
||||
notify_results = _notify_production_after_sync(task, count)
|
||||
failed_notify = [item for item in notify_results if not item["ok"]]
|
||||
|
||||
Reference in new issue
Block a user