Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c48329d4e | ||
|
|
b032bb6729 | ||
|
|
47ff0107bd | ||
|
|
8cd8012632 |
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`。
|
||||||
- 字号和颜色用 `shared/styles/element-theme.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
- 字号和颜色用 `element-trial.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-theme.css`;管理列表用 `element-trial.css`(已包含全站皮肤)。不要再包 `ElConfigProvider`。
|
- [ ] 只在该页入口引入 Element 样式和 `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,10 +101,6 @@ 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/tree 树、成员名单(支持含下级)。
|
逻辑:/departments* 路由。
|
||||||
"""
|
"""
|
||||||
from flask import jsonify, request
|
from flask import jsonify, request
|
||||||
|
|
||||||
@@ -15,17 +15,10 @@ 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():
|
||||||
@@ -38,15 +31,8 @@ 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 搜姓名/工号/邮箱/手机。"""
|
"""返回部门员工数量与名单。"""
|
||||||
include_descendants = request.args.get('include_descendants', '') in ('1', 'true')
|
return jsonify(department_service.list_department_members(id))
|
||||||
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,9 +5,7 @@ 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 urllib.parse import quote
|
from flask import jsonify, request
|
||||||
|
|
||||||
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
|
||||||
@@ -136,15 +134,3 @@ 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
|
|
||||||
@@ -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, capability_list, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
from . import assets, 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,
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
"""
|
|
||||||
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,9 +2,8 @@
|
|||||||
backend/app/api/equipment_acceptance/__init__.py
|
backend/app/api/equipment_acceptance/__init__.py
|
||||||
|
|
||||||
用途:设备验收预警的 Chat 作业面接口。
|
用途:设备验收预警的 Chat 作业面接口。
|
||||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应、jobs.queue。
|
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
||||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;
|
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||||
同步、扫描、发送和保存配置仅平台管理员。扫描与发送改为入队,由 schedule worker 执行,避免 HTTP 504。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -13,17 +12,15 @@ 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, NotFoundError, UnauthorizedError
|
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.jobs.queue import enqueue
|
from app.models import Agent
|
||||||
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,
|
||||||
@@ -31,11 +28,6 @@ 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"
|
||||||
|
|
||||||
@@ -118,7 +110,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 按状态分组,keyword 查三种单号,applicant 查申请人。"""
|
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
||||||
_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)
|
||||||
@@ -127,8 +119,6 @@ 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))
|
||||||
|
|
||||||
@@ -157,79 +147,16 @@ 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"])
|
||||||
|
|||||||
@@ -7,10 +7,9 @@ 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, IntegrityError, OperationalError
|
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, GeneralFeedbackImage, ChatLog
|
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, 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
|
||||||
@@ -33,11 +32,6 @@ 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()
|
||||||
@@ -167,46 +161,9 @@ 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.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()
|
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)
|
||||||
|
|||||||
@@ -4,20 +4,17 @@ 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 io import BytesIO
|
from flask import Blueprint, request
|
||||||
|
|
||||||
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, NotFoundError, UnauthorizedError, ValidationError
|
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.models import Agent, ScheduleRun, VoucherCheckRun
|
from app.models import Agent
|
||||||
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__)
|
||||||
@@ -152,13 +149,12 @@ 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 与 invoice_no 过滤,并返回 by_file_type。
|
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 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,
|
||||||
)
|
)
|
||||||
@@ -181,33 +177,6 @@ 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,7 +7,6 @@ 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,
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
"""
|
|
||||||
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,23 +109,6 @@ 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:
|
||||||
@@ -166,22 +149,13 @@ 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
|
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
|
||||||
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,9 +42,6 @@ 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'
|
||||||
@@ -87,13 +84,7 @@ 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': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
||||||
'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,15 +9,8 @@ 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, user_permission_roles
|
from app.models.permission_role import PermissionRole, permission_role_agents
|
||||||
from app.models.chat import (
|
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||||
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
|
||||||
@@ -274,7 +267,6 @@ __all__ = [
|
|||||||
'Base',
|
'Base',
|
||||||
'user_agent_permissions',
|
'user_agent_permissions',
|
||||||
'permission_role_agents',
|
'permission_role_agents',
|
||||||
'user_permission_roles',
|
|
||||||
'PermissionRole',
|
'PermissionRole',
|
||||||
'ZlLanguage',
|
'ZlLanguage',
|
||||||
'Department',
|
'Department',
|
||||||
@@ -288,7 +280,6 @@ __all__ = [
|
|||||||
'ChatToolRun',
|
'ChatToolRun',
|
||||||
'Feedback',
|
'Feedback',
|
||||||
'GeneralFeedback',
|
'GeneralFeedback',
|
||||||
'GeneralFeedbackImage',
|
|
||||||
'PermissionRequest',
|
'PermissionRequest',
|
||||||
'QuickQuestion',
|
'QuickQuestion',
|
||||||
'FaqHotCandidate',
|
'FaqHotCandidate',
|
||||||
|
|||||||
@@ -135,22 +135,3 @@ 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,40 +1,27 @@
|
|||||||
"""
|
"""
|
||||||
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 Boolean, ForeignKey, String, Text
|
from sqlalchemy import String, Text
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
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 仅要求「同一上级下不重名」(由 department_service 校验),不再全局唯一,
|
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||||
# 以支持多公司存在同名部门(如各公司均有「管理部」)。
|
|
||||||
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。
|
||||||
逻辑:同步服务按来源 oa_system 加流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||||
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
||||||
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||||
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
||||||
保存流程编号和标题。不保存第二合同编号、验收日期和 isremark。
|
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -22,34 +22,18 @@ 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("oa_system", "request_id", name="uq_equipment_acceptance_orders_oa_request"),
|
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||||
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(
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
models/permission_role.py
|
models/permission_role.py
|
||||||
|
|
||||||
用途:可配置权限组(角色包)、角色与 Agent、用户与角色的授权关系。
|
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
||||||
依赖:models.base.Base、agents、users。
|
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
||||||
逻辑:Admin 角色配置读写本表;一个用户可挂多个业务角色,经 user_permission_roles 关联。
|
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
||||||
users.role 只保留排序最前的主角色,供旧查询兼容;运行时按全部角色取并集后再同步到 user_agent_permissions。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -25,12 +24,6 @@ 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,8 +3,7 @@ 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;与权限组多对多经 user_permission_roles。
|
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
|
||||||
users.role 是主角色。已挂多个业务角色时,功能权限与应用入口取并集。
|
|
||||||
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -18,7 +17,6 @@ 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):
|
||||||
@@ -79,10 +77,6 @@ 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)
|
||||||
@@ -124,7 +118,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
|
||||||
@@ -170,14 +164,13 @@ 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 role_auth_payload
|
from app.services.permission_roles.service import list_role_name_map
|
||||||
|
|
||||||
payload = role_auth_payload(self)
|
names = list_role_name_map()
|
||||||
return {
|
return {
|
||||||
'is_platform_admin': self.is_platform_admin(),
|
'is_platform_admin': self.is_platform_admin(),
|
||||||
'role_name': payload['role_name'],
|
'role_name': names.get(self.role) or self.role,
|
||||||
'role_codes': payload['role_codes'],
|
|
||||||
'feature_permissions': self.get_feature_permissions(),
|
'feature_permissions': self.get_feature_permissions(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,206 +1,59 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/admin/department_service.py
|
backend/app/services/admin/department_service.py
|
||||||
|
|
||||||
用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
|
用途:管理端部门 CRUD 业务编排。
|
||||||
依赖:models.Department、models.User、app.core.errors。
|
依赖:models.Department、app.core.errors。
|
||||||
逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
|
逻辑:由 api/admin/departments.py 调用。
|
||||||
树顶公司层不入库,由前端按 company 字段虚拟分组。
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections import defaultdict
|
from typing import Any
|
||||||
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 ConflictError, NotFoundError, ValidationError
|
from app.core.errors import 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 _member_count_by_name() -> dict[str, int]:
|
|
||||||
"""
|
|
||||||
全员按部门名聚合计数。
|
|
||||||
核心逻辑: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}
|
|
||||||
|
|
||||||
|
|
||||||
def _sibling_sort_key(node: dict) -> tuple:
|
|
||||||
"""同级排序:sort_order 升序 → 编码 → 名称(编码可能为空,排最后)。"""
|
|
||||||
return (node['sort_order'], node['code'] or '', node['name'])
|
|
||||||
|
|
||||||
|
|
||||||
def list_departments() -> list[dict]:
|
def list_departments() -> list[dict]:
|
||||||
"""平铺部门列表(保持旧接口兼容),按公司 → 同级排序号 → 名称排序。"""
|
"""返回全部部门(按 name 升序)。"""
|
||||||
depts = db.session.query(Department).all()
|
rows = (
|
||||||
counts = _member_count_by_name()
|
db.session.query(Department, func.count(User.id).label('member_count'))
|
||||||
depts.sort(key=lambda d: (d.company or '', d.sort_order or 0, d.code or '', d.name))
|
.outerjoin(User, User.department == Department.name)
|
||||||
return [{**serialize_department(d), 'member_count': counts.get(d.name, 0)} for d in depts]
|
.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_tree() -> list[dict]:
|
def list_department_members(dept_id: int) -> dict:
|
||||||
"""
|
"""
|
||||||
返回完整部门树(children 嵌套,成员数含下级递归汇总)。
|
查询指定部门的员工名单。
|
||||||
|
|
||||||
[STEP 1] 一次取全表部门 + 一次按部门名聚合人数。
|
[STEP 1] 通过部门主键读取部门名称。
|
||||||
[STEP 2] 按 parent_id 挂 children;父缺失或成环的脏数据按顶级处理(防御)。
|
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
||||||
[STEP 3] 后序遍历汇总 total_member_count(本部门 + 全部下级)。
|
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
||||||
[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('Department not found')
|
raise NotFoundError('Not found')
|
||||||
if include_descendants:
|
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
||||||
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),
|
||||||
'total': total,
|
'count': len(users),
|
||||||
'page': page,
|
|
||||||
'page_size': page_size,
|
|
||||||
'members': [
|
'members': [
|
||||||
{
|
{
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
@@ -208,8 +61,6 @@ def list_department_members(
|
|||||||
'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
|
||||||
@@ -217,104 +68,25 @@ def list_department_members(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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_REQUIRED / PARENT_INVALID / NAME_EXISTS / CODE_EXISTS。
|
ValidationError: name 缺失或 name/code 重复。
|
||||||
"""
|
"""
|
||||||
name = _clean_str(data.get('name'))
|
if not data.get('name'):
|
||||||
if not name:
|
raise ValidationError('Name is required')
|
||||||
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
if db.session.query(Department).filter_by(name=data['name']).first():
|
||||||
parent_id = data.get('parent_id')
|
raise ValidationError('Name exists')
|
||||||
parent = _validate_parent(parent_id)
|
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
||||||
company = _clean_str(data.get('company')) or (parent.company if parent else None)
|
raise ValidationError('Code exists')
|
||||||
_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=name,
|
name=data['name'],
|
||||||
code=code,
|
code=data.get('code'),
|
||||||
company=company,
|
company=data.get('company'),
|
||||||
description=_clean_str(data.get('description')) or None,
|
description=data.get('description'),
|
||||||
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()
|
||||||
@@ -323,64 +95,34 @@ 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_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
|
ValidationError: name/code 与其它记录冲突。
|
||||||
"""
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if not dept:
|
if not dept:
|
||||||
raise NotFoundError('Department not found')
|
raise NotFoundError('Not found')
|
||||||
|
|
||||||
if 'parent_id' in data:
|
|
||||||
parent = _validate_parent_change(dept, data['parent_id'])
|
|
||||||
dept.parent_id = parent.id if parent else None
|
|
||||||
|
|
||||||
if 'company' in data:
|
|
||||||
dept.company = _clean_str(data.get('company')) or None
|
|
||||||
|
|
||||||
if 'name' in data:
|
if 'name' in data:
|
||||||
name = _clean_str(data.get('name'))
|
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
||||||
if not name:
|
raise ValidationError('Name exists')
|
||||||
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
dept.name = data['name']
|
||||||
_validate_sibling_name(name, dept.parent_id, company=dept.company, exclude_id=dept_id)
|
|
||||||
dept.name = name
|
|
||||||
|
|
||||||
if 'code' in data:
|
if 'code' in data:
|
||||||
code = _clean_str(data.get('code')) or None
|
if data['code'] and db.session.query(Department).filter(
|
||||||
if code and db.session.query(Department).filter(
|
Department.code == data['code'], Department.id != dept_id
|
||||||
Department.code == code, Department.id != dept_id
|
|
||||||
).first():
|
).first():
|
||||||
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
raise ValidationError('Code exists')
|
||||||
dept.code = code
|
dept.code = data['code']
|
||||||
|
if 'company' in data:
|
||||||
|
dept.company = data['company']
|
||||||
if 'description' in data:
|
if 'description' in data:
|
||||||
dept.description = _clean_str(data.get('description')) or None
|
dept.description = data['description']
|
||||||
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 not dept:
|
if dept:
|
||||||
return
|
|
||||||
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.delete(dept)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -16,9 +16,8 @@ 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, FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, 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
|
||||||
@@ -37,16 +36,6 @@ 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,
|
||||||
@@ -568,39 +557,6 @@ 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 = (
|
||||||
@@ -630,48 +586,9 @@ 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,22 +3,19 @@ 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
|
||||||
@@ -72,22 +69,15 @@ 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(
|
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
||||||
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': described['role'],
|
'role': user.role,
|
||||||
'role_name': described['role_name'],
|
'role_name': names.get(user.role) or user.role,
|
||||||
'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,
|
||||||
@@ -105,23 +95,12 @@ 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:
|
||||||
@@ -163,8 +142,7 @@ 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()
|
||||||
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
return [serialize_admin_user(u, names) for u 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)
|
||||||
@@ -190,9 +168,8 @@ 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(user, names, assigned.get(user.id)) for user in users],
|
'items': [serialize_admin_user(u, names) for u in users],
|
||||||
'total': int(total),
|
'total': int(total),
|
||||||
'page': page,
|
'page': page,
|
||||||
'page_size': page_size,
|
'page_size': page_size,
|
||||||
@@ -223,17 +200,10 @@ 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')),
|
||||||
)
|
)
|
||||||
if isinstance(data.get('roles'), list) and data.get('roles'):
|
role_code = role_service.assert_role_assignable(
|
||||||
role_codes = [
|
|
||||||
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(),
|
data.get('role') or role_service.default_role_code(),
|
||||||
allow_admin=True,
|
allow_admin=True,
|
||||||
)]
|
)
|
||||||
role_code = role_codes[0]
|
|
||||||
user = User(
|
user = User(
|
||||||
username=data['username'],
|
username=data['username'],
|
||||||
email=email,
|
email=email,
|
||||||
@@ -250,7 +220,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.assign_role_codes(user, role_codes)
|
role_service.sync_user_grants_from_role(user)
|
||||||
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
|
||||||
@@ -309,25 +279,20 @@ 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', 'status', 'real_name', 'employee_id', 'phone_number']:
|
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||||
if key in data:
|
if key in data:
|
||||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
if key == 'role':
|
||||||
|
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() and ('role' in data or 'roles' in data):
|
if role_service.roles_configured():
|
||||||
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:
|
||||||
user.role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
role_service.sync_user_grants_from_role(user)
|
||||||
|
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)
|
||||||
@@ -375,9 +340,6 @@ 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)
|
||||||
if role_service.roles_configured():
|
|
||||||
role_service.assign_role_codes(user, [next_role])
|
|
||||||
else:
|
|
||||||
user.role = next_role
|
user.role = next_role
|
||||||
role_service.sync_user_grants_from_role(user)
|
role_service.sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
"""
|
|
||||||
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 口径。预付款、出货款、验收款、质保款都可手动标为已付,并关闭该节点尚未发送的预警。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
|
||||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -40,7 +40,6 @@ 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
|
||||||
|
|
||||||
@@ -53,7 +52,6 @@ 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")),
|
||||||
@@ -67,7 +65,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
|||||||
|
|
||||||
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
||||||
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
||||||
ERP `apa_file` 的合格付款记录按金额匹配四个阶段,并停止已付款阶段尚未发送的后续轮次。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
|
||||||
Args:
|
Args:
|
||||||
today: 业务日期,未传时使用服务器日期。
|
today: 业务日期,未传时使用服务器日期。
|
||||||
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
||||||
@@ -87,20 +85,14 @@ 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 _ERP_PAID_STAGE_TYPES
|
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
|
||||||
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 (
|
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||||||
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(
|
||||||
@@ -108,11 +100,6 @@ 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
|
||||||
@@ -126,7 +113,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)
|
||||||
@@ -173,10 +160,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: 合同台账主键。
|
||||||
@@ -199,10 +186,8 @@ 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 _ERP_PAID_STAGE_TYPES:
|
if node.node_type not in {"prepayment", "shipment"}:
|
||||||
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, "acceptance": 3, "warranty": 4}
|
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
||||||
# 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,13 +234,14 @@ 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)` 节点;金额为 0 的阶段不要传入。
|
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||||
paid_rows: 该采购单的合格 ERP 付款记录。
|
paid_rows: 该采购单的合格 ERP 付款记录。
|
||||||
Returns:
|
Returns:
|
||||||
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
||||||
@@ -267,13 +268,14 @@ 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)` 节点;金额为 0 的阶段不要传入。
|
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||||
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
||||||
Returns:
|
Returns:
|
||||||
已付款节点 ID 集合。
|
已付款节点 ID 集合。
|
||||||
|
|||||||
@@ -4,13 +4,11 @@ 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
|
||||||
@@ -60,37 +58,6 @@ 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,
|
||||||
@@ -102,11 +69,11 @@ def classify_ledger_status(
|
|||||||
按合同聚合出台账状态,与列表「状态」列一致。
|
按合同聚合出台账状态,与列表「状态」列一致。
|
||||||
|
|
||||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||||
金额和比例都为 0 的阶段不参与判断。其余进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||||
Args:
|
Args:
|
||||||
contract_status: 合同主状态。
|
contract_status: 合同主状态。
|
||||||
parse_status: 解析状态。
|
parse_status: 解析状态。
|
||||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at / percentage / amount。
|
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||||
today: 业务日。
|
today: 业务日。
|
||||||
Returns:
|
Returns:
|
||||||
overdue / due / active / completed / needs_completion。
|
overdue / due / active / completed / needs_completion。
|
||||||
@@ -116,14 +83,7 @@ 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 = [
|
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "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"))
|
||||||
@@ -146,7 +106,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: 业务日,用于确定自然月。
|
||||||
@@ -158,8 +118,6 @@ 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
|
||||||
@@ -173,8 +131,6 @@ 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,47 +136,6 @@ 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,9 +2,8 @@
|
|||||||
backend/app/services/equipment_acceptance/alert_service.py
|
backend/app/services/equipment_acceptance/alert_service.py
|
||||||
|
|
||||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||||
依赖:同步服务、E10 人员目录、E8 人员矩阵、alert_plan、alert_notice、发送记录模型、企微通知。
|
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||||
逻辑:扫描先同步 E10 和 E8,再按停留天数跨档。第 1 档主送使用部门担当,不按当前未办人。
|
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||||
第 4 轮关闭时不生成、也不发送总经理那一轮。
|
|
||||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -36,7 +35,6 @@ 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
|
||||||
@@ -49,9 +47,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 条数。
|
||||||
"""
|
"""
|
||||||
@@ -80,9 +78,9 @@ def refresh_pending_alerts(
|
|||||||
created、updated、cancelled。
|
created、updated、cancelled。
|
||||||
"""
|
"""
|
||||||
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||||
e10_people, e10_deputies, e8_people, e8_matrix, e8_ok = _directories(orders, directory)
|
operators = _operators_by_order([order.id for order in orders])
|
||||||
users_by_job = _users_by_job(_job_numbers(orders, e10_people, e10_deputies, e8_people))
|
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
||||||
users_by_wecom = _users_by_wecom(_wecom_ids(e8_matrix))
|
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||||
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
|
||||||
@@ -98,16 +96,12 @@ 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,
|
||||||
e10_people,
|
operators.get(order.id, []),
|
||||||
e10_deputies,
|
people,
|
||||||
e8_people,
|
deputies,
|
||||||
e8_matrix,
|
|
||||||
users_by_job,
|
users_by_job,
|
||||||
users_by_wecom,
|
|
||||||
roles,
|
roles,
|
||||||
thresholds,
|
thresholds,
|
||||||
max_tier=max_tier,
|
max_tier=max_tier,
|
||||||
@@ -288,31 +282,82 @@ def send_pending_alerts() -> dict[str, Any]:
|
|||||||
|
|
||||||
def _drafts(
|
def _drafts(
|
||||||
order: EquipmentAcceptanceOrder,
|
order: EquipmentAcceptanceOrder,
|
||||||
e10_people: dict[int, dict[str, Any]],
|
operators: list[EquipmentAcceptanceOperator],
|
||||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
people: dict[int, dict[str, Any]],
|
||||||
e8_people: dict[int, dict[str, Any]],
|
deputies: dict[str, list[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 []
|
||||||
owner, supervisors, deputy_people = _owner_seats(
|
handlers: list[dict[str, Any]] = []
|
||||||
order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom
|
supervisors: list[dict[str, Any]] = []
|
||||||
|
deputy_people: list[dict[str, Any]] = []
|
||||||
|
if not operators:
|
||||||
|
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
|
||||||
|
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
|
||||||
|
for operator in operators:
|
||||||
|
fact = people.get(operator.user_id) or {}
|
||||||
|
name = fact.get("name") or operator.handler_name
|
||||||
|
job_num = fact.get("job_num") or operator.handler_job_num
|
||||||
|
shown = name or "处理人"
|
||||||
|
handlers.append(resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="当前处理人",
|
||||||
|
name=name,
|
||||||
|
job_num=job_num,
|
||||||
|
user=users_by_job.get(str(job_num or "")),
|
||||||
|
missing_job_error=f"{shown}没有工号",
|
||||||
|
oa_employee_id=operator.user_id,
|
||||||
|
))
|
||||||
|
superior_id = fact.get("superior_id")
|
||||||
|
if superior_id is None:
|
||||||
|
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
|
||||||
|
else:
|
||||||
|
supervisors.append(resolve_account(
|
||||||
|
slot="cc",
|
||||||
|
label="直接主管",
|
||||||
|
name=fact.get("superior_name"),
|
||||||
|
job_num=fact.get("superior_job_num"),
|
||||||
|
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||||
|
missing_job_error=f"{shown}的直接主管没有工号",
|
||||||
|
oa_employee_id=superior_id,
|
||||||
|
))
|
||||||
|
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||||
|
if not found:
|
||||||
|
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
|
||||||
|
else:
|
||||||
|
for item in found:
|
||||||
|
deputy_people.append(resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="经副理",
|
||||||
|
name=item.get("name"),
|
||||||
|
job_num=item.get("job_num"),
|
||||||
|
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||||
|
missing_job_error=f"{shown}的经副理没有工号",
|
||||||
|
oa_employee_id=item.get("oa_id"),
|
||||||
|
))
|
||||||
|
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||||
|
applicant = resolve_account(
|
||||||
|
slot="cc",
|
||||||
|
label="采购担当",
|
||||||
|
name=(applicant_fact or {}).get("name") or order.applicant_name,
|
||||||
|
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
|
||||||
|
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
|
||||||
|
missing_job_error="没有申请人工号",
|
||||||
|
oa_employee_id=order.applicant_oa_id,
|
||||||
)
|
)
|
||||||
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=[owner],
|
to_people=handlers,
|
||||||
cc_people=[*supervisors, applicant],
|
cc_people=[*supervisors, applicant],
|
||||||
))
|
))
|
||||||
if 2 in due:
|
if 2 in due:
|
||||||
@@ -345,159 +390,6 @@ 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
|
||||||
@@ -510,103 +402,51 @@ def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceO
|
|||||||
row.error_message = draft["error_message"]
|
row.error_message = draft["error_message"]
|
||||||
|
|
||||||
|
|
||||||
def _directories(
|
def _load_directory(
|
||||||
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 要使用部门担当和申请人的主管、部门、经副理。不传入 E8 人员 ID。"""
|
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
||||||
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.oa_system or "e10") == "e8" or order.monitor_status != WATCHING:
|
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
||||||
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],
|
||||||
e10_people: dict[int, dict[str, Any]],
|
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
people: dict[int, dict[str, Any]],
|
||||||
e8_people: dict[int, dict[str, Any]],
|
deputies: dict[str, list[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 fact in (*e10_people.values(), *e8_people.values()):
|
for group in operators.values():
|
||||||
|
for operator in group:
|
||||||
|
if operator.handler_job_num:
|
||||||
|
found.add(operator.handler_job_num)
|
||||||
|
for fact in people.values():
|
||||||
if fact.get("job_num"):
|
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 e10_deputies.values():
|
for group in 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:
|
||||||
|
|||||||
@@ -1,152 +0,0 @@
|
|||||||
"""
|
|
||||||
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
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
"""
|
|
||||||
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()
|
|
||||||
@@ -1,213 +0,0 @@
|
|||||||
"""
|
|
||||||
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
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
"""
|
|
||||||
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 必须是 E10 的 employee.ID。没有人员时不连库。
|
人员 ID 必须是整数。没有人员时不连库。
|
||||||
Args:
|
Args:
|
||||||
employee_ids: 使用部门担当和申请人的 employee.ID。禁止传入 E8 的 HrmResource.id。
|
employee_ids: 当前处理人和申请人的 employee.ID。
|
||||||
Returns:
|
Returns:
|
||||||
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ 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 挂到流程实例。
|
||||||
不取 flowstatus=3 的归档单。flowstatus 为空仍取。
|
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||||
流程编号读 requestmark,标题读 requestname,创建时间读 createdatetime。不读第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -69,8 +68,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 挂到流程实例。
|
||||||
流程编号取 requestmark,标题取 requestname,创建时间取 createdatetime。不查询第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||||
delete_type 只取 0。当前处理人就是这些 userid。归档(flowstatus=3)不取,空状态仍取。
|
delete_type 只取 0。当前处理人就是这些 userid。
|
||||||
Args:
|
Args:
|
||||||
catalogs: 已解析的库名。
|
catalogs: 已解析的库名。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -105,9 +104,6 @@ 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,
|
||||||
@@ -139,7 +135,6 @@ 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
|
||||||
|
|
||||||
用途:设备验收预警的默认排程:每日 06:30 扫描和周五 18:30 发送。
|
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
|
||||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||||
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
||||||
"""
|
"""
|
||||||
@@ -17,10 +17,8 @@ from app.services.schedule.timezone_util import compute_next_run_at
|
|||||||
|
|
||||||
|
|
||||||
_DEFAULTS = (
|
_DEFAULTS = (
|
||||||
# 每天 06:30,错开合同付款预警扫描的 06:00
|
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
|
||||||
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批 06:30)", "30 6 * * *"),
|
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
|
||||||
# 周五 18:30,错开合同付款预警的周五 18:00
|
|
||||||
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:30)", "30 18 * * 5"),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -28,7 +26,7 @@ def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
|
|||||||
"""
|
"""
|
||||||
幂等创建设备验收每日扫描和周五发送两个排程。
|
幂等创建设备验收每日扫描和周五发送两个排程。
|
||||||
|
|
||||||
核心逻辑:发送时刻不在预警配置表。默认每天 06:30、周五 18:30(错开合同付款 06:00 / 18:00),时区 Asia/Shanghai。
|
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 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] 可以验收只有明确为否才停表,空和是都继续计时。0、1、空以外不猜。
|
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
||||||
if can_accept in (1, None) and flow_status == _FLOW_APPROVING and is_returned == 0:
|
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||||
return WATCHING
|
return WATCHING
|
||||||
return EXCLUDED
|
return EXCLUDED
|
||||||
|
|
||||||
|
|||||||
@@ -42,16 +42,12 @@ 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
|
||||||
@@ -77,7 +73,7 @@ def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDr
|
|||||||
按流程实例 requestid 合并联表结果。
|
按流程实例 requestid 合并联表结果。
|
||||||
|
|
||||||
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||||
流程编号和标题随行写入。不读取第二合同编号和验收日期。
|
不读取流程编号、第二合同编号和验收日期。
|
||||||
Args:
|
Args:
|
||||||
rows: 查询别名组成的字典行。
|
rows: 查询别名组成的字典行。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -98,14 +94,10 @@ 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,24 +1,19 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/equipment_acceptance/sync_service.py
|
backend/app/services/equipment_acceptance/sync_service.py
|
||||||
|
|
||||||
用途:把 E10 和 E8 验收单快照写入本地表,并提供管理员查询。
|
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
||||||
依赖:extensions.db、sqlalchemy.or_、equipment_acceptance 模型、snapshot_rules、source_group、e8_group、oa_repository、e8_repository。
|
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_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
|
||||||
@@ -30,15 +25,12 @@ 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",
|
||||||
@@ -50,107 +42,34 @@ _STOPPED_STATUSES = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def sync_acceptance_snapshots(
|
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
rows: list[dict[str, Any]] | None = None,
|
|
||||||
*,
|
|
||||||
e8_rows: list[dict[str, Any]] | None = None,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
"""
|
"""
|
||||||
同步 E10 和 E8 验收单快照。
|
同步验收单快照。
|
||||||
|
|
||||||
核心逻辑:未传入行时分别读两个来源。一边查询失败只跳过这一边,不把已有快照标成消失。
|
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
||||||
只保留未归档单据。该来源本次没返回的本地单删掉。只传入 rows 时只同步 E10,方便既有测试注入联表行。
|
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
||||||
Args:
|
Args:
|
||||||
rows: 已取好的 E10 联表行。None 时访问 E10。
|
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
||||||
e8_rows: 已取好的 E8 联表行。与 rows 同时为 None 时才访问 E8。
|
|
||||||
Returns:
|
Returns:
|
||||||
两边合计的写入、跳过、消失和取消条数,以及 e10、e8 各自的结果。
|
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
||||||
"""
|
"""
|
||||||
fetch_live = rows is None and e8_rows is None
|
if rows is None:
|
||||||
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)
|
|
||||||
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
|
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||||
|
|
||||||
return fetch_acceptance_rows(), True, None
|
rows = fetch_acceptance_rows()
|
||||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_acceptance_rows
|
drafts, skipped = group_acceptance_rows(rows)
|
||||||
|
as_of = datetime.now(_SHANGHAI).date()
|
||||||
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, cancelled_missing = _drop_missing(request_ids, source)
|
absent = _mark_absent(request_ids)
|
||||||
cancelled += cancelled_missing
|
db.session.commit()
|
||||||
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,
|
||||||
@@ -165,23 +84,17 @@ 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 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||||
keyword 在流程编号、验收单号、采购单号里任一包含即命中,再与申请人姓名取交集。
|
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
||||||
已归档不列出。已逾期是计时中且签核天数超过第 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。
|
||||||
|
|
||||||
@@ -193,11 +106,7 @@ 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 = _apply_search(
|
query = db.session.query(EquipmentAcceptanceOrder)
|
||||||
_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:
|
||||||
@@ -222,7 +131,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, keyword=keyword, applicant=applicant),
|
"summary": _ledger_summary(reminder_day),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -251,25 +160,20 @@ 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(
|
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
||||||
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,
|
||||||
@@ -281,9 +185,6 @@ 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
|
||||||
@@ -353,45 +254,12 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
|||||||
return order, cancelled
|
return order, cancelled
|
||||||
|
|
||||||
|
|
||||||
def _drop_missing(request_ids: list[int], oa_system: str) -> tuple[int, int]:
|
def _mark_absent(request_ids: list[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))
|
||||||
gone = query.all()
|
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
||||||
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:
|
||||||
@@ -422,65 +290,9 @@ def _apply_focus(query, focus: str, reminder_day: int):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _clean_search(value: str | None) -> str | None:
|
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
||||||
"""去掉首尾空白。空白视为不筛选。过长时只保留前 100 字,避免把整段说明送进 LIKE。"""
|
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
||||||
text = str(value or "").strip()
|
base = db.session.query(EquipmentAcceptanceOrder)
|
||||||
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(
|
||||||
@@ -547,13 +359,9 @@ 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,10 +129,6 @@ 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,7 +4,6 @@ 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
|
||||||
|
|
||||||
@@ -25,17 +24,6 @@ _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', '')
|
||||||
@@ -153,54 +141,19 @@ 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': _with_agent_source_title(title, enabled=with_agent_source),
|
'title': title[:120],
|
||||||
'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': '查看详情',
|
||||||
@@ -247,7 +200,6 @@ 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 中的映射账号。
|
||||||
@@ -287,13 +239,7 @@ 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(
|
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
||||||
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,12 +23,10 @@ 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
|
||||||
|
|
||||||
@@ -254,38 +252,20 @@ 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:
|
||||||
role_codes = list(task.target_roles)
|
predicates.append(User.role.in_(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:
|
||||||
"""判断员工是否属于周任务对象。任一已挂角色命中,或显式指定用户,即可学习。"""
|
"""判断员工是否属于周任务对象,角色匹配或显式指定任一成立即可学习。"""
|
||||||
if user.status != "active":
|
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
||||||
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,11 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
services/permission_roles/service.py
|
services/permission_roles/service.py
|
||||||
|
|
||||||
用途:权限组 CRUD、成员预览/确认调整、把多个角色包的并集同步到用户授权。
|
用途:权限组 CRUD、成员预览/确认调整、把角色包同步到 users.role 与 user_agent_permissions。
|
||||||
依赖:PermissionRole、user_permission_roles、User、Agent、catalog。
|
依赖:PermissionRole、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'。
|
||||||
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
||||||
"""
|
"""
|
||||||
@@ -16,13 +14,12 @@ 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, user_permission_roles
|
from app.models.permission_role import PermissionRole
|
||||||
from app.services.permission_roles.catalog import (
|
from app.services.permission_roles.catalog import (
|
||||||
FEATURE_CATALOG,
|
FEATURE_CATALOG,
|
||||||
KNOWN_FEATURE_KEYS,
|
KNOWN_FEATURE_KEYS,
|
||||||
@@ -78,187 +75,6 @@ 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
|
||||||
@@ -342,7 +158,7 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
|||||||
"""
|
"""
|
||||||
判断用户是否属于 is_platform_admin 权限组。
|
判断用户是否属于 is_platform_admin 权限组。
|
||||||
|
|
||||||
核心逻辑:已种子时看全部已挂角色里是否有平台管理组;否则回退 role=admin。
|
核心逻辑:已种子时按 users.role join permission_roles;否则回退 role=admin。
|
||||||
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -356,20 +172,22 @@ 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] == cache_key:
|
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == role_code:
|
||||||
return bool(cached[1])
|
return bool(cached[1])
|
||||||
if assigned:
|
if not role_code:
|
||||||
result = any(role.is_platform_admin for role in assigned)
|
user._is_platform_admin_cached = (role_code, False)
|
||||||
elif not role_code:
|
return False
|
||||||
result = False
|
if _permission_roles_exist(session):
|
||||||
elif _permission_roles_exist(session):
|
role = (
|
||||||
result = False
|
session.query(PermissionRole)
|
||||||
|
.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 = (cache_key, result)
|
user._is_platform_admin_cached = (role_code, result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -393,92 +211,46 @@ 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
|
||||||
roles = list_assigned_roles(user)
|
role = get_role_by_code(user.role)
|
||||||
admin = next((role for role in roles if role.is_platform_admin), None)
|
stored = _normalize_feature_map(role.feature_permissions if role else {})
|
||||||
if admin is not None:
|
if role and role.is_platform_admin:
|
||||||
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
||||||
result.update(_normalize_feature_map(admin.feature_permissions))
|
result.update(stored)
|
||||||
return result
|
return result
|
||||||
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
||||||
for role in roles:
|
result.update(stored)
|
||||||
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:
|
||||||
"""
|
"""
|
||||||
按用户已挂的全部角色重算 Agent 授权与个人功能覆盖。
|
按用户当前 role 重写 Agent 授权与个人功能覆盖。
|
||||||
|
|
||||||
核心逻辑:还没有成员行时先按 users.role 写入一行。管理员不写 user_agent_permissions(入口隐式全开);
|
核心逻辑:管理员不写 user_agent_permissions(入口隐式全开);
|
||||||
其他角色把各权限组勾选的 Agent 取并集。个人 feature_permissions 清空,改由角色包计算。
|
其他角色用权限组勾选的 Agent 全量替换;个人 feature_permissions 清空,改由角色包计算。
|
||||||
未配置权限组时不改。
|
未配置权限组时不改。
|
||||||
"""
|
"""
|
||||||
if not roles_configured():
|
if not roles_configured():
|
||||||
return
|
return
|
||||||
if user.id is None:
|
role = get_role_by_code(user.role)
|
||||||
db.session.flush()
|
if role is None:
|
||||||
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
|
||||||
roles = [fallback]
|
user.role = fallback.code
|
||||||
if not _has_membership_rows(user):
|
role = fallback
|
||||||
roles = replace_user_roles(user, roles)
|
|
||||||
admins = [role for role in roles if role.is_platform_admin]
|
|
||||||
user.feature_permissions = {}
|
user.feature_permissions = {}
|
||||||
user._is_platform_admin_cached = None
|
if role.is_platform_admin:
|
||||||
if admins:
|
|
||||||
if len(roles) != 1:
|
|
||||||
replace_user_roles(user, [admins[0]])
|
|
||||||
return
|
return
|
||||||
primary = _primary_role(roles)
|
user.agents = list(role.agents)
|
||||||
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:
|
||||||
role = get_role_by_code(code)
|
|
||||||
if role is None:
|
|
||||||
return db.session.query(User).filter(User.role == code).count()
|
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]:
|
||||||
@@ -665,9 +437,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:
|
||||||
@@ -675,7 +447,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 = _users_for_role(role) if grants_changed else []
|
users = db.session.query(User).filter(User.role == role.code).all() 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()
|
||||||
@@ -698,67 +470,28 @@ def delete_role(code: str) -> dict[str, Any]:
|
|||||||
return {'status': 'ok'}
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
def _person_payload(
|
def _person_payload(user: User, role_names: dict[str, str]) -> dict[str, Any]:
|
||||||
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': primary.code if primary else fallback,
|
'role': user.role,
|
||||||
'role_name': _role_label(roles, role_names, fallback),
|
'role_name': role_names.get(user.role) or user.role,
|
||||||
'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:
|
||||||
admin_ids = (
|
query = query.filter(User.role.notin_(admin_codes))
|
||||||
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()
|
||||||
assigned = roles_by_user_ids([user.id for user in users])
|
return [_person_payload(user, role_names) 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]:
|
||||||
@@ -778,10 +511,7 @@ 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:
|
||||||
@@ -790,59 +520,35 @@ 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 = _users_for_role(role, active_only=True)
|
current_members = (
|
||||||
|
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 _assigned(person: User) -> list[PermissionRole]:
|
def _rows(ids: list[int]) -> list[dict[str, Any]]:
|
||||||
rows = assigned_map.get(person.id)
|
rows = []
|
||||||
if rows:
|
for user_id in ids:
|
||||||
|
user = users_by_id.get(user_id)
|
||||||
|
if not user or user_is_platform_admin(user):
|
||||||
|
continue
|
||||||
|
rows.append(_person_payload(user, role_names))
|
||||||
return rows
|
return rows
|
||||||
return list_assigned_roles(person)
|
|
||||||
|
|
||||||
added = []
|
added = _rows(added_ids)
|
||||||
for user_id in added_ids:
|
removed = _rows(removed_ids)
|
||||||
user = users_by_id.get(user_id)
|
stolen = [row for row in added if row['role'] not in {default_code, role.code}]
|
||||||
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,
|
||||||
@@ -856,28 +562,26 @@ 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
|
||||||
current = list_assigned_roles(user)
|
user.role = role.code
|
||||||
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
|
||||||
current = list_assigned_roles(user)
|
user.role = default_code
|
||||||
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 {
|
||||||
@@ -910,23 +614,12 @@ 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
|
||||||
for code in codes:
|
incoming = get_role_by_code(new_role)
|
||||||
incoming = get_role_by_code(code) if roles_configured() else None
|
|
||||||
if incoming and incoming.is_platform_admin:
|
if incoming and incoming.is_platform_admin:
|
||||||
return
|
return
|
||||||
if not roles_configured() and str(code or '') == PLATFORM_ADMIN_CODE:
|
if not roles_configured() and new_role == PLATFORM_ADMIN_CODE:
|
||||||
return
|
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:
|
||||||
|
|||||||
@@ -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,12 +4,10 @@ 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
|
||||||
@@ -25,65 +23,6 @@ _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:
|
||||||
@@ -326,22 +265,14 @@ 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):
|
||||||
leaf = str(row.get("LeafName") or "").strip()
|
if str(row.get("LeafName") or "").strip() == wanted:
|
||||||
shown = row_display_name(row)
|
|
||||||
if leaf == wanted or shown == wanted:
|
|
||||||
return row
|
return row
|
||||||
if renamed is None and (leaf_names_match(leaf, wanted) or leaf_names_match(shown, wanted)):
|
return None
|
||||||
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]:
|
||||||
@@ -456,121 +387,6 @@ 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,
|
||||||
@@ -581,10 +397,10 @@ class SalesDmsClient:
|
|||||||
) -> tuple[dict[str, Any], bool]:
|
) -> tuple[dict[str, Any], bool]:
|
||||||
"""
|
"""
|
||||||
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
||||||
核心逻辑:先按 LeafName 查目标。已有原名则跳过复制;只有「(重命名)」副本时改回原名。没有再 Copy。收尾时同一目录多出来的该后缀副本删除。
|
核心逻辑:先按 LeafName 查目标;没有再 Copy。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()
|
||||||
@@ -598,21 +414,18 @@ 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 cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
return 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 cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
return 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 (
|
return existing, True
|
||||||
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)
|
||||||
@@ -622,7 +435,7 @@ class SalesDmsClient:
|
|||||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||||
details={"leaf_name": wanted},
|
details={"leaf_name": wanted},
|
||||||
)
|
)
|
||||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=dest_row), False
|
return 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,8 +4,7 @@ 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 避免通用排程重复通知。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -48,7 +47,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 字节,
|
||||||
颜色标签会挤掉后面的缺件类型。
|
颜色标签会挤掉后面的缺件类型。
|
||||||
|
|
||||||
@@ -60,10 +59,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]:
|
||||||
@@ -114,36 +113,6 @@ 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,
|
||||||
@@ -153,17 +122,11 @@ 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,并附上本批检核结果 Excel。
|
按文件类型接收人发送缺件 textcard。
|
||||||
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。
|
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。无缺件或无人可发则写审计不发空消息。
|
||||||
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
|
||||||
@@ -250,20 +213,9 @@ 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 []
|
||||||
@@ -282,8 +234,6 @@ 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]
|
||||||
@@ -294,16 +244,11 @@ def send_batch_missing_summary(
|
|||||||
exc,
|
exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
if file_failed and not file_note:
|
skip_reason = None
|
||||||
file_note = "部分 Excel 附件发送失败"
|
|
||||||
reasons: list[str] = []
|
|
||||||
if not ok_any:
|
if not ok_any:
|
||||||
reasons.append("企业微信发送失败")
|
skip_reason = "企业微信发送失败"
|
||||||
elif plan["unmapped_codes"]:
|
elif plan["unmapped_codes"]:
|
||||||
reasons.append("部分文件类型未配置接收人")
|
skip_reason = "部分文件类型未配置接收人"
|
||||||
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,14 +545,10 @@ 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")
|
||||||
@@ -578,12 +574,6 @@ 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。缺件通知附带与排程落库相同的检核结果 Excel。
|
命中文件复制到所有归档,同名跳过仍记 archived。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -28,11 +28,7 @@ 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 (
|
from app.services.voucher_check.excel_rows import to_excel_invoice_row
|
||||||
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
|
||||||
@@ -373,18 +369,8 @@ 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,
|
||||||
@@ -393,7 +379,6 @@ 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(
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
"""合并意见反馈附图表与设备验收评审两条 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
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
"""合并用户多角色与意见反馈附图两条 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
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
"""设备验收快照增加流程编号、标题和创建时间。
|
|
||||||
|
|
||||||
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")
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
"""设备验收快照增加来源,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")
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
"""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
|
|
||||||
-29
@@ -1,29 +0,0 @@
|
|||||||
"""合并设备验收流程字段与复核行决策码两条 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
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
"""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")
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
"""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 ###
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"_comment": "hrao00 -> 公司中文名。来源 ERP dc.HRAA_FILE(hraa01=公司编号,hraa02=公司名称)。0000 集团公司无部门,保留映射以备后续。",
|
|
||||||
"0000": "集团公司",
|
|
||||||
"0001": "电子",
|
|
||||||
"0002": "科技",
|
|
||||||
"0003": "和信",
|
|
||||||
"0004": "泰国合欣",
|
|
||||||
"0005": "台湾尊场",
|
|
||||||
"0006": "无锡和宏智",
|
|
||||||
"0007": "上海数智"
|
|
||||||
}
|
|
||||||
@@ -1,358 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,256 +0,0 @@
|
|||||||
"""通用意见反馈提交 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
|
|
||||||
@@ -1,180 +1,45 @@
|
|||||||
"""
|
"""
|
||||||
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 ConflictError, NotFoundError, ValidationError
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
from app.models import Department, User
|
from app.models import Department
|
||||||
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_with_parent(app):
|
def test_department_crud(app):
|
||||||
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
|
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
|
created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'})
|
||||||
child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
|
assert created['name'] == 'R&D'
|
||||||
assert child['name'] == '品保课'
|
|
||||||
|
|
||||||
items = list_departments()
|
items = list_departments()
|
||||||
assert any(item['code'] == 'QA1' and item['parent_id'] == parent['id'] for item in items)
|
assert any(item['code'] == 'RD' for item in items)
|
||||||
|
|
||||||
update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
|
update_department(created['id'], {'description': 'Research'})
|
||||||
dept = db.session.get(Department, child['id'])
|
dept = db.session.get(Department, created['id'])
|
||||||
assert dept.sort_order == 9
|
assert dept.description == 'Research'
|
||||||
assert dept.is_hidden is True
|
|
||||||
|
|
||||||
# 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
|
delete_department(created['id'])
|
||||||
with pytest.raises(ConflictError, match='child'):
|
assert db.session.get(Department, created['id']) is None
|
||||||
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_same_parent_duplicate_name(app):
|
def test_create_department_rejects_duplicate_name(app):
|
||||||
"""断言:同一上级下同名部门被拒(同级查重)。"""
|
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
create_department({'name': 'Sales'})
|
create_department({'name': 'Sales'})
|
||||||
with pytest.raises(ValidationError) as exc_info:
|
with pytest.raises(ValidationError, match='Name exists'):
|
||||||
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
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
"""
|
|
||||||
backend/tests/services/test_feedback_notify.py
|
|
||||||
|
|
||||||
用途:锁定企微反馈通知 markdown 组装契约——有图反馈在「反馈内容」段之前
|
|
||||||
多一行「附图:N 张」(N>0 时),无图反馈不得出现「附图」字样,
|
|
||||||
且其余既有行内容与顺序零改动。
|
|
||||||
依赖:app 夹具(create_app('testing') + db.create_all,不走迁移)、
|
|
||||||
GeneralFeedback/GeneralFeedbackImage/User/FileAsset 模型、
|
|
||||||
app.services.feedback_notify.build_feedback_markdown。
|
|
||||||
逻辑:build_feedback_markdown 为纯组装函数(不发网络请求),测试直接落
|
|
||||||
User/FileAsset/GeneralFeedback/GeneralFeedbackImage 行后调用并断言文本,
|
|
||||||
覆盖有图(2 张)与无图两条路径。
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from uuid import uuid4
|
|
||||||
|
|
||||||
from app import db
|
|
||||||
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
|
||||||
from app.services.feedback_notify import build_feedback_markdown
|
|
||||||
|
|
||||||
|
|
||||||
def _create_user(username: str) -> User:
|
|
||||||
"""按用户名幂等落一个测试用户(GeneralFeedback.user_id 外键依赖)。"""
|
|
||||||
user = db.session.query(User).filter_by(username=username).first()
|
|
||||||
if not user:
|
|
||||||
user = User(username=username, email=f"{username}@example.com", role="user", status="active")
|
|
||||||
user.set_password("x")
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
return user
|
|
||||||
|
|
||||||
|
|
||||||
def _make_asset(user_id: int) -> FileAsset:
|
|
||||||
"""直接落一条 ready/temporary 的图片 FileAsset 行(GeneralFeedbackImage.asset_id 外键依赖)。"""
|
|
||||||
asset = FileAsset(
|
|
||||||
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
|
||||||
original_filename="screenshot.png", storage_provider="minio", storage_bucket="test",
|
|
||||||
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
|
||||||
mime_type="image/png", extension="png", upload_status="ready",
|
|
||||||
lifecycle_status="temporary", reference_count=0,
|
|
||||||
)
|
|
||||||
db.session.add(asset)
|
|
||||||
db.session.commit()
|
|
||||||
return asset
|
|
||||||
|
|
||||||
|
|
||||||
def _create_feedback(user: User, content: str) -> GeneralFeedback:
|
|
||||||
"""落一条最小可用的 GeneralFeedback 行(必填字段齐全)。"""
|
|
||||||
feedback = GeneralFeedback(
|
|
||||||
user_id=user.id, username=user.username,
|
|
||||||
feedback_type="问题反馈", feedback_module="知识库", content=content,
|
|
||||||
source_page="workspace",
|
|
||||||
)
|
|
||||||
db.session.add(feedback)
|
|
||||||
db.session.commit()
|
|
||||||
return feedback
|
|
||||||
|
|
||||||
|
|
||||||
def test_markdown_includes_image_count(app):
|
|
||||||
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
|
||||||
with app.app_context():
|
|
||||||
user = _create_user("notifyuser")
|
|
||||||
# 有图反馈:2 条图片关联(asset_id 唯一,各自独立 FileAsset),走真实 images relationship
|
|
||||||
fb_with_images = _create_feedback(user, "这条反馈带两张截图")
|
|
||||||
db.session.add_all([
|
|
||||||
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=0),
|
|
||||||
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=1),
|
|
||||||
])
|
|
||||||
db.session.commit()
|
|
||||||
# 无图反馈:不落任何 GeneralFeedbackImage
|
|
||||||
fb_without_images = _create_feedback(user, "这条反馈没有截图")
|
|
||||||
|
|
||||||
md_with_images = build_feedback_markdown(fb_with_images, None)
|
|
||||||
md_without_images = build_feedback_markdown(fb_without_images, None)
|
|
||||||
|
|
||||||
# 有图:附图行存在,且必须位于「反馈内容」块之前
|
|
||||||
assert "附图:2 张" in md_with_images
|
|
||||||
assert md_with_images.index("附图:2 张") < md_with_images.index("**反馈内容:**")
|
|
||||||
# 无图:不得出现「附图」字样
|
|
||||||
assert "附图" not in md_without_images
|
|
||||||
@@ -4,7 +4,6 @@ backend/tests/test_contract_payment_ledger_focus.py
|
|||||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||||
金额和比例都为 0 的验收款不把合同算进逾期。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -13,7 +12,7 @@ from datetime import date
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||||
from app.services.contract_payment.ledger_focus import classify_ledger_status, ledger_focus_counts
|
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||||
|
|
||||||
|
|
||||||
def _create_user(*, username: str) -> User:
|
def _create_user(*, username: str) -> User:
|
||||||
@@ -137,37 +136,3 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
|||||||
assert summary.get_json()['data']['active'] == 2
|
assert summary.get_json()['data']['active'] == 2
|
||||||
assert 'needs_completion' not in summary.get_json()['data']
|
assert 'needs_completion' not in summary.get_json()['data']
|
||||||
assert empty.get_json()['data']['total'] == 0
|
assert empty.get_json()['data']['total'] == 0
|
||||||
|
|
||||||
|
|
||||||
def test_zero_amount_stage_does_not_mark_contract_overdue():
|
|
||||||
"""金额和比例都为 0 的阶段不参与逾期。"""
|
|
||||||
status = classify_ledger_status(
|
|
||||||
contract_status='active',
|
|
||||||
parse_status='parsed',
|
|
||||||
nodes=[
|
|
||||||
{
|
|
||||||
'status': 'paid',
|
|
||||||
'percentage': '50',
|
|
||||||
'amount': '4250.00',
|
|
||||||
'due_date': date(2026, 9, 2),
|
|
||||||
'anchor_date': date(2026, 9, 2),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'status': 'active',
|
|
||||||
'percentage': '0',
|
|
||||||
'amount': '0.00',
|
|
||||||
'due_date': date(2026, 9, 24),
|
|
||||||
'anchor_date': date(2026, 9, 24),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'status': 'active',
|
|
||||||
'percentage': '0',
|
|
||||||
'amount': '0.00',
|
|
||||||
'due_date': date(2027, 3, 23),
|
|
||||||
'anchor_date': date(2026, 9, 24),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
today=date(2026, 10, 27),
|
|
||||||
)
|
|
||||||
# 关键断言:预付款已付,验收款和质保款为 0,合同应为已完成而不是已逾期。
|
|
||||||
assert status == 'completed'
|
|
||||||
@@ -915,14 +915,7 @@ def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
|
|||||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||||
|
|
||||||
|
|
||||||
def test_erp_payment_matches_acceptance_amount_without_consuming_earlier_stages():
|
def test_oa_company_dropdown_uses_selected_option(app):
|
||||||
"""关键断言:验收款金额单独命中时只标验收款,不把预付款或出货款记成已付。"""
|
|
||||||
nodes = [
|
|
||||||
(1, "prepayment", Decimal("16740")),
|
|
||||||
(2, "shipment", Decimal("27900")),
|
|
||||||
(3, "acceptance", Decimal("11160")),
|
|
||||||
]
|
|
||||||
assert resolve_paid_node_ids(nodes, [Decimal("11160")]) == {3}
|
|
||||||
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
|
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
|
||||||
page = """
|
page = """
|
||||||
<table><tr>
|
<table><tr>
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
"""
|
|
||||||
backend/tests/test_equipment_acceptance_e8.py
|
|
||||||
|
|
||||||
用途:E8 状态翻译、分组、查询语句,以及按使用部门担当组装收件人。
|
|
||||||
依赖:e8_status、e8_group、e8_query、alert_service._drafts。不连接 OA,不启动 Flask。
|
|
||||||
逻辑:暂停和撤销都停表。可以验收按 0=是翻转。第 1 档主送使用部门担当。
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
pytestmark = pytest.mark.pure_unit
|
|
||||||
|
|
||||||
from app.services.equipment_acceptance.alert_service import _drafts
|
|
||||||
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
|
||||||
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
|
||||||
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
|
||||||
from app.services.equipment_acceptance.snapshot_rules import EXCLUDED, classify_monitor_status
|
|
||||||
|
|
||||||
|
|
||||||
def test_e8_null_status_follows_node_type_and_pause_stops():
|
|
||||||
"""空的 currentstatus 看节点类型。暂停和撤销都收成 7。别的值不收成审批中。"""
|
|
||||||
assert e8_flow_status("1", None) == 1
|
|
||||||
assert e8_flow_status(" 3 ", "") == 3
|
|
||||||
assert e8_flow_status("1", 0) == 7
|
|
||||||
assert e8_flow_status("1", 1) == 7
|
|
||||||
assert e8_flow_status("1", 9) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_e8_status_is_not_watching():
|
|
||||||
"""认不出的流程状态留空后,有计时起点也不进进行中。"""
|
|
||||||
assert classify_monitor_status(
|
|
||||||
can_accept=1, is_returned=0, flow_status=None, timer_started=True
|
|
||||||
) == EXCLUDED
|
|
||||||
|
|
||||||
|
|
||||||
def test_e8_rows_group_owner_and_pending_handler():
|
|
||||||
"""计时读 syddjssj,可以验收读 sfkys。当前未办人只留查询给出的 userid。"""
|
|
||||||
drafts, skipped = group_e8_rows([
|
|
||||||
{
|
|
||||||
"requestid": 88,
|
|
||||||
"ysddh": "YS-E8",
|
|
||||||
"cgdh": "CG-1",
|
|
||||||
"htbh": "HT-1",
|
|
||||||
"flow_no": "LC-1",
|
|
||||||
"request_title": "设备验收",
|
|
||||||
"createdate": "2026-10-26",
|
|
||||||
"createtime": "15:46:04",
|
|
||||||
"syddjssj": "2026-08-01",
|
|
||||||
"sfkys": 0,
|
|
||||||
"sfzfth": None,
|
|
||||||
"ycsm": "",
|
|
||||||
"sybmdd": 15,
|
|
||||||
"owner_name": "吴敏",
|
|
||||||
"owner_job_num": "10086",
|
|
||||||
"creater": 22,
|
|
||||||
"applicant_name": "赵琴",
|
|
||||||
"applicant_job_num": "20001",
|
|
||||||
"currentnodetype": "1",
|
|
||||||
"currentstatus": None,
|
|
||||||
"currentnodeid": 6,
|
|
||||||
"nodename": "使用部门担当",
|
|
||||||
"userid": 15,
|
|
||||||
"handler_name": "吴敏",
|
|
||||||
"handler_job_num": "10086",
|
|
||||||
},
|
|
||||||
{"ysddh": "NO-ID"},
|
|
||||||
])
|
|
||||||
assert skipped == 1
|
|
||||||
draft = drafts[0]
|
|
||||||
assert draft.oa_system == "e8"
|
|
||||||
assert draft.timer_started_at is not None
|
|
||||||
assert draft.can_accept == 1
|
|
||||||
assert draft.is_returned == 0
|
|
||||||
assert draft.flow_status_raw == 1
|
|
||||||
assert draft.owner_oa_id == 15
|
|
||||||
assert draft.applicant_oa_id == 22
|
|
||||||
assert draft.flow_no == "LC-1"
|
|
||||||
assert draft.request_title == "设备验收"
|
|
||||||
assert draft.request_created_at == datetime(2026, 10, 26, 15, 46, 4)
|
|
||||||
assert [node.node_name for node in draft.nodes] == ["使用部门担当"]
|
|
||||||
assert [item.user_id for item in draft.operators] == [15]
|
|
||||||
|
|
||||||
|
|
||||||
def test_e8_sql_joins_current_node_and_unfinished_operator():
|
|
||||||
"""当前节点用 currentnodeid。未办人用 isremark=0。不取流程编号。"""
|
|
||||||
sql = build_e8_acceptance_sql().lower()
|
|
||||||
assert "formtable_main_324" in sql
|
|
||||||
assert "w.requestid = f.requestid" in sql
|
|
||||||
assert "n.id = w.currentnodeid" in sql
|
|
||||||
assert "op.nodeid = w.currentnodeid" in sql
|
|
||||||
assert "isremark" in sql
|
|
||||||
assert "w.currentnodetype is null" in sql
|
|
||||||
assert "<> n'3'" in sql
|
|
||||||
assert "w.creater" in sql
|
|
||||||
assert "w.creator" not in sql
|
|
||||||
assert "f.lcbh as flow_no" in sql
|
|
||||||
assert "w.requestname as request_title" in sql
|
|
||||||
assert "w.createdate" in sql
|
|
||||||
assert "w.createtime" in sql
|
|
||||||
assert "lastnodeid" not in sql
|
|
||||||
|
|
||||||
|
|
||||||
def test_tier_one_sends_to_usage_owner_not_current_handler():
|
|
||||||
"""第 1 档主送使用部门担当。当前节点上的另一名处理人不进收件人。"""
|
|
||||||
order = SimpleNamespace(
|
|
||||||
oa_system="e10",
|
|
||||||
dwell_days=31,
|
|
||||||
owner_oa_id=15,
|
|
||||||
owner_name="吴敏",
|
|
||||||
owner_job_num="10086",
|
|
||||||
applicant_oa_id=22,
|
|
||||||
applicant_name="赵琴",
|
|
||||||
applicant_job_num="20001",
|
|
||||||
)
|
|
||||||
people = {
|
|
||||||
15: {
|
|
||||||
"name": "吴敏",
|
|
||||||
"job_num": "10086",
|
|
||||||
"superior_id": 30,
|
|
||||||
"superior_name": "钱伟",
|
|
||||||
"superior_job_num": "30001",
|
|
||||||
"department_id": "9",
|
|
||||||
},
|
|
||||||
22: {"name": "赵琴", "job_num": "20001"},
|
|
||||||
}
|
|
||||||
deputies = {"9": [{"oa_id": 40, "name": "孙经理", "job_num": "40001"}]}
|
|
||||||
users = {
|
|
||||||
"10086": SimpleNamespace(id=7, wecom_userid="wx-owner", real_name="吴敏"),
|
|
||||||
"30001": SimpleNamespace(id=8, wecom_userid="wx-boss", real_name="钱伟"),
|
|
||||||
"20001": SimpleNamespace(id=9, wecom_userid="wx-buyer", real_name="赵琴"),
|
|
||||||
"40001": SimpleNamespace(id=10, wecom_userid="wx-deputy", real_name="孙经理"),
|
|
||||||
}
|
|
||||||
drafts = _drafts(
|
|
||||||
order,
|
|
||||||
people,
|
|
||||||
deputies,
|
|
||||||
{},
|
|
||||||
{},
|
|
||||||
users,
|
|
||||||
{},
|
|
||||||
{"coo": None, "buyer": None, "executive": None},
|
|
||||||
(30, 37, 44, 51),
|
|
||||||
max_tier=3,
|
|
||||||
)
|
|
||||||
tier1 = drafts[0]
|
|
||||||
assert tier1["tier"] == 1
|
|
||||||
assert tier1["to_text"] == "吴敏"
|
|
||||||
assert "钱伟" in (tier1["cc_text"] or "")
|
|
||||||
assert "赵琴" in (tier1["cc_text"] or "")
|
|
||||||
labels = [item["label"] for item in tier1["recipients"]]
|
|
||||||
assert "当前处理人" not in labels
|
|
||||||
assert "使用部门担当" in labels
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/tests/test_equipment_acceptance_snapshot.py
|
backend/tests/test_equipment_acceptance_snapshot.py
|
||||||
|
|
||||||
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
||||||
依赖:snapshot_rules、source_group、query_sql、sync_service 的搜索词整理。不连接 OA,也不启动 Flask。
|
依赖:snapshot_rules、source_group、query_sql。不连接 OA,也不启动 Flask。
|
||||||
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -13,7 +13,6 @@ import pytest
|
|||||||
pytestmark = pytest.mark.pure_unit
|
pytestmark = pytest.mark.pure_unit
|
||||||
|
|
||||||
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
||||||
from app.services.equipment_acceptance.sync_service import _clean_search, _contains_pattern
|
|
||||||
from app.services.equipment_acceptance.snapshot_rules import (
|
from app.services.equipment_acceptance.snapshot_rules import (
|
||||||
EXCLUDED,
|
EXCLUDED,
|
||||||
NOT_STARTED,
|
NOT_STARTED,
|
||||||
@@ -52,16 +51,16 @@ def test_returned_yes_stops_even_while_approving():
|
|||||||
assert status == STOPPED_RETURNED
|
assert status == STOPPED_RETURNED
|
||||||
|
|
||||||
|
|
||||||
def test_cannot_accept_stops_and_null_can_accept_still_watches():
|
def test_cannot_accept_stops_and_null_can_accept_is_not_watching():
|
||||||
"""可以验收明确为否才停表。空值未标明,审批中且已计时仍监控。"""
|
"""can_accept=0 是不可以,停表;空值不是可以验收。"""
|
||||||
stopped = classify_monitor_status(
|
stopped = classify_monitor_status(
|
||||||
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
||||||
)
|
)
|
||||||
watching = classify_monitor_status(
|
excluded = classify_monitor_status(
|
||||||
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
||||||
)
|
)
|
||||||
assert stopped == STOPPED_CANNOT_ACCEPT
|
assert stopped == STOPPED_CANNOT_ACCEPT
|
||||||
assert watching == WATCHING
|
assert excluded == EXCLUDED
|
||||||
|
|
||||||
|
|
||||||
def test_not_returned_and_can_accept_watches():
|
def test_not_returned_and_can_accept_watches():
|
||||||
@@ -205,14 +204,10 @@ def test_sql_uses_dictionary_catalogs_and_does_not_select_isremark():
|
|||||||
assert "workflow_requestbase" not in sql
|
assert "workflow_requestbase" not in sql
|
||||||
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
||||||
assert "d.dataid = f.FORM_DATA_ID" in sql
|
assert "d.dataid = f.FORM_DATA_ID" in sql
|
||||||
assert "r.flowstatus is null or r.flowstatus <> 3" in sql.lower()
|
|
||||||
assert "r.requestmark as flow_no" in sql.lower()
|
|
||||||
assert "r.requestname as request_title" in sql.lower()
|
|
||||||
assert "r.createdatetime" in sql.lower()
|
|
||||||
assert "lcbh" not in sql
|
assert "lcbh" not in sql
|
||||||
assert "htbh1" not in sql
|
assert "htbh1" not in sql
|
||||||
assert "ysrq" not in sql
|
assert "ysrq" not in sql
|
||||||
assert "requestmark" in sql.lower()
|
assert "requestmark" not in sql
|
||||||
assert "operateround" not in sql.lower()
|
assert "operateround" not in sql.lower()
|
||||||
assert "optgroupid" not in sql.lower()
|
assert "optgroupid" not in sql.lower()
|
||||||
assert "batch_number" not in sql.lower()
|
assert "batch_number" not in sql.lower()
|
||||||
@@ -260,11 +255,3 @@ def test_send_record_payload_keeps_written_names():
|
|||||||
assert payload["threshold_days"] == 37
|
assert payload["threshold_days"] == 37
|
||||||
assert payload["status"] == "sent"
|
assert payload["status"] == "sent"
|
||||||
assert payload["sent_at"]
|
assert payload["sent_at"]
|
||||||
|
|
||||||
|
|
||||||
def test_number_keyword_treats_like_wildcards_as_literal_text():
|
|
||||||
"""单号搜索按包含匹配,% 和 _ 保持原字符,空白不参与过滤。"""
|
|
||||||
assert _clean_search(" ") is None
|
|
||||||
assert _clean_search(" 20260718 ") == "20260718"
|
|
||||||
assert _contains_pattern("a%b_c") == "%a\\%b\\_c%"
|
|
||||||
assert len(_clean_search("x" * 120) or "") == 100
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
tests/test_permission_roles.py
|
tests/test_permission_roles.py
|
||||||
|
|
||||||
用途:可配置权限组种子路径:角色包同步、多角色并集、成员确认、禁止按人授权、最后一名管理员、平台管理员查询。
|
用途:可配置权限组种子路径:角色包同步、成员确认、禁止按人授权、最后一名管理员、平台管理员查询。
|
||||||
依赖:PermissionRole、User、Agent、permission_roles.service、user_service、permission_service。
|
依赖:PermissionRole、User、Agent、permission_roles.service、user_service、permission_service。
|
||||||
逻辑:未种子时旧测试仍走按人授权;本文件显式写入权限组后断言新路径。
|
逻辑:未种子时旧测试仍走按人授权;本文件显式写入权限组后断言新路径。
|
||||||
"""
|
"""
|
||||||
@@ -202,10 +202,8 @@ def test_preview_and_apply_role_members(app):
|
|||||||
assert {agent.id for agent in staff.agents} == {entrance.id, training.id}
|
assert {agent.id for agent in staff.agents} == {entrance.id, training.id}
|
||||||
assert admin.role == 'admin'
|
assert admin.role == 'admin'
|
||||||
|
|
||||||
retain_preview = role_service.preview_role_members('user', [other.id, staff.id])
|
steal_preview = role_service.preview_role_members('user', [other.id, staff.id])
|
||||||
# 断言:再挂上默认角色时保留培训 HR,不再把原角色抢走。
|
assert [row['id'] for row in steal_preview['stolen']] == [staff.id]
|
||||||
assert [row['id'] for row in retain_preview['stolen']] == [staff.id]
|
|
||||||
assert retain_preview['stolen'][0]['retained_role_names'] == ['培训 HR']
|
|
||||||
|
|
||||||
|
|
||||||
def test_default_role_ignores_removal(app):
|
def test_default_role_ignores_removal(app):
|
||||||
@@ -224,57 +222,6 @@ def test_default_role_ignores_removal(app):
|
|||||||
assert staff.role == 'user'
|
assert staff.role == 'user'
|
||||||
|
|
||||||
|
|
||||||
def test_business_roles_union_until_last_role_removed(app):
|
|
||||||
"""一个人可同时挂两个业务角色;拿掉最后一个才回到普通用户。"""
|
|
||||||
with app.app_context():
|
|
||||||
entrance = _agent('ent-union', profile='generic_entrance')
|
|
||||||
training = _agent('train-union', profile='training')
|
|
||||||
patent = _agent('patent-union', code='patent_tool')
|
|
||||||
db.session.add_all([entrance, training, patent])
|
|
||||||
db.session.flush()
|
|
||||||
roles = _seed_standard_roles(entrance, training)
|
|
||||||
rd = PermissionRole(
|
|
||||||
code='rd',
|
|
||||||
name='研发',
|
|
||||||
is_default=False,
|
|
||||||
is_system=False,
|
|
||||||
is_platform_admin=False,
|
|
||||||
sort_order=20,
|
|
||||||
feature_permissions={'shipping_notice_force_create': True},
|
|
||||||
)
|
|
||||||
rd.agents = [entrance, patent]
|
|
||||||
db.session.add(rd)
|
|
||||||
staff = _user('union-staff', role='user')
|
|
||||||
db.session.add(staff)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
role_service.apply_role_members('hr', [staff.id])
|
|
||||||
role_service.apply_role_members('rd', [staff.id])
|
|
||||||
db.session.refresh(staff)
|
|
||||||
codes = {role.code for role in role_service.list_assigned_roles(staff)}
|
|
||||||
# 断言:两个业务角色并存,应用和能力取并集,普通用户不再占用名额。
|
|
||||||
assert codes == {'hr', 'rd'}
|
|
||||||
assert {agent.id for agent in staff.agents} == {entrance.id, training.id, patent.id}
|
|
||||||
perms = staff.get_feature_permissions()
|
|
||||||
assert perms['training_hr_manage'] is True
|
|
||||||
assert perms['shipping_notice_force_create'] is True
|
|
||||||
assert roles['user'].id not in {role.id for role in role_service.list_assigned_roles(staff)}
|
|
||||||
|
|
||||||
role_service.apply_role_members('hr', [])
|
|
||||||
db.session.refresh(staff)
|
|
||||||
# 断言:移出培训后仍保留研发。
|
|
||||||
assert {role.code for role in role_service.list_assigned_roles(staff)} == {'rd'}
|
|
||||||
assert staff.get_feature_permissions()['training_hr_manage'] is False
|
|
||||||
assert staff.get_feature_permissions()['shipping_notice_force_create'] is True
|
|
||||||
|
|
||||||
role_service.apply_role_members('rd', [])
|
|
||||||
db.session.refresh(staff)
|
|
||||||
# 断言:最后一个业务角色拿掉后回到默认普通用户。
|
|
||||||
assert {role.code for role in role_service.list_assigned_roles(staff)} == {'user'}
|
|
||||||
assert staff.role == 'user'
|
|
||||||
assert [agent.id for agent in staff.agents] == [entrance.id]
|
|
||||||
|
|
||||||
|
|
||||||
def test_picker_excludes_platform_admin(app):
|
def test_picker_excludes_platform_admin(app):
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
entrance = _agent('ent-pick', profile='generic_entrance')
|
entrance = _agent('ent-pick', profile='generic_entrance')
|
||||||
|
|||||||
@@ -3,15 +3,13 @@ backend/tests/test_voucher_check_permissions.py
|
|||||||
|
|
||||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||||
逻辑:授予 voucher_check Agent 后可查询任务列表并下载企微记录 Excel,但不能触发强制重检、也不能改通知配置。
|
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date
|
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import Agent, ScheduleRun, ScheduleTask, User, VoucherCheckRun
|
from app.models import Agent, User
|
||||||
|
|
||||||
|
|
||||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||||
@@ -178,63 +176,3 @@ def test_voucher_check_notify_config_requires_admin(client, app):
|
|||||||
)
|
)
|
||||||
assert put_res.status_code == 403
|
assert put_res.status_code == 403
|
||||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||||
|
|
||||||
|
|
||||||
def test_voucher_check_excel_download_uses_agent_access_not_schedule_notify(client, app):
|
|
||||||
"""企微发送记录的 Excel 按立账凭证访问权下载,不要求是排程负责人或通知人。"""
|
|
||||||
payload = b'voucher-excel'
|
|
||||||
with app.app_context():
|
|
||||||
owner = _create_user(username='vc_excel_owner')
|
|
||||||
granted = _grant_voucher_check_agent(_create_user(username='vc_excel_viewer'))
|
|
||||||
denied = _create_user(username='vc_excel_denied')
|
|
||||||
task = ScheduleTask(
|
|
||||||
schedule_no='VC-EXCEL-1',
|
|
||||||
name='立账凭证周检',
|
|
||||||
owner_user_id=owner.id,
|
|
||||||
cron_expr='0 6 * * 2',
|
|
||||||
notify_user_ids_json=[],
|
|
||||||
)
|
|
||||||
db.session.add(task)
|
|
||||||
db.session.flush()
|
|
||||||
schedule_run = ScheduleRun(
|
|
||||||
run_no='RUN-VC-EXCEL-1',
|
|
||||||
schedule_task_id=task.id,
|
|
||||||
status='success',
|
|
||||||
excel_file_data=payload,
|
|
||||||
excel_file_name='voucher_check.xlsx',
|
|
||||||
excel_file_size=len(payload),
|
|
||||||
)
|
|
||||||
db.session.add(schedule_run)
|
|
||||||
db.session.flush()
|
|
||||||
db.session.add(VoucherCheckRun(
|
|
||||||
id=88001,
|
|
||||||
schedule_run_id=schedule_run.id,
|
|
||||||
run_no='RUN-VC-EXCEL-1',
|
|
||||||
profile_code='sales',
|
|
||||||
profile_version='1',
|
|
||||||
profile_snapshot_json={},
|
|
||||||
period_month=date(2026, 9, 1),
|
|
||||||
mode='incremental',
|
|
||||||
status='success',
|
|
||||||
))
|
|
||||||
db.session.commit()
|
|
||||||
schedule_run_id = schedule_run.id
|
|
||||||
granted_id = granted.id
|
|
||||||
denied_id = denied.id
|
|
||||||
|
|
||||||
granted_headers = {'X-User-Id': str(granted_id), 'X-Username': 'vc_excel_viewer'}
|
|
||||||
url = f'/api/workspace/accounting-voucher-check/schedule-runs/{schedule_run_id}/excel'
|
|
||||||
ok_res = client.get(url, headers=granted_headers)
|
|
||||||
# 关键断言:不是排程通知人时,立账凭证授权用户仍能拿到 Excel 正文。
|
|
||||||
assert ok_res.status_code == 200
|
|
||||||
assert ok_res.data == payload
|
|
||||||
|
|
||||||
denied_headers = {'X-User-Id': str(denied_id), 'X-Username': 'vc_excel_denied'}
|
|
||||||
denied_res = client.get(url, headers=denied_headers)
|
|
||||||
assert denied_res.status_code == 403
|
|
||||||
assert _json_error(denied_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
|
||||||
|
|
||||||
legacy = client.get(f'/api/workspace/schedule-runs/{schedule_run_id}/excel', headers=granted_headers)
|
|
||||||
# 关键断言:旧排程下载口仍只认负责人/通知人,企微记录不能再走这条。
|
|
||||||
assert legacy.status_code == 403
|
|
||||||
assert _json_error(legacy)['code'] == 'AUTH.FORBIDDEN'
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
"""
|
|
||||||
tests/test_wecom_textcard_source.py
|
|
||||||
|
|
||||||
用途:断言企微 textcard 标题带来源,以及账号类通知不加来源。
|
|
||||||
依赖:app fixture、integrations.wecom.notify。
|
|
||||||
逻辑:直接调用标题函数与发送出口,不经过具体业务模块。
|
|
||||||
"""
|
|
||||||
from app import db
|
|
||||||
from app.models import User
|
|
||||||
from app.services.integrations.wecom.notify import (
|
|
||||||
_with_agent_source_title,
|
|
||||||
send_wecom_event_message,
|
|
||||||
send_wecom_textcard_message,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_agent_source_prefix_stays_when_title_is_truncated():
|
|
||||||
"""超长业务标题截断后,来源前缀仍完整留在最前面。"""
|
|
||||||
title = _with_agent_source_title('缺' * 200)
|
|
||||||
# [断言意图] 前缀不被 120 字上限切掉,业务标题从末尾被截断。
|
|
||||||
assert title.startswith('AI智能体 · ')
|
|
||||||
assert len(title) == 120
|
|
||||||
assert title == f"AI智能体 · {'缺' * 112}"
|
|
||||||
|
|
||||||
|
|
||||||
def test_agent_source_prefix_is_not_repeated():
|
|
||||||
"""已经带来源的标题不再加第二次。"""
|
|
||||||
once = _with_agent_source_title('精益管理培训逾期提醒')
|
|
||||||
twice = _with_agent_source_title(once)
|
|
||||||
# [断言意图] 重复经过发送出口时标题保持单层来源。
|
|
||||||
assert once == 'AI智能体 · 精益管理培训逾期提醒'
|
|
||||||
assert twice == once
|
|
||||||
|
|
||||||
|
|
||||||
def test_textcard_payload_uses_agent_source_title(app, monkeypatch):
|
|
||||||
"""实际发给企业微信的 textcard.title 带来源,调用方传入的仍是业务标题。"""
|
|
||||||
captured = {}
|
|
||||||
|
|
||||||
def _fake_post(_url, params=None, json=None, timeout=None):
|
|
||||||
captured['json'] = json
|
|
||||||
|
|
||||||
class _Resp:
|
|
||||||
def json(self):
|
|
||||||
return {'errcode': 0}
|
|
||||||
|
|
||||||
return _Resp()
|
|
||||||
|
|
||||||
monkeypatch.setattr(
|
|
||||||
'app.services.integrations.wecom.notify._get_access_token',
|
|
||||||
lambda: 'token',
|
|
||||||
)
|
|
||||||
monkeypatch.setattr(
|
|
||||||
'app.services.integrations.wecom.notify.requests.post',
|
|
||||||
_fake_post,
|
|
||||||
)
|
|
||||||
with app.app_context():
|
|
||||||
app.config['WECOM_AGENT_ID'] = '1000002'
|
|
||||||
send_wecom_textcard_message(
|
|
||||||
'wx-user',
|
|
||||||
'销售开票附件缺件提醒',
|
|
||||||
'正文',
|
|
||||||
'https://example.com/detail',
|
|
||||||
)
|
|
||||||
# [断言意图] 企微载荷标题带来源,正文和按钮保持原样。
|
|
||||||
assert captured['json']['textcard']['title'] == 'AI智能体 · 销售开票附件缺件提醒'
|
|
||||||
assert captured['json']['textcard']['description'] == '正文'
|
|
||||||
assert captured['json']['textcard']['btntxt'] == '查看详情'
|
|
||||||
|
|
||||||
|
|
||||||
def test_account_events_keep_business_title(app, monkeypatch):
|
|
||||||
"""密码重置和权限变更不加来源;业务提醒仍然加上。"""
|
|
||||||
captured = {}
|
|
||||||
|
|
||||||
def _fake_send(_userid, title, _description, _jump_url, *, with_agent_source=True):
|
|
||||||
captured['title'] = title
|
|
||||||
captured['with_agent_source'] = with_agent_source
|
|
||||||
return {'errcode': 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(
|
|
||||||
'app.services.integrations.wecom.notify.send_wecom_textcard_message',
|
|
||||||
_fake_send,
|
|
||||||
)
|
|
||||||
with app.app_context():
|
|
||||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
|
||||||
app.config['WECOM_NOTIFY_EVENTS'] = (
|
|
||||||
'password_reset,permission_request_approved,lean_training_overdue'
|
|
||||||
)
|
|
||||||
user = User(
|
|
||||||
username='source-user',
|
|
||||||
email='source@example.com',
|
|
||||||
role='user',
|
|
||||||
wecom_userid='wx-source',
|
|
||||||
)
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
send_wecom_event_message(
|
|
||||||
event_type='password_reset',
|
|
||||||
user=user,
|
|
||||||
title='和信AI智能工作台 密码重置',
|
|
||||||
content='请重置密码',
|
|
||||||
jump_url='https://example.com/reset',
|
|
||||||
)
|
|
||||||
# [断言意图] 密码重置不是智能体推送,发送出口关闭来源前缀。
|
|
||||||
assert captured['with_agent_source'] is False
|
|
||||||
assert captured['title'] == '和信AI智能工作台 密码重置'
|
|
||||||
|
|
||||||
send_wecom_event_message(
|
|
||||||
event_type='permission_request_approved',
|
|
||||||
user=user,
|
|
||||||
title='权限申请已通过',
|
|
||||||
content='已通过',
|
|
||||||
)
|
|
||||||
# [断言意图] 权限变更与密码重置同一排除名单。
|
|
||||||
assert captured['with_agent_source'] is False
|
|
||||||
|
|
||||||
send_wecom_event_message(
|
|
||||||
event_type='lean_training_overdue',
|
|
||||||
user=user,
|
|
||||||
title='精益管理培训逾期提醒',
|
|
||||||
content='请完成学习',
|
|
||||||
)
|
|
||||||
# [断言意图] 业务提醒仍把来源交给 textcard 出口添加。
|
|
||||||
assert captured['with_agent_source'] is True
|
|
||||||
assert captured['title'] == '精益管理培训逾期提醒'
|
|
||||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_dms_archive.py
|
|||||||
|
|
||||||
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
|
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
|
||||||
依赖:pytest;不连文档库。
|
依赖:pytest;不连文档库。
|
||||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy/Rename/Recycle;断言同名不覆盖、带「重命名」的落盘名改回原名、多余副本删除、缺月目录为技术失败。
|
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -19,10 +19,6 @@ from app.services.voucher_check.dms_client import (
|
|||||||
SalesDmsClient,
|
SalesDmsClient,
|
||||||
_extract_item_id,
|
_extract_item_id,
|
||||||
_is_name_conflict,
|
_is_name_conflict,
|
||||||
canonical_leaf_name,
|
|
||||||
dms_stored_leaf_name,
|
|
||||||
leaf_names_match,
|
|
||||||
row_display_name,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -59,280 +55,6 @@ def test_ensure_folder_creates_when_missing(monkeypatch):
|
|||||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
|
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
|
||||||
|
|
||||||
|
|
||||||
def test_recycle_items_posts_library_delete(monkeypatch):
|
|
||||||
# 与文档库列表「删除」同一接口:ItemID 数组,进入回收站。
|
|
||||||
seen: dict[str, object] = {}
|
|
||||||
|
|
||||||
def post(path, payload, **_kwargs):
|
|
||||||
seen["path"] = path
|
|
||||||
seen["payload"] = payload
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
|
||||||
SalesDmsClient.recycle_items(item_ids=["extra-1", "extra-2"])
|
|
||||||
assert seen["path"] == "/Api/_api/APS/Public/Item/Recycle"
|
|
||||||
assert seen["payload"] == {"ItemID": ["extra-1", "extra-2"]}
|
|
||||||
|
|
||||||
|
|
||||||
def test_rename_item_posts_library_rename(monkeypatch):
|
|
||||||
# 与文档库列表「重命名」同一接口:ItemID + 改回后的 LeafName。
|
|
||||||
seen: dict[str, object] = {}
|
|
||||||
|
|
||||||
def post(path, payload, **_kwargs):
|
|
||||||
seen["path"] = path
|
|
||||||
seen["payload"] = payload
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
|
||||||
SalesDmsClient.rename_item(item_id="dest-r", leaf_name="INV001.pdf")
|
|
||||||
assert seen["path"] == "/Api/_api/APS/Public/Item/Rename"
|
|
||||||
assert seen["payload"] == {"ItemID": "dest-r", "LeafName": "INV001.pdf"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_canonical_leaf_name_strips_dms_rename_marker():
|
|
||||||
# 现网复制后的名字是「原名.pdf(重命名).pdf」,还原后必须等于业务文件名。
|
|
||||||
assert canonical_leaf_name("AK260929062-8501-2609290005.pdf(重命名).pdf") == (
|
|
||||||
"AK260929062-8501-2609290005.pdf"
|
|
||||||
)
|
|
||||||
assert canonical_leaf_name("INV001(重命名).pdf") == "INV001.pdf"
|
|
||||||
assert canonical_leaf_name("INV001.pdf") == "INV001.pdf"
|
|
||||||
assert leaf_names_match("AK260929062-8501-2609290005.pdf(重命名).pdf", "AK260929062-8501-2609290005.pdf")
|
|
||||||
assert leaf_names_match("OTHER.pdf(重命名).pdf", "AK260929062-8501-2609290005.pdf") is False
|
|
||||||
assert canonical_leaf_name("QCG260921187-8501-2609210008.pdf (重命名) .pdf") == (
|
|
||||||
"QCG260921187-8501-2609210008.pdf"
|
|
||||||
)
|
|
||||||
# 库内真实名字不带界面补上的第二个 .pdf。改回带 .pdf 的原名会被文档库判成同名。
|
|
||||||
stored = "QCH2609188245-8501-2609170001.pdf(重命名)"
|
|
||||||
assert canonical_leaf_name(stored) == "QCH2609188245-8501-2609170001.pdf"
|
|
||||||
assert dms_stored_leaf_name("QCH2609188245-8501-2609170001.pdf") == "QCH2609188245-8501-2609170001"
|
|
||||||
assert row_display_name({
|
|
||||||
"LeafName": stored,
|
|
||||||
"MainFileAttachment": {"Extension": ".pdf"},
|
|
||||||
}) == "QCH2609188245-8501-2609170001.pdf(重命名).pdf"
|
|
||||||
|
|
||||||
|
|
||||||
def test_find_child_file_accepts_renamed_copy(monkeypatch):
|
|
||||||
# 目录里只有带「重命名」的文件时,按原名查找应命中,避免再次复制。
|
|
||||||
monkeypatch.setattr(
|
|
||||||
SalesDmsClient,
|
|
||||||
"list_files",
|
|
||||||
lambda **_kwargs: [{
|
|
||||||
"ID": "dest-r",
|
|
||||||
"LeafName": "AK260929062-8501-2609290005.pdf(重命名).pdf",
|
|
||||||
"IsFolder": False,
|
|
||||||
}],
|
|
||||||
)
|
|
||||||
row = SalesDmsClient.find_child_file(
|
|
||||||
parent_folder_id="inv-folder",
|
|
||||||
leaf_name="AK260929062-8501-2609290005.pdf",
|
|
||||||
)
|
|
||||||
assert row is not None
|
|
||||||
assert row["ID"] == "dest-r"
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_renames_existing_suffix_back_to_original(monkeypatch):
|
|
||||||
# 目录里只有带「重命名」的文件时,改回原名,不再复制出新文件。
|
|
||||||
files = {"rows": [{"ID": "dest-r", "LeafName": "INV001.pdf(重命名).pdf"}]}
|
|
||||||
copies: list[object] = []
|
|
||||||
renames: list[dict[str, str]] = []
|
|
||||||
|
|
||||||
def list_files(**_kwargs):
|
|
||||||
return files["rows"]
|
|
||||||
|
|
||||||
def rename_item(**kwargs):
|
|
||||||
renames.append(kwargs)
|
|
||||||
files["rows"] = [{"ID": kwargs["item_id"], "LeafName": kwargs["leaf_name"]}]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copies.append(kwargs))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
|
||||||
source_item_id="src-1",
|
|
||||||
dest_folder_id="inv-folder",
|
|
||||||
leaf_name="INV001.pdf",
|
|
||||||
)
|
|
||||||
assert skipped is True
|
|
||||||
assert row["LeafName"] == "INV001"
|
|
||||||
assert renames == [{"item_id": "dest-r", "leaf_name": "INV001"}]
|
|
||||||
assert copies == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_strips_rename_suffix_after_copy(monkeypatch):
|
|
||||||
# 复制成功但落盘名带「重命名」时,立刻改回业务原名。
|
|
||||||
files: dict[str, list[dict[str, str]]] = {"rows": []}
|
|
||||||
renames: list[dict[str, str]] = []
|
|
||||||
|
|
||||||
def list_files(**_kwargs):
|
|
||||||
return files["rows"]
|
|
||||||
|
|
||||||
def copy_items(**_kwargs):
|
|
||||||
files["rows"] = [{"ID": "new-1", "LeafName": "INV001.pdf(重命名).pdf"}]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
def rename_item(**kwargs):
|
|
||||||
renames.append(kwargs)
|
|
||||||
files["rows"] = [{"ID": kwargs["item_id"], "LeafName": kwargs["leaf_name"]}]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", copy_items)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
|
||||||
source_item_id="src-1",
|
|
||||||
dest_folder_id="inv-folder",
|
|
||||||
leaf_name="INV001.pdf",
|
|
||||||
)
|
|
||||||
assert skipped is False
|
|
||||||
assert row["ID"] == "new-1"
|
|
||||||
assert row["LeafName"] == "INV001"
|
|
||||||
assert renames == [{"item_id": "new-1", "leaf_name": "INV001"}]
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_keeps_original_and_recycles_renamed_extras(monkeypatch):
|
|
||||||
# 原名已在时不再复制、不再改名,只删除仍带「重命名」的多余副本。
|
|
||||||
files = {
|
|
||||||
"rows": [
|
|
||||||
{"ID": "clean", "LeafName": "INV001.pdf"},
|
|
||||||
{"ID": "extra", "LeafName": "INV001.pdf(重命名).pdf"},
|
|
||||||
{"ID": "other", "LeafName": "别的资料.pdf"},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
recycled: list[list[str]] = []
|
|
||||||
|
|
||||||
def list_files(**_kwargs):
|
|
||||||
return list(files["rows"])
|
|
||||||
|
|
||||||
def recycle_items(**kwargs):
|
|
||||||
recycled.append(list(kwargs["item_ids"]))
|
|
||||||
drop = set(kwargs["item_ids"])
|
|
||||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "rename_item", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应改名")))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
|
||||||
source_item_id="src-1",
|
|
||||||
dest_folder_id="inv-folder",
|
|
||||||
leaf_name="INV001.pdf",
|
|
||||||
)
|
|
||||||
assert skipped is True
|
|
||||||
assert row["ID"] == "clean"
|
|
||||||
assert recycled == [["extra"]]
|
|
||||||
assert [item["ID"] for item in files["rows"]] == ["clean", "other"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_restores_one_of_three_renamed_copies_and_recycles_the_rest(monkeypatch):
|
|
||||||
# 9 月这类目录只有三份带后缀的同一文件时:改回一份原名,删除另外两份。
|
|
||||||
wanted = "QCG260921187-8501-2609210008.pdf"
|
|
||||||
renamed = f"{wanted}(重命名).pdf"
|
|
||||||
files = {
|
|
||||||
"rows": [
|
|
||||||
{"ID": "a", "LeafName": renamed},
|
|
||||||
{"ID": "b", "LeafName": renamed},
|
|
||||||
{"ID": "c", "LeafName": f"{wanted} (重命名) .pdf"},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
recycled: list[list[str]] = []
|
|
||||||
|
|
||||||
def list_files(**_kwargs):
|
|
||||||
return list(files["rows"])
|
|
||||||
|
|
||||||
def rename_item(**kwargs):
|
|
||||||
for item in files["rows"]:
|
|
||||||
if item["ID"] == kwargs["item_id"]:
|
|
||||||
item["LeafName"] = kwargs["leaf_name"]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
def recycle_items(**kwargs):
|
|
||||||
recycled.append(list(kwargs["item_ids"]))
|
|
||||||
drop = set(kwargs["item_ids"])
|
|
||||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
|
||||||
source_item_id="src-1",
|
|
||||||
dest_folder_id="inv-folder",
|
|
||||||
leaf_name=wanted,
|
|
||||||
)
|
|
||||||
assert skipped is True
|
|
||||||
assert row["ID"] == "a"
|
|
||||||
assert row["LeafName"] == "QCG260921187-8501-2609210008"
|
|
||||||
assert recycled == [["b", "c"]]
|
|
||||||
assert [item["ID"] for item in files["rows"]] == ["a"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_renames_real_dms_leaf_without_extension(monkeypatch):
|
|
||||||
# 现网 LeafName 是「原名.pdf(重命名)」,扩展名在附件上。改名必须去掉扩展名,不能写成「原名.pdf」。
|
|
||||||
wanted = "QCH2609188245-8501-2609170001.pdf"
|
|
||||||
stored = f"{wanted}(重命名)"
|
|
||||||
files = {
|
|
||||||
"rows": [
|
|
||||||
{"ID": "a", "LeafName": stored, "MainFileAttachment": {"Extension": ".pdf"}},
|
|
||||||
{"ID": "b", "LeafName": stored, "MainFileAttachment": {"Extension": ".pdf"}},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
renames: list[dict[str, str]] = []
|
|
||||||
|
|
||||||
def list_files(**_kwargs):
|
|
||||||
return list(files["rows"])
|
|
||||||
|
|
||||||
def rename_item(**kwargs):
|
|
||||||
renames.append(kwargs)
|
|
||||||
for item in files["rows"]:
|
|
||||||
if item["ID"] == kwargs["item_id"]:
|
|
||||||
item["LeafName"] = kwargs["leaf_name"]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
def recycle_items(**kwargs):
|
|
||||||
drop = set(kwargs["item_ids"])
|
|
||||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
|
||||||
return {"Code": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
|
||||||
source_item_id="src-1",
|
|
||||||
dest_folder_id="inv-folder",
|
|
||||||
leaf_name=wanted,
|
|
||||||
)
|
|
||||||
assert skipped is True
|
|
||||||
assert row["ID"] == "a"
|
|
||||||
assert renames == [{"item_id": "a", "leaf_name": "QCH2609188245-8501-2609170001"}]
|
|
||||||
assert [item["ID"] for item in files["rows"]] == ["a"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_skips_when_stored_leaf_is_already_the_stem(monkeypatch):
|
|
||||||
# 改名成功后 LeafName 是不带扩展名的原名,下次检核不能再复制。
|
|
||||||
monkeypatch.setattr(
|
|
||||||
SalesDmsClient,
|
|
||||||
"list_files",
|
|
||||||
lambda **_kwargs: [{
|
|
||||||
"ID": "a",
|
|
||||||
"LeafName": "QCH2609188245-8501-2609170001",
|
|
||||||
"MainFileAttachment": {"Extension": ".pdf"},
|
|
||||||
}],
|
|
||||||
)
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "rename_item", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应改名")))
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应删除")))
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
|
||||||
source_item_id="src-1",
|
|
||||||
dest_folder_id="inv-folder",
|
|
||||||
leaf_name="QCH2609188245-8501-2609170001.pdf",
|
|
||||||
)
|
|
||||||
assert skipped is True
|
|
||||||
assert row["ID"] == "a"
|
|
||||||
|
|
||||||
|
|
||||||
def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
SalesDmsClient,
|
SalesDmsClient,
|
||||||
@@ -341,11 +63,6 @@ def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
|||||||
)
|
)
|
||||||
calls: list[object] = []
|
calls: list[object] = []
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
|
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
|
||||||
monkeypatch.setattr(
|
|
||||||
SalesDmsClient,
|
|
||||||
"list_files",
|
|
||||||
lambda **_kwargs: [{"ID": "dest-1", "LeafName": "INV001.pdf"}],
|
|
||||||
)
|
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||||
source_item_id="src-1",
|
source_item_id="src-1",
|
||||||
dest_folder_id="inv-folder",
|
dest_folder_id="inv-folder",
|
||||||
@@ -366,11 +83,6 @@ def test_copy_when_dest_has_no_same_name(monkeypatch):
|
|||||||
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
|
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||||
monkeypatch.setattr(
|
|
||||||
SalesDmsClient,
|
|
||||||
"list_files",
|
|
||||||
lambda **_kwargs: [{"ID": "dest-2", "LeafName": "INV001.pdf"}],
|
|
||||||
)
|
|
||||||
copied: list[dict] = []
|
copied: list[dict] = []
|
||||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
|
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
|
||||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||||
@@ -393,11 +105,6 @@ def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
|
|||||||
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
|
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
|
||||||
|
|
||||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||||
monkeypatch.setattr(
|
|
||||||
SalesDmsClient,
|
|
||||||
"list_files",
|
|
||||||
lambda **_kwargs: [{"ID": "dest-3", "LeafName": "INV001.pdf"}],
|
|
||||||
)
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
SalesDmsClient,
|
SalesDmsClient,
|
||||||
"copy_items",
|
"copy_items",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_notify_config.py
|
|||||||
|
|
||||||
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
||||||
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
||||||
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型,并收到同一份 Excel。
|
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -179,26 +179,14 @@ def test_notify_config_rejects_non_admin_headers(app, client, user_headers):
|
|||||||
|
|
||||||
|
|
||||||
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||||
"""缺件通知按人拆信,正文只含该人负责的缺失类型,并给每人附上同一份 Excel。"""
|
"""缺件通知按人拆信,正文只含该人负责的缺失类型。"""
|
||||||
sent: list[tuple[str, str, str]] = []
|
sent: list[tuple[str, str, str]] = []
|
||||||
uploaded: list[tuple[bytes, str]] = []
|
|
||||||
files: list[tuple[str, str]] = []
|
|
||||||
|
|
||||||
def _fake_send(wecom_userid, title, description, jump_url):
|
def _fake_send(wecom_userid, title, description, jump_url):
|
||||||
sent.append((wecom_userid, title, description))
|
sent.append((wecom_userid, title, description))
|
||||||
return {"errcode": 0}
|
return {"errcode": 0}
|
||||||
|
|
||||||
def _fake_upload(data, filename):
|
|
||||||
uploaded.append((data, filename))
|
|
||||||
return "media-vc-1"
|
|
||||||
|
|
||||||
def _fake_file(wecom_userid, media_id):
|
|
||||||
files.append((wecom_userid, media_id))
|
|
||||||
return {"errcode": 0}
|
|
||||||
|
|
||||||
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
|
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
|
||||||
monkeypatch.setattr("app.services.integrations.wecom.notify.upload_wecom_temp_media", _fake_upload)
|
|
||||||
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_file_message", _fake_file)
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"app.services.integrations.wecom.notify._create_audit",
|
"app.services.integrations.wecom.notify._create_audit",
|
||||||
lambda *args, **kwargs: SimpleNamespace(
|
lambda *args, **kwargs: SimpleNamespace(
|
||||||
@@ -291,7 +279,6 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
excel_filename="voucher_check_sales_2026-08.xlsx",
|
excel_filename="voucher_check_sales_2026-08.xlsx",
|
||||||
excel_bytes=b"voucher-xlsx",
|
|
||||||
enabled=True,
|
enabled=True,
|
||||||
)
|
)
|
||||||
assert status == "sent"
|
assert status == "sent"
|
||||||
@@ -307,7 +294,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|||||||
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
||||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||||
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
||||||
assert po_title == "销售开票附件缺件提醒"
|
assert po_title == "销售开票附件缺件"
|
||||||
assert "2026年8月" in po_body
|
assert "2026年8月" in po_body
|
||||||
assert "缺 2 份,涉及 1 张发票" in po_body
|
assert "缺 2 份,涉及 1 张发票" in po_body
|
||||||
assert "业务方" not in po_body
|
assert "业务方" not in po_body
|
||||||
@@ -319,7 +306,3 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|||||||
assert "发票:缺" not in po_body
|
assert "发票:缺" not in po_body
|
||||||
assert "提单" in bl_body
|
assert "提单" in bl_body
|
||||||
assert "PO订单:缺" not in bl_body
|
assert "PO订单:缺" not in bl_body
|
||||||
# 关键断言:同一份 Excel 只上传一次,两个收件人都收到文件消息。
|
|
||||||
assert uploaded == [(b"voucher-xlsx", "voucher_check_sales_2026-08.xlsx")]
|
|
||||||
assert files == [("wx-po-recv", "media-vc-1"), ("wx-bl-recv", "media-vc-1")]
|
|
||||||
assert "下一条 Excel" in po_body
|
|
||||||
+4
-12
@@ -1,12 +1,5 @@
|
|||||||
# 智能HR请假管理需求
|
# 智能HR请假管理需求
|
||||||
|
|
||||||
## 制程品质异常预警(2026-10)
|
|
||||||
|
|
||||||
- 只读统计 OA 制程品质异常通知单。统计键是料号 + 不良类别,料号按原值,计次日期是申请日期。归档和在途计入,废弃和撤销不计入。
|
|
||||||
- 近一年是扫描日减 1 年(含)到扫描日前 1 天(含),同一键 ≥ 3 才预警。当月按申请日期所在自然月计,含扫描日当天。当月笔数只决定升级给谁。
|
|
||||||
- 品质担当每周收一封仍 ≥ 3 的全量清单。升级只在当月进入更高档的那一周发一次:第 1 笔主送品质和生产经副理,第 2 笔主送 COO,第 3 笔及以上主送老板并抄送 COO、品质、生产经副理。跳过的档不补发。渠道是 OA 邮件。
|
|
||||||
- 规则已整理,尚未实现。OA 字段和发信方式见后续设计文档。一单多行计次、空不良类别、五个岗位的具体人员仍待确认。需求见 [制程品质异常预警需求](features/process-quality-alert/demand.md)。
|
|
||||||
|
|
||||||
## 年度教育训练计划(2026-10)
|
## 年度教育训练计划(2026-10)
|
||||||
|
|
||||||
独立于入职、安全、精益、出国规章培训。年底按主办单位收集下一年度计划,讲师按月排课;课程库保存可重复使用的课件和试题,签到、录制、考试发布和完成状态记在月度场次上。未完成提醒每周一 09:00 发给当月仍有未完成场次的讲师,文案对齐人事课内部邮件。细则见 [features/training/annual-training-plan-demand.md](features/training/annual-training-plan-demand.md),设计方案见 [features/training/annual-training-plan-design.md](features/training/annual-training-plan-design.md),原型见 [features/training/annual-training-plan-prototype.html](features/training/annual-training-plan-prototype.html)。
|
独立于入职、安全、精益、出国规章培训。年底按主办单位收集下一年度计划,讲师按月排课;课程库保存可重复使用的课件和试题,签到、录制、考试发布和完成状态记在月度场次上。未完成提醒每周一 09:00 发给当月仍有未完成场次的讲师,文案对齐人事课内部邮件。细则见 [features/training/annual-training-plan-demand.md](features/training/annual-training-plan-demand.md),设计方案见 [features/training/annual-training-plan-design.md](features/training/annual-training-plan-design.md),原型见 [features/training/annual-training-plan-prototype.html](features/training/annual-training-plan-prototype.html)。
|
||||||
@@ -19,8 +12,8 @@
|
|||||||
|
|
||||||
## 可配置权限组(2026-09)
|
## 可配置权限组(2026-09)
|
||||||
|
|
||||||
- 每位用户可同时挂多个业务角色(权限组);生效权限是这些角色的应用与能力并集。平台管理员不与其他角色叠加。拿掉最后一个业务角色后回到默认「普通用户」。部门只用于选人筛选,不自动授权。
|
- 每位用户只选一个权限组(角色包);角色 = 可用应用入口 + 应用内能力。部门只用于选人筛选,不自动授权。
|
||||||
- 新建用户由管理员选角色,可多选,默认「普通用户」。新增应用时先勾到需要的角色,再按人数弹窗选人;全选只勾草稿,确定后必须确认追加或移出。
|
- 新建用户由管理员选角色,默认「普通用户」。新增应用时先勾到需要的角色,再按人数弹窗选人;全选只勾草稿,确定后必须确认增减(含来源角色)。
|
||||||
- 管理员为锁定角色(`code=admin`):应用入口隐式全开,选人弹窗不能添加或移出;用户管理改到/改出管理员须额外确认,且不能撤掉最后一名启用中的管理员。
|
- 管理员为锁定角色(`code=admin`):应用入口隐式全开,选人弹窗不能添加或移出;用户管理改到/改出管理员须额外确认,且不能撤掉最后一名启用中的管理员。
|
||||||
- 平台管理员从 AI 工作台进入管理控制台:侧栏底部「返回聊天」上方展示入口,普通用户不显示;对话页齿轮入口保持不变。
|
- 平台管理员从 AI 工作台进入管理控制台:侧栏底部「返回聊天」上方展示入口,普通用户不显示;对话页齿轮入口保持不变。
|
||||||
- 迁移按现网 `users.role` 枚举套标准包(普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员);不再种子设备维保专员,原 `maintenance_manager` 收口到普通用户。个人额外 Agent 勾选丢弃。原型见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
|
- 迁移按现网 `users.role` 枚举套标准包(普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员);不再种子设备维保专员,原 `maintenance_manager` 收口到普通用户。个人额外 Agent 勾选丢弃。原型见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
|
||||||
@@ -33,9 +26,8 @@
|
|||||||
## 设备验收预警(2026-09)
|
## 设备验收预警(2026-09)
|
||||||
|
|
||||||
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
|
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
|
||||||
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人;E8 与 E10 相同,不取当前节点未办人。采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:30 按收件人发送汇总卡片和 Excel 明细(错开合同付款 18:00)。
|
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。
|
||||||
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:30 扫描、每周五 18:30 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。
|
||||||
- E8 补抓已接上(2026-10-26)。与 E10 分来源保存。暂停按撤销停表。没有作废、强制结束。见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md)、[technical.md](features/equipment-acceptance-warning/technical.md)。
|
|
||||||
|
|
||||||
## 合同付款预警 Agent(2026-08)
|
## 合同付款预警 Agent(2026-08)
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,6 @@
|
|||||||
| [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [工作台原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) · [人工复核原型](contract-payment-plan/contract-payment-review-prototype.html) · [Chat Agent 原型](contract-payment-plan/contract-payment-chat-agent-prototype.html) |
|
| [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [工作台原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) · [人工复核原型](contract-payment-plan/contract-payment-review-prototype.html) · [Chat Agent 原型](contract-payment-plan/contract-payment-chat-agent-prototype.html) |
|
||||||
| [equipment-maintenance](equipment-maintenance/README.md) | 设备维保助手 | [聊天原型](equipment-maintenance/equipment-maintenance-agent-chat-lofi.html) |
|
| [equipment-maintenance](equipment-maintenance/README.md) | 设备维保助手 | [聊天原型](equipment-maintenance/equipment-maintenance-agent-chat-lofi.html) |
|
||||||
| [equipment-acceptance-warning](equipment-acceptance-warning/README.md) | 设备验收停留预警 | [需求说明](equipment-acceptance-warning/demand.md) · [数据设计](equipment-acceptance-warning/technical.md) |
|
| [equipment-acceptance-warning](equipment-acceptance-warning/README.md) | 设备验收停留预警 | [需求说明](equipment-acceptance-warning/demand.md) · [数据设计](equipment-acceptance-warning/technical.md) |
|
||||||
| [process-quality-alert](process-quality-alert/demand.md) | 制程品质异常预警 | [需求说明](process-quality-alert/demand.md) · [原型](process-quality-alert/process-quality-alert-prototype.html) |
|
|
||||||
| [training](training/) | 教育训练:新人培训与年度计划 | [年度教育训练计划需求](training/annual-training-plan-demand.md) · [设计方案](training/annual-training-plan-design.md) · [可点击原型](training/annual-training-plan-prototype.html) · [精益周任务规则](training/精益管理周任务规则手册.md) |
|
| [training](training/) | 教育训练:新人培训与年度计划 | [年度教育训练计划需求](training/annual-training-plan-demand.md) · [设计方案](training/annual-training-plan-design.md) · [可点击原型](training/annual-training-plan-prototype.html) · [精益周任务规则](training/精益管理周任务规则手册.md) |
|
||||||
| [faq](faq/) | 常用问题 / FAQ 缓存直答 | [运维手册](faq/faq_cache_ops_manual.md) · [模糊查询与 AI 自动维护设计](faq/faq_fuzzy_and_ai_maintenance_design.md) |
|
| [faq](faq/) | 常用问题 / FAQ 缓存直答 | [运维手册](faq/faq_cache_ops_manual.md) · [模糊查询与 AI 自动维护设计](faq/faq_fuzzy_and_ai_maintenance_design.md) |
|
||||||
|
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ flowchart TD
|
|||||||
| -------- | ------------------------------------------------------------------------------------------------------- |
|
| -------- | ------------------------------------------------------------------------------------------------------- |
|
||||||
| 触发 | 本批存在必检文件缺件 |
|
| 触发 | 本批存在必检文件缺件 |
|
||||||
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
|
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
|
||||||
| 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示下一条消息是本批 Excel。不写业务方代号和批次号。卡片发出后另发本批检核结果 Excel 文件 |
|
| 内容 | 标题为「销售开票附件缺件」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 |
|
||||||
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
|
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
|
||||||
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
|
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
|
||||||
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
|
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
|
||||||
@@ -268,10 +268,10 @@ flowchart TD
|
|||||||
1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。
|
1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。
|
||||||
2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。
|
2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。
|
||||||
3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。
|
3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。
|
||||||
4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型;卡片之后发送本批 Excel 文件。完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。
|
4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。
|
||||||
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
|
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
|
||||||
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。
|
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。
|
||||||
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。文档库自动加上的「(重命名)」改回原名,同一目录多出来的该后缀副本删除。
|
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。
|
||||||
|
|
||||||
## 9. 待补充事项
|
## 9. 待补充事项
|
||||||
|
|
||||||
|
|||||||
@@ -281,7 +281,7 @@ OA 销货放行申请单改为查 E10 `ecology10.dbo.ft_xqqgsq`:出货时间 `
|
|||||||
|
|
||||||
类型目录与一期文件对应(**已确认固定,不改名**):`PO订单`、`报关资料`、`销货放行申请单`、`发票`、`报关单`、`提单`。
|
类型目录与一期文件对应(**已确认固定,不改名**):`PO订单`、`报关资料`、`销货放行申请单`、`发票`、`报关单`、`提单`。
|
||||||
|
|
||||||
ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 `invoice` 关联、命名和文件完整性校验后,**复制**到「所有归档」下该发票子目录(不移动类型目录原件)。同一 `invoice` 的所有成功资料必须集中在同一归档子目录。**重复文件策略:同名跳过**——目标子目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档。文档库自动改成 `原名.pdf(重命名)` 时,先删掉多余副本,再用 `Item/Rename` 把留下的那份改成不含扩展名的 `原名`。改成 `原名.pdf` 会被文档库判成同名。类型目录写入失败或归档复制失败属于技术失败,不可降级为缺件。
|
ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 `invoice` 关联、命名和文件完整性校验后,**复制**到「所有归档」下该发票子目录(不移动类型目录原件)。同一 `invoice` 的所有成功资料必须集中在同一归档子目录。**重复文件策略:同名跳过**——目标子目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档。类型目录写入失败或归档复制失败属于技术失败,不可降级为缺件。
|
||||||
|
|
||||||
### 5.2 建议持久化实体
|
### 5.2 建议持久化实体
|
||||||
|
|
||||||
@@ -318,7 +318,7 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
|
|||||||
|
|
||||||
### 6.2 通知聚合
|
### 6.2 通知聚合
|
||||||
|
|
||||||
缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型,卡片之后再发本批检核结果 Excel。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。
|
缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。
|
||||||
|
|
||||||
### 6.3 检核任务列表
|
### 6.3 检核任务列表
|
||||||
|
|
||||||
|
|||||||
@@ -373,7 +373,7 @@ sequenceDiagram
|
|||||||
|
|
||||||
- ERP/OA 打印或目录扫描的成功文件先写入当月类型存放目录,再校验关联字段和命名后复制到「所有归档/{invoice_no}/」。
|
- ERP/OA 打印或目录扫描的成功文件先写入当月类型存放目录,再校验关联字段和命名后复制到「所有归档/{invoice_no}/」。
|
||||||
- 同一 invoice 的所有文件进入同一归档子目录;不同 invoice 不得混放。
|
- 同一 invoice 的所有文件进入同一归档子目录;不同 invoice 不得混放。
|
||||||
- 复制采用幂等策略:**同名跳过**。目标目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档;不按内容指纹覆盖。文档库复制后的真实名字是 `原名.pdf(重命名)`,扩展名存在附件上,界面显示为 `原名.pdf(重命名).pdf`。把它改成 `原名.pdf` 会被判成同名;`Item/Rename` 只写入不含扩展名的 `原名`。同一目录多出来的该后缀副本先 `Item/Recycle` 删除(进入回收站,不彻底删除)。归档只 `Copy`、不 `Move`。
|
- 复制采用幂等策略:**同名跳过**。目标目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档;不按内容指纹覆盖。归档只 `Copy`、不 `Move`。
|
||||||
- `invoice_no`、业务单号和路径变量必须做路径穿越校验。
|
- `invoice_no`、业务单号和路径变量必须做路径穿越校验。
|
||||||
- 临时目录和日志不得输出密码、Token 或完整外部系统会话信息。
|
- 临时目录和日志不得输出密码、Token 或完整外部系统会话信息。
|
||||||
- 归档记录保存来源路径、临时路径、归档路径、指纹、Profile 版本和处理时间。
|
- 归档记录保存来源路径、临时路径、归档路径、指纹、Profile 版本和处理时间。
|
||||||
|
|||||||
@@ -171,7 +171,7 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
|||||||
- 周汇总批次发送失败时,发送状态旁提供图标;点击后展示该批次的失败原因(如收件人未绑定企业微信、卡片或附件发送失败及企微返回说明)。
|
- 周汇总批次发送失败时,发送状态旁提供图标;点击后展示该批次的失败原因(如收件人未绑定企业微信、卡片或附件发送失败及企微返回说明)。
|
||||||
- 合同台账与待确认列表应支持按合同编号、流程编号、采购单号、供应商名称或申请人模糊检索。
|
- 合同台账与待确认列表应支持按合同编号、流程编号、采购单号、供应商名称或申请人模糊检索。
|
||||||
- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、未到期 7 日外、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。即将到期、逾期未付、未到期互斥;本月应付可与这三项重叠。行级「待补充」仍可出现在状态列,但不作为汇总卡。
|
- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、未到期 7 日外、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。即将到期、逾期未付、未到期互斥;本月应付可与这三项重叠。行级「待补充」仍可出现在状态列,但不作为汇总卡。
|
||||||
- 合同台账四个阶段列都按日期依据显示已逾期、即将到期或未到期。四个阶段对上 ERP 或手动标记后显示已付。日期依据缺失时写明原因,不使用「待补充日期」:预付款为合同归档日未填,出货款为交货日期未填,验收款为验收单未归档,质保款为质保到期日未定。
|
- 合同台账四个阶段列都按日期依据显示已逾期、即将到期或未到期。预付款和出货款另可显示已付;验收款和质保款不能标已付。日期依据缺失时写明原因,不使用「待补充日期」:预付款为合同归档日未填,出货款为交货日期未填,验收款为验收单未归档,质保款为质保到期日未定。
|
||||||
- 同步 OA、强制覆盖 OA 字段、批量重解析存量合同、扫描生成预警和发送预警仅管理员可见;普通授权用户只可查询台账、详情和周汇总批次。
|
- 同步 OA、强制覆盖 OA 字段、批量重解析存量合同、扫描生成预警和发送预警仅管理员可见;普通授权用户只可查询台账、详情和周汇总批次。
|
||||||
- 管理员可手动触发 OA 同步和预警扫描;执行应后台异步化,不阻塞页面请求。
|
- 管理员可手动触发 OA 同步和预警扫描;执行应后台异步化,不阻塞页面请求。
|
||||||
|
|
||||||
|
|||||||
@@ -5,4 +5,4 @@
|
|||||||
| **需求说明** | 产品、业务、研发 | [demand.md](demand.md) |
|
| **需求说明** | 产品、业务、研发 | [demand.md](demand.md) |
|
||||||
| **数据设计** | 研发 | [technical.md](technical.md) |
|
| **数据设计** | 研发 | [technical.md](technical.md) |
|
||||||
|
|
||||||
**状态**:E10 与 E8 都按使用部门担当发第 1 档。E8 暂停按停表。见 [funclist.md](../../funclist.md)「设备验收预警」。
|
**状态**:规则已冻结(2026-09-29)。只读同步、Chat 作业面、每日扫描和周五企业微信已实现(2026-10-12)。入口与合同付款预警相同,内置 Agent `equipment_acceptance`。页签有停留情况、发送记录和预警配置。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。见 [funclist.md](../../funclist.md)「设备验收预警」。
|
||||||
@@ -210,9 +210,9 @@
|
|||||||
<label class="day">超过 <input value="30" /> 天</label>
|
<label class="day">超过 <input value="30" /> 天</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="people">
|
<div class="people">
|
||||||
<div class="line"><span class="tag">主送</span><span class="plain">使用部门担当</span></div>
|
<div class="line"><span class="tag">主送</span><span class="plain">当前节点处理人</span></div>
|
||||||
<div class="line"><span class="tag">抄送</span><span class="plain">其直接主管、采购担当</span></div>
|
<div class="line"><span class="tag">抄送</span><span class="plain">其直接主管、采购担当</span></div>
|
||||||
<span class="note">随单据上的使用部门担当变化,这里不选人</span>
|
<span class="note">随当前单据变化,这里不选人</span>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
@@ -222,7 +222,7 @@
|
|||||||
<label class="day">超过 <input value="37" /> 天</label>
|
<label class="day">超过 <input value="37" /> 天</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="people">
|
<div class="people">
|
||||||
<div class="line"><span class="tag">主送</span><span class="plain">使用部门担当的经副理</span></div>
|
<div class="line"><span class="tag">主送</span><span class="plain">当前节点处理人的经副理</span></div>
|
||||||
<div class="line">
|
<div class="line">
|
||||||
<span class="tag">抄送</span>
|
<span class="tag">抄送</span>
|
||||||
<div class="chips">
|
<div class="chips">
|
||||||
|
|||||||
@@ -1,42 +1,101 @@
|
|||||||
# 设备验收预警需求说明
|
# 设备验收预警需求说明
|
||||||
|
|
||||||
> **版本**:V2.0
|
> **版本**:V1.0
|
||||||
> **更新日期**:2026-10-26
|
> **更新日期**:2026-10-08
|
||||||
> **状态**:E10 已上线。E8 查询已接上。字段和关联见 [technical.md](technical.md)。
|
> **状态**:规则已冻结。只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。发送时刻不在配置页,默认排程每天 06:00 扫描、每周五 18:00 发送。数据设计见 [technical.md](technical.md)。
|
||||||
|
> **适用范围**:OA 资产验收单停留预警、企业微信通知、固定岗位配置
|
||||||
|
|
||||||
验收单从第一次进入「使用部门担当」起按自然日累计。未归档、已经开始计时,且可以验收不是明确为否的单据,超过 30 / 37 / 44 / 51 天升级提醒。合同付款预警只在归档后取日期,本需求不改那条规则。
|
## 1. 背景与目标
|
||||||
|
|
||||||
## 1. 哪些单要提醒
|
资产验收流程可能在某个节点停留很久。从流程进入「使用部门担当」起按自然日累计停留时间,对仍可验收的未归档单据按 30/37/44/51 天升级提醒,避免验收长期挂起。
|
||||||
|
|
||||||
| 条件 | 结果 |
|
现有合同付款预警只在验收单归档后读取 OA(`formtable_main_324`,`currentnodetype=3`),不监控进行中的节点停留。本需求是独立能力,不改付款预警的归档口径。
|
||||||
| --- | --- |
|
|
||||||
| 未归档,可以验收为是或未标明,计时起点已有值 | 提醒 |
|
|
||||||
| 还没进入使用部门担当 | 不计时 |
|
|
||||||
| 可以验收明确为否 | 不监控 |
|
|
||||||
| 退回、撤销 | 停表,取消还没发出的提醒,仍留在列表 |
|
|
||||||
| 归档 | 不抓、不进列表。下次同步从本地删掉,未发出的提醒取消 |
|
|
||||||
| E10 的作废、强制结束、暂停 | 停表 |
|
|
||||||
| E8 | 没有作废、强制结束。暂停与 E10 一样停表 |
|
|
||||||
|
|
||||||
计时起点写入后不改。换后续节点,或退回、无法验收后再进入,仍从第一次的起点累计,不从 0 重计,已发过的档不重发。
|
## 2. 范围
|
||||||
|
|
||||||
## 2. 谁收
|
### 2.1 本期已冻结
|
||||||
|
|
||||||
每一档在同一段累计里只发一次。超过才发,刚好等于不发。第 4 档默认关闭。
|
- 监控对象、计时起点、自然日累计、停表与再进入规则。
|
||||||
|
- 四档升级的主送、抄送,以及当前节点处理人、上级、申请人的取人规则。
|
||||||
|
- 采购经副理、COO、总经理三个固定岗位可在管理界面配置,禁止在代码中写死姓名或账号。
|
||||||
|
- 企业微信为唯一通知渠道。每日扫描只生成待发送记录;发送时刻可配置,初始为每周五 18:00,按收件人汇总一条。
|
||||||
|
- 数据来源见第 7 节。缺字段的单据跳过并留下原因。
|
||||||
|
|
||||||
| 超过 | 主送 | 抄送 |
|
停留列表已接到对话页:内置 Chat Agent `equipment_acceptance`,与合同付款预警一样替换消息列表和输入框。
|
||||||
|
|
||||||
|
### 2.2 本期不做
|
||||||
|
|
||||||
|
- 不接 Dify 对话。
|
||||||
|
- 不撤回已发送的企业微信。停表只取消尚未发出的预警。
|
||||||
|
- 「使用部门担当」之前的节点(ERP 触发、申请人确认、直属上级)不参与计时。
|
||||||
|
|
||||||
|
## 3. 监控对象
|
||||||
|
|
||||||
|
数据源是 E10 验收单主表,字段对照见 [technical.md](technical.md)。只纳入同时满足以下条件的流程:
|
||||||
|
|
||||||
|
- 未归档
|
||||||
|
- 有效(未撤回、未作废)
|
||||||
|
- 可以验收
|
||||||
|
|
||||||
|
计时起点是该流程**第一次进入「使用部门担当」**。进入之后按自然日持续累计,中途更换后续节点不重置。流程图上该节点之后的使用部门经理、品质担当、品质经理、公用主管、设备管理部、设备管理部经理、固定资产管理人、COO、总经理、总务知会,都算在同一段累计时间里。节点正式名称以 OA 为准。
|
||||||
|
|
||||||
|
## 4. 停表与再进入
|
||||||
|
|
||||||
|
出现任一情况立即停止计时,并取消尚未发出的预警:
|
||||||
|
|
||||||
|
- 归档
|
||||||
|
- 退回、撤回、作废
|
||||||
|
- 验收单上为无法验收(说明正文是 `ycsm`,只作留痕,不单独触发通知)
|
||||||
|
|
||||||
|
已确认:退回或无法验收后再进入,「使用部门担当」的计时起点 `sbsyrjssj` 不会改写,签核天数仍按第一次写入的时间计算,不从 0 重计,也不另找起点。四档按这一段累计天数各发一次,不因再进入而重发。`sfzfth` 不考虑从退回(`0`)改回正常(`1` 或空);不靠这个变化恢复计时。撤回、作废、归档后的同一请求不再恢复。
|
||||||
|
|
||||||
|
## 5. 升级与收件人
|
||||||
|
|
||||||
|
每一档在同一计时周期只产生一次待发送。每日扫描判断是否跨档,跨档后等到固定推送时刻再发。一次汇总前若跨了多档,各档都保留,合并进该收件人的同一条汇总,不逐单刷屏。
|
||||||
|
|
||||||
|
| 停留 | 主送 | 抄送 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 30 天 | 使用部门担当 | 其直接主管、采购担当 |
|
| 超过 30 天 | 当前节点处理人(担当) | 其直接主管、采购担当 |
|
||||||
| 37 天 | 该担当的经副理 | COO、采购经副理 |
|
| 超过 37 天 | 当前节点处理人的经副理 | COO、采购经副理 |
|
||||||
| 44 天 | COO | 采购经副理 |
|
| 超过 44 天 | COO | 采购经副理 |
|
||||||
| 51 天 | 总经理 | COO、采购经副理 |
|
| 超过 51 天 | 总经理 | COO、采购经副理 |
|
||||||
|
|
||||||
- 使用部门担当、直接主管、经副理都按表单上的使用部门担当取,不按当前节点未办人。E8 与 E10 相同。
|
第 4 轮在配置里单独开关,默认关闭。关闭时不生成、也不发送总经理这一轮。打开后,下一次扫描才按超过第 4 档的天数产生待发送。前 3 轮不受这个开关影响。
|
||||||
- 采购担当是申请人。
|
|
||||||
- COO、采购经副理、总经理在配置页选择。
|
|
||||||
- 对不上人就记失败,不改发给别人。
|
|
||||||
|
|
||||||
## 3. 怎么发
|
人员解析:
|
||||||
|
|
||||||
- 每天 06:30 扫描,生成待发送(错开合同付款 06:00)。默认每周五 18:30 按收件人发一条企业微信汇总,并附一份只含该人的 Excel(错开合同付款周五 18:00)。时刻可改。
|
- 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。
|
||||||
- 已发送的不撤回、不重发。
|
- 采购担当取该流程的**申请人**。
|
||||||
|
- 采购经副理、COO、总经理是固定岗位。配置初始值分别为赵琴、COO、廖总,必须能在管理界面修改。代码与环境文件不得写死这三个人的姓名或账号。
|
||||||
|
- 当前节点有多名处理人时,主送这些处理人;直接主管、经副理按各处理人展开后去重。
|
||||||
|
- 收件人解析失败(无上级、未绑定企业微信)时,该条保持失败可追查,不改发给别人。
|
||||||
|
|
||||||
|
## 6. 推送
|
||||||
|
|
||||||
|
已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总卡片,并紧跟一份只含该收件人明细的 Excel。这份 Excel 按收件人归档,挂在发送记录表的 Excel 附件列上,点文件名再下载。卡片不逐条列出验收单,也不区分主送和抄送。渠道只有企业微信。
|
||||||
|
|
||||||
|
## 7. 数据来源
|
||||||
|
|
||||||
|
权威设计见 [technical.md](technical.md)。摘要如下:
|
||||||
|
|
||||||
|
- 连接只用 `.env.shared` 的 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`。验收单在 `ecology10`,流程实例字典库为 `weaver_wfc`,节点定义字典库为 `weaver_wfp`。
|
||||||
|
- 验收单主表是 `ecology10.dbo.ft_gdzcysdv2`。验收单单号 `ysddh`,采购单号 `cgdh`。计时起点 `sbsyrjssj` 只在第一次进入「使用部门担当」时写入,之后不改。
|
||||||
|
- `sybmdd`(使用部门担当)、`sbglry`(设备管理人员)存人员 ID,关联 `eteams.dbo.employee.ID`,用工号 `JOB_NUM` 匹配 HXOPS 用户。
|
||||||
|
- `sfkyzcys` 是是否可以正常验收:**0 是可以,1 是不可以**,与常见 0/1 相反。空值不纳入监控。无法验收说明正文是 `ycsm`,只留痕,不单独触发停表。
|
||||||
|
- `sfzfth`:**0 是退回,1 和空都是流程正常。** 空值不当成退回。作废不看这一列。
|
||||||
|
- 未归档、归档、作废、撤销看 `wfc_requestbase.flowstatus`(`1` 审批中,`3` 正常归档,`5` 已作废)。`7`、`8`、`99`、`-99` 都按撤销处理,停表且不再提醒。当前节点看 `weaver_wfc.dbo.wfc_currentnode.nodeid`,名称关联 `weaver_wfp.dbo.wfp_node`。`lastnodeid` 是最后操作节点,不当作当前节点。申请人 `sqr` 已确认是人员 ID。
|
||||||
|
- 当前处理人在 `weaver_wfc.dbo.wfc_operate`。`userid` 是操作人,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一人只留一行。每日扫描按这些人展开四档收件人。
|
||||||
|
|
||||||
|
直接主管取当前处理人的 `employee.SUPERIOR`。经副理用该人的 `employee.DEPARTMENT` 查 `eteams.dbo.hrm_matrix_condition_data`,人在 `eteams.dbo.hrm_matrix_value_data.relate_id`。不查 E8 矩阵。采购经副理、COO、总经理不从矩阵取,只读界面配置。
|
||||||
|
|
||||||
|
## 8. 验收标准(视图到位后的实现对照)
|
||||||
|
|
||||||
|
| 编号 | 条件 | 期望 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| AC-01 | 尚未进入「使用部门担当」 | 不计时、不产生预警 |
|
||||||
|
| AC-02 | 签核天数超过 30/37/44/51 | 各档只产生一次待发送,刚好等于还不发。收件人符合第 5 节 |
|
||||||
|
| AC-03 | 进入后更换后续节点 | 累计天数不重置 |
|
||||||
|
| AC-04 | 归档、退回、撤回、作废或无法验收 | 立即停表,取消未发送预警,已发送消息保留 |
|
||||||
|
| AC-05 | 退回或无法验收后再次进入 | 签核天数仍从原 `sbsyrjssj` 计算。不把 `sfzfth` 从 `0` 改回正常当作恢复 |
|
||||||
|
| AC-06 | 发送时刻 | 默认每周五 18:00 按收件人汇总;时刻可配置 |
|
||||||
|
| AC-07 | 修改采购经副理、COO、总经理配置 | 此后新产生的预警使用新人员,不改历史已发送记录 |
|
||||||
+16
-17
@@ -175,7 +175,7 @@
|
|||||||
<section class="view" id="v-config">
|
<section class="view" id="v-config">
|
||||||
<div class="hero"><div><h1>预警配置</h1><p>天数默认 30、37、44、51,须逐档增大。保存后只影响尚未发送的预警。</p></div></div>
|
<div class="hero"><div><h1>预警配置</h1><p>天数默认 30、37、44、51,须逐档增大。保存后只影响尚未发送的预警。</p></div></div>
|
||||||
<div class="ladder">
|
<div class="ladder">
|
||||||
<label class="rung"><span class="k">第 1 档</span><span class="num"><input id="cfgDay0" type="number" min="1" value="30" /><em>天</em></span><small id="rungWho0">使用部门担当</small></label>
|
<label class="rung"><span class="k">第 1 档</span><span class="num"><input id="cfgDay0" type="number" min="1" value="30" /><em>天</em></span><small id="rungWho0">当前处理人</small></label>
|
||||||
<label class="rung"><span class="k">第 2 档</span><span class="num"><input id="cfgDay1" type="number" min="1" value="37" /><em>天</em></span><small id="rungWho1">经副理</small></label>
|
<label class="rung"><span class="k">第 2 档</span><span class="num"><input id="cfgDay1" type="number" min="1" value="37" /><em>天</em></span><small id="rungWho1">经副理</small></label>
|
||||||
<label class="rung"><span class="k">第 3 档</span><span class="num"><input id="cfgDay2" type="number" min="1" value="44" /><em>天</em></span><small id="rungWho2">COO</small></label>
|
<label class="rung"><span class="k">第 3 档</span><span class="num"><input id="cfgDay2" type="number" min="1" value="44" /><em>天</em></span><small id="rungWho2">COO</small></label>
|
||||||
<label class="rung"><span class="k">第 4 档</span><span class="num"><input id="cfgDay3" type="number" min="1" value="51" /><em>天</em></span><small id="rungWho3">总经理</small></label>
|
<label class="rung"><span class="k">第 4 档</span><span class="num"><input id="cfgDay3" type="number" min="1" value="51" /><em>天</em></span><small id="rungWho3">总经理</small></label>
|
||||||
@@ -217,29 +217,28 @@
|
|||||||
let digest = null;
|
let digest = null;
|
||||||
const cfg = { buyer: '赵琴', coo: 'COO', boss: '廖总', when: '每周五 18:00', days: [30, 37, 44, 51] };
|
const cfg = { buyer: '赵琴', coo: 'COO', boss: '廖总', when: '每周五 18:00', days: [30, 37, 44, 51] };
|
||||||
const orders = [
|
const orders = [
|
||||||
{ id:'YS-2026-0138', po:'CG-2026-0812', applicant:'王磊', node:'设备管理部', owner:'陈工', handlers:['陈工'], supervisor:'何主管', deputy:'周经副理', entered:'2026-08-08', days:53, cycle:1, state:'watching', sent:[0,1,2], fail:'', stop:'', note:'同一周期已发过前三档,本周只待第 4 档。' },
|
{ id:'YS-2026-0138', po:'CG-2026-0812', applicant:'王磊', node:'设备管理部', handlers:['陈工'], supervisor:'何主管', deputy:'周经副理', entered:'2026-08-08', days:53, cycle:1, state:'watching', sent:[0,1,2], fail:'', stop:'', note:'同一周期已发过前三档,本周只待第 4 档。' },
|
||||||
{ id:'YS-2026-0142', po:'CG-2026-0744', applicant:'张敏', node:'品质经理', owner:'李倩', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-15', days:46, cycle:1, state:'watching', sent:[0,1], fail:'', stop:'', note:'换到品质经理后累计不重置。' },
|
{ id:'YS-2026-0142', po:'CG-2026-0744', applicant:'张敏', node:'品质经理', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-15', days:46, cycle:1, state:'watching', sent:[0,1], fail:'', stop:'', note:'换到品质经理后累计不重置。' },
|
||||||
{ id:'YS-2026-0155', po:'CG-2026-0901', applicant:'赵丽', node:'使用部门经理', owner:'周涛', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-23', days:38, cycle:1, state:'watching', sent:[0], fail:'', stop:'', note:'' },
|
{ id:'YS-2026-0155', po:'CG-2026-0901', applicant:'赵丽', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-23', days:38, cycle:1, state:'watching', sent:[0], fail:'', stop:'', note:'' },
|
||||||
{ id:'YS-2026-0160', po:'CG-2026-0886', applicant:'孙浩', node:'公用主管', owner:'吴敏', handlers:['吴敏','林可'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-30', days:31, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'当前节点有两名处理人,第 1 档只发给使用部门担当吴敏,抄送其直接主管钱伟。' },
|
{ id:'YS-2026-0160', po:'CG-2026-0886', applicant:'孙浩', node:'公用主管', handlers:['吴敏','林可'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-30', days:31, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'当前节点两名处理人,直接主管相同,抄送去重为钱伟。' },
|
||||||
{ id:'YS-2026-0188', po:'CG-2026-0910', applicant:'刘洋', node:'品质担当', owner:'郑凯', handlers:['郑凯'], supervisor:'', deputy:'孙经理', entered:'2026-08-28', days:33, cycle:1, state:'watching', sent:[], fail:'直接主管缺失', stop:'', note:'第 1 档无法解析使用部门担当的直接主管,保持失败,不改发。' },
|
{ id:'YS-2026-0188', po:'CG-2026-0910', applicant:'刘洋', node:'品质担当', handlers:['郑凯'], supervisor:'', deputy:'孙经理', entered:'2026-08-28', days:33, cycle:1, state:'watching', sent:[], fail:'直接主管缺失', stop:'', note:'第 1 档无法解析直接主管,保持失败,不改发。' },
|
||||||
{ id:'YS-2026-0172', po:'CG-2026-0933', applicant:'陈静', node:'品质担当', owner:'郑凯', handlers:['郑凯'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-10', days:20, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'未超过第 1 档,只监控不发。' },
|
{ id:'YS-2026-0172', po:'CG-2026-0933', applicant:'陈静', node:'品质担当', handlers:['郑凯'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-10', days:20, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'未超过第 1 档,只监控不发。' },
|
||||||
{ id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', owner:'马超', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-10', days:60, cycle:1, state:'watching', sent:[0,1,2,3], fail:'', stop:'', note:'无法验收后再进入,签核天数仍从第一次写入的计时起点计算,不从 0 重计。' },
|
{ id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-10', days:60, cycle:1, state:'watching', sent:[0,1,2,3], fail:'', stop:'', note:'无法验收后再进入,签核天数仍从第一次写入的计时起点计算,不从 0 重计。' },
|
||||||
{ id:'YS-2026-0071', po:'CG-2026-0550', applicant:'吴芳', node:'品质经理', owner:'李倩', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-01', days:40, cycle:1, state:'stopped', sent:[0], fail:'', stop:'无法验收', note:'无法验收说明:到货规格与请购不符。未发送的后续档已取消。' },
|
{ id:'YS-2026-0071', po:'CG-2026-0550', applicant:'吴芳', node:'品质经理', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-01', days:40, cycle:1, state:'stopped', sent:[0], fail:'', stop:'无法验收', note:'无法验收说明:到货规格与请购不符。未发送的后续档已取消。' },
|
||||||
{ id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', owner:'周涛', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。再进入仍用第一次的计时起点,不按 sfzfth 改回正常来恢复。' },
|
{ id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。再进入仍用第一次的计时起点,不按 sfzfth 改回正常来恢复。' },
|
||||||
{ id:'YS-2026-0201', po:'CG-2026-1008', applicant:'韩冰', node:'直属上级', owner:'', handlers:['—'], supervisor:'', deputy:'', entered:'', days:0, cycle:0, state:'out', sent:[], fail:'', stop:'', note:'尚未进入使用部门担当,不计时。' }
|
{ id:'YS-2026-0201', po:'CG-2026-1008', applicant:'韩冰', node:'直属上级', handlers:['—'], supervisor:'', deputy:'', entered:'', days:0, cycle:0, state:'out', sent:[], fail:'', stop:'', note:'尚未进入使用部门担当,不计时。' }
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按档位序号取主送与抄送。天数读配置,人员规则不随天数变化。
|
* 按档位序号取主送与抄送。天数读配置,人员规则不随天数变化。
|
||||||
* 第 1 档主送使用部门担当,抄送其直接主管和申请人。第 2 档主送该担当的经副理。其后两档读固定岗位。
|
* 第 1 档取当前处理人及其主管、申请人;其后三档读固定岗位。
|
||||||
*/
|
*/
|
||||||
function audience(order, level) {
|
function audience(order, level) {
|
||||||
if (level === 0) {
|
if (level === 0) {
|
||||||
const cc = [];
|
const cc = [];
|
||||||
if (order.supervisor) cc.push(order.supervisor);
|
if (order.supervisor) cc.push(order.supervisor);
|
||||||
cc.push(order.applicant + '(采购担当)');
|
cc.push(order.applicant + '(采购担当)');
|
||||||
const blocked = order.owner ? (order.supervisor ? '' : '直接主管缺失') : '使用部门担当缺失';
|
return { to: order.handlers.slice(), cc, blocked: order.supervisor ? '' : '直接主管缺失' };
|
||||||
return { to: order.owner ? [order.owner] : [], cc, blocked };
|
|
||||||
}
|
}
|
||||||
if (level === 1) return { to:[order.deputy], cc:[cfg.coo, cfg.buyer], blocked: order.deputy ? '' : '经副理缺失' };
|
if (level === 1) return { to:[order.deputy], cc:[cfg.coo, cfg.buyer], blocked: order.deputy ? '' : '经副理缺失' };
|
||||||
if (level === 2) return { to:[cfg.coo], cc:[cfg.buyer], blocked:'' };
|
if (level === 2) return { to:[cfg.coo], cc:[cfg.buyer], blocked:'' };
|
||||||
@@ -437,14 +436,14 @@
|
|||||||
*/
|
*/
|
||||||
function renderRules() {
|
function renderRules() {
|
||||||
const rows = [
|
const rows = [
|
||||||
[cfg.days[0], '使用部门担当', '其直接主管、采购担当'],
|
[cfg.days[0], '当前节点处理人', '直接主管、采购担当'],
|
||||||
[cfg.days[1], '使用部门担当的经副理', cfg.coo + '、' + cfg.buyer],
|
[cfg.days[1], '当前处理人的经副理', cfg.coo + '、' + cfg.buyer],
|
||||||
[cfg.days[2], cfg.coo, cfg.buyer],
|
[cfg.days[2], cfg.coo, cfg.buyer],
|
||||||
[cfg.days[3], cfg.boss, cfg.coo + '、' + cfg.buyer]
|
[cfg.days[3], cfg.boss, cfg.coo + '、' + cfg.buyer]
|
||||||
];
|
];
|
||||||
$('ruleBox').innerHTML = rows.map(([day, to, cc]) => '<tr><td><b>超过 ' + day + ' 天</b></td><td>' + to + '</td><td>' + cc + '</td></tr>').join('')
|
$('ruleBox').innerHTML = rows.map(([day, to, cc]) => '<tr><td><b>超过 ' + day + ' 天</b></td><td>' + to + '</td><td>' + cc + '</td></tr>').join('')
|
||||||
+ '<tr><td><b>解析失败</b></td><td colspan="2">保持失败可追查,不改发给别人</td></tr>';
|
+ '<tr><td><b>解析失败</b></td><td colspan="2">保持失败可追查,不改发给别人</td></tr>';
|
||||||
['使用部门担当', '使用部门担当的经副理', cfg.coo, cfg.boss].forEach((text, index) => { $('rungWho' + index).textContent = text; });
|
['当前处理人', '经副理', cfg.coo, cfg.boss].forEach((text, index) => { $('rungWho' + index).textContent = text; });
|
||||||
$('banner').textContent = '从第一次进入「使用部门担当」起按自然日累计,换节点不重新计算。超过 ' + cfg.days.join('/') + ' 天各提醒一次,' + cfg.when + ' 合并成一条企业微信。无法验收、退回、撤回、作废或归档后不再提醒。';
|
$('banner').textContent = '从第一次进入「使用部门担当」起按自然日累计,换节点不重新计算。超过 ' + cfg.days.join('/') + ' 天各提醒一次,' + cfg.when + ' 合并成一条企业微信。无法验收、退回、撤回、作废或归档后不再提醒。';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,154 +1,438 @@
|
|||||||
# 设备验收预警数据来源
|
# 设备验收预警设计
|
||||||
|
|
||||||
> **版本**:V2.0
|
> **版本**:V1.19
|
||||||
> **更新日期**:2026-10-26
|
> **更新日期**:2026-10-12
|
||||||
> **状态**:E10 已在抓。E8 查询已接上,暂停按撤销停表。业务规则见 [demand.md](demand.md)。
|
> **状态**:只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同:内置 Agent `equipment_acceptance`。当前处理人取当前节点上的 `wfc_operate.userid`,不查询、不保存 `isremark`。发送时刻不在配置表,默认排程是每天 06:00 扫描、每周五 18:00 发送,可在排程页改 Cron。
|
||||||
|
> **业务规则**:[demand.md](demand.md)。本文只说明数据从哪读、人员怎么对上、哪些事实还缺。
|
||||||
|
|
||||||
E10 用 `OA_E10_SQLSERVER_*`,E8 用 `OA_SQLSERVER_*`。一边失败不改走另一边。人员 ID 不混用。流程实例 ID 两边都会撞号,本地用来源分开。合同付款只取 E8 归档日,那条 SQL 不复用。
|
## 1. 结论
|
||||||
|
|
||||||
两边都只抓未归档。E10 不取 `flowstatus = 3`,E8 不取 `currentnodetype = 3`。这两列为空仍抓。退回、作废、强制结束、撤销仍抓。
|
验收单主数据读 OA E10 的 `ecology10.dbo.ft_gdzcysdv2`。人员 ID 到 `eteams.dbo.employee` 取出工号,再用工号对上 HXOPS 用户。流程是否归档、作废、撤销,读 `wfc_requestbase.flowstatus`。当前节点读 `wfc_currentnode.nodeid`,再关联 `wfp_node.nodename`。`lastnodeid` 是最后操作节点,不拿来当当前节点。当前处理人读 `wfc_operate.userid`,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一节点同一人只留一行。每日扫描按这些处理人展开四档收件人。
|
||||||
|
|
||||||
两边表单上的是否字段都是 **0 = 是,1 = 否**。落库翻成 0 = 否、1 = 是。
|
## 2. 连接
|
||||||
|
|
||||||
## 1. 同一件事两边各看哪一列
|
查询走 E10 SQL Server,不走 E8 `ecology`。账号只从 `.env.shared` 读取下面三个变量,不把主机、账号、密码写进代码或文档:
|
||||||
|
|
||||||
| 事实 | E10 | E8 |
|
| 变量 | 用途 |
|
||||||
| --- | --- | --- |
|
| ----------------------------- | ------------------- |
|
||||||
| 验收单单号 | `ft_gdzcysdv2.ysddh` | `formtable_main_324.ysddh` |
|
| `OA_E10_SQLSERVER_HOST` | E10 SQL Server 主机 |
|
||||||
| 采购单号 | `cgdh` | `cgdh` |
|
| `OA_E10_SQLSERVER_USERNAME` | 只读账号 |
|
||||||
| 合同编号 | `htbh` | `htbh` |
|
| `OA_E10_SQLSERVER_PASSWORD` | 只读密码 |
|
||||||
| 流程编号 | `wfc_requestbase.requestmark` | `formtable_main_324.lcbh` |
|
|
||||||
| 标题 | `wfc_requestbase.requestname`。流程默认标题 | `workflow_requestbase.requestname` |
|
|
||||||
| 创建时间 | `wfc_requestbase.createdatetime`。流程创建时间,不是 `create_time` | `workflow_requestbase.createdate` 加 `createtime` |
|
|
||||||
| 计时起点 | `sbsyrjssj`。空 = 未开始 | `syddjssj`。空 = 未开始 |
|
|
||||||
| 使用部门担当 | `sybmdd` = `eteams.employee.ID` | `sybmdd` = `HrmResource.id` |
|
|
||||||
| 申请人(采购担当) | `sqr` = `employee.ID` | `workflow_requestbase.creater` = `HrmResource.id` |
|
|
||||||
| 直接主管 | 该担当的 `employee.SUPERIOR` | 该担当部门的 `Matrixtable_3.zz` |
|
|
||||||
| 经副理 | 该担当部门的 E10 矩阵 | 该担当部门的 `Matrixtable_3.jfl`。值就是企微 userid |
|
|
||||||
| 退回 | `sfzfth`:0 退回,1 和空未退回 | `sfzfth`:同上 |
|
|
||||||
| 可以验收 | `sfkyzcys`:0 可以,1 不可以,空未标明 | `sfkys`:同上 |
|
|
||||||
| 无法验收说明 | `ycsm`,只留痕 | `ycsm`,只留痕 |
|
|
||||||
| 当前节点 | `wfc_currentnode.nodeid` → `wfp_node.nodename` | `currentnodeid` → `workflow_nodebase.nodename` |
|
|
||||||
| 当前处理人 | `wfc_operate.userid`。不读 `isremark`。只展示 | `workflow_currentoperator.userid`,且 `isremark = 0`。只展示 |
|
|
||||||
| 审批中 / 归档 | `flowstatus` 1 / 3 | `currentnodetype` 0、1、2 / 3 |
|
|
||||||
| 撤销 | `flowstatus` 为 7、8、99、-99 | `currentstatus = 1` |
|
|
||||||
| 暂停 | `flowstatus = 7`,按撤销停表 | `currentstatus = 0`,同样写成 `7`,停表 |
|
|
||||||
| 作废 / 强制结束 | `flowstatus` 5 / 4 | 没有,不查 |
|
|
||||||
|
|
||||||
可以验收为空仍监控。只有明确为否才停表,显示为无法验收。计时起点为空仍是未开始。
|
验收单在 `ecology10`,人员表在同一实例的 `eteams`。流程字典写明:`wfc_requestbase`、`wfc_currentnode`、`wfc_operate` 所属库 `weaver_wfc`,`wfp_node` 所属库 `weaver_wfp`。现场曾在 `ecology10` 的 `INFORMATION_SCHEMA` 查出 `wfc_requestbase` 的列,查询时先按字典库名,账号看不到 `weaver_wfc` / `weaver_wfp` 时再改用 `ecology10` 里的同名表。本功能要求上述三个变量已配置,不回退到 E8 的 `OA_SQLSERVER_*`。
|
||||||
|
|
||||||
当前处理人不是收件人。第 1 档主送是使用部门担当,第 2 档主送是这个人的经副理。
|
## 3. 验收单主表
|
||||||
|
|
||||||
## 2. E10
|
表:`ecology10.dbo.ft_gdzcysdv2`。
|
||||||
|
|
||||||
库:验收单 `ecology10`,人员 `eteams`,流程 `weaver_wfc`,节点 `weaver_wfp`。看不到 `weaver_wfc` / `weaver_wfp` 时,流程表和节点表改用 `ecology10` 里的同名表。
|
| 字段 | 含义 | 在预警里的用法 |
|
||||||
|
| ------------- | -------------------- | -------------------------------------------------------------------------------------------- |
|
||||||
|
| `ysddh` | 验收单单号 | 台账、详情、企业微信上的验收单单号。 |
|
||||||
|
| `cgdh` | 采购单号 | 台账上的采购单号。 |
|
||||||
|
| `htbh` | 合同编号 | 只保存这一列。表上没有第二合同编号。 |
|
||||||
|
| `sbsyrjssj` | 设备使用人员计时时间 | 计时起点。第一次进入「使用部门担当」时写入,之后不改。为空表示还没开始计时。 |
|
||||||
|
| `sybmdd` | 使用部门担当 | 人员 ID,关联 `eteams.dbo.employee.ID`。 |
|
||||||
|
| `sbglry` | 设备管理人员 | 人员 ID,关联方式同 `sybmdd`。 |
|
||||||
|
| `sqr` | 申请人 | 预警规则里的采购担当。已确认是人员 ID,关联 `eteams.dbo.employee.ID`。 |
|
||||||
|
| `syry` | 使用人员 | 样例中同样是长整型 ID,按 `employee.ID` 关联。 |
|
||||||
|
| `gzglry` | 固资管理人员 | 人员字段。样例多为空;非空时按同一 ID 关联。 |
|
||||||
|
| `dx` | 使用人员1 | 同上。 |
|
||||||
|
| `agent` | 资管经办人 | 同上。 |
|
||||||
|
| `sfzfth` | 是否作废退回 | OA 上 **0 是退回,1 和空都是流程正常。** 落库 `is_returned` 翻转成 0 否、1 是,空收成 0。作废不看这一列,作废看 `flowstatus = 5`。 |
|
||||||
|
| `sfkyzcys` | 是否可以正常验收 | OA 上 **0 表示可以,1 表示不可以。** 落库 `can_accept` 翻转成 0 否、1 是。空值保持空,不当成可以验收。 |
|
||||||
|
| `ycsm` | 无法验收说明 | 说明正文。落库 `cannot_accept_note`。只留痕,不单独触发停表。停表仍看 `sfkyzcys = 1`。 |
|
||||||
|
|
||||||
关联,只取 `delete_type = 0`:
|
`sfkyzcys` 只表达能不能正常验收。说明正文是 `ycsm`。
|
||||||
|
|
||||||
1. `ft_gdzcysdv2.FORM_DATA_ID` = `wfc_form_data.dataid`
|
已确认按 ID 关联人员的是 `sybmdd`、`sbglry`、`sqr`。`syry`、`gzglry`、`dx`、`agent` 在样例结果里是同类长整型,设计上人员列统一走 `employee.ID`。若核对后某列不是人员 ID,只改该列,不改工号匹配方式。
|
||||||
2. `wfc_form_data.requestid` = `wfc_requestbase.requestid`
|
|
||||||
3. `wfc_requestbase.requestid` = `wfc_currentnode.requestid`
|
|
||||||
4. `wfc_currentnode.nodeid` = `wfp_node.id`,名称 `nodename`
|
|
||||||
5. `wfc_operate.requestid`、`nodeid` 对上当前节点,人是 `userid`
|
|
||||||
|
|
||||||
`lastnodeid` 是刚办过的节点,不是当前节点。分流时当前节点可以多行,都保留。计时按整单,不按节点重置。
|
## 4. 人员怎么对上系统用户
|
||||||
|
|
||||||
### 2.1 验收单 `ft_gdzcysdv2`
|
`eteams.dbo.employee` 使用这些列:
|
||||||
|
|
||||||
| 字段 | 含义 |
|
| 字段 | 含义 |
|
||||||
| --- | --- |
|
| ------------ | ----------------------------------------------------- |
|
||||||
| `ysddh` | 验收单单号 |
|
| `ID` | 与验收单人员字段、操作人 `userid` 关联 |
|
||||||
| `cgdh` | 采购单号 |
|
| `USERNAME` | 显示姓名。只用于展示,不作为匹配键。 |
|
||||||
| `htbh` | 合同编号。没有第二合同编号 |
|
| `JOB_NUM` | 工号。对应 HXOPS 用户表的工号,工号在系统用户中唯一。 |
|
||||||
| `sbsyrjssj` | 计时起点。第一次进入使用部门担当时写入,之后不改 |
|
| `DEPARTMENT` | 部门 ID。只用来查经副理 |
|
||||||
| `sybmdd` | 使用部门担当,人员 ID |
|
| `SUPERIOR` | 直接主管的人员 ID。再关联本表 `ID` |
|
||||||
| `sbglry` | 设备管理人员,人员 ID |
|
|
||||||
| `sqr` | 申请人,人员 ID |
|
|
||||||
| `sfzfth` | 是否退回。0 是,1 和空否。作废不看这列 |
|
|
||||||
| `sfkyzcys` | 是否可以正常验收。0 是,1 否,空未标明 |
|
|
||||||
| `ycsm` | 无法验收说明 |
|
|
||||||
|
|
||||||
`syry`、`gzglry`、`dx`、`agent` 也是人员 ID,预警不用。流程编号和标题在流程表,不在这张验收单上。不读验收日期。
|
关联顺序:
|
||||||
|
|
||||||
### 2.2 流程 `wfc_requestbase.flowstatus`
|
1. 验收单上的人员 ID = `eteams.dbo.employee.ID`。
|
||||||
|
2. 取该行 `JOB_NUM`。
|
||||||
|
3. 用 `JOB_NUM` 匹配 HXOPS 用户工号(`users.employee_id`)。
|
||||||
|
4. 企业微信接收人用该用户已绑定的 `wecom_userid`。
|
||||||
|
|
||||||
`status` 是文本,不拿来停表。结束时间用 `finishdatetime`,不读 `finshdatetime`。流程编号是 `requestmark`。标题是 `requestname`(流程默认标题),不用 `requestnamehtml` 和 `requestnametitle`。创建时间是 `createdatetime`,不用 `create_time`。
|
对不上时该条保持失败,可追查,不改发给别人。失败包括:人员 ID 为空、`employee` 无此 ID、`JOB_NUM` 为空、工号在 HXOPS 无用户、用户未绑定企业微信。
|
||||||
|
|
||||||
| 值 | 含义 | 预警 |
|
直接主管取当前处理人在 `employee.SUPERIOR` 上的人员 ID,不查矩阵。经副理才查 E10 矩阵,见第 4.1 节。不从 `ft_gdzcysdv2` 臆造,也不查 E8 的 `Matrixtable_3`。
|
||||||
|
|
||||||
|
采购经副理、COO、总经理只读界面配置,不从矩阵表取。
|
||||||
|
|
||||||
|
## 4.1 直接主管与经副理
|
||||||
|
|
||||||
|
按当前处理人查,不按申请人查,也不查 E8。
|
||||||
|
|
||||||
|
1. 当前处理人是 `wfc_operate.userid`,等于 `eteams.dbo.employee.ID`。
|
||||||
|
2. 直接主管是该员工的 `SUPERIOR`。这是人员 ID,再关联 `employee.ID` 取姓名和工号。空或关联不上就记失败,不改发给别人。
|
||||||
|
3. 经副理用该员工的 `DEPARTMENT`(部门 ID)查 E10 部门矩阵。人员在 `hrm_matrix_value_data.relate_id`,再同样关联 `employee`。不要把这个 ID 当成企微 userid,也不要对 `HrmResource.id`。
|
||||||
|
|
||||||
|
多名当前处理人时,各自取 `SUPERIOR` 和经副理,然后去重。
|
||||||
|
|
||||||
|
三个固定值已确认。`tenant_key` 为 `temkc46eme`。矩阵 `id` `1115770797884751874` 是苏州和信的「HXJM-审批矩阵」,取自 `eteams.dbo.hrm_matrix.id`。经副理取值配置 `id` `1115771897387991041` 取自 `eteams.dbo.hrm_matrix_value_config`:`config_name` 为「经副理」,且 `matrix_id` 为上面这个矩阵。该配置 `config_type` 是 `resource`,`single_type = 1`(单选)。查人仍用 `hrm_matrix_value_data.relate_id`,不要把配置表的 `id` 当成人员 ID。`delete_type = 0` 为正常。同一矩阵下还有总经理等其他取值配置,不拿来当经副理。
|
||||||
|
|
||||||
|
矩阵 id 和经副理配置 id 按下面两条查出,不在代码里另找别的矩阵:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 苏州和信「HXJM-审批矩阵」的 id。
|
||||||
|
SELECT id
|
||||||
|
FROM eteams.dbo.hrm_matrix
|
||||||
|
WHERE tenant_key = 'temkc46eme'
|
||||||
|
AND matrix_name = N'HXJM-审批矩阵'
|
||||||
|
AND delete_type = 0
|
||||||
|
AND enable_status = 1;
|
||||||
|
-- 结果:1115770797884751874
|
||||||
|
|
||||||
|
-- 该矩阵下 config_name 为「经副理」的取值配置 id。
|
||||||
|
SELECT id
|
||||||
|
FROM eteams.dbo.hrm_matrix_value_config
|
||||||
|
WHERE tenant_key = 'temkc46eme'
|
||||||
|
AND matrix_id = 1115770797884751874
|
||||||
|
AND config_name = N'经副理'
|
||||||
|
AND delete_type = 0;
|
||||||
|
-- 结果:1115771897387991041
|
||||||
|
```
|
||||||
|
|
||||||
|
已用 `employee.DEPARTMENT = 1115763045510725632` 核对:`hrm_matrix_value_data.matrix_data_id` 没有这个值。因此这张矩阵不能把 `matrix_data_id` 直接当成部门 ID。部门 ID 改到条件表 `hrm_matrix_condition_data.relate_id` 里按字符串匹配,先取出矩阵数据行,再取值:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 经副理。表都在 eteams.dbo,不能省库名。
|
||||||
|
-- 返回的 relate_id 是人员 ID,再关联 eteams.dbo.employee.ID,不要当成企微 userid。
|
||||||
|
-- :department_id 取当前处理人的 employee.DEPARTMENT,必须按字符串比较。
|
||||||
|
-- 已用部门 1115763045510725632 跑通,返回一名经副理。
|
||||||
|
SELECT v.relate_id
|
||||||
|
FROM eteams.dbo.hrm_matrix_value_data AS v
|
||||||
|
WHERE v.tenant_key = 'temkc46eme' -- 租户
|
||||||
|
AND v.matrix_id = 1115770797884751874 -- hrm_matrix:苏州和信「HXJM-审批矩阵」的 id
|
||||||
|
AND v.matrix_value_config_id = 1115771897387991041 -- hrm_matrix_value_config:该矩阵下 config_name 为「经副理」的 id,不是人员 ID
|
||||||
|
AND v.delete_type = 0 -- 0 正常,1/2/3 都是删除
|
||||||
|
AND v.matrix_data_id IN (
|
||||||
|
-- 部门 ID 不在 matrix_data_id 上。先从条件表找出矩阵数据行。
|
||||||
|
SELECT c.matrix_data_id
|
||||||
|
FROM eteams.dbo.hrm_matrix_condition_data AS c
|
||||||
|
WHERE c.tenant_key = 'temkc46eme'
|
||||||
|
AND c.matrix_id = 1115770797884751874
|
||||||
|
AND c.delete_type = 0
|
||||||
|
AND c.relate_id = :department_id -- 字符串,例如 '1115763045510725632'
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
条件配置 id 还没限定。若同一部门对出多行,再按 `matrix_condition_config_id` 收窄。
|
||||||
|
|
||||||
|
## 5. 计时与停表在现有字段上怎么落
|
||||||
|
|
||||||
|
计时起点用 `sbsyrjssj`。已确认它只在第一次进入「使用部门担当」时写入一次,之后不改写。从该时间起到当前按自然日累计,换节点不重置。字段为空的单据视为尚未开始计时,不产生预警。
|
||||||
|
|
||||||
|
退回只看 `sfzfth`。OA 取值是 0=是、1=否。落库列 `is_returned` 先翻转成标准布尔:0 否,1 是。已确认取值:
|
||||||
|
|
||||||
|
| OA `sfzfth` | 本地 `is_returned` | 含义 | 预警 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `0` | `1` | 是,退回 | 立即停表,取消尚未发出的预警。不考虑从 `0` 改回 `1` 或空。 |
|
||||||
|
| `1` | `0` | 否,流程正常 | 不因本字段停表 |
|
||||||
|
| 空 | `0` | 否,流程正常 | 与 OA `1` 相同,不当成退回 |
|
||||||
|
|
||||||
|
字段中文名是「是否作废退回」,已确认的取值只区分退回和正常。作废、撤销仍看下一节的 `flowstatus`,不用 `sfzfth` 代替。出现 `0`、`1`、空以外的值时,不判退回,也不当正常,先记下来待确认。
|
||||||
|
|
||||||
|
不考虑 `sfzfth` 从 `0` 改回 `1` 或空。不把这种改写当作恢复计时或新周期。
|
||||||
|
|
||||||
|
是否可以正常验收看 `sfkyzcys`。OA 取值与常见布尔相反:0=是、1=否。落库列 `can_accept` 翻转成 0 否、1 是。空值不翻转成否。
|
||||||
|
|
||||||
|
| OA `sfkyzcys` | 本地 `can_accept` | 含义 | 预警 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `0` | `1` | 是,可以正常验收 | 其他条件也满足时继续计时 |
|
||||||
|
| `1` | `0` | 否,不可以正常验收 | 立即停表,取消尚未发出的预警 |
|
||||||
|
| 空 | 空 | 未标明 | 不纳入监控,不按「可以验收」处理 |
|
||||||
|
|
||||||
|
退回或无法验收后再进入,`sbsyrjssj` 仍是第一次写入的时间,签核天数就按它计算,不从 0 重计。不读取、不保存 `wfc_operate.operateround`。
|
||||||
|
|
||||||
|
## 5.1 流程实例与节点定义
|
||||||
|
|
||||||
|
OA 数据字典:
|
||||||
|
|
||||||
|
| 表 | 中文名 | 字典所属库 | 用途 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `wfc_requestbase` | 流程实例基本信息表 | `weaver_wfc` | 一条流程一行。状态、编号、最后操作节点。 |
|
||||||
|
| `wfc_currentnode` | 流程当前节点表 | `weaver_wfc` | 流程当前停在哪个节点。没有处理人。 |
|
||||||
|
| `wfp_node` | 工作流节点基础信息表 | `weaver_wfp` | 节点定义。用 `id` 取出节点名称和节点类型。 |
|
||||||
|
|
||||||
|
`wfc_currentnode` 字段:
|
||||||
|
|
||||||
|
| 字段 | 字典含义 | 用法 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 0 | 草稿 | 不监控 |
|
| `requestid` | 流程实例 id。来源说明写着 `wfc_operate` | 等于 `wfc_requestbase.requestid` |
|
||||||
| 1 | 审批中 | 其他条件满足才计时 |
|
| `nodeid` | 数据所在节点 ID。来源说明写着 `wfc_operate` | 等于 `wfp_node.id`,这是当前节点 |
|
||||||
| 3 | 正常归档 | 不抓取 |
|
| `nodetype` | 节点类型 | 本表字典没有 0–9。类型以 `wfp_node.nodetype` 为准 |
|
||||||
| 4 | 强制结束 | 停表 |
|
| `delete_type` | 是否删除 | 只取 `0` |
|
||||||
| 5 | 已作废 | 停表 |
|
| `operate_log_id` | 批次号 | 不查询、不保存 |
|
||||||
| 6 | 待提交 | 不监控 |
|
| `creator` | 数据插入人 | 不是当前处理人 |
|
||||||
| 7 | 暂停 | 按撤销停表 |
|
|
||||||
| 8 | 撤销 | 停表 |
|
|
||||||
| 99、-99 | 撤销 | 停表 |
|
|
||||||
|
|
||||||
退回后 `flowstatus` 仍可能是 1。退回只看 `sfzfth = 0`。
|
|
||||||
|
|
||||||
### 2.3 人员
|
|
||||||
|
|
||||||
`eteams.employee`:`ID` 对人员字段和 `userid`,`USERNAME` 只展示,`JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。`DEPARTMENT` 查经副理,`SUPERIOR` 是直接主管的人员 ID。
|
|
||||||
|
|
||||||
经副理:用使用部门担当的 `DEPARTMENT` 对 `hrm_matrix_condition_data.relate_id`(字符串),取出 `matrix_data_id`,再在 `hrm_matrix_value_data` 取 `relate_id`。该值是人员 ID,再对 `employee.ID`,不是企微 userid。`matrix_data_id` 不是部门 ID。
|
|
||||||
|
|
||||||
固定条件:`tenant_key = temkc46eme`,矩阵 `1115770797884751874`(HXJM-审批矩阵),经副理配置 `1115771897387991041`,`delete_type = 0`。同一部门多行时再按 `matrix_condition_config_id` 收窄。
|
|
||||||
|
|
||||||
对不上人、没有主管或经副理:该席位失败,不改发给别人。
|
|
||||||
|
|
||||||
## 3. E8
|
|
||||||
|
|
||||||
库:`ecology`。人员主键是 `HrmResource.id`,不能对 `eteams.employee.ID`。
|
|
||||||
|
|
||||||
关联:
|
关联:
|
||||||
|
|
||||||
1. `formtable_main_324.requestId` = `workflow_requestbase.requestid`
|
1. `ft_gdzcysdv2.FORM_DATA_ID` = `wfc_form_data.dataid`,且 `wfc_form_data.delete_type = 0`。验收单上没有流程编号列,不读 `requestmark`。
|
||||||
2. `workflow_requestbase.currentnodeid` = `workflow_nodebase.id`,名称 `nodename`
|
2. `wfc_form_data.requestid` = `wfc_requestbase.requestid`。本地快照按这个 `requestid` 唯一。归档看 `flowstatus = 3`,不看验收日期。
|
||||||
3. `workflow_currentoperator.requestid` = `workflow_requestbase.requestid`,且 `nodeid` = `currentnodeid`,且 `isremark = 0`
|
3. `wfc_requestbase.requestid` = `wfc_currentnode.requestid`,且 `wfc_currentnode.delete_type = 0`。
|
||||||
|
4. `wfc_currentnode.nodeid` = `wfp_node.id`。展示名称用 `wfp_node.nodename`。
|
||||||
|
5. 分流时一条流程可以有多行当前节点。这些行都保留,节点名称分别列出。计时仍按整单累计,不按节点重置。
|
||||||
|
|
||||||
`lastnodeid` 不是当前节点。`isremark`:0 未操作,2 已操作,4 归档,8 / 9 抄送。只留 0。关联不上不跳过整单。不另存 `isremark`。计时不按节点名过滤。
|
`wfc_requestbase.lastnodeid` 仍是「最后操作节点 ID」,只表示刚办过的节点。当前节点以 `wfc_currentnode.nodeid` 为准。
|
||||||
|
|
||||||
### 3.1 验收单 `formtable_main_324`
|
`wfp_node.nodetype`:0 发起,1 审批,2 确认,3 结束,4 子流程节点,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅。`nodeattr`:0 一般节点,1 分流点,2 分流中间点,3 合流点。`wfc_requestbase.lastnodetype` 只标了「最后操作流程节点类型」,字典没有给出 0–9。不把 `nodetype` 的枚举直接套到 `lastnodetype`。
|
||||||
|
|
||||||
|
流程状态以 `flowstatus` 为准。同表的 `status` 是最长 1000 的文本,没有枚举,不拿来判断停表。
|
||||||
|
|
||||||
|
| `flowstatus` | 字典含义 | 预警 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `0` | 草稿 | 不监控 |
|
||||||
|
| `1` | 审批中 | 其他条件也满足时可以计时 |
|
||||||
|
| `3` | 正常归档 | 停表,不恢复旧周期 |
|
||||||
|
| `4` | 强制结束 | 流程已结束。业务未单列这一项,先按停表、不恢复处理 |
|
||||||
|
| `5` | 已作废 | 停表,不恢复旧周期 |
|
||||||
|
| `6` | 待提交 | 不按审批中处理 |
|
||||||
|
| `7` | 暂停 | 已确认与撤销相同:停表,不再提醒,不恢复旧周期 |
|
||||||
|
| `8` | 撤销 | 停表,不再提醒,不恢复旧周期 |
|
||||||
|
| `99`、`-99` | `99` 为业务确认值;`-99` 是字典截断处 | 与撤销相同:停表,不再提醒 |
|
||||||
|
|
||||||
|
字典没有值为「退回」的流程状态。退回后 `flowstatus` 仍可能是 `1`(审批中)。退回以验收单 `sfzfth = 0` 为准,不从 `flowstatus` 推断。
|
||||||
|
|
||||||
|
`finishdatetime` 是流程归档时间。字典另有拼写 `finshdatetime`(少一个 i),含义写成「流程归档时间、作废时间」。现场列清单里是 `finishdatetime`。查询只用 `finishdatetime`,不查 `finshdatetime`。
|
||||||
|
|
||||||
|
`lastoperator` 是最后操作人,`wfc_currentnode.creator` 是插行的人,都不是当前待办人。`delete_type` 是记录是否删除,不是作废。作废看 `flowstatus = 5`。
|
||||||
|
|
||||||
|
## 5.2 流程操作人
|
||||||
|
|
||||||
|
表:`weaver_wfc.dbo.wfc_operate`,中文名「流程操作人表」。当前处理人在这张表。
|
||||||
|
|
||||||
|
| 字段 | 字典含义 | 用法 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `requestid` | 流程实例 id | 等于 `wfc_currentnode.requestid` |
|
||||||
|
| `nodeid` | 数据所在节点 ID | 等于 `wfc_currentnode.nodeid`。只取当前节点上的操作人 |
|
||||||
|
| `userid` | 操作人 id | 当前处理人。关联 `eteams.dbo.employee.ID` |
|
||||||
|
| `processuser` | 实际操作人 ID | 已经代办或实际点过的人。待办人取 `userid`,不取这一列 |
|
||||||
|
| `usertype` | 人员类型 | 字典没有取值。先按 `userid` 关联员工,关联不上记失败 |
|
||||||
|
| `isremark` | 操作状态 | 不查询、不保存。当前处理人就是当前节点上的 `userid` |
|
||||||
|
| `preisremark` | 插入时的操作状态,插入后不变更 | 不查询、不保存 |
|
||||||
|
| `operatedatetime` | 操作日期时间 | 已办才会有操作时间。不能单靠它为空就把抄送、转发都算成待办 |
|
||||||
|
| `showorder` | 未操作者的显示顺序 | 说明表里包含未操作的人 |
|
||||||
|
| `operateround` | 节点第几次到达 | 不查询、不保存 |
|
||||||
|
| `isbereject` | 是否退回操作 | 字典没有 0/1。退回仍以 `sfzfth = 0` 为准 |
|
||||||
|
| `isprocessing` | 执行中时,流程不出现在待办、已办 | 字典没有哪个值表示执行中。该状态的行不发预警 |
|
||||||
|
| `delete_type` | 是否删除 | 只取 `0` |
|
||||||
|
| `optgroupid` | 操作者批次 | 不查询、不保存 |
|
||||||
|
| `batch_number` | 批次号 | 不查询、不保存。与 `wfc_currentnode.operate_log_id` 一样不参与预警 |
|
||||||
|
|
||||||
|
当前节点上的 `userid` 都是当前处理人。同一人只留一行。直接主管、经副理按各人展开后去重。会签关系 `signorder` 的取值未给,不改变「这些人都要通知」。
|
||||||
|
|
||||||
|
## 6. 查询形态
|
||||||
|
|
||||||
|
同一实例上跨库只读,不把人员 ID 当姓名用。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
f.ysddh,
|
||||||
|
f.cgdh,
|
||||||
|
f.htbh,
|
||||||
|
f.sbsyrjssj,
|
||||||
|
f.sfzfth,
|
||||||
|
f.sfkyzcys,
|
||||||
|
f.ycsm,
|
||||||
|
f.sybmdd,
|
||||||
|
owner.USERNAME AS owner_name,
|
||||||
|
owner.JOB_NUM AS owner_job_num,
|
||||||
|
f.sbglry,
|
||||||
|
equip.USERNAME AS equip_name,
|
||||||
|
equip.JOB_NUM AS equip_job_num,
|
||||||
|
f.sqr,
|
||||||
|
applicant.USERNAME AS applicant_name,
|
||||||
|
applicant.JOB_NUM AS applicant_job_num,
|
||||||
|
r.requestid,
|
||||||
|
r.flowstatus,
|
||||||
|
r.finishdatetime,
|
||||||
|
c.nodeid,
|
||||||
|
n.nodename,
|
||||||
|
n.nodetype,
|
||||||
|
op.userid,
|
||||||
|
handler.USERNAME AS handler_name,
|
||||||
|
handler.JOB_NUM AS handler_job_num
|
||||||
|
FROM ecology10.dbo.ft_gdzcysdv2 AS f
|
||||||
|
LEFT JOIN eteams.dbo.employee AS owner ON owner.ID = f.sybmdd
|
||||||
|
LEFT JOIN eteams.dbo.employee AS equip ON equip.ID = f.sbglry
|
||||||
|
LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr
|
||||||
|
LEFT JOIN weaver_wfc.dbo.wfc_form_data AS d
|
||||||
|
ON d.dataid = f.FORM_DATA_ID
|
||||||
|
AND d.delete_type = 0
|
||||||
|
LEFT JOIN weaver_wfc.dbo.wfc_requestbase AS r
|
||||||
|
ON r.requestid = d.requestid
|
||||||
|
AND r.delete_type = 0
|
||||||
|
LEFT JOIN weaver_wfc.dbo.wfc_currentnode AS c
|
||||||
|
ON c.requestid = r.requestid
|
||||||
|
AND c.delete_type = 0
|
||||||
|
LEFT JOIN weaver_wfp.dbo.wfp_node AS n
|
||||||
|
ON n.id = c.nodeid
|
||||||
|
AND n.delete_type = 0
|
||||||
|
LEFT JOIN weaver_wfc.dbo.wfc_operate AS op
|
||||||
|
ON op.requestid = c.requestid
|
||||||
|
AND op.nodeid = c.nodeid
|
||||||
|
AND op.delete_type = 0
|
||||||
|
LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid;
|
||||||
|
```
|
||||||
|
|
||||||
|
验收单上没有流程编号、第二合同编号和验收日期,这三列不查询、也不写入本地表。归档只看 `flowstatus = 3`。不查询 `isremark`。当前节点上的 `userid` 就是当前处理人,同一人只留一行。一条流程有多个当前节点、每个节点有多名操作人时,这个查询会返回多行。库名按第 2 节:看不到 `weaver_wfc` / `weaver_wfp` 时改为 `ecology10`。`syry`、`gzglry`、`dx`、`agent` 需要展示或发通知时,按同样方式再关联 `employee`。不在应用里先全量拉人再在内存里对 ID。
|
||||||
|
|
||||||
|
## 7. 和需求规则的对照
|
||||||
|
|
||||||
|
| 需求事实 | 现在的来源 | 缺口 |
|
||||||
|
| ---------------------- | -------------------------- | --------------------------- |
|
||||||
|
| 验收单单号 | `ysddh` | 无 |
|
||||||
|
| 采购单号 | `cgdh` | 无 |
|
||||||
|
| 一张流程的身份 | `wfc_requestbase.requestid` | 不保存流程编号。验收日期不参与归档。 |
|
||||||
|
| 计时起点 | `sbsyrjssj`,只写一次、不覆盖 | 再进入也用这个时间,不从 0 重计。 |
|
||||||
|
| 使用部门担当 | `sybmdd` → `employee` | 无 |
|
||||||
|
| 申请人(采购担当) | `sqr` → `employee` | 已确认是人员 ID |
|
||||||
|
| 作废 | `flowstatus = 5` | 不看 `sfzfth` |
|
||||||
|
| 撤销 | `flowstatus` 为 `7`、`8`、`99`、`-99` | 都停表且不再提醒。本地状态 `stopped_revoked` |
|
||||||
|
| 退回 | OA `sfzfth = 0`,本地 `is_returned = 1` | `1` 和空都是未退回,本地写成 `0`。 |
|
||||||
|
| 归档、未归档 | `flowstatus`:`3` 正常归档,`1` 审批中 | `4` 强制结束先按结束。 |
|
||||||
|
| 当前节点名称 | `wfc_currentnode.nodeid` → `wfp_node.nodename` | 分流时可能多行,都保留。`lastnodeid` 不是当前节点 |
|
||||||
|
| 当前处理人 | `wfc_operate.userid`,对齐当前 `requestid` + `nodeid` | 不使用 `isremark`。同一人只留一行 |
|
||||||
|
| 可以正常验收 | OA `sfkyzcys`:`0` 可以,`1` 不可以。本地 `can_accept` 为 `1` 可以、`0` 不可以 | 空值不监控,也不写成 0。说明正文是 `ycsm`。 |
|
||||||
|
| 直接主管 | 当前处理人的 `employee.SUPERIOR` | 人员 ID,再关联 `employee` |
|
||||||
|
| 经副理 | `eteams.dbo.hrm_matrix_value_data.relate_id`。部门 ID 在 `eteams.dbo.hrm_matrix_condition_data.relate_id` | 查询已用部门 `1115763045510725632` 跑通。`matrix_data_id` 不是部门 ID |
|
||||||
|
| 再次进入 | 仍用第一次的 `sbsyrjssj` | 不从 0 重计。不看 `sfzfth` 是否从 `0` 改回正常。不用 `operateround`。 |
|
||||||
|
| 固定岗位三人 | 界面配置 | 不读 OA |
|
||||||
|
|
||||||
|
## 8. 已实现的同步
|
||||||
|
|
||||||
|
平台管理员调用 `POST /api/equipment-acceptance/sync`。连接只用 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`,不回退 E8 的 `OA_SQLSERVER_*`。库名先按字典;实例里没有 `weaver_wfc` 或 `weaver_wfp` 时,流程表和节点表改用 `ecology10`。人员库只认 `eteams`。
|
||||||
|
|
||||||
|
本地表保存 OA 同步快照,另有一张发送记录表。一张验收单在 `equipment_acceptance_orders` 里一行,当前节点和操作人在另外两张表。每次同步按 `request_id` 更新主表,并整批替换该单的节点和操作人。主表删除时,节点和操作人随外键级联删除,发送记录只把 `order_id` 置空并保留单号快照。不保存流程编号、第二合同编号和验收日期。归档看 `flow_status_raw = 3`,不看验收日期。每日扫描写入发送记录;停表时取消还没发出的行。
|
||||||
|
|
||||||
|
### 8.1 `equipment_acceptance_orders`
|
||||||
|
|
||||||
|
一张验收单的最近一次同步结果。`request_id` 唯一。
|
||||||
|
|
||||||
| 字段 | 含义 |
|
| 字段 | 含义 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `cgdh` | 采购单号 |
|
| `id` | 本地主键 |
|
||||||
| `requestId` | 流程实例 ID |
|
| `request_id` | OA 流程实例 ID,来自 `wfc_requestbase.requestid`。一张流程一行 |
|
||||||
| `ysddh` | 验收单单号 |
|
| `acceptance_no` | 验收单单号,来自 `ysddh` |
|
||||||
| `htbh` | 合同编号 |
|
| `purchase_order_no` | 采购单号,来自 `cgdh` |
|
||||||
| `lcbh` | 流程编号 |
|
| `contract_no` | 合同编号,来自 `htbh` |
|
||||||
| `syddjssj` | 使用担当接收时间。计时起点,之后不改 |
|
| `timer_started_at` | 计时起点,来自 `sbsyrjssj`。空表示还没开始计时 |
|
||||||
| `sybmdd` | 使用部门担当,人员 ID |
|
| `dwell_days` | 签核天数。归档、强制结束、作废且有 `finished_at` 时停在结束日,否则算到同步日 |
|
||||||
| `sfzfth` | 是否退回。0 是,1 和空否 |
|
| `can_accept` | 是否可以正常验收。**0 否,1 是,空表示未标明。** 由 OA `sfkyzcys` 翻转而来,OA 是 0 是、1 否。空不写成 0 |
|
||||||
| `sfkys` | 是否可以正常验收。0 是,1 否,空未标明 |
|
| `cannot_accept_note` | 无法验收说明正文,来自 `ycsm`。空表示没有说明。不参与停表判断 |
|
||||||
| `ycsm` | 无法验收说明。只留痕 |
|
| `is_returned` | 是否退回。**0 否,1 是。** 由 OA `sfzfth` 翻转而来,OA 是 0 是、1 否。OA 的 1 和空都收成 0 |
|
||||||
|
| `flow_status_raw` | `wfc_requestbase.flowstatus` 原值。1 审批中,3 正常归档,4 强制结束,5 已作废 |
|
||||||
|
| `finished_at` | 流程结束时间,来自 `finishdatetime`。不拿它判断是否归档 |
|
||||||
|
| `request_match_count` | 这一行对应的流程实例数,现在固定为 1 |
|
||||||
|
| `owner_oa_id` / `owner_name` / `owner_job_num` | 使用部门担当。人员 ID 来自 `sybmdd`,姓名和工号来自 `employee` |
|
||||||
|
| `equip_oa_id` / `equip_name` / `equip_job_num` | 设备管理人员,来自 `sbglry` |
|
||||||
|
| `applicant_oa_id` / `applicant_name` / `applicant_job_num` | 申请人(采购担当),来自 `sqr` |
|
||||||
|
| `monitor_status` | 监控状态,取值见下表 |
|
||||||
|
| `present_in_source` | 这次同步是否还能在 OA 里看到这张单。看不到时保留上次内容,只把本列改成否 |
|
||||||
|
| `synced_at` | 最近一次同步时间 |
|
||||||
|
| `created_at` / `updated_at` | 本地创建、更新时间 |
|
||||||
|
|
||||||
### 3.2 流程 `workflow_requestbase`
|
`monitor_status`:
|
||||||
|
|
||||||
| 字段 | 值 | 含义 |
|
| 值 | 含义 |
|
||||||
| --- | --- | --- |
|
| --- | --- |
|
||||||
| `currentnodetype` | 0、1、2 | 审批中。创建 / 批准 / 提交都算进行中 |
|
| `watching` | 进行中。审批中、可以验收、未退回、已有计时起点 |
|
||||||
| `currentnodetype` | 3 | 正常归档。不抓取 |
|
| `not_started` | 未开始。没有计时起点,且没有更优先的停表原因 |
|
||||||
| `currentstatus` | 空 | 流程正常。再看 `currentnodetype` |
|
| `stopped_returned` | 已退回。`is_returned = 1` |
|
||||||
| `currentstatus` | 1 | 撤销,停表 |
|
| `stopped_cannot_accept` | 无法验收。`can_accept = 0` |
|
||||||
| `currentstatus` | 0 | 暂停。与 E10 一样停表,写成 `7` |
|
| `stopped_archived` | 已归档。`flow_status_raw = 3`,之后不再追踪预警 |
|
||||||
| `currentnodeid` | | 当前节点 ID |
|
| `stopped_force_finished` | 已强制结束。`flow_status_raw = 4` |
|
||||||
| `lastnodeid` | | 最后操作节点,不是当前节点 |
|
| `stopped_voided` | 已作废。`flow_status_raw = 5` |
|
||||||
| `creater` | | 申请人,人员 ID。没有 `creator` 这一列 |
|
| `stopped_revoked` | 已撤销,不再提醒。`flow_status_raw` 为 `7`、`8`、`99` 或 `-99` |
|
||||||
| `requestname` | | 标题 |
|
| `excluded` | 不在监控范围。不含上面的撤销取值 |
|
||||||
| `createdate` | | 创建日期。与 `createtime` 拼成创建时间 |
|
|
||||||
| `createtime` | | 创建时分秒 |
|
|
||||||
|
|
||||||
没有作废、强制结束。不把任何值写成这两类。`currentstatus` 出现空、0、1 以外的值时,不当成正常。`status` 是文本,不拿来停表。`deleted` 是是否删除,不当作废。
|
退回、无法验收先于作废、归档、强制结束和撤销。撤销即使没有计时起点也记为 `stopped_revoked`,不记成未开始。归档、强制结束、作废、撤销且有 `finished_at` 时,签核天数截止到该日。`optgroupid`、`batch_number`、`operate_log_id` 不查询、不保存。
|
||||||
|
|
||||||
### 3.3 人员
|
### 8.2 `equipment_acceptance_nodes`
|
||||||
|
|
||||||
使用部门担当、申请人:`HrmResource.id` 取姓名,`workcode` 对 `users.employee_id`,发送用 `users.wecom_userid`。
|
这张单当前停在哪些节点。同一张单可以有多行,分流时每个当前节点一行。同一张单里 `order_id` + `node_id` 不重复。
|
||||||
|
|
||||||
直接主管和经副理:用该担当的 `departmentid` 对 `Matrixtable_3.bm`,必须只命中一行。`zz` 是直接主管,`jfl` 是经副理。这两个值就是 `HrmResource.id`,也是企微 userid,发送时直接用。无部门、不是一行或对不上,该席位失败,不改发给别人。
|
| 字段 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `id` | 本地主键 |
|
||||||
|
| `order_id` | 对应 `equipment_acceptance_orders.id` |
|
||||||
|
| `node_id` | OA 当前节点 ID,来自 `wfc_currentnode.nodeid` |
|
||||||
|
| `node_name` | 节点名称,来自 `wfp_node.nodename` |
|
||||||
|
| `node_type` | 节点类型原值,来自 `wfp_node.nodetype`。0 发起,1 审批,2 确认,3 结束,4 子流程,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅 |
|
||||||
|
|
||||||
## 4. 状态对照里已经落地的决定
|
`lastnodeid` 不写入本表。
|
||||||
|
|
||||||
E8 `currentstatus = 0` 按 E10 的暂停处理:停表,本地流程状态写成 `7`。空、`0`、`1` 以外不写成审批中。
|
### 8.3 `equipment_acceptance_operators`
|
||||||
|
|
||||||
|
当前节点上的操作人。同一节点同一人只留一行。不保存 `isremark`。
|
||||||
|
|
||||||
|
| 字段 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `id` | 本地主键 |
|
||||||
|
| `order_id` | 对应 `equipment_acceptance_orders.id` |
|
||||||
|
| `node_id` | 这个人所属的当前节点 |
|
||||||
|
| `user_id` | OA 操作人 ID,来自 `wfc_operate.userid` |
|
||||||
|
| `handler_name` | 操作人姓名 |
|
||||||
|
| `handler_job_num` | 操作人工号 |
|
||||||
|
|
||||||
|
扫描按这张表的当前处理人展开直接主管和经副理。直接主管、经副理不在本表,查询时再读 E10。
|
||||||
|
|
||||||
|
`GET /api/equipment-acceptance/orders` 分页列表。`focus` 取 `watching`、`overdue`、`stopped`、`not_started`;`overdue` 是计时中且签核天数超过配置里的第 1 档,默认 30。响应里的 `summary` 始终统计全部单据。`GET /api/equipment-acceptance/orders/<id>` 含当前节点操作人。人员主键以字符串返回。平台管理员,或被授予启用中 Agent 的用户,可以打开列表和详情。同步仍只给平台管理员。停留列表四张汇总卡是进行中、已逾期、不再提醒、未开始。计时中且超过 30 天显示已逾期,未超过显示未超时。停留列表不显示第几档。
|
||||||
|
|
||||||
|
### 8.4 `equipment_acceptance_send_records`
|
||||||
|
|
||||||
|
一张验收单某一档的发送记录。同一张单同一档只有一行。待发送和解析失败的行每次扫描按当前处理人和当前岗位重算;已发送、已取消的姓名不再改写。Chat 页签「发送记录」读 `GET /api/equipment-acceptance/sends`。
|
||||||
|
|
||||||
|
| 字段 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `id` | 本地主键 |
|
||||||
|
| `order_id` | 对应 `equipment_acceptance_orders.id`。验收单被删时置空 |
|
||||||
|
| `acceptance_no` / `purchase_order_no` | 写入时的验收单单号、采购单号 |
|
||||||
|
| `tier` | 第几档,1 到 4 |
|
||||||
|
| `threshold_days` | 这一档当时的天数,例如 30 |
|
||||||
|
| `to_text` / `cc_text` | 解析成功的主送、抄送姓名,用顿号拼接 |
|
||||||
|
| `recipients_json` | 每个席位的角色、姓名、系统用户、企微 userid、OA 人员 ID 和失败原因 |
|
||||||
|
| `status` | `pending` 待发送,`sent` 已发送,`failed` 解析或发送失败,`cancelled` 已取消 |
|
||||||
|
| `sent_at` | 发出时间。只有 `sent` 才有 |
|
||||||
|
| `error_message` | 解析失败或企业微信发送失败的原因。能发出的人仍会发送 |
|
||||||
|
| `created_at` | 记录生成时间 |
|
||||||
|
|
||||||
|
页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。
|
||||||
|
|
||||||
|
`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`round_4_enabled` 默认关闭,关闭时扫描不生成第 4 轮,发送也会跳过已经待发送的第 4 轮。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。
|
||||||
|
|
||||||
|
## 9. 扫描与发送
|
||||||
|
|
||||||
|
每天 06:00(Asia/Shanghai)排程 `equipment-acceptance-alert-scan` 先同步 E10,再按签核天数生成待发送。超过配置天数才进档,刚好等于还不发。默认 30/37/44/51。同一张单每一档只生成一次;已发送和已取消不重算、不重发。
|
||||||
|
|
||||||
|
收件人:
|
||||||
|
|
||||||
|
- 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。
|
||||||
|
- 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。
|
||||||
|
- 超过第 3 档:主送 COO,抄送采购经副理。
|
||||||
|
- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。配置里的第 4 轮开关默认关闭,关闭时这一档不产生、也不发送。
|
||||||
|
|
||||||
|
人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。
|
||||||
|
|
||||||
|
每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号先收一条文本卡片,标题「设备验收停留提醒」,正文先写共多少张验收单已逾期,再写各轮次数量,事件 `equipment_acceptance_warning`。紧跟着一条文件消息《设备验收停留提醒.xlsx》,列是验收单号、采购单号、申请人、轮次、停留天数、当前节点、当前处理人、通知身份。卡片不写主送、抄送,也不逐条列出验收单。卡片和文件都成功才改为已发送。任一失败则整档改为失败,并写上卡片或附件的原因;下次扫描会按当前处理人重算并回到待发送。每位收件人的 Excel 写入 `equipment_acceptance_send_files`,并记下对应的发送记录。发送失败也保留。发送记录表用 Excel 附件列下载,同一行可有多份。已发出的企业微信不撤回。
|
||||||
|
|
||||||
|
停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。
|
||||||
|
|
||||||
|
管理员在发送记录页可以立即「扫描预警」和「发送预警」,对应 `POST /api/equipment-acceptance/alerts/scan` 和 `POST /api/equipment-acceptance/alerts/send`。两个排程启动时写入,已有同编号时不覆盖。Cron 在排程页改,不在预警配置页。
|
||||||
|
|
||||||
|
不查询、不保存 `isremark`。不接 Dify。不给「使用部门担当」之前的节点单独计时。读 OA `sfkyzcys`、`sfzfth` 时仍是 0 表示是、1 表示否,禁止把 OA 原值直接写进 `can_accept`、`is_returned`。`ycsm` 只保存说明,不拿它判断能不能验收。
|
||||||
|
|
||||||
|
数据库升到迁移 `ea8c0a1b2c3d` 后,快照、配置和带收件人明细的发送记录一次建好,扫描才能落库。
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
# 制程品质异常预警需求说明
|
|
||||||
|
|
||||||
> **版本**:V1.0
|
|
||||||
> **更新日期**:2026-10-23
|
|
||||||
> **状态**:规则已整理,尚未实现。OA 表、字段和 OA 邮件发送方式见后续设计文档。第 9 节三项仍待确认。
|
|
||||||
> **适用范围**:OA 制程品质异常通知单的滚动统计,以及按料号 + 不良类别向品质担当和升级对象发送 OA 邮件
|
|
||||||
|
|
||||||
## 1. 背景与目标
|
|
||||||
|
|
||||||
制程品质异常通知单已经在 OA 中流转。同一料号、同一不良类别在近一年内反复出现时,需要按固定节奏提醒品质担当,并在当月再次发生时按次数升级到品质、生产经副理、COO 和老板。
|
|
||||||
|
|
||||||
本需求只定义统计、升级和推送规则。不改 OA 流程本身,也不回写异常单。
|
|
||||||
|
|
||||||
## 2. 范围
|
|
||||||
|
|
||||||
### 2.1 本期已确认
|
|
||||||
|
|
||||||
- 统计键、计次日期、纳入状态、近一年窗口、当月窗口。
|
|
||||||
- 品质担当周报与三档升级的收件人、抄送、不补发和同月不重复。
|
|
||||||
- 通知渠道是 OA 邮件。按收件人汇总,不逐单发信。
|
|
||||||
- 品质担当、品质、生产经副理、COO、老板五个岗位在界面配置。代码和配置文件不写死姓名或账号。品质担当与升级档里的「品质」是两个配置项。
|
|
||||||
|
|
||||||
### 2.2 本期不做
|
|
||||||
|
|
||||||
- 不接 Dify 对话。
|
|
||||||
- 不回写 OA 异常单,不改流程状态。
|
|
||||||
- 不撤回已发出的邮件。
|
|
||||||
- 不为已过去的自然月补发升级信。
|
|
||||||
|
|
||||||
OA 流程表、workflow、料号、不良类别、申请日期的字段名,以及 OA 邮件怎么发,写在后续设计文档,不在本需求里展开。
|
|
||||||
|
|
||||||
## 3. 统计对象
|
|
||||||
|
|
||||||
数据源是 OA「制程品质异常通知单」。一笔计入统计的单据同时满足:
|
|
||||||
|
|
||||||
- 流程处于归档或在途。
|
|
||||||
- 流程不是废弃,也不是撤销。
|
|
||||||
|
|
||||||
不按会签判定结果再过滤。料号按单据原值统计,不去斜杠、不截断、不与其他料号合并。不良项目、机种不参与合并。
|
|
||||||
|
|
||||||
统计键是 **料号 + 不良类别**。近一年和当月都用 **申请日期** 判断落在哪个区间。
|
|
||||||
|
|
||||||
## 4. 两个计数
|
|
||||||
|
|
||||||
两个计数分开。近一年决定要不要预警,当月笔数决定升级给谁。
|
|
||||||
|
|
||||||
### 4.1 近一年
|
|
||||||
|
|
||||||
申请日期落在 **扫描日减 1 年(含)到扫描日前 1 天(含)**。申请日期等于扫描日的单据不计入近一年。
|
|
||||||
|
|
||||||
扫描日 2026-10-23 时,区间是 2025-10-23 至 2026-10-22,两端都含。扫描日为闰年 2 月 29 日时,起始日取前一年 2 月 28 日。
|
|
||||||
|
|
||||||
同一键在这个区间内的合格单据笔数 ≥ 3,才进入预警。
|
|
||||||
|
|
||||||
### 4.2 当月
|
|
||||||
|
|
||||||
按申请日期所在自然月计。该月 1 日到月末都算,含扫描日当天。10 月就是 10 月 1 日到 10 月 31 日。
|
|
||||||
|
|
||||||
申请日期为扫描日当天的单据计入当月,次日才进入近一年。当月笔数只决定升级档,不能单独把近一年不足 3 次的键送进预警。
|
|
||||||
|
|
||||||
例:8 月已有 3 笔,10 月 1 日 1 笔,10 月 23 日又 1 笔。10 月 23 日扫描时,近一年已 ≥ 3(不含当天这一笔),当月是第 2 次,走 COO。
|
|
||||||
|
|
||||||
## 5. 升级与收件人
|
|
||||||
|
|
||||||
升级不补发跳过的档。
|
|
||||||
|
|
||||||
- 近一年这次刚到 3,但这笔已是当月第 2 笔时,只走 COO,不补「当月首次」。
|
|
||||||
- 两次扫描之间当月笔数从 1 直接到 3 及以上时,只走老板档,不补首次和第二次。
|
|
||||||
- 已过去的自然月不补发。
|
|
||||||
|
|
||||||
同一键、同一自然月,只在当月笔数进入更高档的那一周发一次升级信。之后几周停在同一档不再发。下个自然月从 0 重新计。近一年仍 ≥ 3 时,新月份的第一笔再走首次档。
|
|
||||||
|
|
||||||
| 条件 | 主送 | 抄送 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 近一年 ≥ 3,且当月 1 笔,本月未发过该档 | 品质、生产经副理 | 无 |
|
|
||||||
| 近一年 ≥ 3,且当月 2 笔,本月未发过该档 | COO | 无 |
|
|
||||||
| 近一年 ≥ 3,且当月 ≥ 3 笔,本月未发过该档 | 老板 | COO、品质、生产经副理 |
|
|
||||||
|
|
||||||
当月 0 笔时不发升级信。品质担当周报不看当月笔数,见第 6 节。
|
|
||||||
|
|
||||||
五个岗位的具体人员尚未指定,见第 9 节。上线前必须能在界面配置,不能写死在代码或环境文件里。
|
|
||||||
|
|
||||||
## 6. 推送
|
|
||||||
|
|
||||||
渠道是 OA 邮件。每周扫描一次,按收件人汇总成一封,不逐单刷屏。同一周可以同时有周报和升级信:周报里有这个料号,升级信再发给该档收件人。
|
|
||||||
|
|
||||||
### 6.1 品质担当周报
|
|
||||||
|
|
||||||
每周一封。列出当前近一年仍 ≥ 3 的全部料号 + 不良类别。条件一直成立就每周都发,不因上周已发过而跳过。
|
|
||||||
|
|
||||||
### 6.2 升级信
|
|
||||||
|
|
||||||
只发给第 5 节当前档的主送和抄送。同一键、同一自然月、同一档只发一次。
|
|
||||||
|
|
||||||
## 7. 建议默认
|
|
||||||
|
|
||||||
以下四项先按这个写,确认前可以改:
|
|
||||||
|
|
||||||
- 入口做成内置 Chat Agent,不接 Dify。默认页是 Dashboard,其余页签为异常清单、发送记录、收件人配置。管理员可手动扫描。形态对齐设备验收预警。可点击原型见 [process-quality-alert-prototype.html](process-quality-alert-prototype.html)。本期只冻结规则,不在本文件展开页面。
|
|
||||||
- 发送时刻可配置,初始为每周五 18:00,与合同付款预警、设备验收预警一致。
|
|
||||||
- 上线第一周只发品质担当全量周报,不为已经处在当月第 2、第 3 档的历史组合补发升级。
|
|
||||||
- 邮件明细至少包含:单号、申请日期、机种、料号、不良类别、不良项目、不良发生部、近一年次数、当月次数。
|
|
||||||
|
|
||||||
## 8. 留给设计文档
|
|
||||||
|
|
||||||
- OA 流程表、workflow、料号、不良类别、申请日期等字段名,以及怎么接入制程品质异常通知单。
|
|
||||||
- OA 邮件的发送方式。本需求只定渠道是 OA 邮件。
|
|
||||||
|
|
||||||
## 9. 待确认
|
|
||||||
|
|
||||||
确认前,下面三项不算冻结:
|
|
||||||
|
|
||||||
- 一单多行、每行不良类别不同时,是否按行各计 1 次。
|
|
||||||
- 不良类别为空的行是否排除。
|
|
||||||
- 品质担当、品质、生产经副理、COO、老板五个岗位的具体人员。
|
|
||||||
|
|
||||||
## 10. 验收标准
|
|
||||||
|
|
||||||
| 编号 | 条件 | 期望 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| AC-01 | 扫描日 2026-10-23 | 近一年只计申请日期 2025-10-23 至 2026-10-22。申请日期为 2026-10-23 的单据只计入 10 月,不计入近一年 |
|
|
||||||
| AC-02 | 同一料号 + 不良类别在近一年内不足 3 笔 | 不进周报,不发升级信 |
|
|
||||||
| AC-03 | 近一年 ≥ 3,当月 0 笔 | 只出现在品质担当周报 |
|
|
||||||
| AC-04 | 近一年 ≥ 3,当月第 1 / 2 / ≥3 笔,且本月该档未发过 | 分别主送品质+生产经副理、COO、老板。老板档抄送 COO、品质、生产经副理 |
|
|
||||||
| AC-05 | 8 月已有 3 笔,10 月 1 日 1 笔,10 月 23 日再 1 笔,扫描日为 10 月 23 日 | 近一年 ≥ 3,当月第 2 次,主送 COO,不补首次档 |
|
|
||||||
| AC-06 | 同一次扫描中当月笔数从 1 跨到 ≥ 3 | 只发老板档,不补首次和第二次 |
|
|
||||||
| AC-07 | 同一档已在本月发过,后续周当月笔数没有进入更高档 | 品质担当仍收周报;升级对象不再收同一档 |
|
|
||||||
| AC-08 | 单据为废弃或撤销 | 不计入近一年,也不计入当月 |
|
|
||||||
| AC-09 | 单据为归档或在途 | 按申请日期计入对应区间 |
|
|
||||||
| AC-10 | 料号原文带空格或符号 | 按原值与不良类别组成统计键,不另做清洗 |
|
|
||||||
@@ -1,743 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<!--
|
|
||||||
docs/features/process-quality-alert/process-quality-alert-prototype.html
|
|
||||||
用途:制程品质异常预警的可点击评审原型,用样例数据演示近一年窗口、当月升级和 OA 邮件汇总。
|
|
||||||
依赖:浏览器原生 HTML/CSS/JavaScript,无需构建。
|
|
||||||
逻辑:与 demand.md 对齐;不接 OA、不发邮件。默认打开 Dashboard。
|
|
||||||
假设:一单一行计 1 次;样例不含空不良类别。五个岗位人员仍待确认,收件人页改称呼只改写信封。
|
|
||||||
-->
|
|
||||||
<html lang="zh-CN">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
||||||
<title>制程品质异常预警 · 原型</title>
|
|
||||||
<style>
|
|
||||||
:root { --ink:#142033; --muted:#64748b; --line:#dce4ef; --bg:#f4f7fb; --nav:#111c31; --brand:#2563eb; --soft:#eaf2ff; --green:#067647; --amber:#b54708; --red:#b42318; }
|
|
||||||
* { box-sizing:border-box; }
|
|
||||||
body { margin:0; background:var(--bg); color:var(--ink); font:14px/1.5 "Segoe UI","Microsoft YaHei",sans-serif; }
|
|
||||||
button,select,input { font:inherit; }
|
|
||||||
button { cursor:pointer; }
|
|
||||||
.top { display:flex; justify-content:space-between; gap:16px; align-items:center; padding:12px 24px; background:var(--nav); color:#fff; }
|
|
||||||
.top small { color:#aac0db; margin-left:8px; }
|
|
||||||
.tabs { display:flex; gap:5px; flex-wrap:wrap; }
|
|
||||||
.tabs button { border:0; border-radius:7px; padding:7px 11px; color:#c5d3e6; background:transparent; font-weight:700; font-size:12px; }
|
|
||||||
.tabs button.active { color:#fff; background:var(--brand); }
|
|
||||||
main { width:min(1180px,calc(100% - 32px)); margin:auto; padding:22px 0 48px; }
|
|
||||||
.view { display:none; }
|
|
||||||
.view.active { display:block; }
|
|
||||||
.note { margin:0 0 14px; padding:10px 12px; border:1px solid #c9dcfb; border-radius:10px; background:#f3f8ff; color:#334155; font-size:12px; }
|
|
||||||
.hero { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:14px; }
|
|
||||||
.hero h1 { margin:0; font-size:22px; }
|
|
||||||
.hero p { margin:4px 0 0; color:var(--muted); }
|
|
||||||
.windows { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }
|
|
||||||
.windows span { padding:4px 8px; border-radius:99px; background:#fff; border:1px solid var(--line); font-size:12px; font-weight:700; }
|
|
||||||
.btn { border:1px solid var(--line); border-radius:8px; padding:8px 11px; background:#fff; font-size:12px; font-weight:700; }
|
|
||||||
.btn.primary { border-color:var(--brand); color:#fff; background:var(--brand); }
|
|
||||||
.kpis { display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); gap:12px; margin-bottom:14px; }
|
|
||||||
.kpis button { text-align:left; border:1px solid var(--line); border-radius:12px; background:#fff; padding:14px 16px; }
|
|
||||||
.kpis button:hover,.kpis button.active { border-color:#93c5fd; background:#f8fbff; }
|
|
||||||
.kpis b { display:block; font-size:26px; }
|
|
||||||
.kpis span { color:var(--muted); font-size:12px; }
|
|
||||||
.card { border:1px solid var(--line); border-radius:12px; background:#fff; overflow:hidden; }
|
|
||||||
.split { display:grid; grid-template-columns:1.15fr .85fr; gap:14px; margin-bottom:14px; }
|
|
||||||
.hd { display:flex; justify-content:space-between; gap:12px; align-items:flex-start; padding:14px 16px 0; }
|
|
||||||
.hd h2 { margin:0; font-size:15px; }
|
|
||||||
.bd { padding:14px 16px 16px; }
|
|
||||||
.bar { display:grid; grid-template-columns:132px 1fr 28px; gap:8px; align-items:center; margin:8px 0; font-size:12px; }
|
|
||||||
.bar i { display:block; height:10px; border-radius:99px; background:#dbeafe; }
|
|
||||||
.bar i span { display:block; height:100%; border-radius:99px; background:#2563eb; }
|
|
||||||
.bar .amber span { background:#d97706; }
|
|
||||||
.bar .red span { background:#dc2626; }
|
|
||||||
.bar .green span { background:#059669; }
|
|
||||||
.mails { display:grid; gap:8px; }
|
|
||||||
.mail-row { display:flex; justify-content:space-between; gap:8px; padding:8px 10px; border:1px solid var(--line); border-radius:10px; font-size:12px; }
|
|
||||||
.mail-row b { font-size:16px; }
|
|
||||||
.filters { display:flex; flex-wrap:wrap; gap:8px; padding:12px; }
|
|
||||||
.filters button { border:1px solid var(--line); border-radius:99px; padding:5px 10px; background:#fff; font-size:12px; font-weight:700; color:#475569; }
|
|
||||||
.filters button.active { border-color:#bfdbfe; color:#1d4ed8; background:var(--soft); }
|
|
||||||
table { width:100%; border-collapse:collapse; font-size:12px; }
|
|
||||||
th,td { padding:10px 8px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
|
||||||
th { color:var(--muted); background:#f8fbff; font-weight:700; }
|
|
||||||
tr.clickable { cursor:pointer; }
|
|
||||||
tr.clickable:hover,tr.selected { background:#f3f7ff; }
|
|
||||||
.badge { display:inline-flex; padding:2px 8px; border-radius:99px; font-size:11px; font-weight:800; }
|
|
||||||
.blue { color:#175cd3; background:var(--soft); }
|
|
||||||
.green { color:var(--green); background:#eafaf1; }
|
|
||||||
.amber { color:var(--amber); background:#fff7e6; }
|
|
||||||
.red { color:var(--red); background:#fff0ef; }
|
|
||||||
.gray { color:#475569; background:#edf1f6; }
|
|
||||||
.muted { color:var(--muted); }
|
|
||||||
.two { display:grid; grid-template-columns:280px 1fr; gap:14px; }
|
|
||||||
.person { display:flex; flex-direction:column; gap:8px; }
|
|
||||||
.person button { border:1px solid var(--line); border-radius:8px; padding:8px 10px; background:#fff; font-size:12px; text-align:left; font-weight:700; }
|
|
||||||
.person button.active { border-color:#93c5fd; background:var(--soft); }
|
|
||||||
.letter { margin-bottom:12px; padding:14px; border:1px solid var(--line); border-radius:12px; background:#fff; }
|
|
||||||
.letter h3 { margin:0 0 8px; font-size:15px; }
|
|
||||||
.kv { display:grid; grid-template-columns:72px 1fr; gap:6px; margin-bottom:8px; font-size:12px; }
|
|
||||||
.kv b { color:var(--muted); font-weight:700; }
|
|
||||||
.toast { position:fixed; right:16px; bottom:16px; padding:10px 12px; border-radius:8px; color:#fff; background:#142036; opacity:0; transition:.2s; }
|
|
||||||
.toast.show { opacity:1; }
|
|
||||||
.people-grid { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:14px; align-items:start; }
|
|
||||||
#v-people .prow { display:grid; grid-template-columns:minmax(0,1fr) 168px; gap:12px; align-items:center; padding:12px 16px; border-top:1px solid var(--line); }
|
|
||||||
#v-people .prow b { display:block; font-size:13px; }
|
|
||||||
#v-people .prow span { color:var(--muted); font-size:12px; }
|
|
||||||
#v-people select { width:100%; height:36px; padding:0 8px; border:1px solid #d7dee8; border-radius:8px; background:#fff; color:var(--ink); font-weight:650; }
|
|
||||||
#v-people select:focus { outline:2px solid #bfdbfe; border-color:#2563eb; }
|
|
||||||
#v-people .parts { margin:8px 0 0; padding:0; list-style:none; }
|
|
||||||
#v-people .parts li { padding:8px 0; border-top:1px solid var(--line); font-size:12px; }
|
|
||||||
@media (max-width:980px) {
|
|
||||||
.kpis { grid-template-columns:1fr 1fr; }
|
|
||||||
.split,.two,.hero,.top,.people-grid { display:block; }
|
|
||||||
.people-grid > article + article { margin-top:14px; }
|
|
||||||
.tabs { margin-top:8px; }
|
|
||||||
.split > article + article,.two > article + article { margin-top:14px; }
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<header class="top">
|
|
||||||
<div><b>制程品质异常预警</b><small>原型 · 样例数据 · 不接 OA</small></div>
|
|
||||||
<nav class="tabs" id="tabs">
|
|
||||||
<button class="active" data-v="dash">Dashboard</button>
|
|
||||||
<button data-v="list">异常清单</button>
|
|
||||||
<button data-v="mail">发送预览</button>
|
|
||||||
<button data-v="people">收件人</button>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
<main>
|
|
||||||
<p class="note">原型假设:一单一行计 1 次;样例不含空不良类别。五个岗位的具体人员仍待确认,这里的姓名只影响预览称呼。扫描日固定为 2026-10-23。近一年计申请日期 2025-10-23 至 2026-10-22。当月计 2026-10-01 至 2026-10-31,含当天。</p>
|
|
||||||
|
|
||||||
<section class="view active" id="v-dash">
|
|
||||||
<div class="hero">
|
|
||||||
<div>
|
|
||||||
<h1>Dashboard</h1>
|
|
||||||
<p>本周五 18:00 将发出的周报和升级信。近一年不足 3 次的键不出现在这里。</p>
|
|
||||||
<div class="windows">
|
|
||||||
<span>扫描日 2026-10-23</span>
|
|
||||||
<span>近一年 2025-10-23 ~ 2026-10-22</span>
|
|
||||||
<span>当月 2026-10-01 ~ 2026-10-31</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="kpis" id="kpis"></div>
|
|
||||||
<div class="split">
|
|
||||||
<article class="card">
|
|
||||||
<div class="hd"><h2>档位分布</h2></div>
|
|
||||||
<div class="bd" id="bars"></div>
|
|
||||||
</article>
|
|
||||||
<article class="card">
|
|
||||||
<div class="hd"><h2>本周收件人</h2><p class="muted">含抄送。同一人收到多封时分开计数。</p></div>
|
|
||||||
<div class="bd mails" id="mailCounts"></div>
|
|
||||||
</article>
|
|
||||||
</div>
|
|
||||||
<article class="card">
|
|
||||||
<div class="hd"><h2>近一年仍 ≥ 3</h2><p class="muted">按近一年次数从高到低。点一行看单据。</p></div>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>料号</th><th>不良类别</th><th>机种</th><th>近一年</th><th>当月</th><th>本周动作</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody id="watchRows"></tbody>
|
|
||||||
</table>
|
|
||||||
</article>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="view" id="v-list">
|
|
||||||
<div class="hero">
|
|
||||||
<div>
|
|
||||||
<h1>异常清单</h1>
|
|
||||||
<p>废弃、撤销和近一年不足 3 次的样例留在这里,标成不预警。计入标记按申请日期和流程状态计算。</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<article class="card">
|
|
||||||
<div class="filters" id="filters"></div>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>料号</th><th>不良类别</th><th>近一年</th><th>当月</th><th>状态</th><th></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody id="keyRows"></tbody>
|
|
||||||
</table>
|
|
||||||
</article>
|
|
||||||
<article class="card" style="margin-top:14px">
|
|
||||||
<div class="hd"><h2 id="detailTitle">单据明细</h2></div>
|
|
||||||
<div class="bd" id="detailNote"></div>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>单号</th><th>申请日期</th><th>机种</th><th>料号</th><th>不良类别</th><th>不良项目</th><th>不良发生部</th><th>流程</th><th>计入</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody id="formRows"></tbody>
|
|
||||||
</table>
|
|
||||||
</article>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="view" id="v-mail">
|
|
||||||
<div class="hero">
|
|
||||||
<div>
|
|
||||||
<h1>发送预览</h1>
|
|
||||||
<p>本周五 18:00 的 OA 邮件。品质担当收全量周报。升级信只含本周新跨入的档,不补发跳过的档。</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="two">
|
|
||||||
<article class="card"><div class="bd"><div class="person" id="recipients"></div></div></article>
|
|
||||||
<div id="letters"></div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="view" id="v-people">
|
|
||||||
<div class="hero">
|
|
||||||
<div>
|
|
||||||
<h1>收件人</h1>
|
|
||||||
<p>五个岗位分开配置。改称呼会立刻出现在右侧预览里,不进入正式名单。</p>
|
|
||||||
</div>
|
|
||||||
<button class="btn primary" id="savePeople" type="button">保存称呼</button>
|
|
||||||
</div>
|
|
||||||
<div class="people-grid">
|
|
||||||
<article class="card">
|
|
||||||
<div class="hd"><div><h2>岗位</h2><p class="muted">品质担当和升级档里的品质是两个人。</p></div></div>
|
|
||||||
<div id="slipBands"></div>
|
|
||||||
</article>
|
|
||||||
<article class="card">
|
|
||||||
<div class="hd"><div><h2>本周预览</h2><p class="muted" id="slipMeta"></p></div></div>
|
|
||||||
<div class="filters" id="slipPicks"></div>
|
|
||||||
<div class="bd" id="slipLetter"></div>
|
|
||||||
</article>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
<div class="toast" id="toast"></div>
|
|
||||||
<script>
|
|
||||||
/**
|
|
||||||
* 用样例异常单演示近一年窗口、当月升级和按收件人汇总的 OA 邮件。
|
|
||||||
* 核心逻辑:近一年不含扫描日;当月含扫描日;废弃和撤销不计入;跳过的档不补发。
|
|
||||||
*/
|
|
||||||
(() => {
|
|
||||||
const SCAN = '2026-10-23';
|
|
||||||
const YEAR_FROM = '2025-10-23';
|
|
||||||
const YEAR_TO = '2026-10-22';
|
|
||||||
const MONTH_FROM = '2026-10-01';
|
|
||||||
const MONTH_TO = '2026-10-31';
|
|
||||||
const $ = (id) => document.getElementById(id);
|
|
||||||
const ROLE_FIELDS = [
|
|
||||||
['owner', '品质担当'],
|
|
||||||
['quality', '品质'],
|
|
||||||
['prod', '生产经副理'],
|
|
||||||
['coo', 'COO'],
|
|
||||||
['boss', '老板']
|
|
||||||
];
|
|
||||||
const NAME_OPTIONS = ['待确认', '样例·甲', '样例·乙'];
|
|
||||||
|
|
||||||
let view = 'dash';
|
|
||||||
let filter = 'watch';
|
|
||||||
let selected = 'A';
|
|
||||||
let mailPerson = 'owner';
|
|
||||||
let slipId = 'weekly';
|
|
||||||
const people = { owner:'待确认', quality:'待确认', prod:'待确认', coo:'待确认', boss:'待确认' };
|
|
||||||
|
|
||||||
const keys = [
|
|
||||||
{
|
|
||||||
id:'A', model:'AR1.2', part:'D4-A12HOX0000040', defect:'外观不良', sent:[],
|
|
||||||
note:'当月 0 笔。近一年仍 ≥ 3,只进品质担当周报。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2025-0901', date:'2025-09-01', model:'AR1.2', item:'外观划伤', dept:'生二包装', status:'归档' },
|
|
||||||
{ no:'QA-2026-0804', date:'2026-08-04', model:'AR1.2', item:'包装破损', dept:'生二包装', status:'归档' },
|
|
||||||
{ no:'QA-2026-0818', date:'2026-08-18', model:'AR1.2', item:'外观划伤', dept:'生二包装', status:'在途' },
|
|
||||||
{ no:'QA-2026-0906', date:'2026-09-06', model:'AR1.2', item:'包装方式', dept:'生二包装', status:'归档' },
|
|
||||||
{ no:'QA-2026-0920', date:'2026-09-20', model:'AR1.2', item:'外观不良', dept:'生二包装', status:'归档' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id:'B', model:'CE001', part:'I6-CE0010321', defect:'尺寸不良', sent:[],
|
|
||||||
note:'当月第 1 笔,本月尚未发过该档。本周主送品质和生产经副理。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2025-1023', date:'2025-10-23', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' },
|
|
||||||
{ no:'QA-2026-0114', date:'2026-01-14', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' },
|
|
||||||
{ no:'QA-2026-0402', date:'2026-04-02', model:'CE001', item:'孔径超差', dept:'生二下料', status:'在途' },
|
|
||||||
{ no:'QA-2026-0719', date:'2026-07-19', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' },
|
|
||||||
{ no:'QA-2026-1008', date:'2026-10-08', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id:'C', model:'RT05', part:'I9-RT05001106/107', defect:'错漏混', sent:[],
|
|
||||||
note:'8 月 3 笔,10 月 1 日 1 笔,10 月 23 日又 1 笔。近一年不含当天仍 ≥ 3,当月是第 2 次,本周只主送 COO,不补首次档。料号按原值,不去斜杠。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2026-0805', date:'2026-08-05', model:'RT05', item:'漏装', dept:'生二焊接', status:'归档' },
|
|
||||||
{ no:'QA-2026-0812', date:'2026-08-12', model:'RT05', item:'错料', dept:'生二焊接', status:'在途' },
|
|
||||||
{ no:'QA-2026-0820', date:'2026-08-20', model:'RT05', item:'漏焊', dept:'生二焊接', status:'归档' },
|
|
||||||
{ no:'QA-2026-1001', date:'2026-10-01', model:'RT05', item:'错料', dept:'生二焊接', status:'归档' },
|
|
||||||
{ no:'QA-2026-1023', date:'2026-10-23', model:'RT05', item:'漏装', dept:'生二焊接', status:'在途' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id:'D', model:'AR1.1', part:'B3-AR100253', defect:'实物与图不符', sent:[],
|
|
||||||
note:'上次扫描时当月还是 0 笔。本周一次看到 10 月 20、21、22 日三笔,只走老板档,不补首次和第二次。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2026-0302', date:'2026-03-02', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'归档' },
|
|
||||||
{ no:'QA-2026-0411', date:'2026-04-11', model:'AR1.1', item:'图物不符', dept:'生一冲压', status:'归档' },
|
|
||||||
{ no:'QA-2026-0619', date:'2026-06-19', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'在途' },
|
|
||||||
{ no:'QA-2026-1020', date:'2026-10-20', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'归档' },
|
|
||||||
{ no:'QA-2026-1021', date:'2026-10-21', model:'AR1.1', item:'图物不符', dept:'生一冲压', status:'归档' },
|
|
||||||
{ no:'QA-2026-1022', date:'2026-10-22', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'在途' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id:'E', model:'AR1.2', part:'D4-AR1200100', defect:'尺寸不良', sent:['first'],
|
|
||||||
note:'10 月 10 日已发过当月首次。本周当月仍是 1 笔,周报继续收,升级信不再发。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2026-0702', date:'2026-07-02', model:'AR1.2', item:'尺寸超差', dept:'生二折弯', status:'归档' },
|
|
||||||
{ no:'QA-2026-0814', date:'2026-08-14', model:'AR1.2', item:'尺寸超差', dept:'生二折弯', status:'在途' },
|
|
||||||
{ no:'QA-2026-1006', date:'2026-10-06', model:'AR1.2', item:'孔径超差', dept:'生二折弯', status:'归档' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id:'F', model:'CE001', part:'I6-CE0010362', defect:'尺寸不良', sent:[],
|
|
||||||
note:'归档和在途都计入,但近一年只有 2 笔,不预警。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2026-0912', date:'2026-09-12', model:'CE001', item:'尺寸超差', dept:'生二折弯', status:'归档' },
|
|
||||||
{ no:'QA-2026-1015', date:'2026-10-15', model:'CE001', item:'尺寸超差', dept:'生二折弯', status:'在途' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id:'G', model:'AR1.2', part:'D4-AR1200098', defect:'错漏混', sent:[],
|
|
||||||
note:'废弃和撤销不计入。剩下 2 笔有效单,近一年不足 3 次,不预警。',
|
|
||||||
forms:[
|
|
||||||
{ no:'QA-2026-0601', date:'2026-06-01', model:'AR1.2', item:'漏孔', dept:'生二包装', status:'归档' },
|
|
||||||
{ no:'QA-2026-0708', date:'2026-07-08', model:'AR1.2', item:'混料', dept:'生二包装', status:'在途' },
|
|
||||||
{ no:'QA-2026-0819', date:'2026-08-19', model:'AR1.2', item:'漏孔', dept:'生二包装', status:'废弃' },
|
|
||||||
{ no:'QA-2026-0903', date:'2026-09-03', model:'AR1.2', item:'错料', dept:'生二包装', status:'撤销' }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断申请日期是否落在近一年窗口。
|
|
||||||
* 扫描日当天不算。两端日期都含。
|
|
||||||
* @param {string} date - 申请日期,YYYY-MM-DD
|
|
||||||
* @returns {boolean}
|
|
||||||
*/
|
|
||||||
function inYear(date) {
|
|
||||||
return date >= YEAR_FROM && date <= YEAR_TO;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断申请日期是否落在扫描日所在自然月。
|
|
||||||
* 该月 1 日到月末都算,含扫描日当天。
|
|
||||||
* @param {string} date - 申请日期,YYYY-MM-DD
|
|
||||||
* @returns {boolean}
|
|
||||||
*/
|
|
||||||
function inMonth(date) {
|
|
||||||
return date >= MONTH_FROM && date <= MONTH_TO;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归档和在途计入。废弃、撤销不计入。
|
|
||||||
* @param {{status:string}} form - 样例单据
|
|
||||||
* @returns {boolean}
|
|
||||||
*/
|
|
||||||
function countable(form) {
|
|
||||||
return form.status === '归档' || form.status === '在途';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 近一年有效笔数,不含扫描日当天。
|
|
||||||
* @param {{forms:Array}} key - 料号 + 不良类别
|
|
||||||
* @returns {number}
|
|
||||||
*/
|
|
||||||
function yearCount(key) {
|
|
||||||
return key.forms.filter((form) => countable(form) && inYear(form.date)).length;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 当月有效笔数,含扫描日当天。
|
|
||||||
* @param {{forms:Array}} key - 料号 + 不良类别
|
|
||||||
* @returns {number}
|
|
||||||
*/
|
|
||||||
function monthCount(key) {
|
|
||||||
return key.forms.filter((form) => countable(form) && inMonth(form.date)).length;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 当前所处档位。近一年不足 3 次为 none,当月 0 笔为 weekly。
|
|
||||||
* @param {{forms:Array}} key - 料号 + 不良类别
|
|
||||||
* @returns {'none'|'weekly'|'first'|'second'|'third'}
|
|
||||||
*/
|
|
||||||
function standingTier(key) {
|
|
||||||
if (yearCount(key) < 3) return 'none';
|
|
||||||
const month = monthCount(key);
|
|
||||||
if (month <= 0) return 'weekly';
|
|
||||||
if (month === 1) return 'first';
|
|
||||||
if (month === 2) return 'second';
|
|
||||||
return 'third';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 本周要新发的升级档。已发过的同一档不再发,也不补发更低档。
|
|
||||||
* @param {{forms:Array, sent:string[]}} key - 料号 + 不良类别
|
|
||||||
* @returns {'first'|'second'|'third'|null}
|
|
||||||
*/
|
|
||||||
function upgradeTier(key) {
|
|
||||||
const tier = standingTier(key);
|
|
||||||
if (tier === 'none' || tier === 'weekly') return null;
|
|
||||||
if (key.sent.includes(tier)) return null;
|
|
||||||
return tier;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清单和 Dashboard 上的本周动作文案。
|
|
||||||
* @param {{forms:Array, sent:string[]}} key - 料号 + 不良类别
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function actionLabel(key) {
|
|
||||||
const upgrade = upgradeTier(key);
|
|
||||||
if (standingTier(key) === 'none') return '不预警';
|
|
||||||
if (upgrade === 'first') return '周报 + 首次升级';
|
|
||||||
if (upgrade === 'second') return '周报 + 主送 COO';
|
|
||||||
if (upgrade === 'third') return '周报 + 主送老板';
|
|
||||||
if (standingTier(key) === 'weekly') return '只发周报';
|
|
||||||
return '周报照发。当月这一档已经发过,这周不再发升级信';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把本周动作写成徽章。
|
|
||||||
* @param {{forms:Array, sent:string[]}} key - 料号 + 不良类别
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function actionBadge(key) {
|
|
||||||
const upgrade = upgradeTier(key);
|
|
||||||
if (standingTier(key) === 'none') return '<span class="badge gray">不预警</span>';
|
|
||||||
if (upgrade === 'first') return '<span class="badge blue">首次升级</span>';
|
|
||||||
if (upgrade === 'second') return '<span class="badge amber">第二次 · COO</span>';
|
|
||||||
if (upgrade === 'third') return '<span class="badge red">第三次及以上 · 老板</span>';
|
|
||||||
if (standingTier(key) === 'weekly') return '<span class="badge green">只发周报</span>';
|
|
||||||
return '<span class="badge gray">升级已发过</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 单笔单据的计入说明。废弃和撤销优先于日期窗口。
|
|
||||||
* @param {{date:string, status:string}} form - 样例单据
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function countBadge(form) {
|
|
||||||
if (!countable(form)) return '<span class="badge red">不计入(' + form.status + ')</span>';
|
|
||||||
const year = inYear(form.date);
|
|
||||||
const month = inMonth(form.date);
|
|
||||||
if (year && month) return '<span class="badge blue">近一年 + 当月</span>';
|
|
||||||
if (year) return '<span class="badge green">近一年</span>';
|
|
||||||
if (month) return '<span class="badge amber">只算当月</span>';
|
|
||||||
return '<span class="badge gray">两者都不算</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按当前筛选留下的统计键。
|
|
||||||
* @returns {Array}
|
|
||||||
*/
|
|
||||||
function visibleKeys() {
|
|
||||||
return keys.filter((key) => {
|
|
||||||
const tier = standingTier(key);
|
|
||||||
const upgrade = upgradeTier(key);
|
|
||||||
if (filter === 'watch') return yearCount(key) >= 3;
|
|
||||||
if (filter === 'weekly') return tier === 'weekly';
|
|
||||||
if (filter === 'first') return upgrade === 'first';
|
|
||||||
if (filter === 'second') return upgrade === 'second';
|
|
||||||
if (filter === 'third') return upgrade === 'third';
|
|
||||||
if (filter === 'skip') return tier === 'none';
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 岗位显示名。待确认时带上岗位,避免预览里五个人都叫同一句话。
|
|
||||||
* @param {'owner'|'quality'|'prod'|'coo'|'boss'} role - 岗位键
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function personName(role) {
|
|
||||||
const label = ROLE_FIELDS.find((item) => item[0] === role)[1];
|
|
||||||
if (people[role] === '待确认') return label + '(待确认)';
|
|
||||||
return people[role] + ' · ' + label;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 本周要发出的邮件。周报一封;每个新升级档一封,不把跳过的档补进去。
|
|
||||||
* @returns {Array<{id:string, kind:string, to:string[], cc:string[], keys:Array}>}
|
|
||||||
*/
|
|
||||||
function letters() {
|
|
||||||
const watch = keys.filter((key) => yearCount(key) >= 3)
|
|
||||||
.sort((a, b) => yearCount(b) - yearCount(a) || a.part.localeCompare(b.part));
|
|
||||||
const ofTier = (tier) => watch.filter((key) => upgradeTier(key) === tier);
|
|
||||||
const batch = [];
|
|
||||||
if (watch.length) {
|
|
||||||
batch.push({ id:'weekly', kind:'周报', to:[personName('owner')], cc:[], keys:watch });
|
|
||||||
}
|
|
||||||
const first = ofTier('first');
|
|
||||||
if (first.length) {
|
|
||||||
batch.push({ id:'first', kind:'当月首次', to:[personName('quality'), personName('prod')], cc:[], keys:first });
|
|
||||||
}
|
|
||||||
const second = ofTier('second');
|
|
||||||
if (second.length) {
|
|
||||||
batch.push({ id:'second', kind:'当月第二次', to:[personName('coo')], cc:[], keys:second });
|
|
||||||
}
|
|
||||||
const third = ofTier('third');
|
|
||||||
if (third.length) {
|
|
||||||
batch.push({
|
|
||||||
id:'third',
|
|
||||||
kind:'当月第三次及以上',
|
|
||||||
to:[personName('boss')],
|
|
||||||
cc:[personName('coo'), personName('quality'), personName('prod')],
|
|
||||||
keys:third
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return batch;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 某人作为主送或抄送会收到的邮件。
|
|
||||||
* @param {string} name - personName 的结果
|
|
||||||
* @returns {Array}
|
|
||||||
*/
|
|
||||||
function lettersFor(name) {
|
|
||||||
return letters().filter((letter) => letter.to.includes(name) || letter.cc.includes(name));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 切换页签。从 Dashboard 点进清单时保留已选统计键。
|
|
||||||
* @param {string} next - dash、list、mail、people
|
|
||||||
*/
|
|
||||||
function show(next) {
|
|
||||||
view = next;
|
|
||||||
document.querySelectorAll('.tabs button').forEach((button) => {
|
|
||||||
button.classList.toggle('active', button.dataset.v === next);
|
|
||||||
});
|
|
||||||
document.querySelectorAll('.view').forEach((section) => {
|
|
||||||
section.classList.toggle('active', section.id === 'v-' + next);
|
|
||||||
});
|
|
||||||
if (next === 'list') renderList();
|
|
||||||
if (next === 'mail') renderMail();
|
|
||||||
if (next === 'people') renderPeople();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 打开某个统计键的单据明细。
|
|
||||||
* @param {string} id - 样例键 id
|
|
||||||
* @param {string} [nextFilter] - 清单筛选
|
|
||||||
*/
|
|
||||||
function openKey(id, nextFilter) {
|
|
||||||
selected = id;
|
|
||||||
if (nextFilter) filter = nextFilter;
|
|
||||||
show('list');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 画 Dashboard 的指标、档位条、收件人封数和预警清单。
|
|
||||||
*/
|
|
||||||
function renderDash() {
|
|
||||||
const watch = keys.filter((key) => yearCount(key) >= 3);
|
|
||||||
const cards = [
|
|
||||||
['watch', watch.length, '近一年仍 ≥ 3'],
|
|
||||||
['weekly', watch.filter((key) => standingTier(key) === 'weekly').length, '本周只发周报(当月 0 笔)'],
|
|
||||||
['first', watch.filter((key) => upgradeTier(key) === 'first').length, '本周首次升级'],
|
|
||||||
['second', watch.filter((key) => upgradeTier(key) === 'second').length, '本周第二次(COO)'],
|
|
||||||
['third', watch.filter((key) => upgradeTier(key) === 'third').length, '本周第三次及以上(老板)']
|
|
||||||
];
|
|
||||||
$('kpis').innerHTML = cards.map(([id, num, label]) => (
|
|
||||||
'<button type="button" data-jump="' + id + '"><b>' + num + '</b><span>' + label + '</span></button>'
|
|
||||||
)).join('');
|
|
||||||
$('kpis').querySelectorAll('button').forEach((button) => {
|
|
||||||
button.onclick = () => openKey(selected, button.dataset.jump === 'watch' ? 'watch' : button.dataset.jump);
|
|
||||||
});
|
|
||||||
|
|
||||||
const buckets = [
|
|
||||||
['只发周报', cards[1][1], 'green'],
|
|
||||||
['本周首次', cards[2][1], ''],
|
|
||||||
['本周第二次', cards[3][1], 'amber'],
|
|
||||||
['本周第三次及以上', cards[4][1], 'red'],
|
|
||||||
['升级已发过', watch.filter((key) => standingTier(key) !== 'weekly' && !upgradeTier(key)).length, 'green']
|
|
||||||
];
|
|
||||||
const max = Math.max(1, ...buckets.map((item) => item[1]));
|
|
||||||
$('bars').innerHTML = buckets.map(([label, num, tone]) => (
|
|
||||||
'<div class="bar"><span>' + label + '</span><i class="' + tone + '"><span style="width:' + (num / max * 100) + '%"></span></i><b>' + num + '</b></div>'
|
|
||||||
)).join('');
|
|
||||||
|
|
||||||
const names = ['owner', 'quality', 'prod', 'coo', 'boss'].map(personName);
|
|
||||||
$('mailCounts').innerHTML = names.map((name) => {
|
|
||||||
const mine = lettersFor(name);
|
|
||||||
return '<div class="mail-row"><span>' + name + '</span><b>' + mine.length + ' 封</b></div>';
|
|
||||||
}).join('');
|
|
||||||
|
|
||||||
const rows = watch.slice().sort((a, b) => yearCount(b) - yearCount(a) || a.part.localeCompare(b.part));
|
|
||||||
$('watchRows').innerHTML = rows.map((key) => (
|
|
||||||
'<tr class="clickable" data-id="' + key.id + '"><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + key.model + '</td><td>' + yearCount(key) + '</td><td>' + monthCount(key) + '</td><td>' + actionBadge(key) + '</td></tr>'
|
|
||||||
)).join('');
|
|
||||||
$('watchRows').querySelectorAll('tr').forEach((row) => {
|
|
||||||
row.onclick = () => openKey(row.dataset.id, 'all');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 画异常清单和当前统计键的单据明细。
|
|
||||||
*/
|
|
||||||
function renderList() {
|
|
||||||
const filters = [
|
|
||||||
['all', '全部'],
|
|
||||||
['watch', '近一年 ≥ 3'],
|
|
||||||
['weekly', '只发周报'],
|
|
||||||
['first', '本周首次'],
|
|
||||||
['second', '本周第二次'],
|
|
||||||
['third', '本周第三次及以上'],
|
|
||||||
['skip', '不预警']
|
|
||||||
];
|
|
||||||
$('filters').innerHTML = filters.map(([id, label]) => (
|
|
||||||
'<button type="button" data-f="' + id + '"' + (filter === id ? ' class="active"' : '') + '>' + label + '</button>'
|
|
||||||
)).join('');
|
|
||||||
$('filters').querySelectorAll('button').forEach((button) => {
|
|
||||||
button.onclick = () => { filter = button.dataset.f; renderList(); };
|
|
||||||
});
|
|
||||||
|
|
||||||
const rows = visibleKeys().sort((a, b) => yearCount(b) - yearCount(a) || a.part.localeCompare(b.part));
|
|
||||||
if (!rows.some((key) => key.id === selected) && rows[0]) selected = rows[0].id;
|
|
||||||
$('keyRows').innerHTML = rows.map((key) => (
|
|
||||||
'<tr class="clickable' + (key.id === selected ? ' selected' : '') + '" data-id="' + key.id + '"><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + yearCount(key) + '</td><td>' + monthCount(key) + '</td><td>' + actionBadge(key) + '</td><td>' + actionLabel(key) + '</td></tr>'
|
|
||||||
)).join('') || '<tr><td colspan="6" class="muted">这个筛选下没有样例。</td></tr>';
|
|
||||||
$('keyRows').querySelectorAll('tr[data-id]').forEach((row) => {
|
|
||||||
row.onclick = () => { selected = row.dataset.id; renderList(); };
|
|
||||||
});
|
|
||||||
|
|
||||||
const key = keys.find((item) => item.id === selected) || rows[0];
|
|
||||||
if (!key) {
|
|
||||||
$('detailTitle').textContent = '单据明细';
|
|
||||||
$('detailNote').textContent = '';
|
|
||||||
$('formRows').innerHTML = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
$('detailTitle').textContent = key.part + ' · ' + key.defect;
|
|
||||||
$('detailNote').innerHTML = '<p class="muted" style="margin:0">' + key.note + ' 近一年 ' + yearCount(key) + ' 笔,当月 ' + monthCount(key) + ' 笔。</p>';
|
|
||||||
$('formRows').innerHTML = key.forms.map((form) => (
|
|
||||||
'<tr><td>' + form.no + '</td><td>' + form.date + '</td><td>' + form.model + '</td><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + form.item + '</td><td>' + form.dept + '</td><td>' + form.status + '</td><td>' + countBadge(form) + '</td></tr>'
|
|
||||||
)).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 画某个收件人本周会收到的 OA 邮件。
|
|
||||||
*/
|
|
||||||
function renderMail() {
|
|
||||||
const batch = letters();
|
|
||||||
const peopleInBatch = [];
|
|
||||||
batch.forEach((letter) => {
|
|
||||||
letter.to.concat(letter.cc).forEach((name) => {
|
|
||||||
if (!peopleInBatch.includes(name)) peopleInBatch.push(name);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
if (!peopleInBatch.includes(mailPerson) && !peopleInBatch.some((name) => name.startsWith(personName(mailPerson)))) {
|
|
||||||
mailPerson = 'owner';
|
|
||||||
}
|
|
||||||
const activeName = personName(mailPerson);
|
|
||||||
$('recipients').innerHTML = ROLE_FIELDS.map(([role]) => {
|
|
||||||
const name = personName(role);
|
|
||||||
const count = lettersFor(name).length;
|
|
||||||
return '<button type="button" data-role="' + role + '"' + (mailPerson === role ? ' class="active"' : '') + '>' + name + '<br><span class="muted">' + count + ' 封</span></button>';
|
|
||||||
}).join('');
|
|
||||||
$('recipients').querySelectorAll('button').forEach((button) => {
|
|
||||||
button.onclick = () => { mailPerson = button.dataset.role; renderMail(); };
|
|
||||||
});
|
|
||||||
|
|
||||||
const mine = lettersFor(activeName);
|
|
||||||
$('letters').innerHTML = mine.map((letter) => {
|
|
||||||
const roleLine = letter.to.includes(activeName) ? '主送' : '抄送';
|
|
||||||
const body = letter.keys.map((key) => (
|
|
||||||
key.forms.filter((form) => countable(form) && (inYear(form.date) || inMonth(form.date))).map((form) => (
|
|
||||||
'<tr><td>' + form.no + '</td><td>' + form.date + '</td><td>' + form.model + '</td><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + form.item + '</td><td>' + form.dept + '</td><td>' + yearCount(key) + '</td><td>' + monthCount(key) + '</td></tr>'
|
|
||||||
)).join('')
|
|
||||||
)).join('');
|
|
||||||
return '<article class="letter"><h3>' + letter.kind + '</h3><div class="kv"><b>发送</b><span>2026-10-23 18:00 · OA 邮件</span><b>你的身份</b><span>' + roleLine + '</span><b>主送</b><span>' + letter.to.join('、') + '</span><b>抄送</b><span>' + (letter.cc.length ? letter.cc.join('、') : '无') + '</span></div><table><thead><tr><th>单号</th><th>申请日期</th><th>机种</th><th>料号</th><th>不良类别</th><th>不良项目</th><th>不良发生部</th><th>近一年</th><th>当月</th></tr></thead><tbody>' + body + '</tbody></table></article>';
|
|
||||||
}).join('') || '<article class="letter"><p class="muted">这位本周没有邮件。</p></article>';
|
|
||||||
}
|
|
||||||
|
|
||||||
const SLIPS = [
|
|
||||||
{ id:'weekly', title:'周报', to:['owner'], cc:[] },
|
|
||||||
{ id:'first', title:'当月首次', to:['quality','prod'], cc:[] },
|
|
||||||
{ id:'second', title:'当月第二次', to:['coo'], cc:[] },
|
|
||||||
{ id:'third', title:'第三次及以上', to:['boss'], cc:['coo','quality','prod'] }
|
|
||||||
];
|
|
||||||
const ROLE_DUTY = {
|
|
||||||
owner:'周报主送',
|
|
||||||
quality:'首次主送,第三次抄送',
|
|
||||||
prod:'首次主送,第三次抄送',
|
|
||||||
coo:'第二次主送,第三次抄送',
|
|
||||||
boss:'第三次主送'
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 当前这封信要列出的料号。周报是近一年仍不少于 3 次的全部键,升级信只含本周新跨入的那一档。
|
|
||||||
* @param {string} id - weekly、first、second、third
|
|
||||||
* @returns {Array}
|
|
||||||
*/
|
|
||||||
function slipKeys(id) {
|
|
||||||
const watch = keys.filter((key) => yearCount(key) >= 3);
|
|
||||||
if (id === 'weekly') return watch.sort((a, b) => yearCount(b) - yearCount(a));
|
|
||||||
return watch.filter((key) => upgradeTier(key) === id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 画出五个岗位和右侧这封信。每个岗位只出现一次,改称呼只改预览。
|
|
||||||
*/
|
|
||||||
function renderPeople() {
|
|
||||||
$('slipBands').innerHTML = ROLE_FIELDS.map(([role, label]) => {
|
|
||||||
const options = NAME_OPTIONS.map((name) => (
|
|
||||||
'<option' + (people[role] === name ? ' selected' : '') + '>' + name + '</option>'
|
|
||||||
)).join('');
|
|
||||||
return '<div class="prow"><div><b>' + label + '</b><span>' + ROLE_DUTY[role] + '</span></div><select data-role="' + role + '" aria-label="' + label + '">' + options + '</select></div>';
|
|
||||||
}).join('');
|
|
||||||
$('slipBands').querySelectorAll('select').forEach((select) => {
|
|
||||||
select.onchange = () => {
|
|
||||||
people[select.dataset.role] = select.value;
|
|
||||||
renderPeople();
|
|
||||||
renderDash();
|
|
||||||
renderMail();
|
|
||||||
};
|
|
||||||
});
|
|
||||||
$('slipPicks').innerHTML = SLIPS.map((slip) => (
|
|
||||||
'<button type="button" data-slip="' + slip.id + '"' + (slip.id === slipId ? ' class="active"' : '') + '>' + slip.title + '</button>'
|
|
||||||
)).join('');
|
|
||||||
$('slipPicks').querySelectorAll('button').forEach((button) => {
|
|
||||||
button.onclick = () => { slipId = button.dataset.slip; renderPeople(); };
|
|
||||||
});
|
|
||||||
const slip = SLIPS.find((item) => item.id === slipId);
|
|
||||||
const rows = slipKeys(slip.id);
|
|
||||||
const to = slip.to.map(personName).join('、');
|
|
||||||
const cc = slip.cc.length ? slip.cc.map(personName).join('、') : '无';
|
|
||||||
const list = rows.map((key) => (
|
|
||||||
'<li>' + key.part + ' · ' + key.defect + ' · 近一年 ' + yearCount(key) + ' · 当月 ' + monthCount(key) + '</li>'
|
|
||||||
)).join('') || '<li>本周这封没有料号。</li>';
|
|
||||||
$('slipMeta').textContent = '2026-10-23 18:00 · OA 邮件 · ' + rows.length + ' 个料号';
|
|
||||||
$('slipLetter').innerHTML = '<div class="kv"><b>主送</b><span>' + to + '</span><b>抄送</b><span>' + cc + '</span></div><ul class="parts">' + list + '</ul>';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 短暂提示称呼已用于预览。
|
|
||||||
* @param {string} text - 提示文案
|
|
||||||
*/
|
|
||||||
function toast(text) {
|
|
||||||
const node = $('toast');
|
|
||||||
node.textContent = text;
|
|
||||||
node.classList.add('show');
|
|
||||||
setTimeout(() => node.classList.remove('show'), 1600);
|
|
||||||
}
|
|
||||||
|
|
||||||
document.querySelectorAll('.tabs button').forEach((button) => {
|
|
||||||
button.onclick = () => show(button.dataset.v);
|
|
||||||
});
|
|
||||||
$('savePeople').onclick = () => toast('预览称呼已更新,未写入正式配置');
|
|
||||||
|
|
||||||
renderDash();
|
|
||||||
renderList();
|
|
||||||
renderMail();
|
|
||||||
renderPeople();
|
|
||||||
const openView = new URLSearchParams(location.search).get('view') || (location.hash || '').replace('#', '');
|
|
||||||
if (['dash', 'list', 'mail', 'people'].includes(openView)) show(openView);
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
+8
-28
@@ -21,7 +21,7 @@
|
|||||||
| 功能项 | 状态 | 说明 |
|
| 功能项 | 状态 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 权限组表与种子 | 已实现 | `permission_roles` / `permission_role_agents`;标准包为普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员。不再种子设备维保专员。未种子时测试夹具仍走按人授权。 |
|
| 权限组表与种子 | 已实现 | `permission_roles` / `permission_role_agents`;标准包为普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员。不再种子设备维保专员。未种子时测试夹具仍走按人授权。 |
|
||||||
| 角色包即授权 | 已实现 | 用户可同时挂多个业务角色,生效权限取并集;拿掉最后一个业务角色回到默认组。平台管理员不与其他角色叠加。保存角色立即重算该组成员应用入口。`is_platform_admin` 权限组隐式全开应用入口。 |
|
| 角色包即授权 | 已实现 | 用户只选一个角色;保存角色立即同步该组成员应用入口;功能权限改由角色包计算。`is_platform_admin` 权限组隐式全开应用入口。 |
|
||||||
| 管理端角色配置 | 已实现 | `/admin/permissions` 以角色列表为主:编辑时应用卡片内嵌功能权限短标签;点人数打开公共选人弹窗,确定后确认增减才写库。矩阵只读核对。 |
|
| 管理端角色配置 | 已实现 | `/admin/permissions` 以角色列表为主:编辑时应用卡片内嵌功能权限短标签;点人数打开公共选人弹窗,确定后确认增减才写库。矩阵只读核对。 |
|
||||||
| 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 |
|
| 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 |
|
||||||
| 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 |
|
| 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 |
|
||||||
@@ -34,32 +34,23 @@
|
|||||||
| OA 合同与请款同步 | 已实现 | 合同申请单走 HTTP 待办/已办;验收归档查 OA SQL(`formtable_main_324.cgdh` × `workflow_requestbase.currentnodetype=3`)按采购单号落事件;普通同步只补空字段,管理员可强制覆盖 OA 非空字段并保留变更审计。 |
|
| OA 合同与请款同步 | 已实现 | 合同申请单走 HTTP 待办/已办;验收归档查 OA SQL(`formtable_main_324.cgdh` × `workflow_requestbase.currentnodetype=3`)按采购单号落事件;普通同步只补空字段,管理员可强制覆盖 OA 非空字段并保留变更审计。 |
|
||||||
| 四阶段三轮预警扫描 | 已实现 | 每日扫描只生成 pending 预警;第一轮按台账申请人真实姓名匹配系统用户,第二、三轮按申请人部门查 OA `HrmResource` + `Matrixtable_3`(`zz`/`jfl` 即企微 userid)。 |
|
| 四阶段三轮预警扫描 | 已实现 | 每日扫描只生成 pending 预警;第一轮按台账申请人真实姓名匹配系统用户,第二、三轮按申请人部门查 OA `HrmResource` + `Matrixtable_3`(`zz`/`jfl` 即企微 userid)。 |
|
||||||
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;“周汇总批次”保留批次审计,发送失败可点击图标查看原因。 |
|
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;“周汇总批次”保留批次审计,发送失败可点击图标查看原因。 |
|
||||||
| 合同付款台账与详情 | 已实现 | 预付款和出货款按 OA「公司」选择账套查询(默认 HXJM,无锡和宏智散热科技有限公司为 WZHHZ,和泰科技(吴江)有限公司为 HTT)。未付的四个阶段都可手动标为已付。Chat Agent「合同付款预警」以 Tab 展示合同台账:服务端分页展示采购单号、供应商、四阶段列、申请人和简洁状态标签,列表不展示合同号和合同申请单流程编号。阶段列只显示阶段名;预付款和出货款以已付(付款日)或已逾期、即将到期、未到期区分;金额和比例都为 0 的阶段不标已逾期,也不参与汇总。四个阶段都按 ERP `apa_file`(`apa00=15`、`apa41=Y`、`apa63=1`,按 `apa34f` 对金额)标已付,也可以手动标为已付。对上或手动标记后不再显示已逾期。有应付金额且 ERP 未对上时,日期已过、7日内或更远仍显示已逾期、即将到期、未到期。日期依据缺失时按阶段写明原因:合同归档日未填、交货日期未填、验收单未归档、质保到期日未定;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;四张汇总卡按合同统计即将到期(7日内)、逾期未付、未到期(7日外)、本月应付(全量台账),点击过滤列表;点击合同在当前 Tab 内查看概览、原文附件、付款计划和预警记录。 |
|
| 合同付款台账与详情 | 已实现 | 预付款和出货款按 OA「公司」选择账套查询(默认 HXJM,无锡和宏智散热科技有限公司为 WZHHZ,和泰科技(吴江)有限公司为 HTT)。未付的预付款、出货款可手动标为已付。Chat Agent「合同付款预警」以 Tab 展示合同台账:服务端分页展示合同、采购单号、供应商、四阶段列、申请人和简洁状态标签,列表不展示合同申请单流程编号。阶段列只显示阶段名;预付款和出货款以已付(付款日)或已逾期、即将到期、未到期区分;验收款和质保款不能标已付,但日期已过、7日内或更远时同样显示已逾期、即将到期、未到期。日期依据缺失时按阶段写明原因:合同归档日未填、交货日期未填、验收单未归档、质保到期日未定;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;四张汇总卡按合同统计即将到期(7日内)、逾期未付、未到期(7日外)、本月应付(全量台账),点击过滤列表;点击合同在当前 Tab 内查看概览、原文附件、付款计划和预警记录。 |
|
||||||
| 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入 Chat「待确认」Tab,不得触发自动预警。待确认合同可人工复核:补齐采购单号、合同金额和四阶段比例、金额、日期依据,启用阶段合计 100% 后进入合同台账;勾选无此阶段的节点不参与预警。 |
|
| 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入 Chat「待确认」Tab,不得触发自动预警。待确认合同可人工复核:补齐采购单号、合同金额和四阶段比例、金额、日期依据,启用阶段合计 100% 后进入合同台账;勾选无此阶段的节点不参与预警。 |
|
||||||
| 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 |
|
| 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 |
|
||||||
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不覆盖 OA 字段。原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析。 |
|
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不覆盖 OA 字段。原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析。 |
|
||||||
| 合同付款 Agent 授权 | 已实现 | 入口为 Chat builtin Agent `contract_payment`:平台管理员默认可访问;权限组启用后把该 Agent 勾到角色包即可,不再按人授权。旧功能权限 `contract_payment.access` 由迁移写入 Agent 授权后删除。无授权直链提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
| 合同付款 Agent 授权 | 已实现 | 入口为 Chat builtin Agent `contract_payment`:平台管理员默认可访问;权限组启用后把该 Agent 勾到角色包即可,不再按人授权。旧功能权限 `contract_payment.access` 由迁移写入 Agent 授权后删除。无授权直链提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||||
| OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 |
|
| OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 |
|
||||||
|
|
||||||
## 制程品质异常预警
|
|
||||||
|
|
||||||
| 功能项 | 状态 | 说明 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 滚动统计与升级规则 | 规划中 | 料号 + 不良类别,申请日期计次。近一年为扫描日减 1 年至前 1 天,≥ 3 才预警;当月按自然月计含当天。周报给品质担当,当月第 1/2/≥3 笔分别升级到品质+生产经副理、COO、老板(抄送 COO、品质、生产经副理)。废弃和撤销不计入。权威:[features/process-quality-alert/demand.md](features/process-quality-alert/demand.md)。 |
|
|
||||||
| OA 接入与 OA 邮件 | 未开始 | 流程表、字段和发信方式留设计文档。需求只定渠道是 OA 邮件。 |
|
|
||||||
| 收件人与待确认口径 | 待确认 | 五个岗位界面配置、不写死姓名。一单多行是否按行计次、空不良类别是否排除、具体人员尚未确认。 |
|
|
||||||
|
|
||||||
## 设备验收预警
|
## 设备验收预警
|
||||||
|
|
||||||
| 功能项 | 状态 | 说明 |
|
| 功能项 | 状态 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。未归档且已开始计时的单据,可以验收为是或未标明都监控,明确为否才不监控。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
||||||
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 与 E8 未归档验收单、流程状态、当前节点和操作人。不抓归档(E10 `flowstatus = 3`,E8 `currentnodetype = 3`)。按 `sfkyzcys`、`sfzfth`、`flowstatus` 4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。本次结果里没有的本地单删除,并取消未发送预警。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
|
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
|
||||||
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。只列出未归档单据,并展示流程编号、标题和创建时间。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
||||||
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:30(错开合同付款 18:00)。 |
|
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 |
|
||||||
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员「扫描预警 / 发送预警」入队由 schedule worker 执行(避免 HTTP 504),页面轮询 Job 后再刷新结果。 |
|
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
|
||||||
| 四档企业微信升级 | 已按使用部门担当 | 超过 30/37/44/51 天各发一次。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人。E8 与 E10 相同。采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:30 同步并生成待发送,每周五 18:30 按收件人发送一条汇总卡片和一份 Excel 明细(错开合同付款 06:00 / 18:00)。停表取消未发送。已发送不撤回、不重发。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||||
| E8 补抓 | 已接上查询 | 读取 `ecology` 上的验收单,与 E10 分来源保存。计时起点 `syddjssj`。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
|
||||||
|
|
||||||
## 知识库同步状态校验
|
## 知识库同步状态校验
|
||||||
|
|
||||||
@@ -103,16 +94,6 @@
|
|||||||
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
||||||
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
||||||
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
||||||
| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 |
|
|
||||||
|
|
||||||
## 知识库内容清单按钮(2026-10)
|
|
||||||
|
|
||||||
| 功能项 | 状态 | 说明 |
|
|
||||||
| ---------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
||||||
| 兜底回复触发识别 | 已实现 | Dify 知识库未命中兜底回复末尾追加 `[知识库能力清单]` 标记(兼容「内容清单」写法)时,前端识别并在语句结尾渲染【知识库内容清单】按钮;对无标记的已发布兜底原句按特征片段兜底识别,历史会话同样生效 |
|
|
||||||
| 标记展示剥离 | 已实现 | 渲染前从正文剥离标记及其前导标点(含流式半截标记裁剪),用户不会看到原始标记符号 |
|
|
||||||
| 能力清单标准答案查询 | 已实现 | `GET /api/chat/capability-list?agent_id=`(`require_agent_permission` 鉴权)返回常用问题中该应用「能力清单条目」(标题含「能力清单」的全局条目)的标准答案;未配置返回 `CHAT.CAPABILITY_LIST_NOT_FOUND` |
|
|
||||||
| 内容清单弹窗 | 已实现 | 点击按钮后按当前会话应用拉取标准答案并弹窗展示(Markdown 渲染);未配置时按错误码本地化提示,文案同步 zh-CN/zh-TW/en/th |
|
|
||||||
|
|
||||||
## 年度教育训练计划
|
## 年度教育训练计划
|
||||||
|
|
||||||
@@ -692,7 +673,6 @@
|
|||||||
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
|
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
|
||||||
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
|
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
|
||||||
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
|
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
|
||||||
| 管理端部门管理(组织树) | 部门管理改为树形组织结构(对应 OA 组织架构,层级来源对齐 ERP HRAO:hrao01 编码 / hrao02 名称 / hrao06 上级 / hrao09 同级排序 / hrao08 隐藏标记):`departments` 表增加 `parent_id`(邻接表)/ `sort_order` / `is_hidden`(迁移 `dp1a2b3c4d5e6`),`name` 全局唯一放开为「同一上级下唯一」;页面为左树右成员面板(OA 组织结构口径,控件已按 Element Plus 迁移规范 Element 化:ElTable/ElPagination/ElTag/ElDialog/ElMessageBox,树行为自定义层级结构),树顶公司层为前端按 `company` 字段虚拟分组不入库;节点支持添加子部门/编辑/删除(有下级或有员工禁删)、搜索命中自动展开、全部展开/收起;员工展示改为 OA 组织结构口径(左树右成员面板):树表员工计数列剔除,点击部门节点右侧分页展示成员名单(关键词搜索姓名/工号/邮箱/手机、每页 20/50/100 可调,「含下级部门」口径可切换,成员接口 `members` 支持 keyword/page/page_size);新增错误码 `DEPT.*` 四语言。ERP 一次性导入脚本已提供(`backend/scripts/import_departments_from_hrao.py`:DBeaver 导出 HRAO_FILE CSV + 公司映射取自 HRAA_FILE,dry-run 默认、`--apply` 按编码 upsert 合并、悬空/成环/重名告警兜底),已于 2026-10-08 执行首次全量导入(366 部门 / 7 公司,本地 56 行全部按编码命中更新);持续同步仍未做 | 已实现 | P1 |
|
|
||||||
| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
|
| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
## 怎么判权
|
## 怎么判权
|
||||||
|
|
||||||
一个人可以同时挂多个业务角色。生效权限是这些角色的并集:能进的应用合在一起,任一角色打开的应用内能力都生效。平台管理员不与其他角色叠加,应用入口默认全开,也能进管理后台。拿掉最后一个业务角色后回到默认角色。部门不授权。`users.role` 只保存排序最前的主角色,成员关系在 `user_permission_roles`。
|
一个人只绑一个角色。角色包决定能进哪些应用,以及进了应用之后能做哪些事。平台管理员是特例:应用入口默认全开,也能进管理后台。部门不授权。
|
||||||
|
|
||||||
登录后后端下发三样东西,前端路由守卫和后端接口用同一份结果:
|
登录后后端下发三样东西,前端路由守卫和后端接口用同一份结果:
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
| 层 | 存在哪 | 运行时怎么用 |
|
| 层 | 存在哪 | 运行时怎么用 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 角色包 | `user_permission_roles` 挂到 `permission_roles`;`users.role` 是主角色 | 每人可多个业务角色。改其中一个角色的勾选,会按该人全部角色的并集重算应用授权 |
|
| 角色包 | `users.role` 指向 `permission_roles.code` | 每人一个。改角色,或改该角色的勾选,会立刻重写这个人的应用授权 |
|
||||||
| 应用入口 | `permission_role_agents`,同步到 `user_agent_permissions` | 聊天和工作台按「有没有这个 Agent」放行。平台管理员不写授权行,入口隐式全开 |
|
| 应用入口 | `permission_role_agents`,同步到 `user_agent_permissions` | 聊天和工作台按「有没有这个 Agent」放行。平台管理员不写授权行,入口隐式全开 |
|
||||||
| 应用内能力 | 角色包上的 `feature_permissions` | 已经进了应用之后,再卡统计、强制新建、台账维护这类动作 |
|
| 应用内能力 | 角色包上的 `feature_permissions` | 已经进了应用之后,再卡统计、强制新建、台账维护这类动作 |
|
||||||
|
|
||||||
|
|||||||
@@ -1,597 +0,0 @@
|
|||||||
# 意见反馈截图附件 Implementation Plan
|
|
||||||
|
|
||||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
||||||
|
|
||||||
**Goal:** 意见反馈弹窗支持粘贴/选图上传截图(整页换 Element Plus),图片随反馈入库,管理端报表可看缩略图与大图,企微通知加「附图:N 张」文字行。
|
|
||||||
|
|
||||||
**Architecture:** 复用平台文件资产设施(`POST /api/files/assets` → MinIO + 72h 孤儿清理)。用户选图后立即上传,提交时 JSON 携带 `image_asset_nos[]`,后端建子表 `general_feedback_images` 关联并调 `mark_asset_referenced` 防清理。管理端图片由后端 raw 接口代理输出(不走 MinIO 预签名 URL,原因见 spec D6),前端 `requestBlob` 取 blob 展示。
|
|
||||||
|
|
||||||
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;Vue 3 + TS + Element Plus 2.14.7;MinIO。
|
|
||||||
|
|
||||||
**Spec:** `docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md`(执行者必须同时阅读,数值与决策以 spec 为准)
|
|
||||||
|
|
||||||
## Global Constraints
|
|
||||||
|
|
||||||
- 每条反馈最多 **5** 张图,单张 **10MB**,格式仅 png/jpg/jpeg/webp;客户端与服务端双重校验(spec D4)。
|
|
||||||
- 仅允许挂载 `reference_count == 0` 且 `lifecycle_status == 'temporary'` 的资产(spec D9)。
|
|
||||||
- `POST /api/user/feedback` 响应契约不变:`{'status':'ok','id':<int>}`(spec D8)。
|
|
||||||
- 新增错误码 `FEEDBACK.IMAGE_INVALID` / `FEEDBACK.IMAGE_TOO_MANY` / `FEEDBACK.IMAGE_NOT_FOUND` 必须同步四语言 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`(键名为下划线风格,如 `FEEDBACK_IMAGE_INVALID`)。
|
|
||||||
- 所有新增文案四语言齐备,禁止硬编码中文。
|
|
||||||
- 反馈弹窗整页 Element Plus,禁止再出现 `btn-*`/`input-field`/`select-field`/手写 `<button>`/`<select>`/`<textarea>`(管理端 ReportsPage 例外:只加展示型 `<img>` 与 overlay,不新增表单控件)。
|
|
||||||
- 不新增任何第三方依赖。
|
|
||||||
- 新文件顶部按 AGENTS.md §5 写文件层块注释;新增/调整的核心函数带 docstring/JSDoc。
|
|
||||||
- 提交信息符合 Conventional Commits:`type(scope): 中文祈使句`(scope 英文 kebab)。
|
|
||||||
|
|
||||||
## Review Focus
|
|
||||||
|
|
||||||
spec 隐含但任务测试未覆盖、最容易咬人的五类输入(人工验证时重点看):
|
|
||||||
|
|
||||||
1. **粘贴内容同时含文本与图片**(聊天工具复制):只有图片项成为附件,文本粘贴进输入框的行为不得被破坏 → Task 5 的 `onPaste` 只在有 image item 时 `preventDefault`;人工验证。
|
|
||||||
2. **同一张图被并发/重复提交到两条反馈**:应被拒(`FEEDBACK.IMAGE_INVALID`),不能 500 → Task 2 的 commit 包 `IntegrityError` 兜底;测试 `test_submit_rejects_referenced_asset` 钉串行路径。
|
|
||||||
3. **报表页满屏 5 图大图**(慢网络):无图行零图片请求,缩略图 `loading="lazy"` → Task 6 人工验证 Network 面板。
|
|
||||||
4. **历史无图反馈**:images 列显示 `-`,排序/筛选/导出不受影响 → Task 4 测试 `test_report_rows_include_images` 含无图行断言。
|
|
||||||
5. **一次粘贴超过 5 张**:整批拒绝并提示 `feedback.upload.maxCount`,不得静默截取前 5 张 → Task 5 `addImages` 的行为钉死;人工验证。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 1: 数据模型与迁移
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `backend/app/models/chat.py`(在 `GeneralFeedback` 类之后追加)
|
|
||||||
- Modify: `backend/app/models/__init__.py:13`(import 行)与 `__all__` 中 `'GeneralFeedback'` 旁
|
|
||||||
- Create: `backend/migrations/versions/<rev>_add_general_feedback_images.py`(由 flask db migrate 生成)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Produces: 模型 `GeneralFeedbackImage`(表 `general_feedback_images`),字段:`id`(PK)、`feedback_id`(FK `general_feedbacks.id`,NOT NULL,index)、`asset_id`(FK `file_assets.id`,NOT NULL,**unique**)、`sort_order`(Integer,NOT NULL,default 0)、`created_at`(DateTime,default `datetime.utcnow`)。`GeneralFeedback` 上新增 `images: Mapped[list['GeneralFeedbackImage']] = relationship(order_by='GeneralFeedbackImage.sort_order', cascade='all, delete-orphan')`。后续所有任务经 `from app.models import GeneralFeedbackImage` 引用。
|
|
||||||
|
|
||||||
- [ ] **Step 1: 在 `backend/app/models/chat.py` 追加模型**
|
|
||||||
|
|
||||||
```python
|
|
||||||
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)
|
|
||||||
```
|
|
||||||
|
|
||||||
并在 `GeneralFeedback` 类体内加 `images` relationship(如上 Interfaces 所示,含注释说明级联随反馈删除)。
|
|
||||||
|
|
||||||
- [ ] **Step 2: 在 `backend/app/models/__init__.py` 注册导出**
|
|
||||||
|
|
||||||
第 13 行 import 加入 `GeneralFeedbackImage`;`__all__` 列表在 `'GeneralFeedback'` 后加 `'GeneralFeedbackImage'`。
|
|
||||||
|
|
||||||
- [ ] **Step 3: 生成迁移**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd backend && source venv/bin/activate # Windows Git Bash: source venv/Scripts/activate
|
|
||||||
flask db migrate -m "add general_feedback_images table"
|
|
||||||
```
|
|
||||||
|
|
||||||
检查生成的文件:`down_revision` 必须为 `'mh23e4f5a6b7'`(当前单 head),upgrade 只含 `create_table('general_feedback_images', ...)`(id/feedback_id/asset_id/sort_order/created_at + 索引 + unique 约束),无其他意外变更。若本地无可用数据库连接,则手写迁移文件(仿 `backend/migrations/versions/dq2e3f4g5h6i_add_per_source_inventory_rpa_attempts.py` 的结构,`revision` 用新随机 12 位 id)。
|
|
||||||
|
|
||||||
- [ ] **Step 4: 验证迁移链与模型可导入**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
flask db heads # 期望:仅一个 head,即新 revision
|
|
||||||
python -c "from app.models import GeneralFeedbackImage; print(GeneralFeedbackImage.__tablename__)"
|
|
||||||
```
|
|
||||||
|
|
||||||
Expected: 单 head;打印 `general_feedback_images`。
|
|
||||||
|
|
||||||
- [ ] **Step 5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add backend/app/models/chat.py backend/app/models/__init__.py backend/migrations/versions/
|
|
||||||
git commit -m "feat(feedback): 新增反馈图片关联表与模型"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 2: 提交接口携带图片资产(后端)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `backend/app/api/user/handlers.py:122-176`(`submit_general_feedback`)
|
|
||||||
- Test: `backend/tests/api/test_general_feedback_api.py`(新建)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Consumes: Task 1 的 `GeneralFeedbackImage`;现有 `get_asset_for_user(asset_no: str, user_id: int) -> FileAsset`(`app/services/file_assets/service.py:119`,NotFoundError/ForbiddenError)、`mark_asset_referenced(asset: FileAsset) -> None`(`service.py:430`)。
|
|
||||||
- Produces: `POST /api/user/feedback` 请求体新增可选 `image_asset_nos: string[]`(顺序即 sort_order)。校验失败抛 `ValidationError(code='FEEDBACK.IMAGE_TOO_MANY'|'FEEDBACK.IMAGE_INVALID', message=...)` / 沿用 `get_asset_for_user` 的 `FILE_ASSET.*` 异常。
|
|
||||||
|
|
||||||
- [ ] **Step 1: 写失败测试**
|
|
||||||
|
|
||||||
新建 `backend/tests/api/test_general_feedback_api.py`。文件头块注释说明用途/依赖/逻辑(AGENTS.md §5.1)。复用全局 `app`/`client` 夹具(`backend/tests/conftest.py:562,692`,`create_app('testing')` + `create_all`)。鉴权仿 `backend/tests/api/test_transfer_type_api.py:60-77`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
from app.core.auth.jwt import issue_local_access_token
|
|
||||||
|
|
||||||
def _headers(user: User) -> dict:
|
|
||||||
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
|
|
||||||
token = issue_local_access_token(user)
|
|
||||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def user_headers(app):
|
|
||||||
"""普通用户 JWT 请求头。"""
|
|
||||||
with app.app_context():
|
|
||||||
user = db.session.query(User).filter_by(username="fbuser").first()
|
|
||||||
if not user:
|
|
||||||
user = User(username="fbuser", email="fbuser@example.com", role="user", status="active")
|
|
||||||
user.set_password("x")
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
return _headers(user)
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def admin_headers(app):
|
|
||||||
"""平台管理员 JWT 请求头。"""
|
|
||||||
with app.app_context():
|
|
||||||
user = db.session.query(User).filter_by(username="fbadmin").first()
|
|
||||||
if not user:
|
|
||||||
user = User(username="fbadmin", email="fbadmin@example.com", role="admin", status="active")
|
|
||||||
user.set_password("x")
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
return _headers(user)
|
|
||||||
|
|
||||||
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
|
|
||||||
```
|
|
||||||
|
|
||||||
测试用例(本任务实现前 6 个;断言错误码用 `tests/conftest.py` 的 `parse_api_error`):
|
|
||||||
|
|
||||||
```python
|
|
||||||
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")
|
|
||||||
resp = client.post("/api/user/feedback", headers=user_headers, json={
|
|
||||||
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图",
|
|
||||||
"source_page": "workspace", "image_asset_nos": [a1.asset_no, a2.asset_no],
|
|
||||||
})
|
|
||||||
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,反馈不落库。"""
|
|
||||||
def test_submit_rejects_non_image(app, client, user_headers):
|
|
||||||
"""ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。"""
|
|
||||||
def test_submit_rejects_referenced_asset(app, client, user_headers):
|
|
||||||
"""reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。"""
|
|
||||||
def test_submit_rejects_too_many(app, client, user_headers):
|
|
||||||
"""6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。"""
|
|
||||||
def test_submit_text_only_keeps_legacy(app, client, user_headers):
|
|
||||||
"""不带 image_asset_nos:200,general_feedback_images 零行(回归)。"""
|
|
||||||
```
|
|
||||||
|
|
||||||
省略体断言:非 2xx 时用 `parse_api_error(resp.get_json())["code"]` 断错误码,并断 `GeneralFeedbackImage.query.count() == 0`(拒绝路径不落任何行)。
|
|
||||||
|
|
||||||
- [ ] **Step 2: 运行确认失败**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd backend && python -m pytest tests/api/test_general_feedback_api.py -v
|
|
||||||
```
|
|
||||||
|
|
||||||
Expected: FAIL/ERROR(接口忽略 `image_asset_nos`,断言 0 行失败)。
|
|
||||||
|
|
||||||
- [ ] **Step 3: 实现接口逻辑**
|
|
||||||
|
|
||||||
`handlers.py` 顶部模块常量与 import:
|
|
||||||
|
|
||||||
```python
|
|
||||||
_FEEDBACK_MAX_IMAGES = 5
|
|
||||||
_FEEDBACK_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
|
||||||
```
|
|
||||||
|
|
||||||
import 增加 `GeneralFeedbackImage`(第 12 行 models import)与 `from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced`。
|
|
||||||
|
|
||||||
`submit_general_feedback` 中,在现有 chat_log 校验之后、`row = GeneralFeedback(...)` 之前插入 `[STEP]` 注释分块(AGENTS.md §5.3):
|
|
||||||
|
|
||||||
1. 解析:`raw = data.get('image_asset_nos')`;非 list → `ValidationError(code='FEEDBACK.IMAGE_INVALID', message='image_asset_nos must be a list')`;元素转 str 去空白、去重(保序);`len > _FEEDBACK_MAX_IMAGES` → `ValidationError(code='FEEDBACK.IMAGE_TOO_MANY', message='最多附加 5 张图片')`。
|
|
||||||
2. 逐个校验(任一失败整单拒绝):`asset = get_asset_for_user(asset_no, user.id)`;`asset.extension not in _FEEDBACK_IMAGE_EXTENSIONS` → FEEDBACK.IMAGE_INVALID(message 注明仅支持图片);`asset.upload_status != 'ready'` → FEEDBACK.IMAGE_INVALID;`asset.reference_count != 0 or asset.lifecycle_status != 'temporary'` → FEEDBACK.IMAGE_INVALID(message 注明该文件已被使用)。通过者收集为 `assets: list[FileAsset]`。
|
|
||||||
3. 落库:`db.session.add(row)` → `db.session.flush()` 拿 `row.id` → 按枚举序 `GeneralFeedbackImage(feedback_id=row.id, asset_id=a.id, sort_order=idx)` → 逐个 `mark_asset_referenced(a)` → `try: db.session.commit() except IntegrityError: db.session.rollback(); raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片已被使用,请重新添加')`(并发双挂兜底,Review Focus 2;IntegrityError 已在文件头 import)。
|
|
||||||
4. 通知与返回不变(`send_feedback_group_notification(row, user)` 之后,`jsonify({'status': 'ok', 'id': row.id})`)。
|
|
||||||
|
|
||||||
- [ ] **Step 4: 同步错误码四语言**
|
|
||||||
|
|
||||||
`frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` 的 codes 段(搜 `FILE_ASSET_INVALID_TYPE` 所在对象,同层追加):
|
|
||||||
|
|
||||||
- zh-CN:`"FEEDBACK_IMAGE_INVALID": "反馈图片无效或已被使用。"`,`"FEEDBACK_IMAGE_TOO_MANY": "反馈图片数量超过上限。"`,`"FEEDBACK_IMAGE_NOT_FOUND": "反馈图片不存在。"`
|
|
||||||
- zh-TW:`"FEEDBACK_IMAGE_INVALID": "迴饋圖片無效或已被使用。"`,`"FEEDBACK_IMAGE_TOO_MANY": "迴饋圖片數量超過上限。"`,`"FEEDBACK_IMAGE_NOT_FOUND": "迴饋圖片不存在。"`
|
|
||||||
- en:`"FEEDBACK_IMAGE_INVALID": "The feedback image is invalid or already in use."`,`"FEEDBACK_IMAGE_TOO_MANY": "Too many feedback images."`,`"FEEDBACK_IMAGE_NOT_FOUND": "Feedback image not found."`
|
|
||||||
- th:`"FEEDBACK_IMAGE_INVALID": "รูปภาพข้อเสนอแนะไม่ถูกต้องหรือถูกใช้งานแล้ว"`,`"FEEDBACK_IMAGE_TOO_MANY": "จำนวนรูปภาพข้อเสนอแนะเกินกำหนด"`,`"FEEDBACK_IMAGE_NOT_FOUND": "ไม่พบรูปภาพข้อเสนอแนะ"`
|
|
||||||
|
|
||||||
- [ ] **Step 5: 运行测试确认通过**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python -m pytest tests/api/test_general_feedback_api.py -v
|
|
||||||
```
|
|
||||||
|
|
||||||
Expected: 6 个用例全 PASS。
|
|
||||||
|
|
||||||
- [ ] **Step 6: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add backend/app/api/user/handlers.py backend/tests/api/test_general_feedback_api.py frontend/src/locales/
|
|
||||||
git commit -m "feat(feedback): 提交接口支持携带图片资产并校验引用"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 3: 企微通知附图行(后端)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `backend/app/services/feedback_notify.py`(`build_feedback_markdown`,93-135 行)
|
|
||||||
- Test: `backend/tests/services/test_feedback_notify.py`(新建)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Consumes: Task 1 的 `GeneralFeedback.images` relationship。
|
|
||||||
- Produces: markdown 在「反馈内容」段之前多一行 `>附图:{N} 张`(仅当 N>0)。消息其余行与顺序不变。
|
|
||||||
|
|
||||||
- [ ] **Step 1: 写失败测试**
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_markdown_includes_image_count(app):
|
|
||||||
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
|
||||||
# app context 内建 GeneralFeedback + 2 条 GeneralFeedbackImage(feedback_id 指向它),commit;
|
|
||||||
# md = build_feedback_markdown(fb, None)
|
|
||||||
# assert "附图:2 张" in md;再建一条无图反馈断 "附图" not in 其 md
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: 运行确认失败**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python -m pytest tests/services/test_feedback_notify.py -v # Expected: FAIL(无附图行)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: 实现**
|
|
||||||
|
|
||||||
`build_feedback_markdown` 中 `lines.extend(['', '**反馈内容:**', content or '-'])` 之前插入:
|
|
||||||
|
|
||||||
```python
|
|
||||||
image_count = len(feedback.images or [])
|
|
||||||
if image_count:
|
|
||||||
lines.append(f'>附图:{image_count} 张')
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: 运行确认通过** 同 Step 2 命令,Expected: PASS。
|
|
||||||
|
|
||||||
- [ ] **Step 5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add backend/app/services/feedback_notify.py backend/tests/services/test_feedback_notify.py
|
|
||||||
git commit -m "feat(feedback): 企微反馈通知增加附图数量行"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 4: 报表行附图元数据 + 管理端图片代理接口(后端)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `backend/app/services/admin/report_service.py:560-589`(`list_general_feedbacks_report`)与文件内新增函数
|
|
||||||
- Modify: `backend/app/api/admin/reports.py`(追加路由)
|
|
||||||
- Test: `backend/tests/api/test_general_feedback_api.py`(追加用例)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Consumes: Task 1 模型;现有 `read_asset_bytes(asset: FileAsset) -> bytes`(`service.py:623`,校验未删除/未过期)。
|
|
||||||
- Produces:
|
|
||||||
- `list_general_feedbacks_report` 每行新增 `images: list[dict]`,元素键恰为 `image_id, asset_no, original_filename, file_size, sort_order`(int/str/str/int/int),按 sort_order 升序;无图行 `images == []`。
|
|
||||||
- `report_service.get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict`,返回 `{'data': bytes, 'mime_type': str, 'filename': str}`;image 不存在或不属于该 feedback → `NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')`。
|
|
||||||
- 路由 `GET /api/admin/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw`,`@require_admin`,响应为图片字节流:`Content-Type` = mime,`Content-Disposition: inline; filename*=UTF-8''<quote(filename)>`(`urllib.parse.quote`)。
|
|
||||||
|
|
||||||
- [ ] **Step 1: 写失败测试**(追加到 `test_general_feedback_api.py`)
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_report_rows_include_images(app, client, user_headers, admin_headers):
|
|
||||||
"""报表行含 images 元数据;无图行 images==[]。"""
|
|
||||||
# user 提交一条带 a1 的反馈 + 一条纯文本反馈;
|
|
||||||
# admin GET /api/admin/reports/general-feedbacks → 找到两行:
|
|
||||||
# 有图行 images[0] 键集合 == {"image_id","asset_no","original_filename","file_size","sort_order"} 且 asset_no==a1.asset_no;
|
|
||||||
# 无图行 images == []
|
|
||||||
|
|
||||||
def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch):
|
|
||||||
"""管理员经 raw 接口取到图片字节;错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。"""
|
|
||||||
# monkeypatch app.services.file_assets.service.file_asset_storage.get_bytes = lambda key: b"\x89PNG\r\n\x1a\nfake"
|
|
||||||
# 提交一条带图反馈后:GET .../<fb_id>/images/<image_id>/raw → 200,data 匹配,content_type 以 "image/png" 开头
|
|
||||||
# GET .../<fb_id + 99999>/images/<同一 image_id>/raw → 404,parse_api_error code == FEEDBACK.IMAGE_NOT_FOUND
|
|
||||||
# 同接口换 user_headers → 403
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2: 运行确认失败**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python -m pytest tests/api/test_general_feedback_api.py -v # Expected: 新用例 FAIL(无 images 键/404)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: 实现 service 与路由**
|
|
||||||
|
|
||||||
`report_service.py`:import `GeneralFeedbackImage` 与 `from app.models import FileAsset`、`from app.services.file_assets.service import read_asset_bytes`。`list_general_feedbacks_report` 行构建后批量补 images:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def _attach_general_feedback_images(rows: list[dict], feedback_ids: list[int]) -> None:
|
|
||||||
"""批量回填每行 images 元数据(单查询,按 sort_order 排序),无图行置空列表。"""
|
|
||||||
```
|
|
||||||
|
|
||||||
实现:单条 query `GeneralFeedbackImage` join `FileAsset`,`feedback_id.in_(feedback_ids)`,`order_by(sort_order, id)`,按 feedback_id 分组后写入各行。`list_general_feedbacks_report` 末尾调用它。
|
|
||||||
|
|
||||||
新增:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict:
|
|
||||||
"""读取反馈图片字节(管理端代理输出,不走 MinIO 预签名,见 spec D6)。"""
|
|
||||||
# GeneralFeedbackImage.filter_by(id=image_id, feedback_id=feedback_id).first() → 无则 FEEDBACK.IMAGE_NOT_FOUND
|
|
||||||
# asset = db.session.get(FileAsset, img.asset_id);asset 为 None 或 deleted_at 非空 → 同上
|
|
||||||
# data = read_asset_bytes(asset);返回 {'data': data, 'mime_type': asset.mime_type or 'application/octet-stream', 'filename': asset.original_filename}
|
|
||||||
```
|
|
||||||
|
|
||||||
`reports.py` 追加(import `Response`、`urllib.parse.quote`、`report_service` 已有):
|
|
||||||
|
|
||||||
```python
|
|
||||||
@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'])
|
|
||||||
resp.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(payload['filename'])}"
|
|
||||||
return resp
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: 运行确认通过**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python -m pytest tests/api/test_general_feedback_api.py -v # Expected: 全部 PASS
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add backend/app/services/admin/report_service.py backend/app/api/admin/reports.py backend/tests/api/test_general_feedback_api.py
|
|
||||||
git commit -m "feat(admin): 报表反馈行内附图元数据与图片代理接口"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 5: 反馈弹窗 Element Plus 化 + 粘贴/选图上传(前端)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Rewrite: `frontend/src/shared/components/GeneralFeedbackDialog.vue`
|
|
||||||
- Modify: `frontend/src/features/workspace/components/WorkspaceModals.vue`(移除 `:auth-headers` 绑定与未再使用的 `getAuthHeaders` import)
|
|
||||||
- Modify: `frontend/src/features/chat/components/ChatViewOverlays.vue`(同上)
|
|
||||||
- Modify: `frontend/src/features/workspace/pages/FeedbackPage.vue`(同上,若有绑定)
|
|
||||||
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/feedback.json`(新增 `upload` 段)
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Consumes: `uploadFileAsset(file: File): Promise<FileAssetResponse>`(`@/shared/api/file-assets.api.ts`,返回含 `asset_no`);`requestJson<T>(url, init)`(`@/shared/api/client`,自动附鉴权头,失败抛 `BusinessError`);现有 props `modelValue: boolean`、`sourcePage?: string`(默认 'unknown')、`chatLogId?: number | null`,emits `update:modelValue` / `submitted` **保持不变**(仅删除 `authHeaders`)。
|
|
||||||
- Produces: 提交 payload 新增 `image_asset_nos: string[]`(仅 `status==='ready'` 的图,按添加顺序)。i18n 键 `feedback.upload.*`。
|
|
||||||
|
|
||||||
- [ ] **Step 1: 四语言 `feedback.json` 增加 `upload` 段**
|
|
||||||
|
|
||||||
在 `submit` 键后追加(`zh-CN` 为准,其余三语言如下):
|
|
||||||
|
|
||||||
```json
|
|
||||||
"upload": {
|
|
||||||
"addImage": "添加图片",
|
|
||||||
"pasteHint": "支持粘贴截图(Ctrl+V)或点击添加,最多 5 张",
|
|
||||||
"maxCount": "最多添加 {count} 张图片",
|
|
||||||
"maxSize": "单张图片不能超过 {size}MB",
|
|
||||||
"invalidType": "仅支持 png / jpg / jpeg / webp 格式图片",
|
|
||||||
"uploadFailed": "图片上传失败,请重试",
|
|
||||||
"remove": "移除图片"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- zh-TW:`添加圖片` / `支援貼上截圖(Ctrl+V)或點擊新增,最多 5 張` / `最多新增 {count} 張圖片` / `單張圖片不能超過 {size}MB` / `僅支援 png / jpg / jpeg / webp 格式圖片` / `圖片上傳失敗,請重試` / `移除圖片`
|
|
||||||
- en:`Add images` / `Paste a screenshot (Ctrl+V) or click to add, up to 5` / `Up to {count} images` / `Each image must be within {size}MB` / `Only png / jpg / jpeg / webp images are supported` / `Image upload failed, please retry` / `Remove image`
|
|
||||||
- th:`เพิ่มรูปภาพ` / `วางภาพหน้าจอ (Ctrl+V) หรือคลิกเพื่อเพิ่ม สูงสุด 5 รูป` / `เพิ่มได้สูงสุด {count} รูป` / `รูปภาพเดียวต้องไม่เกิน {size}MB` / `รองรับเฉพาะไฟล์ png / jpg / jpeg / webp` / `อัปโหลดรูปภาพไม่สำเร็จ กรุณาลองอีกครั้ง` / `นำรูปภาพออก`
|
|
||||||
|
|
||||||
- [ ] **Step 2: 重写 `GeneralFeedbackDialog.vue`**
|
|
||||||
|
|
||||||
文件头块注释更新(用途/依赖:element-plus、file-assets.api、client/依赖关系)。要点:
|
|
||||||
|
|
||||||
- import 样式仿 `frontend/src/features/admin/modules/agents/AgentsPage.vue:14-23`:按需 `import { ElButton, ElDialog, ElInput, ElMessage, ElOption, ElSegmented, ElSelect } from 'element-plus'` + `import 'element-plus/dist/index.css'`(组件级导入,Vite 自动去重)。
|
|
||||||
- Props 删除 `authHeaders`;`visible = computed({ get: () => props.modelValue, set: (v) => emit('update:modelValue', v) })`。
|
|
||||||
- 模板:`<ElDialog v-model="visible" :title="t('feedback.title')" width="640px" append-to-body :close-on-click-modal="false">`;内容外层 `<div @paste="onPaste">`;类型用 `<ElSegmented :options="typeOptions" v-model="selectedType" />`;模块用 `ElSelect` + `ElOption v-for`;内容用 `<ElInput v-model="content" type="textarea" :rows="5" :maxlength="2000" show-word-limit resize="none" :placeholder="..." />`;底部 `ElButton`(取消)与 `ElButton type="primary" :loading="submitting"`(提交)。字数统计与错误行保留在输入框下方。
|
|
||||||
- 图片条(输入框下方):已添加图片渲染 48×48 缩略图(`:src="img.previewUrl"`,右上角小 × = `removeImage`,uploading 状态加半透明遮罩);末尾「添加图片」格子(Plus 图标 + `t('feedback.upload.addImage')`,点击触发隐藏 `<input type="file" multiple accept="image/png,image/jpeg,image/webp">`);下方灰色提示 `t('feedback.upload.pasteHint')`。
|
|
||||||
- 组件常量与逻辑(签名钉死):
|
|
||||||
|
|
||||||
```ts
|
|
||||||
const MAX_FEEDBACK_IMAGES = 5;
|
|
||||||
const MAX_FEEDBACK_IMAGE_SIZE_MB = 10;
|
|
||||||
const FEEDBACK_IMAGE_ACCEPT = ['image/png', 'image/jpeg', 'image/webp'];
|
|
||||||
|
|
||||||
interface PendingImage {
|
|
||||||
assetNo: string | null; // 上传成功后的 FA 编号
|
|
||||||
status: 'uploading' | 'ready';
|
|
||||||
previewUrl: string; // URL.createObjectURL(file)
|
|
||||||
filename: string;
|
|
||||||
}
|
|
||||||
const images = ref<PendingImage[]>([]);
|
|
||||||
const hasUploadingImage = computed(() => images.value.some((i) => i.status === 'uploading'));
|
|
||||||
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value && !hasUploadingImage.value);
|
|
||||||
|
|
||||||
/** [AI 触发时机] 无 —— 纯 UI 交互:批量加入图片;超过上限整批拒绝并提示 maxCount(不截取前 N 张)。 */
|
|
||||||
async function addImages(files: File[]): Promise<void>
|
|
||||||
// 校验:先过滤类型不在 FEEDBACK_IMAGE_ACCEPT 的 → ElMessage.error(invalidType);
|
|
||||||
// 若 files.length + images.length > MAX_FEEDBACK_IMAGES → ElMessage.error(t('feedback.upload.maxCount', { count: MAX_FEEDBACK_IMAGES })) 且整批不入队;
|
|
||||||
// 单张 file.size > MAX_FEEDBACK_IMAGE_SIZE_MB * 1024 * 1024 → ElMessage.error(maxSize) 跳过该张;
|
|
||||||
// 逐张入队 status='uploading' → uploadFileAsset(file) 成功置 ready+assetNo;失败:移除该项 + ElMessage.error(uploadFailed)。
|
|
||||||
|
|
||||||
function removeImage(index: number): void // revoke previewUrl 后 splice
|
|
||||||
function onPaste(e: ClipboardEvent): void // e.clipboardData.items 中 kind==='file' 且 type 以 'image/' 开头的项 getAsFile();仅当取到文件才 preventDefault;调 addImages
|
|
||||||
function onFileChange(e: Event): void // input.files → addImages → input.value = ''
|
|
||||||
function cleanupImages(): void // 全部 revoke + 清空(resetForm 与弹窗关闭时调用,复用现有 watch(modelValue) 位置)
|
|
||||||
```
|
|
||||||
|
|
||||||
- 提交:`requestJson<void>('/api/user/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ feedback_type, feedback_module, content, source_page, ...(chatLogId != null ? { chat_log_id: chatLogId } : {}), image_asset_nos: images.value.filter(i => i.status === 'ready').map(i => i.assetNo as string) }) })`;捕获 `BusinessError` → `error.value = e.message`(沿用现有内联错误展示);成功路径不变(`emit('submitted'); closeDialog()`)。
|
|
||||||
- 其余行为保持:类型/模块仍存**翻译后的展示文案**;语言切换时 resetForm 的 watch 保留(cleanupImages 一并调用)。
|
|
||||||
|
|
||||||
- [ ] **Step 3: 更新三个挂载点**
|
|
||||||
|
|
||||||
在 `WorkspaceModals.vue`、`ChatViewOverlays.vue`、`FeedbackPage.vue` 中删除传给 `GeneralFeedbackDialog` 的 `:auth-headers="getAuthHeaders()"`(属性名以实际文件为准);若 `getAuthHeaders` 在该文件无其他使用,连同 import 一并删除。
|
|
||||||
|
|
||||||
- [ ] **Step 4: 构建验证**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd frontend && npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
Expected: 构建通过,无 TS 报错;grep 确认 `GeneralFeedbackDialog.vue` 内无 `btn-`/`input-field`/`<textarea`/`<select`。
|
|
||||||
|
|
||||||
- [ ] **Step 5: 人工验证(dev server)**
|
|
||||||
|
|
||||||
`npm run dev` 后:粘贴一张截图 → 缩略图出现;粘贴 6 张 → maxCount 提示;删除、提交成功;workspace 与 chat 两个入口弹窗均可开、提交成功(chat 入口带 chat_log_id)。暗色主题下弹窗可读。
|
|
||||||
|
|
||||||
- [ ] **Step 6: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add frontend/src/shared/components/GeneralFeedbackDialog.vue frontend/src/features/workspace/components/WorkspaceModals.vue frontend/src/features/chat/components/ChatViewOverlays.vue frontend/src/features/workspace/pages/FeedbackPage.vue frontend/src/locales/
|
|
||||||
git commit -m "feat(feedback): 反馈弹窗整页替换 Element Plus 并支持粘贴与选图上传"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 6: 管理端报表附图缩略图与大图预览(前端)
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `frontend/src/features/admin/api/admin.api.ts`(类型)
|
|
||||||
- Modify: `frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts`
|
|
||||||
- Modify: `frontend/src/features/admin/modules/reports/ReportsPage.vue`
|
|
||||||
|
|
||||||
**Interfaces:**
|
|
||||||
- Consumes: Task 4 的行内 `images` 元数据与 raw 接口;现有 `requestBlob(url)`(`@/shared/api/client`,自动附鉴权头,返回 `{ blob, filename? }`)。
|
|
||||||
- Produces(在 `useReportsAdmin` 返回对象中新增,供 ReportsPage 解构):
|
|
||||||
- `feedbackImagePreview: Ref<{ feedbackId: number; images: FeedbackReportImage[]; index: number } | null>`
|
|
||||||
- `feedbackImageUrl(feedbackId: number, imageId: number): string | null`(objectURL 缓存,键 `${feedbackId}:${imageId}`,未加载过返回 null)
|
|
||||||
- `loadFeedbackImage(feedbackId: number, imageId: number): Promise<void>`(缓存键 `${feedbackId}:${imageId}` 已存在时直接 return;否则 `requestBlob('/api/admin/reports/general-feedbacks/${feedbackId}/images/${imageId}/raw')` → `URL.createObjectURL(blob)` 入缓存;失败静默置缓存值为 `''` 表示占位)
|
|
||||||
- `openFeedbackImagePreview(row: any, index: number): void` / `closeFeedbackImagePreview(): void` / `stepFeedbackImagePreview(delta: number): void`(index 在 images 内循环)
|
|
||||||
- 类型:`interface FeedbackReportImage { image_id: number; asset_no: string; original_filename: string; file_size: number; sort_order: number }`(放 admin.api.ts 并导出);报表行类型加可选 `images?: FeedbackReportImage[]`。
|
|
||||||
|
|
||||||
- [ ] **Step 1: composable 改造**
|
|
||||||
|
|
||||||
1. `visibleReportKeys` 的 `feedbackFixedOrder`(1068-1079 行)在 `'content'` 后插入 `'images'`。
|
|
||||||
2. 现有按列名返回宽度的 switch(useReportsAdmin.ts 顶部,`default: return 160;` 处)加 `case 'images': return 176;`。
|
|
||||||
3. `feedbackReportI18nMap` 四个语言包的 `generalColumns` 各加一条(en/zh-CN/zh-TW/th):`images: 'Images'` / `images: '附图'` / `images: '附圖'` / `images: 'รูปภาพ'`(CJK 沿用文件内已有的 `\uXXXX` 转义风格)。
|
|
||||||
4. 新增 Interfaces 段列出的状态与五个函数(含 objectURL 缓存 `Map<string, string>`,模块级或 composable 闭包内)。
|
|
||||||
|
|
||||||
- [ ] **Step 2: ReportsPage 单元格与 lightbox**
|
|
||||||
|
|
||||||
1. 意见反馈内容列旁新增分支(1417 行的 `<template v-if=...>` 链中,chat_log_id 分支之前):
|
|
||||||
|
|
||||||
```html
|
|
||||||
<template v-else-if="isMergedFeedbackTable && feedbackTab === 'general' && key === 'images'">
|
|
||||||
<div class="flex items-center gap-1" :style="getReportCellInnerStyle()">
|
|
||||||
<template v-if="(row.images || []).length">
|
|
||||||
<img
|
|
||||||
v-for="(img, i) in row.images"
|
|
||||||
:key="img.image_id"
|
|
||||||
:src="feedbackImageUrl(row.id, img.image_id) || ''"
|
|
||||||
:alt="img.original_filename"
|
|
||||||
loading="lazy"
|
|
||||||
class="h-10 w-10 cursor-pointer rounded border border-default object-cover"
|
|
||||||
@load="loadFeedbackImage(row.id, img.image_id)"
|
|
||||||
@error="loadFeedbackImage(row.id, img.image_id)"
|
|
||||||
@click.stop="openFeedbackImagePreview(row, i)"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
<span v-else class="text-muted">-</span>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
```
|
|
||||||
|
|
||||||
(`@load`/`@error` 触发懒加载:src 为空时浏览器立即 error → 发起 blob 加载,加载完成后缓存更新触发重渲;`<img>` 无法自带鉴权头,故必须走 blob,见 spec D6。)
|
|
||||||
|
|
||||||
2. 该单元格的 `:title` 绑定(1413 行)把 `key === 'images'` 加入置 undefined 的条件,避免 title 出现 `[object Object]`。
|
|
||||||
3. 表格之后(仿 1523-1543 行 chat-logs 详情 overlay 的自建模式)新增 lightbox:
|
|
||||||
|
|
||||||
```html
|
|
||||||
<div v-if="feedbackImagePreview" class="fixed inset-0 z-50 flex items-center justify-center p-4">
|
|
||||||
<div class="absolute inset-0 bg-black/70" @click="closeFeedbackImagePreview"></div>
|
|
||||||
<div class="relative flex max-h-[90vh] max-w-[90vw] flex-col items-center gap-3">
|
|
||||||
<div class="flex items-center gap-4">
|
|
||||||
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(-1)">‹</button>
|
|
||||||
<img v-if="currentPreviewUrl" :src="currentPreviewUrl" :alt="currentPreviewImage?.original_filename" class="max-h-[80vh] max-w-[80vw] rounded object-contain" />
|
|
||||||
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(1)">›</button>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center gap-3 text-sm text-white/80">
|
|
||||||
<span>{{ feedbackImagePreview.index + 1 }} / {{ feedbackImagePreview.images.length }}</span>
|
|
||||||
<span>{{ currentPreviewImage?.original_filename }}</span>
|
|
||||||
<button type="button" class="btn-icon-ds" :title="t('admin.report.feedback.closePreview')" @click="closeFeedbackImagePreview">✕</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
```
|
|
||||||
|
|
||||||
`currentPreviewImage` / `currentPreviewUrl` 为 ReportsPage 内基于 `feedbackImagePreview` 与 `feedbackImageUrl` 的 computed;打开与翻页时对当前图调用 `loadFeedbackImage`。多图时(仅 1 张也显示,翻页按钮按 images.length 循环)。
|
|
||||||
|
|
||||||
4. `admin.json` 四语言 `report.feedback` 段加 `"closePreview"`:zh-CN `关闭预览` / zh-TW `關閉預覽` / en `Close preview` / th `ปิดตัวอย่าง`。
|
|
||||||
|
|
||||||
- [ ] **Step 3: 构建验证**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd frontend && npm run build # Expected: 通过
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4: 人工验证**
|
|
||||||
|
|
||||||
后端起 dev 服务(需 `flask db upgrade` 到新 head),提交 1-2 条带图反馈后,管理端「报表 → 用户反馈」:有图行显示缩略图,点击放大、左右翻页、关闭;无图行显示 `-`;Network 面板确认无图行零图片请求、缩略图 lazy(Review Focus 3/4)。
|
|
||||||
|
|
||||||
- [ ] **Step 5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add frontend/src/features/admin/
|
|
||||||
git commit -m "feat(admin): 报表意见反馈页签展示附图缩略图与大图预览"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Task 7: 文档同步与收尾验证
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `docs/funclist.md`(意见反馈相关条目)
|
|
||||||
- Modify: `docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md`(状态行改为「已实现」)
|
|
||||||
|
|
||||||
- [ ] **Step 1: 更新 `funclist.md`**
|
|
||||||
|
|
||||||
在功能清单中「意见反馈」所在小节补一行(保持该文件既有格式):`意见反馈支持粘贴/上传截图附件(≤5 张),管理端报表可查看附图与大图预览`。若清单中无意见反馈条目,则在用户端与管理端各自最贴近的位置各补一条。
|
|
||||||
|
|
||||||
- [ ] **Step 2: 全量验证**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd backend && python -m pytest tests/api/test_general_feedback_api.py tests/services/test_feedback_notify.py -v # Expected: 全 PASS
|
|
||||||
cd ../frontend && npm run build # Expected: 通过
|
|
||||||
cd .. && flask db heads # (backend venv)Expected: 单 head
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add docs/funclist.md docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md
|
|
||||||
git commit -m "docs(funclist): 补充意见反馈截图附件功能项"
|
|
||||||
```
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
# 意见反馈支持截图附件 — 设计文档
|
|
||||||
|
|
||||||
- 日期:2026-10-26
|
|
||||||
- 分支:`picture-feedback`(自 `dev` 切出,当前为空分支)
|
|
||||||
- 状态:已实现(2026-10-26,分支 picture-feedback)
|
|
||||||
- 需求来源:用户反馈处理时经常缺少截图,无法复现问题;现反馈弹窗只支持纯文本。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 意图与背景
|
|
||||||
|
|
||||||
意见反馈弹窗(`GeneralFeedbackDialog.vue`)目前只能提交文字(反馈类型/模块/内容/来源页),处理人拿到反馈后经常因为"没有截图、无法复现"反复找提交人确认。本次为反馈增加**截图附件**:用户在弹窗里可以**粘贴(Ctrl+V)**或**点击选图**添加截图,提交后图片随反馈入库;处理人在**管理端报表页**查看反馈时可以看到缩略图并点开大图。
|
|
||||||
|
|
||||||
处理人现有两个入口:企微群机器人通知(文字摘要)+ 后台报表完整记录。**已与需求方确认(方案 1)**:图片只在后台报表查看,企微通知保持纯文字。
|
|
||||||
|
|
||||||
## 2. 目标 / 非目标 / 反目标
|
|
||||||
|
|
||||||
**目标**
|
|
||||||
- 用户弹窗支持粘贴截图 + 点击选图,带缩略图预览与单张删除。
|
|
||||||
- 提交后图片与反馈记录关联,管理端报表「用户反馈」页签可见缩略图、可放大查看、可前后翻图。
|
|
||||||
- 有图时企微通知多一行「附图:N 张」(纯文字,不发图)。
|
|
||||||
- 反馈弹窗整页替换为 Element Plus 控件(需求方已拍板)。
|
|
||||||
|
|
||||||
**非目标(本期不做)**
|
|
||||||
- 企微群消息内嵌图片(企微机器人 markdown 不支持外链图,image 消息单张 ≤2MB,群里会刷屏)。
|
|
||||||
- 服务端图片压缩/旋转/加水印。
|
|
||||||
- 拖拽上传(粘贴 + 点选已覆盖需求)。
|
|
||||||
- gif/bmp 格式(平台文件资产白名单本就不含)。
|
|
||||||
- 提交后增删图片;反馈提交后即不可变。
|
|
||||||
- 关闭反馈时释放图片资产(图片随反馈长期保留)。
|
|
||||||
- 用户侧"我的反馈"回看页面(现网无此入口)。
|
|
||||||
- 管理端 ReportsPage 其余部分的 Element Plus 化(只加展示,不整页替换)。
|
|
||||||
|
|
||||||
**反目标(出现即算失败)**
|
|
||||||
- 破坏现有纯文本反馈的提交链路与 SSE 对话链路。
|
|
||||||
- 未引用图片滞留:孤儿图必须能被现有 72h 清理任务回收,不允许出现"永久滞留的临时资产"。
|
|
||||||
- 同一页面混用两套控件风格(仓库红线)。
|
|
||||||
|
|
||||||
## 3. 约束(来自 AGENTS.md / 现有设施)
|
|
||||||
|
|
||||||
1. **改表必须配套 Alembic 迁移**(当前单 head:`mh23e4f5a6b7`)。
|
|
||||||
2. **前端统一 Element Plus**:弹窗整页替换;管理端 ReportsPage 保持原样,只允许新增 `<img>` 缩略图与自建 overlay 预览(展示型,不新增表单控件)。
|
|
||||||
3. **HTTP 统一 `requestJson`(`@/shared/api/client`)**:弹窗现为裸 `fetch`,本次替换为 `requestJson`;失败以 `BusinessError` + `useMessage()` 展示。**后端接口响应契约保持现状**(`{status:'ok', id}`,唯一消费方就是本弹窗),不强行改 envelope,控制改动面。
|
|
||||||
4. **新增 error.code 同步四语言 `locales/*/errors.json`**。
|
|
||||||
5. **i18n 四语言**:新增文案补齐 zh-CN / zh-TW / en / th,禁止硬编码中文。
|
|
||||||
6. **不新增第三方依赖**:粘贴/上传/预览全部用现有依赖(原生 API + Element Plus + 现有 composables)。
|
|
||||||
7. **注释三层标准**(§5):文件层块注释 + 核心函数注释(含 AI 触发时机如有)+ `[STEP]` 分块。
|
|
||||||
8. **文档同步**:`docs/funclist.md` 与本设计文档随功能同一 PR 更新。
|
|
||||||
|
|
||||||
## 4. 已定决策
|
|
||||||
|
|
||||||
| # | 决策 | 来源 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| D1 | 图片只在管理端报表查看;企微通知纯文字,有图时加「附图:N 张」行 | 需求方(方案 1) |
|
|
||||||
| D2 | 反馈弹窗整页替换为 Element Plus | 需求方 |
|
|
||||||
| D3 | 选图/粘贴后**立即**上传(复用 `POST /api/files/assets` + `uploadFileAsset`),提交时 JSON 携带 `image_asset_nos[]`;取消弹窗的孤儿图交给现有 72h 清理,不新做回收 | 设计默认 |
|
|
||||||
| D4 | 限制:每条反馈最多 **5 张**,单张 **10MB**,格式 png/jpg/jpeg/webp;客户端校验 + **服务端扩展名二次校验**(平台资产白名单还含 pdf/doc 等文档类型,不能依赖) | 设计默认(可调) |
|
|
||||||
| D5 | 新子表 `general_feedback_images` 关联 feedback↔file_asset;`asset_id` 唯一约束(一张图只能挂一条反馈);提交时同事务调 `mark_asset_referenced` | 设计默认(照搬 `ShippingOrderIntake.asset_id` 模式) |
|
|
||||||
| D6 | 图片统一由**后端代理输出**:新增管理端 raw 接口流式返回图片字节,前端带鉴权头 fetch 取 blob 后 `URL.createObjectURL` 展示。**不走 MinIO 预签名 URL**——已核实:`presigned_get_url` 按 `MINIO_ENDPOINT` 签名(storage.py:32,123),`MINIO_PUBLIC_BASE_URL`(settings.py:674)全库无一处使用,生产 `MINIO_ENDPOINT=host.docker.internal:9000` 浏览器不可解析;且 SigV4 签名覆盖 Host,事后改写域名即失效 | 评审修订 |
|
|
||||||
| D7 | 大图预览:ReportsPage 内按该页现有自建 overlay 风格做轻量 lightbox(深色遮罩 + 大图 + 前后翻页);不复用 `FilePreviewModal`(其绑死 chat agent 取流) | 设计默认 |
|
|
||||||
| D8 | 提交接口 `POST /api/user/feedback` 响应契约不变,只扩展请求字段与校验 | 设计默认 |
|
|
||||||
| D9 | 仅允许挂载**全新未引用**资产:`reference_count == 0` 且 `lifecycle_status == 'temporary'`。防止把已投入其他业务(如货代接单)的资产挂到反馈上,污染其引用计数/生命周期 | 评审修订 |
|
|
||||||
| D10 | 缩略图以 `loading="lazy"` 按需加载原图,不做服务端缩略图生成;无图行零图片请求。列表默认 200 行,有图反馈占比低,可接受 | 评审确认 |
|
|
||||||
|
|
||||||
## 5. 方案详述
|
|
||||||
|
|
||||||
### 5.1 数据模型与迁移
|
|
||||||
|
|
||||||
新表 `general_feedback_images`:
|
|
||||||
|
|
||||||
| 列 | 类型 | 说明 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| id | Integer PK | |
|
|
||||||
| feedback_id | FK `general_feedbacks.id`,NOT NULL,indexed | 级联删除随反馈 |
|
|
||||||
| asset_id | FK `file_assets.id`,NOT NULL,**unique** | 一图只挂一条反馈 |
|
|
||||||
| sort_order | Integer,NOT NULL,default 0 | 按添加顺序 |
|
|
||||||
| created_at | DateTime,default utcnow | |
|
|
||||||
|
|
||||||
模型 `GeneralFeedbackImage` 放在 `backend/app/models/chat.py`(`GeneralFeedback` 旁),并在 `GeneralFeedback` 上加 `images` 有序 relationship。Alembic 迁移基于单 head `mh23e4f5a6b7`。
|
|
||||||
|
|
||||||
### 5.2 上传链路(用户弹窗)
|
|
||||||
|
|
||||||
1. 交互:内容输入框下方新增图片条——缩略图(右上角 × 删除)+「添加图片」格子;提示文案"支持粘贴截图(Ctrl+V)或点击添加,最多 5 张"。
|
|
||||||
2. 粘贴:监听弹窗根节点 `paste` 事件,`clipboardData.items` 中 `type startsWith 'image/'` 的项转 `File`;仅当存在图片项时拦截默认行为。
|
|
||||||
3. 选图:隐藏 `<input type="file" multiple accept="image/png,image/jpeg,image/webp">` 由格子触发。
|
|
||||||
4. 客户端校验:格式(扩展名/ mime)、单张 ≤10MB、总数 ≤5(含上传中与已上传);超限给出 i18n 提示。
|
|
||||||
5. 校验通过立即 `uploadFileAsset(file)`(`frontend/src/shared/api/file-assets.api.ts`),格子显示上传中态;失败可重试或移除。
|
|
||||||
6. 弹窗内维护 `uploadedAssets: [{assetNo, filename, previewUrl?, ...}]`。**取消/关闭弹窗不回收资产**:未提交的图是 `temporary` 状态,72h 后被 `SCH-FILE-ASSET-CLEANUP` 每小时任务自动清理(见 `services/file_assets/cleanup.py`),本期不主动调 `release_asset_reference`。
|
|
||||||
7. 缩略图预览优先用 `URL.createObjectURL`,弹窗关闭时 revoke。
|
|
||||||
|
|
||||||
### 5.3 提交接口变更(后端)
|
|
||||||
|
|
||||||
`POST /api/user/feedback`(`backend/app/api/user/handlers.py:122-177` `submit_general_feedback`):
|
|
||||||
|
|
||||||
- 请求体新增可选 `image_asset_nos: string[]`(≤5 个,去重)。
|
|
||||||
- 校验(任一失败整单拒绝,400):每个 asset_no 存在、`owner_user_id == 当前用户`、`upload_status` 为已上传、`deleted_at IS NULL`、扩展名 ∈ {png, jpg, jpeg, webp}(服务端二次校验,见 D4)、`reference_count == 0` 且 `lifecycle_status == 'temporary'`(未被任何业务引用,见 D9;`asset_id` 唯一约束兜底并发双挂)。
|
|
||||||
- 同一事务:创建 `GeneralFeedback` → 批量创建 `GeneralFeedbackImage`(sort_order 按传入顺序)→ 对每个资产调 `mark_asset_referenced`(`services/file_assets/service.py:430`,reference_count+1、lifecycle='referenced'、清 expires_at)→ commit。
|
|
||||||
- 失败路径:校验失败不落任何数据;commit 异常整体回滚。
|
|
||||||
- 响应契约不变:`{status:'ok', id}`。
|
|
||||||
- 错误码走 `AppError` 子类,新增 `FEEDBACK.IMAGE_INVALID` 之类错误码并同步四语言 `errors.json`。
|
|
||||||
|
|
||||||
### 5.4 企微通知调整
|
|
||||||
|
|
||||||
`backend/app/services/feedback_notify.py` `build_feedback_markdown`:仅当 `feedback.images` 非空时,在「反馈内容」前插入一行 `>附图:N 张`(N 为图片数)。不发送图片本体,其余不变。
|
|
||||||
|
|
||||||
### 5.5 管理端列表与图片查看
|
|
||||||
|
|
||||||
**后端**(`backend/app/api/admin/reports.py` + `services/admin/report_service.py`):
|
|
||||||
|
|
||||||
- `list_general_feedbacks_report`(report_service.py:560-590)每行新增 `images: [{image_id, asset_no, original_filename, file_size, sort_order}]`(仅元数据,不含 URL)。
|
|
||||||
- 新接口 `GET /api/admin/reports/general-feedbacks/<feedback_id>/images/<image_id>/raw`:鉴权沿用该 blueprint 现有管理员校验;校验 image 属于该 feedback;`read_asset_bytes` 读字节后流式输出,`Content-Type` 取资产 mime,`Content-Disposition: inline`。前端以带鉴权头的 fetch 取 blob 再 `URL.createObjectURL` 展示(见 D6,不使用预签名 URL,`<img>` 无需自带鉴权头)。
|
|
||||||
|
|
||||||
**前端**(`frontend/src/features/admin/modules/reports/`):
|
|
||||||
|
|
||||||
- `useReportsAdmin.ts` `feedbackFixedOrder`(1070-1083)在 `content` 后插入 `images` 虚拟列;API 类型(`admin.api.ts:856` 附近)同步。
|
|
||||||
- `ReportsPage.vue`:`images` 列渲染缩略图(`<img loading="lazy">`,高约 40px,最多 5 张横向排列),无图显示 `-`,blob 加载失败显示占位。
|
|
||||||
- 点击缩略图打开本页内 lightbox overlay(参照 chat-logs 详情 overlay 的自建模式,ReportsPage.vue:1524-1543):深色遮罩 + 居中大图 + 左右翻页(在该反馈 images 内循环)+ 关闭;打开与翻页时按需 fetch blob,关闭/切换时 revoke 旧 objectURL。
|
|
||||||
- 不改动该页其余控件风格。
|
|
||||||
|
|
||||||
### 5.6 反馈弹窗 Element Plus 化
|
|
||||||
|
|
||||||
`frontend/src/shared/components/GeneralFeedbackDialog.vue` 整页重写:
|
|
||||||
|
|
||||||
- 控件:`el-dialog` + `el-radio-group`/`el-segmented`(反馈类型三选一)+ `el-select`(反馈模块)+ `el-input type="textarea"`(maxlength 2000, show-word-limit)+ `el-button`(取消/提交,提交 loading 态)。图片条可用 `el-upload` 的 list-type="picture-card" 思路或自绘缩略图条(允许:上传区不是表单校验控件;实现者按 EP 惯例选择,但**禁止**再引入 `btn-*`/`input-field` 等旧类)。
|
|
||||||
- 现有行为保持:类型/模块取值仍是**翻译后的展示文案**(后端按 ≤32 字符字符串存储,本次不改该契约);`source-page`、`chat_log_id`(chat 来源时)透传;成功/失败提示文案沿用 `feedback.*` i18n。
|
|
||||||
- 提交改走 `requestJson`(已核实其自动附带鉴权头),移除 `auth-headers` prop,同步更新挂载点:`features/workspace/components/WorkspaceModals.vue`、`features/chat/components/ChatViewOverlays.vue`、`features/workspace/pages/FeedbackPage.vue`。
|
|
||||||
- Element Plus 引入方式参照 `features/admin/modules/agents/AgentsPage.vue`(手动按需 import + `element-plus/dist/index.css`;注意弹窗挂在 workspace/chat 场景下的样式与暗色主题表现)。
|
|
||||||
- 上传/粘贴中禁用提交按钮,防止图片未传完就提交。
|
|
||||||
|
|
||||||
### 5.7 i18n
|
|
||||||
|
|
||||||
- `frontend/src/locales/{zh-CN,zh-TW,en,th}/feedback.json`:新增 `upload.*`(addImage、pasteHint、maxCount、maxSize、invalidType、uploadFailed、remove 等)。
|
|
||||||
- `frontend/src/locales/{...}/admin.json`:`admin.report.feedback.images`(附图列头)与预览相关文案。
|
|
||||||
- `frontend/src/locales/{...}/errors.json`:新增图片校验错误码。
|
|
||||||
|
|
||||||
### 5.8 测试
|
|
||||||
|
|
||||||
- 后端 pytest(新增,无既有反馈测试可依):
|
|
||||||
- 提交带 `image_asset_nos`:资产被引用(reference_count+1、lifecycle='referenced'、expires_at 清空),图片行 sort_order 正确;
|
|
||||||
- 拒绝场景:他人资产、不存在的 asset_no、超过 5 张、重复 asset_no;
|
|
||||||
- 管理端 raw 图片接口:管理员可取且 Content-Type 正确、image 与 feedback 不匹配 404、非管理员被拒;
|
|
||||||
- 拒绝非图片扩展名资产(如 pdf);
|
|
||||||
- 拒绝已被其他业务引用的资产(reference_count > 0);
|
|
||||||
- 报表行内含 `images` 元数据数组。
|
|
||||||
- 既有链路回归:纯文本提交不受影响。
|
|
||||||
- 前端:弹窗无既有 spec,本期不强制新增(可选)。
|
|
||||||
|
|
||||||
## 6. 现有代码坐标(调研结论)
|
|
||||||
|
|
||||||
| 事物 | 位置 |
|
|
||||||
| --- | --- |
|
|
||||||
| 反馈弹窗组件 | `frontend/src/shared/components/GeneralFeedbackDialog.vue`(裸 fetch 提交 98-105 行) |
|
|
||||||
| 弹窗挂载点 | `features/workspace/components/WorkspaceModals.vue:9,122-128`;`features/chat/components/ChatViewOverlays.vue:8,53-54`;状态 `useChatPageDialogs.ts:81`、`useWorkspaceNavigation.ts:63,92,198`;占位路由 `features/workspace/pages/FeedbackPage.vue` |
|
|
||||||
| 提交接口 | `backend/app/api/user/handlers.py:122-177`(校验 feedback_type/module ≤32、content ≤2000、chat_log_id 归属) |
|
|
||||||
| 反馈模型 | `backend/app/models/chat.py:117-140` `GeneralFeedback`(无任何附件字段) |
|
|
||||||
| 企微通知 | `backend/app/services/feedback_notify.py`(markdown 组装 :93,发送 :138,best-effort) |
|
|
||||||
| 管理端路由/服务 | `backend/app/api/admin/reports.py:90-132`;`backend/app/services/admin/report_service.py:560-590` |
|
|
||||||
| 管理端页面 | `frontend/src/features/admin/modules/reports/ReportsPage.vue`(内容 popover :1417-1441;chat-logs 自建 overlay :1524-1543);`composables/useReportsAdmin.ts`(列序 :1070-1083);API `features/admin/api/admin.api.ts:856,888-912` |
|
|
||||||
| 文件资产模型 | `backend/app/models/file_asset.py:22-70`(`owner_user_id`、`lifecycle_status` temporary/referenced/expired、`reference_count`、`expires_at`) |
|
|
||||||
| 文件资产服务 | `backend/app/services/file_assets/service.py`(白名单 :55-58 含 png/jpg/jpeg/webp;序列化 :102-116;**owner-only** :119-136;30MB 限制 :155-157;`mark_asset_referenced` :430;`release_asset_reference` :450);存储 `storage.py`(预签名下载) |
|
|
||||||
| 上传接口(复用) | `POST /api/files/assets`(`backend/app/api/files/assets.py:33-49`,multipart);前端 `frontend/src/shared/api/file-assets.api.ts:24-31` `uploadFileAsset` |
|
|
||||||
| 预签名 URL 风险(已核实) | `storage.py:32` MinIO 客户端以 `MINIO_ENDPOINT` 构建、`:123` `presigned_get_url` 按其签名;`MINIO_PUBLIC_BASE_URL`(settings.py:674)全库未被使用;生产 `MINIO_ENDPOINT=host.docker.internal:9000` 浏览器不可解析 → 反馈图片不走预签名(D6) |
|
|
||||||
| 孤儿清理 | `backend/app/services/file_assets/cleanup.py`(72h TTL,每小时 `SCH-FILE-ASSET-CLEANUP`) |
|
|
||||||
| 关联模式参照 | `backend/app/models/shipping.py:250` `ShippingOrderIntake.asset_id` FK→file_assets |
|
|
||||||
| Element Plus 引入范例 | `App.vue:11-15`(ElConfigProvider);`features/admin/modules/agents/AgentsPage.vue:21-23`(手动 import + css) |
|
|
||||||
| i18n 注册 | `frontend/src/locales/index.ts:45-48`(namespace `feedback`);四语言 `locales/*/feedback.json`、`admin.json`、`errors.json` |
|
|
||||||
| Alembic | 单 head `mh23e4f5a6b7`(385 个 revision) |
|
|
||||||
| 不复用项 | `shared/components/FilePreviewModal.vue`(取流绑死 chat agent,需 agentId) |
|
|
||||||
|
|
||||||
## 7. 留给实现者的开放点(builder's call)
|
|
||||||
|
|
||||||
1. Element Plus 样式引入位置(组件级 vs 全局)与暗色主题验证。
|
|
||||||
2. raw 接口流式响应细节(Content-Disposition 的 UTF-8 文件名编码、缓存头)按后端既有流式惯例实现。
|
|
||||||
3. 图片条实现选 `el-upload` picture-card 还是自绘缩略条(前提:不违反红线 2)。
|
|
||||||
4. 粘贴事件监听目标与输入法/占位符的边界行为。
|
|
||||||
5. 错误码具体命名(遵循 `errors.json` 既有风格)。
|
|
||||||
|
|
||||||
## 8. 验收标准
|
|
||||||
|
|
||||||
1. 弹窗内可粘贴截图与点击选图;实时缩略图、可删除;超 5 张 / 超 10MB / 格式不符有明确提示(四语言)。
|
|
||||||
2. 提交成功后,图片与反馈关联入库;资产 `lifecycle='referenced'`,不会被 72h 清理回收。
|
|
||||||
3. 管理端「用户反馈」页签可见附图缩略图,点开可大图查看并前后翻页;旧的无图反馈展示不受影响;缩略图懒加载,无图行不发起图片请求。
|
|
||||||
4. 有图反馈的企微通知多一行「附图:N 张」;无图反馈通知与现状完全一致。
|
|
||||||
5. 取消弹窗未提交的图片 72h 后被现有清理任务回收。
|
|
||||||
6. `flask db upgrade` 可从单 head 平滑迁移;`npm run build` 通过;后端 pytest 全绿;纯文本反馈回归无影响。
|
|
||||||
7. `docs/funclist.md` 已同步更新。
|
|
||||||
@@ -22,11 +22,6 @@
|
|||||||
- 验收单归档不走合同申请单 HTTP 列表,而查 OA SQL Server(凭据复用 `OA_SQLSERVER_*`):`formtable_main_324.cgdh` 为采购单号,`requestId` 关联 `workflow_requestbase`,`currentnodetype='3'` 为已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。归档日取 `lastoperatedate`/`lastoperatetime`。事件幂等键 `oa-acceptance:{requestId}:c{contractId}`,按采购单号匹配台账;独立断点 `oa-acceptance-archive`。查询失败 fail-safe 跳过且不推进该断点。节点后于事件生成时,`_persist_payment_plan` 回放已有验收事件计算验收款/质保款日期。表名/字段可由 `CONTRACT_PAYMENT_OA_ACCEPTANCE_*` 覆盖。
|
- 验收单归档不走合同申请单 HTTP 列表,而查 OA SQL Server(凭据复用 `OA_SQLSERVER_*`):`formtable_main_324.cgdh` 为采购单号,`requestId` 关联 `workflow_requestbase`,`currentnodetype='3'` 为已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。归档日取 `lastoperatedate`/`lastoperatetime`。事件幂等键 `oa-acceptance:{requestId}:c{contractId}`,按采购单号匹配台账;独立断点 `oa-acceptance-archive`。查询失败 fail-safe 跳过且不推进该断点。节点后于事件生成时,`_persist_payment_plan` 回放已有验收事件计算验收款/质保款日期。表名/字段可由 `CONTRACT_PAYMENT_OA_ACCEPTANCE_*` 覆盖。
|
||||||
- 第二、三轮收件人查同一 OA SQL:`HrmResource.lastname` 唯一匹配台账申请人,取其 `departmentid`;`Matrixtable_3.bm` 关联部门,`zz` 为第二轮、`jfl` 为第三轮。该 ID 即 `HrmResource.id` 与企业微信 userid。优先按 `users.wecom_userid` 映射系统用户,未绑定再用主管 `lastname` 唯一匹配 `real_name`;查不到不向第一轮兜底。表名/字段可由 `CONTRACT_PAYMENT_OA_HRM_*`、`CONTRACT_PAYMENT_OA_MATRIX_*` 覆盖。
|
- 第二、三轮收件人查同一 OA SQL:`HrmResource.lastname` 唯一匹配台账申请人,取其 `departmentid`;`Matrixtable_3.bm` 关联部门,`zz` 为第二轮、`jfl` 为第三轮。该 ID 即 `HrmResource.id` 与企业微信 userid。优先按 `users.wecom_userid` 映射系统用户,未绑定再用主管 `lastname` 唯一匹配 `real_name`;查不到不向第一轮兜底。表名/字段可由 `CONTRACT_PAYMENT_OA_HRM_*`、`CONTRACT_PAYMENT_OA_MATRIX_*` 覆盖。
|
||||||
|
|
||||||
## 设备验收预警(2026-10)
|
|
||||||
|
|
||||||
- 已实现的同步只读 E10:`OA_E10_SQLSERVER_*`,验收单 `ecology10.dbo.ft_gdzcysdv2`,流程 `wfc_requestbase` / `wfc_currentnode` / `wfc_operate`,人员 `eteams.dbo.employee`。不回退 E8。本地快照按 `request_id` 唯一。每天 06:30 先同步再生成待发送,每周五 18:30 只发送(错开合同付款 06:00 / 18:00)。
|
|
||||||
- E8 补抓已接上。`OA_SQLSERVER_*` 读 `ecology`。与 E10 分来源保存。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。字段见 [features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。
|
|
||||||
|
|
||||||
## 货代发货通知 STP + 例外工作台(2026-07-29)
|
## 货代发货通知 STP + 例外工作台(2026-07-29)
|
||||||
|
|
||||||
### 阶段与状态职责基线(2026-08)
|
### 阶段与状态职责基线(2026-08)
|
||||||
|
|||||||
@@ -21,27 +21,21 @@
|
|||||||
```ts
|
```ts
|
||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/shared/styles/element-theme.css';
|
|
||||||
```
|
|
||||||
|
|
||||||
管理列表再加一行。`element-trial.css` 开头会引入 `element-theme.css`,所以管理页只引下面这一行即可,不必两份都写:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import '@/features/admin/styles/element-trial.css';
|
import '@/features/admin/styles/element-trial.css';
|
||||||
```
|
```
|
||||||
|
|
||||||
3. 语言不要在页面里再包。`App.vue` 已用 `useElementProvider()` 取出 `elementLocale`,用 `ElConfigProvider` 包住整个 `router-view`。分页、日期、下拉等 Element 内置文案跟着界面语言走。页面和弹窗不要再包 `ElConfigProvider`,也不要写死 `zh-cn`。亮暗靠现有 `html.dark` 加上面的暗色变量文件,不要在组件里再切一套主题算法。
|
3. 用 `useElementProvider()` 取出 `elementLocale`,页面根上包 `ElConfigProvider`。亮暗靠现有 `html.dark` 加上面的暗色变量文件,不要在组件里再切一套主题算法。
|
||||||
4. 使用 `v-loading` 时,在 `<script setup>` 里写 `const vLoading = ElLoading.directive`。
|
4. 使用 `v-loading` 时,在 `<script setup>` 里写 `const vLoading = ElLoading.directive`。
|
||||||
5. 文案继续用现有 i18n key。新增文案必须同时补齐 zh-CN / zh-TW / en / th。
|
5. 文案继续用现有 i18n key。新增文案必须同时补齐 zh-CN / zh-TW / en / th。
|
||||||
6. 图标用 `@element-plus/icons-vue`,放进 `ElButton` 的 `icon` 属性。不要再把 `lucide-vue-next` 的图标塞进 Element 按钮。
|
6. 图标用 `@element-plus/icons-vue`,放进 `ElButton` 的 `icon` 属性。不要再把 `lucide-vue-next` 的图标塞进 Element 按钮。
|
||||||
|
|
||||||
`shared/styles/element-theme.css` 是全站 Element 皮肤:主题变量,以及和 Tailwind 共存的按钮、输入框修正。对话页在暗色 CSS 之后引入它。`element-trial.css` 只放管理列表的表格内边距、分页条和表单补充说明,并在文件开头引入全站皮肤。某一页的列宽、筛选框宽度不要写进这两个文件。
|
`element-trial.css` 是管理端 Element 的公共皮肤,只放变量和与 Tailwind 共存的修正。某一页的列宽、筛选框宽度不要写进这个文件。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. 先写入变量,再换页面
|
## 2. 先写入变量,再换页面
|
||||||
|
|
||||||
下面这些变量已经写在 `frontend/src/shared/styles/element-theme.css` 的 `:root, html.dark` 里。Element 暗色表在 `html.dark` 上另有一份默认值,所以必须和亮色写在一起,后引入的文件才能盖过它。页面不要再各写一套字号和颜色。
|
下面这些变量已经写在 `frontend/src/features/admin/styles/element-trial.css` 的 `:root, html.dark` 里。Element 暗色表在 `html.dark` 上另有一份默认值,所以必须和亮色写在一起,后引入的文件才能盖过它。页面不要再各写一套字号和颜色。
|
||||||
|
|
||||||
| 变量 | 对齐到 | 用途 |
|
| 变量 | 对齐到 | 用途 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -141,17 +135,16 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
|
|||||||
|
|
||||||
### 4.6 语言
|
### 4.6 语言
|
||||||
|
|
||||||
语言由 `App.vue` 统一注入。`useElementProvider` 映射 zh-CN、zh-TW、en、th,认不出的语言回退简体。新页面不要再包 `ElConfigProvider`,不要在弹窗里写死 `zh-cn`。
|
`useElementProvider` 已映射 zh-CN、zh-TW、en、th。新页面把 `elementLocale` 传给 `ElConfigProvider`,不要在某个弹窗里写死 `zh-cn`。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. 不要这样做
|
## 5. 不要这样做
|
||||||
|
|
||||||
- 不要在 `main.ts` 全量注册 Element。
|
- 不要在 `main.ts` 全量注册 Element。
|
||||||
- 不要在页面或弹窗里再包 `ElConfigProvider`。语言已在 `App.vue` 注入。
|
|
||||||
- 不要在同一工具栏里混用 `.btn-primary` 和 `ElButton`。
|
- 不要在同一工具栏里混用 `.btn-primary` 和 `ElButton`。
|
||||||
- 不要用 `!important` 压 Tailwind。Element 是静态 CSS,用更具体的选择器。单行输入框内部的蓝竖线,只重置 `.el-input__inner`,见 `element-theme.css`。
|
- 不要用 `!important` 压 Tailwind。Element 是静态 CSS,用更具体的选择器。单行输入框内部的蓝竖线,只重置 `.el-input__inner`,见 `element-trial.css`。
|
||||||
- 不要改全局 `svg { display }`。按钮图标的横向排列只写在 `element-theme.css` 的 `.el-button` 上。
|
- 不要改全局 `svg { display }`。按钮图标的横向排列只写在 `element-trial.css` 的 `.el-button` 上。
|
||||||
- 不要新增第二套组件库,也不要在已换 Element 的页面里再手写一套输入框样式。
|
- 不要新增第二套组件库,也不要在已换 Element 的页面里再手写一套输入框样式。
|
||||||
- 不要为了换皮去改接口、分页协议和权限判断。
|
- 不要为了换皮去改接口、分页协议和权限判断。
|
||||||
|
|
||||||
@@ -161,7 +154,7 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
|
|||||||
|
|
||||||
换完一页,逐项核对:
|
换完一页,逐项核对:
|
||||||
|
|
||||||
- [ ] 只在该页入口引入 Element 样式。全站皮肤用 `element-theme.css`;管理列表用 `element-trial.css`(已包含全站皮肤)。不要再包 `ElConfigProvider`。
|
- [ ] 只在该页入口引入 Element 样式和 `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`。
|
||||||
@@ -181,7 +174,7 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
|
|||||||
|
|
||||||
| 现象 | 原因 | 处理 |
|
| 现象 | 原因 | 处理 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 按钮里图标和文字分成两行 | Tailwind preflight 把 `svg` 设成 `display: block` | 只在 `.el-button` 上改为横向 flex,已写在 `element-theme.css` |
|
| 按钮里图标和文字分成两行 | Tailwind preflight 把 `svg` 设成 `display: block` | 只在 `.el-button` 上改为横向 flex,已写在 `element-trial.css` |
|
||||||
| 搜索框聚焦时内部多两条蓝竖线 | `@tailwindcss/forms` 给内部 `input` 加了边框 | 只重置 `.el-input__inner` 的边框和阴影 |
|
| 搜索框聚焦时内部多两条蓝竖线 | `@tailwindcss/forms` 给内部 `input` 加了边框 | 只重置 `.el-input__inner` 的边框和阴影 |
|
||||||
| 多行输入框看起来没有边框 | 上一行修正误伤了 `.el-textarea__inner` | 文本域保留 Element 的内阴影边框 |
|
| 多行输入框看起来没有边框 | 上一行修正误伤了 `.el-textarea__inner` | 文本域保留 Element 的内阴影边框 |
|
||||||
| 筛选框每个占满一行 | `ElInput` / `ElSelect` 默认 `width: 100%` | 外层限定宽度,靠左排列 |
|
| 筛选框每个占满一行 | `ElInput` / `ElSelect` 默认 `width: 100%` | 外层限定宽度,靠左排列 |
|
||||||
@@ -200,7 +193,7 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
|
|||||||
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
|
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
|
||||||
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
|
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
|
||||||
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
|
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
|
||||||
| 部门管理 | 已改为左树右成员面板的组织树页(非 AdminListPage 列表骨架,页面头注释有说明)。树行内链接按钮、成员 ElTable/ElPagination/ElTag、680px 表单(含上级部门/同级排序/隐藏标记)和 ElMessageBox 删除确认已按 §4 对齐;成员分页走服务端。 |
|
| 部门管理 | 列表已用 `AdminListPage`。搜索、表头排序、行内链接、480px 表单、员工名单和删除确认已按 §3、§4 对齐。列表仍是本地过滤和排序,没有分页。 |
|
||||||
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
|
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
|
||||||
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
|
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
|
||||||
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
|
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
|
||||||
@@ -259,7 +252,7 @@ npm run lint
|
|||||||
|
|
||||||
## 10. 建议的切换顺序
|
## 10. 建议的切换顺序
|
||||||
|
|
||||||
1. §2 的变量已写入 `shared/styles/element-theme.css`。换下一页之前,在暗色下打开一张已换页面,看按钮、表格和弹窗是否跟着令牌变。
|
1. §2 的变量已写入 `element-trial.css`。换下一页之前,在暗色下打开一张已换页面,看按钮、表格和弹窗是否跟着令牌变。
|
||||||
2. 三个试点的列表、短弹窗和应用配置创建/编辑表单内部已按 §6 收过。部门管理也已换成 `AdminListPage`。
|
2. 三个试点的列表、短弹窗和应用配置创建/编辑表单内部已按 §6 收过。部门管理也已换成 `AdminListPage`。
|
||||||
3. 之后每个管理端列表按 §6 的清单换,一页一次,骨架用 `AdminListPage`。合并请求用 `.gitee/PULL_REQUEST_TEMPLATE.md` 里的清单。换完再开下一页。
|
3. 之后每个管理端列表按 §6 的清单换,一页一次,骨架用 `AdminListPage`。合并请求用 `.gitee/PULL_REQUEST_TEMPLATE.md` 里的清单。换完再开下一页。
|
||||||
4. §9.1 路径里的页面都换完后,按 §9.2 把 ESLint 规则改成 `error` 并接到 CI。
|
4. §9.1 路径里的页面都换完后,按 §9.2 把 ESLint 规则改成 `error` 并接到 CI。
|
||||||
|
|||||||
+24
-6
@@ -2,15 +2,17 @@
|
|||||||
/**
|
/**
|
||||||
* App.vue
|
* App.vue
|
||||||
* 根组件:主题初始化、全局消息弹窗、401 登出监听、html lang 与 i18n locale 同步。
|
* 根组件:主题初始化、全局消息弹窗、401 登出监听、html lang 与 i18n locale 同步。
|
||||||
* 依赖:useTheme、useGlobalMessageDialog、auth、linked-nav.store、useElementProvider。
|
* 依赖:useTheme、useGlobalMessageDialog、auth、linked-nav.store。
|
||||||
* 逻辑:已登录时预取关联服务侧栏入口,避免页面切换后入口后闪现。
|
* 逻辑:已登录时预取关联服务侧栏入口,避免页面切换后入口后闪现。
|
||||||
* 书签/刷新冷启动遇到 401 时只回登录页;本页已确认会话后中途失效才弹窗。
|
* 书签/刷新冷启动遇到 401 时只回登录页;本页已确认会话后中途失效才弹窗。
|
||||||
* Element 内置文案由根上的 ElConfigProvider 跟随 vue-i18n。页面不要再包一层。
|
|
||||||
*/
|
*/
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { watch, onMounted, onBeforeUnmount } from 'vue';
|
import { computed, watch, onMounted, onBeforeUnmount } from 'vue';
|
||||||
import { ElConfigProvider } from 'element-plus';
|
import { ElConfigProvider } from 'element-plus';
|
||||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
import zhCn from 'element-plus/es/locale/lang/zh-cn';
|
||||||
|
import zhTw from 'element-plus/es/locale/lang/zh-tw';
|
||||||
|
import en from 'element-plus/es/locale/lang/en';
|
||||||
|
import th from 'element-plus/es/locale/lang/th';
|
||||||
import { useTheme } from '@/shared/composables/useTheme';
|
import { useTheme } from '@/shared/composables/useTheme';
|
||||||
import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue';
|
import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue';
|
||||||
import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog';
|
import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog';
|
||||||
@@ -21,7 +23,23 @@ import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
|
|||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { locale, t } = useI18n();
|
const { locale, t } = useI18n();
|
||||||
const { elementLocale } = useElementProvider();
|
|
||||||
|
/**
|
||||||
|
* Element Plus 组件内置文案(下拉占位/日期面板/分页等)跟随应用语言:
|
||||||
|
* EP 有独立 locale 体系,默认英文,必须在根部经 el-config-provider 注入当前语言包。
|
||||||
|
*/
|
||||||
|
const elementPlusLocale = computed(() => {
|
||||||
|
switch (locale.value) {
|
||||||
|
case 'zh-TW':
|
||||||
|
return zhTw;
|
||||||
|
case 'en':
|
||||||
|
return en;
|
||||||
|
case 'th':
|
||||||
|
return th;
|
||||||
|
default:
|
||||||
|
return zhCn;
|
||||||
|
}
|
||||||
|
});
|
||||||
const { themePreference, initTheme, setThemePreference } = useTheme();
|
const { themePreference, initTheme, setThemePreference } = useTheme();
|
||||||
const {
|
const {
|
||||||
messageDialogVisible,
|
messageDialogVisible,
|
||||||
@@ -140,7 +158,7 @@ onBeforeUnmount(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<el-config-provider :locale="elementLocale">
|
<el-config-provider :locale="elementPlusLocale">
|
||||||
<router-view />
|
<router-view />
|
||||||
<LevelMessageDialog
|
<LevelMessageDialog
|
||||||
v-model="messageDialogVisible"
|
v-model="messageDialogVisible"
|
||||||
|
|||||||
@@ -584,24 +584,10 @@ export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =
|
|||||||
body: JSON.stringify({ agent_ids: agentIds }),
|
body: JSON.stringify({ agent_ids: agentIds }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Departments(树形结构:/tree 返回 children 嵌套,成员支持含下级)
|
// Departments
|
||||||
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
||||||
export const listAdminDepartmentTree = () => requestJson<any[]>('/api/admin/departments/tree', auth());
|
export const listAdminDepartmentMembers = (id: number) =>
|
||||||
export interface AdminDepartmentMembersQuery {
|
requestJson(`/api/admin/departments/${id}/members`, auth());
|
||||||
includeDescendants?: boolean;
|
|
||||||
keyword?: string;
|
|
||||||
page?: number;
|
|
||||||
pageSize?: number;
|
|
||||||
}
|
|
||||||
export const listAdminDepartmentMembers = (id: number, query: AdminDepartmentMembersQuery = {}) => {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
if (query.includeDescendants) params.set('include_descendants', '1');
|
|
||||||
if (query.keyword?.trim()) params.set('keyword', query.keyword.trim());
|
|
||||||
if (query.page && query.page > 1) params.set('page', String(query.page));
|
|
||||||
if (query.pageSize && query.pageSize !== 20) params.set('page_size', String(query.pageSize));
|
|
||||||
const qs = params.toString();
|
|
||||||
return requestJson(`/api/admin/departments/${id}/members${qs ? `?${qs}` : ''}`, auth());
|
|
||||||
};
|
|
||||||
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
||||||
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
||||||
@@ -926,30 +912,6 @@ export const closeAdminGeneralFeedback = (feedbackId: number) =>
|
|||||||
`/api/admin/reports/general-feedbacks/${feedbackId}/close`,
|
`/api/admin/reports/general-feedbacks/${feedbackId}/close`,
|
||||||
{ method: 'POST', ...auth() },
|
{ method: 'POST', ...auth() },
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
|
||||||
* 意见反馈附图元数据(管理端报表行内嵌)。
|
|
||||||
* 图片二进制不走预签名 URL,统一经 `/images/<image_id>/raw` 代理接口(requestBlob 附鉴权头)拉取。
|
|
||||||
*/
|
|
||||||
export interface FeedbackReportImage {
|
|
||||||
image_id: number;
|
|
||||||
asset_no: string;
|
|
||||||
original_filename: string;
|
|
||||||
file_size: number;
|
|
||||||
sort_order: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 意见反馈报表行(general_feedbacks)。
|
|
||||||
* 说明:通用报表接口历史上一律以 any 行返回,无显式行类型;此处固化意见反馈行的关键字段供
|
|
||||||
* 前端(useReportsAdmin 附图预览等)按类型消费;`images` 为可选字段以兼容旧数据与无图行。
|
|
||||||
*/
|
|
||||||
export interface AdminGeneralFeedbackReportRow {
|
|
||||||
id: number;
|
|
||||||
status?: string;
|
|
||||||
[key: string]: unknown;
|
|
||||||
images?: FeedbackReportImage[];
|
|
||||||
}
|
|
||||||
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
||||||
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/composables/useElementProvider.ts
|
* features/admin/composables/useElementProvider.ts
|
||||||
* 用途:把当前界面语言映射成 Element Plus 语言包。
|
* 用途:管理端 Element Plus 试点的界面语言。
|
||||||
* 依赖:element-plus locale、vue-i18n。
|
* 依赖:element-plus locale、vue-i18n。
|
||||||
* 逻辑:只由 App.vue 根上的 ElConfigProvider 使用。页面和弹窗不要再包一层。
|
* 逻辑:UsersPage、AgentsPage、KbAdminPanel 把 elementLocale 传给 ElConfigProvider;亮暗靠 html.dark 与 Element 暗色变量,不在这里重复切换。
|
||||||
* 亮暗靠 html.dark 与 Element 暗色变量,不在这里切换。
|
|
||||||
*/
|
*/
|
||||||
import { computed } from 'vue';
|
import { computed } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
@@ -21,8 +20,8 @@ const ELEMENT_LOCALES = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 取当前界面语言对应的 Element Plus 语言包。
|
* 取当前界面语言对应的 Element Plus 语言包。
|
||||||
* 核心逻辑:zh-CN、zh-TW、en、th 各用官方语言包,未知语言回退简体中文。
|
* 核心逻辑:未知语言回退简体中文。
|
||||||
* @returns elementLocale,随 vue-i18n 语言变化。交给 App.vue 的 ElConfigProvider。
|
* @returns elementLocale,随 vue-i18n 语言变化
|
||||||
*/
|
*/
|
||||||
export function useElementProvider() {
|
export function useElementProvider() {
|
||||||
const { locale } = useI18n();
|
const { locale } = useI18n();
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { Plus } from '@element-plus/icons-vue';
|
import { Plus } from '@element-plus/icons-vue';
|
||||||
import {
|
import {
|
||||||
ElButton,
|
ElButton,
|
||||||
|
ElConfigProvider,
|
||||||
ElEmpty,
|
ElEmpty,
|
||||||
ElLoading,
|
ElLoading,
|
||||||
ElTable,
|
ElTable,
|
||||||
@@ -21,6 +22,7 @@ import {
|
|||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/features/admin/styles/element-trial.css';
|
import '@/features/admin/styles/element-trial.css';
|
||||||
|
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||||
import AgentFormModal from './components/AgentFormModal.vue';
|
import AgentFormModal from './components/AgentFormModal.vue';
|
||||||
import AgentPermissionModal from './components/AgentPermissionModal.vue';
|
import AgentPermissionModal from './components/AgentPermissionModal.vue';
|
||||||
import AgentTestModal from './components/AgentTestModal.vue';
|
import AgentTestModal from './components/AgentTestModal.vue';
|
||||||
@@ -28,6 +30,7 @@ import { useAgentsAdmin } from './composables/useAgentsAdmin';
|
|||||||
import type { AgentRow } from '@/features/admin/types/agent.types';
|
import type { AgentRow } from '@/features/admin/types/agent.types';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
const { elementLocale } = useElementProvider();
|
||||||
const vLoading = ElLoading.directive;
|
const vLoading = ElLoading.directive;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -180,6 +183,7 @@ onMounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
<ElConfigProvider :locale="elementLocale">
|
||||||
<section class="admin-table-section min-h-64">
|
<section class="admin-table-section min-h-64">
|
||||||
<div class="admin-table-header admin-table-header--stacked">
|
<div class="admin-table-header admin-table-header--stacked">
|
||||||
<div>
|
<div>
|
||||||
@@ -294,6 +298,7 @@ onMounted(() => {
|
|||||||
@toggle-user="togglePermissionUser"
|
@toggle-user="togglePermissionUser"
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
</ElConfigProvider>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/announcements/AnnouncementsPage.vue
|
* features/admin/modules/announcements/AnnouncementsPage.vue
|
||||||
* 用途:公告管理列表。一张卡片里放标题、发布按钮和表格。
|
* 用途:公告管理列表。一张卡片里放标题、发布按钮和表格。
|
||||||
* 依赖:AdminListPage、useAnnouncementsAdmin、element-plus、公告表单和详情对话框。
|
* 依赖:AdminListPage、useAnnouncementsAdmin、useElementProvider、element-plus、公告表单和详情对话框。
|
||||||
* 逻辑:路由 /admin/announcements。骨架用 AdminListPage。发布、编辑、查看仍由本页的两个对话框完成。删除用 Element 确认框。
|
* 逻辑:路由 /admin/announcements。骨架用 AdminListPage。发布、编辑、查看仍由本页的两个对话框完成。删除用 Element 确认框。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue';
|
import { onMounted } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { Plus } from '@element-plus/icons-vue';
|
import { Plus } from '@element-plus/icons-vue';
|
||||||
import { ElButton, ElTable, ElTableColumn } from 'element-plus';
|
import { ElButton, ElConfigProvider, ElTable, ElTableColumn } from 'element-plus';
|
||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/features/admin/styles/element-trial.css';
|
import '@/features/admin/styles/element-trial.css';
|
||||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||||
|
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||||
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
|
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
|
||||||
import AnnouncementDetailModal from './components/AnnouncementDetailModal.vue';
|
import AnnouncementDetailModal from './components/AnnouncementDetailModal.vue';
|
||||||
import AnnouncementFormModal from './components/AnnouncementFormModal.vue';
|
import AnnouncementFormModal from './components/AnnouncementFormModal.vue';
|
||||||
import { useAnnouncementsAdmin } from './composables/useAnnouncementsAdmin';
|
import { useAnnouncementsAdmin } from './composables/useAnnouncementsAdmin';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
const { elementLocale } = useElementProvider();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
announcements,
|
announcements,
|
||||||
@@ -55,6 +57,7 @@ onMounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
<ElConfigProvider :locale="elementLocale">
|
||||||
<AdminListPage :loading="isLoading">
|
<AdminListPage :loading="isLoading">
|
||||||
<template #title>
|
<template #title>
|
||||||
<h2 class="section-title">{{ t('admin.announcement.title') }}</h2>
|
<h2 class="section-title">{{ t('admin.announcement.title') }}</h2>
|
||||||
@@ -110,6 +113,7 @@ onMounted(() => {
|
|||||||
@close="closeDetailModal"
|
@close="closeDetailModal"
|
||||||
@edit="editFromDetail"
|
@edit="editFromDetail"
|
||||||
/>
|
/>
|
||||||
|
</ElConfigProvider>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -1,23 +1,25 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/approvals/ApprovalsPage.vue
|
* features/admin/modules/approvals/ApprovalsPage.vue
|
||||||
* 用途:用户注册审批列表。一张卡片里放标题和待审表格。
|
* 用途:用户注册审批列表。一张卡片里放标题和待审表格。
|
||||||
* 依赖:AdminListPage、useApprovalsAdmin、element-plus、roleLabel。
|
* 依赖:AdminListPage、useApprovalsAdmin、useElementProvider、element-plus、roleLabel。
|
||||||
* 逻辑:路由未挂进当前菜单。通过和拒绝由 composable 弹出 Element 确认框后调接口。
|
* 逻辑:路由未挂进当前菜单。通过和拒绝由 composable 弹出 Element 确认框后调接口。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue';
|
import { onMounted } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { CircleCheck, Delete } from '@element-plus/icons-vue';
|
import { CircleCheck, Delete } from '@element-plus/icons-vue';
|
||||||
import { ElButton, ElTable, ElTableColumn, ElTag } from 'element-plus';
|
import { ElButton, ElConfigProvider, ElTable, ElTableColumn, ElTag } from 'element-plus';
|
||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/features/admin/styles/element-trial.css';
|
import '@/features/admin/styles/element-trial.css';
|
||||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||||
|
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||||
import { adminRoleLabel } from '@/features/admin/utils/roleLabel';
|
import { adminRoleLabel } from '@/features/admin/utils/roleLabel';
|
||||||
import type { AdminUserRow } from '@/features/admin/types/admin.types';
|
import type { AdminUserRow } from '@/features/admin/types/admin.types';
|
||||||
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
|
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
const { elementLocale } = useElementProvider();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
pendingUsers,
|
pendingUsers,
|
||||||
@@ -33,6 +35,7 @@ onMounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
<ElConfigProvider :locale="elementLocale">
|
||||||
<AdminListPage :loading="isLoading">
|
<AdminListPage :loading="isLoading">
|
||||||
<template #title>
|
<template #title>
|
||||||
<h2 class="section-title">{{ t('admin.approval.title') }}</h2>
|
<h2 class="section-title">{{ t('admin.approval.title') }}</h2>
|
||||||
@@ -87,4 +90,5 @@ onMounted(() => {
|
|||||||
</ElTableColumn>
|
</ElTableColumn>
|
||||||
</ElTable>
|
</ElTable>
|
||||||
</AdminListPage>
|
</AdminListPage>
|
||||||
|
</ElConfigProvider>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/dashboard/DashboardPage.vue
|
* features/admin/modules/dashboard/DashboardPage.vue
|
||||||
* 用途:管理后台仪表盘,四张可点击的统计卡。
|
* 用途:管理后台仪表盘,四张可点击的统计卡。
|
||||||
* 依赖:useDashboardAdmin、element-plus。
|
* 依赖:useDashboardAdmin、useElementProvider、element-plus。
|
||||||
* 逻辑:路由 /admin/dashboard。统计来自 useDashboardAdmin。点击分别进入应用配置、应用权限和数据报表。本页不是列表,不用 AdminListPage。
|
* 逻辑:路由 /admin/dashboard。统计来自 useDashboardAdmin。点击分别进入应用配置、应用权限和数据报表。本页不是列表,不用 AdminListPage。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
@@ -9,15 +9,17 @@ import { onMounted } from 'vue';
|
|||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRouter } from 'vue-router';
|
||||||
import { ChatDotRound, DataAnalysis, Monitor, User } from '@element-plus/icons-vue';
|
import { ChatDotRound, DataAnalysis, Monitor, User } from '@element-plus/icons-vue';
|
||||||
import { ElCard, ElIcon, ElLoading, ElStatistic, ElTag } from 'element-plus';
|
import { ElCard, ElConfigProvider, ElIcon, ElLoading, ElStatistic, ElTag } from 'element-plus';
|
||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/features/admin/styles/element-trial.css';
|
import '@/features/admin/styles/element-trial.css';
|
||||||
|
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||||
import { useDashboardAdmin } from './composables/useDashboardAdmin';
|
import { useDashboardAdmin } from './composables/useDashboardAdmin';
|
||||||
|
|
||||||
const vLoading = ElLoading.directive;
|
const vLoading = ElLoading.directive;
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { elementLocale } = useElementProvider();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
agentCount,
|
agentCount,
|
||||||
@@ -47,6 +49,7 @@ onMounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
<ElConfigProvider :locale="elementLocale">
|
||||||
<section v-loading="isLoading" class="admin-dash">
|
<section v-loading="isLoading" class="admin-dash">
|
||||||
<h2 class="section-title">{{ t('admin.nav.dashboard') }}</h2>
|
<h2 class="section-title">{{ t('admin.nav.dashboard') }}</h2>
|
||||||
<div v-if="!isLoading" class="admin-dash__grid">
|
<div v-if="!isLoading" class="admin-dash__grid">
|
||||||
@@ -80,6 +83,7 @@ onMounted(() => {
|
|||||||
</ElCard>
|
</ElCard>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
</ElConfigProvider>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user