Compare commits
85
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
537e3e18f0 | ||
|
|
2e8405e2f0 | ||
|
|
b2fe9b78e2 | ||
|
|
8336ab6349 | ||
|
|
d64a49548f | ||
|
|
81eeef944f | ||
|
|
60a8b20bf9 | ||
|
|
638a46ad0d | ||
|
|
1b3b63df24 | ||
|
|
eb468d3c78 | ||
|
|
8e73031e42 | ||
|
|
4105fd92f2 | ||
|
|
dd3a671a3d | ||
|
|
ee2b7cdb7e | ||
|
|
26f25d88c0 | ||
|
|
90166068ee | ||
|
|
bf44a5a70e | ||
|
|
be49b44004 | ||
|
|
8c3df85b2e | ||
|
|
97c46625e4 | ||
|
|
d4c30b5825 | ||
|
|
836ddea84d | ||
|
|
c99513092a | ||
|
|
34ad40778b | ||
|
|
859f20eb00 | ||
|
|
d5f988a16c | ||
|
|
26d213c05b | ||
|
|
f269df7941 | ||
|
|
3710aa4d81 | ||
|
|
02aa00e913 | ||
|
|
f0334e5d22 | ||
|
|
b02b776a97 | ||
|
|
81d82a88d5 | ||
|
|
a10ecc8073 | ||
|
|
79050d02ba | ||
|
|
f5611d6783 | ||
|
|
70c7f03a5a | ||
|
|
e8ad4cc743 | ||
|
|
37b743d5d3 | ||
|
|
ade440d004 | ||
|
|
440afe097f | ||
|
|
3f025fbb9b | ||
|
|
dfd48e08e7 | ||
|
|
ed18907e95 | ||
|
|
a91f26f753 | ||
|
|
00c52fdaae | ||
|
|
b64ed9b792 | ||
|
|
6eb4c76beb | ||
|
|
0331029ead | ||
|
|
29315cab20 | ||
|
|
b31e887b2a | ||
|
|
d094d8eb83 | ||
|
|
5d0a79f5fb | ||
|
|
3bb9938c05 | ||
|
|
fa5d316b25 | ||
|
|
95e7db0831 | ||
|
|
724cd74043 | ||
|
|
31434f8424 | ||
|
|
627da80e65 | ||
|
|
9dd7184aa7 | ||
|
|
ec47e012a7 | ||
|
|
63a86f8944 | ||
|
|
0c27b81654 | ||
|
|
ace836c1af | ||
|
|
2cee02bec1 | ||
|
|
194a51bc2d | ||
|
|
11cfedcc62 | ||
|
|
e421d2607d | ||
|
|
a5d7085c08 | ||
|
|
050987692a | ||
|
|
19d6b234ea | ||
|
|
68c944607c | ||
|
|
d75f2e7d86 | ||
|
|
b8fe089b3d | ||
|
|
3e8b12b954 | ||
|
|
6502f73cb5 | ||
|
|
1a2753d3b5 | ||
|
|
2250ac98e6 | ||
|
|
5f9df244c0 | ||
|
|
3b53a2219c | ||
|
|
5187b6105b | ||
|
|
570d1c605c | ||
|
|
396f17a15a | ||
|
|
f7361905b7 | ||
|
|
48fe19ed71 |
No files matched your search
@@ -18,4 +18,4 @@ globs: frontend/src/features/admin/**/*.vue,frontend/src/features/kb/components/
|
|||||||
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
|
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
|
||||||
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
|
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
|
||||||
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
|
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
|
||||||
- 字号和颜色用 `element-trial.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
- 字号和颜色用 `shared/styles/element-theme.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
|
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
|
||||||
|
|
||||||
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
|
- [ ] 只在该页入口引入 Element 样式。全站皮肤用 `element-theme.css`;管理列表用 `element-trial.css`(已包含全站皮肤)。不要再包 `ElConfigProvider`。
|
||||||
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
|
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
|
||||||
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
|
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
|
||||||
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
|
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
|
||||||
|
|||||||
@@ -101,6 +101,10 @@ backend/data/freight_rpa/
|
|||||||
backend/data/shipping_notice/
|
backend/data/shipping_notice/
|
||||||
backend/data/logs/
|
backend/data/logs/
|
||||||
backend/data/logs/*.log
|
backend/data/logs/*.log
|
||||||
|
backend/data/logs/*.log
|
||||||
|
# ERP HRAO 部门导入的本地数据(CSV 导出与真实公司映射不入库,模板 *.example.json 保留)
|
||||||
|
backend/scripts/data/*.csv
|
||||||
|
backend/scripts/data/hrao_company_map.json
|
||||||
|
|
||||||
# Engramory live memory store (plain text, machine-local)
|
# Engramory live memory store (plain text, machine-local)
|
||||||
/.engramory-memory/
|
/.engramory-memory/
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/admin/departments.py
|
backend/app/api/admin/departments.py
|
||||||
|
|
||||||
用途:管理后台部门 CRUD API(薄路由层)。
|
用途:管理后台部门 CRUD API(薄路由层,树形结构)。
|
||||||
依赖:admin.blueprint、services/admin/department_service。
|
依赖:admin.blueprint、services/admin/department_service。
|
||||||
逻辑:/departments* 路由。
|
逻辑:/departments 平铺列表(兼容旧消费方)、/departments/tree 树、成员名单(支持含下级)。
|
||||||
"""
|
"""
|
||||||
from flask import jsonify, request
|
from flask import jsonify, request
|
||||||
|
|
||||||
@@ -15,10 +15,17 @@ from app.services.admin import department_service
|
|||||||
@admin_bp.route('/departments', methods=['GET'])
|
@admin_bp.route('/departments', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def list_departments():
|
def list_departments():
|
||||||
"""返回全部部门列表。"""
|
"""返回全部部门平铺列表(旧消费方兼容:部门下拉等)。"""
|
||||||
return jsonify(department_service.list_departments())
|
return jsonify(department_service.list_departments())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/departments/tree', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def department_tree():
|
||||||
|
"""返回完整部门树(children 嵌套,成员数含下级递归汇总)。"""
|
||||||
|
return jsonify(department_service.list_department_tree())
|
||||||
|
|
||||||
|
|
||||||
@admin_bp.route('/departments', methods=['POST'])
|
@admin_bp.route('/departments', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def create_department():
|
def create_department():
|
||||||
@@ -31,8 +38,15 @@ def create_department():
|
|||||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def list_department_members(id: int):
|
def list_department_members(id: int):
|
||||||
"""返回部门员工数量与名单。"""
|
"""部门员工分页名单(OA 组织面板口径):include_descendants=1 含下级,keyword 搜姓名/工号/邮箱/手机。"""
|
||||||
return jsonify(department_service.list_department_members(id))
|
include_descendants = request.args.get('include_descendants', '') in ('1', 'true')
|
||||||
|
return jsonify(department_service.list_department_members(
|
||||||
|
id,
|
||||||
|
include_descendants,
|
||||||
|
keyword=request.args.get('keyword', ''),
|
||||||
|
page=request.args.get('page', 1, type=int),
|
||||||
|
page_size=request.args.get('page_size', 20, type=int),
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ backend/app/api/admin/reports.py
|
|||||||
依赖:admin.blueprint、services/admin/report_service。
|
依赖:admin.blueprint、services/admin/report_service。
|
||||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||||
"""
|
"""
|
||||||
from flask import jsonify, request
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from flask import Response, jsonify, request
|
||||||
|
|
||||||
from app.api.admin.blueprint import admin_bp
|
from app.api.admin.blueprint import admin_bp
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
@@ -134,3 +136,15 @@ def issue_analysis():
|
|||||||
def close_general_feedback(feedback_id: int):
|
def close_general_feedback(feedback_id: int):
|
||||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def general_feedback_image_raw(feedback_id: int, image_id: int):
|
||||||
|
"""代理输出意见反馈截图字节流(inline 展示用)。"""
|
||||||
|
payload = report_service.get_general_feedback_image_payload(feedback_id, image_id)
|
||||||
|
resp = Response(payload['data'], mimetype=payload['mime_type'])
|
||||||
|
# [SECURITY] Content-Type 已按扩展名白名单收敛,仍禁浏览器嗅探,双保险防内联渲染为 HTML
|
||||||
|
resp.headers['X-Content-Type-Options'] = 'nosniff'
|
||||||
|
resp.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(payload['filename'])}"
|
||||||
|
return resp
|
||||||
@@ -43,7 +43,7 @@ def _ok(data, *, status: int = 200):
|
|||||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
|
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def list_shipping_rpa_profiles():
|
def list_shipping_rpa_profiles():
|
||||||
"""列出脱敏后的 RPA Profile 配置。"""
|
"""列出 RPA Profile;响应含用户名明文,不含密码与密文。"""
|
||||||
return _ok(freight_rpa_source_admin_service.list_profiles())
|
return _ok(freight_rpa_source_admin_service.list_profiles())
|
||||||
|
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ def create_shipping_rpa_profile():
|
|||||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def update_shipping_rpa_profile(profile_id: int):
|
def update_shipping_rpa_profile(profile_id: int):
|
||||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
"""更新 RPA Profile;用户名与已存明文相同、或密码留空时不重写对应密文。"""
|
||||||
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from flask import Blueprint
|
|||||||
chat_bp = Blueprint('chat', __name__)
|
chat_bp = Blueprint('chat', __name__)
|
||||||
|
|
||||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
from . import assets, capability_list, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||||
from .shared import ( # noqa: E402, F401
|
from .shared import ( # noqa: E402, F401
|
||||||
CHAT_USER_ATTACHMENT_LIMIT,
|
CHAT_USER_ATTACHMENT_LIMIT,
|
||||||
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
api/chat/capability_list.py
|
||||||
|
|
||||||
|
用途:聊天端「知识库内容清单」查询接口,作为知识库未命中兜底回复按钮的数据源。
|
||||||
|
依赖:chat.shared(公共上下文与异常)、chat_bp、services.chat.capability_list。
|
||||||
|
逻辑:GET /api/chat/capability-list?agent_id=...,经 require_agent_permission 鉴权后
|
||||||
|
返回常用问题中该应用「能力清单条目」的标准答案;未配置时抛 404 业务错误。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .shared import * # noqa: F403
|
||||||
|
from . import chat_bp
|
||||||
|
from app.services.chat.capability_list import get_agent_capability_list
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/capability-list', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_capability_list():
|
||||||
|
"""
|
||||||
|
获取当前应用的知识库内容清单。
|
||||||
|
用途:AI 回复命中知识库未命中兜底语句时,前端【知识库内容清单】按钮点击后调用。
|
||||||
|
核心逻辑:
|
||||||
|
1. require_agent_permission 从 query 读取 agent_id 并校验用户对该应用的访问权限;
|
||||||
|
2. 委托 services.chat.capability_list 返回「能力清单条目」标准答案;
|
||||||
|
3. 未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND(404),前端按错误码本地化提示。
|
||||||
|
参数约束:agent_id 必须来自当前会话路由(当前聊天应用),禁止跨应用探测他人条目。
|
||||||
|
"""
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
if agent is None:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent context', http_status=500)
|
||||||
|
return jsonify(get_agent_capability_list(agent))
|
||||||
@@ -5,7 +5,7 @@ backend/app/api/contract_payment/__init__.py
|
|||||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||||
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
|
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。四个付款阶段未付时都可手动标为已付。
|
||||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||||
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||||
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
||||||
@@ -641,9 +641,9 @@ def manual_review_contract(contract_id: int):
|
|||||||
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
|
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
|
||||||
def mark_contract_node_paid(contract_id: int, node_id: int):
|
def mark_contract_node_paid(contract_id: int, node_id: int):
|
||||||
"""
|
"""
|
||||||
把未付的预付款或出货款手动标为已付。
|
把未付的付款阶段手动标为已付。
|
||||||
|
|
||||||
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。只改这一阶段,并关闭尚未发送的预警。
|
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。四个阶段都可以标记,只改这一阶段,并关闭尚未发送的预警。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
contract_id: 合同台账主键。
|
contract_id: 合同台账主键。
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
backend/app/api/equipment_acceptance/__init__.py
|
backend/app/api/equipment_acceptance/__init__.py
|
||||||
|
|
||||||
用途:设备验收预警的 Chat 作业面接口。
|
用途:设备验收预警的 Chat 作业面接口。
|
||||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应、jobs.queue。
|
||||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;
|
||||||
|
同步、扫描、发送和保存配置仅平台管理员。扫描与发送改为入队,由 schedule worker 执行,避免 HTTP 504。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -12,15 +13,17 @@ from io import BytesIO
|
|||||||
|
|
||||||
from flask import Blueprint, g, request, send_file
|
from flask import Blueprint, g, request, send_file
|
||||||
|
|
||||||
|
from app import db
|
||||||
from app.core.auth.jwt import get_current_user
|
from app.core.auth.jwt import get_current_user
|
||||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.models import Agent
|
from app.jobs.queue import enqueue
|
||||||
|
from app.jobs.types import JobType
|
||||||
|
from app.models import Agent, Job
|
||||||
from app.services.equipment_acceptance.config_service import (
|
from app.services.equipment_acceptance.config_service import (
|
||||||
get_acceptance_config,
|
get_acceptance_config,
|
||||||
save_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 get_send_file, list_send_files, 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 (
|
from app.services.equipment_acceptance.sync_service import (
|
||||||
get_acceptance_order,
|
get_acceptance_order,
|
||||||
@@ -28,6 +31,11 @@ from app.services.equipment_acceptance.sync_service import (
|
|||||||
sync_acceptance_snapshots,
|
sync_acceptance_snapshots,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_EQUIPMENT_ACCEPTANCE_JOB_TYPES = {
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN.value,
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY.value,
|
||||||
|
}
|
||||||
|
|
||||||
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
||||||
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
||||||
|
|
||||||
@@ -110,7 +118,7 @@ def sync_equipment_acceptance():
|
|||||||
|
|
||||||
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
||||||
def list_equipment_acceptance_orders():
|
def list_equipment_acceptance_orders():
|
||||||
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
"""分页查看已同步的验收单。focus 按状态分组,keyword 查三种单号,applicant 查申请人。"""
|
||||||
_require_equipment_acceptance_access()
|
_require_equipment_acceptance_access()
|
||||||
page = _int_arg("page", 1)
|
page = _int_arg("page", 1)
|
||||||
page_size = _int_arg("page_size", 20)
|
page_size = _int_arg("page_size", 20)
|
||||||
@@ -119,6 +127,8 @@ def list_equipment_acceptance_orders():
|
|||||||
focus=request.args.get("focus"),
|
focus=request.args.get("focus"),
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
|
keyword=request.args.get("keyword"),
|
||||||
|
applicant=request.args.get("applicant"),
|
||||||
)
|
)
|
||||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
@@ -147,16 +157,79 @@ def save_equipment_acceptance_config():
|
|||||||
|
|
||||||
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
||||||
def scan_equipment_acceptance_alerts():
|
def scan_equipment_acceptance_alerts():
|
||||||
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
|
"""
|
||||||
_require_equipment_acceptance_admin()
|
将设备验收扫描任务入队。
|
||||||
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
|
|
||||||
|
核心逻辑:仅平台管理员。Worker 同步后生成待发送,不发企业微信。
|
||||||
|
同业务键已有 queued/running 时复用,避免连点重复扫。
|
||||||
|
Returns:
|
||||||
|
HTTP 202 与 job_id。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_admin()
|
||||||
|
job_id = enqueue(
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
|
||||||
|
{},
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
business_ref="daily-alert",
|
||||||
|
created_by_id=user.id,
|
||||||
|
message="等待扫描设备验收预警",
|
||||||
|
)
|
||||||
|
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||||
|
|
||||||
|
|
||||||
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
||||||
def send_equipment_acceptance_alerts():
|
def send_equipment_acceptance_alerts():
|
||||||
"""管理员立即把待发送记录按收件人发到企业微信。"""
|
"""
|
||||||
_require_equipment_acceptance_admin()
|
将设备验收发送任务入队。
|
||||||
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
|
||||||
|
核心逻辑:仅平台管理员。Worker 按收件人发企微后改发送记录状态。
|
||||||
|
同业务键已有 queued/running 时复用,避免连点重复发。
|
||||||
|
Returns:
|
||||||
|
HTTP 202 与 job_id。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_admin()
|
||||||
|
job_id = enqueue(
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
|
||||||
|
{},
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
business_ref="weekly-alert",
|
||||||
|
created_by_id=user.id,
|
||||||
|
message="等待发送设备验收预警",
|
||||||
|
)
|
||||||
|
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/jobs/<int:job_id>", methods=["GET"])
|
||||||
|
def get_equipment_acceptance_job(job_id: int):
|
||||||
|
"""
|
||||||
|
查询当前管理员提交的设备验收后台任务是否跑完。
|
||||||
|
|
||||||
|
核心逻辑:只返回本人创建的设备验收 Job。发送任务的 result 含 sent/failed。
|
||||||
|
Args:
|
||||||
|
job_id: jobs 表主键。
|
||||||
|
Returns:
|
||||||
|
status、message、result。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 任务不存在或不属于当前管理员。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_admin()
|
||||||
|
row = db.session.get(Job, job_id)
|
||||||
|
if (
|
||||||
|
row is None
|
||||||
|
or row.domain != "equipment_acceptance"
|
||||||
|
or row.job_type not in _EQUIPMENT_ACCEPTANCE_JOB_TYPES
|
||||||
|
or row.created_by_id != user.id
|
||||||
|
):
|
||||||
|
raise NotFoundError("任务不存在")
|
||||||
|
return ok(
|
||||||
|
{
|
||||||
|
"id": row.id,
|
||||||
|
"status": row.status,
|
||||||
|
"message": row.message,
|
||||||
|
"result": row.result_json or {},
|
||||||
|
},
|
||||||
|
request_id=getattr(g, "request_id", None),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ backend/app/api/freight_rpa.py
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
from flask import Blueprint, current_app, jsonify, request
|
||||||
|
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
from app.core.tool_auth import require_tool_auth
|
from app.core.tool_auth import require_tool_auth
|
||||||
@@ -65,6 +65,12 @@ def heartbeat():
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise ValidationError(str(exc))
|
raise ValidationError(str(exc))
|
||||||
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
|
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
|
||||||
|
# 到期的 Crane 定时回查跟着心跳落成 trigger;写失败不让心跳本身失败。
|
||||||
|
try:
|
||||||
|
from app.services.freight_rpa.upload.crane_recheck import materialize_due_crane_rechecks
|
||||||
|
materialize_due_crane_rechecks()
|
||||||
|
except Exception:
|
||||||
|
current_app.logger.exception('crane recheck materialize failed')
|
||||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,8 @@
|
|||||||
unconfigured 后再各写最多一个 batch;
|
unconfigured 后再各写最多一个 batch;
|
||||||
证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用
|
证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用
|
||||||
入站/出站文件;当天清单(GET /sources/<code>/evidence-files)复用可用
|
入站/出站文件;当天清单(GET /sources/<code>/evidence-files)复用可用
|
||||||
条件返回当天全部文件,并分别签发预览地址与带保存名的下载地址;
|
条件返回当天全部文件;单文件下载(GET .../evidence-files/<file_id>)
|
||||||
|
由当前站点回传字节,不把 HTTP MinIO 地址交给 HTTPS 页面;
|
||||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||||
@@ -369,9 +370,9 @@ def list_source_evidence_files_api(source_code: str):
|
|||||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||||
可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。
|
可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。
|
||||||
每项含 file_id、original_filename、created_at、sha256、file_size、
|
每项含 file_id、original_filename、created_at、sha256、file_size、
|
||||||
presigned_url、download_url。不解析 Excel,不含行数。预览与下载各签一次
|
presigned_url、download_url。不解析 Excel,不含行数。预览仍打开
|
||||||
presigned_get_url(storage_key, expires_seconds=300);下载地址额外带
|
presigned_url。单文件下载不使用 download_url,改走
|
||||||
download_name(库存源_东八区年月日_时分.扩展名),避免浏览器用对象键哈希当保存名。
|
GET evidence-files/<file_id>,由当前站点回传。
|
||||||
签发时写 TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
签发时写 TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
||||||
"""
|
"""
|
||||||
from app.services.file_assets.storage import file_asset_storage
|
from app.services.file_assets.storage import file_asset_storage
|
||||||
@@ -401,6 +402,47 @@ def list_source_evidence_files_api(source_code: str):
|
|||||||
return _ok(payload)
|
return _ok(payload)
|
||||||
|
|
||||||
|
|
||||||
|
@in_transit_transfer_bp.route("/sources/<source_code>/evidence-files/<int:file_id>", methods=["GET"])
|
||||||
|
@require_transfer_permission
|
||||||
|
def download_source_evidence_file_api(source_code: str, file_id: int):
|
||||||
|
"""把一份仍可用的证据文件经当前站点返回给浏览器。
|
||||||
|
|
||||||
|
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||||
|
只接受该来源、该记录类型下仍在可用窗口内的归档。保存名用
|
||||||
|
evidence_download_filename。页面是 HTTPS,MinIO 公网地址是 HTTP,
|
||||||
|
直接打开预签名链接会被浏览器当成不安全下载拦掉。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_code: 来源实例编码。
|
||||||
|
file_id: 归档文件主键。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
附件响应。找不到或已不可用时 404,错误码 SHIPPING.INBOUND_FILE_NOT_FOUND。
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import mimetypes
|
||||||
|
|
||||||
|
from app.services.file_assets.storage import file_asset_storage
|
||||||
|
|
||||||
|
kind = str(request.args.get("record_kind") or "inbound").strip()
|
||||||
|
if kind not in {"inbound", "outbound"}:
|
||||||
|
raise ValidationError("record_kind must be inbound or outbound")
|
||||||
|
code = str(source_code or "").strip()
|
||||||
|
report = next((item for item in _usable_archive_files(code, kind) if item.id == file_id), None)
|
||||||
|
if report is None:
|
||||||
|
raise NotFoundError("evidence file is not available", code="SHIPPING.INBOUND_FILE_NOT_FOUND")
|
||||||
|
data = file_asset_storage.get_bytes(report.storage_key)
|
||||||
|
download_name = evidence_download_filename(code, report.created_at, report.original_filename)
|
||||||
|
_record_evidence_download_audit(aggregate_id=code)
|
||||||
|
mime = mimetypes.guess_type(download_name)[0] or "application/octet-stream"
|
||||||
|
return send_file(
|
||||||
|
io.BytesIO(data),
|
||||||
|
mimetype=mime,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=download_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||||
@require_transfer_permission
|
@require_transfer_permission
|
||||||
def get_run_api(run_no: str):
|
def get_run_api(run_no: str):
|
||||||
@@ -1436,6 +1478,7 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
|
|||||||
'item_id': item.item_id,
|
'item_id': item.item_id,
|
||||||
'source_code': item.source_code,
|
'source_code': item.source_code,
|
||||||
'invoice_no': item.invoice_no,
|
'invoice_no': item.invoice_no,
|
||||||
|
'external_doc_no': item.external_doc_no,
|
||||||
'material_no': item.material_no,
|
'material_no': item.material_no,
|
||||||
'status': item.status,
|
'status': item.status,
|
||||||
'reason': item.reason,
|
'reason': item.reason,
|
||||||
|
|||||||
@@ -7,9 +7,10 @@ backend/app/api/user/handlers.py
|
|||||||
"""
|
"""
|
||||||
from flask import Blueprint, request, jsonify, current_app
|
from flask import Blueprint, request, jsonify, current_app
|
||||||
from sqlalchemy import and_, or_
|
from sqlalchemy import and_, or_
|
||||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog
|
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, GeneralFeedbackImage, ChatLog
|
||||||
|
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
||||||
from app.services.feedback_notify import send_feedback_group_notification
|
from app.services.feedback_notify import send_feedback_group_notification
|
||||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||||
@@ -32,6 +33,11 @@ from .auth import (
|
|||||||
)
|
)
|
||||||
user_bp = Blueprint('user', __name__)
|
user_bp = Blueprint('user', __name__)
|
||||||
|
|
||||||
|
# [CONST] 反馈附件图片上限与允许的图片扩展名(POST /feedback 的 image_asset_nos 校验用)
|
||||||
|
_FEEDBACK_MAX_IMAGES = 5
|
||||||
|
_FEEDBACK_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
||||||
|
|
||||||
|
|
||||||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||||||
def mark_wecom_deeplink_opened():
|
def mark_wecom_deeplink_opened():
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
@@ -161,9 +167,46 @@ def submit_general_feedback():
|
|||||||
raise ValidationError('chat_log_id not found')
|
raise ValidationError('chat_log_id not found')
|
||||||
if chat_log.user_id != user.id:
|
if chat_log.user_id != user.id:
|
||||||
raise ForbiddenError('chat_log_id is not owned by current user')
|
raise ForbiddenError('chat_log_id is not owned by current user')
|
||||||
|
# [STEP 1] 解析并规整 image_asset_nos(可选参数):非 list 直接拒绝;元素转 str 去空白、保序去重;超上限整单拒绝
|
||||||
|
raw_asset_nos = data.get('image_asset_nos')
|
||||||
|
normalized_asset_nos: list[str] = []
|
||||||
|
if raw_asset_nos is not None:
|
||||||
|
if not isinstance(raw_asset_nos, list):
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='image_asset_nos must be a list')
|
||||||
|
seen_asset_nos: set[str] = set()
|
||||||
|
for item in raw_asset_nos:
|
||||||
|
asset_no = str(item or '').strip()
|
||||||
|
if not asset_no or asset_no in seen_asset_nos:
|
||||||
|
continue
|
||||||
|
seen_asset_nos.add(asset_no)
|
||||||
|
normalized_asset_nos.append(asset_no)
|
||||||
|
if len(normalized_asset_nos) > _FEEDBACK_MAX_IMAGES:
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_TOO_MANY', message='最多附加 5 张图片')
|
||||||
|
# [STEP 2] 逐个校验资产归属与图片语义(任一失败整单拒绝,反馈与图片关联都不落库)
|
||||||
|
feedback_assets = []
|
||||||
|
for asset_no in normalized_asset_nos:
|
||||||
|
asset = get_asset_for_user(asset_no, user.id)
|
||||||
|
if asset.extension not in _FEEDBACK_IMAGE_EXTENSIONS:
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='仅支持 png/jpg/jpeg/webp 图片')
|
||||||
|
if asset.upload_status != 'ready':
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片尚未上传完成')
|
||||||
|
if asset.reference_count != 0 or asset.lifecycle_status != 'temporary':
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='该文件已被使用')
|
||||||
|
feedback_assets.append(asset)
|
||||||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||||||
|
# [STEP 3] 落库:flush 拿反馈 id → 按枚举序写图片关联(sort_order=下标)→ 逐个标记资产被引用 → commit;
|
||||||
|
# IntegrityError 兜底并发双挂(asset_id 唯一约束),回滚整单并转业务错误
|
||||||
db.session.add(row)
|
db.session.add(row)
|
||||||
db.session.commit()
|
db.session.flush()
|
||||||
|
for idx, asset in enumerate(feedback_assets):
|
||||||
|
db.session.add(GeneralFeedbackImage(feedback_id=row.id, asset_id=asset.id, sort_order=idx))
|
||||||
|
mark_asset_referenced(asset)
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片已被使用,请重新添加')
|
||||||
|
# [STEP 4] 通知与返回不变:提交成功后推送企微群通知(失败不影响提交结果),返回旧契约 JSON
|
||||||
notify_result = send_feedback_group_notification(row, user)
|
notify_result = send_feedback_group_notification(row, user)
|
||||||
if notify_result.get('ok'):
|
if notify_result.get('ok'):
|
||||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||||
|
|||||||
@@ -1102,6 +1102,47 @@ def workspace_confirm_shipping_notice_uploaded(business_no: str):
|
|||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/refresh-crane-upload', methods=['POST'])
|
||||||
|
def workspace_refresh_crane_upload_status(business_no: str):
|
||||||
|
"""手动刷新一张仍在分配中的 Crane 发货单。
|
||||||
|
|
||||||
|
核心逻辑:校验当前用户可见的通知单,读取最近一次上传尝试,写入一条只查状态的 trigger。
|
||||||
|
不改 10 分钟定时回查的到期时间,也不重新上传 Excel。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
business_no: 对外发货通知单号,同时是 Crane 的 Pull Request #。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON: business_no 与 trigger_queued。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 没有可刷新的上传尝试或来源连接。
|
||||||
|
ConflictError: 当前不是分配中,或上一次手动刷新还在排队。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||||
|
from app.services.freight_rpa.upload.crane_recheck import request_manual_crane_refresh
|
||||||
|
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||||
|
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||||
|
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||||
|
|
||||||
|
attempt = latest_upload_attempt(task)
|
||||||
|
from app.models import ShippingExportArtifact
|
||||||
|
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if attempt is not None else None
|
||||||
|
snapshot = task_rpa_inventory_source(task) or {}
|
||||||
|
upload_source = get_rpa_trigger_inventory_source(str(snapshot.get('source_code') or '')) if snapshot.get('source_code') else None
|
||||||
|
if attempt is None or artifact is None or not isinstance(upload_source, dict):
|
||||||
|
raise ValidationError('Crane upload status cannot be refreshed', code='SHIPPING.UPLOAD_CRANE_ALLOCATING')
|
||||||
|
trigger_path = request_manual_crane_refresh(
|
||||||
|
attempt,
|
||||||
|
upload_source,
|
||||||
|
task_no=str(task.task_no),
|
||||||
|
export_file_path=str(artifact.file_path or ''),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return _ok({'business_no': str(task.business_no), 'trigger_queued': bool(trigger_path)})
|
||||||
|
|
||||||
|
|
||||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
||||||
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
||||||
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
||||||
|
|||||||
@@ -4,17 +4,20 @@ backend/app/api/workspace/voucher_check.py
|
|||||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||||
|
批次明细可按 result 与 invoice_no 筛选。企微记录里的 Excel 走本模块下载,不走排程通知人权限。
|
||||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from flask import Blueprint, request
|
from io import BytesIO
|
||||||
|
|
||||||
|
from flask import Blueprint, request, send_file
|
||||||
|
|
||||||
from app.core.auth.jwt import get_current_user
|
from app.core.auth.jwt import get_current_user
|
||||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.models import Agent
|
from app.models import Agent, ScheduleRun, VoucherCheckRun
|
||||||
from app.services.voucher_check import notify_config_service, query_service
|
from app.services.voucher_check import notify_config_service, query_service
|
||||||
|
|
||||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||||
@@ -149,12 +152,13 @@ def workspace_voucher_latest_run():
|
|||||||
def workspace_voucher_run_items(run_id: int):
|
def workspace_voucher_run_items(run_id: int):
|
||||||
"""
|
"""
|
||||||
分页查看批次明细。
|
分页查看批次明细。
|
||||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
|
核心逻辑:委托 query_service.list_run_items,可按 result 与 invoice_no 过滤,并返回 by_file_type。
|
||||||
"""
|
"""
|
||||||
_require_voucher_check_access()
|
_require_voucher_check_access()
|
||||||
data = query_service.list_run_items(
|
data = query_service.list_run_items(
|
||||||
run_id=run_id,
|
run_id=run_id,
|
||||||
result=request.args.get("result"),
|
result=request.args.get("result"),
|
||||||
|
invoice_no=request.args.get("invoice_no"),
|
||||||
page=request.args.get("page", default=1, type=int) or 1,
|
page=request.args.get("page", default=1, type=int) or 1,
|
||||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||||
)
|
)
|
||||||
@@ -177,6 +181,33 @@ def workspace_voucher_notifications():
|
|||||||
return ok(data)
|
return ok(data)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_voucher_check_bp.route(
|
||||||
|
"/accounting-voucher-check/schedule-runs/<int:schedule_run_id>/excel",
|
||||||
|
methods=["GET"],
|
||||||
|
)
|
||||||
|
def workspace_voucher_schedule_excel(schedule_run_id: int):
|
||||||
|
"""
|
||||||
|
下载企微发送记录对应的检核结果 Excel。
|
||||||
|
核心逻辑:能看发送记录的人即可下载。只放行已挂到立账凭证批次上的 ScheduleRun,不按排程负责人或通知人拦截。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 该排程记录不是立账凭证批次,或还没有生成 Excel。
|
||||||
|
"""
|
||||||
|
_require_voucher_check_access()
|
||||||
|
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run_id).first()
|
||||||
|
if engine is None:
|
||||||
|
raise NotFoundError("立账凭证检核批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||||
|
run = ScheduleRun.query.get(schedule_run_id)
|
||||||
|
if run is None or not run.excel_file_data:
|
||||||
|
raise NotFoundError("检核结果 Excel 不存在", code="VOUCHER_CHECK.EXCEL_NOT_FOUND")
|
||||||
|
return send_file(
|
||||||
|
BytesIO(run.excel_file_data),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=run.excel_file_name or "voucher_check.xlsx",
|
||||||
|
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||||
def workspace_voucher_notify_config_get():
|
def workspace_voucher_notify_config_get():
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ backend/app/jobs/handlers/__init__.py
|
|||||||
|
|
||||||
from app.jobs.handlers import ( # noqa: F401
|
from app.jobs.handlers import ( # noqa: F401
|
||||||
contract_payment,
|
contract_payment,
|
||||||
|
equipment_acceptance,
|
||||||
file_check_run,
|
file_check_run,
|
||||||
in_transit_transfer_item,
|
in_transit_transfer_item,
|
||||||
in_transit_transfer_match,
|
in_transit_transfer_match,
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""
|
||||||
|
backend/app/jobs/handlers/equipment_acceptance.py
|
||||||
|
|
||||||
|
用途:执行设备验收预警域后台任务(手动扫描、手动发送)。
|
||||||
|
依赖:jobs.registry、equipment_acceptance.alert_service、jobs.queue.finish_job。
|
||||||
|
逻辑:与周五排程共用 generate_alerts / send_pending_alerts。成功须显式 finish_job,
|
||||||
|
否则 Job 停在 running,超时回收后会重复发送。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.jobs.context import JobContext
|
||||||
|
from app.jobs.queue import finish_job
|
||||||
|
from app.jobs.registry import register_handler
|
||||||
|
from app.jobs.types import JobType
|
||||||
|
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||||
|
|
||||||
|
|
||||||
|
@register_handler(JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN)
|
||||||
|
def run_equipment_acceptance_alert_scan(ctx: JobContext, payload: dict) -> None:
|
||||||
|
"""
|
||||||
|
执行一次设备验收同步并生成待发送记录。
|
||||||
|
|
||||||
|
核心逻辑:不发企业微信。供管理员「扫描预警」入队后由 Worker 执行。
|
||||||
|
Args:
|
||||||
|
ctx: 后台任务上下文。
|
||||||
|
payload: 含通用队列注入的 job_id。
|
||||||
|
Returns:
|
||||||
|
None;结果写入 Job.result_json。
|
||||||
|
"""
|
||||||
|
job_id = int(payload.get("job_id") or 0)
|
||||||
|
result = generate_alerts()
|
||||||
|
ctx.logger.info("equipment acceptance alert scan result=%s", result)
|
||||||
|
if job_id:
|
||||||
|
finish_job(job_id, result=result, message="设备验收预警扫描完成")
|
||||||
|
|
||||||
|
|
||||||
|
@register_handler(JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY)
|
||||||
|
def run_equipment_acceptance_alert_weekly(ctx: JobContext, payload: dict) -> None:
|
||||||
|
"""
|
||||||
|
执行一次设备验收待发送记录的企业微信汇总发送。
|
||||||
|
|
||||||
|
核心逻辑:按收件人发卡片和 Excel,发完后才改发送记录状态。
|
||||||
|
供管理员「发送预警」入队;与周五排程共用同一发送函数。
|
||||||
|
Args:
|
||||||
|
ctx: 后台任务上下文。
|
||||||
|
payload: 含通用队列注入的 job_id。
|
||||||
|
Returns:
|
||||||
|
None;sent/failed 写入 Job.result_json,页面轮询后展示。
|
||||||
|
"""
|
||||||
|
job_id = int(payload.get("job_id") or 0)
|
||||||
|
result = send_pending_alerts()
|
||||||
|
ctx.logger.info("equipment acceptance weekly alert result=%s", result)
|
||||||
|
if job_id:
|
||||||
|
finish_job(job_id, result=result, message="设备验收预警发送完成")
|
||||||
@@ -109,6 +109,23 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
|||||||
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
||||||
job_type=job_type,
|
job_type=job_type,
|
||||||
)
|
)
|
||||||
|
equipment_acceptance_types = (
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
|
||||||
|
)
|
||||||
|
if {item.value for item in equipment_acceptance_types} & allowed_types:
|
||||||
|
from app.jobs.queue import recover_stale_jobs
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
# 设备验收发送可能要给很多收件人发企微,超时与合同付款周汇总同级。
|
||||||
|
for job_type in equipment_acceptance_types:
|
||||||
|
if job_type.value not in allowed_types:
|
||||||
|
continue
|
||||||
|
recover_stale_jobs(
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
||||||
|
job_type=job_type,
|
||||||
|
)
|
||||||
|
|
||||||
# [STEP 2] 按队列优先级 claim
|
# [STEP 2] 按队列优先级 claim
|
||||||
for name in queue_names:
|
for name in queue_names:
|
||||||
@@ -149,13 +166,22 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
|||||||
)
|
)
|
||||||
if job:
|
if job:
|
||||||
return _normalize_generic_job(job)
|
return _normalize_generic_job(job)
|
||||||
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
|
# file-check / 企微通讯录同步 / 设备验收手动扫描发送与排程共用 schedule worker
|
||||||
job = claim_next_job(
|
job = claim_next_job(
|
||||||
domain=None,
|
domain=None,
|
||||||
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
|
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
|
||||||
)
|
)
|
||||||
if job:
|
if job:
|
||||||
return _normalize_generic_job(job)
|
return _normalize_generic_job(job)
|
||||||
|
job = claim_next_job(
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
job_types=[
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
if job:
|
||||||
|
return _normalize_generic_job(job)
|
||||||
elif name == 'transfer':
|
elif name == 'transfer':
|
||||||
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
|
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
|
||||||
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
|
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ class JobType(StrEnum):
|
|||||||
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
||||||
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
||||||
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
||||||
|
# 设备验收预警:管理员手动扫描 / 发送入队,由 schedule worker 执行,避免 HTTP 504。
|
||||||
|
EQUIPMENT_ACCEPTANCE_ALERT_SCAN = 'equipment_acceptance_alert_scan'
|
||||||
|
EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY = 'equipment_acceptance_alert_weekly'
|
||||||
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||||
TRANSFER_MATCH = 'in_transit_transfer_match'
|
TRANSFER_MATCH = 'in_transit_transfer_match'
|
||||||
TRANSFER_RUN = 'in_transit_transfer_run'
|
TRANSFER_RUN = 'in_transit_transfer_run'
|
||||||
@@ -84,7 +87,13 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
|||||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||||
}),
|
}),
|
||||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||||
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
'schedule': frozenset({
|
||||||
|
'schedule_run',
|
||||||
|
'file_check_run',
|
||||||
|
'wecom_directory_sync',
|
||||||
|
'equipment_acceptance_alert_scan',
|
||||||
|
'equipment_acceptance_alert_weekly',
|
||||||
|
}),
|
||||||
'transfer': frozenset({
|
'transfer': frozenset({
|
||||||
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -9,8 +9,15 @@ backend/app/models/__init__.py
|
|||||||
|
|
||||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||||
from app.models.base import Base, user_agent_permissions
|
from app.models.base import Base, user_agent_permissions
|
||||||
from app.models.permission_role import PermissionRole, permission_role_agents
|
from app.models.permission_role import PermissionRole, permission_role_agents, user_permission_roles
|
||||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
from app.models.chat import (
|
||||||
|
ChatLog,
|
||||||
|
ChatSession,
|
||||||
|
ChatToolRun,
|
||||||
|
Feedback,
|
||||||
|
GeneralFeedback,
|
||||||
|
GeneralFeedbackImage,
|
||||||
|
)
|
||||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||||
from app.models.department import Department
|
from app.models.department import Department
|
||||||
from app.models.linked_service import LinkedService
|
from app.models.linked_service import LinkedService
|
||||||
@@ -267,6 +274,7 @@ __all__ = [
|
|||||||
'Base',
|
'Base',
|
||||||
'user_agent_permissions',
|
'user_agent_permissions',
|
||||||
'permission_role_agents',
|
'permission_role_agents',
|
||||||
|
'user_permission_roles',
|
||||||
'PermissionRole',
|
'PermissionRole',
|
||||||
'ZlLanguage',
|
'ZlLanguage',
|
||||||
'Department',
|
'Department',
|
||||||
@@ -280,6 +288,7 @@ __all__ = [
|
|||||||
'ChatToolRun',
|
'ChatToolRun',
|
||||||
'Feedback',
|
'Feedback',
|
||||||
'GeneralFeedback',
|
'GeneralFeedback',
|
||||||
|
'GeneralFeedbackImage',
|
||||||
'PermissionRequest',
|
'PermissionRequest',
|
||||||
'QuickQuestion',
|
'QuickQuestion',
|
||||||
'FaqHotCandidate',
|
'FaqHotCandidate',
|
||||||
|
|||||||
@@ -135,3 +135,22 @@ class GeneralFeedback(Base):
|
|||||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
# 反馈附件截图列表:按 sort_order 排序;级联删除随反馈一并移除
|
||||||
|
images: Mapped[list['GeneralFeedbackImage']] = relationship(
|
||||||
|
order_by='GeneralFeedbackImage.sort_order', cascade='all, delete-orphan'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class GeneralFeedbackImage(Base):
|
||||||
|
"""
|
||||||
|
通用意见反馈附件表
|
||||||
|
用途:关联 general_feedbacks 与 file_assets,一条反馈可带多张截图;asset_id 唯一,一图只挂一条反馈
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'general_feedback_images'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
feedback_id: Mapped[int] = mapped_column(ForeignKey('general_feedbacks.id'), index=True)
|
||||||
|
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), unique=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
@@ -1,27 +1,40 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/models/department.py
|
backend/app/models/department.py
|
||||||
|
|
||||||
用途:部门组织模型。
|
用途:部门组织模型(parent_id 邻接表树形结构,对应 OA 组织架构)。
|
||||||
依赖:models.base.Base。
|
依赖:models.base.Base。
|
||||||
|
逻辑:parent_id 自关联构成部门树;sort_order 为同级排序(对应 ERP HRAO hrao09 阶层序号),
|
||||||
|
is_hidden 对应 hrao08「在组织框架图中显示否」。树的组装与校验在 services/admin/department_service。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import String, Text
|
from sqlalchemy import Boolean, ForeignKey, String, Text
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class Department(Base):
|
class Department(Base):
|
||||||
"""部门表:存储公司部门列表。"""
|
"""部门表:存储公司部门树(parent_id 邻接表)。"""
|
||||||
|
|
||||||
__tablename__ = 'departments'
|
__tablename__ = 'departments'
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
# 树形结构下 name 仅要求「同一上级下不重名」(由 department_service 校验),不再全局唯一,
|
||||||
|
# 以支持多公司存在同名部门(如各公司均有「管理部」)。
|
||||||
|
name: Mapped[str] = mapped_column(String(100))
|
||||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||||
company: Mapped[Optional[str]] = mapped_column(String(100))
|
company: Mapped[Optional[str]] = mapped_column(String(100))
|
||||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
|
# 上级部门主键;None 表示顶级部门(树顶公司层由前端按 company 字段虚拟分组,不入库)
|
||||||
|
parent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('departments.id'), nullable=True)
|
||||||
|
# 同级排序号(升序),对应 ERP hrao09 部门阶层序号
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0, server_default='0', nullable=False)
|
||||||
|
# 是否在组织树中隐藏(对应 ERP hrao08「在组织框架图中显示否」;管理端仍可见并打标)
|
||||||
|
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False, server_default='false', nullable=False)
|
||||||
|
|
||||||
|
# 上级部门;children 由 backref 提供,供 service 组装树
|
||||||
|
parent: Mapped[Optional['Department']] = relationship(remote_side=[id], backref='children')
|
||||||
@@ -3,11 +3,11 @@ backend/app/models/equipment_acceptance.py
|
|||||||
|
|
||||||
用途:设备验收预警的本地同步快照和可改配置。
|
用途:设备验收预警的本地同步快照和可改配置。
|
||||||
依赖:models.base.Base、users。
|
依赖:models.base.Base、users。
|
||||||
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
逻辑:同步服务按来源 oa_system 加流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||||
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
||||||
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||||
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
||||||
不保存流程编号、第二合同编号、验收日期和 isremark。
|
保存流程编号和标题。不保存第二合同编号、验收日期和 isremark。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -22,18 +22,34 @@ from app.models.base import Base
|
|||||||
|
|
||||||
|
|
||||||
class EquipmentAcceptanceOrder(Base):
|
class EquipmentAcceptanceOrder(Base):
|
||||||
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
|
"""一张验收单的最近一次同步结果。同一来源里 request_id 唯一。"""
|
||||||
|
|
||||||
__tablename__ = "equipment_acceptance_orders"
|
__tablename__ = "equipment_acceptance_orders"
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
UniqueConstraint("oa_system", "request_id", name="uq_equipment_acceptance_orders_oa_request"),
|
||||||
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
oa_system: Mapped[str] = mapped_column(String(8), nullable=False, default="e10")
|
||||||
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), 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)
|
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
flow_no: Mapped[Optional[str]] = mapped_column(
|
||||||
|
String(1000),
|
||||||
|
nullable=True,
|
||||||
|
comment="流程编号。E10 取 wfc_requestbase.requestmark,E8 取 formtable_main_324.lcbh。",
|
||||||
|
)
|
||||||
|
request_title: Mapped[Optional[str]] = mapped_column(
|
||||||
|
String(1000),
|
||||||
|
nullable=True,
|
||||||
|
comment="流程标题。两边都取流程表 requestname。E10 这一列是流程默认标题。",
|
||||||
|
)
|
||||||
|
request_created_at: Mapped[Optional[datetime]] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=True,
|
||||||
|
comment="流程创建时间。E10 取 wfc_requestbase.createdatetime。E8 取 createdate 加 createtime。不用 E10 的 create_time。",
|
||||||
|
)
|
||||||
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||||
can_accept: Mapped[Optional[int]] = mapped_column(
|
can_accept: Mapped[Optional[int]] = mapped_column(
|
||||||
|
|||||||
@@ -69,11 +69,9 @@ class FreightRpaProfile(Base):
|
|||||||
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
||||||
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
||||||
)
|
)
|
||||||
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
|
# 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
|
||||||
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
|
# 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
|
||||||
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
|
# 该配置变更不递增 config_version(见 admin 服务)。
|
||||||
# result_mode / result_selector / success_texts / timeout_seconds。
|
|
||||||
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
|
|
||||||
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
models/permission_role.py
|
models/permission_role.py
|
||||||
|
|
||||||
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
用途:可配置权限组(角色包)、角色与 Agent、用户与角色的授权关系。
|
||||||
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
依赖:models.base.Base、agents、users。
|
||||||
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
逻辑:Admin 角色配置读写本表;一个用户可挂多个业务角色,经 user_permission_roles 关联。
|
||||||
|
users.role 只保留排序最前的主角色,供旧查询兼容;运行时按全部角色取并集后再同步到 user_agent_permissions。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -24,6 +25,12 @@ permission_role_agents = db.Table(
|
|||||||
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
user_permission_roles = db.Table(
|
||||||
|
'user_permission_roles',
|
||||||
|
db.Column('user_id', ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||||
|
db.Column('role_id', ForeignKey('permission_roles.id', ondelete='CASCADE'), primary_key=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class PermissionRole(Base):
|
class PermissionRole(Base):
|
||||||
"""权限组:可用应用入口 + 应用内能力。"""
|
"""权限组:可用应用入口 + 应用内能力。"""
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ backend/app/models/user.py
|
|||||||
|
|
||||||
用途:用户账户、首页偏好、登录审计相关模型。
|
用途:用户账户、首页偏好、登录审计相关模型。
|
||||||
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
||||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
|
逻辑:User 与 Agent 多对多经 user_agent_permissions;与权限组多对多经 user_permission_roles。
|
||||||
|
users.role 是主角色。已挂多个业务角色时,功能权限与应用入口取并集。
|
||||||
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|||||||
from werkzeug.security import check_password_hash, generate_password_hash
|
from werkzeug.security import check_password_hash, generate_password_hash
|
||||||
|
|
||||||
from app.models.base import Base, user_agent_permissions
|
from app.models.base import Base, user_agent_permissions
|
||||||
|
from app.models.permission_role import user_permission_roles
|
||||||
|
|
||||||
|
|
||||||
class UserHomepageConfig(Base):
|
class UserHomepageConfig(Base):
|
||||||
@@ -77,6 +79,10 @@ class User(Base):
|
|||||||
secondary=user_agent_permissions,
|
secondary=user_agent_permissions,
|
||||||
back_populates='users',
|
back_populates='users',
|
||||||
)
|
)
|
||||||
|
permission_roles: Mapped[List['PermissionRole']] = relationship(
|
||||||
|
'PermissionRole',
|
||||||
|
secondary=user_permission_roles,
|
||||||
|
)
|
||||||
|
|
||||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
@@ -118,7 +124,7 @@ class User(Base):
|
|||||||
返回当前用户的有效功能权限。
|
返回当前用户的有效功能权限。
|
||||||
|
|
||||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||||
核心逻辑:已配置 permission_roles 时完全由权限组计算;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
核心逻辑:已配置 permission_roles 时按该用户全部角色取并集;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
||||||
输出约束:仅返回布尔型权限键。
|
输出约束:仅返回布尔型权限键。
|
||||||
"""
|
"""
|
||||||
from app.services.permission_roles.service import effective_feature_permissions
|
from app.services.permission_roles.service import effective_feature_permissions
|
||||||
@@ -164,13 +170,14 @@ class User(Base):
|
|||||||
return self.has_feature_permission('training_hr_manage')
|
return self.has_feature_permission('training_hr_manage')
|
||||||
|
|
||||||
def client_auth_fields(self) -> dict:
|
def client_auth_fields(self) -> dict:
|
||||||
"""登录态/首页共用的角色与功能权限字段。"""
|
"""登录态/首页共用的角色与功能权限字段。多个业务角色的名称用顿号拼接。"""
|
||||||
from app.services.permission_roles.service import list_role_name_map
|
from app.services.permission_roles.service import role_auth_payload
|
||||||
|
|
||||||
names = list_role_name_map()
|
payload = role_auth_payload(self)
|
||||||
return {
|
return {
|
||||||
'is_platform_admin': self.is_platform_admin(),
|
'is_platform_admin': self.is_platform_admin(),
|
||||||
'role_name': names.get(self.role) or self.role,
|
'role_name': payload['role_name'],
|
||||||
|
'role_codes': payload['role_codes'],
|
||||||
'feature_permissions': self.get_feature_permissions(),
|
'feature_permissions': self.get_feature_permissions(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,59 +1,206 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/admin/department_service.py
|
backend/app/services/admin/department_service.py
|
||||||
|
|
||||||
用途:管理端部门 CRUD 业务编排。
|
用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
|
||||||
依赖:models.Department、app.core.errors。
|
依赖:models.Department、models.User、app.core.errors。
|
||||||
逻辑:由 api/admin/departments.py 调用。
|
逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
|
||||||
|
树顶公司层不入库,由前端按 company 字段虚拟分组。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Any
|
from collections import defaultdict
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError, ValidationError
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||||
from app.models import Department, User
|
from app.models import Department, User
|
||||||
|
|
||||||
|
# 业务错误码:与前端 locales/*/errors.json 的 codes 段一一对应
|
||||||
|
ERR_NAME_REQUIRED = 'DEPT.NAME_REQUIRED'
|
||||||
|
ERR_PARENT_INVALID = 'DEPT.PARENT_INVALID'
|
||||||
|
ERR_NAME_EXISTS = 'DEPT.NAME_EXISTS'
|
||||||
|
ERR_CODE_EXISTS = 'DEPT.CODE_EXISTS'
|
||||||
|
ERR_CYCLE_FORBIDDEN = 'DEPT.CYCLE_FORBIDDEN'
|
||||||
|
ERR_HAS_CHILDREN = 'DEPT.HAS_CHILDREN'
|
||||||
|
ERR_HAS_MEMBERS = 'DEPT.HAS_MEMBERS'
|
||||||
|
|
||||||
|
|
||||||
def serialize_department(dept: Department) -> dict:
|
def serialize_department(dept: Department) -> dict:
|
||||||
"""部门 ORM → API dict。"""
|
"""部门 ORM → API dict(平铺行,供部门下拉等旧消费方兼容)。"""
|
||||||
return {
|
return {
|
||||||
'id': dept.id,
|
'id': dept.id,
|
||||||
'name': dept.name,
|
'name': dept.name,
|
||||||
'code': dept.code,
|
'code': dept.code,
|
||||||
'company': dept.company,
|
'company': dept.company,
|
||||||
'description': dept.description,
|
'description': dept.description,
|
||||||
|
'parent_id': dept.parent_id,
|
||||||
|
'sort_order': int(dept.sort_order or 0),
|
||||||
|
'is_hidden': bool(dept.is_hidden),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def list_departments() -> list[dict]:
|
def _member_count_by_name() -> dict[str, int]:
|
||||||
"""返回全部部门(按 name 升序)。"""
|
|
||||||
rows = (
|
|
||||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
|
||||||
.outerjoin(User, User.department == Department.name)
|
|
||||||
.group_by(Department.id)
|
|
||||||
.order_by(Department.name.asc())
|
|
||||||
.all()
|
|
||||||
)
|
|
||||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
|
||||||
|
|
||||||
|
|
||||||
def list_department_members(dept_id: int) -> dict:
|
|
||||||
"""
|
"""
|
||||||
查询指定部门的员工名单。
|
全员按部门名聚合计数。
|
||||||
|
核心逻辑:users.department 为文本字段,一次 GROUP BY 供整棵树复用,避免逐节点查库。
|
||||||
|
"""
|
||||||
|
rows = db.session.query(User.department, func.count(User.id)).group_by(User.department).all()
|
||||||
|
return {name: int(cnt) for name, cnt in rows if name}
|
||||||
|
|
||||||
[STEP 1] 通过部门主键读取部门名称。
|
|
||||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
def _sibling_sort_key(node: dict) -> tuple:
|
||||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
"""同级排序:sort_order 升序 → 编码 → 名称(编码可能为空,排最后)。"""
|
||||||
|
return (node['sort_order'], node['code'] or '', node['name'])
|
||||||
|
|
||||||
|
|
||||||
|
def list_departments() -> list[dict]:
|
||||||
|
"""平铺部门列表(保持旧接口兼容),按公司 → 同级排序号 → 名称排序。"""
|
||||||
|
depts = db.session.query(Department).all()
|
||||||
|
counts = _member_count_by_name()
|
||||||
|
depts.sort(key=lambda d: (d.company or '', d.sort_order or 0, d.code or '', d.name))
|
||||||
|
return [{**serialize_department(d), 'member_count': counts.get(d.name, 0)} for d in depts]
|
||||||
|
|
||||||
|
|
||||||
|
def list_department_tree() -> list[dict]:
|
||||||
|
"""
|
||||||
|
返回完整部门树(children 嵌套,成员数含下级递归汇总)。
|
||||||
|
|
||||||
|
[STEP 1] 一次取全表部门 + 一次按部门名聚合人数。
|
||||||
|
[STEP 2] 按 parent_id 挂 children;父缺失或成环的脏数据按顶级处理(防御)。
|
||||||
|
[STEP 3] 后序遍历汇总 total_member_count(本部门 + 全部下级)。
|
||||||
|
[STEP 4] 同级按 sort_order → 编码 → 名称排序后输出根节点数组。
|
||||||
|
"""
|
||||||
|
depts = db.session.query(Department).all()
|
||||||
|
counts = _member_count_by_name()
|
||||||
|
dept_by_id = {d.id: d for d in depts}
|
||||||
|
nodes = {
|
||||||
|
d.id: {
|
||||||
|
**serialize_department(d),
|
||||||
|
'member_count': counts.get(d.name, 0),
|
||||||
|
'total_member_count': counts.get(d.name, 0),
|
||||||
|
'children': [],
|
||||||
|
}
|
||||||
|
for d in depts
|
||||||
|
}
|
||||||
|
|
||||||
|
def _is_orphan(d: Department) -> bool:
|
||||||
|
"""父链断裂或成环时按顶级处理,避免历史脏数据导致死循环。"""
|
||||||
|
seen: set[int] = set()
|
||||||
|
cur = d
|
||||||
|
while cur.parent_id:
|
||||||
|
if cur.parent_id not in dept_by_id or cur.parent_id in seen:
|
||||||
|
return True
|
||||||
|
seen.add(cur.parent_id)
|
||||||
|
cur = dept_by_id[cur.parent_id]
|
||||||
|
return False
|
||||||
|
|
||||||
|
roots: list[dict] = []
|
||||||
|
for d in depts:
|
||||||
|
node = nodes[d.id]
|
||||||
|
parent_node = nodes.get(d.parent_id) if d.parent_id else None
|
||||||
|
if parent_node is not None and not _is_orphan(d):
|
||||||
|
parent_node['children'].append(node)
|
||||||
|
else:
|
||||||
|
roots.append(node)
|
||||||
|
|
||||||
|
def _summarize(node: dict) -> int:
|
||||||
|
"""后序汇总:total_member_count = 本部门 + 直接成员数之和(树已去环,可安全递归)。"""
|
||||||
|
total = node['member_count']
|
||||||
|
for child in node['children']:
|
||||||
|
total += _summarize(child)
|
||||||
|
node['total_member_count'] = total
|
||||||
|
return total
|
||||||
|
|
||||||
|
def _sort_level(level: list[dict]) -> None:
|
||||||
|
level.sort(key=_sibling_sort_key)
|
||||||
|
for n in level:
|
||||||
|
_sort_level(n['children'])
|
||||||
|
|
||||||
|
_sort_level(roots)
|
||||||
|
for r in roots:
|
||||||
|
_summarize(r)
|
||||||
|
return roots
|
||||||
|
|
||||||
|
|
||||||
|
def _subtree_departments(root: Department) -> list[Department]:
|
||||||
|
"""收集 root 的全部下级部门(不含 root 自身;BFS,脏数据由 parent_id 存在性保证收敛)。"""
|
||||||
|
depts = db.session.query(Department).all()
|
||||||
|
by_parent: dict[Optional[int], list[Department]] = defaultdict(list)
|
||||||
|
for d in depts:
|
||||||
|
by_parent[d.parent_id].append(d)
|
||||||
|
out: list[Department] = []
|
||||||
|
stack = [root.id]
|
||||||
|
while stack:
|
||||||
|
current = stack.pop()
|
||||||
|
for child in by_parent.get(current, []):
|
||||||
|
out.append(child)
|
||||||
|
stack.append(child.id)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def list_department_members(
|
||||||
|
dept_id: int,
|
||||||
|
include_descendants: bool = False,
|
||||||
|
keyword: str = '',
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
分页查询部门员工名单(OA 组织结构右侧面板口径)。
|
||||||
|
|
||||||
|
[STEP 1] 读取部门;include_descendants=True 时递归收集子树内全部部门名。
|
||||||
|
[STEP 2] 按 users.department 文本 in 部门名集合过滤,keyword 模糊匹配
|
||||||
|
姓名/用户名/工号/邮箱/手机号。
|
||||||
|
[STEP 3] 返回 total 与当前页成员资料(含成员所属部门名,供含下级视图区分)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
dept_id: 部门主键。
|
||||||
|
include_descendants: 是否包含全部下级部门的成员(默认 False)。
|
||||||
|
keyword: 搜索关键词(姓名/工号/邮箱/手机号/用户名 模糊匹配)。
|
||||||
|
page: 页码,从 1 起;非正数按 1 处理。
|
||||||
|
page_size: 每页条数,钳制在 1..100。
|
||||||
|
Returns:
|
||||||
|
{ department, total, page, page_size, members }。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 部门不存在。
|
||||||
"""
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if not dept:
|
if not dept:
|
||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Department not found')
|
||||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
if include_descendants:
|
||||||
|
dept_names = [dept.name] + [d.name for d in _subtree_departments(dept)]
|
||||||
|
else:
|
||||||
|
dept_names = [dept.name]
|
||||||
|
|
||||||
|
query = db.session.query(User).filter(User.department.in_(dept_names))
|
||||||
|
kw = (keyword or '').strip()
|
||||||
|
if kw:
|
||||||
|
like = f"%{kw}%"
|
||||||
|
query = query.filter(
|
||||||
|
db.or_(
|
||||||
|
User.real_name.ilike(like),
|
||||||
|
User.username.ilike(like),
|
||||||
|
User.employee_id.ilike(like),
|
||||||
|
User.email.ilike(like),
|
||||||
|
User.phone_number.ilike(like),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
total = query.count()
|
||||||
|
page = max(int(page or 1), 1)
|
||||||
|
page_size = min(max(int(page_size or 20), 1), 100)
|
||||||
|
users = (
|
||||||
|
query.order_by(User.real_name.asc(), User.username.asc())
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
'department': serialize_department(dept),
|
'department': serialize_department(dept),
|
||||||
'count': len(users),
|
'total': total,
|
||||||
|
'page': page,
|
||||||
|
'page_size': page_size,
|
||||||
'members': [
|
'members': [
|
||||||
{
|
{
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
@@ -61,6 +208,8 @@ def list_department_members(dept_id: int) -> dict:
|
|||||||
'real_name': user.real_name,
|
'real_name': user.real_name,
|
||||||
'employee_id': user.employee_id,
|
'employee_id': user.employee_id,
|
||||||
'email': user.email,
|
'email': user.email,
|
||||||
|
'phone_number': user.phone_number,
|
||||||
|
'department': user.department,
|
||||||
'status': user.status,
|
'status': user.status,
|
||||||
}
|
}
|
||||||
for user in users
|
for user in users
|
||||||
@@ -68,25 +217,104 @@ def list_department_members(dept_id: int) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_parent(parent_id: Any) -> Optional[Department]:
|
||||||
|
"""校验上级部门存在性;None/空表示顶级。返回上级 ORM 或 None。"""
|
||||||
|
if parent_id in (None, ''):
|
||||||
|
return None
|
||||||
|
parent = db.session.get(Department, int(parent_id))
|
||||||
|
if not parent:
|
||||||
|
raise ValidationError('Parent department not found', code=ERR_PARENT_INVALID)
|
||||||
|
return parent
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_parent_change(dept: Department, new_parent_id: Any) -> Optional[Department]:
|
||||||
|
"""
|
||||||
|
校验修改上级的合法性:上级必须存在,且不能是自己或自己的子孙(防成环)。
|
||||||
|
[STEP 1] 沿新上级逐层向上走。
|
||||||
|
[STEP 2] 途中遇到本部门 id 即说明会把子树挂到自己下面,抛 CYCLE_FORBIDDEN。
|
||||||
|
"""
|
||||||
|
parent = _validate_parent(new_parent_id)
|
||||||
|
if parent is None:
|
||||||
|
return None
|
||||||
|
if parent.id == dept.id:
|
||||||
|
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||||
|
seen = {dept.id}
|
||||||
|
cur_id: Optional[int] = parent.parent_id
|
||||||
|
while cur_id:
|
||||||
|
if cur_id in seen:
|
||||||
|
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||||
|
seen.add(cur_id)
|
||||||
|
cursor = db.session.get(Department, cur_id)
|
||||||
|
if not cursor:
|
||||||
|
break
|
||||||
|
cur_id = cursor.parent_id
|
||||||
|
return parent
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_sibling_name(
|
||||||
|
name: str,
|
||||||
|
parent_id: Optional[int],
|
||||||
|
company: Optional[str] = None,
|
||||||
|
exclude_id: Optional[int] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
同级查重:同一上级下 name 唯一(树形下允许不同分支同名)。
|
||||||
|
顶级部门(parent_id 为空)按 company 分桶查重——树顶公司层为虚拟分组,
|
||||||
|
两家公司的顶级部门允许同名(如各公司均有「管理部」)。
|
||||||
|
"""
|
||||||
|
query = db.session.query(Department).filter(Department.name == name)
|
||||||
|
if parent_id:
|
||||||
|
query = query.filter(Department.parent_id == parent_id)
|
||||||
|
else:
|
||||||
|
query = query.filter(Department.parent_id.is_(None))
|
||||||
|
query = query.filter(Department.company == company) if company else query.filter(Department.company.is_(None))
|
||||||
|
if exclude_id:
|
||||||
|
query = query.filter(Department.id != exclude_id)
|
||||||
|
if query.first():
|
||||||
|
raise ValidationError('Sibling department name exists', code=ERR_NAME_EXISTS)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_str(value: Any) -> str:
|
||||||
|
return (value or '').strip() if isinstance(value, str) else ''
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_int(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def create_department(data: dict[str, Any]) -> dict:
|
def create_department(data: dict[str, Any]) -> dict:
|
||||||
"""
|
"""
|
||||||
创建部门。
|
创建部门。
|
||||||
|
|
||||||
|
[STEP 1] 校验名称必填、上级存在、同级不重名、编码全局唯一。
|
||||||
|
[STEP 2] 公司未填时继承上级部门 company(树顶公司分组依赖该字段)。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{ id, name }。
|
{ id, name }。
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: name 缺失或 name/code 重复。
|
ValidationError: NAME_REQUIRED / PARENT_INVALID / NAME_EXISTS / CODE_EXISTS。
|
||||||
"""
|
"""
|
||||||
if not data.get('name'):
|
name = _clean_str(data.get('name'))
|
||||||
raise ValidationError('Name is required')
|
if not name:
|
||||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||||
raise ValidationError('Name exists')
|
parent_id = data.get('parent_id')
|
||||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
parent = _validate_parent(parent_id)
|
||||||
raise ValidationError('Code exists')
|
company = _clean_str(data.get('company')) or (parent.company if parent else None)
|
||||||
|
_validate_sibling_name(name, parent.id if parent else None, company=company)
|
||||||
|
code = _clean_str(data.get('code')) or None
|
||||||
|
if code and db.session.query(Department).filter_by(code=code).first():
|
||||||
|
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||||
dept = Department(
|
dept = Department(
|
||||||
name=data['name'],
|
name=name,
|
||||||
code=data.get('code'),
|
code=code,
|
||||||
company=data.get('company'),
|
company=company,
|
||||||
description=data.get('description'),
|
description=_clean_str(data.get('description')) or None,
|
||||||
|
parent_id=parent.id if parent else None,
|
||||||
|
sort_order=_clean_int(data.get('sort_order')),
|
||||||
|
is_hidden=bool(data.get('is_hidden')),
|
||||||
)
|
)
|
||||||
db.session.add(dept)
|
db.session.add(dept)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -95,34 +323,64 @@ def create_department(data: dict[str, Any]) -> dict:
|
|||||||
|
|
||||||
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
更新部门字段。
|
更新部门字段(含上级转移、同级排序、隐藏标记)。
|
||||||
|
|
||||||
|
[STEP 1] 名称变更时按「变更后的上级」做同级查重。
|
||||||
|
[STEP 2] 上级变更时校验存在性并防成环。
|
||||||
|
[STEP 3] 编码变更时全局唯一校验。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotFoundError: 部门不存在。
|
NotFoundError: 部门不存在。
|
||||||
ValidationError: name/code 与其它记录冲突。
|
ValidationError: NAME_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
|
||||||
"""
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if not dept:
|
if not dept:
|
||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Department not found')
|
||||||
if 'name' in data:
|
|
||||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
if 'parent_id' in data:
|
||||||
raise ValidationError('Name exists')
|
parent = _validate_parent_change(dept, data['parent_id'])
|
||||||
dept.name = data['name']
|
dept.parent_id = parent.id if parent else None
|
||||||
if 'code' in data:
|
|
||||||
if data['code'] and db.session.query(Department).filter(
|
|
||||||
Department.code == data['code'], Department.id != dept_id
|
|
||||||
).first():
|
|
||||||
raise ValidationError('Code exists')
|
|
||||||
dept.code = data['code']
|
|
||||||
if 'company' in data:
|
if 'company' in data:
|
||||||
dept.company = data['company']
|
dept.company = _clean_str(data.get('company')) or None
|
||||||
|
|
||||||
|
if 'name' in data:
|
||||||
|
name = _clean_str(data.get('name'))
|
||||||
|
if not name:
|
||||||
|
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||||
|
_validate_sibling_name(name, dept.parent_id, company=dept.company, exclude_id=dept_id)
|
||||||
|
dept.name = name
|
||||||
|
|
||||||
|
if 'code' in data:
|
||||||
|
code = _clean_str(data.get('code')) or None
|
||||||
|
if code and db.session.query(Department).filter(
|
||||||
|
Department.code == code, Department.id != dept_id
|
||||||
|
).first():
|
||||||
|
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||||
|
dept.code = code
|
||||||
|
|
||||||
if 'description' in data:
|
if 'description' in data:
|
||||||
dept.description = data['description']
|
dept.description = _clean_str(data.get('description')) or None
|
||||||
|
if 'sort_order' in data:
|
||||||
|
dept.sort_order = _clean_int(data.get('sort_order'))
|
||||||
|
if 'is_hidden' in data:
|
||||||
|
dept.is_hidden = bool(data.get('is_hidden'))
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
def delete_department(dept_id: int) -> None:
|
def delete_department(dept_id: int) -> None:
|
||||||
"""删除部门(不存在时静默成功)。"""
|
"""
|
||||||
|
删除部门。
|
||||||
|
Raises:
|
||||||
|
ConflictError: 存在下级部门(HAS_CHILDREN)或名下仍有员工(HAS_MEMBERS)时禁止删除。
|
||||||
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if dept:
|
if not dept:
|
||||||
db.session.delete(dept)
|
return
|
||||||
db.session.commit()
|
if db.session.query(Department).filter(Department.parent_id == dept_id).first():
|
||||||
|
raise ConflictError('Department has child departments', code=ERR_HAS_CHILDREN)
|
||||||
|
if db.session.query(User).filter(User.department == dept.name).first():
|
||||||
|
raise ConflictError('Department still has members', code=ERR_HAS_MEMBERS)
|
||||||
|
db.session.delete(dept)
|
||||||
|
db.session.commit()
|
||||||
@@ -7,6 +7,7 @@ services/admin/freight_rpa_source_admin_service.py
|
|||||||
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
||||||
onhand_source_repository.validate_source_profile、audit_service。
|
onhand_source_repository.validate_source_profile、audit_service。
|
||||||
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
||||||
|
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
|
||||||
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -15,7 +16,7 @@ from __future__ import annotations
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
from app.models import (
|
from app.models import (
|
||||||
FreightRpaOnhandExternalMapping,
|
FreightRpaOnhandExternalMapping,
|
||||||
@@ -38,7 +39,7 @@ from app.services.admin.freight_rpa_form_utils import (
|
|||||||
validate_report_path as _validate_report_path,
|
validate_report_path as _validate_report_path,
|
||||||
)
|
)
|
||||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||||
@@ -77,27 +78,50 @@ def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _stored_username(profile: FreightRpaProfile) -> str | None:
|
||||||
|
"""解密已保存的用户名,供管理端辨认账号。
|
||||||
|
|
||||||
|
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
|
||||||
|
密码不走本函数。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
profile: 已持久化的货代登录连接。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str | None: 用户名明文;未配置或无法解密时为 None。
|
||||||
|
"""
|
||||||
|
if not profile.username_ciphertext:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return decrypt_credential(profile.username_ciphertext)
|
||||||
|
except (ServiceUnavailableError, ValidationError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||||
|
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
|
||||||
return {
|
return {
|
||||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||||
'upload_config_json': profile.upload_config_json,
|
'upload_config_json': profile.upload_config_json,
|
||||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
'config_version': profile.config_version,
|
||||||
|
'username': _stored_username(profile),
|
||||||
|
'username_masked': _mask(profile.username_ciphertext),
|
||||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _mask(ciphertext: str | None) -> str | None:
|
def _mask(ciphertext: str | None) -> str | None:
|
||||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
"""密码等不可回显凭据只报告是否已配置。"""
|
||||||
return 'configured' if ciphertext else None
|
return 'configured' if ciphertext else None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def list_profiles() -> list[dict[str, Any]]:
|
def list_profiles() -> list[dict[str, Any]]:
|
||||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
|
||||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||||
|
|
||||||
|
|
||||||
@@ -113,7 +137,11 @@ def delete_profile(profile_id: int) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
"""创建或更新货代登录连接。
|
||||||
|
|
||||||
|
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
|
||||||
|
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
|
||||||
|
"""
|
||||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||||
if profile_id and profile is None:
|
if profile_id and profile is None:
|
||||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||||
@@ -138,11 +166,14 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
|
|||||||
)
|
)
|
||||||
username = _text(data, 'username')
|
username = _text(data, 'username')
|
||||||
password = _text(data, 'password')
|
password = _text(data, 'password')
|
||||||
if username is not None:
|
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
|
||||||
|
username_changed = False
|
||||||
|
if username is not None and _stored_username(profile) != username:
|
||||||
profile.username_ciphertext = encrypt_credential(username)
|
profile.username_ciphertext = encrypt_credential(username)
|
||||||
|
username_changed = True
|
||||||
if password is not None:
|
if password is not None:
|
||||||
profile.password_ciphertext = encrypt_credential(password)
|
profile.password_ciphertext = encrypt_credential(password)
|
||||||
if username is not None or password is not None:
|
if username_changed or password is not None:
|
||||||
profile.credential_updated_at = datetime.utcnow()
|
profile.credential_updated_at = datetime.utcnow()
|
||||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||||
if 'upload_config_json' in data:
|
if 'upload_config_json' in data:
|
||||||
|
|||||||
@@ -16,8 +16,9 @@ from sqlalchemy import asc, desc, func, or_
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError
|
from app.core.errors import NotFoundError
|
||||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
from app.models import Agent, ChatLog, Feedback, FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
from app.models.base import user_agent_permissions
|
from app.models.base import user_agent_permissions
|
||||||
|
from app.services.file_assets.service import read_asset_bytes
|
||||||
|
|
||||||
USAGE_BY_USER_TOP_LIMIT = 50
|
USAGE_BY_USER_TOP_LIMIT = 50
|
||||||
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
||||||
@@ -36,6 +37,16 @@ USAGE_LOW_AGENT_MAX_CHATS = 2
|
|||||||
# 运营提醒:低使用应用最多返回条数
|
# 运营提醒:低使用应用最多返回条数
|
||||||
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
||||||
|
|
||||||
|
# 反馈图片响应 Content-Type 白名单:按资产扩展名固定响应类型。
|
||||||
|
# [SECURITY] 存储 mime_type 来自上传时客户端 multipart 头,不可信;代理内联输出时
|
||||||
|
# 若原样透传可被伪造为 text/html 等,构成存储型 XSS 面,故一律按扩展名收敛。
|
||||||
|
FEEDBACK_IMAGE_CONTENT_TYPES = {
|
||||||
|
'png': 'image/png',
|
||||||
|
'jpg': 'image/jpeg',
|
||||||
|
'jpeg': 'image/jpeg',
|
||||||
|
'webp': 'image/webp',
|
||||||
|
}
|
||||||
|
|
||||||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||||||
USAGE_RANGE_DAYS = {
|
USAGE_RANGE_DAYS = {
|
||||||
'7d': 7,
|
'7d': 7,
|
||||||
@@ -557,6 +568,39 @@ def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
|||||||
return query
|
return query
|
||||||
|
|
||||||
|
|
||||||
|
def _attach_general_feedback_images(rows: list[dict], feedback_ids: list[int]) -> None:
|
||||||
|
"""
|
||||||
|
批量回填每行 images 元数据(单查询,按 sort_order 排序),无图行置空列表。
|
||||||
|
|
||||||
|
用途:通用反馈报表行内附图元数据(前端缩略图入口);单条 IN 查询避免 N+1。
|
||||||
|
逻辑:GeneralFeedbackImage join FileAsset 按 feedback_id 批量取行,
|
||||||
|
按 (sort_order, id) 升序分组后写回各行的 'images' 键。
|
||||||
|
Args:
|
||||||
|
rows: list_general_feedbacks_report 构建出的行字典列表(含 'id' 键),原地修改。
|
||||||
|
feedback_ids: rows 对应的反馈 ID 列表。
|
||||||
|
"""
|
||||||
|
if not feedback_ids:
|
||||||
|
return
|
||||||
|
records = (
|
||||||
|
db.session.query(GeneralFeedbackImage, FileAsset)
|
||||||
|
.join(FileAsset, FileAsset.id == GeneralFeedbackImage.asset_id)
|
||||||
|
.filter(GeneralFeedbackImage.feedback_id.in_(feedback_ids))
|
||||||
|
.order_by(asc(GeneralFeedbackImage.sort_order), asc(GeneralFeedbackImage.id))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
grouped: dict[int, list[dict]] = {}
|
||||||
|
for image, asset in records:
|
||||||
|
grouped.setdefault(int(image.feedback_id), []).append({
|
||||||
|
'image_id': int(image.id),
|
||||||
|
'asset_no': asset.asset_no,
|
||||||
|
'original_filename': asset.original_filename,
|
||||||
|
'file_size': int(asset.file_size or 0),
|
||||||
|
'sort_order': int(image.sort_order or 0),
|
||||||
|
})
|
||||||
|
for row in rows:
|
||||||
|
row['images'] = grouped.get(int(row['id']), [])
|
||||||
|
|
||||||
|
|
||||||
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
||||||
"""通用反馈列表(报表页)。"""
|
"""通用反馈列表(报表页)。"""
|
||||||
query = (
|
query = (
|
||||||
@@ -586,9 +630,48 @@ def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
|||||||
row['real_name'] = real_name
|
row['real_name'] = real_name
|
||||||
row['department'] = department
|
row['department'] = department
|
||||||
rows.append(row)
|
rows.append(row)
|
||||||
|
_attach_general_feedback_images(rows, [row['id'] for row in rows])
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict:
|
||||||
|
"""
|
||||||
|
读取反馈图片字节(管理端代理输出,不走 MinIO 预签名,见 spec D6)。
|
||||||
|
|
||||||
|
用途:管理端报表页内联预览反馈截图;由 api/admin/reports.py 的 raw 路由调用。
|
||||||
|
逻辑:校验 image 归属该 feedback → 校验资产未删除 → read_asset_bytes 读字节
|
||||||
|
(内部再拦过期/已删除的 FILE_ASSET.*),错配一律按不存在处理避免探测他人资产。
|
||||||
|
响应 Content-Type 按扩展名白名单(FEEDBACK_IMAGE_CONTENT_TYPES)固定,
|
||||||
|
不透传存储 mime(其来自客户端上传头,不可信)。
|
||||||
|
Args:
|
||||||
|
feedback_id: 反馈 ID;image 必须归属该反馈,错配按不存在处理。
|
||||||
|
image_id: 反馈附件图片 ID。
|
||||||
|
Returns:
|
||||||
|
{'data': bytes, 'mime_type': str, 'filename': str};mime_type 由扩展名白名单决定,
|
||||||
|
未知扩展名(历史/边界行)降级 application/octet-stream。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: code=FEEDBACK.IMAGE_NOT_FOUND——image 不存在、不属于该反馈或资产已删除。
|
||||||
|
"""
|
||||||
|
image = (
|
||||||
|
db.session.query(GeneralFeedbackImage)
|
||||||
|
.filter_by(id=image_id, feedback_id=feedback_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if image is None:
|
||||||
|
raise NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')
|
||||||
|
asset = db.session.get(FileAsset, image.asset_id)
|
||||||
|
if asset is None or asset.deleted_at is not None:
|
||||||
|
raise NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')
|
||||||
|
data = read_asset_bytes(asset)
|
||||||
|
# [SECURITY] 提交时仅校验扩展名白名单,存储 mime 仍是客户端自报值;响应类型只能信扩展名
|
||||||
|
mime_type = FEEDBACK_IMAGE_CONTENT_TYPES.get(str(asset.extension or '').lower(), 'application/octet-stream')
|
||||||
|
return {
|
||||||
|
'data': data,
|
||||||
|
'mime_type': mime_type,
|
||||||
|
'filename': asset.original_filename,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
||||||
"""通用反馈计数。"""
|
"""通用反馈计数。"""
|
||||||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||||
|
|||||||
@@ -3,19 +3,22 @@ backend/app/services/admin/user_service.py
|
|||||||
|
|
||||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
||||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色只同步角色包,不再按人勾应用。
|
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色按角色集合重算并集,不再按人勾应用。
|
||||||
|
提交 roles 时替换该用户的全部业务角色;只提交 role 时改成这一个角色。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.orm import joinedload
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User
|
||||||
|
from app.models.permission_role import PermissionRole, user_permission_roles
|
||||||
from app.services.auth import casdoor_service
|
from app.services.auth import casdoor_service
|
||||||
from app.services.permission_roles import service as role_service
|
from app.services.permission_roles import service as role_service
|
||||||
from app.services.user_admin import delete_admin_users
|
from app.services.user_admin import delete_admin_users
|
||||||
@@ -69,15 +72,22 @@ def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None)
|
|||||||
raise ConflictError(message, code=code, details={'field': field})
|
raise ConflictError(message, code=code, details={'field': field})
|
||||||
|
|
||||||
|
|
||||||
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
def serialize_admin_user(
|
||||||
|
user: User,
|
||||||
|
role_names: dict[str, str] | None = None,
|
||||||
|
assigned: list | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""管理端用户行。role 是主角色,role_name / role_codes 覆盖全部已挂角色。"""
|
||||||
names = role_names if role_names is not None else role_service.list_role_name_map()
|
names = role_names if role_names is not None else role_service.list_role_name_map()
|
||||||
|
described = role_service.describe_user_roles(user, assigned=assigned, role_names=names)
|
||||||
return {
|
return {
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
'username': user.username,
|
'username': user.username,
|
||||||
'email': user.email,
|
'email': user.email,
|
||||||
'department': user.department,
|
'department': user.department,
|
||||||
'role': user.role,
|
'role': described['role'],
|
||||||
'role_name': names.get(user.role) or user.role,
|
'role_name': described['role_name'],
|
||||||
|
'role_codes': described['role_codes'],
|
||||||
'is_platform_admin': user.is_platform_admin(),
|
'is_platform_admin': user.is_platform_admin(),
|
||||||
'status': user.status,
|
'status': user.status,
|
||||||
'real_name': user.real_name,
|
'real_name': user.real_name,
|
||||||
@@ -95,12 +105,23 @@ def apply_users_filters(query, query_params: dict[str, str]):
|
|||||||
'username': User.username,
|
'username': User.username,
|
||||||
'email': User.email,
|
'email': User.email,
|
||||||
'department': User.department,
|
'department': User.department,
|
||||||
'role': User.role,
|
|
||||||
'status': User.status,
|
'status': User.status,
|
||||||
'real_name': User.real_name,
|
'real_name': User.real_name,
|
||||||
'employee_id': User.employee_id,
|
'employee_id': User.employee_id,
|
||||||
'phone_number': User.phone_number,
|
'phone_number': User.phone_number,
|
||||||
}
|
}
|
||||||
|
role_value = (query_params.get('role') or '').strip()
|
||||||
|
if role_value:
|
||||||
|
# [STEP 1] 角色筛选同时命中主角色和成员表里的其他角色
|
||||||
|
if role_service.roles_configured():
|
||||||
|
member_ids = (
|
||||||
|
db.session.query(user_permission_roles.c.user_id)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.filter(PermissionRole.code.ilike(f'%{role_value}%'))
|
||||||
|
)
|
||||||
|
query = query.filter(or_(User.role.ilike(f'%{role_value}%'), User.id.in_(member_ids)))
|
||||||
|
else:
|
||||||
|
query = query.filter(User.role.ilike(f'%{role_value}%'))
|
||||||
for key, column in filter_columns.items():
|
for key, column in filter_columns.items():
|
||||||
value = (query_params.get(key) or '').strip()
|
value = (query_params.get(key) or '').strip()
|
||||||
if value:
|
if value:
|
||||||
@@ -142,7 +163,8 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
|||||||
if 'page' not in query_params:
|
if 'page' not in query_params:
|
||||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||||
names = role_service.list_role_name_map()
|
names = role_service.list_role_name_map()
|
||||||
return [serialize_admin_user(u, names) for u in users]
|
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
||||||
|
return [serialize_admin_user(user, names, assigned.get(user.id)) for user in users]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
page = int(query_params.get('page') or 1)
|
page = int(query_params.get('page') or 1)
|
||||||
@@ -168,8 +190,9 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
|||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
names = role_service.list_role_name_map()
|
names = role_service.list_role_name_map()
|
||||||
|
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
||||||
return {
|
return {
|
||||||
'items': [serialize_admin_user(u, names) for u in users],
|
'items': [serialize_admin_user(user, names, assigned.get(user.id)) for user in users],
|
||||||
'total': int(total),
|
'total': int(total),
|
||||||
'page': page,
|
'page': page,
|
||||||
'page_size': page_size,
|
'page_size': page_size,
|
||||||
@@ -200,10 +223,17 @@ def create_user(data: dict[str, Any]) -> dict:
|
|||||||
employee_id=empty_to_none(data.get('employee_id')),
|
employee_id=empty_to_none(data.get('employee_id')),
|
||||||
phone_number=empty_to_none(data.get('phone_number')),
|
phone_number=empty_to_none(data.get('phone_number')),
|
||||||
)
|
)
|
||||||
role_code = role_service.assert_role_assignable(
|
if isinstance(data.get('roles'), list) and data.get('roles'):
|
||||||
data.get('role') or role_service.default_role_code(),
|
role_codes = [
|
||||||
allow_admin=True,
|
role_service.assert_role_assignable(code, allow_admin=True)
|
||||||
)
|
for code in data.get('roles') or []
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
role_codes = [role_service.assert_role_assignable(
|
||||||
|
data.get('role') or role_service.default_role_code(),
|
||||||
|
allow_admin=True,
|
||||||
|
)]
|
||||||
|
role_code = role_codes[0]
|
||||||
user = User(
|
user = User(
|
||||||
username=data['username'],
|
username=data['username'],
|
||||||
email=email,
|
email=email,
|
||||||
@@ -220,7 +250,7 @@ def create_user(data: dict[str, Any]) -> dict:
|
|||||||
db.session.add(user)
|
db.session.add(user)
|
||||||
try:
|
try:
|
||||||
if role_service.roles_configured():
|
if role_service.roles_configured():
|
||||||
role_service.sync_user_grants_from_role(user)
|
role_service.assign_role_codes(user, role_codes)
|
||||||
elif data.get('agent_ids'):
|
elif data.get('agent_ids'):
|
||||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||||
user.agents = agents
|
user.agents = agents
|
||||||
@@ -279,20 +309,25 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
|||||||
assert_user_unique_fields(user_id, **unique_updates)
|
assert_user_unique_fields(user_id, **unique_updates)
|
||||||
new_password = empty_to_none(data.get('password'))
|
new_password = empty_to_none(data.get('password'))
|
||||||
try:
|
try:
|
||||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
for key in ['email', 'department', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||||
if key in data:
|
if key in data:
|
||||||
if key == 'role':
|
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||||
next_role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
|
||||||
role_service.ensure_not_last_admin(user, next_role)
|
|
||||||
user.role = next_role
|
|
||||||
elif key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
|
||||||
setattr(user, key, empty_to_none(data[key]))
|
setattr(user, key, empty_to_none(data[key]))
|
||||||
else:
|
else:
|
||||||
setattr(user, key, data[key])
|
setattr(user, key, data[key])
|
||||||
if role_service.roles_configured():
|
if role_service.roles_configured() and ('role' in data or 'roles' in data):
|
||||||
|
if isinstance(data.get('roles'), list):
|
||||||
|
codes = [
|
||||||
|
role_service.assert_role_assignable(code, allow_admin=True)
|
||||||
|
for code in data.get('roles') or []
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
codes = [role_service.assert_role_assignable(data.get('role'), allow_admin=True)]
|
||||||
|
role_service.ensure_role_codes_keep_admin(user, codes)
|
||||||
|
role_service.assign_role_codes(user, codes)
|
||||||
|
elif not role_service.roles_configured():
|
||||||
if 'role' in data:
|
if 'role' in data:
|
||||||
role_service.sync_user_grants_from_role(user)
|
user.role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||||
else:
|
|
||||||
if 'feature_permissions' in data or 'role' in data:
|
if 'feature_permissions' in data or 'role' in data:
|
||||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||||
user.set_feature_permissions(permissions_payload)
|
user.set_feature_permissions(permissions_payload)
|
||||||
@@ -340,8 +375,11 @@ def batch_update_users(user_ids: list[Any], data: dict[str, Any]) -> dict:
|
|||||||
user.status = payload.get('status')
|
user.status = payload.get('status')
|
||||||
if next_role:
|
if next_role:
|
||||||
role_service.ensure_not_last_admin(user, next_role)
|
role_service.ensure_not_last_admin(user, next_role)
|
||||||
user.role = next_role
|
if role_service.roles_configured():
|
||||||
role_service.sync_user_grants_from_role(user)
|
role_service.assign_role_codes(user, [next_role])
|
||||||
|
else:
|
||||||
|
user.role = next_role
|
||||||
|
role_service.sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {'status': 'ok', 'updated_count': len(users)}
|
return {'status': 'ok', 'updated_count': len(users)}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""
|
||||||
|
services/chat/capability_list.py
|
||||||
|
|
||||||
|
用途:查询指定智能体在常用问题(QuickQuestion)中的「能力清单」条目标准答案。
|
||||||
|
依赖:models.QuickQuestion、core.errors.AppError、SQLAlchemy db。
|
||||||
|
逻辑:Dify 知识库未命中兜底回复会在前端展示【知识库内容清单】按钮;按钮点击后由
|
||||||
|
api/chat/capability_list.py 调用本模块,按 agent_id 过滤全局条目并返回标准答案。
|
||||||
|
管理端维护约定:条目标题形如「<应用名>·能力清单条目」,因此以标题含「能力清单」
|
||||||
|
作为识别关键字,应用归属仍以 agent_id 外键为准(禁止按标题前缀解析应用名)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.errors import AppError
|
||||||
|
from app.models import QuickQuestion
|
||||||
|
|
||||||
|
# 能力清单条目的标题识别关键字(管理端维护约定,见模块 docstring)。
|
||||||
|
CAPABILITY_LIST_TITLE_KEYWORD = '能力清单'
|
||||||
|
|
||||||
|
|
||||||
|
def get_agent_capability_list(agent: Any) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
查询智能体的知识库内容清单条目。
|
||||||
|
|
||||||
|
用途:聊天端兜底回复【知识库内容清单】按钮的数据来源。
|
||||||
|
核心逻辑:
|
||||||
|
1. 仅匹配全局条目(user_id 为空)且归属当前 agent_id;
|
||||||
|
2. 标题须含「能力清单」关键字,且标准答案非空;
|
||||||
|
3. 多条命中时按 sort_order、id 取第一条,保证返回稳定。
|
||||||
|
Args:
|
||||||
|
agent: 已通过 require_agent_permission 鉴权的 Agent 模型实例,禁止传 None。
|
||||||
|
Returns:
|
||||||
|
含 id/agent_id/title/question/answer 的条目字典,answer 为标准答案原文。
|
||||||
|
Raises:
|
||||||
|
AppError: code=CHAT.CAPABILITY_LIST_NOT_FOUND,表示该应用尚未配置能力清单条目。
|
||||||
|
"""
|
||||||
|
agent_id = getattr(agent, 'id', None)
|
||||||
|
if not agent_id:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent id', http_status=500)
|
||||||
|
|
||||||
|
entry = (
|
||||||
|
db.session.query(QuickQuestion)
|
||||||
|
.filter(
|
||||||
|
QuickQuestion.agent_id == agent_id,
|
||||||
|
QuickQuestion.user_id.is_(None),
|
||||||
|
QuickQuestion.title.contains(CAPABILITY_LIST_TITLE_KEYWORD),
|
||||||
|
QuickQuestion.answer.isnot(None),
|
||||||
|
QuickQuestion.answer != '',
|
||||||
|
)
|
||||||
|
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if entry is None:
|
||||||
|
raise AppError(
|
||||||
|
code='CHAT.CAPABILITY_LIST_NOT_FOUND',
|
||||||
|
message='capability list entry is not configured for this agent',
|
||||||
|
http_status=404,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'id': entry.id,
|
||||||
|
'agent_id': entry.agent_id,
|
||||||
|
'title': entry.title,
|
||||||
|
'question': entry.question,
|
||||||
|
'answer': entry.answer or '',
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
|
|||||||
|
|
||||||
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
||||||
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
||||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
|
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款、验收款、质保款都可手动标为已付,并关闭该节点尚未发送的预警。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -40,6 +40,7 @@ from app.services.contract_payment.erp_payment_service import (
|
|||||||
normalize_purchase_order_no,
|
normalize_purchase_order_no,
|
||||||
resolve_paid_node_dates,
|
resolve_paid_node_dates,
|
||||||
)
|
)
|
||||||
|
from app.services.contract_payment.ledger_focus import stage_has_nothing_to_pay
|
||||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||||
from app.services.schedule.timezone_util import compute_next_run_at
|
from app.services.schedule.timezone_util import compute_next_run_at
|
||||||
|
|
||||||
@@ -52,6 +53,7 @@ class _AlertRecipient:
|
|||||||
oa_wecom_userid: str | None = None
|
oa_wecom_userid: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
_ERP_PAID_STAGE_TYPES = {"prepayment", "shipment", "acceptance", "warranty"}
|
||||||
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
|
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
|
||||||
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
|
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
|
||||||
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
|
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
|
||||||
@@ -65,7 +67,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
|||||||
|
|
||||||
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
||||||
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
||||||
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
|
ERP `apa_file` 的合格付款记录按金额匹配四个阶段,并停止已付款阶段尚未发送的后续轮次。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||||
Args:
|
Args:
|
||||||
today: 业务日期,未传时使用服务器日期。
|
today: 业务日期,未传时使用服务器日期。
|
||||||
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
||||||
@@ -85,14 +87,20 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
|||||||
payable_orders = [
|
payable_orders = [
|
||||||
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
|
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
|
||||||
for node, contract in rows
|
for node, contract in rows
|
||||||
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
|
if node.node_type in _ERP_PAID_STAGE_TYPES
|
||||||
|
and normalize_purchase_order_no(contract.purchase_order_no)
|
||||||
|
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||||
]
|
]
|
||||||
paid_records = fetch_paid_records(payable_orders)
|
paid_records = fetch_paid_records(payable_orders)
|
||||||
paid_node_dates: dict[int, str | None] = {}
|
paid_node_dates: dict[int, str | None] = {}
|
||||||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||||||
for node, contract in rows:
|
for node, contract in rows:
|
||||||
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
||||||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
if (
|
||||||
|
node.node_type in _ERP_PAID_STAGE_TYPES
|
||||||
|
and purchase_order_no
|
||||||
|
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||||
|
):
|
||||||
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
||||||
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
||||||
paid_node_dates.update(resolve_paid_node_dates(
|
paid_node_dates.update(resolve_paid_node_dates(
|
||||||
@@ -100,6 +108,11 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
|||||||
paid_records.get(ledger_key, []),
|
paid_records.get(ledger_key, []),
|
||||||
))
|
))
|
||||||
for node, contract in rows:
|
for node, contract in rows:
|
||||||
|
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||||
|
# 金额和比例都为 0 时没有应付金额,关掉尚未发送的预警,不再按日期升级。
|
||||||
|
resolved += _resolve_pending_alerts(node_id=node.id, reason="nothing_to_pay")
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
anchor = _anchor_date(contract=contract, node=node)
|
anchor = _anchor_date(contract=contract, node=node)
|
||||||
if anchor is None:
|
if anchor is None:
|
||||||
skipped += 1
|
skipped += 1
|
||||||
@@ -113,7 +126,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
|||||||
scheduled_date = anchor + timedelta(days=offset_days)
|
scheduled_date = anchor + timedelta(days=offset_days)
|
||||||
if today < scheduled_date:
|
if today < scheduled_date:
|
||||||
continue
|
continue
|
||||||
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
|
# ERP 合格付款按金额匹配四个阶段;同金额时按预付款、出货款、验收款、质保款的顺序占用。
|
||||||
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
|
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
|
||||||
if erp_paid:
|
if erp_paid:
|
||||||
resolved += _resolve_pending_alerts(node_id=node.id)
|
resolved += _resolve_pending_alerts(node_id=node.id)
|
||||||
@@ -160,10 +173,10 @@ def _resolve_pending_alerts(*, node_id: int, reason: str = "erp_paid") -> int:
|
|||||||
|
|
||||||
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
||||||
"""
|
"""
|
||||||
把一个未付的预付款或出货款手动标为已付。
|
把一个未付阶段手动标为已付。
|
||||||
|
|
||||||
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
核心逻辑:预付款、出货款、验收款、质保款都可以标记。只改这一阶段,写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||||
验收款、质保款和已经付款的阶段不能标记。
|
金额和比例都为 0、已经付款、或不是进行中的阶段不能标记。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
contract_id: 合同台账主键。
|
contract_id: 合同台账主键。
|
||||||
@@ -186,8 +199,10 @@ def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, ope
|
|||||||
node = db.session.get(ContractPaymentNode, node_id)
|
node = db.session.get(ContractPaymentNode, node_id)
|
||||||
if node is None or node.contract_id != contract.id:
|
if node is None or node.contract_id != contract.id:
|
||||||
raise NotFoundError("付款节点不存在")
|
raise NotFoundError("付款节点不存在")
|
||||||
if node.node_type not in {"prepayment", "shipment"}:
|
if node.node_type not in _ERP_PAID_STAGE_TYPES:
|
||||||
raise ValidationError("只有预付款和出货款可以手动标为已付")
|
raise ValidationError("该阶段不能标为已付")
|
||||||
|
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||||
|
raise ValidationError("该阶段没有应付金额,不能标为已付")
|
||||||
if node.status == "paid":
|
if node.status == "paid":
|
||||||
raise ValidationError("该阶段已是已付")
|
raise ValidationError("该阶段已是已付")
|
||||||
if node.status != "active":
|
if node.status != "active":
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/contract_payment/erp_payment_service.py
|
backend/app/services/contract_payment/erp_payment_service.py
|
||||||
|
|
||||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
|
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款、出货款、验收款和质保款的付款完成事实来源。
|
||||||
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
||||||
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||||
"""
|
"""
|
||||||
@@ -17,7 +17,7 @@ from typing import Iterable
|
|||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
||||||
|
|
||||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2, "acceptance": 3, "warranty": 4}
|
||||||
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
||||||
_SCHEMA_BY_COMPANY = {
|
_SCHEMA_BY_COMPANY = {
|
||||||
"无锡和宏智散热科技有限公司": "WZHHZ",
|
"无锡和宏智散热科技有限公司": "WZHHZ",
|
||||||
@@ -100,7 +100,7 @@ def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[s
|
|||||||
"""
|
"""
|
||||||
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
||||||
|
|
||||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
|
AI 触发时机:合同付款预警每日扫描前,需要判断预付款、出货款、验收款、质保款是否已经完成付款。
|
||||||
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
||||||
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
||||||
某一账套查询失败只影响该账套,其它账套继续。
|
某一账套查询失败只影响该账套,其它账套继续。
|
||||||
@@ -234,14 +234,13 @@ def resolve_paid_node_dates(
|
|||||||
paid_rows: Iterable[ErpPaidRow],
|
paid_rows: Iterable[ErpPaidRow],
|
||||||
) -> dict[int, str | None]:
|
) -> dict[int, str | None]:
|
||||||
"""
|
"""
|
||||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
|
将同一采购单的 ERP 付款记录匹配到预付款、出货款、验收款、质保款节点,并返回节点 ID 到付款日期的映射。
|
||||||
|
|
||||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
|
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
|
||||||
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
金额相同则按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||||
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
|
若干阶段金额之和与该笔付款一致,则把这些阶段同时标记为已付款,并携带该笔付款日期。
|
||||||
则把两者同时标记为已付款,并携带该笔付款日期。
|
|
||||||
Args:
|
Args:
|
||||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||||
paid_rows: 该采购单的合格 ERP 付款记录。
|
paid_rows: 该采购单的合格 ERP 付款记录。
|
||||||
Returns:
|
Returns:
|
||||||
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
||||||
@@ -268,14 +267,13 @@ def resolve_paid_node_ids(
|
|||||||
paid_amounts: Iterable[Decimal],
|
paid_amounts: Iterable[Decimal],
|
||||||
) -> set[int]:
|
) -> set[int]:
|
||||||
"""
|
"""
|
||||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
|
将同一采购单的 ERP 付款金额匹配到预付款、出货款、验收款、质保款节点。
|
||||||
|
|
||||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
|
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
|
||||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
|
金额不同则自然对应相应节点,金额相同时按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;
|
||||||
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
|
若单节点无匹配但若干阶段金额之和与该笔付款一致,则一并标记这些阶段为已付款。
|
||||||
(预付款、出货款在同一笔请款中一并请款的场景)。
|
|
||||||
Args:
|
Args:
|
||||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||||
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
||||||
Returns:
|
Returns:
|
||||||
已付款节点 ID 集合。
|
已付款节点 ID 集合。
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ backend/app/services/contract_payment/ledger_focus.py
|
|||||||
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
||||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||||
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||||
|
金额和比例都为 0 的阶段不参与逾期、即将到期和本月应付。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
@@ -58,6 +60,37 @@ def node_due_reference(due_date: date | None, anchor_date: date | None) -> date
|
|||||||
return due_date or anchor_date
|
return due_date or anchor_date
|
||||||
|
|
||||||
|
|
||||||
|
def stage_has_nothing_to_pay(*, status: str | None, percentage: object, amount: object) -> bool:
|
||||||
|
"""
|
||||||
|
判断付款阶段是否没有应付金额。
|
||||||
|
|
||||||
|
核心逻辑:无此阶段,或比例与金额都是 0(空值按 0)。已付阶段不按 0 处理。
|
||||||
|
与前台 isNothingToPay 一致,避免 0 元验收款、质保款把合同标成已逾期。
|
||||||
|
Args:
|
||||||
|
status: 节点状态。
|
||||||
|
percentage: 付款比例,可为 Decimal、数字或字符串。
|
||||||
|
amount: 应付金额,空值视为 0。
|
||||||
|
Returns:
|
||||||
|
无需付款时为 True。
|
||||||
|
"""
|
||||||
|
normalized = str(status or "").strip().lower()
|
||||||
|
if normalized == "not_applicable":
|
||||||
|
return True
|
||||||
|
if normalized == "paid":
|
||||||
|
return False
|
||||||
|
return _is_zero(percentage) and _is_zero(amount)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_zero(value: object) -> bool:
|
||||||
|
"""空值和 0 都视为没有金额或比例;无法解析的值不当成 0。"""
|
||||||
|
if value is None or value == "":
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
return Decimal(str(value)) == 0
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def classify_ledger_status(
|
def classify_ledger_status(
|
||||||
*,
|
*,
|
||||||
contract_status: str | None,
|
contract_status: str | None,
|
||||||
@@ -69,11 +102,11 @@ def classify_ledger_status(
|
|||||||
按合同聚合出台账状态,与列表「状态」列一致。
|
按合同聚合出台账状态,与列表「状态」列一致。
|
||||||
|
|
||||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
金额和比例都为 0 的阶段不参与判断。其余进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||||
Args:
|
Args:
|
||||||
contract_status: 合同主状态。
|
contract_status: 合同主状态。
|
||||||
parse_status: 解析状态。
|
parse_status: 解析状态。
|
||||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at / percentage / amount。
|
||||||
today: 业务日。
|
today: 业务日。
|
||||||
Returns:
|
Returns:
|
||||||
overdue / due / active / completed / needs_completion。
|
overdue / due / active / completed / needs_completion。
|
||||||
@@ -83,7 +116,14 @@ def classify_ledger_status(
|
|||||||
return "needs_completion"
|
return "needs_completion"
|
||||||
if not node_list:
|
if not node_list:
|
||||||
return "needs_completion"
|
return "needs_completion"
|
||||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
active = [
|
||||||
|
node for node in node_list
|
||||||
|
if str(node.get("status") or "").strip().lower() == "active" and not stage_has_nothing_to_pay(
|
||||||
|
status=node.get("status"),
|
||||||
|
percentage=node.get("percentage"),
|
||||||
|
amount=node.get("amount"),
|
||||||
|
)
|
||||||
|
]
|
||||||
if not active:
|
if not active:
|
||||||
has_paid = any(
|
has_paid = any(
|
||||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||||
@@ -106,7 +146,7 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
|||||||
"""
|
"""
|
||||||
合同是否有未付节点的到期日落在本自然月。
|
合同是否有未付节点的到期日落在本自然月。
|
||||||
|
|
||||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
核心逻辑:只看 status=active 且仍有应付金额的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||||
Args:
|
Args:
|
||||||
nodes: 轻量节点 dict。
|
nodes: 轻量节点 dict。
|
||||||
today: 业务日,用于确定自然月。
|
today: 业务日,用于确定自然月。
|
||||||
@@ -118,6 +158,8 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
|||||||
for node in nodes:
|
for node in nodes:
|
||||||
if str(node.get("status") or "").strip().lower() != "active":
|
if str(node.get("status") or "").strip().lower() != "active":
|
||||||
continue
|
continue
|
||||||
|
if stage_has_nothing_to_pay(status=node.get("status"), percentage=node.get("percentage"), amount=node.get("amount")):
|
||||||
|
continue
|
||||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||||
if ref and month_start <= ref < month_end:
|
if ref and month_start <= ref < month_end:
|
||||||
return True
|
return True
|
||||||
@@ -131,6 +173,8 @@ def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
|||||||
"due_date": node.due_date,
|
"due_date": node.due_date,
|
||||||
"anchor_date": node.anchor_date,
|
"anchor_date": node.anchor_date,
|
||||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||||
|
"percentage": node.percentage,
|
||||||
|
"amount": node.amount,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -136,6 +136,47 @@ def resolve_account(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_direct_wecom(
|
||||||
|
*,
|
||||||
|
slot: str,
|
||||||
|
label: str,
|
||||||
|
name: str | None,
|
||||||
|
wecom_userid: str | None,
|
||||||
|
user: Any = None,
|
||||||
|
oa_employee_id: int | None = None,
|
||||||
|
missing_error: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把已经是企业微信 userid 的人员收成收件人。
|
||||||
|
|
||||||
|
核心逻辑:E8 矩阵的 zz、jfl 本身就是企微 userid,不再用工号对用户。
|
||||||
|
系统里能对上这个 userid 时带上用户主键。对不上仍按该 userid 发送。
|
||||||
|
Args:
|
||||||
|
slot: to 或 cc。
|
||||||
|
label: 直接主管或经副理。
|
||||||
|
name: 展示姓名。
|
||||||
|
wecom_userid: 企业微信 userid。
|
||||||
|
user: 已按 wecom_userid 找到的系统用户。可空。
|
||||||
|
oa_employee_id: HrmResource.id。
|
||||||
|
missing_error: 没有 userid 时的失败原因。
|
||||||
|
Returns:
|
||||||
|
一名收件人。
|
||||||
|
"""
|
||||||
|
wecom = str(wecom_userid or "").strip()
|
||||||
|
if not wecom:
|
||||||
|
return make_person(slot=slot, label=label, name=name, oa_employee_id=oa_employee_id, error=missing_error)
|
||||||
|
display = _user_name(user) or name
|
||||||
|
bound = str(getattr(user, "wecom_userid", None) or "").strip() if user is not None else ""
|
||||||
|
return make_person(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=display,
|
||||||
|
user_id=getattr(user, "id", None) if user is not None else None,
|
||||||
|
wecom_userid=bound or wecom,
|
||||||
|
oa_employee_id=oa_employee_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
把预警配置里的固定岗位收成收件人。
|
把预警配置里的固定岗位收成收件人。
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
backend/app/services/equipment_acceptance/alert_service.py
|
backend/app/services/equipment_acceptance/alert_service.py
|
||||||
|
|
||||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||||
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
依赖:同步服务、E10 人员目录、E8 人员矩阵、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||||
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
逻辑:扫描先同步 E10 和 E8,再按停留天数跨档。第 1 档主送使用部门担当,不按当前未办人。
|
||||||
|
第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -35,6 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
|
|||||||
make_person,
|
make_person,
|
||||||
resolve_account,
|
resolve_account,
|
||||||
resolve_configured_user,
|
resolve_configured_user,
|
||||||
|
resolve_direct_wecom,
|
||||||
)
|
)
|
||||||
from app.services.equipment_acceptance.config_service import is_round_4_enabled, 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
|
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||||
@@ -47,9 +49,9 @@ _UNSENT = ("pending", "failed")
|
|||||||
|
|
||||||
def generate_alerts() -> dict[str, Any]:
|
def generate_alerts() -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
同步 E10 后生成或更新待发送记录。
|
同步两个来源后生成或更新待发送记录。
|
||||||
|
|
||||||
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
|
核心逻辑:先拉最新快照,再按使用部门担当解析收件人。本函数不发企业微信。
|
||||||
Returns:
|
Returns:
|
||||||
sync 摘要,以及 created、updated、cancelled 条数。
|
sync 摘要,以及 created、updated、cancelled 条数。
|
||||||
"""
|
"""
|
||||||
@@ -78,9 +80,9 @@ def refresh_pending_alerts(
|
|||||||
created、updated、cancelled。
|
created、updated、cancelled。
|
||||||
"""
|
"""
|
||||||
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||||
operators = _operators_by_order([order.id for order in orders])
|
e10_people, e10_deputies, e8_people, e8_matrix, e8_ok = _directories(orders, directory)
|
||||||
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
users_by_job = _users_by_job(_job_numbers(orders, e10_people, e10_deputies, e8_people))
|
||||||
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
users_by_wecom = _users_by_wecom(_wecom_ids(e8_matrix))
|
||||||
roles = _configured_users()
|
roles = _configured_users()
|
||||||
thresholds = reminder_days()
|
thresholds = reminder_days()
|
||||||
max_tier = 4 if is_round_4_enabled() else 3
|
max_tier = 4 if is_round_4_enabled() else 3
|
||||||
@@ -96,12 +98,16 @@ def refresh_pending_alerts(
|
|||||||
if order.monitor_status != WATCHING:
|
if order.monitor_status != WATCHING:
|
||||||
cancelled += cancel_unsent(order.id)
|
cancelled += cancel_unsent(order.id)
|
||||||
continue
|
continue
|
||||||
|
if (order.oa_system or "e10") == "e8" and not e8_ok:
|
||||||
|
continue
|
||||||
for draft in _drafts(
|
for draft in _drafts(
|
||||||
order,
|
order,
|
||||||
operators.get(order.id, []),
|
e10_people,
|
||||||
people,
|
e10_deputies,
|
||||||
deputies,
|
e8_people,
|
||||||
|
e8_matrix,
|
||||||
users_by_job,
|
users_by_job,
|
||||||
|
users_by_wecom,
|
||||||
roles,
|
roles,
|
||||||
thresholds,
|
thresholds,
|
||||||
max_tier=max_tier,
|
max_tier=max_tier,
|
||||||
@@ -282,82 +288,31 @@ def send_pending_alerts() -> dict[str, Any]:
|
|||||||
|
|
||||||
def _drafts(
|
def _drafts(
|
||||||
order: EquipmentAcceptanceOrder,
|
order: EquipmentAcceptanceOrder,
|
||||||
operators: list[EquipmentAcceptanceOperator],
|
e10_people: dict[int, dict[str, Any]],
|
||||||
people: dict[int, dict[str, Any]],
|
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||||
deputies: dict[str, list[dict[str, Any]]],
|
e8_people: dict[int, dict[str, Any]],
|
||||||
|
e8_matrix: dict[str, dict[str, Any]],
|
||||||
users_by_job: dict[str, User],
|
users_by_job: dict[str, User],
|
||||||
|
users_by_wecom: dict[str, User],
|
||||||
roles: dict[str, User | None],
|
roles: dict[str, User | None],
|
||||||
thresholds: tuple[int, int, int, int],
|
thresholds: tuple[int, int, int, int],
|
||||||
*,
|
*,
|
||||||
max_tier: int = 4,
|
max_tier: int = 4,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
"""按使用部门担当展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||||
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
||||||
if not due:
|
if not due:
|
||||||
return []
|
return []
|
||||||
handlers: list[dict[str, Any]] = []
|
owner, supervisors, deputy_people = _owner_seats(
|
||||||
supervisors: list[dict[str, Any]] = []
|
order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom
|
||||||
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,
|
|
||||||
)
|
)
|
||||||
|
applicant = _applicant(order, e10_people if (order.oa_system or "e10") != "e8" else e8_people, users_by_job)
|
||||||
drafts: list[dict[str, Any]] = []
|
drafts: list[dict[str, Any]] = []
|
||||||
if 1 in due:
|
if 1 in due:
|
||||||
drafts.append(assemble_tier(
|
drafts.append(assemble_tier(
|
||||||
tier=1,
|
tier=1,
|
||||||
threshold_days=thresholds[0],
|
threshold_days=thresholds[0],
|
||||||
to_people=handlers,
|
to_people=[owner],
|
||||||
cc_people=[*supervisors, applicant],
|
cc_people=[*supervisors, applicant],
|
||||||
))
|
))
|
||||||
if 2 in due:
|
if 2 in due:
|
||||||
@@ -390,6 +345,159 @@ def _drafts(
|
|||||||
return drafts
|
return drafts
|
||||||
|
|
||||||
|
|
||||||
|
def _owner_seats(
|
||||||
|
order: EquipmentAcceptanceOrder,
|
||||||
|
e10_people: dict[int, dict[str, Any]],
|
||||||
|
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||||
|
e8_people: dict[int, dict[str, Any]],
|
||||||
|
e8_matrix: dict[str, dict[str, Any]],
|
||||||
|
users_by_job: dict[str, User],
|
||||||
|
users_by_wecom: dict[str, User],
|
||||||
|
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||||
|
"""第 1 档主送和其上级。E8 的上级来自部门矩阵,E10 来自 employee 和审批矩阵。"""
|
||||||
|
if (order.oa_system or "e10") == "e8":
|
||||||
|
return _e8_owner_seats(order, e8_people, e8_matrix, users_by_job, users_by_wecom)
|
||||||
|
return _e10_owner_seats(order, e10_people, e10_deputies, users_by_job)
|
||||||
|
|
||||||
|
|
||||||
|
def _e10_owner_seats(
|
||||||
|
order: EquipmentAcceptanceOrder,
|
||||||
|
people: dict[int, dict[str, Any]],
|
||||||
|
deputies: dict[str, list[dict[str, Any]]],
|
||||||
|
users_by_job: dict[str, User],
|
||||||
|
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||||
|
"""E10 只取 sybmdd 这一名使用部门担当,不展开当前节点上的其他人。"""
|
||||||
|
if not order.owner_oa_id:
|
||||||
|
return (
|
||||||
|
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||||
|
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||||
|
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||||
|
)
|
||||||
|
fact = people.get(order.owner_oa_id) or {}
|
||||||
|
name = fact.get("name") or order.owner_name
|
||||||
|
job_num = fact.get("job_num") or order.owner_job_num
|
||||||
|
shown = name or "使用部门担当"
|
||||||
|
owner = 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=order.owner_oa_id,
|
||||||
|
)
|
||||||
|
superior_id = fact.get("superior_id")
|
||||||
|
if superior_id is None:
|
||||||
|
supervisors = [make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管")]
|
||||||
|
else:
|
||||||
|
supervisors = [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 = [make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理")]
|
||||||
|
else:
|
||||||
|
deputy_people = [
|
||||||
|
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"),
|
||||||
|
)
|
||||||
|
for item in found
|
||||||
|
]
|
||||||
|
return owner, supervisors, deputy_people
|
||||||
|
|
||||||
|
|
||||||
|
def _e8_owner_seats(
|
||||||
|
order: EquipmentAcceptanceOrder,
|
||||||
|
people: dict[int, dict[str, Any]],
|
||||||
|
matrix: dict[str, dict[str, Any]],
|
||||||
|
users_by_job: dict[str, User],
|
||||||
|
users_by_wecom: dict[str, User],
|
||||||
|
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||||
|
"""E8 的直接主管是矩阵 zz,经副理是 jfl。不是一行就不发这两个席位。"""
|
||||||
|
if not order.owner_oa_id:
|
||||||
|
return (
|
||||||
|
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||||
|
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||||
|
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||||
|
)
|
||||||
|
fact = people.get(order.owner_oa_id) or {}
|
||||||
|
name = fact.get("name") or order.owner_name
|
||||||
|
job_num = fact.get("job_num") or order.owner_job_num
|
||||||
|
shown = name or "使用部门担当"
|
||||||
|
owner = 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=order.owner_oa_id,
|
||||||
|
)
|
||||||
|
seat = matrix.get(str(fact.get("department_id") or ""))
|
||||||
|
if not seat or not seat.get("ok"):
|
||||||
|
return (
|
||||||
|
owner,
|
||||||
|
[make_person(slot="cc", label="直接主管", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||||
|
[make_person(slot="to", label="经副理", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||||
|
)
|
||||||
|
return owner, [_matrix_seat(seat.get("zz"), "cc", "直接主管", shown, users_by_wecom)], [
|
||||||
|
_matrix_seat(seat.get("jfl"), "to", "经副理", shown, users_by_wecom)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _matrix_seat(
|
||||||
|
seat: dict[str, Any] | None,
|
||||||
|
slot: str,
|
||||||
|
label: str,
|
||||||
|
owner_name: str,
|
||||||
|
users_by_wecom: dict[str, User],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""矩阵人员按企微 userid 发送。空席位记失败。"""
|
||||||
|
if not seat:
|
||||||
|
return make_person(slot=slot, label=label, name=owner_name, error=f"{owner_name}没有{label}")
|
||||||
|
wecom = str(seat.get("wecom_userid") or "")
|
||||||
|
return resolve_direct_wecom(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=seat.get("name"),
|
||||||
|
wecom_userid=wecom,
|
||||||
|
user=users_by_wecom.get(wecom),
|
||||||
|
oa_employee_id=seat.get("oa_id"),
|
||||||
|
missing_error=f"{owner_name}没有{label}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _applicant(
|
||||||
|
order: EquipmentAcceptanceOrder,
|
||||||
|
people: dict[int, dict[str, Any]],
|
||||||
|
users_by_job: dict[str, User],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""采购担当是申请人。E8 用工号 workcode,E10 用工号 JOB_NUM,都对系统用户。"""
|
||||||
|
fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||||
|
job_num = (fact or {}).get("job_num") or order.applicant_job_num
|
||||||
|
return resolve_account(
|
||||||
|
slot="cc",
|
||||||
|
label="采购担当",
|
||||||
|
name=(fact or {}).get("name") or order.applicant_name,
|
||||||
|
job_num=job_num,
|
||||||
|
user=users_by_job.get(str(job_num or "")),
|
||||||
|
missing_job_error="没有申请人工号",
|
||||||
|
oa_employee_id=order.applicant_oa_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
||||||
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
||||||
row.acceptance_no = order.acceptance_no
|
row.acceptance_no = order.acceptance_no
|
||||||
@@ -402,51 +510,103 @@ def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceO
|
|||||||
row.error_message = draft["error_message"]
|
row.error_message = draft["error_message"]
|
||||||
|
|
||||||
|
|
||||||
def _load_directory(
|
def _directories(
|
||||||
|
orders: list[EquipmentAcceptanceOrder],
|
||||||
|
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None,
|
||||||
|
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]], dict[int, dict[str, Any]], dict[str, dict[str, Any]], bool]:
|
||||||
|
"""分开取 E10 和 E8 的人员。E8 查询失败时本轮不改写 E8 待发送。"""
|
||||||
|
if directory is not None:
|
||||||
|
return directory[0], directory[1], {}, {}, True
|
||||||
|
e10_people, e10_deputies = _load_e10_directory(orders)
|
||||||
|
try:
|
||||||
|
e8_people, e8_matrix = _load_e8_directory(orders)
|
||||||
|
return e10_people, e10_deputies, e8_people, e8_matrix, True
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance e8 directory skipped error=%s", type(exc).__name__)
|
||||||
|
return e10_people, e10_deputies, {}, {}, False
|
||||||
|
|
||||||
|
|
||||||
|
def _load_e10_directory(
|
||||||
orders: list[EquipmentAcceptanceOrder],
|
orders: list[EquipmentAcceptanceOrder],
|
||||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
|
||||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||||
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
"""向 E10 要使用部门担当和申请人的主管、部门、经副理。不传入 E8 人员 ID。"""
|
||||||
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
||||||
|
|
||||||
ids: set[int] = set()
|
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:
|
for order in orders:
|
||||||
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
if (order.oa_system or "e10") == "e8" or order.monitor_status != WATCHING:
|
||||||
|
continue
|
||||||
|
if order.owner_oa_id:
|
||||||
|
ids.add(order.owner_oa_id)
|
||||||
|
if order.applicant_oa_id:
|
||||||
ids.add(order.applicant_oa_id)
|
ids.add(order.applicant_oa_id)
|
||||||
return fetch_alert_directory(sorted(ids))
|
return fetch_alert_directory(sorted(ids))
|
||||||
|
|
||||||
|
|
||||||
|
def _load_e8_directory(
|
||||||
|
orders: list[EquipmentAcceptanceOrder],
|
||||||
|
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||||
|
"""向 E8 要使用部门担当和申请人。人员 ID 只进 HrmResource。"""
|
||||||
|
from app.services.equipment_acceptance.e8_repository import fetch_e8_alert_directory
|
||||||
|
|
||||||
|
ids: set[int] = set()
|
||||||
|
for order in orders:
|
||||||
|
if (order.oa_system or "e10") != "e8" or order.monitor_status != WATCHING:
|
||||||
|
continue
|
||||||
|
if order.owner_oa_id:
|
||||||
|
ids.add(order.owner_oa_id)
|
||||||
|
if order.applicant_oa_id:
|
||||||
|
ids.add(order.applicant_oa_id)
|
||||||
|
return fetch_e8_alert_directory(sorted(ids))
|
||||||
|
|
||||||
|
|
||||||
def _job_numbers(
|
def _job_numbers(
|
||||||
orders: list[EquipmentAcceptanceOrder],
|
orders: list[EquipmentAcceptanceOrder],
|
||||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
e10_people: dict[int, dict[str, Any]],
|
||||||
people: dict[int, dict[str, Any]],
|
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||||
deputies: dict[str, list[dict[str, Any]]],
|
e8_people: dict[int, dict[str, Any]],
|
||||||
) -> set[str]:
|
) -> set[str]:
|
||||||
"""收集要对系统用户的工号。"""
|
"""收集要对系统用户的工号。E8 矩阵人员不走工号。"""
|
||||||
found: set[str] = set()
|
found: set[str] = set()
|
||||||
for order in orders:
|
for order in orders:
|
||||||
|
if order.owner_job_num:
|
||||||
|
found.add(order.owner_job_num)
|
||||||
if order.applicant_job_num:
|
if order.applicant_job_num:
|
||||||
found.add(order.applicant_job_num)
|
found.add(order.applicant_job_num)
|
||||||
for group in operators.values():
|
for fact in (*e10_people.values(), *e8_people.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"):
|
if fact.get("job_num"):
|
||||||
found.add(str(fact["job_num"]))
|
found.add(str(fact["job_num"]))
|
||||||
if fact.get("superior_job_num"):
|
if fact.get("superior_job_num"):
|
||||||
found.add(str(fact["superior_job_num"]))
|
found.add(str(fact["superior_job_num"]))
|
||||||
for group in deputies.values():
|
for group in e10_deputies.values():
|
||||||
for item in group:
|
for item in group:
|
||||||
if item.get("job_num"):
|
if item.get("job_num"):
|
||||||
found.add(str(item["job_num"]))
|
found.add(str(item["job_num"]))
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _wecom_ids(matrix: dict[str, dict[str, Any]]) -> set[str]:
|
||||||
|
"""收集 E8 矩阵上的企业微信 userid,用来补系统用户主键。"""
|
||||||
|
found: set[str] = set()
|
||||||
|
for item in matrix.values():
|
||||||
|
if not item.get("ok"):
|
||||||
|
continue
|
||||||
|
for key in ("zz", "jfl"):
|
||||||
|
seat = item.get(key) or {}
|
||||||
|
wecom = str(seat.get("wecom_userid") or "").strip()
|
||||||
|
if wecom:
|
||||||
|
found.add(wecom)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _users_by_wecom(wecom_ids: set[str]) -> dict[str, User]:
|
||||||
|
"""按企业微信 userid 索引系统用户。"""
|
||||||
|
if not wecom_ids:
|
||||||
|
return {}
|
||||||
|
rows = db.session.query(User).filter(User.wecom_userid.in_(wecom_ids)).all()
|
||||||
|
return {str(row.wecom_userid): row for row in rows if row.wecom_userid}
|
||||||
|
|
||||||
|
|
||||||
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
||||||
"""用工号索引系统用户。"""
|
"""用工号索引系统用户。"""
|
||||||
if not job_nums:
|
if not job_nums:
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/e8_group.py
|
||||||
|
|
||||||
|
用途:把 E8 验收单联表行收成与 E10 相同的快照草稿。
|
||||||
|
依赖:e8_status、snapshot_rules、source_group。
|
||||||
|
逻辑:同步服务在写库前调用。流程状态先翻译。人员 ID 仍是 E8 的 HrmResource.id。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import (
|
||||||
|
as_datetime,
|
||||||
|
as_int,
|
||||||
|
can_accept_from_oa,
|
||||||
|
is_returned_from_oa,
|
||||||
|
)
|
||||||
|
from app.services.equipment_acceptance.source_group import (
|
||||||
|
AcceptanceDraft,
|
||||||
|
NodeDraft,
|
||||||
|
OperatorDraft,
|
||||||
|
)
|
||||||
|
|
||||||
|
_TERMINAL_FLOW = {3, 7}
|
||||||
|
|
||||||
|
|
||||||
|
def group_e8_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
|
||||||
|
"""
|
||||||
|
按 requestid 合并 E8 联表行。
|
||||||
|
|
||||||
|
核心逻辑:没有 requestid 的行跳过。同一请求的未办人收成一张单。
|
||||||
|
计时起点读 syddjssj。可以验收读 sfkys。来源标记为 e8。
|
||||||
|
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:
|
||||||
|
"""同一流程的多行收成一条 E8 草稿。"""
|
||||||
|
header = items[0]
|
||||||
|
flow_status = e8_flow_status(header.get("currentnodetype"), header.get("currentstatus"))
|
||||||
|
return AcceptanceDraft(
|
||||||
|
oa_system="e8",
|
||||||
|
request_id=request_id,
|
||||||
|
acceptance_no=_text(header.get("ysddh")),
|
||||||
|
purchase_order_no=_text(header.get("cgdh")),
|
||||||
|
contract_no=_text(header.get("htbh")),
|
||||||
|
flow_no=_text(header.get("flow_no")),
|
||||||
|
request_title=_text(header.get("request_title")),
|
||||||
|
request_created_at=_e8_created_at(header),
|
||||||
|
timer_started_at=as_datetime(header.get("syddjssj")),
|
||||||
|
can_accept=can_accept_from_oa(as_int(header.get("sfkys"))),
|
||||||
|
cannot_accept_note=_text(header.get("ycsm")),
|
||||||
|
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
|
||||||
|
flow_status_raw=flow_status,
|
||||||
|
finished_at=_finished_at(header, flow_status),
|
||||||
|
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=None,
|
||||||
|
equip_name=None,
|
||||||
|
equip_job_num=None,
|
||||||
|
applicant_oa_id=as_int(header.get("creater")),
|
||||||
|
applicant_name=_text(header.get("applicant_name")),
|
||||||
|
applicant_job_num=_text(header.get("applicant_job_num")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _e8_created_at(header: dict[str, Any]) -> datetime | None:
|
||||||
|
"""
|
||||||
|
拼出 E8 流程创建时间。
|
||||||
|
|
||||||
|
核心逻辑:createdate 是日期,createtime 是时分秒,两边分开存。
|
||||||
|
只有日期时按当天 0 点。都空则没有创建时间。
|
||||||
|
"""
|
||||||
|
day = _text(header.get("createdate"))
|
||||||
|
clock = _text(header.get("createtime"))
|
||||||
|
if day is None:
|
||||||
|
return None
|
||||||
|
if clock is None:
|
||||||
|
return as_datetime(day)
|
||||||
|
return as_datetime(f"{day} {clock}")
|
||||||
|
|
||||||
|
|
||||||
|
def _finished_at(header: dict[str, Any], flow_status: int | None) -> datetime | None:
|
||||||
|
"""归档或撤销时,用最后操作时间作为结束时间。进行中不写。"""
|
||||||
|
if flow_status not in _TERMINAL_FLOW:
|
||||||
|
return None
|
||||||
|
parsed = as_datetime(header.get("lastoperatedate"))
|
||||||
|
if parsed is not None:
|
||||||
|
return parsed
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
|
||||||
|
"""当前节点只取 currentnodeid。没有节点 ID 时不造一行。"""
|
||||||
|
found: dict[int, NodeDraft] = {}
|
||||||
|
for row in rows:
|
||||||
|
node_id = as_int(row.get("currentnodeid"))
|
||||||
|
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=None,
|
||||||
|
)
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
|
||||||
|
"""当前未办人。查询已限定 isremark=0,这里只按人和节点去重。"""
|
||||||
|
found: dict[tuple[int, int], OperatorDraft] = {}
|
||||||
|
for row in rows:
|
||||||
|
node_id = as_int(row.get("currentnodeid"))
|
||||||
|
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,71 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/e8_query.py
|
||||||
|
|
||||||
|
用途:组装 E8 验收单只读 SQL。
|
||||||
|
依赖:无。不连接数据库。
|
||||||
|
逻辑:e8_repository 执行本文件的语句。表名固定,不拼接外部字符串。
|
||||||
|
不复用合同付款只取归档日的查询。不取 currentnodetype=3 的归档单,空节点类型仍取。
|
||||||
|
流程编号取 lcbh,标题取 requestname。创建时间取 createdate 加 createtime。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def build_e8_acceptance_sql() -> str:
|
||||||
|
"""
|
||||||
|
组装未归档的 E8 验收单查询。
|
||||||
|
|
||||||
|
核心逻辑:formtable_main_324.requestId 对 workflow_requestbase.requestid。
|
||||||
|
当前节点用 currentnodeid,不用 lastnodeid。当前未办人是 isremark=0。
|
||||||
|
currentnodetype=3 的归档单不取,空值仍取。申请人读 creater,不是 creator。
|
||||||
|
流程编号读 lcbh,标题读 requestname。创建时间由 createdate 与 createtime 拼成。
|
||||||
|
Returns:
|
||||||
|
一条 SELECT。
|
||||||
|
"""
|
||||||
|
return """
|
||||||
|
SELECT
|
||||||
|
f.ysddh AS ysddh,
|
||||||
|
f.cgdh AS cgdh,
|
||||||
|
f.htbh AS htbh,
|
||||||
|
f.lcbh AS flow_no,
|
||||||
|
f.syddjssj AS syddjssj,
|
||||||
|
f.sfzfth AS sfzfth,
|
||||||
|
f.sfkys AS sfkys,
|
||||||
|
f.ycsm AS ycsm,
|
||||||
|
f.sybmdd AS sybmdd,
|
||||||
|
w.requestid AS requestid,
|
||||||
|
w.requestname AS request_title,
|
||||||
|
w.createdate AS createdate,
|
||||||
|
w.createtime AS createtime,
|
||||||
|
LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) AS currentnodetype,
|
||||||
|
w.currentstatus AS currentstatus,
|
||||||
|
w.currentnodeid AS currentnodeid,
|
||||||
|
w.creater AS creater,
|
||||||
|
w.lastoperatedate AS lastoperatedate,
|
||||||
|
w.lastoperatetime AS lastoperatetime,
|
||||||
|
n.nodename AS nodename,
|
||||||
|
op.userid AS userid,
|
||||||
|
owner.lastname AS owner_name,
|
||||||
|
owner.workcode AS owner_job_num,
|
||||||
|
applicant.lastname AS applicant_name,
|
||||||
|
applicant.workcode AS applicant_job_num,
|
||||||
|
handler.lastname AS handler_name,
|
||||||
|
handler.workcode AS handler_job_num
|
||||||
|
FROM formtable_main_324 AS f
|
||||||
|
INNER JOIN workflow_requestbase AS w
|
||||||
|
ON w.requestid = f.requestId
|
||||||
|
LEFT JOIN workflow_nodebase AS n
|
||||||
|
ON n.id = w.currentnodeid
|
||||||
|
LEFT JOIN workflow_currentoperator AS op
|
||||||
|
ON op.requestid = w.requestid
|
||||||
|
AND op.nodeid = w.currentnodeid
|
||||||
|
AND LTRIM(RTRIM(CAST(op.isremark AS nvarchar(10)))) = N'0'
|
||||||
|
LEFT JOIN HrmResource AS owner
|
||||||
|
ON owner.id = f.sybmdd
|
||||||
|
LEFT JOIN HrmResource AS applicant
|
||||||
|
ON applicant.id = w.creater
|
||||||
|
LEFT JOIN HrmResource AS handler
|
||||||
|
ON handler.id = op.userid
|
||||||
|
WHERE w.currentnodetype IS NULL
|
||||||
|
OR LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) <> N'3'
|
||||||
|
""".strip()
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/e8_repository.py
|
||||||
|
|
||||||
|
用途:只读拉取 E8 验收单,以及使用部门担当的直接主管和经副理。
|
||||||
|
依赖:OASQLServerService、e8_query。不连接 E10,不把人员 ID 送进 eteams。
|
||||||
|
逻辑:验收单一次联表。收件人再按 HrmResource.id 查部门和 Matrixtable_3。
|
||||||
|
zz、jfl 就是企业微信 userid。矩阵不是一行时该部门失败。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.errors import ServiceUnavailableError
|
||||||
|
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import as_int
|
||||||
|
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_e8_acceptance_rows() -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
从 E8 拉验收单联表结果。
|
||||||
|
|
||||||
|
核心逻辑:复用 OA_SQLSERVER_* 只读连接。失败不改走 E10。
|
||||||
|
Returns:
|
||||||
|
字段名为小写别名的字典行。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ServiceUnavailableError: 连接或查询失败。
|
||||||
|
"""
|
||||||
|
connection = _open()
|
||||||
|
try:
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute(build_e8_acceptance_sql())
|
||||||
|
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 ServiceUnavailableError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance e8 sql failed error=%s", type(exc).__name__)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"查询 E8 设备验收数据失败",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_e8_alert_directory(
|
||||||
|
person_ids: list[int],
|
||||||
|
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
按使用部门担当和申请人的 HrmResource.id 取工号,并按部门取直接主管、经副理。
|
||||||
|
|
||||||
|
核心逻辑:工号是 workcode。Matrixtable_3.bm 必须只命中一行,zz 是直接主管,jfl 是经副理。
|
||||||
|
这两个 ID 同时是企业微信 userid。没有人员时不连库。
|
||||||
|
Args:
|
||||||
|
person_ids: HrmResource.id。禁止传入 E10 的 employee.ID。
|
||||||
|
Returns:
|
||||||
|
(人员字典, 部门 ID 到矩阵结果)。矩阵结果含 ok、zz、jfl。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ServiceUnavailableError: 连接或查询失败。
|
||||||
|
"""
|
||||||
|
ids = sorted({int(item) for item in person_ids if item is not None})
|
||||||
|
if not ids:
|
||||||
|
return {}, {}
|
||||||
|
connection = _open()
|
||||||
|
try:
|
||||||
|
cursor = connection.cursor()
|
||||||
|
people = _load_people(cursor, ids)
|
||||||
|
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
|
||||||
|
matrix = _load_matrix(cursor, departments)
|
||||||
|
_fill_matrix_names(cursor, matrix)
|
||||||
|
return people, matrix
|
||||||
|
except ServiceUnavailableError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance e8 directory failed error=%s", type(exc).__name__)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"查询 E8 直接主管和经副理失败",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _open():
|
||||||
|
"""打开 E8 ecology 连接。异常收成业务错误,不把连接串写进日志。"""
|
||||||
|
try:
|
||||||
|
return OASQLServerService._connect()
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance e8 connect failed error=%s", type(exc).__name__)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"连接 E8 SQL Server 失败",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _load_people(cursor: Any, person_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||||
|
"""取出姓名、工号和部门。"""
|
||||||
|
found: dict[int, dict[str, Any]] = {}
|
||||||
|
for chunk in _chunks(person_ids):
|
||||||
|
marks = ",".join("?" for _ in chunk)
|
||||||
|
cursor.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, lastname, workcode, departmentid
|
||||||
|
FROM HrmResource
|
||||||
|
WHERE id IN ({marks})
|
||||||
|
""",
|
||||||
|
chunk,
|
||||||
|
)
|
||||||
|
for raw in cursor.fetchall():
|
||||||
|
person_id = as_int(raw[0])
|
||||||
|
if person_id is None:
|
||||||
|
continue
|
||||||
|
found[person_id] = {
|
||||||
|
"oa_id": person_id,
|
||||||
|
"name": _clean(raw[1]),
|
||||||
|
"job_num": _clean(raw[2]),
|
||||||
|
"department_id": _clean(raw[3]),
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _load_matrix(cursor: Any, department_ids: list[str]) -> dict[str, dict[str, Any]]:
|
||||||
|
"""按部门取矩阵。不是正好一行就记失败,不挑其中一行。"""
|
||||||
|
grouped: dict[str, list[tuple[Any, Any]]] = {}
|
||||||
|
if not department_ids:
|
||||||
|
return {}
|
||||||
|
for chunk in _chunks(department_ids):
|
||||||
|
marks = ",".join("?" for _ in chunk)
|
||||||
|
params = [int(item) if str(item).isdigit() else item for item in chunk]
|
||||||
|
cursor.execute(
|
||||||
|
f"""
|
||||||
|
SELECT bm, zz, jfl
|
||||||
|
FROM Matrixtable_3
|
||||||
|
WHERE bm IN ({marks})
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
for raw in cursor.fetchall():
|
||||||
|
department_id = _clean(raw[0])
|
||||||
|
if not department_id:
|
||||||
|
continue
|
||||||
|
grouped.setdefault(department_id, []).append((raw[1], raw[2]))
|
||||||
|
found: dict[str, dict[str, Any]] = {}
|
||||||
|
for department_id, rows in grouped.items():
|
||||||
|
if len(rows) != 1:
|
||||||
|
found[department_id] = {"ok": False, "zz": None, "jfl": None}
|
||||||
|
continue
|
||||||
|
zz_id = as_int(rows[0][0])
|
||||||
|
jfl_id = as_int(rows[0][1])
|
||||||
|
found[department_id] = {
|
||||||
|
"ok": True,
|
||||||
|
"zz": _seat(zz_id),
|
||||||
|
"jfl": _seat(jfl_id),
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_matrix_names(cursor: Any, matrix: dict[str, dict[str, Any]]) -> None:
|
||||||
|
"""给直接主管和经副理补姓名。查不到姓名仍保留企微 userid。"""
|
||||||
|
ids = sorted({
|
||||||
|
seat["oa_id"]
|
||||||
|
for item in matrix.values()
|
||||||
|
if item.get("ok")
|
||||||
|
for seat in (item.get("zz"), item.get("jfl"))
|
||||||
|
if seat and seat.get("oa_id") is not None
|
||||||
|
})
|
||||||
|
if not ids:
|
||||||
|
return
|
||||||
|
names = _load_people(cursor, ids)
|
||||||
|
for item in matrix.values():
|
||||||
|
if not item.get("ok"):
|
||||||
|
continue
|
||||||
|
for key in ("zz", "jfl"):
|
||||||
|
seat = item.get(key)
|
||||||
|
if not seat:
|
||||||
|
continue
|
||||||
|
fact = names.get(seat["oa_id"]) or {}
|
||||||
|
if fact.get("name"):
|
||||||
|
seat["name"] = fact["name"]
|
||||||
|
|
||||||
|
|
||||||
|
def _seat(person_id: int | None) -> dict[str, Any] | None:
|
||||||
|
"""矩阵里的人员 ID 直接作为企业微信 userid。"""
|
||||||
|
if person_id is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"oa_id": person_id,
|
||||||
|
"name": None,
|
||||||
|
"wecom_userid": str(person_id),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
|
||||||
|
"""把 IN 列表拆开。"""
|
||||||
|
return [values[index:index + size] for index in range(0, len(values), size)]
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(value: Any) -> str | None:
|
||||||
|
"""去掉空白。"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = str(value).strip()
|
||||||
|
return text or None
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/e8_status.py
|
||||||
|
|
||||||
|
用途:把 E8 流程状态收成与 E10 相同的 flow_status_raw。
|
||||||
|
依赖:无。不读数据库。
|
||||||
|
逻辑:同步分组在落库前调用。currentstatus 优先于 currentnodetype。
|
||||||
|
E8 没有作废和强制结束,不写成 5 或 4。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
# 与 E10 的审批中、归档、撤销对齐。暂停按 E10 的 flowstatus=7,同样停表。
|
||||||
|
_APPROVING = 1
|
||||||
|
_ARCHIVED = 3
|
||||||
|
_REVOKED = 7
|
||||||
|
_APPROVING_NODE_TYPES = {"0", "1", "2"}
|
||||||
|
_PAUSE_OR_REVOKE = {0, 1}
|
||||||
|
|
||||||
|
|
||||||
|
def e8_flow_status(currentnodetype: Any, currentstatus: Any) -> int | None:
|
||||||
|
"""
|
||||||
|
把 E8 的节点类型和暂停/撤销收成本地流程状态。
|
||||||
|
|
||||||
|
核心逻辑:currentstatus 为空才看 currentnodetype。0 暂停、1 撤销都写成 7。
|
||||||
|
空、0、1 以外不写成审批中,返回空,调用方不把这张单放进进行中。
|
||||||
|
Args:
|
||||||
|
currentnodetype: workflow_requestbase.currentnodetype。0/1/2 审批中,3 归档。
|
||||||
|
currentstatus: workflow_requestbase.currentstatus。空是正常,0 暂停,1 撤销。
|
||||||
|
Returns:
|
||||||
|
1、3 或 7。无法识别时为 None。
|
||||||
|
"""
|
||||||
|
status = _blank_to_none(currentstatus)
|
||||||
|
if status is not None:
|
||||||
|
code = _as_int(status)
|
||||||
|
if code in _PAUSE_OR_REVOKE:
|
||||||
|
return _REVOKED
|
||||||
|
return None
|
||||||
|
node_type = _blank_to_none(currentnodetype)
|
||||||
|
if node_type in _APPROVING_NODE_TYPES:
|
||||||
|
return _APPROVING
|
||||||
|
if node_type == "3":
|
||||||
|
return _ARCHIVED
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _blank_to_none(value: Any) -> str | None:
|
||||||
|
"""空白当成没有值。数字也收成去掉空白的文本。"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = str(value).strip()
|
||||||
|
return text or None
|
||||||
|
|
||||||
|
|
||||||
|
def _as_int(value: str) -> int | None:
|
||||||
|
"""整数字符串收成 int。带小数或字母的不猜。"""
|
||||||
|
try:
|
||||||
|
if "." in value:
|
||||||
|
return None
|
||||||
|
return int(value)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
@@ -126,12 +126,12 @@ def _open_connection(settings: EquipmentAcceptanceSqlSettings):
|
|||||||
|
|
||||||
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||||
"""
|
"""
|
||||||
读取处理人的直接主管,并按部门查出经副理。
|
读取使用部门担当的直接主管,并按部门查出经副理。
|
||||||
|
|
||||||
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
||||||
人员 ID 必须是整数。没有人员时不连库。
|
人员 ID 必须是 E10 的 employee.ID。没有人员时不连库。
|
||||||
Args:
|
Args:
|
||||||
employee_ids: 当前处理人和申请人的 employee.ID。
|
employee_ids: 使用部门担当和申请人的 employee.ID。禁止传入 E8 的 HrmResource.id。
|
||||||
Returns:
|
Returns:
|
||||||
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ backend/app/services/equipment_acceptance/query_sql.py
|
|||||||
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
||||||
依赖:无 Flask。库名只允许字母、数字和下划线。
|
依赖:无 Flask。库名只允许字母、数字和下划线。
|
||||||
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
||||||
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
不取 flowstatus=3 的归档单。flowstatus 为空仍取。
|
||||||
|
流程编号读 requestmark,标题读 requestname,创建时间读 createdatetime。不读第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -68,8 +69,8 @@ def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
|
|||||||
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
||||||
|
|
||||||
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
||||||
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
流程编号取 requestmark,标题取 requestname,创建时间取 createdatetime。不查询第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||||
delete_type 只取 0。当前处理人就是这些 userid。
|
delete_type 只取 0。当前处理人就是这些 userid。归档(flowstatus=3)不取,空状态仍取。
|
||||||
Args:
|
Args:
|
||||||
catalogs: 已解析的库名。
|
catalogs: 已解析的库名。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -104,6 +105,9 @@ SELECT
|
|||||||
applicant.USERNAME AS applicant_name,
|
applicant.USERNAME AS applicant_name,
|
||||||
applicant.JOB_NUM AS applicant_job_num,
|
applicant.JOB_NUM AS applicant_job_num,
|
||||||
r.requestid,
|
r.requestid,
|
||||||
|
r.requestmark AS flow_no,
|
||||||
|
r.requestname AS request_title,
|
||||||
|
r.createdatetime,
|
||||||
r.flowstatus,
|
r.flowstatus,
|
||||||
r.finishdatetime,
|
r.finishdatetime,
|
||||||
c.nodeid,
|
c.nodeid,
|
||||||
@@ -135,6 +139,7 @@ LEFT JOIN {operate} AS op
|
|||||||
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
||||||
WHERE ISNULL(f.delete_type, 0) = 0
|
WHERE ISNULL(f.delete_type, 0) = 0
|
||||||
AND r.requestid IS NOT NULL
|
AND r.requestid IS NOT NULL
|
||||||
|
AND (r.flowstatus IS NULL OR r.flowstatus <> 3)
|
||||||
""".strip()
|
""".strip()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/equipment_acceptance/schedule_seed.py
|
backend/app/services/equipment_acceptance/schedule_seed.py
|
||||||
|
|
||||||
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
|
用途:设备验收预警的默认排程:每日 06:30 扫描和周五 18:30 发送。
|
||||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||||
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
||||||
"""
|
"""
|
||||||
@@ -17,8 +17,10 @@ from app.services.schedule.timezone_util import compute_next_run_at
|
|||||||
|
|
||||||
|
|
||||||
_DEFAULTS = (
|
_DEFAULTS = (
|
||||||
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
|
# 每天 06:30,错开合同付款预警扫描的 06:00
|
||||||
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
|
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批 06:30)", "30 6 * * *"),
|
||||||
|
# 周五 18:30,错开合同付款预警的周五 18:00
|
||||||
|
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:30)", "30 18 * * 5"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -26,7 +28,7 @@ def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
|
|||||||
"""
|
"""
|
||||||
幂等创建设备验收每日扫描和周五发送两个排程。
|
幂等创建设备验收每日扫描和周五发送两个排程。
|
||||||
|
|
||||||
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
|
核心逻辑:发送时刻不在预警配置表。默认每天 06:30、周五 18:30(错开合同付款 06:00 / 18:00),时区 Asia/Shanghai。
|
||||||
Args:
|
Args:
|
||||||
commit: 为 False 时只 flush,交给外层事务提交。
|
commit: 为 False 时只 flush,交给外层事务提交。
|
||||||
Returns:
|
Returns:
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ def classify_monitor_status(
|
|||||||
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
||||||
|
|
||||||
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
||||||
审批中、可以验收、未退回、已有计时起点才是计时中。
|
审批中、未退回、已有计时起点,且可以验收不是明确为否时计时。空和是都监控。
|
||||||
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
||||||
Args:
|
Args:
|
||||||
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
||||||
@@ -204,8 +204,8 @@ def classify_monitor_status(
|
|||||||
return STOPPED_REVOKED
|
return STOPPED_REVOKED
|
||||||
if not timer_started:
|
if not timer_started:
|
||||||
return NOT_STARTED
|
return NOT_STARTED
|
||||||
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
# [STEP 2] 可以验收只有明确为否才停表,空和是都继续计时。0、1、空以外不猜。
|
||||||
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
if can_accept in (1, None) and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||||
return WATCHING
|
return WATCHING
|
||||||
return EXCLUDED
|
return EXCLUDED
|
||||||
|
|
||||||
|
|||||||
@@ -42,12 +42,16 @@ class NodeDraft:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class AcceptanceDraft:
|
class AcceptanceDraft:
|
||||||
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
|
"""一张验收单在一次同步中的快照草稿。含流程编号、标题和创建时间。不含第二合同编号和验收日期。"""
|
||||||
|
|
||||||
|
oa_system: str
|
||||||
request_id: int
|
request_id: int
|
||||||
acceptance_no: str | None
|
acceptance_no: str | None
|
||||||
purchase_order_no: str | None
|
purchase_order_no: str | None
|
||||||
contract_no: str | None
|
contract_no: str | None
|
||||||
|
flow_no: str | None
|
||||||
|
request_title: str | None
|
||||||
|
request_created_at: datetime | None
|
||||||
timer_started_at: datetime | None
|
timer_started_at: datetime | None
|
||||||
can_accept: int | None
|
can_accept: int | None
|
||||||
cannot_accept_note: str | None
|
cannot_accept_note: str | None
|
||||||
@@ -73,7 +77,7 @@ def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDr
|
|||||||
按流程实例 requestid 合并联表结果。
|
按流程实例 requestid 合并联表结果。
|
||||||
|
|
||||||
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||||
不读取流程编号、第二合同编号和验收日期。
|
流程编号和标题随行写入。不读取第二合同编号和验收日期。
|
||||||
Args:
|
Args:
|
||||||
rows: 查询别名组成的字典行。
|
rows: 查询别名组成的字典行。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -94,10 +98,14 @@ def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> Acceptance
|
|||||||
"""同一流程实例的多行收成一条草稿。"""
|
"""同一流程实例的多行收成一条草稿。"""
|
||||||
header = items[0]
|
header = items[0]
|
||||||
return AcceptanceDraft(
|
return AcceptanceDraft(
|
||||||
|
oa_system="e10",
|
||||||
request_id=request_id,
|
request_id=request_id,
|
||||||
acceptance_no=_text(header.get("ysddh")),
|
acceptance_no=_text(header.get("ysddh")),
|
||||||
purchase_order_no=_text(header.get("cgdh")),
|
purchase_order_no=_text(header.get("cgdh")),
|
||||||
contract_no=_text(header.get("htbh")),
|
contract_no=_text(header.get("htbh")),
|
||||||
|
flow_no=_text(header.get("flow_no")),
|
||||||
|
request_title=_text(header.get("request_title")),
|
||||||
|
request_created_at=as_datetime(header.get("createdatetime")),
|
||||||
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
||||||
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
||||||
cannot_accept_note=_text(header.get("ycsm")),
|
cannot_accept_note=_text(header.get("ycsm")),
|
||||||
|
|||||||
@@ -1,19 +1,24 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/equipment_acceptance/sync_service.py
|
backend/app/services/equipment_acceptance/sync_service.py
|
||||||
|
|
||||||
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
用途:把 E10 和 E8 验收单快照写入本地表,并提供管理员查询。
|
||||||
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
|
依赖:extensions.db、sqlalchemy.or_、equipment_acceptance 模型、snapshot_rules、source_group、e8_group、oa_repository、e8_repository。
|
||||||
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
|
逻辑:两个来源分开拉取。一边失败不改另一边的快照,也不把失败来源标成消失。
|
||||||
停表时取消该单未发送的预警。操作人不保存 isremark。
|
只保留未归档单据。归档单不写入;该来源本次结果里没有的本地单删除,并取消未发送预警。
|
||||||
|
主表按 oa_system + request_id 更新,并写入流程编号和标题。子表整批替换。停表时取消未发送预警。
|
||||||
|
列表查询由 api/equipment_acceptance 调用。单号关键字同时匹配流程编号、验收单号和采购单号,再与申请人取交集。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import or_
|
||||||
|
|
||||||
from app.core.errors import NotFoundError, ValidationError
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
from app.core.response import utc_iso
|
from app.core.response import utc_iso
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
@@ -25,12 +30,15 @@ from app.models.equipment_acceptance import (
|
|||||||
from app.services.equipment_acceptance.config_service import first_reminder_day
|
from app.services.equipment_acceptance.config_service import first_reminder_day
|
||||||
from app.services.equipment_acceptance.snapshot_rules import (
|
from app.services.equipment_acceptance.snapshot_rules import (
|
||||||
MONITOR_STATUSES,
|
MONITOR_STATUSES,
|
||||||
|
STOPPED_ARCHIVED,
|
||||||
classify_monitor_status,
|
classify_monitor_status,
|
||||||
dwell_days,
|
dwell_days,
|
||||||
)
|
)
|
||||||
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||||
|
_ARCHIVED_FLOW = 3
|
||||||
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
||||||
_STOPPED_STATUSES = (
|
_STOPPED_STATUSES = (
|
||||||
"stopped_returned",
|
"stopped_returned",
|
||||||
@@ -42,34 +50,107 @@ _STOPPED_STATUSES = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
def sync_acceptance_snapshots(
|
||||||
|
rows: list[dict[str, Any]] | None = None,
|
||||||
|
*,
|
||||||
|
e8_rows: list[dict[str, Any]] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
同步验收单快照。
|
同步 E10 和 E8 验收单快照。
|
||||||
|
|
||||||
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
核心逻辑:未传入行时分别读两个来源。一边查询失败只跳过这一边,不把已有快照标成消失。
|
||||||
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
只保留未归档单据。该来源本次没返回的本地单删掉。只传入 rows 时只同步 E10,方便既有测试注入联表行。
|
||||||
Args:
|
Args:
|
||||||
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
rows: 已取好的 E10 联表行。None 时访问 E10。
|
||||||
|
e8_rows: 已取好的 E8 联表行。与 rows 同时为 None 时才访问 E8。
|
||||||
Returns:
|
Returns:
|
||||||
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
两边合计的写入、跳过、消失和取消条数,以及 e10、e8 各自的结果。
|
||||||
"""
|
"""
|
||||||
if rows is None:
|
fetch_live = rows is None and e8_rows is None
|
||||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
e10_rows, e10_ok, e10_error = _source_rows("e10", rows, fetch_live)
|
||||||
|
e8_input, e8_ok, e8_error = _source_rows("e8", e8_rows, fetch_live)
|
||||||
rows = fetch_acceptance_rows()
|
|
||||||
drafts, skipped = group_acceptance_rows(rows)
|
|
||||||
as_of = datetime.now(_SHANGHAI).date()
|
as_of = datetime.now(_SHANGHAI).date()
|
||||||
|
e10_result = _apply_source("e10", e10_rows, e10_ok, e10_error, as_of, group_acceptance_rows)
|
||||||
|
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
||||||
|
|
||||||
|
e8_result = _apply_source("e8", e8_input, e8_ok, e8_error, as_of, group_e8_rows)
|
||||||
|
db.session.commit()
|
||||||
|
cancelled = e10_result["cancelled"] + e8_result["cancelled"]
|
||||||
|
counts: Counter[str] = Counter(e10_result["by_status"])
|
||||||
|
counts.update(e8_result["by_status"])
|
||||||
|
return {
|
||||||
|
"upserted": e10_result["upserted"] + e8_result["upserted"],
|
||||||
|
"skipped_without_request_id": (
|
||||||
|
e10_result["skipped_without_request_id"] + e8_result["skipped_without_request_id"]
|
||||||
|
),
|
||||||
|
"absent": e10_result["absent"] + e8_result["absent"],
|
||||||
|
"cancelled": cancelled,
|
||||||
|
"by_status": dict(counts),
|
||||||
|
"e10": e10_result,
|
||||||
|
"e8": e8_result,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _source_rows(
|
||||||
|
source: str,
|
||||||
|
injected: list[dict[str, Any]] | None,
|
||||||
|
fetch_live: bool,
|
||||||
|
) -> tuple[list[dict[str, Any]] | None, bool, str | None]:
|
||||||
|
"""取一个来源的行。注入的行视为成功。实时查询失败时不标消失。"""
|
||||||
|
if injected is not None:
|
||||||
|
return injected, True, None
|
||||||
|
if not fetch_live:
|
||||||
|
return None, False, None
|
||||||
|
try:
|
||||||
|
if source == "e10":
|
||||||
|
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||||
|
|
||||||
|
return fetch_acceptance_rows(), True, None
|
||||||
|
from app.services.equipment_acceptance.e8_repository import fetch_e8_acceptance_rows
|
||||||
|
|
||||||
|
return fetch_e8_acceptance_rows(), True, None
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance %s sync skipped error=%s", source, type(exc).__name__)
|
||||||
|
return None, False, type(exc).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_source(
|
||||||
|
source: str,
|
||||||
|
rows: list[dict[str, Any]] | None,
|
||||||
|
ok: bool,
|
||||||
|
error: str | None,
|
||||||
|
as_of,
|
||||||
|
grouper,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""把一个来源的未归档草稿写入。该来源这次没返回的本地单删除。"""
|
||||||
|
if not ok or rows is None:
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"error": error,
|
||||||
|
"upserted": 0,
|
||||||
|
"skipped_without_request_id": 0,
|
||||||
|
"absent": 0,
|
||||||
|
"cancelled": 0,
|
||||||
|
"by_status": {},
|
||||||
|
}
|
||||||
|
drafts, skipped = grouper(rows)
|
||||||
counts: Counter[str] = Counter()
|
counts: Counter[str] = Counter()
|
||||||
request_ids: list[int] = []
|
request_ids: list[int] = []
|
||||||
cancelled = 0
|
cancelled = 0
|
||||||
for draft in drafts:
|
for draft in drafts:
|
||||||
|
# [STEP] 归档单不落本地。查询已排除;这里再挡一层,避免注入行把归档单写回来。
|
||||||
|
if draft.flow_status_raw == _ARCHIVED_FLOW:
|
||||||
|
continue
|
||||||
|
draft.oa_system = source
|
||||||
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
||||||
request_ids.append(order.request_id)
|
request_ids.append(order.request_id)
|
||||||
counts[order.monitor_status] += 1
|
counts[order.monitor_status] += 1
|
||||||
cancelled += cancelled_now
|
cancelled += cancelled_now
|
||||||
absent = _mark_absent(request_ids)
|
absent, cancelled_missing = _drop_missing(request_ids, source)
|
||||||
db.session.commit()
|
cancelled += cancelled_missing
|
||||||
return {
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"error": None,
|
||||||
"upserted": len(drafts),
|
"upserted": len(drafts),
|
||||||
"skipped_without_request_id": skipped,
|
"skipped_without_request_id": skipped,
|
||||||
"absent": absent,
|
"absent": absent,
|
||||||
@@ -84,17 +165,23 @@ def list_acceptance_orders(
|
|||||||
focus: str | None,
|
focus: str | None,
|
||||||
page: int,
|
page: int,
|
||||||
page_size: int,
|
page_size: int,
|
||||||
|
keyword: str | None = None,
|
||||||
|
applicant: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
分页列出本地快照。
|
分页列出本地快照。
|
||||||
|
|
||||||
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
核心逻辑:focus 按全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||||
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
keyword 在流程编号、验收单号、采购单号里任一包含即命中,再与申请人姓名取交集。
|
||||||
|
已归档不列出。已逾期是计时中且签核天数超过第 1 档。
|
||||||
|
汇总不看当前状态分组,但跟着单号关键字和申请人走,也不计归档。
|
||||||
Args:
|
Args:
|
||||||
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
||||||
focus: watching、overdue、stopped、not_started 或空。
|
focus: watching、overdue、stopped、not_started 或空。
|
||||||
page: 从 1 开始。
|
page: 从 1 开始。
|
||||||
page_size: 每页条数,上限 100。
|
page_size: 每页条数,上限 100。
|
||||||
|
keyword: 流程编号、验收单号或采购单号的包含匹配。空白表示不筛。
|
||||||
|
applicant: 申请人姓名的包含匹配。空白表示不筛。
|
||||||
Returns:
|
Returns:
|
||||||
items、total、page、page_size、summary。
|
items、total、page、page_size、summary。
|
||||||
|
|
||||||
@@ -106,7 +193,11 @@ def list_acceptance_orders(
|
|||||||
reminder_day = first_reminder_day()
|
reminder_day = first_reminder_day()
|
||||||
page = max(1, page)
|
page = max(1, page)
|
||||||
page_size = min(100, max(1, page_size))
|
page_size = min(100, max(1, page_size))
|
||||||
query = db.session.query(EquipmentAcceptanceOrder)
|
query = _apply_search(
|
||||||
|
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||||
|
keyword=keyword,
|
||||||
|
applicant=applicant,
|
||||||
|
)
|
||||||
if ledger_focus:
|
if ledger_focus:
|
||||||
query = _apply_focus(query, ledger_focus, reminder_day)
|
query = _apply_focus(query, ledger_focus, reminder_day)
|
||||||
elif status:
|
elif status:
|
||||||
@@ -131,7 +222,7 @@ def list_acceptance_orders(
|
|||||||
"page": page,
|
"page": page,
|
||||||
"page_size": page_size,
|
"page_size": page_size,
|
||||||
"pages": pages,
|
"pages": pages,
|
||||||
"summary": _ledger_summary(reminder_day),
|
"summary": _ledger_summary(reminder_day, keyword=keyword, applicant=applicant),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -160,20 +251,25 @@ def get_acceptance_order(order_id: int) -> dict[str, Any]:
|
|||||||
|
|
||||||
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
||||||
"""
|
"""
|
||||||
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
|
按来源和流程实例更新主表,并替换该单的节点和操作人。
|
||||||
|
|
||||||
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
||||||
|
E10 与 E8 的 request_id 可以相同,必须连 oa_system 一起查。
|
||||||
Returns:
|
Returns:
|
||||||
更新后的验收单,以及本次改成已取消的发送记录条数。
|
更新后的验收单,以及本次改成已取消的发送记录条数。
|
||||||
"""
|
"""
|
||||||
order = (
|
order = (
|
||||||
db.session.query(EquipmentAcceptanceOrder)
|
db.session.query(EquipmentAcceptanceOrder)
|
||||||
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
.filter(
|
||||||
|
EquipmentAcceptanceOrder.oa_system == draft.oa_system,
|
||||||
|
EquipmentAcceptanceOrder.request_id == draft.request_id,
|
||||||
|
)
|
||||||
.one_or_none()
|
.one_or_none()
|
||||||
)
|
)
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
if order is None:
|
if order is None:
|
||||||
order = EquipmentAcceptanceOrder(
|
order = EquipmentAcceptanceOrder(
|
||||||
|
oa_system=draft.oa_system,
|
||||||
request_id=draft.request_id,
|
request_id=draft.request_id,
|
||||||
monitor_status="excluded",
|
monitor_status="excluded",
|
||||||
synced_at=now,
|
synced_at=now,
|
||||||
@@ -185,6 +281,9 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
|||||||
order.acceptance_no = draft.acceptance_no
|
order.acceptance_no = draft.acceptance_no
|
||||||
order.purchase_order_no = draft.purchase_order_no
|
order.purchase_order_no = draft.purchase_order_no
|
||||||
order.contract_no = draft.contract_no
|
order.contract_no = draft.contract_no
|
||||||
|
order.flow_no = draft.flow_no
|
||||||
|
order.request_title = draft.request_title
|
||||||
|
order.request_created_at = draft.request_created_at
|
||||||
order.timer_started_at = draft.timer_started_at
|
order.timer_started_at = draft.timer_started_at
|
||||||
order.can_accept = draft.can_accept
|
order.can_accept = draft.can_accept
|
||||||
order.cannot_accept_note = draft.cannot_accept_note
|
order.cannot_accept_note = draft.cannot_accept_note
|
||||||
@@ -254,12 +353,45 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
|||||||
return order, cancelled
|
return order, cancelled
|
||||||
|
|
||||||
|
|
||||||
def _mark_absent(request_ids: list[int]) -> int:
|
def _drop_missing(request_ids: list[int], oa_system: str) -> tuple[int, int]:
|
||||||
"""把这次没拉到的单据标成源里不存在。"""
|
"""
|
||||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
|
删除这个来源里本次未归档结果没有的本地单。
|
||||||
|
|
||||||
|
核心逻辑:查询已不含归档。本地还在、结果里没有的单,视为已归档或已从 OA 消失。
|
||||||
|
先取消未发送预警,再删主表。节点和操作人随外键级联删除。已发送记录保留,只解开验收单外键。
|
||||||
|
不改另一个来源。查询失败的来源不会进到这里。
|
||||||
|
Returns:
|
||||||
|
删除张数,以及取消的未发送条数。
|
||||||
|
"""
|
||||||
|
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.oa_system == oa_system)
|
||||||
if request_ids:
|
if request_ids:
|
||||||
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
||||||
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
gone = query.all()
|
||||||
|
if not gone:
|
||||||
|
return 0, 0
|
||||||
|
from app.services.equipment_acceptance.alert_service import cancel_unsent
|
||||||
|
|
||||||
|
cancelled = 0
|
||||||
|
for order in gone:
|
||||||
|
cancelled += cancel_unsent(order.id)
|
||||||
|
db.session.delete(order)
|
||||||
|
return len(gone), cancelled
|
||||||
|
|
||||||
|
|
||||||
|
def _without_archived(query):
|
||||||
|
"""
|
||||||
|
列表和汇总都不展示已归档。
|
||||||
|
|
||||||
|
核心逻辑:状态已是归档的不显示。流程原值已是 3 的也不显示,
|
||||||
|
避免退回或无法验收优先落成别的状态后,归档单仍留在列表里。
|
||||||
|
"""
|
||||||
|
return query.filter(
|
||||||
|
EquipmentAcceptanceOrder.monitor_status != STOPPED_ARCHIVED,
|
||||||
|
or_(
|
||||||
|
EquipmentAcceptanceOrder.flow_status_raw.is_(None),
|
||||||
|
EquipmentAcceptanceOrder.flow_status_raw != _ARCHIVED_FLOW,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _clean_focus(focus: str | None) -> str | None:
|
def _clean_focus(focus: str | None) -> str | None:
|
||||||
@@ -290,9 +422,65 @@ def _apply_focus(query, focus: str, reminder_day: int):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
def _clean_search(value: str | None) -> str | None:
|
||||||
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
"""去掉首尾空白。空白视为不筛选。过长时只保留前 100 字,避免把整段说明送进 LIKE。"""
|
||||||
base = db.session.query(EquipmentAcceptanceOrder)
|
text = str(value or "").strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
return text[:100]
|
||||||
|
|
||||||
|
|
||||||
|
def _contains_pattern(text: str) -> str:
|
||||||
|
"""
|
||||||
|
把用户输入收成包含匹配,并把 LIKE 通配符当成普通字符。
|
||||||
|
|
||||||
|
核心逻辑:% 和 _ 要能搜出单号里的原字符,不能变成任意匹配。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: 已经去掉空白的搜索词。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
带前后百分号、且转义过的模式。
|
||||||
|
"""
|
||||||
|
escaped = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
return f"%{escaped}%"
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_search(query, *, keyword: str | None, applicant: str | None):
|
||||||
|
"""
|
||||||
|
按单号关键字和申请人收窄查询。
|
||||||
|
|
||||||
|
核心逻辑:关键字在流程编号、验收单号、采购单号三者取并集;申请人再与这个结果取交集。
|
||||||
|
比较不区分大小写。空值不加入条件。
|
||||||
|
"""
|
||||||
|
number = _clean_search(keyword)
|
||||||
|
if number:
|
||||||
|
pattern = _contains_pattern(number)
|
||||||
|
query = query.filter(or_(
|
||||||
|
EquipmentAcceptanceOrder.flow_no.ilike(pattern, escape="\\"),
|
||||||
|
EquipmentAcceptanceOrder.acceptance_no.ilike(pattern, escape="\\"),
|
||||||
|
EquipmentAcceptanceOrder.purchase_order_no.ilike(pattern, escape="\\"),
|
||||||
|
))
|
||||||
|
person = _clean_search(applicant)
|
||||||
|
if person:
|
||||||
|
query = query.filter(
|
||||||
|
EquipmentAcceptanceOrder.applicant_name.ilike(_contains_pattern(person), escape="\\"),
|
||||||
|
)
|
||||||
|
return query
|
||||||
|
|
||||||
|
|
||||||
|
def _ledger_summary(
|
||||||
|
reminder_day: int,
|
||||||
|
*,
|
||||||
|
keyword: str | None = None,
|
||||||
|
applicant: str | None = None,
|
||||||
|
) -> dict[str, int]:
|
||||||
|
"""统计未归档单据的进行中、已逾期、不再提醒、未开始。不看状态分组,但跟着单号和申请人走。"""
|
||||||
|
base = _apply_search(
|
||||||
|
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||||
|
keyword=keyword,
|
||||||
|
applicant=applicant,
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
||||||
"overdue": base.filter(
|
"overdue": base.filter(
|
||||||
@@ -359,9 +547,13 @@ def _order_payload(
|
|||||||
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
||||||
payload: dict[str, Any] = {
|
payload: dict[str, Any] = {
|
||||||
"id": order.id,
|
"id": order.id,
|
||||||
|
"oa_system": order.oa_system,
|
||||||
"acceptance_no": order.acceptance_no,
|
"acceptance_no": order.acceptance_no,
|
||||||
"purchase_order_no": order.purchase_order_no,
|
"purchase_order_no": order.purchase_order_no,
|
||||||
"contract_no": order.contract_no,
|
"contract_no": order.contract_no,
|
||||||
|
"flow_no": order.flow_no,
|
||||||
|
"request_title": order.request_title,
|
||||||
|
"request_created_at": utc_iso(order.request_created_at),
|
||||||
"timer_started_at": utc_iso(order.timer_started_at),
|
"timer_started_at": utc_iso(order.timer_started_at),
|
||||||
"dwell_days": order.dwell_days,
|
"dwell_days": order.dwell_days,
|
||||||
"can_accept": order.can_accept,
|
"can_accept": order.can_accept,
|
||||||
|
|||||||
@@ -129,6 +129,10 @@ def build_feedback_markdown(feedback: GeneralFeedback, user: User | None) -> str
|
|||||||
lines.append(f'>来源页面:{feedback.source_page}')
|
lines.append(f'>来源页面:{feedback.source_page}')
|
||||||
if feedback.chat_log_id:
|
if feedback.chat_log_id:
|
||||||
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
||||||
|
# 附图行:仅在有截图时展示数量,置于「反馈内容」之前,便于处理人先感知附件再读正文
|
||||||
|
image_count = len(feedback.images or [])
|
||||||
|
if image_count:
|
||||||
|
lines.append(f'>附图:{image_count} 张')
|
||||||
lines.extend(['', '**反馈内容:**', content or '-'])
|
lines.extend(['', '**反馈内容:**', content or '-'])
|
||||||
if report_url:
|
if report_url:
|
||||||
lines.extend(['', f'[打开后台报表]({report_url})'])
|
lines.extend(['', f'[打开后台报表]({report_url})'])
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ backend/app/services/file_assets/storage.py
|
|||||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||||
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
||||||
|
读写删走 MINIO_ENDPOINT(容器内网)。浏览器预签走 MINIO_PUBLIC_BASE_URL,
|
||||||
|
因为签名包含 Host,不能把 host.docker.internal 交给浏览器后再替换。
|
||||||
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -13,6 +15,7 @@ import io
|
|||||||
import logging
|
import logging
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from typing import BinaryIO
|
from typing import BinaryIO
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
from minio import Minio
|
from minio import Minio
|
||||||
from minio.error import S3Error
|
from minio.error import S3Error
|
||||||
@@ -24,16 +27,75 @@ _LOGGER = logging.getLogger(__name__)
|
|||||||
_cfg = config[ACTIVE_ENV_NAME]
|
_cfg = config[ACTIVE_ENV_NAME]
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_presign_endpoint(
|
||||||
|
public_base: str,
|
||||||
|
fallback_endpoint: str,
|
||||||
|
fallback_secure: bool,
|
||||||
|
) -> tuple[str, bool]:
|
||||||
|
"""把浏览器可访问的 MinIO 基址收成预签名客户端的 endpoint 与 secure。
|
||||||
|
|
||||||
|
核心逻辑:SigV4 把 Host 写进签名。正式环境容器用 host.docker.internal:9000
|
||||||
|
读写,浏览器必须打开 MINIO_PUBLIC_BASE_URL(如 http://ai.well-trust.com:9000)。
|
||||||
|
基址为空或解析不出主机时退回内网端点。80/443 省略端口,交给 Minio 客户端按协议补。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
public_base: MINIO_PUBLIC_BASE_URL,可带或不带协议。
|
||||||
|
fallback_endpoint: 容器内访问用的 host:port。
|
||||||
|
fallback_secure: 内网端点是否走 HTTPS。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(endpoint, secure)。endpoint 形如 ai.well-trust.com:9000。
|
||||||
|
"""
|
||||||
|
raw = (public_base or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return fallback_endpoint, fallback_secure
|
||||||
|
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
|
||||||
|
host = parsed.hostname
|
||||||
|
if not host:
|
||||||
|
return fallback_endpoint, fallback_secure
|
||||||
|
if ":" in host:
|
||||||
|
host = f"[{host}]"
|
||||||
|
secure = parsed.scheme.lower() == "https"
|
||||||
|
port = parsed.port
|
||||||
|
if port and not ((secure and port == 443) or (not secure and port == 80)):
|
||||||
|
return f"{host}:{port}", secure
|
||||||
|
return host, secure
|
||||||
|
|
||||||
|
|
||||||
class FileAssetStorage:
|
class FileAssetStorage:
|
||||||
"""私有业务文件 MinIO 存储客户端。"""
|
"""私有业务文件 MinIO 存储客户端。"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
|
"""分别建立内网读写客户端与浏览器预签名客户端。
|
||||||
|
|
||||||
|
核心逻辑:两端点主机与协议相同时共用一个客户端。预签名客户端只在
|
||||||
|
生成 URL 时做本地签名,不靠它访问内网 MinIO。
|
||||||
|
"""
|
||||||
|
endpoint = str(_cfg.MINIO_ENDPOINT or "").strip()
|
||||||
|
access_key = _cfg.MINIO_ACCESS_KEY
|
||||||
|
secret_key = _cfg.MINIO_SECRET_KEY
|
||||||
|
secure = bool(_cfg.MINIO_SECURE)
|
||||||
self.client = Minio(
|
self.client = Minio(
|
||||||
_cfg.MINIO_ENDPOINT,
|
endpoint,
|
||||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
access_key=access_key,
|
||||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
secret_key=secret_key,
|
||||||
secure=_cfg.MINIO_SECURE,
|
secure=secure,
|
||||||
)
|
)
|
||||||
|
# [STEP 1] 预签名单独用浏览器主机。只改 URL 字符串会使签名失效。
|
||||||
|
presign_endpoint, presign_secure = resolve_presign_endpoint(
|
||||||
|
str(_cfg.MINIO_PUBLIC_BASE_URL or ""),
|
||||||
|
endpoint,
|
||||||
|
secure,
|
||||||
|
)
|
||||||
|
if presign_endpoint == endpoint and presign_secure == secure:
|
||||||
|
self.presign_client = self.client
|
||||||
|
else:
|
||||||
|
self.presign_client = Minio(
|
||||||
|
presign_endpoint,
|
||||||
|
access_key=access_key,
|
||||||
|
secret_key=secret_key,
|
||||||
|
secure=presign_secure,
|
||||||
|
)
|
||||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||||
|
|
||||||
def _ensure_bucket_exists(self) -> None:
|
def _ensure_bucket_exists(self) -> None:
|
||||||
@@ -120,6 +182,19 @@ class FileAssetStorage:
|
|||||||
except S3Error:
|
except S3Error:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def _bind_presign_region(self) -> None:
|
||||||
|
"""把内网客户端已探到的 region 抄给预签名客户端。
|
||||||
|
|
||||||
|
核心逻辑:minio-py 在签名前会请求 GetBucketLocation。若用公网客户端发这次请求,
|
||||||
|
容器里可能访问不到浏览器入口,或每次下载多一次公网探测。
|
||||||
|
bucket 检查已经通过内网客户端写入 _region_map;这里只复用该结果。
|
||||||
|
尚未探测到时用 MinIO 默认 us-east-1。
|
||||||
|
"""
|
||||||
|
if self.presign_client is self.client:
|
||||||
|
return
|
||||||
|
region = self.client._region_map.get(self.bucket_name) or "us-east-1"
|
||||||
|
self.presign_client._region_map[self.bucket_name] = region
|
||||||
|
|
||||||
def presigned_get_url(
|
def presigned_get_url(
|
||||||
self,
|
self,
|
||||||
storage_key: str,
|
storage_key: str,
|
||||||
@@ -129,7 +204,9 @@ class FileAssetStorage:
|
|||||||
) -> str:
|
) -> str:
|
||||||
"""生成短期受控下载 URL。
|
"""生成短期受控下载 URL。
|
||||||
|
|
||||||
核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。
|
核心逻辑:先把内网探到的 region 绑到 presign_client,再用它签名。
|
||||||
|
主机来自 MINIO_PUBLIC_BASE_URL。签名在本地完成,不再向公网探测 bucket 区域。
|
||||||
|
对象键常为内容哈希,浏览器会把它当成保存名。
|
||||||
download_name 非空时把 response-content-disposition 签进 URL,
|
download_name 非空时把 response-content-disposition 签进 URL,
|
||||||
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
||||||
|
|
||||||
@@ -139,16 +216,17 @@ class FileAssetStorage:
|
|||||||
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
带过期签名的 GET URL。
|
带过期签名的 GET URL,主机是浏览器可访问的 MinIO 地址。
|
||||||
"""
|
"""
|
||||||
self._ensure_bucket_exists()
|
self._ensure_bucket_exists()
|
||||||
|
self._bind_presign_region()
|
||||||
response_headers = None
|
response_headers = None
|
||||||
if download_name:
|
if download_name:
|
||||||
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
||||||
response_headers = {
|
response_headers = {
|
||||||
'response-content-disposition': f'attachment; filename="{safe}"',
|
'response-content-disposition': f'attachment; filename="{safe}"',
|
||||||
}
|
}
|
||||||
return self.client.presigned_get_object(
|
return self.presign_client.presigned_get_object(
|
||||||
self.bucket_name,
|
self.bucket_name,
|
||||||
storage_key,
|
storage_key,
|
||||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||||
|
|||||||
@@ -3,8 +3,9 @@ services/freight_rpa/common/credential_crypto.py
|
|||||||
|
|
||||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
|
逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
|
||||||
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
|
||||||
|
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
|
|||||||
ciphertext: 数据库中保存的 Fernet 密文。
|
ciphertext: 数据库中保存的 Fernet 密文。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: 仅供 RPA 执行内存使用的明文。
|
str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ from app.core.errors import NotFoundError
|
|||||||
from app.models import (
|
from app.models import (
|
||||||
FreightRpaInboundReportConfig,
|
FreightRpaInboundReportConfig,
|
||||||
FreightRpaInboundReportFile,
|
FreightRpaInboundReportFile,
|
||||||
|
FreightRpaInboundUnitRun,
|
||||||
FreightRpaOnhandReportConfig,
|
FreightRpaOnhandReportConfig,
|
||||||
FreightRpaOutboundReportConfig,
|
FreightRpaOutboundReportConfig,
|
||||||
FreightRpaOutboundReportFile,
|
FreightRpaOutboundReportFile,
|
||||||
@@ -659,6 +660,72 @@ def latest_usable_inbound_file(
|
|||||||
return _inbound_file_view(report)
|
return _inbound_file_view(report)
|
||||||
|
|
||||||
|
|
||||||
|
def latest_usable_inbound_files_by_source(
|
||||||
|
source_ids: list[int],
|
||||||
|
*,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> dict[str, InboundFileView]:
|
||||||
|
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
|
||||||
|
|
||||||
|
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
|
||||||
|
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
|
||||||
|
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
|
||||||
|
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||||
|
Returns:
|
||||||
|
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
|
||||||
|
只留 created_at/id 最新一条。
|
||||||
|
"""
|
||||||
|
rows = (
|
||||||
|
FreightRpaInboundReportFile.query
|
||||||
|
.join(FreightRpaInboundReportFile.unit_run)
|
||||||
|
.filter(
|
||||||
|
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||||
|
usable_inbound_file_condition(now=now),
|
||||||
|
)
|
||||||
|
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
picked: dict[str, InboundFileView] = {}
|
||||||
|
for report in rows:
|
||||||
|
view = _inbound_file_view(report)
|
||||||
|
if view.source_code not in picked:
|
||||||
|
picked[view.source_code] = view
|
||||||
|
return picked
|
||||||
|
|
||||||
|
|
||||||
|
def expired_inbound_source_codes(
|
||||||
|
source_ids: list[int],
|
||||||
|
*,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> set[str]:
|
||||||
|
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
|
||||||
|
|
||||||
|
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
|
||||||
|
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_ids: 来源主键集合。
|
||||||
|
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||||
|
Returns:
|
||||||
|
至少有一份失效未清理入站归档的 source_code 集合。
|
||||||
|
"""
|
||||||
|
rows = (
|
||||||
|
FreightRpaInboundReportFile.query
|
||||||
|
.join(FreightRpaInboundReportFile.unit_run)
|
||||||
|
.filter(
|
||||||
|
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||||
|
expired_inbound_file_condition(now=now),
|
||||||
|
)
|
||||||
|
.with_entities(FreightRpaInboundUnitRun.source_code)
|
||||||
|
.distinct()
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {str(row[0]) for row in rows}
|
||||||
|
|
||||||
|
|
||||||
def read_inbound_file_bytes(file_id: int) -> bytes:
|
def read_inbound_file_bytes(file_id: int) -> bytes:
|
||||||
"""按 file_id 读取入站归档文件的对象字节。
|
"""按 file_id 读取入站归档文件的对象字节。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
"""
|
||||||
|
services/freight_rpa/upload/crane_recheck.py
|
||||||
|
|
||||||
|
用途:Crane 发货单进入分配中之后的状态回查。
|
||||||
|
依赖:ShippingUploadAttempt、freight_rpa.upload.trigger_io、page_contract。
|
||||||
|
逻辑:自动上传只排一次 10 分钟后的回查;手动刷新另写一条 status_check trigger,
|
||||||
|
不顺延、不取消那一次定时。两条回查都只让 Worker 重新登录并按 Pull Request # 看行。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.errors import ConflictError, ValidationError
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import ShippingExportArtifact, ShippingNotice, ShippingUploadAttempt
|
||||||
|
from app.services.freight_rpa.upload.page_contract import crane_recheck_due_at
|
||||||
|
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||||
|
|
||||||
|
CRANE_ALLOCATING_CODE = 'CRANE_ALLOCATING'
|
||||||
|
|
||||||
|
|
||||||
|
def is_crane_allocating(attempt: ShippingUploadAttempt | None) -> bool:
|
||||||
|
"""当前尝试是否停在 Crane 已接收、尚未分配完成。"""
|
||||||
|
return (
|
||||||
|
attempt is not None
|
||||||
|
and attempt.status == 'running'
|
||||||
|
and attempt.error_code == CRANE_ALLOCATING_CODE
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _evidence(attempt: ShippingUploadAttempt) -> dict[str, Any]:
|
||||||
|
raw = attempt.success_evidence_json
|
||||||
|
return dict(raw) if isinstance(raw, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _recheck(evidence: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
raw = evidence.get('crane_recheck')
|
||||||
|
return dict(raw) if isinstance(raw, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def remember_crane_allocating(
|
||||||
|
attempt: ShippingUploadAttempt,
|
||||||
|
artifact: ShippingExportArtifact,
|
||||||
|
callback_id: str,
|
||||||
|
*,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> ShippingUploadAttempt:
|
||||||
|
"""把尝试标成分配中,并在首次进入时记下唯一一次定时回查。
|
||||||
|
|
||||||
|
核心逻辑:due_at 只在还没有时写入。后续回查回调仍是分配中时,不改到期时间,
|
||||||
|
也不把定时标记成已触发。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
attempt: 本次上传尝试。
|
||||||
|
artifact: 已提交的发货 Excel。
|
||||||
|
callback_id: 本次回调幂等键。重复的同一个键直接返回。
|
||||||
|
now: 测试注入的当前时间。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ShippingUploadAttempt: 仍为 running、错误码为 CRANE_ALLOCATING 的尝试。
|
||||||
|
"""
|
||||||
|
evidence = _evidence(attempt)
|
||||||
|
if evidence.get('last_callback_id') == callback_id or attempt.callback_id == callback_id:
|
||||||
|
return attempt
|
||||||
|
recheck = _recheck(evidence)
|
||||||
|
if not recheck.get('due_at'):
|
||||||
|
pull_request_no = str(artifact.file_name or '').rsplit('.', 1)[0] or str(artifact.file_name or '')
|
||||||
|
recheck = {
|
||||||
|
'due_at': crane_recheck_due_at(now).isoformat(timespec='seconds'),
|
||||||
|
'fired': False,
|
||||||
|
'pull_request_no': pull_request_no,
|
||||||
|
}
|
||||||
|
evidence['crane_recheck'] = recheck
|
||||||
|
evidence['last_callback_id'] = callback_id
|
||||||
|
evidence['manual_refresh_inflight'] = False
|
||||||
|
attempt.success_evidence_json = evidence
|
||||||
|
attempt.status = 'running'
|
||||||
|
attempt.error_code = CRANE_ALLOCATING_CODE
|
||||||
|
attempt.error_message = None
|
||||||
|
attempt.finished_at = None
|
||||||
|
if not attempt.callback_id:
|
||||||
|
attempt.callback_id = callback_id
|
||||||
|
artifact.status = 'uploading'
|
||||||
|
db.session.flush()
|
||||||
|
return attempt
|
||||||
|
|
||||||
|
|
||||||
|
def _write_status_check(
|
||||||
|
attempt: ShippingUploadAttempt,
|
||||||
|
upload_source: dict[str, Any],
|
||||||
|
*,
|
||||||
|
task_no: str,
|
||||||
|
export_file_path: str,
|
||||||
|
pull_request_no: str,
|
||||||
|
kind: str,
|
||||||
|
) -> str | None:
|
||||||
|
"""写入一条只查状态的上传 trigger。文件复制失败时返回 None。"""
|
||||||
|
# 定时回查的回调键固定,重复心跳不会写成两次有效回调。
|
||||||
|
# 手动刷新每次使用新键,避免上一次「仍在分配」把这一次回调当成重复而跳过。
|
||||||
|
callback_id = f'crane-recheck:{attempt.id}:scheduled'
|
||||||
|
trigger_filename = f'upload_recheck_{task_no}_scheduled.json'
|
||||||
|
if kind == 'manual':
|
||||||
|
callback_id = f'crane-recheck:{attempt.id}:manual:{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||||
|
trigger_filename = f'upload_recheck_{task_no}_manual.json'
|
||||||
|
_queue, trigger_path, _callback = write_upload_trigger(
|
||||||
|
task_no,
|
||||||
|
export_file_path,
|
||||||
|
{'mode': 'status_check', 'recheck_kind': kind, 'pull_request_no': pull_request_no},
|
||||||
|
attempt_id=int(attempt.id),
|
||||||
|
artifact_id=int(attempt.artifact_id),
|
||||||
|
connector_type='crane',
|
||||||
|
upload_config={'enabled': True},
|
||||||
|
login_url=str(upload_source.get('login_url') or '').strip() or None,
|
||||||
|
credential_envelope=upload_source.get('credential_envelope') if isinstance(upload_source.get('credential_envelope'), dict) else None,
|
||||||
|
callback_id=callback_id,
|
||||||
|
business_no=pull_request_no,
|
||||||
|
trigger_filename=trigger_filename,
|
||||||
|
)
|
||||||
|
return trigger_path
|
||||||
|
|
||||||
|
|
||||||
|
def fire_scheduled_crane_recheck(
|
||||||
|
attempt: ShippingUploadAttempt,
|
||||||
|
upload_source: dict[str, Any],
|
||||||
|
*,
|
||||||
|
task_no: str,
|
||||||
|
export_file_path: str,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""到期后写入唯一一次定时回查。未到期、已触发或不是分配中时不写文件。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 本次是否新写了 trigger。
|
||||||
|
"""
|
||||||
|
if not is_crane_allocating(attempt):
|
||||||
|
return False
|
||||||
|
evidence = _evidence(attempt)
|
||||||
|
recheck = _recheck(evidence)
|
||||||
|
if recheck.get('fired') or not recheck.get('due_at'):
|
||||||
|
return False
|
||||||
|
due_at = datetime.fromisoformat(str(recheck['due_at']))
|
||||||
|
if due_at > (now or datetime.utcnow()):
|
||||||
|
return False
|
||||||
|
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||||
|
trigger_path = _write_status_check(
|
||||||
|
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||||
|
pull_request_no=pull_request_no, kind='scheduled',
|
||||||
|
)
|
||||||
|
if not trigger_path:
|
||||||
|
return False
|
||||||
|
recheck['fired'] = True
|
||||||
|
evidence['crane_recheck'] = recheck
|
||||||
|
attempt.success_evidence_json = evidence
|
||||||
|
db.session.flush()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def request_manual_crane_refresh(
|
||||||
|
attempt: ShippingUploadAttempt,
|
||||||
|
upload_source: dict[str, Any],
|
||||||
|
*,
|
||||||
|
task_no: str,
|
||||||
|
export_file_path: str,
|
||||||
|
) -> str:
|
||||||
|
"""手动刷新:立刻写一条状态回查,不改定时回查的到期时间和已触发标记。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ConflictError: 当前不是分配中,或上一次手动刷新还没回调。
|
||||||
|
ValidationError: 共享目录写不出 trigger。
|
||||||
|
"""
|
||||||
|
if not is_crane_allocating(attempt):
|
||||||
|
raise ConflictError(
|
||||||
|
'Crane upload is not waiting for allocation',
|
||||||
|
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||||
|
)
|
||||||
|
evidence = _evidence(attempt)
|
||||||
|
if evidence.get('manual_refresh_inflight'):
|
||||||
|
raise ConflictError(
|
||||||
|
'A Crane status refresh is already queued',
|
||||||
|
code='SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT',
|
||||||
|
)
|
||||||
|
recheck = _recheck(evidence)
|
||||||
|
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||||
|
due_at = recheck.get('due_at')
|
||||||
|
fired = bool(recheck.get('fired'))
|
||||||
|
trigger_path = _write_status_check(
|
||||||
|
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||||
|
pull_request_no=pull_request_no, kind='manual',
|
||||||
|
)
|
||||||
|
if not trigger_path:
|
||||||
|
raise ValidationError(
|
||||||
|
'Crane status refresh trigger directory is unavailable',
|
||||||
|
code='SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE',
|
||||||
|
)
|
||||||
|
evidence['manual_refresh_inflight'] = True
|
||||||
|
evidence['crane_recheck'] = {**recheck, 'due_at': due_at, 'fired': fired, 'pull_request_no': pull_request_no}
|
||||||
|
attempt.success_evidence_json = evidence
|
||||||
|
db.session.flush()
|
||||||
|
return trigger_path
|
||||||
|
|
||||||
|
|
||||||
|
def materialize_due_crane_rechecks(now: datetime | None = None) -> int:
|
||||||
|
"""心跳时把已到期且尚未触发的 Crane 定时回查写成 trigger。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: 新写入的 trigger 数量。
|
||||||
|
"""
|
||||||
|
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||||
|
|
||||||
|
moment = now or datetime.utcnow()
|
||||||
|
written = 0
|
||||||
|
attempts = ShippingUploadAttempt.query.filter_by(status='running', error_code=CRANE_ALLOCATING_CODE).all()
|
||||||
|
for attempt in attempts:
|
||||||
|
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||||
|
notice = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None
|
||||||
|
if artifact is None or notice is None or not artifact.file_path:
|
||||||
|
continue
|
||||||
|
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||||
|
|
||||||
|
snapshot = task_rpa_inventory_source(notice) or {}
|
||||||
|
source_code = str(snapshot.get('source_code') or '').strip()
|
||||||
|
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
|
||||||
|
if not isinstance(upload_source, dict) or str(upload_source.get('connector_type') or '').lower() != 'crane':
|
||||||
|
continue
|
||||||
|
if fire_scheduled_crane_recheck(
|
||||||
|
attempt, upload_source, task_no=str(notice.task_no),
|
||||||
|
export_file_path=str(artifact.file_path), now=moment,
|
||||||
|
):
|
||||||
|
written += 1
|
||||||
|
if written:
|
||||||
|
db.session.commit()
|
||||||
|
return written
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""
|
||||||
|
services/freight_rpa/upload/page_contract.py
|
||||||
|
|
||||||
|
用途:货代发货 Excel 上传的平台页面契约。入口路径、文件控件和成功条件由代码固定。
|
||||||
|
依赖:标准库 urllib。
|
||||||
|
逻辑:系统连接只保存是否启用自动上传;Worker 用登录地址的主机拼出上传页。
|
||||||
|
DBS 上传后当页即可判定;Crane 先进入分配中,10 分钟后再查一次。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
CRANE_RECHECK_DELAY = timedelta(minutes=10)
|
||||||
|
DBS_UPLOAD_PATH = '/main/portal/frame/WMSUpload2'
|
||||||
|
CRANE_UPLOAD_HASH = '/#/shipping-order-upload'
|
||||||
|
|
||||||
|
|
||||||
|
def build_upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||||
|
"""按平台把登录地址的主机拼成上传页。
|
||||||
|
|
||||||
|
核心逻辑:页面路径属于连接器代码。管理端不再保存上传入口 URL。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
connector_type: dbs 或 crane。
|
||||||
|
login_url: 系统连接上的 HTTPS 登录地址。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 该平台固定上传页。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 连接类型或登录地址无法构成上传页。
|
||||||
|
"""
|
||||||
|
kind = str(connector_type or '').strip().lower()
|
||||||
|
parsed = urlsplit(str(login_url or '').strip())
|
||||||
|
host = parsed.netloc.strip()
|
||||||
|
if parsed.scheme.lower() != 'https' or not host or not parsed.hostname:
|
||||||
|
raise ValueError('login_url must be HTTPS with a host')
|
||||||
|
if kind == 'dbs':
|
||||||
|
return f'https://{host}{DBS_UPLOAD_PATH}'
|
||||||
|
if kind == 'crane':
|
||||||
|
return f'https://{host}{CRANE_UPLOAD_HASH}'
|
||||||
|
raise ValueError(f'unsupported connector_type: {connector_type or "<empty>"}')
|
||||||
|
|
||||||
|
|
||||||
|
def classify_crane_order_row(order_status: str, order_status_description: str) -> str:
|
||||||
|
"""判断 Crane 发货单行处于分配中、已分配,还是都不是。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
order_status: Order Status 列文本。
|
||||||
|
order_status_description: Order Status Description 列文本。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: allocated、allocating 或 other。
|
||||||
|
"""
|
||||||
|
status = ' '.join(str(order_status or '').split()).lower()
|
||||||
|
description = ' '.join(str(order_status_description or '').split()).lower()
|
||||||
|
if status == 'processing' and description == 'shipping order allocated':
|
||||||
|
return 'allocated'
|
||||||
|
if status == 'processing' and description == 'allocating the shipping order':
|
||||||
|
return 'allocating'
|
||||||
|
return 'other'
|
||||||
|
|
||||||
|
|
||||||
|
def crane_recheck_due_at(now: datetime | None = None) -> datetime:
|
||||||
|
"""自动上传进入分配中之后,唯一一次定时回查的到期时间。"""
|
||||||
|
return (now or datetime.utcnow()) + CRANE_RECHECK_DELAY
|
||||||
@@ -76,6 +76,7 @@ def write_upload_trigger(
|
|||||||
credential_envelope: dict[str, Any] | None = None,
|
credential_envelope: dict[str, Any] | None = None,
|
||||||
callback_id: str | None = None,
|
callback_id: str | None = None,
|
||||||
business_no: str | None = None,
|
business_no: str | None = None,
|
||||||
|
trigger_filename: str | None = None,
|
||||||
) -> tuple[str | None, str | None, str | None]:
|
) -> tuple[str | None, str | None, str | None]:
|
||||||
"""
|
"""
|
||||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||||
@@ -84,7 +85,7 @@ def write_upload_trigger(
|
|||||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||||
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
|
平台页面动作由 Worker 连接器代码固定;upload_config 只携带是否启用自动上传。
|
||||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -100,6 +101,7 @@ def write_upload_trigger(
|
|||||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||||
|
trigger_filename: 触发文件名。状态回查使用独立文件名,避免覆盖正在上传的 trigger。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||||
@@ -113,14 +115,21 @@ def write_upload_trigger(
|
|||||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
src = Path(export_file_path)
|
src = Path(export_file_path)
|
||||||
if not src.is_file():
|
status_check = str((payload or {}).get('mode') or '') == 'status_check'
|
||||||
|
if not src.is_file() and not status_check:
|
||||||
return None, None, None
|
return None, None, None
|
||||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||||
emit_no = str(business_no or '').strip() or task_no
|
emit_no = str(business_no or '').strip() or task_no
|
||||||
suffix = str(src.suffix or '.xlsx').lower()
|
suffix = str(src.suffix or '.xlsx').lower()
|
||||||
dest = queue / f"{emit_no}{suffix}"
|
dest = queue / f"{emit_no}{suffix}"
|
||||||
shutil.copy2(src, dest)
|
if src.is_file():
|
||||||
|
shutil.copy2(src, dest)
|
||||||
|
queued_file = str(dest)
|
||||||
|
elif status_check:
|
||||||
|
queued_file = ''
|
||||||
|
else:
|
||||||
|
return None, None, None
|
||||||
|
|
||||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||||
body = {
|
body = {
|
||||||
@@ -135,10 +144,10 @@ def write_upload_trigger(
|
|||||||
"upload_config_hash": upload_config_hash,
|
"upload_config_hash": upload_config_hash,
|
||||||
"login_url": login_url,
|
"login_url": login_url,
|
||||||
"credential_envelope": credential_envelope,
|
"credential_envelope": credential_envelope,
|
||||||
"file_path": str(dest),
|
"file_path": queued_file,
|
||||||
"requested_at": datetime.utcnow().isoformat(),
|
"requested_at": datetime.utcnow().isoformat(),
|
||||||
**(payload or {}),
|
**(payload or {}),
|
||||||
}
|
}
|
||||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
trigger_path = trigger_dir / (trigger_filename or f"upload_{task_no}.json")
|
||||||
_write_trigger_json_atomic(trigger_path, body)
|
_write_trigger_json_atomic(trigger_path, body)
|
||||||
return str(dest), str(trigger_path), resolved_callback_id
|
return str(dest), str(trigger_path), resolved_callback_id
|
||||||
@@ -36,6 +36,7 @@ from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLed
|
|||||||
from app.services.in_transit_transfer.matching_service import (
|
from app.services.in_transit_transfer.matching_service import (
|
||||||
circle_ledger_record_ids_scope_union,
|
circle_ledger_record_ids_scope_union,
|
||||||
pending_ledger_query,
|
pending_ledger_query,
|
||||||
|
ledger_external_doc_no,
|
||||||
transfer_type_code_of,
|
transfer_type_code_of,
|
||||||
)
|
)
|
||||||
from app.services.in_transit_transfer.status import TransferStatus
|
from app.services.in_transit_transfer.status import TransferStatus
|
||||||
@@ -100,6 +101,8 @@ class BacklogItemDTO:
|
|||||||
result_code: Optional[str] = None
|
result_code: Optional[str] = None
|
||||||
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
||||||
transfer_type: str = ""
|
transfer_type: str = ""
|
||||||
|
# 档上的外部单号。空串表示这行没有外部单号。
|
||||||
|
external_doc_no: str = ""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -207,7 +210,7 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
|
|||||||
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
|
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
|
||||||
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
|
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
|
||||||
|
|
||||||
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
|
keyword 与前端池内筛选同字段集(单号/外部单号/料号/品名/来源,2026-10-16 随
|
||||||
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -222,12 +225,19 @@ def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: st
|
|||||||
query = query.filter_by(source_code=source_code)
|
query = query.filter_by(source_code=source_code)
|
||||||
if keyword:
|
if keyword:
|
||||||
like = f"%{keyword}%"
|
like = f"%{keyword}%"
|
||||||
query = query.filter(or_(
|
query = (
|
||||||
TransferInvoiceItem.invoice_no.ilike(like),
|
query.outerjoin(
|
||||||
TransferInvoiceItem.material_no.ilike(like),
|
TransferMovementLedger,
|
||||||
TransferInvoiceItem.material_name.ilike(like),
|
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||||
TransferInvoiceItem.source_code.ilike(like),
|
)
|
||||||
))
|
.filter(or_(
|
||||||
|
TransferInvoiceItem.invoice_no.ilike(like),
|
||||||
|
TransferMovementLedger.external_doc_no.ilike(like),
|
||||||
|
TransferInvoiceItem.material_no.ilike(like),
|
||||||
|
TransferInvoiceItem.material_name.ilike(like),
|
||||||
|
TransferInvoiceItem.source_code.ilike(like),
|
||||||
|
))
|
||||||
|
)
|
||||||
return query
|
return query
|
||||||
|
|
||||||
|
|
||||||
@@ -266,6 +276,7 @@ def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[Ba
|
|||||||
item_id=item.id,
|
item_id=item.id,
|
||||||
source_code=item.source_code,
|
source_code=item.source_code,
|
||||||
invoice_no=item.invoice_no,
|
invoice_no=item.invoice_no,
|
||||||
|
external_doc_no=ledger_external_doc_no(item),
|
||||||
material_no=item.material_no,
|
material_no=item.material_no,
|
||||||
status=item.status,
|
status=item.status,
|
||||||
reason=item.result_message or item.result_code or "",
|
reason=item.result_message or item.result_code or "",
|
||||||
@@ -303,7 +314,10 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
|||||||
current = now or datetime.utcnow()
|
current = now or datetime.utcnow()
|
||||||
rows = (
|
rows = (
|
||||||
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
||||||
.options(joinedload(TransferInvoiceItem.matching))
|
.options(
|
||||||
|
joinedload(TransferInvoiceItem.matching),
|
||||||
|
joinedload(TransferInvoiceItem.ledger_record),
|
||||||
|
)
|
||||||
.order_by(*_BACKLOG_ORDER_BY)
|
.order_by(*_BACKLOG_ORDER_BY)
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
@@ -330,7 +344,7 @@ def list_backlog_page(
|
|||||||
Args:
|
Args:
|
||||||
now: 判定时刻(默认当前时间)。
|
now: 判定时刻(默认当前时间)。
|
||||||
source_code: 可选来源过滤。
|
source_code: 可选来源过滤。
|
||||||
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
|
keyword: 可选关键字(单号/外部单号/料号/品名/来源,子串大小写不敏感)。
|
||||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||||
page: 页码(1 起)。
|
page: 页码(1 起)。
|
||||||
page_size: 每页行数(1..100)。
|
page_size: 每页行数(1..100)。
|
||||||
@@ -345,7 +359,10 @@ def list_backlog_page(
|
|||||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||||
total = base.count()
|
total = base.count()
|
||||||
rows = (
|
rows = (
|
||||||
base.options(joinedload(TransferInvoiceItem.matching))
|
base.options(
|
||||||
|
joinedload(TransferInvoiceItem.matching),
|
||||||
|
joinedload(TransferInvoiceItem.ledger_record),
|
||||||
|
)
|
||||||
.order_by(*_BACKLOG_ORDER_BY)
|
.order_by(*_BACKLOG_ORDER_BY)
|
||||||
.offset((page - 1) * page_size)
|
.offset((page - 1) * page_size)
|
||||||
.limit(page_size)
|
.limit(page_size)
|
||||||
|
|||||||
@@ -124,6 +124,8 @@ class MatchingItemDTO:
|
|||||||
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||||
# 无匹配或快照未写类型时为空串。
|
# 无匹配或快照未写类型时为空串。
|
||||||
transfer_type: str = ""
|
transfer_type: str = ""
|
||||||
|
# 档上的外部单号(WMS Order #)。空串表示这行没有外部单号。
|
||||||
|
external_doc_no: str = ""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ from app.services.in_transit_transfer.matching_service import (
|
|||||||
RouteMapping,
|
RouteMapping,
|
||||||
TransferDeps,
|
TransferDeps,
|
||||||
item_external_lot_no,
|
item_external_lot_no,
|
||||||
|
ledger_external_doc_no,
|
||||||
)
|
)
|
||||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||||
from app.services.in_transit_transfer.orchestrator import (
|
from app.services.in_transit_transfer.orchestrator import (
|
||||||
@@ -805,12 +806,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
|||||||
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
|
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
|
||||||
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
|
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
|
||||||
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
|
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
|
||||||
行内附带 invoice_no 溯源(逗号连接,供测试替身/排障;ERP 契约无此字段,
|
行内附带 invoice_no 与 external_doc_no 溯源(各自逗号连接,供清单展示与排障;
|
||||||
真实绑定未映射即透传为惰性键)。
|
ERP 契约无这两字段,真实绑定未映射即透传为惰性键)。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
|
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
|
||||||
quantity/unit/invoice_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
quantity/unit/invoice_no/external_doc_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||||
"""
|
"""
|
||||||
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
||||||
for item in items:
|
for item in items:
|
||||||
@@ -831,6 +832,9 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
|||||||
quantity = total.quantize(_QUANTITY_QUANT)
|
quantity = total.quantize(_QUANTITY_QUANT)
|
||||||
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
|
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
|
||||||
invoices = ",".join(sorted({item.invoice_no for item in group}))
|
invoices = ",".join(sorted({item.invoice_no for item in group}))
|
||||||
|
external_docs = ",".join(sorted({
|
||||||
|
doc for item in group if (doc := ledger_external_doc_no(item))
|
||||||
|
}))
|
||||||
lines.append({
|
lines.append({
|
||||||
"line_no": index,
|
"line_no": index,
|
||||||
"material_no": key[0],
|
"material_no": key[0],
|
||||||
@@ -840,6 +844,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
|||||||
"quantity": float(quantity),
|
"quantity": float(quantity),
|
||||||
"unit": unit,
|
"unit": unit,
|
||||||
"invoice_no": invoices,
|
"invoice_no": invoices,
|
||||||
|
"external_doc_no": external_docs,
|
||||||
"quantity_text": f"{quantity:.6f}",
|
"quantity_text": f"{quantity:.6f}",
|
||||||
})
|
})
|
||||||
return lines
|
return lines
|
||||||
@@ -1273,6 +1278,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
|||||||
material_name=item.material_name,
|
material_name=item.material_name,
|
||||||
specification=item.specification,
|
specification=item.specification,
|
||||||
invoice_no=item.invoice_no,
|
invoice_no=item.invoice_no,
|
||||||
|
external_doc_no=ledger_external_doc_no(item),
|
||||||
movement_date=item.movement_date,
|
movement_date=item.movement_date,
|
||||||
from_warehouse=item.from_warehouse,
|
from_warehouse=item.from_warehouse,
|
||||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
|
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
|
||||||
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
|
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
|
||||||
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
|
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
|
||||||
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
取消匹配即释放;ADR 0007 匹配顶替在圈档前取消被新范围盖住、尚未写 ERP 的旧匹配)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||||
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
|
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
|
||||||
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
|
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
|
||||||
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
|
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
|
||||||
@@ -295,11 +295,12 @@ def _dedupe_ledger_records_for_item_birth(
|
|||||||
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||||
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
|
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
|
||||||
|
|
||||||
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
|
占用定义(规格 §9 + grain 互斥 + ADR 0007):存在已挂上匹配的有效 item
|
||||||
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
|
(所属匹配未取消,或该行是人工关闭;行非 blocked_file_removed)且满足其一
|
||||||
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
|
——(a) ledger_record_id 直指本档;(b) 与本档同匹配 grain
|
||||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
|
(source/invoice=doc_no/material/movement_date)。没有挂上匹配的明细不占用。
|
||||||
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
|
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档。取消匹配即释放,
|
||||||
|
人工关闭除外;成功终态不释放。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
|
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
|
||||||
@@ -308,9 +309,8 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
|||||||
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
|
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
|
||||||
"""
|
"""
|
||||||
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
|
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
|
||||||
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
|
# 【ADR 0007】没有挂上匹配的明细不占货(直指与 grain 都不算)。
|
||||||
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
|
# 人工关闭在所属匹配被顶替之后仍然占用。
|
||||||
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
|
|
||||||
grain_match = and_(
|
grain_match = and_(
|
||||||
TransferInvoiceItem.matching_id.isnot(None),
|
TransferInvoiceItem.matching_id.isnot(None),
|
||||||
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
|
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
|
||||||
@@ -328,17 +328,21 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
|||||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||||
]
|
]
|
||||||
if exclude_matching_id is None:
|
if exclude_matching_id is None:
|
||||||
# 匹配创建:任何未取消匹配(含无归属的历史行)的有效引用都算占用。
|
# 匹配创建:必须已挂上匹配。未取消的匹配占用;人工关闭在匹配被顶替后仍占用。
|
||||||
|
item_conditions.append(TransferInvoiceItem.matching_id.isnot(None))
|
||||||
item_conditions.append(or_(
|
item_conditions.append(or_(
|
||||||
TransferInvoiceItem.matching_id.is_(None),
|
|
||||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||||
|
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||||
))
|
))
|
||||||
else:
|
else:
|
||||||
# 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。
|
# 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。
|
||||||
item_conditions.append(and_(
|
item_conditions.append(and_(
|
||||||
TransferInvoiceItem.matching_id.isnot(None),
|
TransferInvoiceItem.matching_id.isnot(None),
|
||||||
TransferInvoiceItem.matching_id != exclude_matching_id,
|
TransferInvoiceItem.matching_id != exclude_matching_id,
|
||||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
or_(
|
||||||
|
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||||
|
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||||
|
),
|
||||||
))
|
))
|
||||||
occupancy = (
|
occupancy = (
|
||||||
db.session.query(TransferInvoiceItem.id)
|
db.session.query(TransferInvoiceItem.id)
|
||||||
@@ -611,6 +615,23 @@ def matching_transform_rules(matching: TransferMatching) -> tuple[TransformRule,
|
|||||||
return parse_transform_rules(scope.get("transform_rules"))
|
return parse_transform_rules(scope.get("transform_rules"))
|
||||||
|
|
||||||
|
|
||||||
|
def ledger_external_doc_no(item: TransferInvoiceItem) -> str:
|
||||||
|
"""读取明细行对应异动档上的外部单号。
|
||||||
|
|
||||||
|
核心逻辑:外部单号只在档上(WMS Order #),明细行经 ledger_record_id 指向档。
|
||||||
|
没有档、或档上为空时返回空串,列表显示占位。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
item: 明细行。ledger_record 可已预加载;未预加载时按外键懒加载。
|
||||||
|
Returns:
|
||||||
|
外部单号;没有则空串。
|
||||||
|
"""
|
||||||
|
record = item.ledger_record
|
||||||
|
if record is None:
|
||||||
|
return ""
|
||||||
|
return str(record.external_doc_no or "").strip()
|
||||||
|
|
||||||
|
|
||||||
def item_external_lot_no(item: TransferInvoiceItem) -> str:
|
def item_external_lot_no(item: TransferInvoiceItem) -> str:
|
||||||
"""行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。
|
"""行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。
|
||||||
|
|
||||||
@@ -1242,6 +1263,116 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
|||||||
return lines[0].get("file_sha256")
|
return lines[0].get("file_sha256")
|
||||||
|
|
||||||
|
|
||||||
|
def _source_set(codes: list[str] | None) -> tuple[str, ...]:
|
||||||
|
"""把来源编码收成可比较的集合。
|
||||||
|
|
||||||
|
核心逻辑:去掉空白后排序,使 [B, A] 与 [A, B] 视为同一组来源。
|
||||||
|
Args:
|
||||||
|
codes: 来源编码列表;None 当空。
|
||||||
|
Returns:
|
||||||
|
排序后的来源编码元组。
|
||||||
|
"""
|
||||||
|
return tuple(sorted(str(code).strip() for code in (codes or []) if str(code).strip()))
|
||||||
|
|
||||||
|
|
||||||
|
def _date_range_covers(new_from: str | None, new_to: str | None, old_from: str | None, old_to: str | None) -> bool:
|
||||||
|
"""新异动日期范围是否把旧范围整个盖住。
|
||||||
|
|
||||||
|
核心逻辑:任一侧缺少起或止,都视为没盖住(无日期范围的旧匹配不被顶替)。
|
||||||
|
日期是 YYYY-MM-DD,字符串序与日历序一致。
|
||||||
|
Args:
|
||||||
|
new_from / new_to: 本次匹配的异动日期起止。
|
||||||
|
old_from / old_to: 旧匹配快照上的异动日期起止。
|
||||||
|
Returns:
|
||||||
|
新范围包含旧范围时为 True。
|
||||||
|
"""
|
||||||
|
if not new_from or not new_to or not old_from or not old_to:
|
||||||
|
return False
|
||||||
|
return str(new_from) <= str(old_from) and str(new_to) >= str(old_to)
|
||||||
|
|
||||||
|
|
||||||
|
def _matching_has_erp_activity(items: list[TransferInvoiceItem]) -> bool:
|
||||||
|
"""匹配是否已经写出单据,或有行正在写、结果未知。
|
||||||
|
|
||||||
|
核心逻辑:有外部单号,或行状态为执行中、结果未知、成功,就不顶替,
|
||||||
|
避免把在途 ERP 写入拆成两张单。
|
||||||
|
Args:
|
||||||
|
items: 该匹配名下的明细。
|
||||||
|
Returns:
|
||||||
|
存在上述活动时为 True。
|
||||||
|
"""
|
||||||
|
active = {
|
||||||
|
status_machine.TransferStatus.EXECUTING.value,
|
||||||
|
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||||
|
status_machine.TransferStatus.SUCCESS.value,
|
||||||
|
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||||
|
}
|
||||||
|
return any(
|
||||||
|
(item.external_document_no or "").strip() or item.status in active
|
||||||
|
for item in items
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _supersede_covered_matchings(
|
||||||
|
*,
|
||||||
|
transfer_type: str,
|
||||||
|
source_codes: list[str],
|
||||||
|
movement_date_from: str | None,
|
||||||
|
movement_date_to: str | None,
|
||||||
|
exclude_matching_id: int,
|
||||||
|
) -> None:
|
||||||
|
"""圈档前顶替被新范围盖住、尚未写 ERP 的旧匹配(ADR 0007)。
|
||||||
|
|
||||||
|
核心逻辑:同一调拨类型、同一组来源、旧日期范围被新范围整个盖住,且名下没有
|
||||||
|
ERP 单据、没有正在写或结果未知的行,则匹配改为 cancelled,名下明细一并取消。
|
||||||
|
盖不住或已在写 ERP 的旧匹配保持原样,清单不列举它们的编号。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
transfer_type: 本次匹配的调拨类型编码。
|
||||||
|
source_codes: 本次来源集合。
|
||||||
|
movement_date_from / movement_date_to: 本次异动日期范围;缺一则不顶替任何人。
|
||||||
|
exclude_matching_id: 刚落库、尚未圈档的本次匹配,不能把自己顶掉。
|
||||||
|
"""
|
||||||
|
new_sources = _source_set(source_codes)
|
||||||
|
if not new_sources:
|
||||||
|
return
|
||||||
|
candidates = (
|
||||||
|
TransferMatching.query
|
||||||
|
.filter(TransferMatching.id != exclude_matching_id)
|
||||||
|
.filter(TransferMatching.status != _MATCHING_STATUS_CANCELLED)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for matching in candidates:
|
||||||
|
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||||
|
if str(scope.get("transfer_type") or "") != transfer_type:
|
||||||
|
continue
|
||||||
|
if _source_set(scope.get("source_codes")) != new_sources:
|
||||||
|
continue
|
||||||
|
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||||
|
covered = _date_range_covers(
|
||||||
|
movement_date_from,
|
||||||
|
movement_date_to,
|
||||||
|
scope.get("movement_date_from"),
|
||||||
|
scope.get("movement_date_to"),
|
||||||
|
)
|
||||||
|
# 匹配状态 success 只表示没有可执行行(全阻断也会落成 success),
|
||||||
|
# 不能当成已经写出 ERP。是否写过只看行上的单据号和执行状态。
|
||||||
|
if (
|
||||||
|
not covered
|
||||||
|
or matching.status == status_machine.TransferStatus.EXECUTING.value
|
||||||
|
or _matching_has_erp_activity(items)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
matching.status = _MATCHING_STATUS_CANCELLED
|
||||||
|
for item in items:
|
||||||
|
# 人工关闭是仓库人员的裁定,顶替不把它改回可圈状态。
|
||||||
|
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
|
||||||
|
continue
|
||||||
|
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||||
|
item.result_code = "cancelled"
|
||||||
|
item.result_message = "superseded by a new matching"
|
||||||
|
|
||||||
|
|
||||||
def create_matching(
|
def create_matching(
|
||||||
*,
|
*,
|
||||||
source_codes: list[str],
|
source_codes: list[str],
|
||||||
@@ -1259,6 +1390,7 @@ def create_matching(
|
|||||||
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
|
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
|
||||||
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
|
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
|
||||||
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
|
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
|
||||||
|
【ADR 0007】圈档前顶替被本次日期范围盖住、尚未写 ERP 的同类型同来源旧匹配。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
source_codes / business_date / deps: 同 run_matching。
|
source_codes / business_date / deps: 同 run_matching。
|
||||||
@@ -1299,6 +1431,14 @@ def create_matching(
|
|||||||
)
|
)
|
||||||
db.session.add(matching)
|
db.session.add(matching)
|
||||||
db.session.flush()
|
db.session.flush()
|
||||||
|
# [ADR 0007] 先释放被盖住的旧匹配,本次圈档才能看到那批货。
|
||||||
|
_supersede_covered_matchings(
|
||||||
|
transfer_type=config.code,
|
||||||
|
source_codes=list(source_codes),
|
||||||
|
movement_date_from=movement_date_from,
|
||||||
|
movement_date_to=movement_date_to,
|
||||||
|
exclude_matching_id=matching.id,
|
||||||
|
)
|
||||||
|
|
||||||
result = run_matching(
|
result = run_matching(
|
||||||
source_codes=source_codes,
|
source_codes=source_codes,
|
||||||
@@ -1404,6 +1544,7 @@ def restore_matching(
|
|||||||
# 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。
|
# 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。
|
||||||
rows_all = (
|
rows_all = (
|
||||||
TransferInvoiceItem.query
|
TransferInvoiceItem.query
|
||||||
|
.options(joinedload(TransferInvoiceItem.ledger_record))
|
||||||
.filter(TransferInvoiceItem.matching_id == matching.id)
|
.filter(TransferInvoiceItem.matching_id == matching.id)
|
||||||
.order_by(
|
.order_by(
|
||||||
TransferInvoiceItem.movement_date.asc().nulls_last(),
|
TransferInvoiceItem.movement_date.asc().nulls_last(),
|
||||||
@@ -1531,6 +1672,7 @@ def _item_dto(
|
|||||||
material_name=item.material_name,
|
material_name=item.material_name,
|
||||||
specification=item.specification,
|
specification=item.specification,
|
||||||
invoice_no=item.invoice_no,
|
invoice_no=item.invoice_no,
|
||||||
|
external_doc_no=ledger_external_doc_no(item),
|
||||||
movement_date=item.movement_date,
|
movement_date=item.movement_date,
|
||||||
lot_no=item.lot_no or "",
|
lot_no=item.lot_no or "",
|
||||||
movement_warehouse_code=item.movement_warehouse_code or "",
|
movement_warehouse_code=item.movement_warehouse_code or "",
|
||||||
@@ -1600,7 +1742,10 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
|||||||
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
||||||
rows = (
|
rows = (
|
||||||
TransferInvoiceItem.query
|
TransferInvoiceItem.query
|
||||||
.options(joinedload(TransferInvoiceItem.matching))
|
.options(
|
||||||
|
joinedload(TransferInvoiceItem.matching),
|
||||||
|
joinedload(TransferInvoiceItem.ledger_record),
|
||||||
|
)
|
||||||
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
|
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
|
||||||
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
|
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
|
||||||
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
|
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from app.services.in_transit_transfer.matching_service import item_external_lot_no
|
from app.services.in_transit_transfer.matching_service import (
|
||||||
|
item_external_lot_no,
|
||||||
|
ledger_external_doc_no,
|
||||||
|
)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||||
@@ -71,6 +74,7 @@ def serialize_item(item) -> dict[str, Any]:
|
|||||||
"material_name": item.material_name,
|
"material_name": item.material_name,
|
||||||
"specification": item.specification,
|
"specification": item.specification,
|
||||||
"invoice_no": item.invoice_no,
|
"invoice_no": item.invoice_no,
|
||||||
|
"external_doc_no": getattr(item, "external_doc_no", "") or "",
|
||||||
"lot_no": item.lot_no,
|
"lot_no": item.lot_no,
|
||||||
"movement_date": item.movement_date,
|
"movement_date": item.movement_date,
|
||||||
"from_warehouse": item.from_warehouse,
|
"from_warehouse": item.from_warehouse,
|
||||||
@@ -177,6 +181,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
|||||||
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||||
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
||||||
"invoice_no": line["invoice_no"],
|
"invoice_no": line["invoice_no"],
|
||||||
|
"external_doc_no": line.get("external_doc_no") or "",
|
||||||
"material_no": line["material_no"],
|
"material_no": line["material_no"],
|
||||||
"material_name": name_by_key.get(
|
"material_name": name_by_key.get(
|
||||||
(line["material_no"], line["lot_no"],
|
(line["material_no"], line["lot_no"],
|
||||||
@@ -222,6 +227,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
|||||||
"items": [
|
"items": [
|
||||||
{
|
{
|
||||||
"invoice_no": item.invoice_no,
|
"invoice_no": item.invoice_no,
|
||||||
|
"external_doc_no": ledger_external_doc_no(item),
|
||||||
"material_no": item.material_no,
|
"material_no": item.material_no,
|
||||||
"material_name": item.material_name,
|
"material_name": item.material_name,
|
||||||
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
||||||
|
|||||||
@@ -4,10 +4,11 @@
|
|||||||
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
||||||
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
||||||
调拨不维护独立抓取状态表(低耦合)。
|
调拨不维护独立抓取状态表(低耦合)。
|
||||||
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
|
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
|
||||||
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
|
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
|
||||||
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
|
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
|
||||||
入站可用条件同口径)。
|
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
|
||||||
|
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
|
||||||
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
||||||
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
||||||
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
||||||
@@ -28,10 +29,9 @@ from typing import Any, Callable
|
|||||||
from sqlalchemy import and_, not_, or_
|
from sqlalchemy import and_, not_, or_
|
||||||
|
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
from app.models.freight_rpa_inbound_report import (
|
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
|
||||||
FreightRpaInboundReportFile,
|
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
|
||||||
FreightRpaInboundUnitRun,
|
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
|
||||||
)
|
|
||||||
from app.models.freight_rpa_outbound_report import (
|
from app.models.freight_rpa_outbound_report import (
|
||||||
FreightRpaOutboundReportConfig,
|
FreightRpaOutboundReportConfig,
|
||||||
FreightRpaOutboundReportFile,
|
FreightRpaOutboundReportFile,
|
||||||
@@ -39,12 +39,12 @@ from app.models.freight_rpa_outbound_report import (
|
|||||||
)
|
)
|
||||||
from app.services.freight_rpa.reports.queries import (
|
from app.services.freight_rpa.reports.queries import (
|
||||||
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
||||||
expired_inbound_file_condition,
|
expired_inbound_source_codes,
|
||||||
get_outbound_config,
|
get_outbound_config,
|
||||||
has_expired_inbound_file,
|
has_expired_inbound_file,
|
||||||
latest_usable_inbound_file,
|
latest_usable_inbound_file,
|
||||||
|
latest_usable_inbound_files_by_source,
|
||||||
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
||||||
usable_inbound_file_condition,
|
|
||||||
)
|
)
|
||||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||||
|
|
||||||
@@ -288,13 +288,13 @@ def _project_file_status(
|
|||||||
|
|
||||||
|
|
||||||
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
||||||
"""一次取出这批来源各自最新的可用归档。
|
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
|
||||||
|
|
||||||
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
||||||
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
file_model: 入站或出站归档文件模型。
|
file_model: 出站归档文件模型。
|
||||||
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
||||||
source_ids: 要投影的来源主键。
|
source_ids: 要投影的来源主键。
|
||||||
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
||||||
@@ -359,13 +359,13 @@ def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str,
|
|||||||
|
|
||||||
|
|
||||||
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
||||||
"""一次找出仍有失效未清理归档的来源编码。
|
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
|
||||||
|
|
||||||
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
||||||
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
file_model: 入站或出站归档文件模型。
|
file_model: 出站归档文件模型。
|
||||||
unit_model: 对应的执行单元模型。
|
unit_model: 对应的执行单元模型。
|
||||||
source_ids: 要投影的来源主键。
|
source_ids: 要投影的来源主键。
|
||||||
filters: 失效文件条件。
|
filters: 失效文件条件。
|
||||||
@@ -412,19 +412,17 @@ def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict
|
|||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
inbound_files = _latest_files_by_source(
|
inbound_files = {
|
||||||
FreightRpaInboundReportFile,
|
code: _FileFact(
|
||||||
FreightRpaInboundUnitRun,
|
file_id=view.file_id,
|
||||||
source_ids,
|
original_filename=view.original_filename,
|
||||||
usable_inbound_file_condition(now=now),
|
sha256=view.sha256,
|
||||||
)
|
parse_failed_at=view.parse_failed_at,
|
||||||
|
)
|
||||||
|
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
|
||||||
|
}
|
||||||
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
||||||
inbound_expired = _expired_source_codes(
|
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
|
||||||
FreightRpaInboundReportFile,
|
|
||||||
FreightRpaInboundUnitRun,
|
|
||||||
source_ids,
|
|
||||||
expired_inbound_file_condition(now=now),
|
|
||||||
)
|
|
||||||
outbound_files = _latest_files_by_source(
|
outbound_files = _latest_files_by_source(
|
||||||
FreightRpaOutboundReportFile,
|
FreightRpaOutboundReportFile,
|
||||||
FreightRpaOutboundUnitRun,
|
FreightRpaOutboundUnitRun,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ backend/app/services/integrations/wecom/notify.py
|
|||||||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||||||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||||||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||||||
|
文本卡片标题默认加上「AI智能体」来源;密码重置和权限变更保持原标题。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -24,6 +25,17 @@ _TOKEN_CACHE = {
|
|||||||
'expires_at': None,
|
'expires_at': None,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 企微 textcard 没有发送者栏,用来源前缀让收件人看出是 AI 智能体推送。
|
||||||
|
_AGENT_SOURCE_PREFIX = 'AI智能体 · '
|
||||||
|
_TEXT_CARD_TITLE_LIMIT = 120
|
||||||
|
# 账号与权限通知不是智能体推送,标题不加来源。
|
||||||
|
_NO_AGENT_SOURCE_EVENTS = frozenset({
|
||||||
|
'password_reset',
|
||||||
|
'permission_batch_updated',
|
||||||
|
'permission_request_approved',
|
||||||
|
'permission_request_rejected',
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
def _get_enabled_events() -> set[str]:
|
def _get_enabled_events() -> set[str]:
|
||||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||||
@@ -141,19 +153,54 @@ def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
|||||||
return resp.json()
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
|
def _with_agent_source_title(title: str, *, enabled: bool = True) -> str:
|
||||||
|
"""
|
||||||
|
给企微 textcard 标题加上「AI智能体」来源,并限制在 120 字以内。
|
||||||
|
|
||||||
|
核心逻辑:前缀放在最前,超长时截断业务标题,避免来源被切掉。
|
||||||
|
已带相同前缀时不重复添加。enabled 为 False 时只做长度截断。
|
||||||
|
Args:
|
||||||
|
title: 业务侧传入的卡片标题。
|
||||||
|
enabled: 为 False 时保持原标题,用于密码重置和权限变更。
|
||||||
|
Returns:
|
||||||
|
实际发给企业微信的标题。
|
||||||
|
"""
|
||||||
|
text = (title or '').strip()
|
||||||
|
if not enabled:
|
||||||
|
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||||
|
if text.startswith(_AGENT_SOURCE_PREFIX):
|
||||||
|
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||||
|
return f'{_AGENT_SOURCE_PREFIX}{text}'[:_TEXT_CARD_TITLE_LIMIT]
|
||||||
|
|
||||||
|
|
||||||
def send_wecom_textcard_message(
|
def send_wecom_textcard_message(
|
||||||
wecom_userid: str,
|
wecom_userid: str,
|
||||||
title: str,
|
title: str,
|
||||||
description: str,
|
description: str,
|
||||||
jump_url: str,
|
jump_url: str,
|
||||||
|
*,
|
||||||
|
with_agent_source: bool = True,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
|
"""
|
||||||
|
发送企业微信文本卡片。
|
||||||
|
|
||||||
|
核心逻辑:默认在标题前加上「AI智能体」来源。审计记录仍保存调用方传入的业务标题。
|
||||||
|
Args:
|
||||||
|
wecom_userid: 企业微信 userid。
|
||||||
|
title: 业务标题。
|
||||||
|
description: 卡片正文。
|
||||||
|
jump_url: 点击跳转地址。
|
||||||
|
with_agent_source: 为 False 时标题不加来源。
|
||||||
|
Returns:
|
||||||
|
企业微信 message/send 的 JSON 响应。
|
||||||
|
"""
|
||||||
token = _get_access_token()
|
token = _get_access_token()
|
||||||
payload = {
|
payload = {
|
||||||
'touser': wecom_userid,
|
'touser': wecom_userid,
|
||||||
'msgtype': 'textcard',
|
'msgtype': 'textcard',
|
||||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||||
'textcard': {
|
'textcard': {
|
||||||
'title': title[:120],
|
'title': _with_agent_source_title(title, enabled=with_agent_source),
|
||||||
'description': (description or '')[:1024],
|
'description': (description or '')[:1024],
|
||||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||||
'btntxt': '查看详情',
|
'btntxt': '查看详情',
|
||||||
@@ -200,6 +247,7 @@ def send_wecom_event_message(
|
|||||||
|
|
||||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||||
|
标题在发送时加上「AI智能体」来源;密码重置和权限变更不加。审计 title 保持业务标题。
|
||||||
Args:
|
Args:
|
||||||
event_type: 通知事件开关名。
|
event_type: 通知事件开关名。
|
||||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||||
@@ -239,7 +287,13 @@ def send_wecom_event_message(
|
|||||||
else:
|
else:
|
||||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||||
audit.jump_url = final_jump_url
|
audit.jump_url = final_jump_url
|
||||||
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
data = send_wecom_textcard_message(
|
||||||
|
target_userid,
|
||||||
|
title,
|
||||||
|
content,
|
||||||
|
final_jump_url,
|
||||||
|
with_agent_source=event_type not in _NO_AGENT_SOURCE_EVENTS,
|
||||||
|
)
|
||||||
if data.get('errcode') == 0:
|
if data.get('errcode') == 0:
|
||||||
audit.status = 'sent'
|
audit.status = 'sent'
|
||||||
return {'ok': True, 'trace_id': trace_id}
|
return {'ok': True, 'trace_id': trace_id}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ backend/app/services/lean_training_service.py
|
|||||||
|
|
||||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;学员端"本期视频"口径为本任务首次推送的
|
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;受训角色按用户已挂的全部权限组匹配。
|
||||||
视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
学员端「本期视频」口径为本任务首次推送的视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
||||||
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -23,10 +23,12 @@ from app.models import (
|
|||||||
Agent,
|
Agent,
|
||||||
LeanTrainingCompletion,
|
LeanTrainingCompletion,
|
||||||
LeanTrainingWeeklyTask,
|
LeanTrainingWeeklyTask,
|
||||||
|
PermissionRole,
|
||||||
TrainingConfig,
|
TrainingConfig,
|
||||||
TrainingConfigResource,
|
TrainingConfigResource,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
|
from app.models.permission_role import user_permission_roles
|
||||||
from app.services.integrations.minio import minio_service
|
from app.services.integrations.minio import minio_service
|
||||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||||
|
|
||||||
@@ -252,20 +254,38 @@ def _normalize_target_user_ids(value: Any) -> list[int]:
|
|||||||
|
|
||||||
|
|
||||||
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
||||||
"""返回周任务的在职受训对象,角色和用户指定对象按并集处理。"""
|
"""返回周任务的在职受训对象。指定用户,以及主角色或任一已挂角色命中的人,按并集处理。"""
|
||||||
predicates = []
|
predicates = []
|
||||||
if task.target_user_ids:
|
if task.target_user_ids:
|
||||||
predicates.append(User.id.in_(list(task.target_user_ids)))
|
predicates.append(User.id.in_(list(task.target_user_ids)))
|
||||||
if task.target_roles:
|
if task.target_roles:
|
||||||
predicates.append(User.role.in_(list(task.target_roles)))
|
role_codes = list(task.target_roles)
|
||||||
|
member_ids = (
|
||||||
|
select(user_permission_roles.c.user_id)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.where(PermissionRole.code.in_(role_codes))
|
||||||
|
)
|
||||||
|
predicates.append(or_(User.role.in_(role_codes), User.id.in_(member_ids)))
|
||||||
if not predicates:
|
if not predicates:
|
||||||
return set()
|
return set()
|
||||||
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
||||||
|
|
||||||
|
|
||||||
def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
||||||
"""判断员工是否属于周任务对象,角色匹配或显式指定任一成立即可学习。"""
|
"""判断员工是否属于周任务对象。任一已挂角色命中,或显式指定用户,即可学习。"""
|
||||||
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
if user.status != "active":
|
||||||
|
return False
|
||||||
|
if user.id in set(task.target_user_ids or []):
|
||||||
|
return True
|
||||||
|
codes = set(task.target_roles or [])
|
||||||
|
if not codes:
|
||||||
|
return False
|
||||||
|
from app.services.permission_roles.service import list_assigned_roles, roles_configured
|
||||||
|
|
||||||
|
assigned = {str(user.role or "")}
|
||||||
|
if roles_configured():
|
||||||
|
assigned.update(role.code for role in list_assigned_roles(user))
|
||||||
|
return bool(assigned & codes)
|
||||||
|
|
||||||
|
|
||||||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
services/permission_roles/service.py
|
services/permission_roles/service.py
|
||||||
|
|
||||||
用途:权限组 CRUD、成员预览/确认调整、把角色包同步到 users.role 与 user_agent_permissions。
|
用途:权限组 CRUD、成员预览/确认调整、把多个角色包的并集同步到用户授权。
|
||||||
依赖:PermissionRole、User、Agent、catalog。
|
依赖:PermissionRole、user_permission_roles、User、Agent、catalog。
|
||||||
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
||||||
|
一个用户可挂多个业务角色,应用入口与能力取并集;平台管理员不与其他角色叠加。
|
||||||
|
拿掉最后一个业务角色时回到默认权限组。users.role 只记主角色。
|
||||||
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
||||||
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
||||||
"""
|
"""
|
||||||
@@ -14,12 +16,13 @@ import re
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from sqlalchemy import delete, insert, select
|
||||||
from sqlalchemy.orm import joinedload
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User
|
||||||
from app.models.permission_role import PermissionRole
|
from app.models.permission_role import PermissionRole, user_permission_roles
|
||||||
from app.services.permission_roles.catalog import (
|
from app.services.permission_roles.catalog import (
|
||||||
FEATURE_CATALOG,
|
FEATURE_CATALOG,
|
||||||
KNOWN_FEATURE_KEYS,
|
KNOWN_FEATURE_KEYS,
|
||||||
@@ -75,6 +78,187 @@ def list_role_name_map() -> dict[str, str]:
|
|||||||
return {row.code: row.name for row in rows}
|
return {row.code: row.name for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def list_assigned_roles(user: User, sess: Any | None = None) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
读取用户已挂的权限组。
|
||||||
|
|
||||||
|
核心逻辑:有成员表行时以成员表为准;还没回填时回退 users.role,兼容只写 role 的旧数据和测试。
|
||||||
|
"""
|
||||||
|
session = _orm_session(sess)
|
||||||
|
if user is None or getattr(user, 'id', None) is None or not _permission_roles_exist(session):
|
||||||
|
return []
|
||||||
|
linked = (
|
||||||
|
session.query(PermissionRole)
|
||||||
|
.join(user_permission_roles, user_permission_roles.c.role_id == PermissionRole.id)
|
||||||
|
.filter(user_permission_roles.c.user_id == user.id)
|
||||||
|
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
if linked:
|
||||||
|
return linked
|
||||||
|
code = str(getattr(user, 'role', '') or '').strip()
|
||||||
|
if not code:
|
||||||
|
return []
|
||||||
|
fallback = session.query(PermissionRole).filter(PermissionRole.code == code).one_or_none()
|
||||||
|
return [fallback] if fallback else []
|
||||||
|
|
||||||
|
|
||||||
|
def roles_by_user_ids(user_ids: list[int]) -> dict[int, list[PermissionRole]]:
|
||||||
|
"""批量读取成员关系,避免用户列表逐人查询。"""
|
||||||
|
if not user_ids or not roles_configured():
|
||||||
|
return {}
|
||||||
|
rows = (
|
||||||
|
db.session.query(user_permission_roles.c.user_id, PermissionRole)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.filter(user_permission_roles.c.user_id.in_(user_ids))
|
||||||
|
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
grouped: dict[int, list[PermissionRole]] = {}
|
||||||
|
for user_id, role in rows:
|
||||||
|
grouped.setdefault(int(user_id), []).append(role)
|
||||||
|
return grouped
|
||||||
|
|
||||||
|
|
||||||
|
def _primary_role(roles: list[PermissionRole]) -> PermissionRole | None:
|
||||||
|
"""主角色:平台管理员优先,否则取非默认角色里排序最前的一个。"""
|
||||||
|
if not roles:
|
||||||
|
return None
|
||||||
|
admins = [role for role in roles if role.is_platform_admin]
|
||||||
|
pool = admins or [role for role in roles if not role.is_default] or roles
|
||||||
|
return sorted(pool, key=lambda role: (role.sort_order, role.id or 0))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _role_label(roles: list[PermissionRole], role_names: dict[str, str], fallback: str) -> str:
|
||||||
|
"""多个角色显示名用顿号拼接;没有成员行时回退主角色名。"""
|
||||||
|
if roles:
|
||||||
|
return '、'.join(role.name for role in roles)
|
||||||
|
return role_names.get(fallback) or fallback
|
||||||
|
|
||||||
|
|
||||||
|
def describe_user_roles(
|
||||||
|
user: User,
|
||||||
|
assigned: list[PermissionRole] | None = None,
|
||||||
|
role_names: dict[str, str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
用户当前的主角色与全部角色。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
assigned: 已批量查出的角色;None 时再查成员表。空列表表示调用方确认没有成员行。
|
||||||
|
"""
|
||||||
|
names = role_names if role_names is not None else list_role_name_map()
|
||||||
|
if assigned is None and roles_configured():
|
||||||
|
roles = list_assigned_roles(user)
|
||||||
|
else:
|
||||||
|
roles = list(assigned or [])
|
||||||
|
primary = _primary_role(roles)
|
||||||
|
fallback = str(user.role or '')
|
||||||
|
return {
|
||||||
|
'role': primary.code if primary else fallback,
|
||||||
|
'role_name': _role_label(roles, names, fallback),
|
||||||
|
'role_codes': [role.code for role in roles] or ([fallback] if fallback else []),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def role_auth_payload(user: User) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
登录态里的角色展示。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
role_name: 全部角色名,顿号拼接。
|
||||||
|
role_codes: 全部角色 code;未配置权限组时只有 users.role。
|
||||||
|
"""
|
||||||
|
described = describe_user_roles(user)
|
||||||
|
return {
|
||||||
|
'role_name': described['role_name'],
|
||||||
|
'role_codes': described['role_codes'],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _has_membership_rows(user: User) -> bool:
|
||||||
|
"""该用户是否已有成员表行。"""
|
||||||
|
if user.id is None:
|
||||||
|
return False
|
||||||
|
found = db.session.execute(
|
||||||
|
select(user_permission_roles.c.user_id)
|
||||||
|
.where(user_permission_roles.c.user_id == user.id)
|
||||||
|
.limit(1)
|
||||||
|
).first()
|
||||||
|
return found is not None
|
||||||
|
|
||||||
|
|
||||||
|
def replace_user_roles(user: User, roles: list[PermissionRole]) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
用给定权限组替换成员关系,并回写 users.role 主角色。
|
||||||
|
|
||||||
|
核心逻辑:出现平台管理员时只保留该角色。空列表回落到默认权限组。
|
||||||
|
"""
|
||||||
|
if user.id is None:
|
||||||
|
db.session.flush()
|
||||||
|
unique: list[PermissionRole] = []
|
||||||
|
seen: set[int] = set()
|
||||||
|
for role in roles:
|
||||||
|
if role is None or role.id in seen:
|
||||||
|
continue
|
||||||
|
seen.add(role.id)
|
||||||
|
unique.append(role)
|
||||||
|
admins = [role for role in unique if role.is_platform_admin]
|
||||||
|
if admins:
|
||||||
|
unique = [sorted(admins, key=lambda role: (role.sort_order, role.id or 0))[0]]
|
||||||
|
elif not unique:
|
||||||
|
default = get_default_role()
|
||||||
|
unique = [default] if default else []
|
||||||
|
db.session.execute(
|
||||||
|
delete(user_permission_roles).where(user_permission_roles.c.user_id == user.id)
|
||||||
|
)
|
||||||
|
if unique:
|
||||||
|
db.session.execute(
|
||||||
|
insert(user_permission_roles),
|
||||||
|
[{'user_id': user.id, 'role_id': role.id} for role in unique],
|
||||||
|
)
|
||||||
|
primary = _primary_role(unique)
|
||||||
|
user.role = primary.code if primary else default_role_code()
|
||||||
|
user._is_platform_admin_cached = None
|
||||||
|
db.session.flush()
|
||||||
|
return unique
|
||||||
|
|
||||||
|
|
||||||
|
def roles_after_grant(current: list[PermissionRole], incoming: PermissionRole) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
追加一个角色后的成员集合。
|
||||||
|
|
||||||
|
核心逻辑:业务角色会拿掉默认角色,避免「普通用户」人数把已有专属角色的人再计一次;
|
||||||
|
其他业务角色保留。追加默认角色时不拿掉已有业务角色。平台管理员独占。
|
||||||
|
"""
|
||||||
|
if incoming.is_platform_admin:
|
||||||
|
return [incoming]
|
||||||
|
if incoming.is_default:
|
||||||
|
if any(role.id == incoming.id for role in current):
|
||||||
|
return list(current)
|
||||||
|
return [*current, incoming]
|
||||||
|
kept = [
|
||||||
|
role for role in current
|
||||||
|
if not role.is_default and not role.is_platform_admin and role.id != incoming.id
|
||||||
|
]
|
||||||
|
return [*kept, incoming]
|
||||||
|
|
||||||
|
|
||||||
|
def roles_after_revoke(current: list[PermissionRole], incoming: PermissionRole) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
移出一个角色后的成员集合。
|
||||||
|
|
||||||
|
核心逻辑:还剩别的角色就只移出这一个。一个都不剩时回到默认权限组。
|
||||||
|
默认角色是唯一角色时保持不变。
|
||||||
|
"""
|
||||||
|
kept = [role for role in current if role.id != incoming.id]
|
||||||
|
if not kept:
|
||||||
|
default = get_default_role()
|
||||||
|
if default is not None:
|
||||||
|
return [default]
|
||||||
|
return kept
|
||||||
|
|
||||||
|
|
||||||
def _orm_session(sess: Any | None):
|
def _orm_session(sess: Any | None):
|
||||||
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
||||||
return sess if sess is not None else db.session
|
return sess if sess is not None else db.session
|
||||||
@@ -158,7 +342,7 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
|||||||
"""
|
"""
|
||||||
判断用户是否属于 is_platform_admin 权限组。
|
判断用户是否属于 is_platform_admin 权限组。
|
||||||
|
|
||||||
核心逻辑:已种子时按 users.role join permission_roles;否则回退 role=admin。
|
核心逻辑:已种子时看全部已挂角色里是否有平台管理组;否则回退 role=admin。
|
||||||
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -172,22 +356,20 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
|||||||
return False
|
return False
|
||||||
session = _orm_session(sess)
|
session = _orm_session(sess)
|
||||||
role_code = str(getattr(user, 'role', '') or '').strip()
|
role_code = str(getattr(user, 'role', '') or '').strip()
|
||||||
|
assigned = list_assigned_roles(user, session) if _permission_roles_exist(session) else []
|
||||||
|
cache_key = (role_code, tuple(role.code for role in assigned))
|
||||||
cached = getattr(user, '_is_platform_admin_cached', None)
|
cached = getattr(user, '_is_platform_admin_cached', None)
|
||||||
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == role_code:
|
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == cache_key:
|
||||||
return bool(cached[1])
|
return bool(cached[1])
|
||||||
if not role_code:
|
if assigned:
|
||||||
user._is_platform_admin_cached = (role_code, False)
|
result = any(role.is_platform_admin for role in assigned)
|
||||||
return False
|
elif not role_code:
|
||||||
if _permission_roles_exist(session):
|
result = False
|
||||||
role = (
|
elif _permission_roles_exist(session):
|
||||||
session.query(PermissionRole)
|
result = False
|
||||||
.filter(PermissionRole.code == role_code)
|
|
||||||
.one_or_none()
|
|
||||||
)
|
|
||||||
result = bool(role and role.is_platform_admin)
|
|
||||||
else:
|
else:
|
||||||
result = role_code == PLATFORM_ADMIN_CODE
|
result = role_code == PLATFORM_ADMIN_CODE
|
||||||
user._is_platform_admin_cached = (role_code, result)
|
user._is_platform_admin_cached = (cache_key, result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -211,46 +393,92 @@ def _normalize_feature_map(raw: Any) -> dict[str, bool]:
|
|||||||
|
|
||||||
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
||||||
"""
|
"""
|
||||||
若已配置权限组,返回该用户角色包的有效功能权限;否则 None 表示走 User 旧默认值。
|
若已配置权限组,返回该用户全部角色的有效功能权限;否则 None 表示走 User 旧默认值。
|
||||||
|
|
||||||
|
核心逻辑:任一业务角色打开的能力即生效。平台管理员仍默认全开,再用该组上的显式值覆盖。
|
||||||
"""
|
"""
|
||||||
if not roles_configured():
|
if not roles_configured():
|
||||||
return None
|
return None
|
||||||
role = get_role_by_code(user.role)
|
roles = list_assigned_roles(user)
|
||||||
stored = _normalize_feature_map(role.feature_permissions if role else {})
|
admin = next((role for role in roles if role.is_platform_admin), None)
|
||||||
if role and role.is_platform_admin:
|
if admin is not None:
|
||||||
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
||||||
result.update(stored)
|
result.update(_normalize_feature_map(admin.feature_permissions))
|
||||||
return result
|
return result
|
||||||
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
||||||
result.update(stored)
|
for role in roles:
|
||||||
|
for key, enabled in _normalize_feature_map(role.feature_permissions).items():
|
||||||
|
if enabled:
|
||||||
|
result[key] = True
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def sync_user_grants_from_role(user: User) -> None:
|
def sync_user_grants_from_role(user: User) -> None:
|
||||||
"""
|
"""
|
||||||
按用户当前 role 重写 Agent 授权与个人功能覆盖。
|
按用户已挂的全部角色重算 Agent 授权与个人功能覆盖。
|
||||||
|
|
||||||
核心逻辑:管理员不写 user_agent_permissions(入口隐式全开);
|
核心逻辑:还没有成员行时先按 users.role 写入一行。管理员不写 user_agent_permissions(入口隐式全开);
|
||||||
其他角色用权限组勾选的 Agent 全量替换;个人 feature_permissions 清空,改由角色包计算。
|
其他角色把各权限组勾选的 Agent 取并集。个人 feature_permissions 清空,改由角色包计算。
|
||||||
未配置权限组时不改。
|
未配置权限组时不改。
|
||||||
"""
|
"""
|
||||||
if not roles_configured():
|
if not roles_configured():
|
||||||
return
|
return
|
||||||
role = get_role_by_code(user.role)
|
if user.id is None:
|
||||||
if role is None:
|
db.session.flush()
|
||||||
|
roles = list_assigned_roles(user)
|
||||||
|
if not roles:
|
||||||
fallback = get_default_role()
|
fallback = get_default_role()
|
||||||
if fallback is None:
|
if fallback is None:
|
||||||
return
|
return
|
||||||
user.role = fallback.code
|
roles = [fallback]
|
||||||
role = fallback
|
if not _has_membership_rows(user):
|
||||||
|
roles = replace_user_roles(user, roles)
|
||||||
|
admins = [role for role in roles if role.is_platform_admin]
|
||||||
user.feature_permissions = {}
|
user.feature_permissions = {}
|
||||||
if role.is_platform_admin:
|
user._is_platform_admin_cached = None
|
||||||
|
if admins:
|
||||||
|
if len(roles) != 1:
|
||||||
|
replace_user_roles(user, [admins[0]])
|
||||||
return
|
return
|
||||||
user.agents = list(role.agents)
|
primary = _primary_role(roles)
|
||||||
|
if primary is not None and user.role != primary.code:
|
||||||
|
user.role = primary.code
|
||||||
|
seen: dict[int, Agent] = {}
|
||||||
|
for role in roles:
|
||||||
|
for agent in role.agents:
|
||||||
|
seen[agent.id] = agent
|
||||||
|
user.agents = list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _users_for_role(role: PermissionRole, *, active_only: bool = False) -> list[User]:
|
||||||
|
"""
|
||||||
|
某权限组的成员。
|
||||||
|
|
||||||
|
核心逻辑:成员表里挂了该角色的人,加上尚未回填、users.role 仍等于该 code 的人。
|
||||||
|
"""
|
||||||
|
linked_ids = select(user_permission_roles.c.user_id).where(
|
||||||
|
user_permission_roles.c.role_id == role.id
|
||||||
|
)
|
||||||
|
any_membership = select(user_permission_roles.c.user_id)
|
||||||
|
linked = db.session.query(User).filter(User.id.in_(linked_ids))
|
||||||
|
unlinked = db.session.query(User).filter(
|
||||||
|
User.role == role.code,
|
||||||
|
~User.id.in_(any_membership),
|
||||||
|
)
|
||||||
|
if active_only:
|
||||||
|
linked = linked.filter(User.status == 'active')
|
||||||
|
unlinked = unlinked.filter(User.status == 'active')
|
||||||
|
found: dict[int, User] = {}
|
||||||
|
for user in [*linked.all(), *unlinked.all()]:
|
||||||
|
found[user.id] = user
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
def _count_members(code: str) -> int:
|
def _count_members(code: str) -> int:
|
||||||
return db.session.query(User).filter(User.role == code).count()
|
role = get_role_by_code(code)
|
||||||
|
if role is None:
|
||||||
|
return db.session.query(User).filter(User.role == code).count()
|
||||||
|
return len(_users_for_role(role))
|
||||||
|
|
||||||
|
|
||||||
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
||||||
@@ -437,9 +665,9 @@ def create_role(data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
保存权限组。仅当应用勾选或能力开关变化时,才同步该组用户的应用授权。
|
保存权限组。仅当应用勾选或能力开关变化时,才按并集重算该组用户的应用授权。
|
||||||
|
|
||||||
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。
|
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。其他人身上的其他角色保留。
|
||||||
"""
|
"""
|
||||||
role = get_role_by_code(code)
|
role = get_role_by_code(code)
|
||||||
if not role:
|
if not role:
|
||||||
@@ -447,7 +675,7 @@ def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
allow_agents = not role.is_platform_admin
|
allow_agents = not role.is_platform_admin
|
||||||
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
||||||
_apply_package(role, data, allow_agents=allow_agents)
|
_apply_package(role, data, allow_agents=allow_agents)
|
||||||
users = db.session.query(User).filter(User.role == role.code).all() if grants_changed else []
|
users = _users_for_role(role) if grants_changed else []
|
||||||
for user in users:
|
for user in users:
|
||||||
sync_user_grants_from_role(user)
|
sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -470,28 +698,67 @@ def delete_role(code: str) -> dict[str, Any]:
|
|||||||
return {'status': 'ok'}
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
def _person_payload(user: User, role_names: dict[str, str]) -> dict[str, Any]:
|
def _person_payload(
|
||||||
|
user: User,
|
||||||
|
role_names: dict[str, str],
|
||||||
|
assigned: list[PermissionRole] | None = None,
|
||||||
|
*,
|
||||||
|
retained_role_names: list[str] | None = None,
|
||||||
|
returns_to_default: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""选人与确认框共用的人员行。role 是主角色,role_codes 是全部角色。"""
|
||||||
|
roles = list_assigned_roles(user) if assigned is None else assigned
|
||||||
|
primary = _primary_role(roles)
|
||||||
|
fallback = str(user.role or '')
|
||||||
return {
|
return {
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
'username': user.username,
|
'username': user.username,
|
||||||
'real_name': user.real_name,
|
'real_name': user.real_name,
|
||||||
'employee_id': user.employee_id,
|
'employee_id': user.employee_id,
|
||||||
'department': user.department,
|
'department': user.department,
|
||||||
'role': user.role,
|
'role': primary.code if primary else fallback,
|
||||||
'role_name': role_names.get(user.role) or user.role,
|
'role_name': _role_label(roles, role_names, fallback),
|
||||||
|
'role_codes': [role.code for role in roles] or ([fallback] if fallback else []),
|
||||||
|
'retained_role_names': list(retained_role_names or []),
|
||||||
|
'returns_to_default': returns_to_default,
|
||||||
'wecom_bound': bool(user.wecom_userid),
|
'wecom_bound': bool(user.wecom_userid),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def assign_role_codes(user: User, codes: list[str]) -> None:
|
||||||
|
"""
|
||||||
|
按 code 列表替换该用户的全部角色并重算授权。
|
||||||
|
|
||||||
|
核心逻辑:空列表回落到默认权限组。平台管理员 code 会清掉其他角色。
|
||||||
|
"""
|
||||||
|
roles: list[PermissionRole] = []
|
||||||
|
for code in codes:
|
||||||
|
role = get_role_by_code(code)
|
||||||
|
if role is not None:
|
||||||
|
roles.append(role)
|
||||||
|
replace_user_roles(user, roles)
|
||||||
|
sync_user_grants_from_role(user)
|
||||||
|
|
||||||
|
|
||||||
def list_picker_people() -> list[dict[str, Any]]:
|
def list_picker_people() -> list[dict[str, Any]]:
|
||||||
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
||||||
role_names = list_role_name_map()
|
role_names = list_role_name_map()
|
||||||
query = db.session.query(User).filter(User.status == 'active')
|
query = db.session.query(User).filter(User.status == 'active')
|
||||||
admin_codes = platform_admin_role_codes()
|
admin_codes = platform_admin_role_codes()
|
||||||
if admin_codes:
|
if admin_codes:
|
||||||
query = query.filter(User.role.notin_(admin_codes))
|
admin_ids = (
|
||||||
|
select(user_permission_roles.c.user_id)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.where(PermissionRole.is_platform_admin.is_(True))
|
||||||
|
)
|
||||||
|
query = query.filter(User.role.notin_(admin_codes), ~User.id.in_(admin_ids))
|
||||||
users = query.order_by(User.id.asc()).all()
|
users = query.order_by(User.id.asc()).all()
|
||||||
return [_person_payload(user, role_names) for user in users]
|
assigned = roles_by_user_ids([user.id for user in users])
|
||||||
|
payloads = []
|
||||||
|
for user in users:
|
||||||
|
roles = assigned.get(user.id) or list_assigned_roles(user)
|
||||||
|
payloads.append(_person_payload(user, role_names, roles))
|
||||||
|
return payloads
|
||||||
|
|
||||||
|
|
||||||
def _normalize_selected_ids(raw: Any) -> list[int]:
|
def _normalize_selected_ids(raw: Any) -> list[int]:
|
||||||
@@ -511,7 +778,10 @@ def _normalize_selected_ids(raw: Any) -> list[int]:
|
|||||||
|
|
||||||
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
计算勾选草稿相对当前成员的增减,供确认框展示来源角色。
|
计算勾选草稿相对当前成员的增减。
|
||||||
|
|
||||||
|
核心逻辑:加入是追加本角色,不拿走其他业务角色。移出只拿掉本角色;
|
||||||
|
一个业务角色都不剩时回到默认权限组。默认角色若已是唯一角色,取消勾选不算变更。
|
||||||
"""
|
"""
|
||||||
role = get_role_by_code(code)
|
role = get_role_by_code(code)
|
||||||
if not role:
|
if not role:
|
||||||
@@ -520,35 +790,59 @@ def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
|||||||
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
||||||
default_code = default_role_code()
|
default_code = default_role_code()
|
||||||
selected = set(_normalize_selected_ids(selected_ids))
|
selected = set(_normalize_selected_ids(selected_ids))
|
||||||
current_members = (
|
current_members = _users_for_role(role, active_only=True)
|
||||||
db.session.query(User)
|
|
||||||
.filter(User.role == role.code)
|
|
||||||
.filter(User.status == 'active')
|
|
||||||
.all()
|
|
||||||
)
|
|
||||||
current_ids = {user.id for user in current_members}
|
current_ids = {user.id for user in current_members}
|
||||||
added_ids = [item for item in selected if item not in current_ids]
|
added_ids = [item for item in selected if item not in current_ids]
|
||||||
removed_ids = [item for item in current_ids if item not in selected]
|
removed_ids = [item for item in current_ids if item not in selected]
|
||||||
if role.code == default_code:
|
|
||||||
removed_ids = []
|
|
||||||
users_by_id = {
|
users_by_id = {
|
||||||
user.id: user
|
user.id: user
|
||||||
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
||||||
} if added_ids or removed_ids else {}
|
} if added_ids or removed_ids else {}
|
||||||
role_names = list_role_name_map()
|
role_names = list_role_name_map()
|
||||||
|
assigned_map = roles_by_user_ids(added_ids + removed_ids)
|
||||||
|
|
||||||
def _rows(ids: list[int]) -> list[dict[str, Any]]:
|
def _assigned(person: User) -> list[PermissionRole]:
|
||||||
rows = []
|
rows = assigned_map.get(person.id)
|
||||||
for user_id in ids:
|
if rows:
|
||||||
user = users_by_id.get(user_id)
|
return rows
|
||||||
if not user or user_is_platform_admin(user):
|
return list_assigned_roles(person)
|
||||||
continue
|
|
||||||
rows.append(_person_payload(user, role_names))
|
|
||||||
return rows
|
|
||||||
|
|
||||||
added = _rows(added_ids)
|
added = []
|
||||||
removed = _rows(removed_ids)
|
for user_id in added_ids:
|
||||||
stolen = [row for row in added if row['role'] not in {default_code, role.code}]
|
user = users_by_id.get(user_id)
|
||||||
|
if not user or user_is_platform_admin(user):
|
||||||
|
continue
|
||||||
|
current = _assigned(user)
|
||||||
|
nxt = roles_after_grant(current, role)
|
||||||
|
if role.is_default:
|
||||||
|
retained = [item.name for item in nxt if item.id != role.id]
|
||||||
|
else:
|
||||||
|
retained = [item.name for item in nxt if item.id != role.id and not item.is_default]
|
||||||
|
added.append(_person_payload(
|
||||||
|
user,
|
||||||
|
role_names,
|
||||||
|
current,
|
||||||
|
retained_role_names=retained,
|
||||||
|
))
|
||||||
|
removed = []
|
||||||
|
for user_id in removed_ids:
|
||||||
|
user = users_by_id.get(user_id)
|
||||||
|
if not user or user_is_platform_admin(user):
|
||||||
|
continue
|
||||||
|
current = _assigned(user)
|
||||||
|
nxt = roles_after_revoke(current, role)
|
||||||
|
if {item.id for item in nxt} == {item.id for item in current}:
|
||||||
|
continue
|
||||||
|
returns = bool(nxt) and all(item.is_default for item in nxt)
|
||||||
|
retained = [] if returns else [item.name for item in nxt]
|
||||||
|
removed.append(_person_payload(
|
||||||
|
user,
|
||||||
|
role_names,
|
||||||
|
current,
|
||||||
|
retained_role_names=retained,
|
||||||
|
returns_to_default=returns,
|
||||||
|
))
|
||||||
|
stolen = [row for row in added if row['retained_role_names']]
|
||||||
return {
|
return {
|
||||||
'role_code': role.code,
|
'role_code': role.code,
|
||||||
'role_name': role.name,
|
'role_name': role.name,
|
||||||
@@ -562,26 +856,28 @@ def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
|||||||
|
|
||||||
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
确认后写回成员:勾选的人改入本角色;取消勾选的人回到默认角色。
|
确认后写回成员:勾选的人追加本角色;取消勾选的人只移出本角色。
|
||||||
排除管理员;默认角色忽略移出。
|
|
||||||
|
核心逻辑:其他业务角色保留。移出后没有任何角色时回到默认权限组。排除管理员。
|
||||||
"""
|
"""
|
||||||
preview = preview_role_members(code, selected_ids)
|
preview = preview_role_members(code, selected_ids)
|
||||||
role = get_role_by_code(code)
|
role = get_role_by_code(code)
|
||||||
default_code = preview['default_role_code']
|
|
||||||
skipped_admin = 0
|
skipped_admin = 0
|
||||||
for row in preview['added']:
|
for row in preview['added']:
|
||||||
user = db.session.get(User, row['id'])
|
user = db.session.get(User, row['id'])
|
||||||
if not user or user_is_platform_admin(user):
|
if not user or user_is_platform_admin(user):
|
||||||
skipped_admin += 1
|
skipped_admin += 1
|
||||||
continue
|
continue
|
||||||
user.role = role.code
|
current = list_assigned_roles(user)
|
||||||
|
replace_user_roles(user, roles_after_grant(current, role))
|
||||||
sync_user_grants_from_role(user)
|
sync_user_grants_from_role(user)
|
||||||
for row in preview['removed']:
|
for row in preview['removed']:
|
||||||
user = db.session.get(User, row['id'])
|
user = db.session.get(User, row['id'])
|
||||||
if not user or user_is_platform_admin(user):
|
if not user or user_is_platform_admin(user):
|
||||||
skipped_admin += 1
|
skipped_admin += 1
|
||||||
continue
|
continue
|
||||||
user.role = default_code
|
current = list_assigned_roles(user)
|
||||||
|
replace_user_roles(user, roles_after_revoke(current, role))
|
||||||
sync_user_grants_from_role(user)
|
sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {
|
return {
|
||||||
@@ -614,13 +910,24 @@ def assert_role_assignable(code: str | None, *, allow_admin: bool) -> str:
|
|||||||
|
|
||||||
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
||||||
"""禁止撤掉最后一名启用中的平台管理员。"""
|
"""禁止撤掉最后一名启用中的平台管理员。"""
|
||||||
|
ensure_role_codes_keep_admin(user, [new_role])
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_role_codes_keep_admin(user: User, codes: list[str]) -> None:
|
||||||
|
"""
|
||||||
|
禁止把最后一名启用中的平台管理员改成不含管理组的角色集合。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
codes: 即将写入的角色 code。空列表视为卸下管理身份。
|
||||||
|
"""
|
||||||
if not user_is_platform_admin(user):
|
if not user_is_platform_admin(user):
|
||||||
return
|
return
|
||||||
incoming = get_role_by_code(new_role)
|
for code in codes:
|
||||||
if incoming and incoming.is_platform_admin:
|
incoming = get_role_by_code(code) if roles_configured() else None
|
||||||
return
|
if incoming and incoming.is_platform_admin:
|
||||||
if not roles_configured() and new_role == PLATFORM_ADMIN_CODE:
|
return
|
||||||
return
|
if not roles_configured() and str(code or '') == PLATFORM_ADMIN_CODE:
|
||||||
|
return
|
||||||
others = platform_admin_users_query().filter(User.id != user.id).first()
|
others = platform_admin_users_query().filter(User.id != user.id).first()
|
||||||
if others is None:
|
if others is None:
|
||||||
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
||||||
|
|||||||
@@ -2,18 +2,24 @@
|
|||||||
|
|
||||||
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
|
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
|
||||||
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
||||||
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
|
依赖:auto_transfer、recovery_service、transfer deps、job_registry.ScheduleExecuteResult、
|
||||||
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
|
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
|
||||||
|
transfer_type_config_service.get_enabled(缺省类型口径)、
|
||||||
date_policy(业务日与日期解析)。
|
date_policy(业务日与日期解析)。
|
||||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
|
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
|
||||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
|
不依赖其他排程成功;来源留空兜底为全部启用入站来源;【调拨类型 2026-10-23】
|
||||||
|
job_params.transfer_types 为 multi_select,留空=全部启用中的类型配置,
|
||||||
|
按类型逐轮 run_auto_transfer(恢复复核与类型无关,循环外只跑一次);
|
||||||
|
类型配置为空/读取失败 fail-closed 硬失败,不静默跳过;可选异动日期范围
|
||||||
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
|
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
|
||||||
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
|
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
|
||||||
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
|
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
|
||||||
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
|
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
|
||||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
|
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(全部
|
||||||
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
|
类型均无 run_no 且无 errors)置 domain_notification_managed 保持静默
|
||||||
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||||
|
返回:七元组位序=(total, success, failed, skipped, details, errors, step_logs),
|
||||||
|
warnings 无对应槽位——恢复/来源汇总写 step_logs(dict),不得挤占 errors 位。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -21,11 +27,13 @@ from __future__ import annotations
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.errors import AppError
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
from app.services.in_transit_transfer import deps as transfer_deps
|
from app.services.in_transit_transfer import deps as transfer_deps
|
||||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
|
||||||
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
||||||
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
||||||
|
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
|
||||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||||
|
|
||||||
|
|
||||||
@@ -52,6 +60,33 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
|||||||
return codes
|
return codes
|
||||||
|
|
||||||
|
|
||||||
|
def _wanted_transfer_types(params: dict[str, Any], errors: list[str]) -> list[str]:
|
||||||
|
"""提取结构化 transfer_types;留空回落为全部启用中的类型配置(fail-closed)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
params: 排程结构化参数(job_params.transfer_types 可为列表/字符串/缺省)。
|
||||||
|
errors: 错误累积列表(类型配置读取失败/为空时写入,由调用方硬失败)。
|
||||||
|
Returns:
|
||||||
|
去空白后的类型编码列表;配置为空或脏配置读取失败时为空列表(已落错误)。
|
||||||
|
"""
|
||||||
|
values = params.get("transfer_types") or []
|
||||||
|
if isinstance(values, str):
|
||||||
|
values = [values]
|
||||||
|
codes = [str(item).strip() for item in values if str(item).strip()]
|
||||||
|
if codes:
|
||||||
|
return codes
|
||||||
|
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||||
|
|
||||||
|
try:
|
||||||
|
codes = [dto.code for dto in get_enabled()]
|
||||||
|
except AppError as exc:
|
||||||
|
errors.append(f"调拨类型配置读取失败: {exc}")
|
||||||
|
return []
|
||||||
|
if not codes:
|
||||||
|
errors.append("无启用中的调拨类型配置(须先在管理端调拨类型页创建并启用)")
|
||||||
|
return codes
|
||||||
|
|
||||||
|
|
||||||
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
||||||
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
|
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
|
||||||
|
|
||||||
@@ -77,12 +112,14 @@ def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: li
|
|||||||
|
|
||||||
|
|
||||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
|
"""自动调拨:恢复(一次)→ 按类型逐轮「匹配(严格相等)+ 执行」;通知走排程「启用通知」。
|
||||||
|
|
||||||
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
|
核心逻辑:不自建领域汇总通知(收件人取排程表单底部「启用通知」配置);
|
||||||
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
|
仅在空数据日(全部类型均无 run_no 且无 errors)置 domain_notification_managed
|
||||||
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
|
抑制框架完成卡(C5 空数据日静默);有 run_no 或硬失败时框架卡照常发送/兜底。
|
||||||
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
|
调拨类型留空=全部启用类型逐轮执行(D8:类型=平台配置,排程不隐式假设单一
|
||||||
|
类型;配置为空/读取失败 fail-closed 硬失败);历史恢复与类型无关,循环外
|
||||||
|
只跑一次(重复恢复会对同一批行重复建 Attempt 并重复外部查询)。
|
||||||
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
||||||
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
||||||
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
|
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
|
||||||
@@ -90,7 +127,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
|||||||
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
|
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
task: 排程任务(job_params: source_codes/recover_history/
|
task: 排程任务(job_params: transfer_types/source_codes/recover_history/
|
||||||
receipt_from_offset_days/receipt_to_offset_days)。
|
receipt_from_offset_days/receipt_to_offset_days)。
|
||||||
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -101,60 +138,99 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
|||||||
recover_history = bool(params.get("recover_history", True))
|
recover_history = bool(params.get("recover_history", True))
|
||||||
business_date = str(business_date_now())
|
business_date = str(business_date_now())
|
||||||
|
|
||||||
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
# [STEP 1] 配置解析与 T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||||
# 防止坏参数被静默忽略后退化成全量积压处理。
|
# 防止坏参数被静默忽略后退化成全量积压处理。硬失败以 failed_count=1 落终态
|
||||||
param_errors: list[str] = []
|
# failed(total=0 且 errors 非空会被框架判 success「无待处理数据」,不可用)。
|
||||||
|
errors: list[str] = []
|
||||||
|
transfer_types = _wanted_transfer_types(params, errors)
|
||||||
movement_date_from = _offset_to_date(
|
movement_date_from = _offset_to_date(
|
||||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
|
business_date, params.get("receipt_from_offset_days"), "异动日期起点", errors)
|
||||||
movement_date_to = _offset_to_date(
|
movement_date_to = _offset_to_date(
|
||||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
|
business_date, params.get("receipt_to_offset_days"), "异动日期终点", errors)
|
||||||
if param_errors:
|
if errors:
|
||||||
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
return (1, 0, 1, 0, [], errors, [
|
||||||
|
{"step": "config", "status": "failed", "detail": f"sources={len(source_codes)}"},
|
||||||
|
])
|
||||||
|
|
||||||
deps = transfer_deps.get_transfer_dependencies()
|
deps = transfer_deps.get_transfer_dependencies()
|
||||||
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
|
|
||||||
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
|
|
||||||
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
|
|
||||||
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
|
|
||||||
transfer_type = str(params.get("transfer_type") or "").strip() or None
|
|
||||||
outcome = run_auto_transfer(
|
|
||||||
business_date=business_date,
|
|
||||||
deps=deps,
|
|
||||||
source_codes=source_codes,
|
|
||||||
recover_history=recover_history,
|
|
||||||
movement_date_from=movement_date_from,
|
|
||||||
movement_date_to=movement_date_to,
|
|
||||||
transfer_type=transfer_type,
|
|
||||||
)
|
|
||||||
|
|
||||||
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
# [STEP 2] 恢复复核只跑一次:扫全部 blocked_recoverable 行(与类型无关),
|
||||||
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
# result_unknown / manually_closed 在服务内只读隔离/永久排除。恢复失败计一个
|
||||||
if not outcome.run_no and not outcome.errors:
|
# failed 单元——否则「恢复失败+各类型均空数据日」total=0 会被框架判 success。
|
||||||
|
recovery = RecoveryOutcome()
|
||||||
|
recovery_failed = False
|
||||||
|
if recover_history:
|
||||||
|
try:
|
||||||
|
recovery = run_daily_recovery(business_date=business_date, deps=deps)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
recovery_failed = True
|
||||||
|
errors.append(f"recovery_failed: {exc}")
|
||||||
|
step_logs: list[dict[str, Any]] = [{
|
||||||
|
"step": "recovery",
|
||||||
|
"status": "failed" if recovery_failed else ("success" if recover_history else "skipped"),
|
||||||
|
"detail": {
|
||||||
|
"recovered": recovery.recovered_count,
|
||||||
|
"still_blocked": recovery.still_blocked_count,
|
||||||
|
"skipped_result_unknown": recovery.skipped_result_unknown,
|
||||||
|
"skipped_manually_closed": recovery.skipped_manually_closed,
|
||||||
|
},
|
||||||
|
}]
|
||||||
|
failed_units = 1 if recovery_failed else 0
|
||||||
|
|
||||||
|
# [STEP 3] 按类型逐轮自动调拨:单类型失败不阻断其余类型(run_auto_transfer
|
||||||
|
# 内部捕获进 outcome.errors)。
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
success_runs = 0
|
||||||
|
failed_runs = 0
|
||||||
|
for code in transfer_types:
|
||||||
|
outcome = run_auto_transfer(
|
||||||
|
business_date=business_date,
|
||||||
|
deps=deps,
|
||||||
|
source_codes=source_codes,
|
||||||
|
recover_history=False,
|
||||||
|
movement_date_from=movement_date_from,
|
||||||
|
movement_date_to=movement_date_to,
|
||||||
|
transfer_type=code,
|
||||||
|
)
|
||||||
|
errors.extend(outcome.errors)
|
||||||
|
if outcome.run_no:
|
||||||
|
results.append({
|
||||||
|
"transfer_type": code,
|
||||||
|
"run_no": outcome.run_no,
|
||||||
|
"status": outcome.run_status,
|
||||||
|
})
|
||||||
|
if outcome.run_status in {"success", "partial_failed"}:
|
||||||
|
success_runs += 1
|
||||||
|
else:
|
||||||
|
failed_runs += 1
|
||||||
|
elif outcome.errors:
|
||||||
|
failed_runs += 1
|
||||||
|
|
||||||
|
# [STEP 4] 空数据日静默门禁:全部类型均无 run 且无错误(C5)时置标记抑制
|
||||||
|
# 框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||||
|
if not results and not errors:
|
||||||
run.response_summary_json = {
|
run.response_summary_json = {
|
||||||
**(run.response_summary_json or {}),
|
**(run.response_summary_json or {}),
|
||||||
"domain_notification_managed": True,
|
"domain_notification_managed": True,
|
||||||
}
|
}
|
||||||
results: list[dict[str, Any]] = []
|
step_logs.append({
|
||||||
errors: list[str] = list(outcome.errors)
|
"step": "auto_transfer", "status": "skipped",
|
||||||
recovery = outcome.recovery
|
"detail": "no executable items; execution and notification skipped",
|
||||||
warnings: list[str] = [
|
|
||||||
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
|
|
||||||
]
|
|
||||||
if outcome.run_no:
|
|
||||||
results.append({
|
|
||||||
"run_no": outcome.run_no,
|
|
||||||
"status": outcome.run_status,
|
|
||||||
})
|
})
|
||||||
elif not outcome.errors:
|
|
||||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
summary_text = (
|
||||||
warnings.append("no executable items; execution and notification skipped")
|
f"sources={len(source_codes)} types={len(transfer_types)} "
|
||||||
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
|
f"runs={len(results)} recovered={recovery.recovered_count} "
|
||||||
|
f"still_blocked={recovery.still_blocked_count}"
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
success + recovery.recovered_count,
|
success_runs + failed_runs + recovery.recovered_count + failed_units,
|
||||||
success,
|
success_runs,
|
||||||
recovery.still_blocked_count,
|
failed_runs + failed_units + recovery.still_blocked_count,
|
||||||
0,
|
0,
|
||||||
results,
|
results,
|
||||||
warnings,
|
|
||||||
errors,
|
errors,
|
||||||
|
step_logs + [
|
||||||
|
{"step": "summary", "status": "failed" if errors else "success", "detail": summary_text},
|
||||||
|
],
|
||||||
)
|
)
|
||||||
@@ -5,7 +5,8 @@ backend/app/services/schedule/job_options.py
|
|||||||
依赖:models.Agent、shipping_notice.onhand_source_repository。
|
依赖:models.Agent、shipping_notice.onhand_source_repository。
|
||||||
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
||||||
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
||||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
|
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources;
|
||||||
|
在途调拨注册键为 transfer_types(启用中的调拨类型配置)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -78,6 +79,20 @@ def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
|
|||||||
} for source, _config in rows]
|
} for source, _config in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _transfer_types_options() -> list[dict[str, Any]]:
|
||||||
|
"""启用中的调拨类型(value=类型编码;供在途自动调拨排程选类型,留空=全部)。"""
|
||||||
|
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"label": (dto.names or {}).get("zh-CN") or dto.code,
|
||||||
|
"value": dto.code,
|
||||||
|
"description": dto.description or None,
|
||||||
|
}
|
||||||
|
for dto in get_enabled()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def _hxops_users_options() -> list[dict[str, Any]]:
|
def _hxops_users_options() -> list[dict[str, Any]]:
|
||||||
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
||||||
from app.models import User
|
from app.models import User
|
||||||
@@ -118,6 +133,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
|||||||
"freight_rpa_sources": _freight_rpa_sources_options,
|
"freight_rpa_sources": _freight_rpa_sources_options,
|
||||||
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
|
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
|
||||||
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
|
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
|
||||||
|
"transfer_types": _transfer_types_options,
|
||||||
"hxops_users": _hxops_users_options,
|
"hxops_users": _hxops_users_options,
|
||||||
"users": _users_options,
|
"users": _users_options,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -606,10 +606,21 @@ def _register_builtin_platform_jobs() -> None:
|
|||||||
handler=run_in_transit_transfer_schedule,
|
handler=run_in_transit_transfer_schedule,
|
||||||
description=(
|
description=(
|
||||||
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
||||||
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
|
"缺收料文件时自动触发收料 RPA。调拨类型留空=全部启用类型逐轮执行。"
|
||||||
|
"执行时间建议配置在期望调拨时点之前。"
|
||||||
),
|
),
|
||||||
category="platform",
|
category="platform",
|
||||||
params_schema=(
|
params_schema=(
|
||||||
|
{
|
||||||
|
"key": "transfer_types",
|
||||||
|
"type": "multi_select",
|
||||||
|
"label": "调拨类型",
|
||||||
|
"label_key": "admin.schedule.form.transferTypeCodes",
|
||||||
|
"required": False,
|
||||||
|
"default": [],
|
||||||
|
"options_source": "transfer_types",
|
||||||
|
"help": "留空=全部启用中的调拨类型;按类型逐轮匹配并执行,恢复复核只跑一次。",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "source_codes",
|
"key": "source_codes",
|
||||||
"type": "multi_select",
|
"type": "multi_select",
|
||||||
|
|||||||
@@ -46,26 +46,56 @@ from app.path_utils import resolve_backend_relative_path
|
|||||||
from app.services.file_assets.storage import file_asset_storage
|
from app.services.file_assets.storage import file_asset_storage
|
||||||
|
|
||||||
|
|
||||||
|
def _released_line_indexes_for_task(order_task_id: int) -> set[int]:
|
||||||
|
"""按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。"""
|
||||||
|
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||||
|
|
||||||
|
rows = (
|
||||||
|
ShippingOrderReviewLineDecision.query
|
||||||
|
.join(
|
||||||
|
ShippingOrderReviewCase,
|
||||||
|
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
|
||||||
|
)
|
||||||
|
.filter(
|
||||||
|
ShippingOrderReviewCase.confirmed_task_id == int(order_task_id),
|
||||||
|
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||||
|
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||||
|
ShippingOrderReviewLineDecision.line_index.isnot(None),
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {int(row.line_index) for row in rows}
|
||||||
|
|
||||||
|
|
||||||
def _notice_source_code(task: ShippingNotice) -> str | None:
|
def _notice_source_code(task: ShippingNotice) -> str | None:
|
||||||
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
|
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
|
||||||
|
|
||||||
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
|
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
|
||||||
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
|
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
|
||||||
|
已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found
|
||||||
|
(如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性
|
||||||
|
裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源
|
||||||
|
(回归 OT-20261027-4BD4CEFF)。
|
||||||
"""
|
"""
|
||||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||||
if task_id is None:
|
if task_id is None:
|
||||||
return None
|
return None
|
||||||
task_id = int(task_id)
|
task_id = int(task_id)
|
||||||
|
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||||
codes = [
|
codes = [
|
||||||
str(row[0]).strip().upper()
|
str(row[0]).strip().upper()
|
||||||
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
|
for row in db.session.query(
|
||||||
|
ShippingNoticeLineOnhandMatch.source_code,
|
||||||
|
ShippingNoticeLineOnhandMatch.match_result,
|
||||||
|
ShippingNoticeLineOnhandMatch.line_index,
|
||||||
|
).filter(
|
||||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
|
||||||
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
|
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
|
||||||
).distinct().all()
|
).all()
|
||||||
if row[0]
|
if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes))
|
||||||
]
|
]
|
||||||
|
codes = list(dict.fromkeys(codes))
|
||||||
return codes[0] if len(codes) == 1 else None
|
return codes[0] if len(codes) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
@@ -87,19 +117,31 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
|
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
|
||||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
|
"""从 Notice 行级匹配读取本次导出的唯一库存文件。
|
||||||
|
|
||||||
|
已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时
|
||||||
|
库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。
|
||||||
|
"""
|
||||||
task_id = getattr(task, 'order_task_id', None)
|
task_id = getattr(task, 'order_task_id', None)
|
||||||
if task_id is None:
|
if task_id is None:
|
||||||
return None
|
return None
|
||||||
task_id = int(task_id)
|
task_id = int(task_id)
|
||||||
|
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||||
ids = [
|
ids = [
|
||||||
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
|
int(row[0]) for row in db.session.query(
|
||||||
|
ShippingNoticeLineOnhandMatch.onhand_snapshot_id,
|
||||||
|
ShippingNoticeLineOnhandMatch.match_result,
|
||||||
|
ShippingNoticeLineOnhandMatch.line_index,
|
||||||
|
).filter(
|
||||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
|
||||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
|
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
|
||||||
).distinct().all()
|
).all()
|
||||||
|
if row[0] is not None and (
|
||||||
|
row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)
|
||||||
|
)
|
||||||
]
|
]
|
||||||
|
ids = list(dict.fromkeys(ids))
|
||||||
return ids[0] if len(ids) == 1 else None
|
return ids[0] if len(ids) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
@@ -799,8 +841,14 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
|||||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||||
|
# [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是
|
||||||
|
# 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空,
|
||||||
|
# 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。
|
||||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||||
|
|
||||||
|
order_task_id_for_decisions = int(
|
||||||
|
getattr(source_notice, 'order_task_id', None) or source_notice.id
|
||||||
|
)
|
||||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||||
released_source_line_indexes: set[int] = set()
|
released_source_line_indexes: set[int] = set()
|
||||||
if source_notice.id is not None:
|
if source_notice.id is not None:
|
||||||
@@ -808,7 +856,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
|||||||
ShippingOrderReviewLineDecision.query
|
ShippingOrderReviewLineDecision.query
|
||||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||||
.filter(
|
.filter(
|
||||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||||
)
|
)
|
||||||
@@ -835,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
|||||||
ShippingOrderReviewLineDecision.query
|
ShippingOrderReviewLineDecision.query
|
||||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||||
.filter(
|
.filter(
|
||||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2520,7 +2520,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||||
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
|
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
|
||||||
raw_result = str(payload.get('result') or '').strip().lower()
|
raw_result = str(payload.get('result') or '').strip().lower()
|
||||||
if raw_result in {'success', 'failed', 'unknown'}:
|
if raw_result in {'success', 'failed', 'unknown', 'allocating'}:
|
||||||
result_status = raw_result
|
result_status = raw_result
|
||||||
else:
|
else:
|
||||||
result_status = 'success' if success else 'failed'
|
result_status = 'success' if success else 'failed'
|
||||||
@@ -2614,6 +2614,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
|
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if completed.status == 'running' and completed.error_code == 'CRANE_ALLOCATING':
|
||||||
|
set_task_step_progress(
|
||||||
|
task,
|
||||||
|
stage="freight_uploading",
|
||||||
|
step_title="上传货代",
|
||||||
|
status="running",
|
||||||
|
message='货代已接收文件,正在分配,稍后自动回查一次',
|
||||||
|
progress_percent=90,
|
||||||
|
detail='Processing + Allocating the Shipping Order',
|
||||||
|
)
|
||||||
|
log_task_event(task, 'upload_rpa_allocating', {'artifact_id': completed.artifact_id, 'attempt_id': completed.id})
|
||||||
|
db.session.commit()
|
||||||
|
return tool_response(
|
||||||
|
status='running',
|
||||||
|
task=task,
|
||||||
|
message='货代已接收文件,正在分配',
|
||||||
|
data=serialize_task_for_tool(task),
|
||||||
|
)
|
||||||
|
|
||||||
if completed.status == 'unknown':
|
if completed.status == 'unknown':
|
||||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||||
set_task_step_progress(
|
set_task_step_progress(
|
||||||
|
|||||||
@@ -414,7 +414,11 @@ def _shortage_release_required_fields(
|
|||||||
source_code=resolved_source_code, enabled=True,
|
source_code=resolved_source_code, enabled=True,
|
||||||
).first()
|
).first()
|
||||||
template = getattr(source, 'excel_template', None) if source is not None else None
|
template = getattr(source, 'excel_template', None) if source is not None else None
|
||||||
profile = getattr(source, 'parsing_profile', None) if source is not None else None
|
# [s18 改名] 解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系
|
||||||
|
# (与 freight_rpa.parsing_profile.require_source_profile 同口径);
|
||||||
|
# 站点行 getattr 读法会静默得 None,曾致短缺放行(自动+人工)全部失败。
|
||||||
|
release_config = getattr(source, 'onhand_report_config', None) if source is not None else None
|
||||||
|
profile = release_config.parsing_profile if release_config is not None else None
|
||||||
if template is None or profile is None:
|
if template is None or profile is None:
|
||||||
raise ConflictError(
|
raise ConflictError(
|
||||||
'Inventory source export template is unavailable',
|
'Inventory source export template is unavailable',
|
||||||
|
|||||||
@@ -1951,16 +1951,19 @@ def list_freight_notice_groups_for_task(
|
|||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
||||||
|
projected_upload_status = project_notice_upload_status(notice)
|
||||||
|
hide_allocating_error = projected_upload_status == 'allocating'
|
||||||
items.append({
|
items.append({
|
||||||
'business_no': business_no,
|
'business_no': business_no,
|
||||||
'po_number': po_number,
|
'po_number': po_number,
|
||||||
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
|
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
|
||||||
'upload_status': project_notice_upload_status(notice),
|
'upload_status': projected_upload_status,
|
||||||
'upload_mode': upload_mode,
|
'upload_mode': upload_mode,
|
||||||
'upload_attempt': upload_attempt,
|
'upload_attempt': upload_attempt,
|
||||||
'upload_error_code': getattr(latest_attempt, 'error_code', None),
|
'upload_error_code': None if hide_allocating_error else getattr(latest_attempt, 'error_code', None),
|
||||||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
||||||
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
|
# 分配中的内部错误码不是失败原因,不能把这一行显示成需人工。
|
||||||
|
'upload_error_message': None if hide_allocating_error else ((getattr(latest_attempt, 'error_message', None) or '')[:500] or None),
|
||||||
'export_file_name': getattr(artifact, 'file_name', None),
|
'export_file_name': getattr(artifact, 'file_name', None),
|
||||||
'available_actions': available_actions,
|
'available_actions': available_actions,
|
||||||
'lines': _notice_line_summary_for_task(notice),
|
'lines': _notice_line_summary_for_task(notice),
|
||||||
|
|||||||
@@ -75,6 +75,14 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
|
|||||||
return existing
|
return existing
|
||||||
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
|
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
|
||||||
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
|
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
|
||||||
|
allocating = ShippingUploadAttempt.query.filter_by(
|
||||||
|
artifact_id=artifact.id, status='running', error_code='CRANE_ALLOCATING',
|
||||||
|
).first()
|
||||||
|
if allocating is not None:
|
||||||
|
raise ConflictError(
|
||||||
|
'Crane has accepted the file and is still allocating; refresh status instead of uploading again',
|
||||||
|
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||||
|
)
|
||||||
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
|
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
|
||||||
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
|
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
|
||||||
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
|
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
|
||||||
@@ -123,7 +131,7 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
|||||||
task: 正式 Notice,或可解析到 Notice 的 OT。
|
task: 正式 Notice,或可解析到 Notice 的 OT。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
|
uploaded | allocating | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||||
"""
|
"""
|
||||||
attempt = latest_upload_attempt(task)
|
attempt = latest_upload_attempt(task)
|
||||||
if attempt is not None:
|
if attempt is not None:
|
||||||
@@ -131,6 +139,8 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
|||||||
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
|
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
|
||||||
if status == 'succeeded':
|
if status == 'succeeded':
|
||||||
return 'uploaded'
|
return 'uploaded'
|
||||||
|
if status == 'running' and str(getattr(attempt, 'error_code', None) or '') == 'CRANE_ALLOCATING':
|
||||||
|
return 'allocating'
|
||||||
if status in _UPLOAD_IN_FLIGHT_TOKENS:
|
if status in _UPLOAD_IN_FLIGHT_TOKENS:
|
||||||
return 'uploading'
|
return 'uploading'
|
||||||
if status == 'pending':
|
if status == 'pending':
|
||||||
@@ -221,9 +231,9 @@ def _normalize_callback_result(result: str | None, success: bool) -> str:
|
|||||||
"""
|
"""
|
||||||
if result is not None:
|
if result is not None:
|
||||||
normalized = str(result or '').strip().lower()
|
normalized = str(result or '').strip().lower()
|
||||||
if normalized not in {'success', 'failed', 'unknown'}:
|
if normalized not in {'success', 'failed', 'unknown', 'allocating'}:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'result must be success, failed or unknown',
|
'result must be success, failed, unknown or allocating',
|
||||||
code='SHIPPING.UPLOAD_RESULT_INVALID',
|
code='SHIPPING.UPLOAD_RESULT_INVALID',
|
||||||
)
|
)
|
||||||
return normalized
|
return normalized
|
||||||
@@ -243,7 +253,7 @@ def complete_attempt(
|
|||||||
callback_id: 回调幂等键(唯一)。
|
callback_id: 回调幂等键(唯一)。
|
||||||
freight_ref_no: 成功时货代回执号。
|
freight_ref_no: 成功时货代回执号。
|
||||||
error_message: 失败/未知时的脱敏错误信息。
|
error_message: 失败/未知时的脱敏错误信息。
|
||||||
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
|
result: success / failed / unknown / allocating。allocating 表示 Crane 已接收且仍在分配。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
ShippingUploadAttempt: 已更新状态的 Attob。
|
ShippingUploadAttempt: 已更新状态的 Attob。
|
||||||
@@ -266,10 +276,16 @@ def complete_attempt(
|
|||||||
if artifact.status in {'superseded', 'invalidated'}:
|
if artifact.status in {'superseded', 'invalidated'}:
|
||||||
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
|
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
|
||||||
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
|
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
|
||||||
|
if str(result or '').strip().lower() == 'allocating':
|
||||||
|
return attempt
|
||||||
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||||
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
|
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
|
||||||
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||||
result_status = _normalize_callback_result(result, success)
|
result_status = _normalize_callback_result(result, success)
|
||||||
|
if result_status == 'allocating':
|
||||||
|
from app.services.freight_rpa.upload.crane_recheck import remember_crane_allocating
|
||||||
|
|
||||||
|
return remember_crane_allocating(attempt, artifact, callback)
|
||||||
attempt.callback_id = callback
|
attempt.callback_id = callback
|
||||||
attempt.finished_at = datetime.utcnow()
|
attempt.finished_at = datetime.utcnow()
|
||||||
task = db.session.get(ShippingNotice, artifact.task_id)
|
task = db.session.get(ShippingNotice, artifact.task_id)
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
services/shipping_notice/upload_config_validation.py
|
services/shipping_notice/upload_config_validation.py
|
||||||
|
|
||||||
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
|
用途:系统连接只保存「是否启用发货 Excel 自动上传」。
|
||||||
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
|
依赖:app.core.errors.ValidationError;标准库 hashlib/json。
|
||||||
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
|
逻辑:页面路径、选择器和成功文案由连接器代码固定,管理端提交的这些字段一律丢弃。
|
||||||
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
upload_config 快照只保留 enabled,供本次上传审计。
|
||||||
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -16,192 +15,34 @@ from typing import Any
|
|||||||
|
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
|
|
||||||
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
|
|
||||||
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
|
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
|
||||||
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
|
|
||||||
'dbs': ('dbschenker.com',),
|
|
||||||
'crane': ('craneww.com',),
|
|
||||||
}
|
|
||||||
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
|
|
||||||
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
|
|
||||||
|
|
||||||
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
|
|
||||||
ALLOWED_KEYS = frozenset({
|
|
||||||
'enabled', 'entry_url', 'file_input_selector',
|
|
||||||
'submit_mode', 'submit_selector',
|
|
||||||
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
|
|
||||||
})
|
|
||||||
|
|
||||||
MAX_ENTRY_URL_LENGTH = 500
|
|
||||||
MAX_SELECTOR_LENGTH = 200
|
|
||||||
MAX_SUCCESS_TEXTS = 10
|
|
||||||
MAX_SUCCESS_TEXT_LENGTH = 200
|
|
||||||
MIN_TIMEOUT_SECONDS = 1
|
|
||||||
MAX_TIMEOUT_SECONDS = 600
|
|
||||||
DEFAULT_TIMEOUT_SECONDS = 120
|
|
||||||
|
|
||||||
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
|
|
||||||
_BLOCKED_SELECTOR_MARKERS = (
|
|
||||||
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
|
|
||||||
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
|
|
||||||
)
|
|
||||||
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
|
|
||||||
|
|
||||||
|
|
||||||
def _reject(message: str, *, field: str) -> None:
|
def _reject(message: str, *, field: str) -> None:
|
||||||
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
|
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
|
||||||
|
|
||||||
|
|
||||||
def _normalize_text(value: Any) -> str:
|
|
||||||
return str(value or '').strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
|
|
||||||
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
|
|
||||||
url = _normalize_text(value)
|
|
||||||
if not url:
|
|
||||||
if required:
|
|
||||||
_reject('entry_url is required', field='entry_url')
|
|
||||||
return None
|
|
||||||
if len(url) > MAX_ENTRY_URL_LENGTH:
|
|
||||||
_reject('entry_url is too long', field='entry_url')
|
|
||||||
if not url.lower().startswith('https://'):
|
|
||||||
_reject('entry_url must be HTTPS', field='entry_url')
|
|
||||||
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
|
|
||||||
scheme_rest = url[8:]
|
|
||||||
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
|
|
||||||
host = authority.split('@')[-1].split(':')[0].strip().lower()
|
|
||||||
if not host:
|
|
||||||
_reject('entry_url host is invalid', field='entry_url')
|
|
||||||
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
|
|
||||||
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
|
|
||||||
_reject(
|
|
||||||
f'entry_url host not allowed for {connector_type}',
|
|
||||||
field='entry_url',
|
|
||||||
)
|
|
||||||
return url
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
|
|
||||||
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
|
|
||||||
selector = _normalize_text(value)
|
|
||||||
if not selector:
|
|
||||||
if required:
|
|
||||||
_reject(f'{field} is required', field=field)
|
|
||||||
return None
|
|
||||||
if len(selector) > MAX_SELECTOR_LENGTH:
|
|
||||||
_reject(f'{field} is too long', field=field)
|
|
||||||
lowered = selector.lower()
|
|
||||||
for marker in _BLOCKED_SELECTOR_MARKERS:
|
|
||||||
if marker in lowered:
|
|
||||||
_reject(f'{field} contains script semantics', field=field)
|
|
||||||
for char in _BLOCKED_SELECTOR_CHARS:
|
|
||||||
if char in selector:
|
|
||||||
_reject(f'{field} contains an invalid character', field=field)
|
|
||||||
return selector
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_success_texts(value: Any) -> list[str]:
|
|
||||||
if value in (None, ''):
|
|
||||||
return []
|
|
||||||
if not isinstance(value, list):
|
|
||||||
_reject('success_texts must be a list', field='success_texts')
|
|
||||||
if len(value) > MAX_SUCCESS_TEXTS:
|
|
||||||
_reject('success_texts is too long', field='success_texts')
|
|
||||||
result: list[str] = []
|
|
||||||
for item in value:
|
|
||||||
text = _normalize_text(item)
|
|
||||||
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
|
|
||||||
_reject('success_texts contains an invalid item', field='success_texts')
|
|
||||||
if text not in result:
|
|
||||||
result.append(text)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
|
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
|
||||||
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
|
"""只保留 enabled。页面参数即使随旧表单提交也不落库。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
connector_type: 连接类型,仅允许 dbs / crane。
|
connector_type: 连接类型,仅允许 dbs / crane。
|
||||||
raw: 管理端提交的原始上传配置对象。
|
raw: 管理端提交的上传配置。None 或空串表示未配置。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict | None: 规范化受限 JSON;未配置时返回 None。
|
dict | None: ``{"enabled": bool}``;未配置时返回 None。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
|
ValidationError: 连接类型非法或上传配置不是对象。
|
||||||
enabled=true 但缺少上传或结果判定所需字段。
|
|
||||||
"""
|
"""
|
||||||
normalized_connector = _normalize_text(connector_type).lower()
|
normalized_connector = str(connector_type or '').strip().lower()
|
||||||
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
|
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
|
||||||
_reject('connector_type must be dbs or crane', field='connector_type')
|
_reject('connector_type must be dbs or crane', field='connector_type')
|
||||||
if raw in (None, ''):
|
if raw in (None, ''):
|
||||||
return None
|
return None
|
||||||
if not isinstance(raw, dict):
|
if not isinstance(raw, dict):
|
||||||
_reject('upload_config must be an object', field='upload_config_json')
|
_reject('upload_config must be an object', field='upload_config_json')
|
||||||
unknown = set(raw) - ALLOWED_KEYS
|
return {'enabled': raw.get('enabled') is True}
|
||||||
if unknown:
|
|
||||||
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
|
|
||||||
|
|
||||||
enabled = raw.get('enabled') is True
|
|
||||||
|
|
||||||
config: dict[str, Any] = {
|
|
||||||
'enabled': enabled,
|
|
||||||
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
|
|
||||||
'file_input_selector': _validate_css_selector(
|
|
||||||
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
|
|
||||||
),
|
|
||||||
'submit_mode': _normalize_text(raw.get('submit_mode')),
|
|
||||||
'submit_selector': _validate_css_selector(
|
|
||||||
raw.get('submit_selector'), field='submit_selector', required=False,
|
|
||||||
),
|
|
||||||
'result_mode': _normalize_text(raw.get('result_mode')),
|
|
||||||
'result_selector': _validate_css_selector(
|
|
||||||
raw.get('result_selector'), field='result_selector', required=False,
|
|
||||||
),
|
|
||||||
'success_texts': _validate_success_texts(raw.get('success_texts')),
|
|
||||||
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
|
|
||||||
}
|
|
||||||
|
|
||||||
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
|
|
||||||
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
|
|
||||||
if config['result_mode'] not in ALLOWED_RESULT_MODES:
|
|
||||||
_reject('result_mode must be page_notice or history_record', field='result_mode')
|
|
||||||
if config['submit_mode'] == 'auto_after_file':
|
|
||||||
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
|
|
||||||
config['submit_selector'] = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
timeout = int(config['timeout_seconds'])
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
_reject('timeout_seconds must be an integer', field='timeout_seconds')
|
|
||||||
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
|
|
||||||
_reject(
|
|
||||||
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
|
|
||||||
field='timeout_seconds',
|
|
||||||
)
|
|
||||||
config['timeout_seconds'] = timeout
|
|
||||||
|
|
||||||
if enabled:
|
|
||||||
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
|
|
||||||
if not config['file_input_selector']:
|
|
||||||
_reject('enabled upload requires file_input_selector', field='file_input_selector')
|
|
||||||
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
|
|
||||||
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
|
|
||||||
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
|
|
||||||
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
|
|
||||||
if normalized_connector == 'crane':
|
|
||||||
if config['result_mode'] == 'page_notice':
|
|
||||||
if not config['result_selector'] or not config['success_texts']:
|
|
||||||
_reject(
|
|
||||||
'enabled crane page_notice upload requires result_selector and success_texts',
|
|
||||||
field='result_selector',
|
|
||||||
)
|
|
||||||
elif config['result_mode'] == 'history_record' and not config['result_selector']:
|
|
||||||
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
|
|
||||||
|
|
||||||
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
|
|
||||||
return config
|
|
||||||
|
|
||||||
|
|
||||||
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
|
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class DmsArchiveAdapter:
|
|||||||
"""
|
"""
|
||||||
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
|
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
|
||||||
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
|
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
|
||||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
|
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有原名则跳过。带「(重命名)」的副本改回原名,同一目录多出来的该后缀文件删除。
|
||||||
"""
|
"""
|
||||||
yyyy = f"{period_month.year:04d}"
|
yyyy = f"{period_month.year:04d}"
|
||||||
mm = f"{period_month.month:02d}"
|
mm = f"{period_month.month:02d}"
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ backend/app/services/voucher_check/dms_client.py
|
|||||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
||||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
||||||
|
文档库复制后 LeafName 写成「原名.pdf(重命名)」,扩展名另存。改回「原名.pdf」会被判同名,必须改成不含扩展名的「原名」;多余副本用 Item/Recycle 删除。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from datetime import date
|
from datetime import date
|
||||||
@@ -23,6 +25,65 @@ _LOCK = threading.Lock()
|
|||||||
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
|
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
|
||||||
|
|
||||||
ARCHIVE_ROOT_LEAF = "所有归档"
|
ARCHIVE_ROOT_LEAF = "所有归档"
|
||||||
|
# 文档库同名冲突或复制后自动改名。标记前后可能有空格,后面有时还有 (1)。
|
||||||
|
_DMS_RENAME_RE = re.compile(
|
||||||
|
r"\s*[((]\s*重命名\s*[))]\s*(?:\(\s*\d+\s*\)|(\s*\d+\s*))?"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_leaf_name(name: str) -> str:
|
||||||
|
"""
|
||||||
|
去掉文档库自动加上的「重命名」标记,还原业务文件名。
|
||||||
|
核心逻辑:`发票.pdf(重命名).pdf` 或带空格的 `发票.pdf (重命名) .pdf` 去掉标记后会多出一个扩展名,再折成 `发票.pdf`。
|
||||||
|
"""
|
||||||
|
text = str(name or "").strip()
|
||||||
|
cleaned = _DMS_RENAME_RE.sub("", text)
|
||||||
|
if cleaned == text:
|
||||||
|
return text
|
||||||
|
return re.sub(r"(\.[A-Za-z0-9]{1,8})\s*\1$", r"\1", cleaned).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def dms_stored_leaf_name(filename: str) -> str:
|
||||||
|
"""
|
||||||
|
算出文档库改名接口要写入的 LeafName。
|
||||||
|
核心逻辑:库里真实名字是「发票.pdf(重命名)」,扩展名在附件上。改成「发票.pdf」会和自己判成同名;改成「发票」后界面仍显示「发票.pdf」。
|
||||||
|
"""
|
||||||
|
name = str(filename or "").strip()
|
||||||
|
suffix = Path(name).suffix
|
||||||
|
if suffix and name.lower().endswith(suffix.lower()) and len(name) > len(suffix):
|
||||||
|
return name[: -len(suffix)]
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def row_display_name(row: dict[str, Any]) -> str:
|
||||||
|
"""
|
||||||
|
还原文档库界面上的文件名。
|
||||||
|
核心逻辑:LeafName 没有以附件扩展名结尾时,界面会把扩展名补在后面。
|
||||||
|
"""
|
||||||
|
leaf = str((row or {}).get("LeafName") or "").strip()
|
||||||
|
attachment = (row or {}).get("MainFileAttachment") or {}
|
||||||
|
if not isinstance(attachment, dict):
|
||||||
|
attachment = {}
|
||||||
|
ext = str(attachment.get("Extension") or "").strip()
|
||||||
|
if ext and not ext.startswith("."):
|
||||||
|
ext = f".{ext}"
|
||||||
|
if ext and leaf and not leaf.lower().endswith(ext.lower()):
|
||||||
|
return f"{leaf}{ext}"
|
||||||
|
return leaf
|
||||||
|
|
||||||
|
|
||||||
|
def leaf_names_match(actual: str, wanted: str) -> bool:
|
||||||
|
"""
|
||||||
|
判断目录里的文件名是否就是要找的那一份。
|
||||||
|
核心逻辑:完全一致,或实际名字只是想要的名字加上了文档库「重命名」。
|
||||||
|
"""
|
||||||
|
left = str(actual or "").strip()
|
||||||
|
right = str(wanted or "").strip()
|
||||||
|
if not left or not right:
|
||||||
|
return False
|
||||||
|
if left == right:
|
||||||
|
return True
|
||||||
|
return canonical_leaf_name(left) == right
|
||||||
|
|
||||||
|
|
||||||
def _extract_item_id(payload: dict[str, Any]) -> str:
|
def _extract_item_id(payload: dict[str, Any]) -> str:
|
||||||
@@ -265,14 +326,22 @@ class SalesDmsClient:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
|
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
|
||||||
"""在父目录下按 LeafName 找非文件夹条目,找不到返回 None。"""
|
"""
|
||||||
|
在父目录下按 LeafName 找非文件夹条目,找不到返回 None。
|
||||||
|
核心逻辑:优先完全同名。库内名字可能是「原名.pdf(重命名)」或已改回的「原名」,都按界面显示名认成同一份。
|
||||||
|
"""
|
||||||
wanted = str(leaf_name or "").strip()
|
wanted = str(leaf_name or "").strip()
|
||||||
if not wanted:
|
if not wanted:
|
||||||
return None
|
return None
|
||||||
|
renamed: dict[str, Any] | None = None
|
||||||
for row in cls.list_files(folder_id=parent_folder_id):
|
for row in cls.list_files(folder_id=parent_folder_id):
|
||||||
if str(row.get("LeafName") or "").strip() == wanted:
|
leaf = str(row.get("LeafName") or "").strip()
|
||||||
|
shown = row_display_name(row)
|
||||||
|
if leaf == wanted or shown == wanted:
|
||||||
return row
|
return row
|
||||||
return None
|
if renamed is None and (leaf_names_match(leaf, wanted) or leaf_names_match(shown, wanted)):
|
||||||
|
renamed = row
|
||||||
|
return renamed
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
|
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
|
||||||
@@ -387,6 +456,121 @@ class SalesDmsClient:
|
|||||||
failure_message="文档库复制文件失败",
|
failure_message="文档库复制文件失败",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def rename_item(cls, *, item_id: str, leaf_name: str) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把文档库条目改成指定文件名。
|
||||||
|
核心逻辑:POST Item/Rename,与文档库列表「重命名」一致,只改 LeafName、不另存一份。
|
||||||
|
"""
|
||||||
|
item = str(item_id or "").strip()
|
||||||
|
wanted = str(leaf_name or "").strip()
|
||||||
|
if not item:
|
||||||
|
raise ValidationError("重命名条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||||
|
if not wanted:
|
||||||
|
raise ValidationError("重命名文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||||
|
return cls._post_json(
|
||||||
|
"/Api/_api/APS/Public/Item/Rename",
|
||||||
|
{"ItemID": item, "LeafName": wanted},
|
||||||
|
timeout=30,
|
||||||
|
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||||
|
failure_message="文档库去掉重命名后缀失败",
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _restore_exact_leaf(
|
||||||
|
cls,
|
||||||
|
*,
|
||||||
|
parent_folder_id: str,
|
||||||
|
wanted: str,
|
||||||
|
row: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
所有归档要求界面上不带「(重命名)」。
|
||||||
|
核心逻辑:先确认这份就是目标文件。改名只写不含扩展名的 LeafName;写成「原名.pdf」会和「原名.pdf(重命名)」判成同名。
|
||||||
|
"""
|
||||||
|
leaf = str(row.get("LeafName") or "").strip()
|
||||||
|
shown = row_display_name(row)
|
||||||
|
target = dms_stored_leaf_name(wanted)
|
||||||
|
if leaf in {wanted, target} or shown == wanted:
|
||||||
|
return row
|
||||||
|
if canonical_leaf_name(leaf) != wanted and canonical_leaf_name(shown) != wanted:
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"目标目录文件名与归档文件名不一致",
|
||||||
|
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||||
|
details={"leaf_name": wanted, "actual_name": leaf},
|
||||||
|
)
|
||||||
|
cls.rename_item(item_id=str(row.get("ID") or ""), leaf_name=target)
|
||||||
|
for item in cls.list_files(folder_id=parent_folder_id):
|
||||||
|
item_leaf = str(item.get("LeafName") or "").strip()
|
||||||
|
if item_leaf in {wanted, target} or row_display_name(item) == wanted:
|
||||||
|
return item
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"去掉重命名后缀后未找到原文件名",
|
||||||
|
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||||
|
details={"leaf_name": wanted},
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def recycle_items(cls, *, item_ids: list[str]) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
按文档库列表「删除」把条目放进回收站。
|
||||||
|
核心逻辑:POST Item/Recycle,ItemID 为数组;不调用彻底删除,误删可从回收站恢复。
|
||||||
|
"""
|
||||||
|
ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()]
|
||||||
|
if not ids:
|
||||||
|
raise ValidationError("删除条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||||
|
return cls._post_json(
|
||||||
|
"/Api/_api/APS/Public/Item/Recycle",
|
||||||
|
{"ItemID": ids},
|
||||||
|
timeout=30,
|
||||||
|
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||||
|
failure_message="文档库删除多余重命名文件失败",
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _drop_extra_renamed_copies(
|
||||||
|
cls,
|
||||||
|
*,
|
||||||
|
parent_folder_id: str,
|
||||||
|
wanted: str,
|
||||||
|
keep_item_id: str,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
删掉同一目录里多出来的「(重命名)」副本。
|
||||||
|
核心逻辑:只删文件名还原后等于目标原名、且仍带重命名标记的条目;原名和其他文件不动。
|
||||||
|
"""
|
||||||
|
keep = str(keep_item_id or "").strip()
|
||||||
|
extras: list[str] = []
|
||||||
|
for row in cls.list_files(folder_id=parent_folder_id):
|
||||||
|
item_id = str(row.get("ID") or "").strip()
|
||||||
|
leaf = str(row.get("LeafName") or "").strip()
|
||||||
|
shown = row_display_name(row)
|
||||||
|
if not item_id or item_id == keep or ("重命名" not in leaf and "重命名" not in shown):
|
||||||
|
continue
|
||||||
|
if canonical_leaf_name(leaf) == wanted or canonical_leaf_name(shown) == wanted:
|
||||||
|
extras.append(item_id)
|
||||||
|
if extras:
|
||||||
|
cls.recycle_items(item_ids=extras)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _settle_archived_file(
|
||||||
|
cls,
|
||||||
|
*,
|
||||||
|
parent_folder_id: str,
|
||||||
|
wanted: str,
|
||||||
|
row: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
归档落盘后收成一个界面上不带后缀的原名。
|
||||||
|
核心逻辑:先删掉其余「(重命名)」副本,再把留下的那份改成不含扩展名的 LeafName。先改名会被文档库判成同名。
|
||||||
|
"""
|
||||||
|
cls._drop_extra_renamed_copies(
|
||||||
|
parent_folder_id=parent_folder_id,
|
||||||
|
wanted=wanted,
|
||||||
|
keep_item_id=str(row.get("ID") or "").strip(),
|
||||||
|
)
|
||||||
|
return cls._restore_exact_leaf(parent_folder_id=parent_folder_id, wanted=wanted, row=row)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def copy_file_skip_same_name(
|
def copy_file_skip_same_name(
|
||||||
cls,
|
cls,
|
||||||
@@ -397,10 +581,10 @@ class SalesDmsClient:
|
|||||||
) -> tuple[dict[str, Any], bool]:
|
) -> tuple[dict[str, Any], bool]:
|
||||||
"""
|
"""
|
||||||
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
||||||
核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。
|
核心逻辑:先按 LeafName 查目标。已有原名则跳过复制;只有「(重命名)」副本时改回原名。没有再 Copy。收尾时同一目录多出来的该后缀副本删除。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。
|
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有文件(必要时已去掉重命名后缀并删除多余副本)。
|
||||||
"""
|
"""
|
||||||
wanted = str(leaf_name or "").strip()
|
wanted = str(leaf_name or "").strip()
|
||||||
source = str(source_item_id or "").strip()
|
source = str(source_item_id or "").strip()
|
||||||
@@ -414,18 +598,21 @@ class SalesDmsClient:
|
|||||||
|
|
||||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||||
if existing:
|
if existing:
|
||||||
return existing, True
|
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cls.copy_items(item_ids=[source], dest_folder_id=dest)
|
cls.copy_items(item_ids=[source], dest_folder_id=dest)
|
||||||
except ServiceUnavailableError as exc:
|
except ServiceUnavailableError as exc:
|
||||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||||
if existing:
|
if existing:
|
||||||
return existing, True
|
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
||||||
if _is_name_conflict(exc.message):
|
if _is_name_conflict(exc.message):
|
||||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||||
if existing:
|
if existing:
|
||||||
return existing, True
|
return (
|
||||||
|
cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing),
|
||||||
|
True,
|
||||||
|
)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||||
@@ -435,7 +622,7 @@ class SalesDmsClient:
|
|||||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||||
details={"leaf_name": wanted},
|
details={"leaf_name": wanted},
|
||||||
)
|
)
|
||||||
return dest_row, False
|
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=dest_row), False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
|
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ backend/app/services/voucher_check/notification.py
|
|||||||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||||
卡片标题为「销售开票附件缺件」,不写业务方代号和批次号;
|
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
|
||||||
|
卡片发出后紧跟本批检核结果 Excel,收件人不用进详情才知道缺哪张票;
|
||||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -47,7 +48,7 @@ def _missing_type_line(item: dict[str, Any]) -> str:
|
|||||||
|
|
||||||
def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]:
|
def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
组装销售开票附件缺件 textcard。
|
组装销售开票附件缺件 textcard,标题为「销售开票附件缺件提醒」。
|
||||||
核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节,
|
核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节,
|
||||||
颜色标签会挤掉后面的缺件类型。
|
颜色标签会挤掉后面的缺件类型。
|
||||||
|
|
||||||
@@ -59,10 +60,10 @@ def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[s
|
|||||||
_friendly_period_label(period_month),
|
_friendly_period_label(period_month),
|
||||||
"销售开票附件已检核,你负责的类型还有缺件:",
|
"销售开票附件已检核,你负责的类型还有缺件:",
|
||||||
*[_missing_type_line(item) for item in items],
|
*[_missing_type_line(item) for item in items],
|
||||||
"请尽快补齐。完整清单见详情里的 Excel。",
|
"请尽快补齐。缺件明细见下一条 Excel。",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
return "销售开票附件缺件", body
|
return "销售开票附件缺件提醒", body
|
||||||
|
|
||||||
|
|
||||||
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
||||||
@@ -113,6 +114,36 @@ def _persist_skip(
|
|||||||
return send_status
|
return send_status
|
||||||
|
|
||||||
|
|
||||||
|
def _send_excel_file(wecom_userid: str, media_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
把已上传的检核结果 Excel 发给一个收件人。
|
||||||
|
核心逻辑:企微文件消息与 textcard 是两条消息,失败只记日志,不回滚已发出的卡片。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
企业微信 errcode 为 0 时为 True。
|
||||||
|
"""
|
||||||
|
from app.services.integrations.wecom.notify import send_wecom_file_message
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = send_wecom_file_message(wecom_userid, media_id)
|
||||||
|
except Exception as exc:
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[voucher-check] excel file failed user=%s err=%s",
|
||||||
|
wecom_userid,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
if data.get("errcode") == 0:
|
||||||
|
return True
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[voucher-check] excel file failed user=%s errcode=%s errmsg=%s",
|
||||||
|
wecom_userid,
|
||||||
|
data.get("errcode"),
|
||||||
|
data.get("errmsg"),
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def send_batch_missing_summary(
|
def send_batch_missing_summary(
|
||||||
*,
|
*,
|
||||||
task: ScheduleTask,
|
task: ScheduleTask,
|
||||||
@@ -122,11 +153,17 @@ def send_batch_missing_summary(
|
|||||||
period_month: str,
|
period_month: str,
|
||||||
stats: dict[str, Any],
|
stats: dict[str, Any],
|
||||||
excel_filename: str | None,
|
excel_filename: str | None,
|
||||||
|
excel_bytes: bytes | None = None,
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
按文件类型接收人发送缺件 textcard。
|
按文件类型接收人发送缺件 textcard,并附上本批检核结果 Excel。
|
||||||
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。无缺件或无人可发则写审计不发空消息。
|
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。
|
||||||
|
Excel 全批共用一份,上传一次后随卡片发给每个收件人。附件失败不挡住卡片,原因写入审计。
|
||||||
|
无缺件或无人可发则写审计不发空消息。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
excel_bytes: 与排程落库同一份检核结果。为空时只发卡片。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||||||
@@ -213,9 +250,20 @@ def send_batch_missing_summary(
|
|||||||
_build_jump_url,
|
_build_jump_url,
|
||||||
_create_audit,
|
_create_audit,
|
||||||
send_wecom_textcard_message,
|
send_wecom_textcard_message,
|
||||||
|
upload_wecom_temp_media,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
media_id = None
|
||||||
|
file_note = None
|
||||||
|
if excel_bytes and excel_filename:
|
||||||
|
try:
|
||||||
|
media_id = upload_wecom_temp_media(excel_bytes, excel_filename)
|
||||||
|
except Exception as exc:
|
||||||
|
file_note = "Excel 附件上传失败"
|
||||||
|
current_app.logger.warning("[voucher-check] excel upload failed: %s", exc)
|
||||||
|
|
||||||
ok_any = False
|
ok_any = False
|
||||||
|
file_failed = False
|
||||||
sent_ids: list[int] = []
|
sent_ids: list[int] = []
|
||||||
for user in users:
|
for user in users:
|
||||||
items = plan["user_rules"].get(int(user.id)) or []
|
items = plan["user_rules"].get(int(user.id)) or []
|
||||||
@@ -234,6 +282,8 @@ def send_batch_missing_summary(
|
|||||||
audit.status = "sent"
|
audit.status = "sent"
|
||||||
ok_any = True
|
ok_any = True
|
||||||
sent_ids.append(int(user.id))
|
sent_ids.append(int(user.id))
|
||||||
|
if media_id and not _send_excel_file(user.wecom_userid, media_id):
|
||||||
|
file_failed = True
|
||||||
else:
|
else:
|
||||||
audit.error_code = str(data.get("errcode"))
|
audit.error_code = str(data.get("errcode"))
|
||||||
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
|
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
|
||||||
@@ -244,11 +294,16 @@ def send_batch_missing_summary(
|
|||||||
exc,
|
exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
skip_reason = None
|
if file_failed and not file_note:
|
||||||
|
file_note = "部分 Excel 附件发送失败"
|
||||||
|
reasons: list[str] = []
|
||||||
if not ok_any:
|
if not ok_any:
|
||||||
skip_reason = "企业微信发送失败"
|
reasons.append("企业微信发送失败")
|
||||||
elif plan["unmapped_codes"]:
|
elif plan["unmapped_codes"]:
|
||||||
skip_reason = "部分文件类型未配置接收人"
|
reasons.append("部分文件类型未配置接收人")
|
||||||
|
if file_note:
|
||||||
|
reasons.append(file_note)
|
||||||
|
skip_reason = ";".join(reasons) or None
|
||||||
persist_notification(
|
persist_notification(
|
||||||
run_id=engine_run_id,
|
run_id=engine_run_id,
|
||||||
excel_filename=excel_filename,
|
excel_filename=excel_filename,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/query_service.py
|
|||||||
|
|
||||||
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
|
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
|
||||||
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
|
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
|
||||||
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
|
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细可按状态和 invoice 号筛选行,by_file_type 仍是整批;强制重检写入 run_options.mode=force_all。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -545,10 +545,14 @@ def list_run_items(
|
|||||||
*,
|
*,
|
||||||
run_id: int,
|
run_id: int,
|
||||||
result: str | None = None,
|
result: str | None = None,
|
||||||
|
invoice_no: str | None = None,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = 50,
|
page_size: int = 50,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
|
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。
|
||||||
|
|
||||||
|
核心逻辑:result 精确匹配状态;invoice_no 按包含、忽略大小写筛行。文件类型汇总不跟着这两个条件缩。
|
||||||
|
"""
|
||||||
run = ScheduleRun.query.get(run_id)
|
run = ScheduleRun.query.get(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||||
@@ -574,6 +578,12 @@ def list_run_items(
|
|||||||
result_filter = str(result).strip() if result else ""
|
result_filter = str(result).strip() if result else ""
|
||||||
if result_filter:
|
if result_filter:
|
||||||
items = [row for row in items if row.get("result") == result_filter]
|
items = [row for row in items if row.get("result") == result_filter]
|
||||||
|
invoice_filter = str(invoice_no).strip().casefold() if invoice_no else ""
|
||||||
|
if invoice_filter:
|
||||||
|
items = [
|
||||||
|
row for row in items
|
||||||
|
if invoice_filter in str(row.get("invoice_no") or "").casefold()
|
||||||
|
]
|
||||||
total = len(items)
|
total = len(items)
|
||||||
sliced = items[(page - 1) * page_size : page * page_size]
|
sliced = items[(page - 1) * page_size : page * page_size]
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ backend/app/services/voucher_check/runner.py
|
|||||||
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
|
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
|
||||||
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
|
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
|
||||||
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。
|
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。
|
||||||
命中文件复制到所有归档,同名跳过仍记 archived。
|
命中文件复制到所有归档,同名跳过仍记 archived。缺件通知附带与排程落库相同的检核结果 Excel。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -28,7 +28,11 @@ from app.services.voucher_check.engine_persistence import (
|
|||||||
persist_engine_results,
|
persist_engine_results,
|
||||||
)
|
)
|
||||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||||
from app.services.voucher_check.excel_rows import to_excel_invoice_row
|
from app.services.voucher_check.excel_rows import (
|
||||||
|
VOUCHER_CHECK_HEADER_LABELS,
|
||||||
|
VOUCHER_CHECK_HEADER_ORDER,
|
||||||
|
to_excel_invoice_row,
|
||||||
|
)
|
||||||
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
|
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
|
||||||
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
|
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
|
||||||
from app.services.voucher_check.profiles.sales import required_file_rules
|
from app.services.voucher_check.profiles.sales import required_file_rules
|
||||||
@@ -369,8 +373,18 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
|
|||||||
to_excel_invoice_row(item, period=period, executed_at=executed_at)
|
to_excel_invoice_row(item, period=period, executed_at=executed_at)
|
||||||
for item in stats["excel_rows"]
|
for item in stats["excel_rows"]
|
||||||
]
|
]
|
||||||
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
|
|
||||||
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知
|
# 与排程落库用同一导出,保证企微附件和事后下载是同一张表。
|
||||||
|
excel_bytes, _, _ = export_schedule_result_excel(
|
||||||
|
run_no=run.run_no,
|
||||||
|
summary={"period": period},
|
||||||
|
details=details,
|
||||||
|
header_order=list(VOUCHER_CHECK_HEADER_ORDER),
|
||||||
|
header_labels=VOUCHER_CHECK_HEADER_LABELS,
|
||||||
|
)
|
||||||
|
|
||||||
|
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知,并附上本批 Excel
|
||||||
notify_status = send_batch_missing_summary(
|
notify_status = send_batch_missing_summary(
|
||||||
task=task,
|
task=task,
|
||||||
schedule_run=run,
|
schedule_run=run,
|
||||||
@@ -379,6 +393,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
|
|||||||
period_month=period,
|
period_month=period,
|
||||||
stats=stats,
|
stats=stats,
|
||||||
excel_filename=excel_filename,
|
excel_filename=excel_filename,
|
||||||
|
excel_bytes=excel_bytes,
|
||||||
enabled=config.notify_missing_enabled,
|
enabled=config.notify_missing_enabled,
|
||||||
)
|
)
|
||||||
step_logs.append(
|
step_logs.append(
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""合并意见反馈附图表与设备验收评审两条 Alembic 头
|
||||||
|
|
||||||
|
Revision ID: 7e5bc4bc0cbc
|
||||||
|
Revises: mh24f5a6b7c8, sxw4m73amjyh
|
||||||
|
Create Date: 2026-10-29 11:00:46.546116
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '7e5bc4bc0cbc'
|
||||||
|
down_revision = ('mh24f5a6b7c8', 'sxw4m73amjyh')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""合并用户多角色与意见反馈附图两条 Alembic 头
|
||||||
|
|
||||||
|
Revision ID: c375467a21f9
|
||||||
|
Revises: 7e5bc4bc0cbc, pr0a1b2c3d4e5
|
||||||
|
Create Date: 2026-10-29 12:41:08.055302
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'c375467a21f9'
|
||||||
|
down_revision = ('7e5bc4bc0cbc', 'pr0a1b2c3d4e5')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""merge migration heads: 合并「用户多角色/意见反馈附图」与「部门树」两条迁移头
|
||||||
|
|
||||||
|
用途:c375467a21f9 与 eff84b4f6171 两条并行迁移链各自成头,导致
|
||||||
|
``flask db upgrade`` 报 Multiple head revisions(见 scripts/check_migration_heads.py)。
|
||||||
|
本迁移仅归并两条链,无任何表结构变更,upgrade/downgrade 均为空操作。
|
||||||
|
|
||||||
|
依赖关系:down_revision 同时挂载两条待归并的迁移头
|
||||||
|
- c375467a21f9(合并用户多角色与意见反馈附图两条 alembic 头)
|
||||||
|
- eff84b4f6171(合并部门树与最新 dev 迁移头)
|
||||||
|
|
||||||
|
逻辑关系:作为迁移图的新唯一 head,位于两条链收敛点之后,
|
||||||
|
后续新迁移应以本 revision 为 down_revision。
|
||||||
|
|
||||||
|
Revision ID: d143df04ab5a
|
||||||
|
Revises: c375467a21f9, eff84b4f6171
|
||||||
|
Create Date: 2026-10-30
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'd143df04ab5a'
|
||||||
|
down_revision = ('c375467a21f9', 'eff84b4f6171')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
"""纯 merge 迁移:仅收敛迁移图,无结构变更。"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
"""拆开 merge 点即回到原两条并行头,无需回滚任何结构。"""
|
||||||
|
pass
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Add department tree columns
|
||||||
|
|
||||||
|
Revision ID: dp1a2b3c4d5e6
|
||||||
|
Revises: 9e5045511198
|
||||||
|
Create Date: 2026-10-08 10:00:00.000000
|
||||||
|
|
||||||
|
用途:departments 表升级为树形结构(parent_id 邻接表 + 同级排序 + 隐藏标记),
|
||||||
|
并放开 name 全局唯一约束(多公司允许同名部门,改由 service 层做同级查重)。
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'dp1a2b3c4d5e6'
|
||||||
|
down_revision = '9e5045511198'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
conn = op.get_bind()
|
||||||
|
insp = sa.inspect(conn)
|
||||||
|
tables = set(insp.get_table_names())
|
||||||
|
|
||||||
|
if 'departments' not in tables:
|
||||||
|
# 防御:空库直接按新结构建表
|
||||||
|
op.create_table(
|
||||||
|
'departments',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('code', sa.String(length=50), nullable=True),
|
||||||
|
sa.Column('company', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('parent_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'),
|
||||||
|
sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('code'),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
['parent_id'], ['departments.id'], name='fk_departments_parent_id_departments'
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||||
|
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||||
|
if 'parent_id' not in cols:
|
||||||
|
batch_op.add_column(sa.Column('parent_id', sa.Integer(), nullable=True))
|
||||||
|
if 'sort_order' not in cols:
|
||||||
|
batch_op.add_column(sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'))
|
||||||
|
if 'is_hidden' not in cols:
|
||||||
|
batch_op.add_column(sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()))
|
||||||
|
|
||||||
|
# 重新内省后再补自关联外键(列可能由上一步刚添加)
|
||||||
|
insp2 = sa.inspect(conn)
|
||||||
|
fks = insp2.get_foreign_keys('departments')
|
||||||
|
has_parent_fk = any(
|
||||||
|
'parent_id' in (fk.get('constrained_columns') or []) for fk in fks
|
||||||
|
)
|
||||||
|
if not has_parent_fk:
|
||||||
|
op.create_foreign_key(
|
||||||
|
'fk_departments_parent_id_departments', 'departments', 'departments',
|
||||||
|
['parent_id'], ['id'],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 放开 name 全局唯一:删除覆盖 name 列的 unique 约束(同名约束名在不同库不一致,按列名探测)
|
||||||
|
name_uq_names = [
|
||||||
|
uq['name'] for uq in insp2.get_unique_constraints('departments')
|
||||||
|
if set(uq.get('column_names') or []) == {'name'} and uq.get('name')
|
||||||
|
]
|
||||||
|
if name_uq_names:
|
||||||
|
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||||
|
for uq_name in name_uq_names:
|
||||||
|
batch_op.drop_constraint(uq_name, type_='unique')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
conn = op.get_bind()
|
||||||
|
insp = sa.inspect(conn)
|
||||||
|
if 'departments' not in set(insp.get_table_names()):
|
||||||
|
return
|
||||||
|
|
||||||
|
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||||
|
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||||
|
if 'is_hidden' in cols:
|
||||||
|
batch_op.drop_column('is_hidden')
|
||||||
|
if 'sort_order' in cols:
|
||||||
|
batch_op.drop_column('sort_order')
|
||||||
|
if 'parent_id' in cols:
|
||||||
|
try:
|
||||||
|
batch_op.drop_constraint('fk_departments_parent_id_departments', type_='foreignkey')
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
batch_op.drop_column('parent_id')
|
||||||
|
# 恢复 name 全局唯一;若历史数据存在重名会失败,需先清洗数据
|
||||||
|
try:
|
||||||
|
batch_op.create_unique_constraint('uq_departments_name', ['name'])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""设备验收快照增加流程编号、标题和创建时间。
|
||||||
|
|
||||||
|
Revision ID: ea1b2c3d4e5f
|
||||||
|
Revises: ea9d1e2f3a4b
|
||||||
|
Create Date: 2026-10-26 19:20:00.000000
|
||||||
|
|
||||||
|
用途:equipment_acceptance_orders 增加 flow_no、request_title、request_created_at。
|
||||||
|
依赖:ea9d1e2f3a4b 已加上 oa_system。不改合同付款表。
|
||||||
|
逻辑:三列可空。已有行留空,下次同步按来源回填。创建时间不是本地行的 created_at。
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = "ea1b2c3d4e5f"
|
||||||
|
down_revision = "ea9d1e2f3a4b"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
"""加上流程编号、标题和创建时间。已有单据留空,等下一次同步写入。"""
|
||||||
|
op.add_column(
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
sa.Column("flow_no", sa.String(length=1000), nullable=True),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
sa.Column("request_title", sa.String(length=1000), nullable=True),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
sa.Column("request_created_at", sa.DateTime(), nullable=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
"""去掉流程编号、标题和创建时间。"""
|
||||||
|
op.drop_column("equipment_acceptance_orders", "request_created_at")
|
||||||
|
op.drop_column("equipment_acceptance_orders", "request_title")
|
||||||
|
op.drop_column("equipment_acceptance_orders", "flow_no")
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""设备验收快照增加来源,E10 与 E8 的流程号分开。
|
||||||
|
|
||||||
|
Revision ID: ea9d1e2f3a4b
|
||||||
|
Revises: b51c9e4a7d30, tt21c8d9e0f1a2
|
||||||
|
Create Date: 2026-10-26 16:20:00.000000
|
||||||
|
|
||||||
|
用途:equipment_acceptance_orders 增加 oa_system,唯一约束改为 (oa_system, request_id)。
|
||||||
|
依赖:equipment_acceptance_orders 已存在。不改合同付款表。
|
||||||
|
逻辑:已有行回填 e10。E8 的 request_id 可以与 E10 相同,不能再共用单列唯一。
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = "ea9d1e2f3a4b"
|
||||||
|
down_revision = ("b51c9e4a7d30", "tt21c8d9e0f1a2")
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
"""加上来源列,并把唯一约束从 request_id 改成来源加流程号。"""
|
||||||
|
op.add_column(
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
sa.Column("oa_system", sa.String(length=8), nullable=False, server_default="e10"),
|
||||||
|
)
|
||||||
|
op.drop_constraint(
|
||||||
|
"uq_equipment_acceptance_orders_request_id",
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
type_="unique",
|
||||||
|
)
|
||||||
|
op.create_unique_constraint(
|
||||||
|
"uq_equipment_acceptance_orders_oa_request",
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
["oa_system", "request_id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
"""去掉来源列,恢复只按 request_id 唯一。E8 行若与 E10 撞号,降级会失败。"""
|
||||||
|
op.drop_constraint(
|
||||||
|
"uq_equipment_acceptance_orders_oa_request",
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
type_="unique",
|
||||||
|
)
|
||||||
|
op.create_unique_constraint(
|
||||||
|
"uq_equipment_acceptance_orders_request_id",
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
["request_id"],
|
||||||
|
)
|
||||||
|
op.drop_column("equipment_acceptance_orders", "oa_system")
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""merge department tree and latest dev migration heads
|
||||||
|
|
||||||
|
Revision ID: eff84b4f6171
|
||||||
|
Revises: fa1d22f99de9, pr0a1b2c3d4e5
|
||||||
|
Create Date: 2026-10-29 17:06:07.732022
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'eff84b4f6171'
|
||||||
|
down_revision = ('fa1d22f99de9', 'pr0a1b2c3d4e5')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""merge department tree and dev migration heads
|
||||||
|
|
||||||
|
Revision ID: fa1d22f99de9
|
||||||
|
Revises: dp1a2b3c4d5e6, eah8c9d0e1f2
|
||||||
|
Create Date: 2026-10-22 13:19:23.491330
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'fa1d22f99de9'
|
||||||
|
down_revision = ('dp1a2b3c4d5e6', 'eah8c9d0e1f2')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""合并常用问题模糊匹配与库存异动自然键两条 Alembic 头。
|
||||||
|
|
||||||
|
backend/migrations/versions/mh23e4f5a6b7_merge_faq_fuzzy_and_ledger_heads.py
|
||||||
|
用途:把 FAQ 模糊匹配列与库存异动外部单号自然键收成单一升级路径。
|
||||||
|
依赖:b51c9e4a7d30、tt21c8d9e0f1a2。
|
||||||
|
逻辑:不改业务表,只声明两条已完成迁移线在此收敛,避免 flask db upgrade 与 pre-commit 因多 head 失败。
|
||||||
|
|
||||||
|
Revision ID: mh23e4f5a6b7
|
||||||
|
Revises: b51c9e4a7d30, tt21c8d9e0f1a2
|
||||||
|
Create Date: 2026-10-23 15:05:00.000000
|
||||||
|
"""
|
||||||
|
|
||||||
|
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||||
|
|
||||||
|
|
||||||
|
revision = "mh23e4f5a6b7"
|
||||||
|
down_revision = ("b51c9e4a7d30", "tt21c8d9e0f1a2")
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""合并 FAQ 模糊匹配 head 与库存异动自然键 head,不执行数据库结构变更。"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||||
|
pass
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
"""合并设备验收流程字段与复核行决策码两条 Alembic 头。
|
||||||
|
|
||||||
|
Revision ID: mh24f5a6b7c8
|
||||||
|
Revises: ea1b2c3d4e5f, s20a1b2c3d4e
|
||||||
|
Create Date: 2026-10-28 10:55:00.000000
|
||||||
|
|
||||||
|
用途:将 ``ea1b2c3d4e5f``(设备验收流程编号、标题与来源)与
|
||||||
|
``s20a1b2c3d4e``(复核行决策码改名)收成单一升级路径。
|
||||||
|
依赖:``ea1b2c3d4e5f``、``s20a1b2c3d4e``。
|
||||||
|
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||||
|
|
||||||
|
|
||||||
|
revision = "mh24f5a6b7c8"
|
||||||
|
down_revision = ("ea1b2c3d4e5f", "s20a1b2c3d4e")
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""合并设备验收 head 与复核行决策码 head,不执行数据库结构变更。"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||||
|
pass
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Add user-to-permission-role membership.
|
||||||
|
|
||||||
|
Revision ID: pr0a1b2c3d4e5
|
||||||
|
Revises: mh24f5a6b7c8
|
||||||
|
Create Date: 2026-10-29 09:55:00.000000
|
||||||
|
|
||||||
|
用途:用户与权限组改为一对多,支持同时挂多个业务角色。
|
||||||
|
依赖:users、permission_roles。
|
||||||
|
逻辑:建 user_permission_roles,并按现有 users.role 回填一行成员关系。users.role 保留为主角色。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = "pr0a1b2c3d4e5"
|
||||||
|
down_revision = "mh24f5a6b7c8"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
"user_permission_roles",
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("role_id", sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["role_id"], ["permission_roles.id"], ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("user_id", "role_id"),
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO user_permission_roles (user_id, role_id)
|
||||||
|
SELECT u.id, pr.id
|
||||||
|
FROM users u
|
||||||
|
JOIN permission_roles pr ON pr.code = u.role
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_table("user_permission_roles")
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
migrations/versions/s20a1b2c3d4e_review_line_decision_code_rename.py
|
||||||
|
|
||||||
|
用途:批次 S 漏网补丁——复核行决定表的决策码迁移。
|
||||||
|
s17b(表改名)/s17c(枚举数据替换)/s18 均未覆盖
|
||||||
|
shipping_order_review_line_decisions.decision_code:旧码数据不搬、
|
||||||
|
ck_shipping_review_line_decisions_code 不重建,导致新代码写入
|
||||||
|
release_onhand_shortage / wait_onhand 时撞 prod 旧 CHECK
|
||||||
|
(IntegrityError,自动放行被吞、人工放行报错)。
|
||||||
|
依赖:alembic.op、SQLAlchemy;down_revision 为 mh23e4f5a6b7(现仓库唯一 head)。
|
||||||
|
逻辑:先 drop 旧 CHECK(否则新码 UPDATE 直接违约),再做两次精确值替换
|
||||||
|
(release_inventory_shortage→release_onhand_shortage、
|
||||||
|
wait_inventory→wait_onhand,其余码不变),最后按
|
||||||
|
models/shipping_order_review_line_decision.py 的现行码集重建同名 CHECK。
|
||||||
|
line_status 的 CHECK 已是新集(released_shortage 早已在列),本迁移不动。
|
||||||
|
snapshot_json 内的历史码是审计快照,按不可变原则不改写。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
|
||||||
|
revision = "s20a1b2c3d4e"
|
||||||
|
down_revision = "mh23e4f5a6b7"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
_TABLE = "shipping_order_review_line_decisions"
|
||||||
|
_CHECK = "ck_shipping_review_line_decisions_code"
|
||||||
|
|
||||||
|
# 与模型 CheckConstraint 逐字一致的新码集(升级方向)
|
||||||
|
_NEW_CODES = (
|
||||||
|
"'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
|
||||||
|
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
|
||||||
|
)
|
||||||
|
# hg1i2j3k4l5m 时的旧码集(降级方向)
|
||||||
|
_OLD_CODES = (
|
||||||
|
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
||||||
|
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 旧码 → 新码(词根 inventory→onhand 的两个改名对;升级方向)
|
||||||
|
_UPDATES_UP: tuple[tuple[str, str], ...] = (
|
||||||
|
("release_inventory_shortage", "release_onhand_shortage"),
|
||||||
|
("wait_inventory", "wait_onhand"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# [STEP 1] 先摘旧 CHECK:旧码集不含新码,先改值必违约。
|
||||||
|
op.drop_constraint(_CHECK, _TABLE, type_="check")
|
||||||
|
# [STEP 2] 精确值替换(只碰两个改名对,其余决策码保持原值)。
|
||||||
|
for old, new in _UPDATES_UP:
|
||||||
|
op.execute(
|
||||||
|
sa.text(
|
||||||
|
f"UPDATE {_TABLE} SET decision_code = :new WHERE decision_code = :old"
|
||||||
|
).bindparams(old=old, new=new)
|
||||||
|
)
|
||||||
|
# [STEP 3] 按模型现行码集重建同名 CHECK。
|
||||||
|
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_NEW_CODES})")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# [STEP 1] 先摘新 CHECK,再把新码精确换回旧码。
|
||||||
|
op.drop_constraint(_CHECK, _TABLE, type_="check")
|
||||||
|
for old, new in _UPDATES_UP:
|
||||||
|
op.execute(
|
||||||
|
sa.text(
|
||||||
|
f"UPDATE {_TABLE} SET decision_code = :old WHERE decision_code = :new"
|
||||||
|
).bindparams(old=old, new=new)
|
||||||
|
)
|
||||||
|
# [STEP 2] 恢复旧码集 CHECK。
|
||||||
|
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_OLD_CODES})")
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""add general_feedback_images table
|
||||||
|
|
||||||
|
backend/migrations/versions/sxw4m73amjyh_add_general_feedback_images.py
|
||||||
|
用途:创建意见反馈截图附件关联表 general_feedback_images,一条反馈可挂多张截图(asset_id 唯一,一图只挂一条反馈)。
|
||||||
|
依赖:mh23e4f5a6b7(FAQ 模糊匹配与库存异动自然键两条迁移头的合并节点,当前唯一 head)。
|
||||||
|
逻辑:upgrade 仅建表(id/feedback_id/asset_id/sort_order/created_at + feedback_id 索引 + asset_id 唯一约束);
|
||||||
|
downgrade 按相反顺序删索引、删表;删除反馈时级联删除附件为 ORM 层行为(GeneralFeedback.images cascade)。
|
||||||
|
|
||||||
|
Revision ID: sxw4m73amjyh
|
||||||
|
Revises: mh23e4f5a6b7
|
||||||
|
Create Date: 2026-10-26 16:11:31.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'sxw4m73amjyh'
|
||||||
|
down_revision = 'mh23e4f5a6b7'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
'general_feedback_images',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('feedback_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('asset_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['asset_id'], ['file_assets.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['feedback_id'], ['general_feedbacks.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('asset_id'),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
op.f('ix_general_feedback_images_feedback_id'),
|
||||||
|
'general_feedback_images',
|
||||||
|
['feedback_id'],
|
||||||
|
unique=False,
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index(
|
||||||
|
op.f('ix_general_feedback_images_feedback_id'),
|
||||||
|
table_name='general_feedback_images',
|
||||||
|
)
|
||||||
|
op.drop_table('general_feedback_images')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"_comment": "hrao00 -> 公司中文名。来源 ERP dc.HRAA_FILE(hraa01=公司编号,hraa02=公司名称)。0000 集团公司无部门,保留映射以备后续。",
|
||||||
|
"0000": "集团公司",
|
||||||
|
"0001": "电子",
|
||||||
|
"0002": "科技",
|
||||||
|
"0003": "和信",
|
||||||
|
"0004": "泰国合欣",
|
||||||
|
"0005": "台湾尊场",
|
||||||
|
"0006": "无锡和宏智",
|
||||||
|
"0007": "上海数智"
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
"""Import ERP HRAO_FILE departments into the local department tree.
|
||||||
|
|
||||||
|
Purpose: one-shot import of the Tiptop department master (ERP `dc.HRAO_FILE`) exported as
|
||||||
|
CSV from DBeaver into the local `departments` tree, upserting by department code (hrao01).
|
||||||
|
Dependencies: Flask app context, SQLAlchemy models, csv/json stdlib (no Oracle driver).
|
||||||
|
Flow: dry-run is the default and only prints a validation report; pass `--apply` to write.
|
||||||
|
hrao06 parent codes resolve to hrao01 after all rows are upserted; dangling parents and
|
||||||
|
cycles fall back to top-level with a report. Local rows whose code is absent from the ERP
|
||||||
|
file are kept untouched (per the agreed merge policy). `users.department` links by name
|
||||||
|
text, so renames are reported for manual re-linking instead of being rewritten here.
|
||||||
|
|
||||||
|
Usage (from backend/):
|
||||||
|
python scripts/import_departments_from_hrao.py --file scripts/data/hrao_departments.csv
|
||||||
|
python scripts/import_departments_from_hrao.py --file ... --apply
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(BACKEND_ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(BACKEND_ROOT))
|
||||||
|
|
||||||
|
from app import create_app
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import Department, User
|
||||||
|
|
||||||
|
DEFAULT_CSV = Path("scripts/data/hrao_departments.csv")
|
||||||
|
DEFAULT_COMPANY_MAP = Path("scripts/data/hrao_company_map.json")
|
||||||
|
HIDDEN_MODES = ("ignore", "n_is_hidden", "not_y_is_hidden")
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(value: Any) -> str:
|
||||||
|
"""Trim a CSV cell to a normalized string ('' for None)."""
|
||||||
|
return str(value or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _read_csv(path: Path) -> list[dict[str, str]]:
|
||||||
|
"""Read the DBeaver CSV export; headers are normalized to lowercase (utf-8 with BOM tolerated).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: CSV file exported from `SELECT hrao00, hrao01, hrao02, hrao03, hrao06, hrao09, ... FROM dc.HRAO_FILE`.
|
||||||
|
Returns:
|
||||||
|
List of row dicts keyed by lowercase column names (hrao00 ...).
|
||||||
|
Raises:
|
||||||
|
SystemExit: file missing or no recognizable hrao01 header.
|
||||||
|
"""
|
||||||
|
if not path.exists():
|
||||||
|
raise SystemExit(f"CSV not found: {path}\n先在 DBeaver 导出 HRAO 查询结果为 CSV(UTF-8),再放到该路径。")
|
||||||
|
import csv
|
||||||
|
|
||||||
|
with path.open(encoding="utf-8-sig", newline="") as fh:
|
||||||
|
reader = csv.DictReader(fh)
|
||||||
|
rows = [
|
||||||
|
{(k or "").strip().lower(): (v or "") for k, v in raw.items()}
|
||||||
|
for raw in reader
|
||||||
|
]
|
||||||
|
if rows and not any("hrao01" in row for row in rows[:1]):
|
||||||
|
raise SystemExit(f"CSV 首行未找到 hrao01 列头,请确认导出来自 HRAO_FILE 查询:{path}")
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _load_company_map(path: Path) -> dict[str, str]:
|
||||||
|
"""Load hrao00 -> company display name mapping from a JSON file.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
SystemExit: mapping file missing (with a template hint).
|
||||||
|
"""
|
||||||
|
if not path.exists():
|
||||||
|
raise SystemExit(
|
||||||
|
f"公司映射文件不存在:{path}\n"
|
||||||
|
'请创建 JSON:{"0002": "苏州和信精密科技有限公司", ...}(hrao00 -> 公司中文名)。'
|
||||||
|
)
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
return {_clean(k): _clean(v) for k, v in data.items() if _clean(k)}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_hidden(hrao08: str, mode: str) -> bool:
|
||||||
|
"""Map hrao08 (在组织框架图中显示否) to is_hidden per the chosen mode.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
mode: ignore(默认,全部不隐藏)| n_is_hidden(N=不显示→隐藏)| not_y_is_hidden(非 Y 即隐藏)。
|
||||||
|
"""
|
||||||
|
flag = _clean(hrao08).upper()
|
||||||
|
if mode == "n_is_hidden":
|
||||||
|
return flag == "N"
|
||||||
|
if mode == "not_y_is_hidden":
|
||||||
|
return flag != "Y"
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_rows(
|
||||||
|
raw_rows: list[dict[str, str]], hidden_mode: str
|
||||||
|
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||||
|
"""Normalize CSV rows into import payloads; duplicate hrao01 keeps the first occurrence.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(rows, problems) — rows keyed by code with name/company_code/parent_code/sort_order/is_hidden.
|
||||||
|
"""
|
||||||
|
rows: dict[str, dict[str, Any]] = {}
|
||||||
|
problems: list[str] = []
|
||||||
|
for raw in raw_rows:
|
||||||
|
code = _clean(raw.get("hrao01"))
|
||||||
|
name = _clean(raw.get("hrao02")) or _clean(raw.get("hrao03"))
|
||||||
|
if not code:
|
||||||
|
problems.append(f"跳过:hrao01 为空(hrao02={_clean(raw.get('hrao02'))!r})")
|
||||||
|
continue
|
||||||
|
if not name:
|
||||||
|
problems.append(f"跳过:{code} 部门名称为空(hrao02/hrao03 均空)")
|
||||||
|
continue
|
||||||
|
if code in rows:
|
||||||
|
problems.append(f"跳过重复编码:{code} 第二次出现({name!r}),保留首行")
|
||||||
|
continue
|
||||||
|
sort_raw = _clean(raw.get("hrao09"))
|
||||||
|
parent = _clean(raw.get("hrao06"))
|
||||||
|
rows[code] = {
|
||||||
|
"code": code,
|
||||||
|
"name": name,
|
||||||
|
"company_code": _clean(raw.get("hrao00")),
|
||||||
|
"parent_code": parent if parent and parent != "0" else None,
|
||||||
|
"sort_order": int(sort_raw) if sort_raw.isdigit() else 0,
|
||||||
|
"is_hidden": _parse_hidden(raw.get("hrao08"), hidden_mode),
|
||||||
|
}
|
||||||
|
return list(rows.values()), problems
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_parents(rows: list[dict[str, Any]]) -> tuple[dict[str, Optional[str]], list[str]]:
|
||||||
|
"""Resolve each row's parent code; dangling/self references fall back to top-level.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(parent_by_code, problems) — parent codes or None for top-level.
|
||||||
|
"""
|
||||||
|
codes = {r["code"] for r in rows}
|
||||||
|
parent_by_code: dict[str, Optional[str]] = {}
|
||||||
|
problems: list[str] = []
|
||||||
|
for row in rows:
|
||||||
|
parent = row["parent_code"]
|
||||||
|
if parent is not None and (parent not in codes or parent == row["code"]):
|
||||||
|
problems.append(f"悬空上级:{row['code']} {row['name']} 的 hrao06={parent!r} 匹配不到 hrao01,按顶级导入")
|
||||||
|
parent = None
|
||||||
|
parent_by_code[row["code"]] = parent
|
||||||
|
return parent_by_code, problems
|
||||||
|
|
||||||
|
|
||||||
|
def _break_cycles(
|
||||||
|
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||||||
|
) -> tuple[dict[str, Optional[str]], list[str]]:
|
||||||
|
"""Rows caught in a parent cycle (e.g. A->B->A) are detached to top-level.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(parent_by_code, problems)
|
||||||
|
"""
|
||||||
|
problems: list[str] = []
|
||||||
|
for row in rows:
|
||||||
|
seen: set[str] = set()
|
||||||
|
cursor: Optional[str] = row["code"]
|
||||||
|
cyclic = False
|
||||||
|
while cursor and parent_by_code.get(cursor):
|
||||||
|
if cursor in seen:
|
||||||
|
cyclic = True
|
||||||
|
break
|
||||||
|
seen.add(cursor)
|
||||||
|
cursor = parent_by_code[cursor]
|
||||||
|
if cyclic:
|
||||||
|
name = next(r["name"] for r in rows if r["code"] == row["code"])
|
||||||
|
problems.append(f"成环:{row['code']} {name} 的上级链形成环,整链按顶级导入")
|
||||||
|
parent_by_code[row["code"]] = None
|
||||||
|
return parent_by_code, problems
|
||||||
|
|
||||||
|
|
||||||
|
def _find_name_conflicts(
|
||||||
|
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||||||
|
) -> list[str]:
|
||||||
|
"""Same-parent (or same-company top-level) duplicate names would fail sibling validation."""
|
||||||
|
buckets: Counter = Counter()
|
||||||
|
for row in rows:
|
||||||
|
parent = parent_by_code[row["code"]]
|
||||||
|
company = row["company_code"] if parent is None else parent
|
||||||
|
buckets[(company, parent, row["name"])] += 1
|
||||||
|
return [
|
||||||
|
f"同级重名:{name!r}(公司/父={key})出现 {count} 次,需人工改名后再导入"
|
||||||
|
for (key, _, name), count in buckets.items()
|
||||||
|
if count > 1
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def plan_import(
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
company_map: dict[str, str],
|
||||||
|
allow_unmapped: bool,
|
||||||
|
) -> tuple[dict[str, Any], list[str]]:
|
||||||
|
"""Diff ERP rows against local departments into an upsert plan.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
rows: normalized ERP rows.
|
||||||
|
company_map: hrao00 -> company display name.
|
||||||
|
allow_unmapped: when False, unmapped hrao00 aborts the plan (apply refuses).
|
||||||
|
Returns:
|
||||||
|
(plan, problems) — plan holds inserts/updates/kept/dangling etc. for the reporter.
|
||||||
|
"""
|
||||||
|
problems: list[str] = []
|
||||||
|
unmapped = sorted({r["company_code"] for r in rows if r["company_code"] and r["company_code"] not in company_map})
|
||||||
|
if unmapped and not allow_unmapped:
|
||||||
|
problems.append(f"未映射的公司编码:{unmapped}(补 hrao_company_map.json 或加 --allow-unmapped)")
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
row["company"] = company_map.get(row["company_code"])
|
||||||
|
|
||||||
|
local_by_code = {d.code: d for d in db.session.query(Department).all()}
|
||||||
|
inserts = [r for r in rows if r["code"] not in local_by_code]
|
||||||
|
updates = [
|
||||||
|
{"local": local_by_code[r["code"]], "row": r}
|
||||||
|
for r in rows
|
||||||
|
if r["code"] in local_by_code
|
||||||
|
]
|
||||||
|
kept = sorted(set(local_by_code) - {r["code"] for r in rows})
|
||||||
|
|
||||||
|
renames = []
|
||||||
|
for item in updates:
|
||||||
|
old_name = item["local"].name
|
||||||
|
if old_name != item["row"]["name"]:
|
||||||
|
linked = db.session.query(User).filter(User.department == old_name).count()
|
||||||
|
renames.append((old_name, item["row"]["name"], linked))
|
||||||
|
|
||||||
|
plan = {
|
||||||
|
"inserts": inserts,
|
||||||
|
"updates": updates,
|
||||||
|
"kept": kept,
|
||||||
|
"renames": renames,
|
||||||
|
"unmapped": unmapped,
|
||||||
|
}
|
||||||
|
return plan, problems
|
||||||
|
|
||||||
|
|
||||||
|
def apply_plan(plan: dict[str, Any], parent_by_code: dict[str, Optional[str]]) -> tuple[int, int]:
|
||||||
|
"""Execute the plan in one transaction; parents are linked after ids exist.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(created, updated) row counts.
|
||||||
|
"""
|
||||||
|
code_to_id = {d.code: d.id for d in db.session.query(Department).all()}
|
||||||
|
created = updated = 0
|
||||||
|
# [STEP 1] 先落行(parent_id 暂空),拿到主键后再统一挂父,避免插入顺序依赖
|
||||||
|
for row in plan["inserts"]:
|
||||||
|
dept = Department(
|
||||||
|
name=row["name"],
|
||||||
|
code=row["code"],
|
||||||
|
company=row["company"],
|
||||||
|
parent_id=None,
|
||||||
|
sort_order=row["sort_order"],
|
||||||
|
is_hidden=row["is_hidden"],
|
||||||
|
)
|
||||||
|
db.session.add(dept)
|
||||||
|
db.session.flush()
|
||||||
|
code_to_id[row["code"]] = dept.id
|
||||||
|
created += 1
|
||||||
|
# [STEP 2] 更新已存在行(按编码 upsert,保留本地多余行)
|
||||||
|
for item in plan["updates"]:
|
||||||
|
local, row = item["local"], item["row"]
|
||||||
|
local.name = row["name"]
|
||||||
|
local.company = row["company"]
|
||||||
|
local.sort_order = row["sort_order"]
|
||||||
|
local.is_hidden = row["is_hidden"]
|
||||||
|
updated += 1
|
||||||
|
# [STEP 3] 挂上级:本地已有编码或本次新插入的编码都可作为父
|
||||||
|
for row in plan["inserts"] + [i["row"] for i in plan["updates"]]:
|
||||||
|
parent_code = parent_by_code[row["code"]]
|
||||||
|
if parent_code:
|
||||||
|
db.session.get(Department, code_to_id[row["code"]]).parent_id = code_to_id.get(parent_code)
|
||||||
|
db.session.commit()
|
||||||
|
return created, updated
|
||||||
|
|
||||||
|
|
||||||
|
def _print_report(
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
plan: dict[str, Any],
|
||||||
|
problems: list[str],
|
||||||
|
company_map: dict[str, str],
|
||||||
|
raw_rows: list[dict[str, str]],
|
||||||
|
) -> None:
|
||||||
|
"""Print the dry-run/apply report; problem lines always warn before the summary."""
|
||||||
|
companies = Counter(r["company_code"] for r in rows)
|
||||||
|
print("== 公司分布(hrao00 -> 行数)==")
|
||||||
|
for code, count in sorted(companies.items()):
|
||||||
|
print(f" {code or '(空)'} x{count} -> {company_map.get(code, '(未映射)')}")
|
||||||
|
if plan["unmapped"]:
|
||||||
|
print(f" ⚠ 未映射编码:{plan['unmapped']}")
|
||||||
|
print(f"== 汇总 == ERP 行 {len(rows)};插入 {len(plan['inserts'])};更新 {len(plan['updates'])};本地保留 {len(plan['kept'])}")
|
||||||
|
if plan["renames"]:
|
||||||
|
print("== 更名(users.department 按名称关联,需人工重挂)==")
|
||||||
|
for old, new, linked in plan["renames"]:
|
||||||
|
print(f" {old!r} -> {new!r}(名下员工 {linked} 人)")
|
||||||
|
for line in problems:
|
||||||
|
print(f" ⚠ {line}")
|
||||||
|
if not any("⚠" in line for line in problems) and not plan["renames"]:
|
||||||
|
print(" (无告警)")
|
||||||
|
# hrao 标志位分布,帮助确认 is_hidden 映射是否正确
|
||||||
|
for col in ("hrao05", "hrao07", "hrao08"):
|
||||||
|
dist = Counter(_clean(r.get(col)).upper() for r in raw_rows)
|
||||||
|
print(f"== {col} 取值分布 == {dict(dist)}")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Parse args, build the plan, and write only with --apply (single transaction)."""
|
||||||
|
parser = argparse.ArgumentParser(description="Import ERP HRAO_FILE departments (CSV) into the local tree")
|
||||||
|
parser.add_argument("--file", type=Path, default=DEFAULT_CSV, help="DBeaver 导出的 HRAO CSV 路径")
|
||||||
|
parser.add_argument("--company-map", type=Path, default=DEFAULT_COMPANY_MAP, help="hrao00 -> 公司名 JSON")
|
||||||
|
parser.add_argument("--hidden-mode", choices=HIDDEN_MODES, default="ignore",
|
||||||
|
help="hrao08 -> is_hidden 映射;默认 ignore(不隐藏)")
|
||||||
|
parser.add_argument("--allow-unmapped", action="store_true", help="允许未映射公司编码(company 置空)")
|
||||||
|
parser.add_argument("--company", action="append", default=None,
|
||||||
|
help="只导入指定 hrao00 的公司(可多次传入,如 --company 0003);缺省导入全部")
|
||||||
|
parser.add_argument("--apply", action="store_true", help="真正写库;缺省仅 dry-run 预览")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
company_map = _load_company_map(args.company_map)
|
||||||
|
raw_rows = _read_csv(args.file)
|
||||||
|
rows, problems = _normalize_rows(raw_rows, args.hidden_mode)
|
||||||
|
if args.company:
|
||||||
|
wanted = {c.strip() for c in args.company}
|
||||||
|
missing = wanted - {r["company_code"] for r in rows}
|
||||||
|
if missing:
|
||||||
|
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||||||
|
rows = [r for r in rows if r["company_code"] in wanted]
|
||||||
|
if args.company:
|
||||||
|
wanted = {c.strip() for c in args.company}
|
||||||
|
missing = wanted - {r["company_code"] for r in rows}
|
||||||
|
if missing:
|
||||||
|
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||||||
|
rows = [r for r in rows if r["company_code"] in wanted]
|
||||||
|
parent_by_code, parent_problems = _resolve_parents(rows)
|
||||||
|
parent_by_code, cycle_problems = _break_cycles(rows, parent_by_code)
|
||||||
|
problems += parent_problems + cycle_problems
|
||||||
|
problems += _find_name_conflicts(rows, parent_by_code)
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
with app.app_context():
|
||||||
|
plan, plan_problems = plan_import(rows, company_map, args.allow_unmapped)
|
||||||
|
problems += plan_problems
|
||||||
|
_print_report(rows, plan, problems, company_map, raw_rows)
|
||||||
|
fatal = [p for p in problems if "需人工" in p or "未映射的公司编码" in p]
|
||||||
|
if args.apply and not fatal:
|
||||||
|
created, updated = apply_plan(plan, parent_by_code)
|
||||||
|
print(f"✅ 已写入:插入 {created},更新 {updated}(事务已提交)")
|
||||||
|
elif args.apply:
|
||||||
|
raise SystemExit("存在需人工处理的告警,已阻止写库;处理后重试或加对应参数。")
|
||||||
|
else:
|
||||||
|
print("(dry-run 未写库;确认无误后加 --apply 执行)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
"""通用意见反馈提交 API 契约测试(POST /api/user/feedback 携带图片资产)。
|
||||||
|
|
||||||
|
用途:锁定反馈提交接口外部契约——image_asset_nos 按顺序落 general_feedback_images
|
||||||
|
并把 FileAsset 置为 referenced(reference_count+1、expires_at 清空),
|
||||||
|
他人资产/非图片/已被引用/超 5 张等非法输入整单拒绝且不落任何行
|
||||||
|
(FILE_ASSET.* 与 FEEDBACK.IMAGE_* 错误码),纯文本提交保持旧契约。
|
||||||
|
依赖:app/client 夹具(create_app('testing') + create_all)、issue_local_access_token、
|
||||||
|
parse_api_error(错误 envelope 断言);前置数据直接落 User/FileAsset 行。
|
||||||
|
逻辑:校验逻辑由 handlers.submit_general_feedback 承载,本文件只测 API 壳
|
||||||
|
(鉴权/状态码/错误码/落库副作用/回归路径)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.auth.jwt import issue_local_access_token
|
||||||
|
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
|
from tests.conftest import parse_api_error
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _disable_wecom_feedback_notify(app):
|
||||||
|
"""测试绝不触发真实企微群通知(2026-10-26 曾因未隔离 webhook 向真实群发出消息)。"""
|
||||||
|
app.config["WECOM_FEEDBACK_NOTIFY_ENABLED"] = False
|
||||||
|
|
||||||
|
|
||||||
|
def _headers(user: User) -> dict:
|
||||||
|
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
|
||||||
|
token = issue_local_access_token(user)
|
||||||
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
|
def _create_user(username: str, role: str = "user") -> User:
|
||||||
|
"""按用户名幂等落一个测试用户。"""
|
||||||
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
if not user:
|
||||||
|
user = User(username=username, email=f"{username}@example.com", role=role, status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def user_headers(app):
|
||||||
|
"""普通用户 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
return _headers(_create_user("fbuser"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_headers(app):
|
||||||
|
"""平台管理员 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
return _headers(_create_user("fbadmin", role="admin"))
|
||||||
|
|
||||||
|
|
||||||
|
def _make_asset(user_id: int, ext: str = "png", mime: str = "image/png", *, reference_count: int = 0, lifecycle: str = "temporary") -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的 FileAsset 行(不经过 MinIO)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename=f"screenshot.{ext}", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type=mime, extension=ext, upload_status="ready",
|
||||||
|
lifecycle_status=lifecycle, reference_count=reference_count,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
|
||||||
|
|
||||||
|
def _submit_payload(**overrides) -> dict:
|
||||||
|
"""合法反馈提交载荷基线(纯文本,不带图片)。"""
|
||||||
|
payload = {
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "测试反馈内容",
|
||||||
|
"source_page": "workspace",
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_with_images_claims_assets(app, client, user_headers):
|
||||||
|
"""带图提交:两图按顺序落库,资产被引用(reference_count=1、referenced、expires_at 清空)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
a2 = _make_asset(u.id, ext="jpg", mime="image/jpeg")
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
asset_nos = [a1.asset_no, a2.asset_no]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json={
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图",
|
||||||
|
"source_page": "workspace", "image_asset_nos": asset_nos,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with app.app_context():
|
||||||
|
imgs = GeneralFeedbackImage.query.order_by(GeneralFeedbackImage.sort_order).all()
|
||||||
|
assert [i.sort_order for i in imgs] == [0, 1]
|
||||||
|
for i in imgs:
|
||||||
|
asset = db.session.get(FileAsset, i.asset_id)
|
||||||
|
assert asset.reference_count == 1
|
||||||
|
assert asset.lifecycle_status == "referenced"
|
||||||
|
assert asset.expires_at is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_foreign_asset(app, client, user_headers):
|
||||||
|
"""他人资产 → 403 FILE_ASSET.FORBIDDEN,反馈不落库。"""
|
||||||
|
with app.app_context():
|
||||||
|
other = _create_user("fbother")
|
||||||
|
foreign = _make_asset(other.id)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
foreign_no = foreign.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂别人资产", image_asset_nos=[foreign_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FILE_ASSET.FORBIDDEN"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行:反馈与图片关联均为零
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_non_image(app, client, user_headers):
|
||||||
|
"""ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
pdf_asset = _make_asset(u.id, ext="pdf", mime="application/pdf")
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
pdf_no = pdf_asset.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂非图片", image_asset_nos=[pdf_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_referenced_asset(app, client, user_headers):
|
||||||
|
"""reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
used = _make_asset(u.id, reference_count=1)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
used_no = used.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂已引用资产", image_asset_nos=[used_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_too_many(app, client, user_headers):
|
||||||
|
"""6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。"""
|
||||||
|
asset_nos = [f"FA-TEST-{i:04d}" for i in range(6)]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="一次挂六张", image_asset_nos=asset_nos,
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_TOO_MANY"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_text_only_keeps_legacy(app, client, user_headers):
|
||||||
|
"""不带 image_asset_nos:200,general_feedback_images 零行(回归)。"""
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload())
|
||||||
|
assert resp.status_code == 200
|
||||||
|
body = resp.get_json()
|
||||||
|
assert body.get("status") == "ok"
|
||||||
|
assert isinstance(body.get("id"), int)
|
||||||
|
with app.app_context():
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_rows_include_images(app, client, user_headers, admin_headers):
|
||||||
|
"""报表行含 images 元数据;无图行 images==[]。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
asset_no = a1.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="带图反馈", image_asset_nos=[asset_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with_image_id = resp.get_json()["id"]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(content="纯文本反馈"))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
text_only_id = resp.get_json()["id"]
|
||||||
|
|
||||||
|
resp = client.get("/api/admin/reports/general-feedbacks", headers=admin_headers)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
rows = resp.get_json()
|
||||||
|
rows_by_id = {row["id"]: row for row in rows}
|
||||||
|
# 有图行:images[0] 键集合恰为 5 个元数据键,asset_no 与提交资产一致
|
||||||
|
with_image_row = rows_by_id[with_image_id]
|
||||||
|
assert len(with_image_row["images"]) == 1
|
||||||
|
assert set(with_image_row["images"][0].keys()) == {
|
||||||
|
"image_id", "asset_no", "original_filename", "file_size", "sort_order",
|
||||||
|
}
|
||||||
|
assert with_image_row["images"][0]["asset_no"] == asset_no
|
||||||
|
# 无图行:images 置空列表而非缺键
|
||||||
|
assert rows_by_id[text_only_id]["images"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch):
|
||||||
|
"""管理员经 raw 接口取到图片字节(Content-Type 按扩展名固定 + nosniff);错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。"""
|
||||||
|
# 隔离 MinIO:读取字节走本地假实现,提交仍只落库不触对象存储
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.services.file_assets.service.file_asset_storage.get_bytes",
|
||||||
|
lambda key: b"\x89PNG\r\n\x1a\nfake",
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
asset_no = a1.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="取图反馈", image_asset_nos=[asset_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
fb_id = resp.get_json()["id"]
|
||||||
|
with app.app_context():
|
||||||
|
img = GeneralFeedbackImage.query.filter_by(feedback_id=fb_id).first()
|
||||||
|
image_id = img.id
|
||||||
|
|
||||||
|
resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=admin_headers)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.data == b"\x89PNG\r\n\x1a\nfake"
|
||||||
|
assert resp.content_type.startswith("image/png")
|
||||||
|
# 安全响应头:Content-Type 按扩展名白名单固定后,仍禁用浏览器 MIME 嗅探(防伪造内容内联渲染)
|
||||||
|
assert resp.headers.get("X-Content-Type-Options") == "nosniff"
|
||||||
|
|
||||||
|
# 错配 feedback_id:image 不属于该反馈 → FEEDBACK.IMAGE_NOT_FOUND(而非 FILE_ASSET.*)
|
||||||
|
resp = client.get(
|
||||||
|
f"/api/admin/reports/general-feedbacks/{fb_id + 99999}/images/{image_id}/raw", headers=admin_headers,
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_NOT_FOUND"
|
||||||
|
|
||||||
|
# 非管理员访问 raw 接口 → 403
|
||||||
|
resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=user_headers)
|
||||||
|
assert resp.status_code == 403
|
||||||
@@ -2255,3 +2255,51 @@ def test_evidence_files_list_returns_today_size_and_presigned_url(
|
|||||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||||
).one()
|
).one()
|
||||||
assert audit.aggregate_id == EVIDENCE_SOURCE
|
assert audit.aggregate_id == EVIDENCE_SOURCE
|
||||||
|
|
||||||
|
|
||||||
|
def test_evidence_file_download_streams_through_the_site(
|
||||||
|
app, client, admin_headers, monkeypatch,
|
||||||
|
):
|
||||||
|
"""单文件下载由当前站点回传,保存名不用对象键。"""
|
||||||
|
now = datetime.utcnow().replace(microsecond=0)
|
||||||
|
source = _ensure_evidence_source()
|
||||||
|
report = _seed_evidence_file(
|
||||||
|
source, kind="inbound", filename="Inbound.xlsx",
|
||||||
|
storage_key="evidence/one", sha="61" * 32, file_size=12,
|
||||||
|
created_at=now,
|
||||||
|
)
|
||||||
|
_patch_archive_bytes(monkeypatch, {"evidence/one": b"PK-xlsx"})
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||||
|
headers=admin_headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
# [断言意图] 响应体是对象内容,不是跳到 MinIO 的地址。
|
||||||
|
assert response.data == b"PK-xlsx"
|
||||||
|
from app.api.in_transit_transfer import evidence_download_filename
|
||||||
|
|
||||||
|
download_name = evidence_download_filename(EVIDENCE_SOURCE, now, "Inbound.xlsx")
|
||||||
|
# [断言意图] 保存名沿用库存源加东八区时间,浏览器不会落到哈希对象键。
|
||||||
|
assert download_name in response.headers.get("Content-Disposition", "")
|
||||||
|
|
||||||
|
|
||||||
|
def test_evidence_file_download_rejects_unavailable_file(app, client, admin_headers):
|
||||||
|
"""已清理或不在可用窗口的归档不能经站点下载。"""
|
||||||
|
now = datetime.utcnow().replace(microsecond=0)
|
||||||
|
source = _ensure_evidence_source()
|
||||||
|
report = _seed_evidence_file(
|
||||||
|
source, kind="inbound", filename="Deleted.xlsx",
|
||||||
|
storage_key="evidence/gone", sha="62" * 32, file_size=12,
|
||||||
|
created_at=now, deleted=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||||
|
headers=admin_headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
# [断言意图] 清单里不会出现的文件,单文件下载同样拒绝。
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.get_json()["error"]["code"] == "SHIPPING.INBOUND_FILE_NOT_FOUND"
|
||||||
@@ -1,45 +1,180 @@
|
|||||||
"""
|
"""
|
||||||
tests/services/admin/test_department_service.py
|
tests/services/admin/test_department_service.py
|
||||||
|
|
||||||
用途:department_service CRUD 单元测试。
|
用途:department_service 部门树 CRUD、树组装、成员口径单元测试。
|
||||||
|
覆盖:父子挂接 / 同级查重 / 编码唯一 / 防成环 / 删除保护(有下级、有员工)/ 成员数含下级汇总。
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError, ValidationError
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||||
from app.models import Department
|
from app.models import Department, User
|
||||||
from app.services.admin.department_service import (
|
from app.services.admin.department_service import (
|
||||||
create_department,
|
create_department,
|
||||||
delete_department,
|
delete_department,
|
||||||
|
list_department_members,
|
||||||
|
list_department_tree,
|
||||||
list_departments,
|
list_departments,
|
||||||
update_department,
|
update_department,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_department_crud(app):
|
def test_department_crud_with_parent(app):
|
||||||
|
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'})
|
parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
|
||||||
assert created['name'] == 'R&D'
|
child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
|
||||||
|
assert child['name'] == '品保课'
|
||||||
|
|
||||||
items = list_departments()
|
items = list_departments()
|
||||||
assert any(item['code'] == 'RD' for item in items)
|
assert any(item['code'] == 'QA1' and item['parent_id'] == parent['id'] for item in items)
|
||||||
|
|
||||||
update_department(created['id'], {'description': 'Research'})
|
update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
|
||||||
dept = db.session.get(Department, created['id'])
|
dept = db.session.get(Department, child['id'])
|
||||||
assert dept.description == 'Research'
|
assert dept.sort_order == 9
|
||||||
|
assert dept.is_hidden is True
|
||||||
|
|
||||||
delete_department(created['id'])
|
# 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
|
||||||
assert db.session.get(Department, created['id']) is None
|
with pytest.raises(ConflictError, match='child'):
|
||||||
|
delete_department(parent['id'])
|
||||||
|
delete_department(child['id'])
|
||||||
|
delete_department(parent['id'])
|
||||||
|
assert db.session.get(Department, parent['id']) is None
|
||||||
|
|
||||||
|
|
||||||
def test_create_department_rejects_duplicate_name(app):
|
def test_create_department_rejects_same_parent_duplicate_name(app):
|
||||||
|
"""断言:同一上级下同名部门被拒(同级查重)。"""
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
create_department({'name': 'Sales'})
|
create_department({'name': 'Sales'})
|
||||||
with pytest.raises(ValidationError, match='Name exists'):
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
create_department({'name': 'Sales'})
|
create_department({'name': 'Sales'})
|
||||||
|
# 断言业务错误码而非消息文本(str(exc) 仅含 message,不含 code)
|
||||||
|
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_allows_same_name_under_different_parents(app):
|
||||||
|
"""断言:不同分支(多公司)允许同名部门——name 全局唯一已放开。"""
|
||||||
|
with app.app_context():
|
||||||
|
root_a = create_department({'name': '和信', 'company': '和信'})
|
||||||
|
root_b = create_department({'name': '泰国合欣', 'company': '泰国合欣'})
|
||||||
|
create_department({'name': '管理部', 'parent_id': root_a['id']})
|
||||||
|
create_department({'name': '管理部', 'parent_id': root_b['id']})
|
||||||
|
tree = list_department_tree()
|
||||||
|
assert len(tree) == 2
|
||||||
|
assert all(len([c for c in root['children'] if c['name'] == '管理部']) == 1 for root in tree)
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_allows_same_name_root_across_companies(app):
|
||||||
|
"""分支测试意图:两家公司的顶级部门允许同名(按 company 分桶查重),同公司顶级同名仍拒绝。"""
|
||||||
|
with app.app_context():
|
||||||
|
create_department({'name': '管理部', 'company': '苏州和信'})
|
||||||
|
create_department({'name': '管理部', 'company': '泰国合欣'})
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
create_department({'name': '管理部', 'company': '苏州和信'})
|
||||||
|
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_inherits_company_from_parent(app):
|
||||||
|
"""断言:未填公司时继承上级部门 company(公司虚拟分组依赖)。"""
|
||||||
|
with app.app_context():
|
||||||
|
root = create_department({'name': '和信', 'company': '苏州和信'})
|
||||||
|
child = create_department({'name': '财务部', 'parent_id': root['id']})
|
||||||
|
dept = db.session.get(Department, child['id'])
|
||||||
|
assert dept.company == '苏州和信'
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_rejects_duplicate_code(app):
|
||||||
|
"""断言:部门编码全局唯一。"""
|
||||||
|
with app.app_context():
|
||||||
|
create_department({'name': 'A', 'code': 'C1'})
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
create_department({'name': 'B', 'code': 'C1'})
|
||||||
|
assert exc_info.value.code == 'DEPT.CODE_EXISTS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_parent_cycle_rejected(app):
|
||||||
|
"""分支测试意图:把部门挂到自己或自己的子孙下必须被 CYCLE_FORBIDDEN 拦截。"""
|
||||||
|
with app.app_context():
|
||||||
|
root = create_department({'name': 'Root'})
|
||||||
|
child = create_department({'name': 'Child', 'parent_id': root['id']})
|
||||||
|
grand = create_department({'name': 'Grand', 'parent_id': child['id']})
|
||||||
|
assert grand['name'] == 'Grand'
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
update_department(root['id'], {'parent_id': grand['id']})
|
||||||
|
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
update_department(root['id'], {'parent_id': root['id']})
|
||||||
|
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||||
|
|
||||||
|
|
||||||
def test_update_department_not_found(app):
|
def test_update_department_not_found(app):
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
with pytest.raises(NotFoundError):
|
with pytest.raises(NotFoundError):
|
||||||
update_department(99999, {'name': 'X'})
|
update_department(99999, {'name': 'X'})
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_department_with_members_rejected(app):
|
||||||
|
"""断言:名下仍有员工(users.department 文本命中)时删除被 HAS_MEMBERS 拦截。"""
|
||||||
|
with app.app_context():
|
||||||
|
dept = create_department({'name': '品保部'})
|
||||||
|
db.session.add(User(username='u1', email='u1@example.com', department='品保部', role='user', status='active'))
|
||||||
|
db.session.commit()
|
||||||
|
with pytest.raises(ConflictError, match='members'):
|
||||||
|
delete_department(dept['id'])
|
||||||
|
|
||||||
|
|
||||||
|
def test_member_count_tree_rollup_and_members_scope(app):
|
||||||
|
"""断言:树节点 member_count 为直属人数、total_member_count 递归含下级;成员接口按口径过滤。"""
|
||||||
|
with app.app_context():
|
||||||
|
root = create_department({'name': '物料部'})
|
||||||
|
child = create_department({'name': '仓储课', 'parent_id': root['id']})
|
||||||
|
db.session.add_all([
|
||||||
|
User(username='r1', email='r1@example.com', department='物料部', role='user', status='active'),
|
||||||
|
User(username='c1', email='c1@example.com', department='仓储课', role='user', status='active'),
|
||||||
|
User(username='c2', email='c2@example.com', department='仓储课', role='user', status='active'),
|
||||||
|
])
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
tree = list_department_tree()
|
||||||
|
node = tree[0]
|
||||||
|
assert node['member_count'] == 1
|
||||||
|
assert node['total_member_count'] == 3
|
||||||
|
assert node['children'][0]['total_member_count'] == 2
|
||||||
|
|
||||||
|
direct = list_department_members(child['id'])
|
||||||
|
assert direct['total'] == 2
|
||||||
|
subtree = list_department_members(root['id'], include_descendants=True)
|
||||||
|
assert subtree['total'] == 3
|
||||||
|
assert all(member.get('department') in ('物料部', '仓储课') for member in subtree['members'])
|
||||||
|
|
||||||
|
|
||||||
|
def test_members_keyword_search_and_pagination(app):
|
||||||
|
"""分支测试意图:成员接口按 姓名/工号/手机 模糊搜索,并按 page/page_size 分页。"""
|
||||||
|
with app.app_context():
|
||||||
|
dept = create_department({'name': '品保部'})
|
||||||
|
db.session.add_all([
|
||||||
|
User(username='u1', real_name='张一', employee_id='E001', phone_number='13800000001',
|
||||||
|
email='u1@example.com', department='品保部', role='user', status='active'),
|
||||||
|
User(username='u2', real_name='张二', employee_id='E002', phone_number='13800000002',
|
||||||
|
email='u2@example.com', department='品保部', role='user', status='active'),
|
||||||
|
User(username='u3', real_name='李三', employee_id='E003', phone_number='13800000003',
|
||||||
|
email='u3@example.com', department='品保部', role='user', status='active'),
|
||||||
|
])
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# 关键词命中工号
|
||||||
|
by_emp = list_department_members(dept['id'], keyword='E003')
|
||||||
|
assert by_emp['total'] == 1
|
||||||
|
assert by_emp['members'][0]['real_name'] == '李三'
|
||||||
|
# 关键词命中手机号
|
||||||
|
by_phone = list_department_members(dept['id'], keyword='13800000002')
|
||||||
|
assert by_phone['total'] == 1
|
||||||
|
assert by_phone['members'][0]['username'] == 'u2'
|
||||||
|
# 关键词命中姓名(同姓两人)
|
||||||
|
by_name = list_department_members(dept['id'], keyword='张')
|
||||||
|
assert by_name['total'] == 2
|
||||||
|
# 分页:page_size=2 时第 2 页只剩 1 条
|
||||||
|
paged = list_department_members(dept['id'], page=2, page_size=2)
|
||||||
|
assert paged['total'] == 3
|
||||||
|
assert paged['page'] == 2
|
||||||
|
assert len(paged['members']) == 1
|
||||||
@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
|
|||||||
|
|
||||||
用途:验证库存主数据管理服务的安全性和关键业务约束。
|
用途:验证库存主数据管理服务的安全性和关键业务约束。
|
||||||
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
|
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
|
||||||
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -22,6 +22,7 @@ from app.models import (
|
|||||||
FreightRpaSource,
|
FreightRpaSource,
|
||||||
FreightRpaSourceParsingBindingAudit,
|
FreightRpaSourceParsingBindingAudit,
|
||||||
FreightRpaOnhandStructureAnalysis,
|
FreightRpaOnhandStructureAnalysis,
|
||||||
|
FreightRpaProfile,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_profile_credentials_are_not_returned(app):
|
def test_profile_returns_username_and_keeps_password_secret(app):
|
||||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
|
||||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||||
|
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
|
||||||
|
assert payload['username'] == 'test-user'
|
||||||
assert payload['password_configured'] is True
|
assert payload['password_configured'] is True
|
||||||
assert payload['username_masked'] == 'configured'
|
assert payload['username_masked'] == 'configured'
|
||||||
assert 'password' not in payload
|
assert 'password' not in payload
|
||||||
assert 'ciphertext' not in payload
|
assert 'ciphertext' not in payload
|
||||||
|
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||||
|
original_username = stored.username_ciphertext
|
||||||
|
original_password = stored.password_ciphertext
|
||||||
|
original_updated_at = stored.credential_updated_at
|
||||||
|
unchanged = _profile_data()
|
||||||
|
unchanged.pop('password')
|
||||||
|
unchanged['display_name'] = 'DBS EU renamed'
|
||||||
|
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
|
||||||
|
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
|
||||||
|
assert again['username'] == 'test-user'
|
||||||
|
db.session.refresh(stored)
|
||||||
|
assert stored.username_ciphertext == original_username
|
||||||
|
assert stored.password_ciphertext == original_password
|
||||||
|
assert stored.credential_updated_at == original_updated_at
|
||||||
|
assert stored.display_name == 'DBS EU renamed'
|
||||||
|
|
||||||
|
|
||||||
|
def test_profile_username_change_reencrypts_without_touching_password(app):
|
||||||
|
"""只改用户名时重写用户名密文,密码密文保持不变。"""
|
||||||
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||||
|
with app.app_context():
|
||||||
|
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||||
|
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||||
|
original_username = stored.username_ciphertext
|
||||||
|
original_password = stored.password_ciphertext
|
||||||
|
changed = _profile_data()
|
||||||
|
changed.pop('password')
|
||||||
|
changed['username'] = 'other-user'
|
||||||
|
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
|
||||||
|
assert updated['username'] == 'other-user'
|
||||||
|
db.session.refresh(stored)
|
||||||
|
assert stored.username_ciphertext != original_username
|
||||||
|
assert stored.password_ciphertext == original_password
|
||||||
|
|
||||||
|
|
||||||
def test_profile_rejects_page_operation_configuration(app):
|
def test_profile_rejects_page_operation_configuration(app):
|
||||||
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
|||||||
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||||
base_version = profile['config_version']
|
base_version = profile['config_version']
|
||||||
upload_cfg = {
|
upload_cfg = {
|
||||||
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
|
'enabled': True, 'entry_url': 'https://evil.example/steal',
|
||||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
|
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
|
||||||
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
|
|
||||||
}
|
}
|
||||||
updated = freight_rpa_source_admin_service.save_profile(
|
updated = freight_rpa_source_admin_service.save_profile(
|
||||||
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
|
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
|
||||||
)
|
)
|
||||||
assert updated['config_version'] == base_version
|
assert updated['config_version'] == base_version
|
||||||
assert updated['upload_config_json']['enabled'] is True
|
assert updated['upload_config_json'] == {'enabled': True}
|
||||||
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
|
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
|
||||||
bumped = freight_rpa_source_admin_service.save_profile(
|
bumped = freight_rpa_source_admin_service.save_profile(
|
||||||
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
|
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
|
||||||
actor_id=None, profile_id=profile['id'],
|
actor_id=None, profile_id=profile['id'],
|
||||||
)
|
)
|
||||||
assert bumped['config_version'] == base_version + 1
|
assert bumped['config_version'] == base_version + 1
|
||||||
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
|
# 上传配置必须是对象;页面字段不再作为校验对象。
|
||||||
with pytest.raises(ValidationError):
|
with pytest.raises(ValidationError):
|
||||||
freight_rpa_source_admin_service.save_profile(
|
freight_rpa_source_admin_service.save_profile(
|
||||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
{**_profile_data(), 'upload_config_json': 'not-an-object'},
|
||||||
actor_id=None, profile_id=profile['id'],
|
|
||||||
)
|
|
||||||
with pytest.raises(ValidationError):
|
|
||||||
freight_rpa_source_admin_service.save_profile(
|
|
||||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
|
||||||
actor_id=None, profile_id=profile['id'],
|
actor_id=None, profile_id=profile['id'],
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/services/file_assets/test_storage_presign.py
|
||||||
|
|
||||||
|
用途:验证业务文件预签名下载地址使用浏览器可访问的 MinIO 主机。
|
||||||
|
依赖:file_assets.storage、minio。
|
||||||
|
逻辑:正式环境内网端点与公网基址不同;断言签名 URL 的主机是公网基址,读写客户端仍是内网端点。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.services.file_assets import storage as storage_mod
|
||||||
|
from app.services.file_assets.storage import resolve_presign_endpoint
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.pure_unit
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_minio_config(monkeypatch, *, public_base: str, secure: bool = False) -> None:
|
||||||
|
"""把存储配置钉成正式环境形态:容器内网端点 + 浏览器公网基址。"""
|
||||||
|
monkeypatch.setattr(storage_mod._cfg, "MINIO_ENDPOINT", "host.docker.internal:9000")
|
||||||
|
monkeypatch.setattr(storage_mod._cfg, "MINIO_ACCESS_KEY", "test-access")
|
||||||
|
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECRET_KEY", "test-secret")
|
||||||
|
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECURE", secure)
|
||||||
|
monkeypatch.setattr(storage_mod._cfg, "MINIO_PUBLIC_BASE_URL", public_base)
|
||||||
|
monkeypatch.setattr(storage_mod._cfg, "MINIO_FILE_ASSETS_BUCKET", "hxops-file-assets")
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_presign_endpoint_keeps_explicit_port():
|
||||||
|
"""公网基址的非默认端口必须留在预签名端点里。"""
|
||||||
|
endpoint, secure = resolve_presign_endpoint(
|
||||||
|
"http://ai.well-trust.com:9000",
|
||||||
|
"host.docker.internal:9000",
|
||||||
|
False,
|
||||||
|
)
|
||||||
|
# [断言意图] 正式环境浏览器入口是 9000,不能收成 80。
|
||||||
|
assert endpoint == "ai.well-trust.com:9000"
|
||||||
|
assert secure is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_presign_endpoint_falls_back_when_public_base_empty():
|
||||||
|
"""公网基址为空时继续用内网端点,避免签出空主机。"""
|
||||||
|
endpoint, secure = resolve_presign_endpoint("", "192.168.100.192:9000", False)
|
||||||
|
# [断言意图] 未配置公网基址时行为与改前一致。
|
||||||
|
assert endpoint == "192.168.100.192:9000"
|
||||||
|
assert secure is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_presigned_get_url_uses_public_host(monkeypatch):
|
||||||
|
"""正式环境下载链接的主机必须是 MINIO_PUBLIC_BASE_URL。"""
|
||||||
|
_patch_minio_config(monkeypatch, public_base="http://ai.well-trust.com:9000")
|
||||||
|
store = storage_mod.FileAssetStorage()
|
||||||
|
monkeypatch.setattr(store, "_ensure_bucket_exists", lambda: None)
|
||||||
|
|
||||||
|
url = store.presigned_get_url(
|
||||||
|
"shipping/outbound-reports/2026/10/1/abc.xlsx",
|
||||||
|
expires_seconds=300,
|
||||||
|
download_name="CRANE_20261020_1815.xlsx",
|
||||||
|
)
|
||||||
|
|
||||||
|
# [断言意图] 浏览器打开的是公网 MinIO,签名里不能再出现容器内网主机。
|
||||||
|
assert url.startswith(
|
||||||
|
"http://ai.well-trust.com:9000/hxops-file-assets/shipping/outbound-reports/2026/10/1/abc.xlsx?"
|
||||||
|
)
|
||||||
|
assert "host.docker.internal" not in url
|
||||||
|
assert "X-Amz-Signature=" in url
|
||||||
|
assert "response-content-disposition=" in url
|
||||||
|
# [断言意图] 读写仍走容器内网端点,避免把公网主机写进上传客户端。
|
||||||
|
assert store.client is not store.presign_client
|
||||||
|
assert store.client._base_url.host == "host.docker.internal:9000"
|
||||||
|
assert store.presign_client._base_url.host == "ai.well-trust.com:9000"
|
||||||
|
|
||||||
|
|
||||||
|
def test_presigned_get_url_reuses_client_when_hosts_match(monkeypatch):
|
||||||
|
"""内网端点与公网基址相同时不另建客户端。"""
|
||||||
|
_patch_minio_config(monkeypatch, public_base="http://host.docker.internal:9000")
|
||||||
|
store = storage_mod.FileAssetStorage()
|
||||||
|
# [断言意图] 开发环境两端点一致,预签名与读写共用同一客户端。
|
||||||
|
assert store.presign_client is store.client
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
|
||||||
|
|
||||||
|
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
|
||||||
|
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
|
||||||
|
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.errors import ConflictError
|
||||||
|
from app.services.freight_rpa.upload.crane_recheck import (
|
||||||
|
fire_scheduled_crane_recheck,
|
||||||
|
request_manual_crane_refresh,
|
||||||
|
)
|
||||||
|
from app.services.freight_rpa.upload.page_contract import (
|
||||||
|
build_upload_entry_url,
|
||||||
|
classify_crane_order_row,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.upload_attempt_service import (
|
||||||
|
complete_attempt,
|
||||||
|
project_notice_upload_status,
|
||||||
|
start_rpa_attempt,
|
||||||
|
)
|
||||||
|
from tests.test_shipping_upload_attempt import _ready_artifact
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
|
||||||
|
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
|
||||||
|
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
|
||||||
|
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
|
||||||
|
)
|
||||||
|
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
|
||||||
|
'https://wms-portal.craneww.com/#/shipping-order-upload'
|
||||||
|
)
|
||||||
|
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
|
||||||
|
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
|
||||||
|
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
|
||||||
|
|
||||||
|
|
||||||
|
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
|
||||||
|
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
|
||||||
|
with app.app_context():
|
||||||
|
notice, artifact, _reservation = _ready_artifact()
|
||||||
|
artifact.file_name = 'MXI26082801.xlsx'
|
||||||
|
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
|
||||||
|
started = datetime(2026, 10, 23, 3, 0, 0)
|
||||||
|
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
|
||||||
|
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
|
||||||
|
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
|
||||||
|
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
|
||||||
|
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||||
|
assert project_notice_upload_status(notice) == 'allocating'
|
||||||
|
|
||||||
|
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
|
||||||
|
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
|
||||||
|
|
||||||
|
with pytest.raises(ConflictError) as blocked:
|
||||||
|
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
|
||||||
|
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
|
||||||
|
assert started < due_at
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
|
||||||
|
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
|
||||||
|
with app.app_context():
|
||||||
|
notice, artifact, _reservation = _ready_artifact()
|
||||||
|
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
|
||||||
|
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
|
||||||
|
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
|
||||||
|
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
|
||||||
|
|
||||||
|
first = request_manual_crane_refresh(
|
||||||
|
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||||
|
)
|
||||||
|
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
|
||||||
|
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||||
|
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||||
|
|
||||||
|
with pytest.raises(ConflictError) as inflight:
|
||||||
|
request_manual_crane_refresh(
|
||||||
|
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||||
|
)
|
||||||
|
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
|
||||||
|
|
||||||
|
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
|
||||||
|
assert fire_scheduled_crane_recheck(
|
||||||
|
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||||
|
) is True
|
||||||
|
assert fire_scheduled_crane_recheck(
|
||||||
|
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||||
|
) is False
|
||||||
|
db.session.refresh(attempt)
|
||||||
|
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||||
|
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
|
||||||
@@ -1,16 +1,18 @@
|
|||||||
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
|
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
|
||||||
|
|
||||||
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
|
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
|
||||||
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
|
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
|
||||||
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
|
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
|
||||||
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
|
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
|
||||||
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
|
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
|
||||||
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
|
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
|
||||||
外部系统 单号投影。
|
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
|
||||||
|
执行入口(execute_matching_items)与按外部系统单号投影。
|
||||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
||||||
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
|
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
|
||||||
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
|
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
|
||||||
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
|
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
|
||||||
|
matching_service 命名空间)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
|
|||||||
RouteMapping,
|
RouteMapping,
|
||||||
TransferDeps,
|
TransferDeps,
|
||||||
create_matching,
|
create_matching,
|
||||||
|
list_executable_items,
|
||||||
)
|
)
|
||||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
||||||
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
|
|||||||
assert _execution_runs() == []
|
assert _execution_runs() == []
|
||||||
|
|
||||||
|
|
||||||
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
|
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
|
||||||
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
|
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
|
||||||
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
|
):
|
||||||
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
|
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
|
||||||
|
|
||||||
|
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
|
||||||
|
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
|
||||||
|
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
|
||||||
|
"""
|
||||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||||
|
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
|
||||||
|
# 消费方),此处同步打桩保持与执行侧替身同源。
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||||
|
lambda *, source_code, record_kind="inbound": {
|
||||||
|
"file_status": "ready", "has_ready_file": True,
|
||||||
|
"file_no": "REC-TEST", "file_sha256": "e" * 64,
|
||||||
|
},
|
||||||
|
)
|
||||||
deps, erp, items = _ready_items(
|
deps, erp, items = _ready_items(
|
||||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||||
)
|
)
|
||||||
|
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
|
||||||
|
listing = list_executable_items(deps=deps)
|
||||||
|
decorated = {row.item_id: row for row in listing["items"]}
|
||||||
|
assert all(decorated[item.id].file_current is False for item in items)
|
||||||
|
|
||||||
with pytest.raises(ValidationError) as excinfo:
|
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
|
||||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
assert outcome.status == "success"
|
||||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
assert len(erp.write_calls()) == 1
|
||||||
assert erp.write_calls() == []
|
linked = _load_items(outcome.run_no)
|
||||||
assert _execution_runs() == []
|
assert all(item.status == "success" for item in linked.values())
|
||||||
|
|
||||||
|
|
||||||
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||||
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
|
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
|
||||||
|
|
||||||
|
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
|
||||||
|
"""
|
||||||
patch_source_file_status({"DBS-AWSBI": None})
|
patch_source_file_status({"DBS-AWSBI": None})
|
||||||
deps, erp, items = _ready_items(
|
deps, erp, items = _ready_items(
|
||||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||||
)
|
)
|
||||||
|
|
||||||
with pytest.raises(ValidationError) as excinfo:
|
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
|
||||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
assert outcome.status == "success"
|
||||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
assert len(erp.write_calls()) == 1
|
||||||
assert erp.write_calls() == []
|
linked = _load_items(outcome.run_no)
|
||||||
|
assert all(item.status == "success" for item in linked.values())
|
||||||
|
|
||||||
|
|
||||||
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
||||||
|
|
||||||
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
|
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
|
||||||
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
|
匹配快照 Hash 稳定、缺文件等待与进度恢复、匹配顶替;专项用例锁生产默认 lag=2。
|
||||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||||
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
|
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
|
||||||
@@ -1152,3 +1152,182 @@ def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file):
|
|||||||
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||||
assert len(born) == 2
|
assert len(born) == 2
|
||||||
assert all(row.status == "ready_to_execute" for row in born)
|
assert all(row.status == "ready_to_execute" for row in born)
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_matching_supersedes_covered_unwritten_matching(transfer_db, dbs_ready_file):
|
||||||
|
"""新匹配盖住同一类型、同一来源、尚未写 ERP 的旧匹配时,旧匹配取消,货出现在新匹配上。
|
||||||
|
|
||||||
|
夹具两行异动日都是 2026-08-04。第一次与第二次都用 08-01~08-04,新范围盖住旧范围。
|
||||||
|
"""
|
||||||
|
from app.models import TransferInvoiceItem, TransferMatching
|
||||||
|
|
||||||
|
deps, erp, _ = _deps(dbs_ready_file)
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||||
|
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
covered = dict(
|
||||||
|
source_codes=["DBS-AWSBI"],
|
||||||
|
business_date="2026-08-06",
|
||||||
|
transfer_type="in_transit_to_hub",
|
||||||
|
movement_date_from="2026-08-01",
|
||||||
|
movement_date_to="2026-08-04",
|
||||||
|
)
|
||||||
|
|
||||||
|
first = create_matching(deps=deps, **covered)
|
||||||
|
# [断言意图] 顶替前旧匹配自己先圈到夹具的两张单,证明后面的 2 不是「本来就没占上」。
|
||||||
|
assert first.counts.executable_count == 2
|
||||||
|
|
||||||
|
second = create_matching(deps=deps, **covered)
|
||||||
|
|
||||||
|
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||||
|
# [断言意图] 被盖住且未写 ERP 的旧匹配不再有效,其可执行行不能留在队列里二次写 ERP。
|
||||||
|
assert first_matching.status == "cancelled"
|
||||||
|
retired = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id).all()
|
||||||
|
assert retired
|
||||||
|
assert all(row.status == "cancelled" for row in retired)
|
||||||
|
# [断言意图] 同一批货(HOM-001、HOX-002)出现在新匹配上,且仍可执行。
|
||||||
|
assert second.counts.executable_count == 2
|
||||||
|
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||||
|
reborn = {
|
||||||
|
row.invoice_no
|
||||||
|
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||||
|
}
|
||||||
|
assert reborn == {"HOM-001", "HOX-002"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_matching_supersedes_covered_matching_with_only_blocked_rows(transfer_db, dbs_ready_file):
|
||||||
|
"""全阻断的旧匹配状态虽是 success,只要还没写 ERP,新范围盖住时仍要顶替。"""
|
||||||
|
from app.models import TransferInvoiceItem, TransferMatching
|
||||||
|
|
||||||
|
deps, erp, _ = _deps(dbs_ready_file)
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1")
|
||||||
|
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
covered = dict(
|
||||||
|
source_codes=["DBS-AWSBI"],
|
||||||
|
business_date="2026-08-06",
|
||||||
|
transfer_type="in_transit_to_hub",
|
||||||
|
movement_date_from="2026-08-01",
|
||||||
|
movement_date_to="2026-08-04",
|
||||||
|
)
|
||||||
|
first = create_matching(deps=deps, **covered)
|
||||||
|
# [断言意图] 数量对不上时匹配状态是 success,不能因此被当成「已经写出单据」。
|
||||||
|
assert first.status == "success"
|
||||||
|
assert first.counts.executable_count == 0
|
||||||
|
|
||||||
|
second = create_matching(deps=deps, **covered)
|
||||||
|
|
||||||
|
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||||
|
assert first_matching.status == "cancelled"
|
||||||
|
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||||
|
reborn = {
|
||||||
|
row.invoice_no
|
||||||
|
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||||
|
}
|
||||||
|
assert reborn == {"HOM-001", "HOX-002"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_matching_keeps_previous_when_new_range_does_not_cover(transfer_db, dbs_ready_file):
|
||||||
|
"""新范围盖不住旧范围时,旧匹配保持有效,货仍留在旧匹配上。"""
|
||||||
|
from app.models import TransferMatching
|
||||||
|
|
||||||
|
deps, erp, _ = _deps(dbs_ready_file)
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||||
|
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
first = create_matching(
|
||||||
|
source_codes=["DBS-AWSBI"],
|
||||||
|
business_date="2026-08-06",
|
||||||
|
deps=deps,
|
||||||
|
transfer_type="in_transit_to_hub",
|
||||||
|
movement_date_from="2026-08-01",
|
||||||
|
movement_date_to="2026-08-04",
|
||||||
|
)
|
||||||
|
second = create_matching(
|
||||||
|
source_codes=["DBS-AWSBI"],
|
||||||
|
business_date="2026-08-06",
|
||||||
|
deps=deps,
|
||||||
|
transfer_type="in_transit_to_hub",
|
||||||
|
movement_date_from="2026-08-04",
|
||||||
|
movement_date_to="2026-08-04",
|
||||||
|
)
|
||||||
|
|
||||||
|
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||||
|
# [断言意图] 08-04~08-04 盖不住 08-01~08-04,旧匹配不能被取消。
|
||||||
|
assert first_matching.status == "ready_to_execute"
|
||||||
|
# [断言意图] 货仍被旧匹配占用,新匹配圈不到,清单不另列历史匹配编号。
|
||||||
|
assert second.counts.executable_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_supersede_keeps_manually_closed_goods_out_of_the_new_matching(transfer_db, dbs_ready_file):
|
||||||
|
"""顶替后,人工关闭的单号不回到新匹配。"""
|
||||||
|
from app.models import TransferInvoiceItem, TransferMatching
|
||||||
|
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||||
|
|
||||||
|
deps, erp, _ = _deps(dbs_ready_file)
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||||
|
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
covered = dict(
|
||||||
|
source_codes=["DBS-AWSBI"],
|
||||||
|
business_date="2026-08-06",
|
||||||
|
transfer_type="in_transit_to_hub",
|
||||||
|
movement_date_from="2026-08-01",
|
||||||
|
movement_date_to="2026-08-04",
|
||||||
|
)
|
||||||
|
first = create_matching(deps=deps, **covered)
|
||||||
|
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||||
|
closed = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id, invoice_no="HOX-002").one()
|
||||||
|
manual_close_item(item_id=closed.id, reason="这批不再调拨")
|
||||||
|
|
||||||
|
second = create_matching(deps=deps, **covered)
|
||||||
|
|
||||||
|
# [断言意图] 人工关闭跨过顶替仍然有效,新匹配不能把 HOX-002 再圈成可执行。
|
||||||
|
assert db.session.get(TransferInvoiceItem, closed.id).status == "manually_closed"
|
||||||
|
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||||
|
reborn = {
|
||||||
|
row.invoice_no
|
||||||
|
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||||
|
}
|
||||||
|
assert reborn == {"HOM-001"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_unattached_item_does_not_block_a_new_matching(transfer_db, dbs_ready_file):
|
||||||
|
"""没有挂上任何匹配的明细不占货,新匹配仍能圈到那张单。"""
|
||||||
|
from app.models import TransferInvoiceItem, TransferMatching, TransferMovementLedger
|
||||||
|
|
||||||
|
deps, erp, _ = _deps(dbs_ready_file)
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||||
|
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
ledger = TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI", doc_no="HOM-001").first()
|
||||||
|
db.session.add(TransferInvoiceItem(
|
||||||
|
matching_id=None,
|
||||||
|
ledger_record_id=ledger.id,
|
||||||
|
source_code="DBS-AWSBI",
|
||||||
|
invoice_no="HOM-001",
|
||||||
|
material_no="MAT-001",
|
||||||
|
movement_date="2026-08-04",
|
||||||
|
from_warehouse="DBS-TRANSIT",
|
||||||
|
to_warehouse="HUB-CN01",
|
||||||
|
movement_quantity="1200",
|
||||||
|
status="matching",
|
||||||
|
result_code="pending_stock_check",
|
||||||
|
))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
summary = create_matching(
|
||||||
|
source_codes=["DBS-AWSBI"],
|
||||||
|
business_date="2026-08-06",
|
||||||
|
deps=deps,
|
||||||
|
transfer_type="in_transit_to_hub",
|
||||||
|
movement_date_from="2026-08-01",
|
||||||
|
movement_date_to="2026-08-04",
|
||||||
|
)
|
||||||
|
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
|
||||||
|
# [断言意图] 悬挂行没有匹配编号,不能挡住 HOM-001;两张夹具单都进新匹配。
|
||||||
|
invoices = {
|
||||||
|
row.invoice_no
|
||||||
|
for row in TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||||
|
}
|
||||||
|
assert invoices == {"HOM-001", "HOX-002"}
|
||||||
@@ -3,14 +3,20 @@
|
|||||||
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
||||||
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
||||||
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
||||||
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
|
依赖:schedule.job_registry、job_options、inbound_trigger_service、
|
||||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
transfer_type_config_service、in_transit_transfer_job。
|
||||||
|
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
|
||||||
|
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
|
||||||
|
skipped, results, errors, step_logs),errors 位只放真实错误。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
|
||||||
|
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
|
||||||
|
from app.services.schedule.job_options import is_known_options_source
|
||||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||||
|
|
||||||
|
|
||||||
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
|
|||||||
|
|
||||||
|
|
||||||
def test_transfer_job_registered_with_schedule_defaults():
|
def test_transfer_job_registered_with_schedule_defaults():
|
||||||
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
|
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||||
import re
|
import re
|
||||||
|
|
||||||
job = get_platform_job("in-transit-transfer")
|
job = get_platform_job("in-transit-transfer")
|
||||||
assert job is not None
|
assert job is not None
|
||||||
assert job.enabled
|
assert job.enabled
|
||||||
keys = {field.get("key") for field in job.params_schema}
|
keys = {field.get("key") for field in job.params_schema}
|
||||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
assert {
|
||||||
|
"transfer_types", "source_codes", "recover_history",
|
||||||
|
"receipt_from_offset_days", "receipt_to_offset_days",
|
||||||
|
} <= keys
|
||||||
|
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
|
||||||
|
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
|
||||||
|
assert types_field.get("type") == "multi_select"
|
||||||
|
assert types_field.get("options_source") == "transfer_types"
|
||||||
|
assert types_field.get("default") == []
|
||||||
|
assert is_known_options_source("transfer_types")
|
||||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||||
assert "notify_user_ids" not in keys
|
assert "notify_user_ids" not in keys
|
||||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||||
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
|||||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||||
|
|
||||||
|
|
||||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
|
||||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
|
||||||
|
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||||
|
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
|
||||||
|
|
||||||
|
errors: list[str] = []
|
||||||
|
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
|
||||||
|
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
|
||||||
|
])
|
||||||
|
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
|
||||||
|
assert errors == []
|
||||||
|
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
|
||||||
|
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
|
||||||
|
|
||||||
|
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
|
||||||
|
assert _wanted_transfer_types({}, errors) == []
|
||||||
|
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
|
||||||
|
assert errors and "调拨类型" in errors[-1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
|
||||||
|
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
|
||||||
|
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
|
||||||
|
from app.services.schedule.job_options import list_job_options
|
||||||
|
|
||||||
|
seed_transfer_type_config("in_transit_to_hub", enabled=True)
|
||||||
|
seed_transfer_type_config("hub_repair_out", enabled=False)
|
||||||
|
transfer_db.session.commit()
|
||||||
|
|
||||||
|
options = list_job_options("transfer_types")
|
||||||
|
codes = {option["value"] for option in options}
|
||||||
|
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
|
||||||
|
assert "in_transit_to_hub" in codes
|
||||||
|
assert "hub_repair_out" not in codes
|
||||||
|
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
|
||||||
|
assert label == "类型 in_transit_to_hub"
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
|
||||||
|
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
|
||||||
|
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
|
||||||
|
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||||
|
monkeypatch.setattr(
|
||||||
|
type_mod, "get_enabled",
|
||||||
|
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
|
||||||
|
)
|
||||||
|
return job_mod
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||||
|
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||||
captured = {}
|
captured = {}
|
||||||
|
|
||||||
def _fake_auto_transfer(**kwargs):
|
def _fake_auto_transfer(**kwargs):
|
||||||
captured.update(kwargs)
|
captured.update(kwargs)
|
||||||
return job_mod.AutoTransferOutcome()
|
return AutoTransferOutcome()
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
|
||||||
|
|
||||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
total, success, failed, skipped, results, errors, step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
|
||||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
|
||||||
assert "sender" not in captured
|
assert captured["recover_history"] is False
|
||||||
assert "recipients" not in captured
|
|
||||||
assert captured["movement_date_from"] is None
|
assert captured["movement_date_from"] is None
|
||||||
assert captured["movement_date_to"] is None
|
assert captured["movement_date_to"] is None
|
||||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||||
assert captured["recover_history"] is True
|
assert captured["transfer_type"] == "in_transit_to_hub"
|
||||||
assert run.response_summary_json["domain_notification_managed"] is True
|
assert run.response_summary_json["domain_notification_managed"] is True
|
||||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||||
assert results == []
|
assert results == [] and errors == []
|
||||||
assert any("no executable items" in w for w in warnings)
|
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
|
||||||
|
assert step_logs[0]["step"] == "recovery"
|
||||||
|
assert any(item.get("step") == "auto_transfer" for item in step_logs)
|
||||||
|
|
||||||
|
|
||||||
def test_handler_converts_t_minus_offsets(monkeypatch):
|
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||||
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||||
captured = {}
|
captured = {}
|
||||||
|
|
||||||
def _fake_auto_transfer(**kwargs):
|
def _fake_auto_transfer(**kwargs):
|
||||||
captured.update(kwargs)
|
captured.update(kwargs)
|
||||||
return job_mod.AutoTransferOutcome()
|
return AutoTransferOutcome()
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
|
||||||
|
|
||||||
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||||
run = ScheduleRun(run_no="RUNR-4", status="running")
|
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||||
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
|||||||
|
|
||||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||||
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
|
||||||
def _must_not_run(**kwargs):
|
def _must_not_run(**kwargs):
|
||||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
|
||||||
|
|
||||||
run = ScheduleRun(run_no="RUNR-5", status="running")
|
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||||
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
)
|
)
|
||||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
|
||||||
|
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
|
||||||
|
assert (total, failed) == (1, 1)
|
||||||
assert results == []
|
assert results == []
|
||||||
assert any("异动日期起点" in e for e in errors)
|
assert any("异动日期起点" in e for e in errors)
|
||||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
|
|
||||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
|
||||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
)
|
)
|
||||||
# 断言:小数偏移同样快速失败。
|
# 断言:小数偏移同样快速失败。
|
||||||
assert any("异动日期终点" in e for e in errors)
|
assert any("异动日期终点" in e for e in errors)
|
||||||
|
|
||||||
|
|
||||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
|
||||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
|
||||||
|
recovery_calls: list[dict] = []
|
||||||
|
|
||||||
|
def _fake_recovery(**kwargs):
|
||||||
|
recovery_calls.append(kwargs)
|
||||||
|
return RecoveryOutcome(recovered_count=2)
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
|
||||||
|
calls: list[dict] = []
|
||||||
|
|
||||||
def _fake_auto_transfer(**kwargs):
|
def _fake_auto_transfer(**kwargs):
|
||||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
calls.append(kwargs)
|
||||||
|
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
|
||||||
|
run = ScheduleRun(run_no="RUNR-6", status="running")
|
||||||
|
total, success, failed, skipped, results, errors, step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
|
||||||
|
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
|
||||||
|
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
|
||||||
|
assert all(c["recover_history"] is False for c in calls)
|
||||||
|
assert len(recovery_calls) == 1
|
||||||
|
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
|
||||||
|
assert (total, success, failed, skipped) == (4, 2, 0, 0)
|
||||||
|
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
|
||||||
|
assert errors == []
|
||||||
|
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
|
||||||
|
assert step_logs[0]["step"] == "recovery"
|
||||||
|
assert step_logs[0]["detail"]["recovered"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_empty_type_config_fails_hard(monkeypatch):
|
||||||
|
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
job_mod = _patch_schedule_env(monkeypatch, types=[])
|
||||||
|
|
||||||
|
def _must_not_run(**kwargs):
|
||||||
|
raise AssertionError("run_auto_transfer must not run without transfer types")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={})
|
||||||
|
run = ScheduleRun(run_no="RUNR-7", status="running")
|
||||||
|
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
|
||||||
|
assert (total, failed) == (1, 1)
|
||||||
|
assert results == []
|
||||||
|
assert any("调拨类型" in e for e in errors)
|
||||||
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||||
|
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||||
|
|
||||||
|
def _fake_auto_transfer(**kwargs):
|
||||||
|
return AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
|
||||||
|
|
||||||
task = ScheduleTask(job_params={})
|
task = ScheduleTask(job_params={})
|
||||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
total, success, failed, skipped, results, errors, _step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
|
||||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
|
||||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
assert results and results[0]["run_no"] == "TR-1"
|
assert results and results[0]["run_no"] == "TR-1"
|
||||||
|
assert results[0]["transfer_type"] == "in_transit_to_hub"
|
||||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||||
assert errors == []
|
assert errors == []
|
||||||
|
|
||||||
|
|
||||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
|
||||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
|
||||||
|
def _boom(**_kwargs):
|
||||||
|
raise RuntimeError("stock source offline")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
|
||||||
|
|
||||||
def _fake_auto_transfer(**kwargs):
|
def _fake_auto_transfer(**kwargs):
|
||||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={})
|
||||||
|
run = ScheduleRun(run_no="RUNR-9", status="running")
|
||||||
|
total, success, failed, _skipped, results, errors, step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
|
||||||
|
# 恢复 step_log 标 failed;不置静默标记。
|
||||||
|
assert (total, success, failed) == (1, 0, 1)
|
||||||
|
assert results == []
|
||||||
|
assert errors == ["recovery_failed: stock source offline"]
|
||||||
|
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
|
||||||
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
|
||||||
|
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
|
||||||
|
def _must_not_recover(**_kwargs):
|
||||||
|
raise AssertionError("run_daily_recovery must not run when recover_history is false")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
job_mod, "run_auto_transfer",
|
||||||
|
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
|
||||||
|
)
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={"recover_history": False})
|
||||||
|
run = ScheduleRun(run_no="RUNR-10", status="running")
|
||||||
|
total, success, failed, _skipped, results, errors, step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
|
||||||
|
assert (total, success, failed) == (1, 1, 0)
|
||||||
|
assert results and results[0]["run_no"] == "TR-10"
|
||||||
|
assert errors == []
|
||||||
|
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||||
|
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
job_mod = _patch_schedule_env(monkeypatch)
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||||
|
|
||||||
|
def _fake_auto_transfer(**kwargs):
|
||||||
|
return AutoTransferOutcome(errors=["match pipeline boom"])
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
|
||||||
|
|
||||||
task = ScheduleTask(job_params={})
|
task = ScheduleTask(job_params={})
|
||||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
_total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
|
||||||
|
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
|
||||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
assert results == []
|
assert results == []
|
||||||
assert errors == ["match pipeline boom"]
|
assert errors == ["match pipeline boom"]
|
||||||
|
assert failed == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_type_failure_isolated_per_type(monkeypatch):
|
||||||
|
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
|
||||||
|
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||||
|
|
||||||
|
def _fake_auto_transfer(**kwargs):
|
||||||
|
if kwargs["transfer_type"] == "bad_type":
|
||||||
|
return AutoTransferOutcome(errors=["type config disabled"])
|
||||||
|
return AutoTransferOutcome(run_no="TR-9", run_status="success")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={})
|
||||||
|
run = ScheduleRun(run_no="RUNR-8", status="running")
|
||||||
|
total, success, failed, _skipped, results, errors, _step_logs = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
|
||||||
|
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
|
||||||
|
assert (total, success, failed) == (2, 1, 1)
|
||||||
|
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
|
||||||
|
assert errors == ["type config disabled"]
|
||||||
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user