diff --git a/.env.shared b/.env.shared index 10765a36..a0e00b2c 100644 --- a/.env.shared +++ b/.env.shared @@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN= WECOM_PUBLIC_BASE_URL= WECOM_NOTIFY_ENABLED=true WECOM_NOTIFY_BASE_URL= -WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines +WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines WECOM_FEEDBACK_NOTIFY_ENABLED=true WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881 # 企业微信群机器人 webhook,按环境写入 .env. 或部署平台变量;不要提交真实 URL。 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 3f42956b..fe84f089 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -122,6 +122,16 @@ def create_app(config_name='default'): ensure_default_contract_payment_schedules() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure contract-payment schedules: %s', exc) + try: + from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules + ensure_default_order_delivery_schedules() + except Exception as exc: # pragma: no cover - 表未就绪时容忍 + logger.warning('Failed to ensure order-delivery-reply schedule: %s', exc) + try: + from app.services.order_delivery_reply.app_seed import ensure_builtin_order_delivery_agent + ensure_builtin_order_delivery_agent() + except Exception as exc: # pragma: no cover - 表未就绪时容忍 + logger.warning('Failed to ensure order-delivery-reply agent: %s', exc) try: from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule ensure_default_lean_training_schedule() @@ -129,7 +139,9 @@ def create_app(config_name='default'): logger.warning('Failed to ensure lean-training schedule: %s', exc) else: logger.info('Skip startup schedule seeding: schedule_tasks table is not ready') - # 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程。 + # 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程; + # 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器) + # 负责(dev Wave 4),Web 进程不再兜底扫描。 # AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。 try: from app.services.shipping_notice.rpa_worker_heartbeat import ( diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index 5a6e132d..48f89307 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -49,6 +49,7 @@ def register_blueprints(app: Flask) -> None: ) from app.api.files import files_bp from app.api.contract_payment import contract_payment_bp + from app.api.order_delivery_reply import order_delivery_reply_bp from app.api.in_transit_transfer import in_transit_transfer_bp from app.api.integration_connector import integration_connector_bp @@ -80,5 +81,6 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(files_bp, url_prefix='/api/files') app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract') app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment') + app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply') app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer') app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector') diff --git a/backend/app/api/chat/completions.py b/backend/app/api/chat/completions.py index b9b443e5..297e2fbf 100644 --- a/backend/app/api/chat/completions.py +++ b/backend/app/api/chat/completions.py @@ -39,6 +39,7 @@ def chat_completions(): # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() + shipping_batch_no = str(data.get('batch_no') or '').strip() kb_type = data.get('kb_type', '企业知识库') files = data.get('files') request_id = uuid.uuid4().hex[:12] @@ -174,6 +175,7 @@ def chat_completions(): normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, + shipping_batch_no=shipping_batch_no, ), shipping_task_id=shipping_task_id, kb_type=kb_type, @@ -214,6 +216,7 @@ def chat_completions(): user_role=user_proxy.role, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, + shipping_batch_no=shipping_batch_no, ), ), ) diff --git a/backend/app/api/chat/core.py b/backend/app/api/chat/core.py index f076a6ff..c9b01ec0 100644 --- a/backend/app/api/chat/core.py +++ b/backend/app/api/chat/core.py @@ -10,19 +10,21 @@ from __future__ import annotations from .shared import * # noqa: F403 -def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None: +def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None: """ 构建聊天入口分发给领域 adapter 的提示字典。 - 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示, + 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示, 统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。 """ task_id = str(shipping_task_id or '').strip() - if not task_id: + batch_no = str(shipping_batch_no or '').strip() + if not task_id and not batch_no: return None return { 'shipping_notice': { 'task_id': task_id or None, + 'batch_no': batch_no or None, } } diff --git a/backend/app/api/order_delivery_reply.py b/backend/app/api/order_delivery_reply.py new file mode 100644 index 00000000..0e7a7710 --- /dev/null +++ b/backend/app/api/order_delivery_reply.py @@ -0,0 +1,292 @@ +""" +backend/app/api/order_delivery_reply.py + +用途:订单交期回复工作台 API——列表筛选分页、单行详情、最近同步时间、保存交期批次、单行通知、 + 联合回复保存与批量通知、手动全量同步。 +依赖:JWT 当前用户、统一响应 envelope、ForbiddenError/NotFoundError/ValidationError、 + services/order_delivery_reply(query_service 查询、reply_service 保存批次、 + notify_service 通知锁定、sync_service 同步状态)。 +逻辑:读取只打本地快照,不触碰 ERP;保存批次只写批次与 save 审计,不通知不锁定; + 通知与锁定在 notify_service 中同事务完成(企微成功才锁定)。 + 权限要求 access 或 manage(manage 隐含 access),键常量与技术文档 §7.2 一致;写接口要求 manage。 +鉴权:GET 系列要求 `order_delivery_reply.access` 或 `order_delivery_reply.manage`; + 保存批次 / 单行通知 / 联合回复 / 批量通知 / 手动同步要求 `order_delivery_reply.manage`; + 部门批量发放仅 admin 角色。两键 admin 默认开(User._role_default_feature_permissions)。 +""" + +from __future__ import annotations + +from flask import Blueprint, g, request + +from app.core.auth.jwt import get_current_user +from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError +from app.core.response import ok +from app.extensions import db +from app.models import User +from app.services.order_delivery_reply import notify_service, query_service, reply_service +from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService + +order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__) + + +def _utc_to_shanghai(value) -> str | None: + """ + 把后端 naive-UTC 时间转为北京时间的展示字符串(YYYY-MM-DD HH:MM:SS)。 + + 用途:sync_runs / notified_at 等以 utcnow 落库,直接 isoformat 会把 UTC 当本地时间误导用户。 + 约束:仅用于展示序列化,不改变库内存储;无法解析时原样返回。 + """ + from datetime import timezone + from zoneinfo import ZoneInfo + + if value is None: + return None + try: + local = value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")) + return local.strftime("%Y-%m-%d %H:%M:%S") + except (AttributeError, ValueError): + return value.isoformat() if hasattr(value, "isoformat") else str(value) + +# 功能权限键(与 docs/features/order-delivery-reply/technical-design.md §7.2 对齐)。 +PERMISSION_MANAGE = "order_delivery_reply.manage" +PERMISSION_ACCESS = "order_delivery_reply.access" + + +def _require_user(): + """返回当前登录用户;未认证抛 UnauthorizedError。""" + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + + +def _has_order_delivery_permission(user, key: str) -> bool: + """ + 判定功能权限:统一走 User.has_feature_permission(角色默认 + 显式勾选合并)。 + + 核心逻辑:admin 角色两键默认开(User._role_default_feature_permissions); + 普通用户按用户管理表单勾选;每次请求只看勾选,不拿部门当门禁(技术文档 §7.2)。 + """ + return user.has_feature_permission(key) + + +def _require_access(): + """ + 确保当前用户可访问订单交期回复(查看)。 + + Raises: + UnauthorizedError: 未登录。 + ForbiddenError: 已登录但既无 manage 也无 access(manage 命中视为有 access)。 + """ + user = _require_user() + if not (_has_order_delivery_permission(user, PERMISSION_MANAGE) or _has_order_delivery_permission(user, PERMISSION_ACCESS)): + raise ForbiddenError( + "Order delivery reply access required", + code="ORDER_DELIVERY_REPLY.FORBIDDEN", + ) + return user + + +def _require_manage(): + """ + 确保当前用户可写订单交期回复(保存批次 / 通知 / 手动同步)。 + + Raises: + UnauthorizedError: 未登录。 + ForbiddenError: 已登录但无 manage(仅有 access 的业务用户只读)。 + """ + user = _require_user() + if not _has_order_delivery_permission(user, PERMISSION_MANAGE): + raise ForbiddenError( + "Order delivery reply manage permission required", + code="ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN", + ) + return user + + +@order_delivery_reply_bp.get("/lines") +def list_lines(): + """ + 订单行列表(筛选 + 分页)。 + + 用途与触发时机:工作台首屏与筛选刷新;全选仅作用于本页返回的 items。 + + 参数与输出约束:查询参数 keyword/order_date/status/page/page_size——keyword 为合并搜索 + (订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号 + 命中任一即返回);status ∈ 空(全部) | replied(已回复) | not_fully_replied(未完全回复); + 返回统一 envelope,data.items 为行序列化(含批次、状态、未交数量)。 + """ + _require_access() + data = query_service.list_lines(request.args.to_dict(flat=True)) + return ok(data, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.get("/lines//") +def get_line(order_no: str, line_no: int): + """ + 单行详情:快照 + 批次 + 状态 + 审计事件。 + + 参数与输出约束:order_no/line_no 为行唯一键;不存在或已标 erp_missing(已不在同步范围) + 的行一律按不存在处理返回 404,不在工作台展示。 + """ + _require_access() + payload = query_service.get_line(order_no, line_no) + if payload is None: + raise NotFoundError( + "Order delivery line not found", + code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND", + ) + return ok(payload, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.put("/lines///batches") +def save_line_batches(order_no: str, line_no: int): + """ + 保存单行交期批次(未锁定行整表替换)。 + + 用途与触发时机:单行弹窗「回复交期/修改回复」提交;联合回复保存逐行复用同一服务入口。 + + 参数与输出约束:body {"batches": [{planned_date, qty, remark?}]};交期必填 YYYY-MM-DD、 + 数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;各批次合计必须等于订单数量, + 不等返回 422 BATCH_QTY_TOTAL_MISMATCH(2026-09-23 由「超额仅提醒」修订)。 + 已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。 + """ + user = _require_manage() + payload = request.get_json(silent=True) or {} + data = reply_service.save_batches(order_no, line_no, payload.get("batches"), user.id) + return ok(data, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.post("/lines///notify") +def notify_line(order_no: str, line_no: int): + """ + 单行发送通知业务部门(企微),成功后行级锁定。 + + 用途与触发时机:生管在行内点「发送通知业务部门」(该行已有批次且未锁定时可用)。 + + 参数与输出约束:无 body;无批次 422(请先回复交期)、已锁定 409、业务员对不上 + User.employee_id 或企微发送失败 503(该行不锁定);成功返回 + locked=true 与交期回复人员(生管工号+姓名)、通知时间、trace_id。 + """ + user = _require_manage() + data = notify_service.notify_line(order_no, line_no, user) + return ok(data, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.post("/batch-reply") +def batch_reply(): + """ + 联合回复交期:对勾选多行逐行保存批次(只保存,不通知、不锁定)。 + + 用途与触发时机:勾选多行 →「+ 联合回复交期」→ 按行填批次 → 保存回复(R-REPLY-02)。 + + 参数与输出约束:body {"items": [{order_no, line_no, batches: [{planned_date, qty, remark?}]}]}, + 单次 ≤ 200 行;每行各批次合计必须等于订单数量(不等该行失败,2026-09-23 修订); + 单行失败不回滚其它行,响应按行给 ok/error; + 全部行保存成功 success 才为 true 语义由 data.succeeded/failed 表达。 + """ + user = _require_manage() + payload = request.get_json(silent=True) or {} + data = reply_service.batch_reply(payload.get("items"), user.id) + return ok(data, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.post("/notify-batch") +def notify_batch(): + """ + 批量通知:对勾选中「已有批次且未锁定」的行逐行发送企微通知并锁定。 + + 用途与触发时机:勾选多行 → 工具栏「批量通知」(R-NOTIFY-02);与联合回复是两个独立操作。 + + 参数与输出约束:body {"lines": [{order_no, line_no}]},单次 ≤ 200 行; + 无批次或已锁定的勾选行 skipped(带 reason)不计成败; + 单行失败不回滚其它行;返回 succeeded/failed/skipped 与逐行结果。 + """ + user = _require_manage() + payload = request.get_json(silent=True) or {} + data = notify_service.notify_batch(payload.get("lines"), user) + return ok(data, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.get("/sync/latest") +def latest_sync(): + """ + 最近一次同步运行记录,供页面展示同步时间与结果。 + + 参数与输出约束:无参数;从未同步过时 data 为 null(前端展示「尚未同步」), + 失败时返回 failed 状态与错误摘要,前端明示同步失败并保留上次快照口径。 + """ + _require_access() + run = OrderDeliverySyncService.latest_run() + if run is None: + return ok(None, request_id=getattr(g, "request_id", None)) + return ok( + { + "id": run.id, + "trigger": run.trigger, + "status": run.status, + "started_at": _utc_to_shanghai(run.started_at), + "finished_at": _utc_to_shanghai(run.finished_at), + "line_count": run.line_count, + "error_message": run.error_message, + }, + request_id=getattr(g, "request_id", None), + ) + + +@order_delivery_reply_bp.post("/sync") +def run_sync(): + """ + 手动触发一次 ERP 全量同步(范围与 07:00 排程完全一致)。 + + 用途与触发时机:生管在工作台点「手动刷新」(需求 §15);同步互斥——排程正在跑时 + 返回 skipped,不并发执行。 + + 参数与输出约束:无 body;同步在本请求内同步执行(一期口径,行量在万级内可控), + 返回 {run_id, status: success|skipped, line_count};失败原样抛 AppError + (上次快照保留,页面明示失败原因)。 + """ + _require_manage() + data = OrderDeliverySyncService.run_sync(trigger="manual") + return ok(data, request_id=getattr(g, "request_id", None)) + + +@order_delivery_reply_bp.post("/admin/permissions/grant-by-department") +def grant_permissions_by_department(): + """ + 按部门批量发放订单交期回复功能权限(可选能力,仅 admin)。 + + 用途与触发时机:用户量大时管理员选部门一次性把勾选写到当时该部门成员账号上(需求 §3)。 + + 参数与输出约束:body {"department": "<部门名>", "permission": "manage" | "access"}; + 这是一次性发放——调岗后权限不随部门字段变化自动增减,需再勾或再跑一次; + 只做授予(置 true),不撤销;返回 {"department", "permission", "granted"}。 + 部门无成员时 granted=0,不视为错误。 + """ + user = _require_user() + if getattr(user, "role", None) != "admin": + raise ForbiddenError( + "Admin privilege required for department permission grant", + code="ORDER_DELIVERY_REPLY.ADMIN_REQUIRED", + ) + payload = request.get_json(silent=True) or {} + department = str(payload.get("department") or "").strip() + permission = str(payload.get("permission") or "").strip() + if not department: + raise ValidationError("department 必填", code="ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED") + if permission not in (PERMISSION_MANAGE, PERMISSION_ACCESS): + raise ValidationError("permission 须为 manage 或 access", code="ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID") + + members = User.query.filter(User.department == department).all() + granted = 0 + for member in members: + # [STEP] 经 set_feature_permissions 归一化:只持久化与角色默认不同的覆盖项。 + raw = dict(member.feature_permissions) if isinstance(member.feature_permissions, dict) else {} + raw[permission] = True + member.set_feature_permissions(raw) + granted += 1 + db.session.commit() + return ok( + {"department": department, "permission": permission, "granted": granted}, + request_id=getattr(g, "request_id", None), + ) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index dcee3d6b..743c1f54 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -499,7 +499,7 @@ class Config: WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL') WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true' WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL') - WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines') + WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines') # 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/)。 # 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent # (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」); @@ -553,6 +553,13 @@ class Config: SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true' SCHEDULE_WORKER_POLL_SECONDS = float(os.getenv('SCHEDULE_WORKER_POLL_SECONDS', '30') or '30') SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS', '7200') or '7200') + # Web 进程内排程兜底扫描:仅本地开发(ENV_NAME=dev,无 schedule-worker 容器)默认开启; + # test/prod 由 hxops-schedule-worker 容器负责(run.py 固定走 DevelopmentConfig,不能按配置类判定)。 + _scanner_env_raw = str(os.getenv('SCHEDULE_WEB_SCANNER_ENABLED') or '').strip().lower() + if _scanner_env_raw: + SCHEDULE_WEB_SCANNER_ENABLED = _scanner_env_raw in ('1', 'true', 'yes', 'on') + else: + SCHEDULE_WEB_SCANNER_ENABLED = _normalize_env_name(os.getenv('ENV_NAME') or ACTIVE_ENV_NAME) == 'dev' # Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。 SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip() SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '') @@ -778,6 +785,7 @@ class TestingConfig(Config): WTF_CSRF_ENABLED = False SQLALCHEMY_ENGINE_OPTIONS = {} SCHEDULE_WORKER_ENABLED = False + SCHEDULE_WEB_SCANNER_ENABLED = False FIXED_ASSETS_SYNC_ENABLED = False FIXED_ASSETS_EXPORT_TO_DOCS = False ENV_NAME = 'dev' diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 7062b255..1af4e837 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -238,6 +238,13 @@ from app.models.contract_payment import ( ContractPaymentSyncState, ContractPaymentVendorRequest, ) +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryBatch, + OrderDeliveryErpLine, + OrderDeliveryLineState, + OrderDeliverySyncRun, +) from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit __all__ = [ @@ -440,4 +447,9 @@ __all__ = [ 'IntegrationInterfaceDefinition', 'IntegrationBinding', 'IntegrationCall', + 'OrderDeliveryErpLine', + 'OrderDeliveryBatch', + 'OrderDeliveryLineState', + 'OrderDeliveryAuditEvent', + 'OrderDeliverySyncRun', ] diff --git a/backend/app/models/order_delivery_reply.py b/backend/app/models/order_delivery_reply.py new file mode 100644 index 00000000..3676d213 --- /dev/null +++ b/backend/app/models/order_delivery_reply.py @@ -0,0 +1,146 @@ +""" +backend/app/models/order_delivery_reply.py + +用途:订单交期回复域模型,保存 ERP 订单行快照、交期批次、行级锁定状态、审计与同步运行记录。 +依赖:models.base.Base、users。 +逻辑:同步服务只写 erp_lines 的 ERP 快照列;保存回复只写 batches;通知成功路径才写 + line_states.locked;audit_events 记录保存/通知/锁定/同步;sync_runs 记录每次同步。 + 工作台所有读取只打本地库,禁止回写 ERP。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from decimal import Decimal +from typing import Any, Optional + +from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, JSON, Numeric, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class OrderDeliveryErpLine(Base): + """ERP 销售订单行快照(订单单号+项次唯一);仅同步服务写入 ERP 列,不覆盖批次与锁定。""" + + __tablename__ = "order_delivery_erp_lines" + __table_args__ = ( + UniqueConstraint("order_no", "line_no", name="uq_order_delivery_erp_lines_order_line"), + Index("ix_order_delivery_erp_lines_order_date", "order_date"), + Index("ix_order_delivery_erp_lines_customer_no", "customer_no"), + Index("ix_order_delivery_erp_lines_salesperson", "salesperson_code"), + Index("ix_order_delivery_erp_lines_slip_code", "slip_code"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + order_no: Mapped[str] = mapped_column(String(64), nullable=False) + line_no: Mapped[int] = mapped_column(nullable=False) + order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + customer_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + customer_short_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + customer_full_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + # salesperson_code 对 HXOPS User.employee_id,供企微收件人映射;列表展示 salesperson_name。 + salesperson_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + salesperson_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + dept_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + dept_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + customer_po: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + part_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + spec: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + customer_part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + agreed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True) + delivered_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True) + # 单别取 oea01 连字符前段(8301-1605280014 → 8301);一期只落库预留,不展示不过滤。 + slip_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + # 本轮同步未命中但已有批次或锁定的行不删除,置 true 后默认列表不展示。 + erp_missing: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True) + last_synced_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + +class OrderDeliveryBatch(Base): + """订单行的交期批次(计划交期+数量+备注);未锁定行保存时整表替换。仅保存回复路径写入。""" + + __tablename__ = "order_delivery_batches" + __table_args__ = ( + UniqueConstraint("line_id", "seq", name="uq_order_delivery_batches_line_seq"), + Index("ix_order_delivery_batches_line", "line_id"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + line_id: Mapped[int] = mapped_column( + ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False + ) + seq: Mapped[int] = mapped_column(nullable=False) + planned_date: Mapped[date] = mapped_column(Date, nullable=False) + qty: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False) + # 备注 ≤ 200 字符,由 API 层校验。 + remark: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + +class OrderDeliveryLineState(Base): + """订单行锁定状态(一行一态);仅通知成功路径写入 locked=true,与通知同一事务。""" + + __tablename__ = "order_delivery_line_states" + __table_args__ = ( + UniqueConstraint("line_id", name="uq_order_delivery_line_states_line"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + line_id: Mapped[int] = mapped_column( + ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False + ) + locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) + # 交期回复人员 = 最近一次发送成功的生管;存快照工号+姓名便于审计回溯。 + notified_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) + notified_employee_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + notified_user_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + +class OrderDeliveryAuditEvent(Base): + """订单交期回复审计:保存批次、发送通知、锁定、同步、出货提醒、未回复提醒六类动作。""" + + __tablename__ = "order_delivery_audit_events" + __table_args__ = ( + Index("ix_order_delivery_audit_events_line", "line_id"), + Index("ix_order_delivery_audit_events_action", "action", "created_at"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + # sync 事件无具体行时 line_id 为空。 + line_id: Mapped[Optional[int]] = mapped_column( + ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=True + ) + order_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + line_no: Mapped[Optional[int]] = mapped_column(nullable=True) + # save | notify | lock | sync | ship_remind(出货提醒,payload.ok=true 参与去重)| unreplied_remind(未回复再提醒) + action: Mapped[str] = mapped_column(String(32), nullable=False) + operator_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True) + payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class OrderDeliverySyncRun(Base): + """订单交期同步运行记录;同步作业每次运行写一行,失败保留上次快照。""" + + __tablename__ = "order_delivery_sync_runs" + __table_args__ = ( + Index("ix_order_delivery_sync_runs_started", "started_at"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + trigger: Mapped[str] = mapped_column(String(16), nullable=False) # scheduled | manual + status: Mapped[str] = mapped_column(String(16), nullable=False) # running | success | failed + started_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + line_count: Mapped[int] = mapped_column(default=0, nullable=False) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) diff --git a/backend/app/models/user.py b/backend/app/models/user.py index 40bbd909..9316054b 100644 --- a/backend/app/models/user.py +++ b/backend/app/models/user.py @@ -100,6 +100,11 @@ class User(Base): 'shipping_notice.xfa_split_rule_preview': admin, 'shipping_notice.xfa_split_rule_publish': admin, 'maintenance.ledger_write': admin, + # 合同付款预警已改走 Agent 授权(agent_code=contract_payment),不再占用功能权限键。 + # 订单交期回复:manage=生管可写(保存/通知/同步),access=业务只读; + # manage 命中视为有 access(判定见 api/order_delivery_reply.py)。 + 'order_delivery_reply.manage': admin, + 'order_delivery_reply.access': admin, } def is_platform_admin(self) -> bool: diff --git a/backend/app/services/admin/training_exam_pdf_service.py b/backend/app/services/admin/training_exam_pdf_service.py index 8530167a..6f3cc27c 100644 --- a/backend/app/services/admin/training_exam_pdf_service.py +++ b/backend/app/services/admin/training_exam_pdf_service.py @@ -228,10 +228,10 @@ def _section_type_for_line(line: str) -> str | None: def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]: - """提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。""" + """提取 PDF 后半段按小节重复出现的填空/判断标准答案,避免把答案行当作新题目。""" occurrences: dict[str, int] = {} active_type: str | None = None - answers: dict[str, list[str]] = {'fill': []} + answers: dict[str, list[str]] = {'fill': [], 'boolean': []} in_answer_sheet = False for line in lines: if _is_answer_section_heading(line): @@ -241,17 +241,34 @@ def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]: section_type = _section_type_for_line(line) if section_type: occurrences[section_type] = occurrences.get(section_type, 0) + 1 - if occurrences[section_type] > 1: - in_answer_sheet = True - active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None + repeated = occurrences[section_type] > 1 + in_answer_sheet = in_answer_sheet or repeated + active_type = section_type if (repeated or in_answer_sheet) else None + # 小节标题行自带答案内容(如「二、判断题:1-2、√ ×」):去掉标题前缀后按判断答案表解析 + if in_answer_sheet and section_type == 'boolean': + remainder = _BOOLEAN_SECTION_PATTERN.sub('', _normalize_spaces(line), count=1) + remainder = remainder.lstrip('一二三四五六七八九十、..::\t (()) ') + if remainder and not _QUESTION_START_PATTERN.match(remainder): + for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(remainder): + answer = _normalize_answer_token(raw_token) + if answer: + answers['boolean'].append(answer) continue - if not in_answer_sheet or active_type != 'fill': + if not in_answer_sheet or active_type not in {'fill', 'boolean'}: continue match = _QUESTION_START_PATTERN.match(line) - if match: - value = _normalize_spaces(match.group(2)) - if value: - answers['fill'].append(value) + if not match: + continue + value = _normalize_spaces(match.group(2)) + if not value: + continue + if active_type == 'fill': + answers['fill'].append(value) + elif ' ' not in value: + # 判断答案行只接受整行单 token(如「1、√」);带空格的多题答案表交由题号映射解析 + answer = _normalize_answer_token(value) + if answer: + answers['boolean'].append(answer) return answers @@ -320,11 +337,12 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None] continue if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')): continue - if _is_answer_sheet_line(line): - continue + # 题干匹配必须先于答案表过滤:行内答案题干(如「1. 题干… 答案:C 解析:…」)整行含「答案」, + # 若先走答案表过滤会被整体丢弃导致整卷解析为空(2026-09-29 修复,原顺序该分支为死代码)。 question_match = _QUESTION_START_PATTERN.match(line) if question_match: if _is_answer_sheet_line(line) and '答案' not in line: + # 疑似答案表行(如「1.B 2.A 3.正确」)即使形如题干也不生成题目 continue if current_no is not None and current_lines: blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type)) @@ -480,6 +498,7 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]: question_bank: list[dict[str, Any]] = [] skipped_questions: list[int] = [] fill_answer_index = 0 + boolean_answer_index = 0 # [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。 answer_sequence_index = 0 @@ -497,6 +516,17 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]: mapped_answer=answer_map.get(question_no, ''), ordered_answer=ordered_answer, ) + if section_type == 'boolean': + # 分节重复答案区(如「二、判断题 1、√」「二、判断题:1-2、√ ×」)提取到的判断答案 + # 作为兜底候选补入;内联/题号映射/整卷顺序命中时仍优先。 + repeated_answer = ( + repeated_section_answers['boolean'][boolean_answer_index] + if boolean_answer_index < len(repeated_section_answers['boolean']) + else '' + ) + boolean_answer_index += 1 + if repeated_answer and repeated_answer not in answer_candidates: + answer_candidates.append(repeated_answer) if section_type == 'boolean': for answer in answer_candidates: question_payload = _build_boolean_question( diff --git a/backend/app/services/order_delivery_reply/__init__.py b/backend/app/services/order_delivery_reply/__init__.py new file mode 100644 index 00000000..0aa4b9e4 --- /dev/null +++ b/backend/app/services/order_delivery_reply/__init__.py @@ -0,0 +1,13 @@ +""" +backend/app/services/order_delivery_reply/__init__.py + +用途:订单交期回复域服务包入口;聚合导出同步服务与 SQL 常量。 +依赖:本包 sql / sync_service。 +逻辑:API 层(app/api/order_delivery_reply.py)与排程种子经此包调用同步;scripts/order_delivery_query.py + 复用 ORDER_DELIVERY_SQL 保持取数口径一致。 +""" + +from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL +from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService + +__all__ = ["ORDER_DELIVERY_SQL", "OrderDeliverySyncService"] diff --git a/backend/app/services/order_delivery_reply/app_seed.py b/backend/app/services/order_delivery_reply/app_seed.py new file mode 100644 index 00000000..6fd3d29e --- /dev/null +++ b/backend/app/services/order_delivery_reply/app_seed.py @@ -0,0 +1,57 @@ +""" +backend/app/services/order_delivery_reply/app_seed.py + +用途:把「订单交期回复」注册为应用管理中的内置 iframe 应用(不接 Dify)。 +依赖:models.Agent;启动时由 app/__init__.py 幂等调用。 +逻辑:按 agent_code 幂等创建一条 runtime_provider='iframe' 的 Agent 记录, + iframe_url 指向前端免布局嵌入路由 /apps/order-delivery-reply; + 在聊天壳内整页渲染工作台操作页。应用的可见性走 Agent 权限 + (admin 自动可见,普通用户在用户管理授权);页面与 API 仍由 + order_delivery_reply.access/manage 功能权限守卫,两层各司其职。 + 管理员可在应用管理中修改名称/描述/图标/排序,但不应把 + runtime_provider 改回 dify(本应用没有 Dify 绑定)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.models import Agent + +ORDER_DELIVERY_AGENT_CODE = 'order_delivery_reply' +ORDER_DELIVERY_IFRAME_URL = '/apps/order-delivery-reply' + + +def ensure_builtin_order_delivery_agent(*, commit: bool = True): + """ + 幂等创建订单交期回复内置应用(iframe 型,非 Dify)。 + + Args: + commit: 是否提交;测试或外层事务可传 False。 + Returns: + 新建的 Agent;已存在时返回 None。 + """ + existing = Agent.query.filter_by(agent_code=ORDER_DELIVERY_AGENT_CODE).first() + if existing: + return None + agent = Agent( + name='订单交期回复', + description='查单 → 填交期 → 通知业务员;ERP 订单交期回复工作台', + agent_code=ORDER_DELIVERY_AGENT_CODE, + runtime_provider='iframe', + conversation_mode='embedded', + iframe_url=ORDER_DELIVERY_IFRAME_URL, + dify_app_id=None, + dify_api_key=None, + is_active=True, + category='业务应用', + sort_order=0, + created_at=datetime.utcnow(), + ) + db.session.add(agent) + if commit: + db.session.commit() + else: + db.session.flush() + return agent diff --git a/backend/app/services/order_delivery_reply/notify_service.py b/backend/app/services/order_delivery_reply/notify_service.py new file mode 100644 index 00000000..7f19a116 --- /dev/null +++ b/backend/app/services/order_delivery_reply/notify_service.py @@ -0,0 +1,281 @@ +""" +backend/app/services/order_delivery_reply/notify_service.py + +用途:订单交期回复的通知与锁定——按行通知订单业务员(企微)、成功后行级锁定并留痕。 +依赖:wecom_notify.send_wecom_event_message(平台统一 textcard,本域只传业务参数)、 + models/order_delivery_reply、models.User(employee_id → wecom_userid 映射)、extensions.db。 +逻辑:发送成功与 locked=true 在同一事务提交(禁止「已通知未锁定」);失败不锁定; + 收件人是订单业务员(oea14 → User.employee_id),与操作人(生管)无关; + 交期回复人员 = 最近一次发送成功的生管工号+姓名(R-NOTIFY-03)。 + 批量通知(第 5 步)逐行复用本模块,单行失败不回滚其它行。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from sqlalchemy import select + +from app.core.errors import ( + ConflictError, + NotFoundError, + ServiceUnavailableError, + ValidationError, +) +from app.extensions import db +from app.models import User +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryBatch, + OrderDeliveryErpLine, + OrderDeliveryLineState, +) +from app.services.integrations.wecom.notify import send_wecom_event_message + +# 企微事件开关名;与 settings.WECOM_NOTIFY_EVENTS 默认值条目一致(同 contract_payment_warning 命名风格)。 +WECOM_EVENT_TYPE = "order_delivery_reply_notify" +# 工作台跳转路由(前端第 8 步落地,带上该行查询参数直开行)。 +JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏 + + +def _load_line(order_no: str, line_no: int) -> OrderDeliveryErpLine: + """按行唯一键取未 erp_missing 的快照行;不存在/不在同步范围抛 404。""" + line = db.session.scalar( + select(OrderDeliveryErpLine).where( + OrderDeliveryErpLine.order_no == order_no, + OrderDeliveryErpLine.line_no == line_no, + OrderDeliveryErpLine.erp_missing.is_(False), + ) + ) + if not line: + raise NotFoundError( + "Order delivery line not found", + code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND", + ) + return line + + +def _load_state(line_id: int) -> OrderDeliveryLineState | None: + return db.session.scalar( + select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line_id) + ) + + +def _resolve_recipient(line: OrderDeliveryErpLine) -> User: + """ + 订单业务员 → HXOPS 用户:salesperson_code(oea14) 对 User.employee_id。 + + Returns: + 对应 User。 + Raises: + ServiceUnavailableError: 对不上或账号未绑企微——该行通知失败、不锁定(需求 §13)。 + """ + recipient = db.session.scalar( + select(User).where(User.employee_id == (line.salesperson_code or "").strip()) + ) + if recipient is None or not (recipient.wecom_userid or "").strip(): + raise ServiceUnavailableError( + f"业务员工号 {line.salesperson_code} 未关联 HXOPS 用户或未绑定企微,无法通知", + code="ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED", + ) + return recipient + + +def _send_line_notification(line: OrderDeliveryErpLine, recipient: User) -> dict[str, Any]: + """ + 调平台既有 send_wecom_event_message 发送单行通知(textcard 壳、按钮、回执全用现成实现)。 + + 参数与输出约束:content 按需求 §13 固定文案;jump_params 带该行唯一键供企微直达; + 返回 {ok, trace_id, ...},成败以函数返回为准(回执只留痕不改状态)。 + """ + return send_wecom_event_message( + event_type=WECOM_EVENT_TYPE, + user=recipient, + title="订单交期回复", + content=f"您有订单号:项次{line.order_no}:{line.line_no}的订单需要填写/确认/查看交期。", + jump_path=JUMP_PATH, + jump_params={"order_no": line.order_no, "line_no": line.line_no}, + ) + + +def notify_line(order_no: str, line_no: int, operator: User) -> dict[str, Any]: + """ + 单行通知 + 锁定 + 审计(行内「发送通知业务部门」入口)。 + + 用途与触发时机:生管在行内点「发送通知业务部门」;AI/排程不触发。 + 批量通知逐行复用本函数,外层保证单行失败不影响其它行。 + + 核心逻辑:[STEP 1] 行存在校验;无批次 → 422(请先回复交期);已锁定 → 409; + [STEP 2] 解析收件人(订单业务员),对不上 → 该行失败不锁定; + [STEP 3] 发企微;发送失败 → 该行失败不锁定(503 NOTIFY_FAILED); + [STEP 4] 发送成功后同一事务写 locked + 交期回复人员快照 + notify/lock 审计并提交。 + + Args: + order_no / line_no: 行唯一键。 + operator: 操作的生管(HXOPS 用户);交期回复人员取其工号+姓名。 + Returns: + {"order_no", "line_no", "locked": true, "notified_user_name", "notified_at"}。 + """ + # [STEP 1] 前置校验:无批次不能通知;已锁定不能重复通知。 + line = _load_line(order_no, line_no) + state = _load_state(line.id) + if state and state.locked: + raise ConflictError( + "该订单行已通知锁定,无需重复通知", + code="ORDER_DELIVERY_REPLY.LINE_LOCKED", + ) + batch_count = len( + db.session.scalars( + select(OrderDeliveryBatch.id).where(OrderDeliveryBatch.line_id == line.id) + ).all() + ) + if batch_count == 0: + raise ValidationError("请先回复交期再发送通知", code="ORDER_DELIVERY_REPLY.BATCHES_REQUIRED") + + # [STEP 2] 收件人 = 订单业务员,与操作权限无关。 + recipient = _resolve_recipient(line) + + # [STEP 3] 先发送:成败以 send_wecom_event_message 返回为准;失败不写任何锁定状态。 + result = _send_line_notification(line, recipient) + if not result.get("ok"): + raise ServiceUnavailableError( + "企微通知发送失败,该行未锁定", + code="ORDER_DELIVERY_REPLY.NOTIFY_FAILED", + details={"trace_id": result.get("trace_id"), "reason": result.get("reason")}, + ) + + # [STEP 4] 发送成功 → 同一事务锁定 + 快照 + 审计;提交失败会整体回滚(宁可不锁定,禁止已通知未锁定)。 + notified_at = datetime.utcnow() + if state is None: + state = OrderDeliveryLineState(line_id=line.id) + db.session.add(state) + state.locked = True + state.notified_user_id = operator.id + state.notified_employee_id = (operator.employee_id or "").strip() or None + state.notified_user_name = operator.real_name + state.notified_at = notified_at + + db.session.add_all( + [ + OrderDeliveryAuditEvent( + line_id=line.id, + order_no=line.order_no, + line_no=line.line_no, + action="notify", + operator_user_id=operator.id, + payload_json={ + "recipient_employee_id": line.salesperson_code, + "recipient_wecom_userid": recipient.wecom_userid, + "trace_id": result.get("trace_id"), + "notified_at": notified_at.isoformat(), + }, + ), + OrderDeliveryAuditEvent( + line_id=line.id, + order_no=line.order_no, + line_no=line.line_no, + action="lock", + operator_user_id=operator.id, + payload_json={ + "notified_employee_id": state.notified_employee_id, + "notified_user_name": state.notified_user_name, + "notified_at": notified_at.isoformat(), + }, + ), + ] + ) + db.session.commit() + + return { + "order_no": line.order_no, + "line_no": line.line_no, + "locked": True, + "notified_employee_id": state.notified_employee_id, + "notified_user_name": state.notified_user_name, + "notified_at": notified_at.isoformat(), + "wecom_trace_id": result.get("trace_id"), + } + + +def notify_batch(raw_lines: list, operator: User) -> dict[str, Any]: + """ + 批量通知:对勾选行逐行发送通知并锁定(无批次或已锁定的行跳过)。 + + 用途与触发时机:工作台勾选多行后点工具栏「批量通知」(R-NOTIFY-02); + 与「联合回复交期」是两个独立操作,本函数不做任何批次保存。 + + 核心逻辑:[STEP 1] 校验请求结构(非空数组、每项含 order_no/line_no,上限 200); + [STEP 2] 逐行:无批次 → skipped;已锁定 → skipped;其余调 notify_line; + 单行失败不回滚其它行(notify_line 每行独立事务),失败行带原因返回; + [STEP 3] 汇总 succeeded / failed / skipped 与各行结果。 + + Args: + raw_lines: [{"order_no", "line_no"}]。 + operator: 操作的生管(HXOPS 用户)。 + Returns: + {"succeeded": N, "failed": N, "skipped": N, + "items": [{order_no, line_no, ok, skipped?, reason?, data?}]}。 + """ + from app.core.errors import AppError + + if not isinstance(raw_lines, list) or not raw_lines: + raise ValidationError("lines 必须为非空数组", code="ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY") + if len(raw_lines) > 200: + raise ValidationError("单次批量通知行数超过上限 200", code="ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY") + + def _key(item: dict) -> tuple[str, int] | None: + try: + order_no = str(item.get("order_no") or "").strip() + line_no = int(item.get("line_no")) + return (order_no, line_no) if order_no else None + except (TypeError, ValueError): + return None + + results: list[dict[str, Any]] = [] + for item in raw_lines: + if not isinstance(item, dict): + results.append({"ok": False, "error": "行格式不合法"}) + continue + key = _key(item) + if key is None: + results.append({"ok": False, "error": "行唯一键缺失或格式不合法"}) + continue + order_no, line_no = key + + # [STEP 2] 跳过语义:无批次(不能通知)/ 已锁定(无需重复通知)不计入成败。 + line = db.session.scalar( + select(OrderDeliveryErpLine).where( + OrderDeliveryErpLine.order_no == order_no, + OrderDeliveryErpLine.line_no == line_no, + OrderDeliveryErpLine.erp_missing.is_(False), + ) + ) + if line is None: + results.append({"order_no": order_no, "line_no": line_no, "ok": False, "error": "订单行不存在"}) + continue + state = _load_state(line.id) + if state and state.locked: + results.append({"order_no": order_no, "line_no": line_no, "ok": True, "skipped": True, "reason": "already_locked"}) + continue + has_batch = db.session.scalar( + select(OrderDeliveryBatch.id).where(OrderDeliveryBatch.line_id == line.id).limit(1) + ) + if has_batch is None: + results.append({"order_no": order_no, "line_no": line_no, "ok": True, "skipped": True, "reason": "no_batches"}) + continue + + try: + data = notify_line(order_no, line_no, operator) + results.append({"order_no": order_no, "line_no": line_no, "ok": True, "data": data}) + except AppError as exc: + # 单行失败不回滚其它行:notify_line 内部已按行提交或未写入。 + db.session.rollback() + results.append({"order_no": order_no, "line_no": line_no, "ok": False, "error": exc.message}) + + return { + "succeeded": sum(1 for r in results if r.get("ok") and not r.get("skipped")), + "failed": sum(1 for r in results if not r.get("ok")), + "skipped": sum(1 for r in results if r.get("skipped")), + "items": results, + } diff --git a/backend/app/services/order_delivery_reply/query_service.py b/backend/app/services/order_delivery_reply/query_service.py new file mode 100644 index 00000000..96737e82 --- /dev/null +++ b/backend/app/services/order_delivery_reply/query_service.py @@ -0,0 +1,320 @@ +""" +backend/app/services/order_delivery_reply/query_service.py + +用途:订单交期回复工作台只读查询——列表筛选分页、单行详情、状态推导与序列化。 +依赖:models/order_delivery_reply(快照/批次/状态)、extensions.db。 +逻辑:所有读取只打本地快照;行状态为读时推导(无批次=未回复,有批次未锁定=部分回复, + 已锁定=已回复),筛选「已回复/未完全回复」据此下推到 SQL;erp_missing 行一律不返回。 + 本服务不做任何写操作,也不访问 ERP。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from decimal import Decimal +from typing import Any + +from sqlalchemy import Select, func, or_, select + +from app.extensions import db +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryBatch, + OrderDeliveryErpLine, + OrderDeliveryLineState, +) + +# 状态筛选合法值:空/None = 全部。 +STATUS_FILTER_VALUES = {"replied", "not_fully_replied"} + +DEFAULT_PAGE_SIZE = 50 +MAX_PAGE_SIZE = 200 + + +def _utc_to_shanghai(value) -> str | None: + """naive-UTC 时间转北京时间展示串;仅用于序列化,详情见 api 层同名 helper 注释。""" + from datetime import timezone + from zoneinfo import ZoneInfo + + if value is None: + return None + try: + return value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).strftime("%Y-%m-%d %H:%M:%S") + except (AttributeError, ValueError): + return value.isoformat() if hasattr(value, "isoformat") else str(value) + + +def _dec_str(value: Decimal | None) -> str | None: + """ + Numeric 序列化为去尾零的十进制字符串(80.0000 → "80",7.5000 → "7.5")。 + + 用途:数量/未交数量展示;Postgres Numeric 保留列 scale,直接 str() 会带多余尾零。 + 约束:仅用于展示序列化,不改变库内精度。 + """ + if value is None: + return None + text = format(value, "f") + if "." in text: + text = text.rstrip("0").rstrip(".") + return text or "0" + + +def _has_batch_subquery(): + """该订单行是否已存在交期批次的 EXISTS 子查询(状态推导用)。""" + return select(OrderDeliveryBatch.line_id).where(OrderDeliveryBatch.line_id == OrderDeliveryErpLine.id).exists() + + +def _locked_subquery(): + """该订单行是否已通知锁定的 EXISTS 子查询(状态推导用)。""" + return ( + select(OrderDeliveryLineState.line_id) + .where( + OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id, + OrderDeliveryLineState.locked.is_(True), + ) + .exists() + ) + + +def _reply_person_subquery(like: str): + """该订单行的交期回复人员(姓名/工号,存于行状态快照)命中关键词的 EXISTS 子查询。""" + return ( + select(OrderDeliveryLineState.line_id) + .where( + OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id, + or_( + OrderDeliveryLineState.notified_user_name.ilike(like), + OrderDeliveryLineState.notified_employee_id.ilike(like), + ), + ) + .exists() + ) + + +def _base_query() -> Select: + """列表基础查询:只取未标 erp_missing 的已同步行(默认列表不展示已不在同步范围的行)。""" + return select(OrderDeliveryErpLine).where(OrderDeliveryErpLine.erp_missing.is_(False)) + + +def _apply_filters(stmt: Select, params: dict[str, Any]) -> Select: + """ + 应用列表筛选(AND 语义)与状态筛选下推。 + + 核心逻辑:keyword 关键词合并搜索——订单单号/客户订单/客户编号/客户简称/公司全名/ + 产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号, + 2026-09-23 增补,按行状态快照 EXISTS)命中任一字段即返回(OR,工作台单搜索框口径); + order_date 精确单日;status=replied → 已锁定, + status=not_fully_replied → 未锁定(未回复∪部分回复)。 + """ + keyword = str(params.get("keyword") or "").strip() + if keyword: + like = f"%{keyword}%" + stmt = stmt.where( + or_( + OrderDeliveryErpLine.order_no.ilike(like), + OrderDeliveryErpLine.customer_po.ilike(like), + OrderDeliveryErpLine.customer_no.ilike(like), + OrderDeliveryErpLine.customer_short_name.ilike(like), + OrderDeliveryErpLine.customer_full_name.ilike(like), + OrderDeliveryErpLine.part_no.ilike(like), + OrderDeliveryErpLine.part_name.ilike(like), + OrderDeliveryErpLine.customer_part_no.ilike(like), + OrderDeliveryErpLine.salesperson_name.ilike(like), + OrderDeliveryErpLine.salesperson_code.ilike(like), + _reply_person_subquery(like), + ) + ) + + order_date_raw = params.get("order_date") + if order_date_raw: + parsed = _parse_date(order_date_raw) + if parsed is None: + from app.core.errors import ValidationError + + raise ValidationError("订单日期格式须为 YYYY-MM-DD") + stmt = stmt.where(OrderDeliveryErpLine.order_date == parsed) + + status = (params.get("status") or "").strip() + if status and status not in STATUS_FILTER_VALUES: + from app.core.errors import ValidationError + + raise ValidationError(f"不支持的状态筛选:{status}") + if status == "replied": + stmt = stmt.where(_locked_subquery()) + elif status == "not_fully_replied": + # 未完全回复 = 未回复 ∪ 部分回复,统一口径为「尚未通知锁定」。 + stmt = stmt.where(~_locked_subquery()) + + return stmt + + +def _parse_date(raw: Any) -> date | None: + """解析 YYYY-MM-DD 单日;非法返回 None(由调用方决定是否报错)。""" + if isinstance(raw, date) and not isinstance(raw, datetime): + return raw + try: + return date.fromisoformat(str(raw)) + except (TypeError, ValueError): + return None + + +def _serialize_line( + line: OrderDeliveryErpLine, + batches: list[OrderDeliveryBatch], + state: OrderDeliveryLineState | None, +) -> dict[str, Any]: + """ + 序列化一行工作台列表/详情数据。 + + 核心逻辑:行状态读时推导(见模块 docstring);未交数量 = 数量 − 已交数量(None 当 0), + 只做展示派生,不落库;不输出 slip_code(一期列表不出单别列)。 + """ + locked = bool(state and state.locked) + if locked: + status = "replied" + elif batches: + status = "partial_replied" + else: + status = "not_replied" + + qty = line.qty or Decimal(0) + delivered = line.delivered_qty or Decimal(0) + + return { + "id": line.id, + "order_no": line.order_no, + "line_no": line.line_no, + "order_date": line.order_date.isoformat() if line.order_date else None, + "customer_no": line.customer_no, + "customer_short_name": line.customer_short_name, + "customer_full_name": line.customer_full_name, + "salesperson_code": line.salesperson_code, + "salesperson_name": line.salesperson_name, + "dept_code": line.dept_code, + "dept_name": line.dept_name, + "customer_po": line.customer_po, + "part_no": line.part_no, + "part_name": line.part_name, + "spec": line.spec, + "customer_part_no": line.customer_part_no, + "agreed_date": line.agreed_date.isoformat() if line.agreed_date else None, + "unit": line.unit, + "qty": _dec_str(line.qty), + "delivered_qty": _dec_str(line.delivered_qty), + "undelivered_qty": _dec_str(qty - delivered), + "status": status, + "locked": locked, + "batches": [ + { + "seq": batch.seq, + "planned_date": batch.planned_date.isoformat() if batch.planned_date else None, + "qty": _dec_str(batch.qty), + "remark": batch.remark, + } + for batch in batches + ], + "notified_employee_id": state.notified_employee_id if state else None, + "notified_user_name": state.notified_user_name if state else None, + "notified_at": _utc_to_shanghai(state.notified_at if state else None), + } + + +def list_lines(params: dict[str, Any]) -> dict[str, Any]: + """ + 订单行列表查询(筛选 + 分页 + 默认排序)。 + + 用途与触发时机:GET /api/order-delivery-reply/lines 的服务层实现;工作台首屏与筛选刷新。 + + 核心逻辑:[STEP 1] 组装基础查询(排除 erp_missing)并应用筛选; + [STEP 2] count 总数后按默认排序分页取本页行; + [STEP 3] 批量预取本页行的批次与锁定状态,避免 N+1,再逐行序列化。 + + Args: + params: keyword / order_date / status / page / page_size。 + Returns: + {"items": [...], "page", "page_size", "total"};items 含批次与状态(见 _serialize_line)。 + """ + stmt = _apply_filters(_base_query(), params) + + total = db.session.scalar(select(func.count()).select_from(stmt.subquery())) + + try: + page = max(int(params.get("page") or 1), 1) + page_size = min(max(int(params.get("page_size") or DEFAULT_PAGE_SIZE), 1), MAX_PAGE_SIZE) + except (TypeError, ValueError): + from app.core.errors import ValidationError + + raise ValidationError("分页参数须为整数") + + stmt = stmt.order_by( + OrderDeliveryErpLine.order_date.asc(), + OrderDeliveryErpLine.customer_no.asc(), + OrderDeliveryErpLine.order_no.asc(), + OrderDeliveryErpLine.line_no.asc(), + OrderDeliveryErpLine.part_no.asc(), + ).limit(page_size).offset((page - 1) * page_size) + + lines = list(db.session.scalars(stmt).all()) + line_ids = [line.id for line in lines] + + batches_by_line: dict[int, list[OrderDeliveryBatch]] = {} + states_by_line: dict[int, OrderDeliveryLineState] = {} + if line_ids: + for batch in db.session.scalars( + select(OrderDeliveryBatch) + .where(OrderDeliveryBatch.line_id.in_(line_ids)) + .order_by(OrderDeliveryBatch.line_id, OrderDeliveryBatch.seq) + ).all(): + batches_by_line.setdefault(batch.line_id, []).append(batch) + for state in db.session.scalars( + select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id.in_(line_ids)) + ).all(): + states_by_line[state.line_id] = state + + items = [ + _serialize_line(line, batches_by_line.get(line.id, []), states_by_line.get(line.id)) + for line in lines + ] + return {"items": items, "page": page, "page_size": page_size, "total": total or 0} + + +def get_line(order_no: str, line_no: int) -> dict[str, Any] | None: + """ + 单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。 + + Args: + order_no / line_no: 行唯一键;erp_missing 行按不存在处理(返回 None → API 404)。 + Returns: + 序列化 dict;不存在或已不在同步范围返回 None。 + """ + line = db.session.scalar( + _base_query().where( + OrderDeliveryErpLine.order_no == order_no, + OrderDeliveryErpLine.line_no == line_no, + ) + ) + if not line: + return None + + batches = list( + db.session.scalars( + select(OrderDeliveryBatch).where(OrderDeliveryBatch.line_id == line.id).order_by(OrderDeliveryBatch.seq) + ).all() + ) + state = db.session.scalar(select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line.id)) + + payload = _serialize_line(line, batches, state) + payload["audit_events"] = [ + { + "action": event.action, + "operator_user_id": event.operator_user_id, + "payload_json": event.payload_json, + "created_at": _utc_to_shanghai(event.created_at), + } + for event in db.session.scalars( + select(OrderDeliveryAuditEvent) + .where(OrderDeliveryAuditEvent.line_id == line.id) + .order_by(OrderDeliveryAuditEvent.created_at.desc()) + ).all() + ] + return payload diff --git a/backend/app/services/order_delivery_reply/reminder_service.py b/backend/app/services/order_delivery_reply/reminder_service.py new file mode 100644 index 00000000..2e0a17ff --- /dev/null +++ b/backend/app/services/order_delivery_reply/reminder_service.py @@ -0,0 +1,362 @@ +""" +backend/app/services/order_delivery_reply/reminder_service.py + +用途:订单交期回复的定时提醒扫描——已回复行按回复交期提前 N 天提醒业务员出货; + 未回复行超过 N 天再次提醒生管。由排程 order-delivery-remind(日批)调用。 +依赖:models/order_delivery_reply(快照/批次/锁定/审计)、models.User(工号 → 企微映射)、 + wecom_notify.send_wecom_event_message、services/schedule/timezone_util(北京时区业务日)。 +逻辑:[出货提醒] 已锁定(已回复)行的批次 planned_date 落在 [今天, 今天+N] 时,按业务员聚合 + 发一条企微;同一 (行, 交期) 只提醒一次(audit_events action=ship_remind 去重),发送失败 + 不落成功记录,次日扫描自动补发。 + [未回复提醒] 未锁定行的订单日期(order_date,取 ERP oea02)距今 ≥ N 天时再次提醒生管 + (收件人 = 任务参数 unreplied_remind_user_ids,留空回退任务通知人),同一行每 N 天最多 + 提醒一次(action=unreplied_remind 去重),多行聚合成一条通知避免刷屏。 + 提醒只读业务数据 + 写审计,绝不改动批次/锁定状态。 + (2026-09-23 修订:超期锚点由快照首次入库 created_at 改为订单日期,按业务确认以订单日期计超期。) +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +from sqlalchemy import select +from zoneinfo import ZoneInfo + +from app.extensions import db +from app.models import User +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryBatch, + OrderDeliveryErpLine, + OrderDeliveryLineState, +) +from app.services.integrations.wecom.notify import send_wecom_event_message + +# 企微事件开关名:与行级通知共用同一事件(WECOM_NOTIFY_EVENTS 已包含,无需新增配置)。 +WECOM_EVENT_TYPE = "order_delivery_reply_notify" +JUMP_PATH = "/apps/order-delivery-reply" # 免布局嵌入路由:企微内打开不带工作台侧栏 + +# 通知正文最多列出的订单条数;超出的折叠为「…等 N 笔」,避免超出企微卡片描述上限。 +MAX_LISTED_ORDERS = 8 + +# 审计动作名(models.order_delivery_reply.OrderDeliveryAuditEvent.action,String(32))。 +ACTION_SHIP_REMIND = "ship_remind" +ACTION_UNREPLIED_REMIND = "unreplied_remind" + + +def _business_today(): + """北京时间业务日(约定交货日/回复交期都是业务日期,不能拿 UTC 日期比较)。""" + return datetime.now(ZoneInfo("Asia/Shanghai")).date() + + +def _resolve_salesperson_user(salesperson_code: str | None) -> User | None: + """订单业务员工号 → HXOPS 用户(须已绑企微);对不上返回 None,由调用方记录失败。""" + code = (salesperson_code or "").strip() + if not code: + return None + user = db.session.scalar(select(User).where(User.employee_id == code)) + if user is None or not (user.wecom_userid or "").strip(): + return None + return user + + +def _audit_reminded_keys(action: str, since_days: int) -> dict[int, set[str]]: + """ + 读取历史上「发送成功」的已提醒 (line_id → planned_date 集合),供去重。 + + 核心逻辑:只认 payload.ok=true 的审计——发送失败不算已提醒,次日扫描自动补发; + Args: + action: ship_remind(payload 带 planned_date 与 ok)。 + since_days: 只回看最近 N 天的审计(窗口远大于提醒周期,足够去重且避免全表扫描)。 + """ + since = datetime.utcnow() - timedelta(days=since_days) + events = db.session.scalars( + select(OrderDeliveryAuditEvent).where( + OrderDeliveryAuditEvent.action == action, + OrderDeliveryAuditEvent.created_at >= since, + ) + ).all() + reminded: dict[int, set[str]] = {} + for event in events: + payload = event.payload_json if isinstance(event.payload_json, dict) else {} + if payload.get("ok") is not True: + continue + key = str(payload.get("planned_date") or "") + reminded.setdefault(event.line_id or 0, set()).add(key) + return reminded + + +def _last_successful_unreplied_remind_at(since_days: int) -> dict[int, datetime]: + """ + 每行最近一次「发送成功」的未回复提醒时间(控制 N 天一次的再次提醒节奏)。 + + 核心逻辑:只统计 payload.ok=true 的事件;窗口外的旧事件等价于「从未提醒」 + (超过 N 天本来就该再次提醒),因此按窗口过滤不改变节奏语义。 + """ + since = datetime.utcnow() - timedelta(days=since_days) + events = db.session.scalars( + select(OrderDeliveryAuditEvent).where( + OrderDeliveryAuditEvent.action == ACTION_UNREPLIED_REMIND, + OrderDeliveryAuditEvent.created_at >= since, + ) + ).all() + last_by_line: dict[int, datetime] = {} + for event in events: + payload = event.payload_json if isinstance(event.payload_json, dict) else {} + if payload.get("ok") is not True or event.line_id is None or event.created_at is None: + continue + line_id = int(event.line_id) + if line_id not in last_by_line or event.created_at > last_by_line[line_id]: + last_by_line[line_id] = event.created_at + return last_by_line + + +def _truncate_orders(entries: list[str]) -> str: + """订单清单截断:最多列 MAX_LISTED_ORDERS 条,其余折叠为「…等 N 笔」。""" + if len(entries) <= MAX_LISTED_ORDERS: + return "\n".join(entries) + listed = "\n".join(entries[:MAX_LISTED_ORDERS]) + return f"{listed}\n…等共 {len(entries)} 笔" + + +def _send_remind_card(user: User, content: str, jump_params: dict[str, Any] | None = None) -> dict[str, Any]: + """发提醒卡片;返回 {ok, trace_id?/reason?},成败以 send_wecom_event_message 返回为准。""" + result = send_wecom_event_message( + event_type=WECOM_EVENT_TYPE, + user=user, + title="订单交期回复", + content=content, + jump_path=JUMP_PATH, + jump_params=jump_params, + ) + return {"ok": bool(result.get("ok")), "trace_id": result.get("trace_id"), "reason": result.get("reason")} + + +def run_ship_reminders(advance_days: int) -> dict[str, Any]: + """ + 出货提醒:已回复(已锁定)行中,回复交期距今 ≤ advance_days 天的,提醒对应业务员出货。 + + 核心逻辑:[STEP 1] 业务窗口 [today, today+advance_days];查已锁定且未标 erp_missing 的 + 行批次候选;[STEP 2] 按 (line_id, planned_date) 去重(历史 ship_remind 审计); + [STEP 3] 按业务员聚合发一条企微(一条多单,避免逐单刷屏),发送失败不计成功; + [STEP 4] 逐行写 ship_remind 审计(含 trace/成败),供下次去重与追溯。 + Returns: + {"advance_days", "candidate_lines", "notified_salespersons", "notified_lines", + "failed_salespersons", "skipped_unmapped"}。 + """ + today = _business_today() + window_end = today + timedelta(days=max(0, int(advance_days))) + + candidates: dict[int, list[dict[str, Any]]] = {} + rows = db.session.execute( + select(OrderDeliveryBatch, OrderDeliveryErpLine) + .join(OrderDeliveryErpLine, OrderDeliveryErpLine.id == OrderDeliveryBatch.line_id) + .join(OrderDeliveryLineState, OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id) + .where( + OrderDeliveryErpLine.erp_missing.is_(False), + OrderDeliveryLineState.locked.is_(True), + OrderDeliveryBatch.planned_date >= today, + OrderDeliveryBatch.planned_date <= window_end, + ) + .order_by(OrderDeliveryBatch.planned_date.asc()) + ).all() + for batch, line in rows: + candidates.setdefault(line.id, []).append( + { + "planned_date": batch.planned_date, + "qty": batch.qty, + "line": line, + } + ) + if not candidates: + return {"advance_days": advance_days, "candidate_lines": 0, "notified_salespersons": 0, + "notified_lines": 0, "failed_salespersons": 0, "skipped_unmapped": 0} + + # [STEP 2] 去重:同 (行, 回复交期) 只提醒一次;回看窗口取 3 倍提前天数(至少 30 天)。 + reminded = _audit_reminded_keys(ACTION_SHIP_REMIND, since_days=max(30, int(advance_days) * 3)) + + # 按业务员聚合并过滤已提醒的 (行, 交期)。 + by_salesperson: dict[str, dict[str, Any]] = {} + notified_lines = 0 + for line_id, entries in candidates.items(): + fresh = [e for e in entries if e["planned_date"].isoformat() not in reminded.get(line_id, set())] + if not fresh: + continue + line = fresh[0]["line"] + code = (line.salesperson_code or "").strip() + bucket = by_salesperson.setdefault( + code, {"entries": [], "line_ids": set()}, + ) + for entry in fresh: + bucket["entries"].append(entry) + bucket["line_ids"].add(line_id) + + notified_persons = 0 + failed_persons = 0 + skipped_unmapped = 0 + for code, bucket in by_salesperson.items(): + user = _resolve_salesperson_user(code) + if user is None: + # 业务员未映射企微:记失败审计(不带 trace),次日扫描同样会重试。 + skipped_unmapped += 1 + for entry in bucket["entries"]: + db.session.add(OrderDeliveryAuditEvent( + line_id=entry["line"].id, + order_no=entry["line"].order_no, + line_no=entry["line"].line_no, + action=ACTION_SHIP_REMIND, + payload_json={ + "kind": "ship", + "planned_date": entry["planned_date"].isoformat(), + "ok": False, + "reason": "salesperson_unmapped", + "salesperson_code": code, + }, + )) + db.session.commit() + continue + + lines_text = _truncate_orders([ + f"{entry['line'].order_no}:{entry['line'].line_no} 交期 {entry['planned_date'].isoformat()}" + for entry in bucket["entries"] + ]) + content = ( + f"您有 {len(bucket['entries'])} 笔订单将在 {advance_days} 天内交货,请及时安排出货:\n{lines_text}" + ) + # 卡片带 status=replied:业务员点开直达「已回复」视图(出货提醒行必然已回复锁定)。 + result = _send_remind_card(user, content, jump_params={"status": "replied"}) + if result["ok"]: + notified_persons += 1 + notified_lines += len(bucket["line_ids"]) + else: + failed_persons += 1 + for entry in bucket["entries"]: + db.session.add(OrderDeliveryAuditEvent( + line_id=entry["line"].id, + order_no=entry["line"].order_no, + line_no=entry["line"].line_no, + action=ACTION_SHIP_REMIND, + payload_json={ + "kind": "ship", + "planned_date": entry["planned_date"].isoformat(), + "ok": result["ok"], + "reason": result.get("reason"), + "recipient_employee_id": code, + "recipient_wecom_userid": user.wecom_userid, + "trace_id": result.get("trace_id"), + }, + )) + db.session.commit() + + return { + "advance_days": advance_days, + "candidate_lines": len(candidates), + "notified_salespersons": notified_persons, + "notified_lines": notified_lines, + "failed_salespersons": failed_persons, + "skipped_unmapped": skipped_unmapped, + } + + +def run_unreplied_reminders(unreplied_days: int, notify_user_ids: list[int]) -> dict[str, Any]: + """ + 未回复再提醒:订单日期距今超 N 天仍未回复的订单行,聚合提醒生管(收件人 = 排程任务通知人配置)。 + + 核心逻辑:[STEP 1] 候选 = 未锁定且未标 erp_missing、订单日期(order_date)距今 + ≥ unreplied_days 的行(订单日期为空不参与提醒); + [STEP 2] 同行距上次提醒 ≥ unreplied_days 才再次提醒 + (audit action=unreplied_remind 的 max(created_at) 控制,未提醒过则立即提醒); + [STEP 3] 汇总为一 + 条企微发给每个配置的生管收件人;无收件人时跳过并如实返回。 + Returns: + {"unreplied_days", "due_lines", "notified_recipients", "failed_recipients", "skipped_no_recipient"}。 + """ + today = _business_today() + threshold_date = today - timedelta(days=max(0, int(unreplied_days))) + + locked_subq = ( + select(OrderDeliveryLineState.line_id) + .where(OrderDeliveryLineState.line_id == OrderDeliveryErpLine.id, + OrderDeliveryLineState.locked.is_(True)) + .exists() + ) + due_lines = list( + db.session.scalars( + select(OrderDeliveryErpLine) + .where( + OrderDeliveryErpLine.erp_missing.is_(False), + ~locked_subq, + # 超期锚点 = ERP 订单日期(oea02,2026-09-23 由 created_at 改来,按业务确认口径): + # 订单日期距今 ≥ N 天仍未锁定即入选;订单日期为空无法判定,不参与提醒。 + OrderDeliveryErpLine.order_date.is_not(None), + OrderDeliveryErpLine.order_date <= threshold_date, + ) + .order_by(OrderDeliveryErpLine.order_date.asc()) + ).all() + ) + if not due_lines: + return {"unreplied_days": unreplied_days, "due_lines": 0, "notified_recipients": 0, + "failed_recipients": 0, "skipped_no_recipient": False} + + # [STEP 2] 同一行 N 天内不重复提醒(只看发送成功的记录;失败不算已提醒)。 + last_reminded = _last_successful_unreplied_remind_at(since_days=max(30, int(unreplied_days) * 3)) + pending_lines = [ + line for line in due_lines + if line.id not in last_reminded + or (datetime.utcnow() - last_reminded[line.id]) >= timedelta(days=max(1, int(unreplied_days))) + ] + if not pending_lines: + return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0, + "failed_recipients": 0, "skipped_no_recipient": False} + + recipient_ids = [int(uid) for uid in (notify_user_ids or []) if uid] + if not recipient_ids: + return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0, + "failed_recipients": 0, "skipped_no_recipient": True} + recipients = [u for u in User.query.filter(User.id.in_(recipient_ids)).all() if (u.wecom_userid or "").strip()] + if not recipients: + return {"unreplied_days": unreplied_days, "due_lines": len(due_lines), "notified_recipients": 0, + "failed_recipients": 0, "skipped_no_recipient": True} + + lines_text = _truncate_orders([ + f"{line.order_no}:{line.line_no} 客户 {line.customer_no or '—'} 下单 {line.order_date.isoformat() if line.order_date else '—'}" + for line in pending_lines + ]) + content = ( + f"有 {len(pending_lines)} 笔订单交期已超过 {unreplied_days} 天未回复,请及时查看并回复交期:\n{lines_text}" + ) + + notified = 0 + failed = 0 + for user in recipients: + result = _send_remind_card(user, content, jump_params={"status": "not_fully_replied"}) + if result["ok"]: + notified += 1 + else: + failed += 1 + # 提醒节奏按「发送时间」记(成功失败都记,失败下次扫描重试不叠加节奏)。 + for line in pending_lines: + db.session.add(OrderDeliveryAuditEvent( + line_id=line.id, + order_no=line.order_no, + line_no=line.line_no, + action=ACTION_UNREPLIED_REMIND, + payload_json={ + "kind": "unreplied", + "unreplied_days": unreplied_days, + "ok": result["ok"], + "reason": result.get("reason"), + "recipient_user_id": user.id, + "trace_id": result.get("trace_id"), + }, + )) + db.session.commit() + + return { + "unreplied_days": unreplied_days, + "due_lines": len(pending_lines), + "notified_recipients": notified, + "failed_recipients": failed, + "skipped_no_recipient": False, + } diff --git a/backend/app/services/order_delivery_reply/reply_service.py b/backend/app/services/order_delivery_reply/reply_service.py new file mode 100644 index 00000000..e3c308dc --- /dev/null +++ b/backend/app/services/order_delivery_reply/reply_service.py @@ -0,0 +1,270 @@ +""" +backend/app/services/order_delivery_reply/reply_service.py + +用途:订单交期回复的写路径——单行/联合保存交期批次(未锁定行整表替换)。 +依赖:models/order_delivery_reply(快照/批次/状态/审计)、extensions.db、core.errors。 +逻辑:保存与通知是两步(需求 §5):本服务只写批次与 save 审计,不通知、不锁定; + 已锁定行拒绝写入(409);批次校验(交期必填、数量>0、备注≤200、各批次合计必须 + 等于订单数量——2026-09-23 由「超额仅提醒」修订,BATCH_QTY_TOTAL_MISMATCH)在此层完成。 + 后续通知/锁定在 notify_service 中与企微发送同事务实现,禁止在本文件锁定。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from decimal import Decimal, InvalidOperation +from typing import Any + +from sqlalchemy import select + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryBatch, + OrderDeliveryErpLine, + OrderDeliveryLineState, +) + +# 批次数量上限:单行允许维护的批次条数(需求 §10「1..N 批」,N 收敛为 20 防误操作)。 +MAX_BATCH_COUNT = 20 +REMARK_MAX_LENGTH = 200 + + +def _parse_batches(raw_batches: Any) -> list[dict[str, Any]]: + """ + 校验并规范化请求中的批次列表。 + + 用途与触发时机:单行保存与联合回复保存共用;在触碰数据库之前先做全量校验。 + + 核心逻辑:必须为非空 list(1..MAX_BATCH_COUNT 条);每条交期必填且为合法日期、 + 数量 > 0、备注 ≤ 200;同一次提交内不允许重复交期(重复即录入错误)。 + + Args: + raw_batches: 请求 body 中的 batches 数组,元素 {planned_date, qty, remark?}。 + Returns: + 规范化后的 [{planned_date: date, qty: Decimal, remark: str|None}],按提交顺序。 + Raises: + ValidationError: 结构、日期、数量、备注长度、重复交期不合法。 + """ + if not isinstance(raw_batches, list) or not raw_batches: + raise ValidationError("batches 必须为非空数组", code="ORDER_DELIVERY_REPLY.BATCHES_REQUIRED") + if len(raw_batches) > MAX_BATCH_COUNT: + raise ValidationError(f"单行批次数量超过上限 {MAX_BATCH_COUNT}", code="ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED") + + normalized: list[dict[str, Any]] = [] + seen_dates: set[date] = set() + for idx, item in enumerate(raw_batches, start=1): + if not isinstance(item, dict): + raise ValidationError(f"第 {idx} 条批次格式不合法", code="ORDER_DELIVERY_REPLY.BATCH_INVALID") + + planned_raw = item.get("planned_date") + try: + planned_date = date.fromisoformat(str(planned_raw)) + except (TypeError, ValueError): + raise ValidationError( + f"第 {idx} 条批次交期必填且须为 YYYY-MM-DD", + code="ORDER_DELIVERY_REPLY.BATCH_INVALID", + ) + if planned_date in seen_dates: + raise ValidationError( + f"第 {idx} 条批次交期 {planned_date} 重复", + code="ORDER_DELIVERY_REPLY.BATCH_INVALID", + ) + seen_dates.add(planned_date) + + qty_raw = item.get("qty") + try: + qty = Decimal(str(qty_raw)) + except (TypeError, InvalidOperation): + raise ValidationError(f"第 {idx} 条批次数量不合法", code="ORDER_DELIVERY_REPLY.BATCH_INVALID") + if qty <= 0: + raise ValidationError(f"第 {idx} 条批次数量必须大于 0", code="ORDER_DELIVERY_REPLY.BATCH_INVALID") + + remark = item.get("remark") + if remark is not None: + remark = str(remark).strip() or None + if len(remark) > REMARK_MAX_LENGTH: + raise ValidationError( + f"第 {idx} 条批次备注超过 {REMARK_MAX_LENGTH} 字符", + code="ORDER_DELIVERY_REPLY.BATCH_INVALID", + ) + + normalized.append({"planned_date": planned_date, "qty": qty, "remark": remark}) + return normalized + + +def get_line_for_write(order_no: str, line_no: int) -> tuple[OrderDeliveryErpLine, OrderDeliveryLineState | None]: + """ + 取可写的订单行与其锁定状态(写路径统一入口)。 + + Args: + order_no / line_no: 行唯一键。 + Returns: + (行, 状态或None)。 + Raises: + NotFoundError: 行不存在或已标 erp_missing(直链按不存在处理)。 + ConflictError: 行已通知锁定,禁止再改批次。 + """ + line = db.session.scalar( + select(OrderDeliveryErpLine).where( + OrderDeliveryErpLine.order_no == order_no, + OrderDeliveryErpLine.line_no == line_no, + OrderDeliveryErpLine.erp_missing.is_(False), + ) + ) + if not line: + raise NotFoundError( + "Order delivery line not found", + code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND", + ) + state = db.session.scalar( + select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id == line.id) + ) + if state and state.locked: + raise ConflictError( + "该订单行交期已通知锁定,不能修改批次", + code="ORDER_DELIVERY_REPLY.LINE_LOCKED", + ) + return line, state + + +def save_batches(order_no: str, line_no: int, raw_batches: Any, operator_user_id: int | None) -> dict[str, Any]: + """ + 保存一行交期批次(未锁定行整表替换:删旧批 → 写新批 → 记审计)。 + + 用途与触发时机:单行「回复交期/修改回复」与联合回复保存逐行复用本入口; + AI/排程不触发本函数(无自动回复语义)。 + + 核心逻辑:[STEP 1] 校验批次结构(_parse_batches); + [STEP 2] get_line_for_write 确认行存在且未锁定;数量守恒校验:各批次合计必须 + 等于订单数量(2026-09-23 由「超额仅提醒」修订),不等抛 422 BATCH_QTY_TOTAL_MISMATCH; + [STEP 3] 事务内删除旧批次、按序号写入新批次; + [STEP 4] 写 action=save 审计(含批次快照)。 + 保存后行仍为部分回复;通知与锁定走 notify 路径,本函数不触碰 line_states。 + + Args: + order_no / line_no: 行唯一键。 + raw_batches: [{planned_date, qty, remark?}]。 + operator_user_id: 保存人(HXOPS 用户 id),审计用。 + Returns: + {"order_no", "line_no", "batches": [...], "total_qty"} 序列化结果。 + """ + normalized = _parse_batches(raw_batches) + line, _state = get_line_for_write(order_no, line_no) + + # [STEP 2] 数量守恒:各批次合计必须等于订单数量(保存口径 2026-09-23 修订,原允许超额仅提醒); + # 校验在任何写操作之前,失败时不落批次也不落审计。 + total_qty = sum((batch["qty"] for batch in normalized), Decimal(0)) + order_qty = line.qty if line.qty is not None else Decimal(0) + if total_qty != order_qty: + raise ValidationError( + f"各批次数量合计({total_qty})必须等于订单数量({order_qty}),请调整后重新保存", + code="ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH", + ) + + # [STEP 3] 整表替换:未锁定行的旧批次全部作废,以本次提交为准。 + db.session.query(OrderDeliveryBatch).filter(OrderDeliveryBatch.line_id == line.id).delete() + for seq, batch in enumerate(normalized, start=1): + db.session.add( + OrderDeliveryBatch( + line_id=line.id, + seq=seq, + planned_date=batch["planned_date"], + qty=batch["qty"], + remark=batch["remark"], + created_by=operator_user_id, + ) + ) + + db.session.add( + OrderDeliveryAuditEvent( + line_id=line.id, + order_no=line.order_no, + line_no=line.line_no, + action="save", + operator_user_id=operator_user_id, + payload_json={ + "batch_count": len(normalized), + "total_qty": str(total_qty), + "batches": [ + { + "seq": seq, + "planned_date": batch["planned_date"].isoformat(), + "qty": str(batch["qty"]), + "remark": batch["remark"], + } + for seq, batch in enumerate(normalized, start=1) + ], + "saved_at": datetime.utcnow().isoformat(), + }, + ) + ) + db.session.commit() + + return { + "order_no": line.order_no, + "line_no": line.line_no, + "batches": [ + { + "seq": seq, + "planned_date": batch["planned_date"].isoformat(), + "qty": str(batch["qty"]), + "remark": batch["remark"], + } + for seq, batch in enumerate(normalized, start=1) + ], + "total_qty": str(total_qty), + } + + +def batch_reply(raw_items: Any, operator_user_id: int | None) -> dict[str, Any]: + """ + 联合回复:对勾选的多行逐行保存批次(只保存,不通知、不锁定)。 + + 用途与触发时机:工作台勾选多行后点「+ 联合回复交期」并逐行填批次提交(R-REPLY-02)。 + + 核心逻辑:[STEP 1] 校验请求结构(非空数组、每项含 order_no/line_no/batches); + [STEP 2] 逐行调用 save_batches;单行失败不回滚已成功的行(草稿语义, + 部分保存优于整体失败),失败行带错误信息返回由前端标红重试; + [STEP 3] 汇总 succeeded/failed 与各行结果。 + + Args: + raw_items: [{"order_no", "line_no", "batches": [{planned_date, qty, remark?}]}]。 + operator_user_id: 保存人。 + Returns: + {"succeeded": N, "failed": N, "items": [{order_no, line_no, ok, error?, data?}]}。 + """ + from app.core.errors import AppError + + if not isinstance(raw_items, list) or not raw_items: + raise ValidationError("items 必须为非空数组", code="ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY") + if len(raw_items) > 200: + raise ValidationError("单次联合回复行数超过上限 200", code="ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY") + + results: list[dict[str, Any]] = [] + for item in raw_items: + if not isinstance(item, dict) or not item.get("order_no") or item.get("line_no") is None: + results.append({"ok": False, "error": "行唯一键缺失(order_no/line_no)"}) + continue + order_no = str(item["order_no"]).strip() + try: + line_no = int(item["line_no"]) + except (TypeError, ValueError): + results.append({"order_no": order_no, "ok": False, "error": "line_no 须为整数"}) + continue + try: + data = save_batches(order_no, line_no, item.get("batches"), operator_user_id) + results.append({"order_no": order_no, "line_no": line_no, "ok": True, "data": data}) + except AppError as exc: + # [STEP 2] 单行失败只记结果,不回滚其它行(save_batches 每行独立事务)。 + db.session.rollback() + results.append( + {"order_no": order_no, "line_no": line_no, "ok": False, "error": exc.message} + ) + + return { + "succeeded": sum(1 for r in results if r.get("ok")), + "failed": sum(1 for r in results if not r.get("ok")), + "items": results, + } diff --git a/backend/app/services/order_delivery_reply/schedule_seed.py b/backend/app/services/order_delivery_reply/schedule_seed.py new file mode 100644 index 00000000..2866526d --- /dev/null +++ b/backend/app/services/order_delivery_reply/schedule_seed.py @@ -0,0 +1,50 @@ +"""订单交期回复默认排程种子:每天 07:00(Asia/Shanghai)ERP 全量同步 + 07:10 每日提醒。""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.models import ScheduleTask, User +from app.services.schedule.timezone_util import compute_next_run_at + + +_DEFAULTS = ( + ('SCH-ORDER-DELIVERY-SYNC', 'order-delivery-sync', '订单交期回复 ERP 同步(日批 07:00)', '0 7 * * *'), + # 提醒排在同步之后:扫描的是当天刚同步的最新快照。 + ('SCH-ORDER-DELIVERY-REMIND', 'order-delivery-remind', '订单交期回复 提醒(日批 07:10)', '10 7 * * *'), +) + + +def ensure_default_order_delivery_schedules(*, commit: bool = True): + """ + 幂等创建订单交期回复每日同步默认排程。 + + Args: + commit: 是否提交新建排程;测试或外层事务可传 False。 + Returns: + 新建的 ScheduleTask 列表;无用户时返回空列表。 + """ + owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first() + if owner is None: + return [] + created = [] + for schedule_no, platform_path, name, cron in _DEFAULTS: + existing = db.session.query(ScheduleTask).filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path)).first() + if existing: + continue + now = datetime.utcnow() + task = ScheduleTask( + schedule_no=schedule_no, name=name, schedule_type='platform_job', owner_user_id=owner.id, + cron_expr=cron, schedule_timezone='Asia/Shanghai', wait_seconds=0, + platform_api_path=platform_path, job_params={}, kb_sync_enabled=False, + notify_user_ids_json=[], notify_enabled=False, enabled=True, + next_run_at=compute_next_run_at(cron, timezone_name='Asia/Shanghai') or now, + created_by=owner.id, updated_by=owner.id, created_at=now, updated_at=now, + ) + db.session.add(task); created.append(task) + if commit and created: + db.session.commit() + elif not commit: + db.session.flush() + return created diff --git a/backend/app/services/order_delivery_reply/sql.py b/backend/app/services/order_delivery_reply/sql.py new file mode 100644 index 00000000..e353dd5d --- /dev/null +++ b/backend/app/services/order_delivery_reply/sql.py @@ -0,0 +1,45 @@ +""" +backend/app/services/order_delivery_reply/sql.py + +用途:订单交期回复 ERP(鼎捷 topprod)取数 SQL 唯一权威定义;同步服务与原型脚本共用。 +依赖:无(纯常量);连接约定见 services/text2sql.py(ERP_DB_DSN / ERP_DB_USER / ERP_DB_PASSWORD)。 +逻辑:一期同步全部「已审核 oeaconf='Y' + 已核准 oea49='1' + 未结案 oeb70≠Y」合格订单行, + 不按单别过滤;后期单别白名单在此基础上追加 IN 条件。业务约束:仅只读 SELECT, + 禁止改写为 INSERT/UPDATE/DELETE。 +""" + +# 基础 SELECT:不带分页/排序,同步服务按 oea01 keyset 分页时在外层包装。 +# 关联:oea01=oeb01;oeb04=ima01 且 oeb06=ima02;oea03=occ01;oea14=gen01;oea15=gem01。 +# 别名与 docs/features/order-delivery-reply/technical-design.md §3.5 标准 SELECT 逐列一致。 +ORDER_DELIVERY_SQL = """ +SELECT + a.oea01 AS order_no, + b.oeb03 AS line_no, + a.oea02 AS order_date, + a.oea03 AS customer_no, + d.occ02 AS customer_short_name, + d.occ18 AS customer_full_name, + a.oea14 AS salesperson_code, + e.gen02 AS salesperson_name, + a.oea15 AS dept_code, + f.gem02 AS dept_name, + a.oea10 AS customer_po, + b.oeb04 AS part_no, + b.oeb06 AS part_name, + c.ima021 AS spec, + b.oeb11 AS customer_part_no, + b.oeb15 AS agreed_date, + b.oeb05 AS unit, + b.oeb12 AS qty, + NVL(b.oeb24, 0) AS delivered_qty +FROM HXJM.OEA_FILE a +INNER JOIN HXJM.OEB_FILE b ON a.oea01 = b.oeb01 +LEFT JOIN HXJM.IMA_FILE c ON b.oeb04 = c.ima01 AND b.oeb06 = c.ima02 +LEFT JOIN HXJM.OCC_FILE d ON a.oea03 = d.occ01 +LEFT JOIN HXJM.GEN_FILE e ON a.oea14 = e.gen01 +LEFT JOIN HXJM.GEM_FILE f ON a.oea15 = f.gem01 +WHERE a.oeaconf = 'Y' + AND a.oea49 = '1' + AND NVL(b.oeb70, 'N') = 'N' + AND NVL(b.oeb24, 0) = 0 +""" diff --git a/backend/app/services/order_delivery_reply/sync_service.py b/backend/app/services/order_delivery_reply/sync_service.py new file mode 100644 index 00000000..4619a107 --- /dev/null +++ b/backend/app/services/order_delivery_reply/sync_service.py @@ -0,0 +1,306 @@ +""" +backend/app/services/order_delivery_reply/sync_service.py + +用途:订单交期回复 ERP 全量同步服务(07:00 排程与手动刷新共用);只读 ERP、upsert 本地快照。 +依赖:services/order_delivery_reply/sql(取数口径)、services/text2sql(Oracle thick 模式初始化)、 + models/order_delivery_reply(本地表)、extensions.db。 +逻辑:按 oea01 keyset 分页拉取合格订单行 → 对 (order_no, line_no) 做 upsert 且只更新 ERP 列白名单 + (绝不覆盖批次/锁定)→ 本轮未命中的本地行置 erp_missing=true(不删除)→ 写 sync_runs。 + 全程模块级锁保证同时只有一个同步;失败保留上次快照并记录错误。 +""" + +from __future__ import annotations + +import logging +import os +import threading +from datetime import datetime +from typing import Any + +from sqlalchemy import select, update + +from app.extensions import db +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryErpLine, + OrderDeliverySyncRun, +) +from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL + +logger = logging.getLogger(__name__) + +# 同步 upsert 只允许更新这些 ERP 快照列;触碰批次/锁定列会覆盖业务回复,禁止扩充业务列进来。 +ERP_LINE_COLUMNS = ( + "order_date", + "customer_no", + "customer_short_name", + "customer_full_name", + "salesperson_code", + "salesperson_name", + "dept_code", + "dept_name", + "customer_po", + "part_no", + "part_name", + "spec", + "customer_part_no", + "agreed_date", + "unit", + "qty", + "delivered_qty", + "slip_code", +) + +_FETCH_SIZE = 500 + +_thick_init_lock = threading.Lock() +_thick_initialized = False + + +def _ensure_thick_client(oracledb) -> None: + """按 ORACLE_CLIENT_LIB_DIR(或 backend/oracle_client 约定)初始化 thick 模式;幂等且失败不掩埋。""" + global _thick_initialized + with _thick_init_lock: + if _thick_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)(): + _thick_initialized = True + return + candidates = [] + env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip() + if env_dir: + candidates.append(os.path.normpath(env_dir)) + backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + candidates.append(os.path.join(backend_dir, "oracle_client")) + marker = {"oci.dll", "libclntsh.so", "libclntsh.dylib"} + lib_dir = None + for root in candidates: + if not root or not os.path.isdir(root): + continue + if marker & {n.lower() for n in os.listdir(root)}: + lib_dir = root + break + sub = [d for d in os.listdir(root) if d.startswith("instantclient_") and os.path.isdir(os.path.join(root, d))] + if sub: + lib_dir = os.path.join(root, sub[0]) + break + if lib_dir: + os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "") + if hasattr(os, "add_dll_directory"): + os.add_dll_directory(lib_dir) + oracledb.init_oracle_client(lib_dir=lib_dir) + else: + oracledb.init_oracle_client() + _thick_initialized = True + +# 进程内互斥:同一 worker 同时只跑一个同步(多 worker 由 sync_runs running 行兜底,一期单机足够)。 +_sync_lock = threading.Lock() + + +def _extract_slip_code(order_no: str | None) -> str | None: + """从订单单号取连字符前的单别(8301-1605280014 → 8301);无连字符返回整号前缀。""" + if not order_no: + return None + return order_no.split("-", 1)[0] + + +class OrderDeliverySyncService: + """ERP → 本地 Postgres 的订单行全量同步;所有方法不回写 ERP。""" + + @staticmethod + def _connect(): + """ + 建立 ERP Oracle 连接(凭据复用合同付款预警的 CONTRACT_PAYMENT_ERP_* 配置)。 + + 核心逻辑:账号/密码优先专用键 ERP_DB_USER / ERP_DB_PASSWORD(或 ERP_USERNAME/ERP_PASSWORD), + 缺省回退 .env.shared 已有的 CONTRACT_PAYMENT_ERP_USERNAME / CONTRACT_PAYMENT_ERP_PASSWORD + (hxjm 账号,与合同付款预警同一连接口径,技术文档 §3.1);DSN 用 ERP_DB_DSN。 + thin 优先,失败时按 Text2SQL 既有路径切 thick(本地 Instant Client)。 + + Returns: + oracledb.Connection;凭据缺失时抛 RuntimeError 提示配置来源。 + """ + import oracledb + + user = ( + os.getenv("ERP_DB_USER") + or os.getenv("ERP_USERNAME") + or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME") + or "EXT_VIEW_USER" + ) + password = ( + os.getenv("ERP_DB_PASSWORD") + or os.getenv("ERP_PASSWORD") + or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD") + ) + dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod") + if not password: + raise RuntimeError( + "ERP 口令未配置:请设置 ERP_DB_PASSWORD,或复用 .env.shared 的 " + "CONTRACT_PAYMENT_ERP_PASSWORD(与合同付款预警同一 topprod 连接)" + ) + try: + return oracledb.connect(user=user, password=password, dsn=dsn) + except oracledb.DatabaseError: + # thin 模式连不上(topprod 为 11g 必走 thick):用 ORACLE_CLIENT_LIB_DIR 自初始化, + # 不再依赖 services/text2sql——worker 进程 sys.path 差异曾致 + # "No module named app.services.text2sql"(2026-09-22 排程同步失败根因)。 + _ensure_thick_client(oracledb) + return oracledb.connect(user=user, password=password, dsn=dsn) + + @classmethod + def _fetch_page(cls, cursor, last_order_no: str | None) -> list[dict[str, Any]]: + """ + 按 oea01 keyset 分页拉取一页订单行。 + + Args: + cursor: oracledb 游标。 + last_order_no: 上一页最后一条订单单号;None 表示从头发起。 + Returns: + 本页行字典列表(列为 sql.ORDER_DELIVERY_SQL 的别名)。 + """ + # Oracle 空串即 NULL:首页不能带 `order_no > ''`(与 NULL 比较恒 UNKNOWN 会滤掉全部行), + # 因此首页与续页使用两个 SQL 变体。 + if last_order_no: + page_sql = ( + f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) " + f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}" + ) + cursor.execute(page_sql, last_order_no=last_order_no) + else: + page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}" + cursor.execute(page_sql) + columns = [col[0].lower() for col in cursor.description] + return [dict(zip(columns, row)) for row in cursor.fetchall()] + + @classmethod + def _upsert_page(cls, rows: list[dict[str, Any]], synced_at: datetime) -> set[tuple[str, int]]: + """ + upsert 一页快照行:只更新 ERP 列白名单并复位 erp_missing,绝不覆盖批次/锁定。 + + Returns: + 本页命中的 (order_no, line_no) 集合,供整轮结束后标记 erp_missing。 + """ + from sqlalchemy.dialects.postgresql import insert + + hit_keys: set[tuple[str, int]] = set() + for raw in rows: + order_no = str(raw["order_no"] or "").strip() + if not order_no or raw["line_no"] is None: + continue + line_no = int(raw["line_no"]) + values = { + "order_no": order_no, + "line_no": line_no, + "slip_code": _extract_slip_code(order_no), + "erp_missing": False, + "last_synced_at": synced_at, + } + for col in ERP_LINE_COLUMNS: + if col == "slip_code": + continue + value = raw.get(col) + if isinstance(value, datetime): + value = value.date() + values[col] = value + + stmt = insert(OrderDeliveryErpLine).values(**values) + stmt = stmt.on_conflict_do_update( + constraint="uq_order_delivery_erp_lines_order_line", + set_={**{col: stmt.excluded[col] for col in ERP_LINE_COLUMNS}, + "erp_missing": False, + "last_synced_at": synced_at}, + ) + db.session.execute(stmt) + hit_keys.add((order_no, line_no)) + return hit_keys + + @classmethod + def run_sync(cls, trigger: str = "manual") -> dict[str, Any]: + """ + 执行一次全量同步(排程传 'scheduled',手动传 'manual')。 + + 用途与触发时机:07:00 定时任务与生管手动刷新共用入口;AI/脚本也可直调验证取数。 + + 核心逻辑:[STEP 1] 抢互斥锁并写 running 状态的 sync_runs; + [STEP 2] 按 oea01 分页拉 ERP 合格行,逐页 upsert(仅 ERP 列白名单); + [STEP 3] 本轮未命中的本地行统一置 erp_missing=true(不删除,默认列表不展示); + [STEP 4] 写审计与终态 sync_runs;任何异常保留上次快照、记 failed。 + + Args: + trigger: 'scheduled' | 'manual'。 + Returns: + {"run_id", "status", "line_count"};并发冲突返回 status='skipped'。 + """ + if not _sync_lock.acquire(blocking=False): + return {"run_id": None, "status": "skipped", "line_count": 0} + + synced_at = datetime.utcnow() + run = OrderDeliverySyncRun(trigger=trigger, status="running", started_at=synced_at) + db.session.add(run) + db.session.commit() + + hit_keys: set[tuple[str, int]] = set() + try: + with cls._connect() as conn: + with conn.cursor() as cursor: + last_order_no: str | None = None + while True: + page = cls._fetch_page(cursor, last_order_no) + if not page: + break + hit_keys |= cls._upsert_page(page, synced_at) + db.session.commit() + last_order_no = str(page[-1]["order_no"]) + + # [STEP 3] 未命中行标记 erp_missing:已有批次/锁定的行保留可追,纯快照行同样不再展示。 + missing_ids = [ + row_id + for row_id, order_no, line_no, _missing in db.session.execute( + select( + OrderDeliveryErpLine.id, + OrderDeliveryErpLine.order_no, + OrderDeliveryErpLine.line_no, + OrderDeliveryErpLine.erp_missing, + ) + ).all() + if (order_no, line_no) not in hit_keys + ] + if missing_ids: + db.session.execute( + update(OrderDeliveryErpLine) + .where(OrderDeliveryErpLine.id.in_(missing_ids)) + .values(erp_missing=True) + ) + + run.status = "success" + run.line_count = len(hit_keys) + run.finished_at = datetime.utcnow() + db.session.add( + OrderDeliveryAuditEvent( + action="sync", + payload_json={"trigger": trigger, "line_count": len(hit_keys), "missing_count": len(missing_ids)}, + ) + ) + db.session.commit() + logger.info("order-delivery-reply sync done: trigger=%s lines=%s missing=%s", trigger, len(hit_keys), len(missing_ids)) + return {"run_id": run.id, "status": "success", "line_count": len(hit_keys)} + except Exception as exc: # noqa: BLE001 — 同步失败必须落库留痕并保留上次快照 + db.session.rollback() + run.status = "failed" + run.error_message = str(exc)[:4000] + run.finished_at = datetime.utcnow() + db.session.add(run) + db.session.commit() + logger.exception("order-delivery-reply sync failed (trigger=%s)", trigger) + raise + finally: + _sync_lock.release() + + @staticmethod + def latest_run() -> OrderDeliverySyncRun | None: + """最近一次同步运行记录,供页面展示同步时间与结果。""" + return ( + db.session.execute( + select(OrderDeliverySyncRun).order_by(OrderDeliverySyncRun.started_at.desc()).limit(1) + ) + .scalar_one_or_none() + ) diff --git a/backend/app/services/permission_roles/catalog.py b/backend/app/services/permission_roles/catalog.py index 7b61fd90..76ff15aa 100644 --- a/backend/app/services/permission_roles/catalog.py +++ b/backend/app/services/permission_roles/catalog.py @@ -19,6 +19,9 @@ KNOWN_FEATURE_KEYS: tuple[str, ...] = ( 'shipping_notice.xfa_split_rule_preview', 'shipping_notice.xfa_split_rule_publish', 'maintenance.ledger_write', + # 订单交期回复(2026-09-29 合并登记):manage 命中视为有 access,两键须一并授予。 + 'order_delivery_reply.manage', + 'order_delivery_reply.access', ) FEATURE_CATALOG: tuple[dict[str, Any], ...] = ( @@ -64,6 +67,18 @@ FEATURE_CATALOG: tuple[dict[str, Any], ...] = ( 'name': '台账与维修维护', 'hint': '维护设备台账与维修记录', }, + { + 'key': 'order_delivery_reply.manage', + 'bind': 'agent_code:order_delivery_reply', + 'name': '订单交期回复管理', + 'hint': '生管回复交期、发送通知并手动同步', + }, + { + 'key': 'order_delivery_reply.access', + 'bind': 'agent_code:order_delivery_reply', + 'name': '订单交期回复查看', + 'hint': '业务只读查看已同步订单与回复结果', + }, ) # 现网 users.role 枚举对应的标准权限组。admin/user/hr 为内置;rd/shipping 可后续增删应用。 diff --git a/backend/app/services/schedule/file_asset_cleanup_job.py b/backend/app/services/schedule/file_asset_cleanup_job.py index 2f7192cc..c41a7469 100644 --- a/backend/app/services/schedule/file_asset_cleanup_job.py +++ b/backend/app/services/schedule/file_asset_cleanup_job.py @@ -3,24 +3,57 @@ backend/app/services/schedule/file_asset_cleanup_job.py 用途:排程平台 Job —— 清理过期未引用的临时文件资产。 依赖:file_assets.cleanup。 -逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。 +逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用; + 包装 cleanup_expired_temporary_assets 的统计字典为平台标准七元组 + (total/success/failed/skipped/details/errors/step_logs),对齐其它平台 Job 契约。 """ from __future__ import annotations from typing import Any +from app.models import ScheduleRun, ScheduleTask from app.services.file_assets.cleanup import cleanup_expired_temporary_assets +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] -def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]: + +def run_file_asset_cleanup_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ - 执行临时文件资产 TTL 清理。 + 执行临时文件资产 TTL 清理并返回平台标准审计七元组。 + + 统计口径:total=scanned(本批扫描数)、success=deleted(物理删除数)、 + failed=errors(删除失败数)、skipped=expired 未删除部分。 + Args: - task: ScheduleTask。 + task: ScheduleTask(job_params.limit 可调单批上限,缺省 200)。 run: ScheduleRun。 Returns: - 清理统计。 + (total, success, failed, skipped, details, errors, step_logs)。 """ - _ = task, run - return cleanup_expired_temporary_assets(limit=200) + _ = run + params = task.job_params if isinstance(task.job_params, dict) else {} + try: + limit = int(params.get("limit") or 200) + except (TypeError, ValueError): + limit = 200 + + stats = cleanup_expired_temporary_assets(limit=limit) + scanned = int(stats.get("scanned") or 0) + deleted = int(stats.get("deleted") or 0) + errors_count = int(stats.get("errors") or 0) + expired = int(stats.get("expired") or 0) + skipped = max(0, expired - deleted) + + errors: list[str] = [] + if errors_count: + errors.append(f"临时文件资产清理有 {errors_count} 个对象删除失败,详见 step_logs 统计") + + step_logs: list[dict[str, Any]] = [ + { + "step": "file_asset_cleanup", + "status": "success" if errors_count == 0 else "partial", + "detail": stats, + } + ] + return (scanned, deleted, errors_count, skipped, [stats], errors, step_logs) diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 952b45cd..63fb0b38 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -64,6 +64,21 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]: } for source, _config in rows] +def _hxops_users_options() -> list[dict[str, Any]]: + """全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。""" + from app.models import User + + users = User.query.filter(User.status == "active").order_by(User.real_name.asc(), User.id.asc()).all() + return [ + { + "label": f"{u.real_name or u.username}({u.employee_id or '-'})", + "value": u.id, + "description": u.department or None, + } + for u in users + ] + + def _users_options() -> list[dict[str, Any]]: """启用中的用户列表(value=user.id),供排程通知人类参数选择。""" from app.models import User @@ -88,6 +103,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = { "agent_apps": _agent_apps_options, "shipping_inventory_sources": _shipping_inventory_sources_options, "shipping_receipt_sources": _shipping_receipt_sources_options, + "hxops_users": _hxops_users_options, "users": _users_options, } diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index d77deedd..c3bbe733 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -162,6 +162,96 @@ def _register_builtin_platform_jobs() -> None: key="contract-payment-sync", label="合同付款 OA 同步", handler=run_contract_payment_sync_schedule, description="同步 OA 合同归档、验收归档和厂商预付款请款作业。", category="contract_payment", )) + from app.services.schedule.order_delivery_reply_job import run_order_delivery_sync_schedule + from app.services.schedule.order_delivery_remind_job import ( + DEFAULT_SHIP_ADVANCE_DAYS, + DEFAULT_SHIP_REMIND_ENABLED, + DEFAULT_UNREPLIED_DAYS, + DEFAULT_UNREPLIED_REMIND_ENABLED, + run_order_delivery_remind_schedule, + ) + + register_platform_job(PlatformJobDefinition( + key="order-delivery-sync", label="订单交期回复 ERP 同步", handler=run_order_delivery_sync_schedule, + description=( + "每天 07:00 全量同步已审核、已核准、未结案的 ERP 销售订单行快照;" + "同步成功后按任务参数「同步完成提醒收件人」提醒生管查看回复(未配置时回退本任务通知人)。" + ), + category="order_delivery_reply", + params_schema=( + { + "key": "sync_remind_user_ids", + "type": "multi_select", + "label": "同步完成提醒收件人(生管)", + "required": False, + "default": [], + "options_source": "hxops_users", + "help": "同步完成提醒的生管收件人,可从全部启用用户中搜索选择;" + "与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。", + }, + ), + defaults={"sync_remind_user_ids": []}, + )) + register_platform_job(PlatformJobDefinition( + key="order-delivery-remind", label="订单交期回复 提醒", handler=run_order_delivery_remind_schedule, + description=( + "每天扫描:已回复行按回复交期提前 N 天企微提醒对应业务员出货;" + "超 N 天未回复的行再次企微提醒生管(收件人取任务参数「未回复提醒收件人」," + "未配置时回退本任务通知人)。两类提醒可通过任务参数独立启停。" + ), + category="order_delivery_reply", + params_schema=( + { + "key": "ship_remind_enabled", + "type": "boolean", + "label": "启用出货提醒", + "required": False, + "default": DEFAULT_SHIP_REMIND_ENABLED, + "help": "关闭后不再按回复交期提前提醒业务员出货;未回复提醒不受影响。", + }, + { + "key": "ship_remind_advance_days", + "type": "number", + "label": "出货提醒提前天数", + "required": False, + "default": DEFAULT_SHIP_ADVANCE_DAYS, + "help": "已回复订单的回复交期距今 ≤ 该天数时,企微提醒对应业务员安排出货。取值 0-3650。", + }, + { + "key": "unreplied_remind_enabled", + "type": "boolean", + "label": "启用未回复提醒", + "required": False, + "default": DEFAULT_UNREPLIED_REMIND_ENABLED, + "help": "关闭后不再对超期未回复的订单行再次提醒生管;出货提醒不受影响。", + }, + { + "key": "unreplied_remind_days", + "type": "number", + "label": "未回复再次提醒天数", + "required": False, + "default": DEFAULT_UNREPLIED_DAYS, + "help": "订单日期距今超过该天数仍未回复交期时再次提醒生管;同一行每达到该天数最多提醒一次。取值 0-3650。", + }, + { + "key": "unreplied_remind_user_ids", + "type": "multi_select", + "label": "未回复提醒收件人(生管)", + "required": False, + "default": [], + "options_source": "hxops_users", + "help": "超期未回复提醒的生管收件人,可从全部启用用户中搜索选择;" + "与本任务「通知人」(运行结果通知)互相独立;留空时回退通知人名单以兼容旧配置。", + }, + ), + defaults={ + "ship_remind_enabled": DEFAULT_SHIP_REMIND_ENABLED, + "ship_remind_advance_days": DEFAULT_SHIP_ADVANCE_DAYS, + "unreplied_remind_enabled": DEFAULT_UNREPLIED_REMIND_ENABLED, + "unreplied_remind_days": DEFAULT_UNREPLIED_DAYS, + "unreplied_remind_user_ids": [], + }, + )) register_platform_job(PlatformJobDefinition( key="lean-training-reminder", label="精益管理培训逾期提醒", handler=run_lean_training_reminder_schedule, description="周日截止后,于周一、周三、周五向未完成员工推送精益培训提醒。", category="training", diff --git a/backend/app/services/schedule/order_delivery_remind_job.py b/backend/app/services/schedule/order_delivery_remind_job.py new file mode 100644 index 00000000..109279f0 --- /dev/null +++ b/backend/app/services/schedule/order_delivery_remind_job.py @@ -0,0 +1,148 @@ +""" +backend/app/services/schedule/order_delivery_remind_job.py + +用途:将订单交期回复的每日提醒适配到平台排程(ScheduleTask platform_job,job key + order-delivery-remind,默认日批 07:10 在同步之后执行)。 +依赖:services/order_delivery_reply/reminder_service(出货提醒 + 未回复再提醒)、 + ScheduleTask/ScheduleRun。 +逻辑:从 task.job_params 读取配置(管理端排程表单「任务参数」可改,均有默认值): + ship_remind_enabled / unreplied_remind_enabled 布尔开关独立启停两类提醒; + ship_remind_advance_days 默认 3、unreplied_remind_days 默认 3。 + 未回复提醒收件人优先取 job_params 的 unreplied_remind_user_ids(管理端「未回复提醒收件人」 + 多选参数,与平台运行结果通知的「通知人」互相独立);未配置时回退任务 notify_user_ids_json + 兼容旧配置。天数统一钳制在 0-3650,防止表单误填巨大值导致 today+timedelta 溢出 + (OverflowError: date value out of range,2026-09-22 出货提醒扫描事故根因)。 + 两个扫描互相独立:单个扫描抛错回滚后继续另一个,最终把错误计入 errors + (failed_count>0 时平台排程标 partial_failed/failed,不影响数据快照); + 开关关闭的一侧直接跳过(summary 记 skipped=disabled),不影响另一侧。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +from app.models import ScheduleRun, ScheduleTask + +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] + +# 配置键与默认值:与 job_registry 中 order-delivery-remind 的 params_schema 一致。 +SHIP_REMIND_ENABLED_KEY = "ship_remind_enabled" +UNREPLIED_REMIND_ENABLED_KEY = "unreplied_remind_enabled" +SHIP_REMIND_ADVANCE_DAYS_KEY = "ship_remind_advance_days" +UNREPLIED_REMIND_DAYS_KEY = "unreplied_remind_days" +DEFAULT_SHIP_REMIND_ENABLED = True +DEFAULT_UNREPLIED_REMIND_ENABLED = True +DEFAULT_UNREPLIED_USER_IDS_KEY = "unreplied_remind_user_ids" +DEFAULT_SHIP_ADVANCE_DAYS = 3 +DEFAULT_UNREPLIED_DAYS = 3 +# 天数上限(约 10 年):date + timedelta 超过 9999 年会抛 OverflowError: date value out of range。 +MAX_REMIND_DAYS = 3650 + + +def _read_days(task: ScheduleTask, key: str, default: int) -> int: + """读取 job_params 中的天数配置;非法值回退默认,并钳制到 [0, MAX_REMIND_DAYS]。 + + 上限原因:today + timedelta(days=N) 在 N 巨大时溢出抛 + OverflowError: date value out of range(2026-09-22 出货提醒扫描失败根因)。 + """ + params = task.job_params if isinstance(task.job_params, dict) else {} + try: + value = int(params.get(key, default)) + except (TypeError, ValueError): + return default + return min(max(value, 0), MAX_REMIND_DAYS) + + +def _read_unreplied_recipients(task: ScheduleTask) -> list[int]: + """读取未回复提醒的生管收件人:优先任务参数多选名单,留空回退任务通知人(旧配置兼容)。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + raw = params.get(DEFAULT_UNREPLIED_USER_IDS_KEY) + ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else [] + if ids: + return ids + if task.notify_enabled: + return [int(uid) for uid in (task.notify_user_ids_json or []) if uid] + return [] + + +def _read_bool(task: ScheduleTask, key: str, default: bool) -> bool: + """读取 job_params 中的开关配置;非法值回退默认(参数类型已由契约层校验)。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + value = params.get(key, default) + return value if isinstance(value, bool) else default + + +def _run_scan(errors: list[str], label: str, scan: Callable[[], dict[str, Any]]) -> dict[str, Any]: + """执行单个扫描:异常回滚后记入 errors(failed+1),不吞掉另一侧扫描。""" + from app.extensions import db + + try: + return scan() + except Exception as exc: # noqa: BLE001 — 扫描失败计入运行结果,由排程页展示 + db.session.rollback() + errors.append(f"{label}扫描失败: {exc}") + return {"error": str(exc)} + + +def run_order_delivery_remind_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """ + 执行每日提醒扫描:已回复行提前 N 天提醒业务员出货;超 N 天未回复行再次提醒生管。 + + 两类提醒由 job_params 的布尔开关独立启停(ship_remind_enabled / unreplied_remind_enabled); + 关闭的一侧跳过并在 summary 标记 skipped=disabled,不影响另一侧。 + + Args: + task: 当前排程任务定义(job_params 带天数/开关配置,notify_user_ids_json 带生管收件人)。 + run: 当前排程执行记录。 + Returns: + 通用排程审计七元组;total/success/failed 按两侧扫描的发送对象计数汇总。 + """ + from app.services.order_delivery_reply.reminder_service import ( + run_ship_reminders, + run_unreplied_reminders, + ) + + ship_enabled = _read_bool(task, SHIP_REMIND_ENABLED_KEY, DEFAULT_SHIP_REMIND_ENABLED) + unreplied_enabled = _read_bool(task, UNREPLIED_REMIND_ENABLED_KEY, DEFAULT_UNREPLIED_REMIND_ENABLED) + advance_days = _read_days(task, SHIP_REMIND_ADVANCE_DAYS_KEY, DEFAULT_SHIP_ADVANCE_DAYS) + unreplied_days = _read_days(task, UNREPLIED_REMIND_DAYS_KEY, DEFAULT_UNREPLIED_DAYS) + + errors: list[str] = [] + if ship_enabled: + ship_result = _run_scan(errors, "出货提醒", lambda: run_ship_reminders(advance_days)) + if ship_result.get("skipped_unmapped"): + errors.append( + f"出货提醒有 {ship_result['skipped_unmapped']} 名业务员工号未映射 HXOPS 企微用户,未送达" + ) + else: + ship_result = {"skipped": "disabled", "advance_days": advance_days} + + unreplied_recipients = _read_unreplied_recipients(task) + if unreplied_enabled: + unreplied_result = _run_scan(errors, "未回复提醒", lambda: run_unreplied_reminders(unreplied_days, unreplied_recipients)) + if unreplied_result.get("skipped_no_recipient"): + errors.append("存在超期未回复订单,但未配置「未回复提醒收件人」(且任务通知人未配置或开关关闭),未发送提醒") + else: + unreplied_result = {"skipped": "disabled", "unreplied_days": unreplied_days} + + # 统计口径:出货提醒按业务员(人)、未回复提醒按收件人生管(人);扫描异常各计 1 笔失败。 + success = int(ship_result.get("notified_salespersons") or 0) + int(unreplied_result.get("notified_recipients") or 0) + failed = ( + int(ship_result.get("failed_salespersons") or 0) + + int(unreplied_result.get("failed_recipients") or 0) + + sum(1 for result in (ship_result, unreplied_result) if result.get("error")) + ) + skipped = int(ship_result.get("skipped_unmapped") or 0) + total = success + failed + skipped + + summary = { + "ship_remind": ship_result, + "unreplied_remind": unreplied_result, + "ship_remind_enabled": ship_enabled, + "unreplied_remind_enabled": unreplied_enabled, + "advance_days": advance_days, + "unreplied_days": unreplied_days, + "unreplied_recipients": unreplied_recipients, + } + step_logs = [{"step": "order_delivery_remind", "status": "success" if failed == 0 else "partial", "detail": summary}] + return (total, success, failed, skipped, [summary], errors, step_logs) diff --git a/backend/app/services/schedule/order_delivery_reply_job.py b/backend/app/services/schedule/order_delivery_reply_job.py new file mode 100644 index 00000000..24a7902a --- /dev/null +++ b/backend/app/services/schedule/order_delivery_reply_job.py @@ -0,0 +1,113 @@ +""" +backend/app/services/schedule/order_delivery_reply_job.py + +用途:将订单交期回复 ERP 全量同步适配到平台排程(ScheduleTask platform_job)。 +依赖:services/order_delivery_reply/sync_service(同步本体)、notify_service(企微事件类型与跳转路径)、 + wecom_notify.send_wecom_event_message、ScheduleTask/ScheduleRun。 +逻辑:排程 worker 每天 07:00(Asia/Shanghai)触发 handler,内部以 trigger='scheduled' + 复用与手动刷新完全相同的 run_sync;同步成功后按任务参数 sync_remind_user_ids + (管理端「同步完成提醒收件人」多选,与运行结果通知的「通知人」互相独立; + 留空回退 notify_user_ids_json 兼容旧配置)给生管发提醒, + 并把 domain_notification_managed 写入 run 摘要,抑制通用「排程执行结果」通知避免重复; + 通知失败不改变同步结果(同步已成功落库,仅记录失败原因)。 + 同步失败向上抛出,由平台排程标记本次运行失败并保留上次快照(sync_runs 已各自留痕)。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask, User + +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] + + +SYNC_REMIND_USER_IDS_KEY = "sync_remind_user_ids" + + +def _read_sync_remind_recipients(task: ScheduleTask) -> list[int]: + """同步完成提醒收件人:优先任务参数 sync_remind_user_ids,留空回退任务通知人(旧配置兼容)。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + raw = params.get(SYNC_REMIND_USER_IDS_KEY) + ids = [int(uid) for uid in raw if uid] if isinstance(raw, list) else [] + if ids: + return ids + if task.notify_enabled: + return [int(uid) for uid in (task.notify_user_ids_json or []) if uid] + return [] + + +def _notify_production_after_sync(task: ScheduleTask, line_count: int) -> list[dict[str, Any]]: + """ + 同步成功后提醒生管查看订单交期回复(收件人 = 任务参数 sync_remind_user_ids,回退通知人)。 + + Args: + task: 触发本次同步的排程任务。 + line_count: 本次同步的订单行数量,用于通知文案。 + Returns: + 逐人发送结果列表 [{user_id, ok, reason?}];未配置收件人时返回空列表。 + """ + from app.services.order_delivery_reply.notify_service import ( + WECOM_EVENT_TYPE, + JUMP_PATH, + ) + from app.services.integrations.wecom.notify import send_wecom_event_message + + user_ids = _read_sync_remind_recipients(task) + if not user_ids: + return [] + + users = User.query.filter(User.id.in_(user_ids)).all() + results: list[dict[str, Any]] = [] + for user in users: + result = send_wecom_event_message( + event_type=WECOM_EVENT_TYPE, + user=user, + title="订单交期回复", + content=f"今日订单交期数据已同步完成(共 {line_count} 行),请及时查看并回复交期。", + jump_path=JUMP_PATH, + # 卡片带 status=not_fully_replied:生管点开直达「未完全回复」视图(待回复行)。 + jump_params={"status": "not_fully_replied"}, + ) + entry: dict[str, Any] = {"user_id": user.id, "ok": bool(result.get("ok"))} + if not entry["ok"]: + entry["reason"] = result.get("reason") + results.append(entry) + return results + + +def run_order_delivery_sync_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """ + 执行订单交期回复 ERP 全量同步(已审核 + 已核准 + 未结案订单行)并提醒生管。 + + Args: + task: 当前排程任务定义。 + run: 当前排程执行记录。 + Returns: + 通用排程审计七元组;同步异常原样抛出,交由平台排程记录失败运行。 + """ + from app.extensions import db + from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService + + summary = OrderDeliverySyncService.run_sync(trigger="scheduled") + count = int(summary.get("line_count") or 0) + + # [STEP 2] 域内已自行通知生管:写入标记,抑制通用「排程执行结果」企微通知避免双重打扰。 + # 直调(run=None,脚本/测试)时跳过 run 摘要写入。 + if run is not None: + run.response_summary_json = {"domain_notification_managed": True} + db.session.commit() + + notify_results = _notify_production_after_sync(task, count) + failed_notify = [item for item in notify_results if not item["ok"]] + step_logs = [ + { + "step": "order_delivery_sync", + "status": "success", + "detail": {**summary, "production_notify": notify_results}, + } + ] + errors: list[str] = [ + f"生管通知发送失败 user_id={item['user_id']} reason={item.get('reason')}" for item in failed_notify + ] + return (count, count, 0, 0, [summary], errors, step_logs) diff --git a/backend/app/services/schedule/web_scanner.py b/backend/app/services/schedule/web_scanner.py new file mode 100644 index 00000000..188bf8fa --- /dev/null +++ b/backend/app/services/schedule/web_scanner.py @@ -0,0 +1,63 @@ +""" +backend/app/services/schedule/web_scanner.py + +用途:Web 进程内的排程扫描兜底线程——让开发环境(只跑 run.py,没有独立 schedule-worker + 容器)也能按 cron 触发到期排程(如订单交期回复每天 07:00 的 ERP 全量同步)。 +依赖:app.jobs.runner.run_forever、app.jobs.store.claim_next(schedule 队列)、JobContext。 +逻辑:create_app 启动时按 SCHEDULE_WEB_SCANNER_ENABLED 决定是否拉起守护线程;线程内 + 推送 app context 后复用与 workers/worker_scheduler.py 完全相同的消费路径 + (claim_next('schedule') → prepare_schedule_queue 扫描到期任务 → handler 执行)。 + 多进程并发安全由 enqueue_due_schedule_runs 的 FOR UPDATE SKIP LOCKED 与 + schedule_runs 活动 run 去重保证,与独立 worker 并存不会重复执行。 + 生产环境默认关闭(compose 已有 hxops-schedule-worker 专职容器),可用环境变量覆盖。 +""" + +from __future__ import annotations + +import threading + +_web_scanner_started = False +_web_scanner_lock = threading.Lock() + + +def start_web_schedule_scanner(app) -> None: + """ + 按配置在 Web 进程内启动排程扫描守护线程(幂等;重复调用直接返回)。 + + 用途与触发时机:create_app 启动阶段调用;AI/请求路径不触发。 + 开发环境默认开启(SCHEDULE_WEB_SCANNER_ENABLED 缺省 true), + 生产环境默认关闭(缺省 false,由 hxops-schedule-worker 容器负责)。 + + 核心逻辑:[STEP 1] 读 SCHEDULE_WEB_SCANNER_ENABLED,关闭则不打扰; + [STEP 2] 进程内单例锁后起 daemon 线程,线程内推送 app context、 + 导入 handlers、复用 run_forever(queues=['schedule']) 主循环。 + """ + global _web_scanner_started + + enabled = bool(app.config.get("SCHEDULE_WEB_SCANNER_ENABLED", False)) + if not enabled: + app.logger.info("Web schedule scanner disabled by SCHEDULE_WEB_SCANNER_ENABLED=false") + return + + with _web_scanner_lock: + if _web_scanner_started: + return + + def _loop(app_ref=app): + with app_ref.app_context(): + import app.jobs.handlers # noqa: F401 — 触发 @register_handler + from app.jobs.context import JobContext + from app.jobs.runner import run_forever + + ctx = JobContext( + config=dict(app_ref.config), + logger=app_ref.logger, + extras={"queues": ["schedule"]}, + ) + app_ref.logger.info("Web schedule scanner starting (queues=['schedule'])") + run_forever(ctx) + + thread = threading.Thread(target=_loop, name="web-schedule-scanner", daemon=True) + thread.start() + _web_scanner_started = True + app.logger.info("Web schedule scanner started") diff --git a/backend/migrations/versions/959afe816337_merge_order_delivery_reply_and_dev_heads.py b/backend/migrations/versions/959afe816337_merge_order_delivery_reply_and_dev_heads.py new file mode 100644 index 00000000..f5421c75 --- /dev/null +++ b/backend/migrations/versions/959afe816337_merge_order_delivery_reply_and_dev_heads.py @@ -0,0 +1,24 @@ +"""merge order-delivery-reply and dev heads + +Revision ID: 959afe816337 +Revises: a7c1d2e3f4b9, rc2b3c4d5e6f +Create Date: 2026-09-22 09:21:43.949845 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '959afe816337' +down_revision = ('a7c1d2e3f4b9', 'rc2b3c4d5e6f') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/migrations/versions/9e5045511198_merge_migration_heads_after_dev_auto_.py b/backend/migrations/versions/9e5045511198_merge_migration_heads_after_dev_auto_.py new file mode 100644 index 00000000..b2104770 --- /dev/null +++ b/backend/migrations/versions/9e5045511198_merge_migration_heads_after_dev_auto_.py @@ -0,0 +1,24 @@ +"""merge migration heads after dev auto-transfer merge + +Revision ID: 9e5045511198 +Revises: b8baf0905ec6, t5a6b7c8d9e0f +Create Date: 2026-09-30 08:38:49.231759 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9e5045511198' +down_revision = ('b8baf0905ec6', 't5a6b7c8d9e0f') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/migrations/versions/a7c1d2e3f4b9_add_order_delivery_reply_tables.py b/backend/migrations/versions/a7c1d2e3f4b9_add_order_delivery_reply_tables.py new file mode 100644 index 00000000..61a14dd8 --- /dev/null +++ b/backend/migrations/versions/a7c1d2e3f4b9_add_order_delivery_reply_tables.py @@ -0,0 +1,155 @@ +"""add order delivery reply tables + +Revision ID: a7c1d2e3f4b9 +Revises: 353ebb6187ce +Create Date: 2026-09-16 + +用途:订单交期回复一期建表迁移,对应模型 app/models/order_delivery_reply.py。 +依赖:users 表(批次/状态/审计的操作人与通知人外键);基线 353ebb6187ce(多分支 merge head)。 +逻辑:up 建五张本地表(ERP 行快照 / 交期批次 / 行级锁定 / 审计 / 同步运行); + down 逆序整域回滚。手写原因:autogenerate 被既有 shipping 超长索引名问题阻断,与本域无关。 + 红线:改列/改表必须出新迁移,禁止改动本文件已上线的 upgrade/downgrade。 +""" + +from alembic import op +import sqlalchemy as sa + +revision = 'a7c1d2e3f4b9' +down_revision = '353ebb6187ce' +branch_labels = None +depends_on = None + + +def upgrade(): + """ + 建表:五张表按依赖顺序创建(快照表先行,其余三表以 line_id 外键挂靠)。 + + 写边界约定(与模型层一致,供后续迁移审查对照): + - erp_lines 仅同步服务写 ERP 快照列;batches 仅保存回复路径写; + line_states.locked 仅通知成功事务写;audit_events / sync_runs 各自路径留痕。 + - slip_code 一期只落库预留(单别白名单后期启用),列表不出该列。 + - erp_missing 默认 false;本轮同步未命中的行由同步服务置 true,不物理删除。 + """ + # ERP 订单行快照:唯一键 (order_no, line_no);(order_no, line_no) 上的业务行均由此表派生。 + op.create_table( + 'order_delivery_erp_lines', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_no', sa.String(length=64), nullable=False), + sa.Column('line_no', sa.Integer(), nullable=False), + sa.Column('order_date', sa.Date(), nullable=True), + sa.Column('customer_no', sa.String(length=64), nullable=True), + sa.Column('customer_short_name', sa.String(length=255), nullable=True), + sa.Column('customer_full_name', sa.String(length=255), nullable=True), + sa.Column('salesperson_code', sa.String(length=64), nullable=True), + sa.Column('salesperson_name', sa.String(length=255), nullable=True), + sa.Column('dept_code', sa.String(length=64), nullable=True), + sa.Column('dept_name', sa.String(length=255), nullable=True), + sa.Column('customer_po', sa.String(length=128), nullable=True), + sa.Column('part_no', sa.String(length=128), nullable=True), + sa.Column('part_name', sa.String(length=512), nullable=True), + sa.Column('spec', sa.String(length=512), nullable=True), + sa.Column('customer_part_no', sa.String(length=128), nullable=True), + sa.Column('agreed_date', sa.Date(), nullable=True), + sa.Column('unit', sa.String(length=32), nullable=True), + sa.Column('qty', sa.Numeric(18, 4), nullable=True), + sa.Column('delivered_qty', sa.Numeric(18, 4), nullable=True), + sa.Column('slip_code', sa.String(length=32), nullable=True), + sa.Column('erp_missing', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('last_synced_at', sa.DateTime(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('order_no', 'line_no', name='uq_order_delivery_erp_lines_order_line'), + ) + op.create_index('ix_order_delivery_erp_lines_order_date', 'order_delivery_erp_lines', ['order_date']) + op.create_index('ix_order_delivery_erp_lines_customer_no', 'order_delivery_erp_lines', ['customer_no']) + op.create_index('ix_order_delivery_erp_lines_salesperson', 'order_delivery_erp_lines', ['salesperson_code']) + op.create_index('ix_order_delivery_erp_lines_slip_code', 'order_delivery_erp_lines', ['slip_code']) + op.create_index('ix_order_delivery_erp_lines_erp_missing', 'order_delivery_erp_lines', ['erp_missing']) + + # 交期批次:未锁定行保存时整表替换(line_id + seq 唯一);remark ≤200 由 API 层校验,库层只限长。 + op.create_table( + 'order_delivery_batches', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('line_id', sa.Integer(), nullable=False), + sa.Column('seq', sa.Integer(), nullable=False), + sa.Column('planned_date', sa.Date(), nullable=False), + sa.Column('qty', sa.Numeric(18, 4), nullable=False), + sa.Column('remark', sa.String(length=200), nullable=True), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['line_id'], ['order_delivery_erp_lines.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['created_by'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('line_id', 'seq', name='uq_order_delivery_batches_line_seq'), + ) + op.create_index('ix_order_delivery_batches_line', 'order_delivery_batches', ['line_id']) + + # 行级锁定状态:一行一态(line_id 唯一);locked 只在「企微通知成功」同一事务内置 true, + # 快照字段存最近一次通知成功的生管工号/姓名,满足 R-NOTIFY-03 审计回溯。 + op.create_table( + 'order_delivery_line_states', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('line_id', sa.Integer(), nullable=False), + sa.Column('locked', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('notified_user_id', sa.Integer(), nullable=True), + sa.Column('notified_employee_id', sa.String(length=64), nullable=True), + sa.Column('notified_user_name', sa.String(length=255), nullable=True), + sa.Column('notified_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['line_id'], ['order_delivery_erp_lines.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['notified_user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('line_id', name='uq_order_delivery_line_states_line'), + ) + + # 审计:action ∈ save | notify | lock | sync;sync 类事件无具体行,line_id/order_no 允许为空。 + op.create_table( + 'order_delivery_audit_events', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('line_id', sa.Integer(), nullable=True), + sa.Column('order_no', sa.String(length=64), nullable=True), + sa.Column('line_no', sa.Integer(), nullable=True), + sa.Column('action', sa.String(length=32), nullable=False), + sa.Column('operator_user_id', sa.Integer(), nullable=True), + sa.Column('payload_json', sa.JSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['line_id'], ['order_delivery_erp_lines.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['operator_user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_order_delivery_audit_events_line', 'order_delivery_audit_events', ['line_id']) + op.create_index('ix_order_delivery_audit_events_action', 'order_delivery_audit_events', ['action', 'created_at']) + + # 同步运行记录:每次 07:00 排程或手动刷新各写一行;失败保留上次快照,仅状态置 failed 留痕。 + op.create_table( + 'order_delivery_sync_runs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('trigger', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=False), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('line_count', sa.Integer(), nullable=False, server_default='0'), + sa.Column('error_message', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_order_delivery_sync_runs_started', 'order_delivery_sync_runs', ['started_at']) + + +def downgrade(): + """逆序回滚:先删挂靠表(索引随表,但显式 drop index 与 upgrade 对称),最后删快照主表。""" + op.drop_index('ix_order_delivery_sync_runs_started', table_name='order_delivery_sync_runs') + op.drop_table('order_delivery_sync_runs') + op.drop_index('ix_order_delivery_audit_events_action', table_name='order_delivery_audit_events') + op.drop_index('ix_order_delivery_audit_events_line', table_name='order_delivery_audit_events') + op.drop_table('order_delivery_audit_events') + op.drop_table('order_delivery_line_states') + op.drop_index('ix_order_delivery_batches_line', table_name='order_delivery_batches') + op.drop_table('order_delivery_batches') + op.drop_index('ix_order_delivery_erp_lines_erp_missing', table_name='order_delivery_erp_lines') + op.drop_index('ix_order_delivery_erp_lines_slip_code', table_name='order_delivery_erp_lines') + op.drop_index('ix_order_delivery_erp_lines_salesperson', table_name='order_delivery_erp_lines') + op.drop_index('ix_order_delivery_erp_lines_customer_no', table_name='order_delivery_erp_lines') + op.drop_index('ix_order_delivery_erp_lines_order_date', table_name='order_delivery_erp_lines') + op.drop_table('order_delivery_erp_lines') diff --git a/backend/migrations/versions/b8baf0905ec6_merge_migration_heads_after_dev_role_.py b/backend/migrations/versions/b8baf0905ec6_merge_migration_heads_after_dev_role_.py new file mode 100644 index 00000000..1525379d --- /dev/null +++ b/backend/migrations/versions/b8baf0905ec6_merge_migration_heads_after_dev_role_.py @@ -0,0 +1,24 @@ +"""merge migration heads after dev role merge + +Revision ID: b8baf0905ec6 +Revises: d0304d47d364, mh3b4c5d6e7f +Create Date: 2026-09-29 15:32:31.593063 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'b8baf0905ec6' +down_revision = ('d0304d47d364', 'mh3b4c5d6e7f') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/migrations/versions/d0304d47d364_merge_migration_heads_after_dev_merge.py b/backend/migrations/versions/d0304d47d364_merge_migration_heads_after_dev_merge.py new file mode 100644 index 00000000..1f014267 --- /dev/null +++ b/backend/migrations/versions/d0304d47d364_merge_migration_heads_after_dev_merge.py @@ -0,0 +1,24 @@ +"""merge migration heads after dev merge + +Revision ID: d0304d47d364 +Revises: 6d7b0d04ac25, d425edfa336c, p1b2c3d4e5f6 +Create Date: 2026-09-29 14:39:03.805744 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd0304d47d364' +down_revision = ('6d7b0d04ac25', 'd425edfa336c', 'p1b2c3d4e5f6') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/migrations/versions/d425edfa336c_merge_migration_heads.py b/backend/migrations/versions/d425edfa336c_merge_migration_heads.py new file mode 100644 index 00000000..2c4dd26b --- /dev/null +++ b/backend/migrations/versions/d425edfa336c_merge_migration_heads.py @@ -0,0 +1,24 @@ +"""merge migration heads + +Revision ID: d425edfa336c +Revises: 43a8179cdd88, 959afe816337 +Create Date: 2026-09-23 11:59:11.702696 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd425edfa336c' +down_revision = ('43a8179cdd88', '959afe816337') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/scripts/order_delivery_query.py b/backend/scripts/order_delivery_query.py new file mode 100644 index 00000000..3b7b75e0 --- /dev/null +++ b/backend/scripts/order_delivery_query.py @@ -0,0 +1,72 @@ +""" +scripts/order_delivery_query.py + +Purpose: 订单交期回复(order-delivery-reply)功能的 ERP 取数查询原型——按目标展示顺序关联 + 订单头/身/料件/客户/员工/部门,过滤已审核、已核准、未结案订单行。 +Dependencies: python-oracledb;连接约定与 services/text2sql.py 一致(ERP_DB_DSN,默认 192.168.8.24:1521/topprod)。 +Flow: 本脚本可独立运行验证 SQL 与数据;后续 order-delivery-reply 后端服务应引用 + ORDER_DELIVERY_SQL 常量(或迁移为 service 方法),保持口径一致。 +""" + +import os +import sys +from pathlib import Path + +# [STEP 1] 让脚本可独立运行:把 backend/ 加入 sys.path 后复用服务包中的权威 SQL 常量。 +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL # noqa: E402 + +# 订单交期查询列的中文展示名,顺序与服务层 ORDER_DELIVERY_SQL 别名一一对应(仅本脚本预览使用)。 +COLUMN_LABELS = [ + "订单单号", "项次", "订单日期", "客户编号", "客户简称", "公司全名", + "业务员工号", "业务员", "部门编码", "部门", "客户订单", + "产品编号", "品名", "规格", "客户产品编号", "约定交货日", "单位", "数量", "已交数量", +] + +# 预览用 SQL:按目标展示顺序排序。业务约束:仅做只读 SELECT,禁止改写为 INSERT/UPDATE/DELETE。 +PREVIEW_SQL = f"{ORDER_DELIVERY_SQL} ORDER BY a.oea02, a.oea03, a.oea01, b.oeb03" + + +def fetch_order_delivery(limit=None): + """ + 执行订单交期查询并返回列名与数据行。 + + 用途与触发时机:验证/预览订单交期明细;联调 order-delivery-reply 功能时用于人工核对 ERP 数据。 + + 核心逻辑:[STEP 1] 读取 ERP_DB_USER / ERP_DB_PASSWORD / ERP_DB_DSN 连接 topprod; + [STEP 2] 执行 PREVIEW_SQL(可选 ROWNUM 限行预览),SQL 本体复用服务包权威常量; + [STEP 3] 返回 (columns, rows);连接或执行异常原样抛出。 + + 参数与输出约束:limit 为可选最大行数(业务约束:仅限人工预览使用,禁止在正式服务链路传 None 全量拉取); + 返回 (list[str], list[tuple]),列名为目标展示顺序的中文字段名(COLUMN_LABELS)。 + """ + import oracledb + + # 凭据回退链与服务层 sync_service._connect 一致:专用键 → 合同付款预警的共享配置。 + user = os.getenv("ERP_DB_USER") or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME", "EXT_VIEW_USER") + password = os.getenv("ERP_DB_PASSWORD") or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD") + dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod") + if not password: + raise RuntimeError( + "ERP 口令未配置:请设置 ERP_DB_PASSWORD,或复用 .env.shared 的 " + "CONTRACT_PAYMENT_ERP_PASSWORD(与合同付款预警同一 topprod 连接)" + ) + + sql = PREVIEW_SQL + if limit: + sql = f"SELECT * FROM ({sql}) WHERE ROWNUM <= {int(limit)}" + + with oracledb.connect(user=user, password=password, dsn=dsn) as conn: + with conn.cursor() as cursor: + cursor.execute(sql) + rows = cursor.fetchall() + # 列名以常量映射为权威,不依赖 DB 返回的英文别名。 + return list(COLUMN_LABELS), rows + + +if __name__ == "__main__": + cols, data = fetch_order_delivery(limit=50) + print(" | ".join(cols)) + for row in data: + print(" | ".join("" if v is None else str(v) for v in row)) + print(f"-- 共 {len(data)} 行") diff --git a/backend/tests/services/admin/test_dashboard_service.py b/backend/tests/services/admin/test_dashboard_service.py index a6229c6e..d1e498d6 100644 --- a/backend/tests/services/admin/test_dashboard_service.py +++ b/backend/tests/services/admin/test_dashboard_service.py @@ -2,11 +2,11 @@ tests/services/admin/test_dashboard_service.py 用途:dashboard_service 统计聚合单元测试。 +说明:侧栏角标(pending_approvals / pending_requests)已随用户审批功能下线一并删除 + (dev commit 07e83132「删除用户审批功能」),2026-09-29 删除对应失效用例, + legacy 统计断言对齐现役四键(total_users / active_agents / total_conversations / avg_score)。 """ -from app import db -from app.models import Agent, ChatLog, Feedback, PermissionRequest, User from app.services.admin.dashboard_service import ( - compute_dashboard_badges, compute_dashboard_summary, compute_legacy_dashboard_stats, ) @@ -21,24 +21,10 @@ def test_compute_dashboard_summary_empty(app): assert summary['avg_score'] == 0.0 -def test_compute_dashboard_badges_counts_pending(app): - with app.app_context(): - user = User(username='pending-u', email='p@example.com', status='pending', role='user') - agent = Agent(name='a1', is_active=True) - db.session.add_all([user, agent]) - db.session.flush() - req = PermissionRequest(user_id=user.id, agent_id=agent.id, status='pending', reason='test') - db.session.add(req) - db.session.commit() - - badges = compute_dashboard_badges() - assert badges['pending_approvals'] >= 1 - assert badges['pending_requests'] >= 1 - - def test_compute_legacy_dashboard_stats_keys(app): with app.app_context(): stats = compute_legacy_dashboard_stats() assert 'total_users' in stats - assert 'pending_approvals' in stats - assert 'pending_requests' in stats + assert 'active_agents' in stats + assert 'total_conversations' in stats + assert 'avg_score' in stats diff --git a/backend/tests/services/admin/test_permission_service.py b/backend/tests/services/admin/test_permission_service.py index a466a7f2..0efcb287 100644 --- a/backend/tests/services/admin/test_permission_service.py +++ b/backend/tests/services/admin/test_permission_service.py @@ -1,13 +1,15 @@ """ tests/services/admin/test_permission_service.py -用途:permission_service 批量授权与权限申请审批单元测试。 +用途:permission_service 批量授权单元测试。 +说明:权限申请审批后端已随 dev 重构整体下线(approve_permission_request/list_permission_requests + 已删除,PermissionRequest 仅保留删 Agent/用户时的级联清理),2026-09-29 删除对应失效用例。 """ import pytest from app import db -from app.core.errors import ForbiddenError, NotFoundError, ValidationError -from app.models import Agent, PermissionRequest, User +from app.core.errors import ValidationError +from app.models import Agent, User from app.services.admin import permission_service @@ -48,32 +50,3 @@ def test_batch_update_permissions_no_users(app): with app.app_context(): with pytest.raises(ValidationError): permission_service.batch_update_permissions({'user_ids': [], 'agent_ids': [1]}) - - -def test_permission_request_approve(app, monkeypatch): - with app.app_context(): - agent = Agent(name='req-agent', type='api', dify_app_id='app-r', dify_api_key='key-r') - user = User(username='req-user', email='req@example.com', role='user') - db.session.add_all([agent, user]) - db.session.flush() - req = PermissionRequest(user_id=user.id, agent_id=agent.id, reason='need access', status='pending') - db.session.add(req) - db.session.commit() - - monkeypatch.setattr( - 'app.services.admin.permission_service.send_wecom_event_message', - lambda **kwargs: None, - ) - - permission_service.approve_permission_request(req.id) - db.session.refresh(req) - db.session.refresh(user) - assert req.status == 'approved' - assert req.reviewed_at is not None - assert agent in user.agents - - -def test_permission_request_not_found(app): - with app.app_context(): - with pytest.raises(NotFoundError): - permission_service.approve_permission_request(999999) diff --git a/backend/tests/services/admin/test_report_service.py b/backend/tests/services/admin/test_report_service.py index 9e1de5a5..6e340855 100644 --- a/backend/tests/services/admin/test_report_service.py +++ b/backend/tests/services/admin/test_report_service.py @@ -109,8 +109,7 @@ def test_build_feedback_report(app): def test_build_application_report(app): - """应用运营报表应聚合对话 / 授权 / 待审 / 评分,且不含配置敏感字段。""" - from app.models import PermissionRequest + """应用运营报表应聚合对话 / 授权 / 评分,且不含配置敏感字段。""" from app.models.base import user_agent_permissions with app.app_context(): @@ -126,8 +125,9 @@ def test_build_application_report(app): db.session.execute( user_agent_permissions.insert().values(user_id=user.id, agent_id=hot.id) ) - db.session.add( - PermissionRequest(user_id=user.id, agent_id=cold.id, reason='need', status='pending') + # cold-app 授权但零对话:验证「授权闲置」标记(原 pending_requests 断言已随审批功能下线删除) + db.session.execute( + user_agent_permissions.insert().values(user_id=user.id, agent_id=cold.id) ) db.session.commit() @@ -136,7 +136,6 @@ def test_build_application_report(app): assert data['summary']['agent_total'] >= 2 assert data['summary']['used_agents'] >= 1 assert data['summary']['unused_agents'] >= 1 - assert data['summary']['pending_permission_total'] >= 1 by_name = {item['name']: item for item in data['items']} assert 'hot-app' in by_name @@ -145,7 +144,8 @@ def test_build_application_report(app): assert by_name['hot-app']['authorized_users'] == 1 assert by_name['hot-app']['avg_score'] == 4.0 assert by_name['cold-app']['chat_count'] == 0 - assert by_name['cold-app']['pending_requests'] == 1 + # 断言:已授权但零对话的应用标记为授权闲置(pending_requests 断言已随审批功能下线删除) + assert by_name['cold-app']['authorized_unused'] is True # 断言:导出字段不含 API Key assert 'dify_api_key' not in by_name['hot-app'] assert 'api_base_url' not in by_name['hot-app'] diff --git a/backend/tests/services/permission_roles/__init__.py b/backend/tests/services/permission_roles/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/tests/services/permission_roles/test_catalog.py b/backend/tests/services/permission_roles/test_catalog.py new file mode 100644 index 00000000..13c65b69 --- /dev/null +++ b/backend/tests/services/permission_roles/test_catalog.py @@ -0,0 +1,51 @@ +""" +tests/services/permission_roles/test_catalog.py + +用途:角色包能力目录与订单交期回复权限键的回归测试。 +依赖:conftest 的 app 夹具(testing + sqlite create_all)、permission_roles catalog/service。 +逻辑:[防回归] KNOWN_FEATURE_KEYS / FEATURE_CATALOG / User 旧默认值三处必须都包含 + order_delivery_reply.manage|access——角色包启用后 effective_feature_permissions + 只输出 KNOWN_FEATURE_KEYS 内的键,catalog 漏登记会导致该功能权限全员失效 + (2026-09-29 合并 dev 角色包时发现并登记)。 +""" +from app import db +from app.models import PermissionRole, User +from app.services.permission_roles.catalog import FEATURE_CATALOG, KNOWN_FEATURE_KEYS +from app.services.permission_roles.service import effective_feature_permissions, roles_configured + +ODR_KEYS = {'order_delivery_reply.manage', 'order_delivery_reply.access'} + + +def test_catalog_covers_order_delivery_reply_keys(): + """catalog 双登记(KNOWN_FEATURE_KEYS + FEATURE_CATALOG)不漂移,且包含订单交期回复两键。""" + assert ODR_KEYS <= set(KNOWN_FEATURE_KEYS) + catalog_keys = {entry['key'] for entry in FEATURE_CATALOG} + assert ODR_KEYS <= catalog_keys + # 断言:两处键集合一致,防止只改一处导致角色包展示与实际输出不一致 + assert set(KNOWN_FEATURE_KEYS) == catalog_keys + + +def test_effective_permissions_include_odr_keys_when_packaged(app): + """角色包启用后:平台管理包隐式全开含 odr 两键;非管理员包按勾选精确输出。""" + with app.app_context(): + admin_role = PermissionRole( + code='admin', name='管理员', is_platform_admin=True, is_system=True, + ) + manager_role = PermissionRole( + code='production', name='生管', + feature_permissions={'order_delivery_reply.manage': True}, + ) + admin_user = User(username='odr-admin', email='odr-a@example.com', role='admin') + manager_user = User(username='odr-manager', email='odr-m@example.com', role='production') + db.session.add_all([admin_role, manager_role, admin_user, manager_user]) + db.session.commit() + + assert roles_configured() is True + admin_perms = effective_feature_permissions(admin_user) + # 断言:平台管理包隐式全开 KNOWN_FEATURE_KEYS,订单交期回复两键为 True + assert ODR_KEYS <= {key for key, value in admin_perms.items() if value} + + manager_perms = effective_feature_permissions(manager_user) + # 断言:非管理员包只开勾选键——manage=True,access 未勾=False(两键独立授予) + assert manager_perms['order_delivery_reply.manage'] is True + assert manager_perms['order_delivery_reply.access'] is False diff --git a/backend/tests/test_order_delivery_query.py b/backend/tests/test_order_delivery_query.py new file mode 100644 index 00000000..e7ce96e5 --- /dev/null +++ b/backend/tests/test_order_delivery_query.py @@ -0,0 +1,103 @@ +""" +tests/test_order_delivery_query.py + +用途:订单交期回复列表合并关键词搜索(keyword OR 语义)的单测。 +依赖:conftest 的 app 夹具(testing + sqlite create_all)、query_service.list_lines。 +逻辑:keyword 命中订单单号/客户编号/产品编号/品名等任一字段即返回该行; + 订单维度命中时该订单全部项次返回;日期与状态筛选行为不回归。 +""" + +from datetime import date +from decimal import Decimal + +from app.extensions import db +from app.models.order_delivery_reply import OrderDeliveryErpLine +from app.services.order_delivery_reply.query_service import list_lines + + +def _line(order_no, line_no, *, cust_no="C001", part_no="P-1", part_name="标准物料", cust_part="CP-1"): + """构造一行最小快照(字段名/值供 keyword 断言用)。""" + row = OrderDeliveryErpLine( + order_no=order_no, + line_no=line_no, + order_date=date(2024, 6, 1), + customer_no=cust_no, + customer_short_name="恒远电子", + part_no=part_no, + part_name=part_name, + customer_part_no=cust_part, + qty=Decimal("100"), + delivered_qty=Decimal("0"), + erp_missing=False, + ) + db.session.add(row) + return row + + +def test_keyword_matches_any_field_or_semantics(app): + """keyword 命中订单单号/客户编号/品名任一字段即返回(OR)。""" + _line("8301-A", 1, part_name="驱动齿轮") + _line("8301-B", 1, cust_no="C999") + _line("8301-C", 1, part_no="P-XYZ") + db.session.commit() + + # 断言:品名命中 → 只返回 8301-A + assert [i["order_no"] for i in list_lines({"keyword": "齿轮"})["items"]] == ["8301-A"] + # 断言:客户编号命中 → 只返回 8301-B + assert [i["order_no"] for i in list_lines({"keyword": "C999"})["items"]] == ["8301-B"] + # 断言:产品编号命中 → 只返回 8301-C(大小写不敏感) + assert [i["order_no"] for i in list_lines({"keyword": "p-xyz"})["items"]] == ["8301-C"] + # 断言:订单单号片段命中 → 8301-A + assert [i["order_no"] for i in list_lines({"keyword": "8301-A"})["items"]] == ["8301-A"] + # 断言:无命中 → 空 + assert list_lines({"keyword": "不存在"})["items"] == [] + # 断言:空关键词 = 全部 + assert list_lines({})["total"] == 3 + + +def test_keyword_and_date_status_filters_stack(app): + """keyword 与 order_date/status 叠加时仍为 AND 语义。""" + _line("8301-D", 1, part_name="齿轮") + _line("8301-E", 1, part_name="齿轮") + db.session.commit() + + from app.models.order_delivery_reply import OrderDeliveryBatch + + db.session.add(OrderDeliveryBatch(line_id=2, seq=1, planned_date=date(2024, 7, 1), qty=1)) + db.session.commit() + + # 断言:关键词 + 日期叠加 → 只留同时满足的行 + result = list_lines({"keyword": "齿轮", "order_date": "2024-06-01"}) + assert result["total"] == 2 + result = list_lines({"keyword": "齿轮", "order_date": "2024-06-02"}) + assert result["total"] == 0 + # 断言:status=not_fully_replied(未锁定)两行都算;有批次的行仍是未锁定(部分回复) + assert list_lines({"keyword": "齿轮", "status": "not_fully_replied"})["total"] == 2 + + +def test_keyword_matches_salesperson_and_reply_person(app): + """keyword 命中业务员(姓名/工号)与交期回复人员(姓名/工号)即返回(2026-09-23 增补)。""" + from app.models.order_delivery_reply import OrderDeliveryLineState + + salesperson_line = _line("8301-P1", 1, cust_no="C-A") + salesperson_line.salesperson_name = "王瑞雪" + salesperson_line.salesperson_code = "26070045" + replied_line = _line("8301-P2", 2, cust_no="C-B") + replied_line.salesperson_name = "张小奇" + db.session.flush() + # 交期回复人员快照存于行状态表(notified_user_name / notified_employee_id) + db.session.add(OrderDeliveryLineState( + line_id=replied_line.id, notified_user_name="李生", notified_employee_id="10002", + )) + db.session.commit() + + # 断言:业务员姓名命中 → 只返回 8301-P1 + assert [i["order_no"] for i in list_lines({"keyword": "王瑞雪"})["items"]] == ["8301-P1"] + # 断言:业务员工号命中 → 只返回 8301-P1 + assert [i["order_no"] for i in list_lines({"keyword": "26070045"})["items"]] == ["8301-P1"] + # 断言:交期回复人员姓名命中(状态表 EXISTS 子查询)→ 只返回 8301-P2 + assert [i["order_no"] for i in list_lines({"keyword": "李生"})["items"]] == ["8301-P2"] + # 断言:交期回复人员工号命中 → 只返回 8301-P2 + assert [i["order_no"] for i in list_lines({"keyword": "10002"})["items"]] == ["8301-P2"] + # 断言:未命中任何人员 → 空 + assert list_lines({"keyword": "不存在的名字"})["items"] == [] diff --git a/backend/tests/test_order_delivery_reminder.py b/backend/tests/test_order_delivery_reminder.py new file mode 100644 index 00000000..7bf088f6 --- /dev/null +++ b/backend/tests/test_order_delivery_reminder.py @@ -0,0 +1,335 @@ +""" +tests/test_order_delivery_reminder.py + +用途:订单交期回复每日提醒(出货提醒 / 未回复再提醒)与 Web 排程兜底扫描的单测。 +依赖:conftest 的 app 夹具(testing + sqlite create_all)、reminder_service、web_scanner。 +逻辑:出货提醒验证「窗口内锁定行按业务员聚合一、去重只发一次、未映射业务员记失败审计」; + 未回复提醒验证「超期行聚合提醒生管、N 天内不重复提醒、无收件人跳过」; + 企微发送以 monkeypatch 替身控制成败,不触网。 +""" + +from datetime import datetime, timedelta +from decimal import Decimal + +import pytest + +from app import db +from app.extensions import db as db_ext +from app.models import User +from app.models.order_delivery_reply import ( + OrderDeliveryAuditEvent, + OrderDeliveryBatch, + OrderDeliveryErpLine, + OrderDeliveryLineState, +) +from app.services.order_delivery_reply.reminder_service import ( + ACTION_SHIP_REMIND, + ACTION_UNREPLIED_REMIND, + run_ship_reminders, + run_unreplied_reminders, +) + + +def _make_line(order_no="8301-1605280014", line_no=1, salesperson="10001", order_days_ago=0): + """构造一行已同步快照(order_days_ago 控制订单日期距今天数,即未回复超期判定的锚点)。""" + line = OrderDeliveryErpLine( + order_no=order_no, + line_no=line_no, + order_date=datetime.utcnow().date() - timedelta(days=order_days_ago), + customer_no="C001", + salesperson_code=salesperson, + qty=Decimal("100"), + delivered_qty=Decimal("0"), + erp_missing=False, + ) + db.session.add(line) + db.session.flush() + return line + + +def _lock_line(line, planned_date): + """锁定行 + 一个批次:出货提醒候选(已回复 = 已锁定)。""" + db.session.add(OrderDeliveryBatch(line_id=line.id, seq=1, planned_date=planned_date, qty=Decimal("100"))) + db.session.add(OrderDeliveryLineState(line_id=line.id, locked=True)) + db.session.flush() + + +def _make_user(employee_id, wecom_userid="wx_10001"): + """构造已绑企微的用户(出货提醒收件人按 employee_id 映射)。""" + user = User( + username=f"u_{employee_id}", + email=f"u_{employee_id}@test.local", + real_name=f"业务{employee_id}", + employee_id=employee_id, + wecom_userid=wecom_userid, + role="user", + ) + db.session.add(user) + db.session.flush() + return user + + +@pytest.fixture +def send_recorder(monkeypatch): + """替身企微发送:记录 (收件人, 正文) 并可 scripted 控制成败;断言「发送过几条、发给谁」。""" + calls = {"list": [], "ok": True} + + def _fake_send(event_type, user, title, content, jump_path="/workspace", jump_params=None, **_kw): + calls["list"].append({"user": user, "content": content, "jump_path": jump_path}) + return {"ok": calls["ok"], "trace_id": "t-" + str(len(calls["list"]))} + + monkeypatch.setattr( + "app.services.order_delivery_reply.reminder_service.send_wecom_event_message", _fake_send + ) + return calls + + +def test_ship_reminder_groups_by_salesperson_and_dedupes(app, send_recorder): + """窗口内两行同业务员 → 只发 1 条聚合卡片;再次扫描同 (行, 交期) 不重发。""" + from datetime import date + + _make_user("10001") + today = date.today() + line_a = _make_line(order_no="8301-A", line_no=1) + line_b = _make_line(order_no="8301-B", line_no=2) + _lock_line(line_a, today + timedelta(days=3)) + _lock_line(line_b, today + timedelta(days=2)) + db.session.commit() + + result = run_ship_reminders(advance_days=3) + # 断言:候选 2 行、聚合后只发 1 人 1 条 + assert result["candidate_lines"] == 2 + assert result["notified_salespersons"] == 1 + assert len(send_recorder["list"]) == 1 + assert "8301-A:1" in send_recorder["list"][0]["content"] + assert "8301-B:2" in send_recorder["list"][0]["content"] + + # 再次扫描:同 (行, 交期) 已成功提醒过,不得重发 + second = run_ship_reminders(advance_days=3) + assert second["candidate_lines"] == 2 + assert second["notified_salespersons"] == 0 + assert len(send_recorder["list"]) == 1 + + +def test_ship_reminder_retries_after_failed_send(app, send_recorder): + """发送失败不算已提醒:次日(再次扫描)应自动补发。""" + from datetime import date + + _make_user("10001") + line = _make_line(order_no="8301-C", line_no=1) + _lock_line(line, date.today() + timedelta(days=1)) + db.session.commit() + + send_recorder["ok"] = False + failed = run_ship_reminders(advance_days=3) + # 断言:失败发送计入 failed 且仍落审计(ok=false 不参与去重) + assert failed["notified_salespersons"] == 0 + assert failed["failed_salespersons"] == 1 + ok_events = [ + e for e in OrderDeliveryAuditEvent.query.filter_by(action=ACTION_SHIP_REMIND).all() + if (e.payload_json or {}).get("ok") is True + ] + assert ok_events == [] + + send_recorder["ok"] = True + retried = run_ship_reminders(advance_days=3) + # 断言:第二次扫描补发成功 + assert retried["notified_salespersons"] == 1 + assert len(send_recorder["list"]) == 2 + + +def test_ship_reminder_records_unmapped_salesperson(app, send_recorder): + """业务员工号对不上已绑企微用户:不发送、计入 skipped_unmapped 并留失败审计。""" + from datetime import date + + line = _make_line(order_no="8301-D", line_no=1, salesperson="99999") + _lock_line(line, date.today() + timedelta(days=3)) + db.session.commit() + + result = run_ship_reminders(advance_days=3) + # 断言:无发送、无成功审计 + assert result["notified_salespersons"] == 0 + assert result["skipped_unmapped"] == 1 + assert send_recorder["list"] == [] + + +def test_unreplied_reminder_notifies_recipients_with_cadence(app, send_recorder): + """超期未回复行提醒配置的生管;N 天内第二次扫描不重复提醒。""" + _make_user("10001", "wx_admin1") # 生管收件人 + _make_line(order_no="8301-E", line_no=1, order_days_ago=5) # 订单日期超 3 天未回复 + _make_line(order_no="8301-F", line_no=2, order_days_ago=1) # 未超期,不应入选 + db.session.commit() + + result = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1]) + # 断言:只有超期行入选(due_lines=1),发送 1 个收件人 1 条 + assert result["due_lines"] == 1 + assert result["notified_recipients"] == 1 + assert len(send_recorder["list"]) == 1 + assert "8301-E:1" in send_recorder["list"][0]["content"] + + # 同行 3 天内不重复提醒 + again = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1]) + assert again["notified_recipients"] == 0 + assert len(send_recorder["list"]) == 1 + + +def test_unreplied_reminder_skips_without_recipients(app, send_recorder): + """未配置生管收件人(开关关闭或名单为空):跳过发送并如实标记。""" + _make_line(order_no="8301-G", line_no=1, order_days_ago=10) + db.session.commit() + + result = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[]) + # 断言:有到期行但无收件人 → skipped_no_recipient=True 且不发送 + assert result["due_lines"] == 1 + assert result["skipped_no_recipient"] is True + assert send_recorder["list"] == [] + + +def test_unreplied_reminder_failed_send_does_not_advance_cadence(app, send_recorder): + """发送失败不推进提醒节奏:紧接着的再次扫描仍会尝试提醒(不做 N 天静默)。""" + _make_user("10001", "wx_admin2") + _make_line(order_no="8301-H", line_no=1, order_days_ago=5) + db.session.commit() + + send_recorder["ok"] = False + run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1]) + # 断言:首次发送失败 + assert len(send_recorder["list"]) == 1 + + send_recorder["ok"] = True + retried = run_unreplied_reminders(unreplied_days=3, notify_user_ids=[1]) + # 断言:失败后不静默,立即重试成功 + assert retried["notified_recipients"] == 1 + assert len(send_recorder["list"]) == 2 + + +def test_web_scanner_respects_disabled_flag(app): + """SCHEDULE_WEB_SCANNER_ENABLED=false 时不启动线程(幂等入口可重复调用)。""" + from app.services.schedule import web_scanner + + app.config["SCHEDULE_WEB_SCANNER_ENABLED"] = False + web_scanner.start_web_schedule_scanner(app) # 不应抛错、不启动线程 + import threading + + names = [t.name for t in threading.enumerate()] + # 断言:关闭开关时没有新的 web-schedule-scanner 线程 + assert names.count("web-schedule-scanner") == 0 + + +# ============ 提醒任务独立启停(布尔任务参数) ============ + + +def _make_remind_task(job_params, notify_enabled=True, notify_user_ids=None): + """构造内存态提醒排程任务(不落库,handler 只读 job_params 与通知配置)。""" + from app.models import ScheduleTask + + return ScheduleTask( + schedule_no="SCH-TEST-REMIND", + name="提醒测试", + schedule_type="platform_job", + platform_api_path="order-delivery-remind", + job_params=job_params, + notify_enabled=notify_enabled, + notify_user_ids_json=notify_user_ids or [], + ) + + +def test_remind_params_defaults_backfill_both_enabled(app): + """契约层对空 job_params 回填默认值:两类提醒默认开启、天数默认 3。""" + from app.services.schedule.job_params import validate_task_params + + normalized = validate_task_params("order-delivery-remind", {}, check_options=False) + # 断言:五个参数齐全,开关默认 True、天数默认 3;未回复提醒收件人默认空(回退任务通知人) + assert normalized == { + "ship_remind_enabled": True, + "ship_remind_advance_days": 3, + "unreplied_remind_enabled": True, + "unreplied_remind_days": 3, + "unreplied_remind_user_ids": [], + } + + +def test_disabled_ship_reminder_skips_only_ship(app, send_recorder): + """ship_remind_enabled=false:出货提醒跳过,未回复提醒照常发送。""" + from datetime import date + + recipient = _make_user("10001", "wx_admin") + today = date.today() + locked_line = _make_line(order_no="8301-S1", line_no=1) + _lock_line(locked_line, today + timedelta(days=2)) # 出货提醒候选 + _make_line(order_no="8301-S2", line_no=2, order_days_ago=5) # 未回复候选 + db.session.commit() + + task = _make_remind_task( + {"ship_remind_enabled": False}, + notify_enabled=True, + notify_user_ids=[recipient.id], + ) + from app.services.schedule.order_delivery_remind_job import run_order_delivery_remind_schedule + + total, success, failed, skipped, details, errors, _logs = run_order_delivery_remind_schedule(task, None) + + summary = details[0] + # 断言:出货侧跳过(skipped=disabled),未回复侧正常发送 1 条 + assert summary["ship_remind"].get("skipped") == "disabled" + assert summary["unreplied_remind"].get("notified_recipients") == 1 + assert len(send_recorder["list"]) == 1 + assert "8301-S2:2" in send_recorder["list"][0]["content"] + assert (total, success, failed) == (1, 1, 0) + + +def test_disabled_unreplied_reminder_skips_only_unreplied(app, send_recorder): + """unreplied_remind_enabled=false:未回复提醒跳过,出货提醒照常发送。""" + from datetime import date + + _make_user("10001", "wx_sales") + today = date.today() + locked_line = _make_line(order_no="8301-U1", line_no=1) + _lock_line(locked_line, today + timedelta(days=2)) # 出货提醒候选 + _make_line(order_no="8301-U2", line_no=2, order_days_ago=5) # 未回复候选(应被跳过不提醒) + db.session.commit() + + task = _make_remind_task( + {"unreplied_remind_enabled": False}, + notify_enabled=True, + notify_user_ids=[1], + ) + from app.services.schedule.order_delivery_remind_job import run_order_delivery_remind_schedule + + total, success, failed, skipped, details, errors, _logs = run_order_delivery_remind_schedule(task, None) + + summary = details[0] + # 断言:未回复侧跳过,出货侧正常发送 1 条;无未回复提醒相关错误 + assert summary["unreplied_remind"].get("skipped") == "disabled" + assert summary["ship_remind"].get("notified_salespersons") == 1 + assert len(send_recorder["list"]) == 1 + assert "8301-U1:1" in send_recorder["list"][0]["content"] + assert (total, success, failed) == (1, 1, 0) + + +def test_both_disabled_no_scan_no_send(app, send_recorder): + """两类提醒都关闭:不扫描不发送,计数全零且无错误。""" + from datetime import date + + _make_user("10001", "wx_any") + locked_line = _make_line(order_no="8301-X1", line_no=1) + _lock_line(locked_line, date.today() + timedelta(days=2)) + _make_line(order_no="8301-X2", line_no=2, order_days_ago=5) + db.session.commit() + + task = _make_remind_task( + {"ship_remind_enabled": False, "unreplied_remind_enabled": False}, + notify_enabled=True, + notify_user_ids=[1], + ) + from app.services.schedule.order_delivery_remind_job import run_order_delivery_remind_schedule + + total, success, failed, skipped, details, errors, _logs = run_order_delivery_remind_schedule(task, None) + + summary = details[0] + # 断言:两侧都标记 disabled、无任何发送、计数全零 + assert summary["ship_remind"].get("skipped") == "disabled" + assert summary["unreplied_remind"].get("skipped") == "disabled" + assert send_recorder["list"] == [] + assert (total, success, failed, skipped) == (0, 0, 0, 0) + assert errors == [] diff --git a/backend/tests/test_order_delivery_reply_validation.py b/backend/tests/test_order_delivery_reply_validation.py new file mode 100644 index 00000000..c5d24b28 --- /dev/null +++ b/backend/tests/test_order_delivery_reply_validation.py @@ -0,0 +1,81 @@ +""" +tests/test_order_delivery_reply_validation.py + +用途:订单交期回复保存「数量守恒」校验的单测——每行各批次合计必须等于订单数量 + (2026-09-23 由「超额仅提醒」修订)。 +依赖:conftest 的 app 夹具(testing + sqlite create_all)、reply_service.save_batches/batch_reply。 +逻辑:合计 ≠ 订单数量 → ValidationError(BATCH_QTY_TOTAL_MISMATCH)且不落任何批次/审计; + 合计 = 订单数量 → 正常保存(多批次拆分亦同);联合回复中单行不等 → 该行按行失败, + 不影响其它行(部分成功语义)。 +""" + +from datetime import date +from decimal import Decimal + +import pytest + +from app.core.errors import ValidationError +from app.extensions import db +from app.models.order_delivery_reply import OrderDeliveryBatch, OrderDeliveryErpLine +from app.services.order_delivery_reply.reply_service import batch_reply, save_batches + + +def _line(order_no, line_no=1, qty="100"): + """构造一行最小快照(qty 即订单数量,未回复提醒/保存校验的对照基准)。""" + row = OrderDeliveryErpLine( + order_no=order_no, + line_no=line_no, + order_date=date(2024, 6, 1), + customer_no="C001", + qty=Decimal(qty), + delivered_qty=Decimal("0"), + erp_missing=False, + ) + db.session.add(row) + return row + + +def test_save_batches_rejects_total_not_equal_order_qty(app): + """各批次合计 90 ≠ 订单数量 100 → 422 数量守恒错误,且不落任何批次。""" + _line("8301-V1", qty="100") + db.session.commit() + + with pytest.raises(ValidationError) as exc: + save_batches("8301-V1", 1, [{"planned_date": "2026-10-01", "qty": "90"}], operator_user_id=None) + # 断言:错误码为数量守恒专用码,便于前端与 errors.json 四语言文案对应 + assert exc.value.code == "ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH" + # 断言:校验在任何写操作之前,失败不落批次 + assert OrderDeliveryBatch.query.count() == 0 + + +def test_save_batches_accepts_exact_total_with_multi_batches(app): + """60 + 40 = 订单数量 100 → 保存成功,多批次拆分合法。""" + _line("8301-V2", qty="100") + db.session.commit() + + data = save_batches("8301-V2", 1, [ + {"planned_date": "2026-10-01", "qty": "60"}, + {"planned_date": "2026-11-01", "qty": "40"}, + ], operator_user_id=None) + # 断言:保存成功且 total_qty 与订单数量一致 + assert data["total_qty"] == "100" + assert len(data["batches"]) == 2 + assert OrderDeliveryBatch.query.count() == 2 + + +def test_batch_reply_mismatch_line_fails_others_succeed(app): + """联合回复:单行合计不等按行失败,另一行正常保存(部分成功语义不回归)。""" + _line("8301-V3", line_no=1, qty="100") + _line("8301-V3", line_no=2, qty="200") + db.session.commit() + + summary = batch_reply([ + {"order_no": "8301-V3", "line_no": 1, "batches": [{"planned_date": "2026-10-01", "qty": "100"}]}, + {"order_no": "8301-V3", "line_no": 2, "batches": [{"planned_date": "2026-10-01", "qty": "150"}]}, + ], operator_user_id=None) + # 断言:行 2 合计 150 ≠ 200 失败;行 1 保存成功 + assert summary["succeeded"] == 1 + assert summary["failed"] == 1 + assert summary["items"][1]["ok"] is False + # 断言:仅成功行落批次 + assert OrderDeliveryBatch.query.count() == 1 diff --git a/docs/demand.md b/docs/demand.md index 79d7323f..7aaf481c 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -1,5 +1,11 @@ # 智能HR请假管理需求 +## 订单交期回复 Agent(2026-09) + +生管在工作台按 ERP 已审核、已核准、未结案的销售订单行回复交期(可拆多批次),保存后经行内或批量企微通知对应业务员并锁定;具备只读权限的业务人员可查看,回执不改状态。系统只读 ERP,不回写。操作权限按用户功能权限划分。每天 07:00(北京时间)全量同步全部合格订单,可手动刷新。一期不做单别白名单管理,操作页不出单别列。细则见 [features/order-delivery-reply/demand.md](features/order-delivery-reply/demand.md)。 + +定时提醒(2026-09-21 增补):07:00 同步成功后企微提醒生管查看当天回复(收件人=排程通知人配置);新日批 07:10 提醒排程——已回复行按回复交期提前 N 天(默认 3)提醒对应业务员出货,超 N 天(默认 3)未回复的行再次提醒生管;天数与生管收件人都在管理端排程表单配置,不新增配置页面。 + ## 可配置权限组(2026-09) - 每位用户只选一个权限组(角色包);角色 = 可用应用入口 + 应用内能力。部门只用于选人筛选,不自动授权。 @@ -467,6 +473,7 @@ ## 4. 业务角色 + | 角色 | 说明 | | -------------------- | -------------------------------------------------------------------------------------------------------------- | | 管理员 | 平台管理员,默认拥有所有功能权限,包括设备台账配置和维修记录维护 | diff --git a/docs/features/README.md b/docs/features/README.md index b464de50..700a7649 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -5,6 +5,7 @@ | 域 | 说明 | 入口 | | --- | --- | --- | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) | +| [order-delivery-reply](order-delivery-reply/README.md) | 订单交期回复 Agent | [需求说明](order-delivery-reply/demand.md) · [技术设计](order-delivery-reply/technical-design.md) · [原型 v4](order-delivery-reply/order-delivery-reply-prototype.html) | | [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [开发部门需求与原型评审包](in-transit-transfer/mvp-requirements-and-prototype-review-pack.md) · [来源实例 Lean UX Canvas](in-transit-transfer/mvp-source-instance-lean-ux-canvas.md) · [可点击原型](../platform/in-transit-transfer-source-instance-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [一期 TDD](in-transit-transfer/in-transit-transfer-tdd.md) · [运维手册](in-transit-transfer/technical.md) | | [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) | diff --git a/docs/features/order-delivery-reply/README.md b/docs/features/order-delivery-reply/README.md new file mode 100644 index 00000000..d6e2af8d --- /dev/null +++ b/docs/features/order-delivery-reply/README.md @@ -0,0 +1,19 @@ +# 订单交期回复(order-delivery-reply) + +| 文档 | 读者 | 路径 | +| --- | --- | --- | +| **需求说明** | 产品、业务、测试、研发 | [demand.md](demand.md) | +| **技术设计** | 研发 | [technical-design.md](technical-design.md) | +| **原型 v4** | 产品、业务、测试 | [order-delivery-reply-prototype.html](order-delivery-reply-prototype.html) | + +**定位**:工作台型 Agent。生管按 ERP 销售订单行回复交期(可拆多批次),经企业微信通知对应业务员后行级锁定,形成可审计记录。 + +**要解决的问题**:交期目前靠线下沟通,缺少按「订单单号:项次」落库的回复、通知与锁定事实。 + +**一期形态**:独立菜单页「订单交期回复」;只读 ERP,不回写;不做 Chat 对话,不做已锁定行的纠正 / 解锁。 + +**状态**:需求 v0.9、技术设计 v1.0(2026-09-21)。一期同步全部合格订单,不做单别白名单管理(后期再加)。企微复用平台 `send_wecom_event_message`。操作权限按用户功能权限(`manage` / `access`)。操作页不出单别列。原型已去掉订单类型 / 已转请购 / 排定交货日;联合回复只保存,另用批量通知。 + +**2026-09-21 增补**:① 07:00 到期排程在开发环境由 Web 进程内兜底扫描触发(生产走 schedule-worker 容器);② 同步成功后按排程通知配置企微提醒生管;③ 新增日批 07:10 提醒排程——已回复行按回复交期提前 N 天提醒业务员出货、超 N 天未回复再次提醒生管,天数可配、两类提醒可独立启停(排程任务参数);④ 工作台列顺序按业务指定调整,产品编号+品名、业务员+部门合并为上下两行展示(以 demand.md §8 修订为准)。 + +**实现状态**:见 [funclist.md](../../funclist.md)(已实现)。 diff --git a/docs/features/order-delivery-reply/demand.md b/docs/features/order-delivery-reply/demand.md new file mode 100644 index 00000000..e40942bd --- /dev/null +++ b/docs/features/order-delivery-reply/demand.md @@ -0,0 +1,328 @@ +# 订单交期回复 — 需求说明 + +| 项目 | 说明 | +|------|------| +| 版本 | v0.9(2026-09-21;§8 列顺序与合并展示修订、§13.1 定时提醒增补、§15 兜底触发说明) | +| 状态 | 已拍板,可按本文与技术设计实现 | +| 形态 | 工作台独立页;聊天侧栏/首页提供跳转入口(R-ENTRY-02),不做对话式填写 | +| 关联 | [原型](order-delivery-reply-prototype.html) · [技术设计](technical-design.md) | + +--- + +## 1. 背景与目标 + +### 1.1 背景 + +销售订单交期目前由生管与业务员线下沟通,缺少按「订单行」落库的回复记录,也无法证明何时通知、谁回复、是否已锁定。ERP(鼎捷 `axmt410`)保存约定交货日与已交数量,但不承担「生管承诺交期 → 通知业务 → 锁定」这条协作链。 + +### 1.2 目标 + +1. 生管按 ERP 销售订单行回复交期,允许拆成多个「交期 + 数量 + 备注」批次。 +2. 通过企业微信通知该订单对应业务员;通知成功后行级锁定。 +3. 具备只读权限的业务人员可查看回复结果;企微回执仅留痕,不改变交期回复状态。 +4. 形成可审计记录:谁在何时对哪一行发送了通知并锁定。 + +### 1.3 成功标准 + +- 生管可在系统内完成「查单 → 填交期 → 通知业务 → 锁定」。 +- 任意一行的批次、状态、是否锁定、回复人员可在工作台直接看到。 +- 已锁定行不能再改批次;纠正 / 解锁本期不做。 + +--- + +## 2. 范围 + +### 2.1 本期范围 + +| 编号 | 能力 | +|------|------| +| R-ENTRY-01 | 工作台独立操作页「订单交期回复」(直链 `/workspace/order-delivery-reply`;不在工作台侧栏货代分组下设置菜单) | +| R-ENTRY-02 | 以**独立应用**形态接入应用管理:注册一条 `runtime_provider='iframe'`、`iframe_url=/apps/order-delivery-reply` 的 Agent(不接 Dify);出现在应用管理与全部应用/聊天侧栏列表,点击在聊天壳内整页打开操作页。可见性走 Agent 权限(admin 自动可见,普通用户在用户管理授权);页面与 API 仍受 `access`/`manage` 功能权限守卫 | +| R-DATA-01 | 只读同步已审核、已核准、未结案的全部合格 ERP 订单行到本地库,不回写 ERP | +| R-LIST-01 | 组合查询 + 重置;默认排序;空结果提示 | +| R-LIST-02 | 行唯一键 `订单单号:项次`;全选三态 | +| R-REPLY-01 | 单行回复 / 修改:弹窗维护批次 | +| R-REPLY-02 | 勾选多行「联合回复交期」:只保存批次,不自动通知 | +| R-NOTIFY-02 | 工具栏「批量通知」:对已勾选且已填批次、未锁定的行发送通知并锁定(唯一通知入口) | +| R-NOTIFY-04 | 每天 07:00 排程同步成功后企微提醒生管查看当天交期回复;收件人=排程任务通知人配置(2026-09-21 增补) | +| R-NOTIFY-05 | 每日提醒排程(07:10):已回复行按回复交期提前 N 天(默认 3)提醒对应业务员出货;超 N 天(默认 3)未回复的行再次提醒生管;天数可配、两类提醒可独立启停、生管收件人可配(2026-09-21 增补,详见 §13.1) | +| R-STATUS-01 | 行上仍分未回复 / 部分回复 / 已回复(已回复 = 已通知并锁定);筛选选项为已回复、未完全回复(含未回复+部分回复) | +| R-NOTIFY-01 | 通知统一走工具栏「批量通知」(行内不再提供发送按钮);成功后行级锁定,行内列显示已通知对象与时间 | +| R-NOTIFY-03 | 交期回复人员 = 最近一次发送成功的生管工号 + 姓名 | +| R-AUDIT-01 | 发送通知与锁定记入审计 | +| R-RBAC-01 | 用户功能权限:`manage` 生管可写,`access` 业务只读;可选按部门批量发放勾选 | + +### 2.2 非本期范围 + +- 纠正已锁定交期、解锁、作废通知 +- 回写 ERP;对话式填交期(在 Chat 对话中直接填写/修改批次——区别于 R-ENTRY-02 的跳转入口) +- 邮件通知;撤回已发企微 +- 回执改变交期回复状态 +- **订单类型列、已转请购 / 已转采购、排定交货日**(已取消,不上操作页列表) +- 工作台单别列 +- **单别白名单管理配置**(R-ADM-01,后期再做;一期默认同步全部合格订单) +- 每次请求按部门名称判定操作权限(已废止) +- 本 Agent 自绘企微卡片样式 / 按钮 / 模板卡片 +- 原型 v2 左侧统计侧栏 + +--- + +## 3. 角色与权限 + +操作权限按 **HXOPS 用户功能权限** 判定,不按所属部门名称每次比对。不新增系统角色。 + +| 身份 | 如何判定 | 权限 | +| --- | --- | --- | +| 生管 | 用户勾选 `order_delivery_reply.manage` | 查看已同步订单;回复;单行/批量通知;手动同步 | +| 业务 | 用户勾选 `order_delivery_reply.access`(无 `manage`) | 查看已同步订单;只读 | +| 未授权 | 两键均未勾选 | 无入口、无 API | +| 平台管理员 | `admin` 角色默认两键均开 | 等同生管;可在用户管理勾选或按部门批量发放 | + +`manage` 同时视为有 `access`。权限在用户管理勾选,与合同付款预警 `contract_payment.access` 同一机制。人多时管理员可按部门一次性把勾选写到该部门成员账号上;此后仍以用户勾选为准,调岗不会自动改权限。 + +企微通知对象仍是订单业务员,与工作台操作权限无关。有权进入的人看已同步全量,不按「是否本人的单」裁行。 + +--- + +## 4. 术语 + +| 术语 | 含义 | +|------|------| +| 订单行 | ERP 销售订单单身一行,唯一键 `订单单号:项次` | +| 未交数量 | `数量 − 已交数量` | +| 已回复数量 | 已保存各批次数量之和 | +| 批次 | 计划交期 + 数量 + 可选备注 | +| 锁定 | 该行通知成功后不可再改批次 | +| 交期回复人员 | 最近一次发送通知成功的生管:工号 + 真实姓名 | +| 客户简称 / 公司全名 | `OCC_FILE.occ02` / `occ18`,展示在客户编号旁 | +| 单别 | 订单单号连字符前的编码(如 `8301` 外销)。一期列表不出此列、无管理勾选;后期可用白名单约束同步 | + +--- + +## 5. 业务流程 + +```mermaid +flowchart TD + syncJob[每天07:00或手动同步ERP] --> showList[工作台列表] + showList --> fillReply[生管单行或联合填写并保存批次] + fillReply --> notifyBiz[行内通知或批量通知] + notifyBiz --> lockRow[该行锁定且状态为已回复] + lockRow --> receipt[业务员企微回执仅留痕] +``` + +- 保存批次与发送通知是两步。联合回复保存后**不**自动通知。 +- 未锁定前可反复修改批次。 +- 不回写 ERP。 + +--- + +## 6. 数据来源与字段 + +### 6.1 写边界 + +订单事实只读 ERP。批次、状态、锁定、通知、审计只存在于 HXOPS。禁止对 ERP 做 INSERT / UPDATE / DELETE。 + +### 6.2 关联 + +- `oea01 = oeb01` +- `oeb04 = ima01` 且 `oeb06 = ima02` +- `oea03 = occ01`(对照表曾写 `ooc01`,按客户主档主键 `occ01`) +- `oea14 = gen01`(业务员姓名) +- `oea15 = gem01`(部门名称) + +### 6.3 展示字段 + +| 展示名 | 取值列 | 表 | +| --- | --- | --- | +| 订单单号 | `oea01` | `HXJM.OEA_FILE` | +| 订单日期 | `oea02` | `HXJM.OEA_FILE` | +| 客户编号 | `oea03` / `occ01` | `OEA_FILE` / `OCC_FILE` | +| 客户简称 | `occ02` | `HXJM.OCC_FILE` | +| 公司全名 | `occ18` | `HXJM.OCC_FILE` | +| 业务员 | 编码 `oea14`,名称 `gen02` | `OEA_FILE` / `GEN_FILE` | +| 部门 | 编码 `oea15`,名称 `gem02` | `OEA_FILE` / `GEM_FILE` | +| 客户订单 | `oea10` | `OEA_FILE` | +| 项次 | `oeb03` | `OEB_FILE` | +| 产品编号 | `oeb04` | `OEB_FILE` | +| 品名 | `oeb06` | `OEB_FILE` | +| 规格 | `ima021` | `IMA_FILE` | +| 客户产品编号 | `oeb11` | `OEB_FILE` | +| 约定交货日 | `oeb15` | `OEB_FILE` | +| 单位 | `oeb05` | `OEB_FILE` | +| 数量 | `oeb12` | `OEB_FILE` | +| 已交数量 | `oeb24` | `OEB_FILE` | + +派生:`订单单号:项次`、未交数量(仅内部计算,列表不再展示已交/未交两列)、交期回复状态、批次、通知、交期回复人员。 + +列表**不展示**:订单类型、单别、已转请购 / 已转采购、排定交货日。一期无单别管理勾选。 + +### 6.4 同步范围 + +只同步同时满足的订单行: + +- 已审核:`oeaconf = 'Y'` +- 已核准:`oea49 = '1'` +- 未结案:`oeb70` 结案否为 N(`NVL(oeb70, 'N') = 'N'`) +- 完全未交:已交数量为 0(`NVL(oeb24, 0) = 0`,2026-09-17 增补——已有交货的行不再进入同步与列表) + +一期**不按单别过滤**,上述条件命中的订单行全部同步。 + +本地已有批次或已锁定、但本轮 ERP 不再命中的行:保留不删,标记为 ERP 已不在同步范围,默认列表不展示。 + +--- + +## 7. 查询与列表 + +筛选(AND):**关键词**(合并搜索:订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号)命中任一即返回;2026-09-21 由三个独立搜索框合并,2026-09-23 增补人员搜索)、订单日期(单日)、交期回复状态。 + +交期回复状态筛选项: + +| 选项 | 包含的行状态 | +| --- | --- | +| 全部 | 不限 | +| 已回复 | 已通知并锁定 | +| 未完全回复 | 未回复 + 部分回复(尚未通知锁定) | + +列表行上仍用未回复(红)/ 部分回复(橙)/ 已回复(绿)徽标,不把「未完全回复」画成第四种行状态。 + +工作台列出当前已同步且未标「已不在同步范围」的行。一期不按单别裁行。 + +默认排序:订单日期 → 客户编号 → 订单单号 → 项次 / 产品编号,升序。分页默认 50。 + +全选作用于当前筛选结果的**本页**。未勾选时「联合回复交期」「批量通知」不可用。 + +--- + +## 8. 列表列 + +(2026-09-21 修订列顺序与合并展示,按业务指定顺序;独立「部门」「品名」列取消,与业务员/产品编号合并为上下两行展示,样式同客户编号+简称。) + +1. 勾选 +2. 客户编号(副文案:客户简称;可悬停看公司全名) +3. 订单日期 +4. 订单单号:项次 +5. 产品编号(副文案:品名) +6. 客户产品编号 +7. 数量 +8. 约定交货日 +9. 交期回复状态 +10. 交期回复 +11. 交期回复人员(锁定行在姓名下附带「已通知 {业务员} + 时间」;原「通知业务部门」列已取消) +12. 业务员(显示姓名;副文案:部门名称) +13. 客户订单 +14. 规格 +15. 单位 + +(2026-09-17 增补同步条件 `NVL(oeb24,0)=0` 后,「已交数量 / 未交数量」两列信息量归零,已取消展示;数量与未交口径仍由后端派生,供回复弹窗数量守恒校验使用。) + +不增加单别列。一期无单别管理勾选。 + +交期回复:无批次显示「回复交期」;有批次可展开;未锁定可「修改回复」;已锁定显示「交期已锁定」。 + +通知:列已取消(行内不设发送按钮);发送统一走工具栏「批量通知」;已通知对象与时间并入「交期回复人员」列展示。 + +--- + +## 9. 显示规则 + +- (2026-09-23 修订)回复弹窗**数量守恒**:每行各批次填写合计必须**等于订单数量**才能保存——弹窗内实时红字提示已填合计、保存时拦截,后端 422(`BATCH_QTY_TOTAL_MISMATCH`)兜底;原「超额显示『超』,不拦截保存」废止。列表行「超」标记仅对历史超额数据展示。 +- 状态:未回复红、部分回复橙、已回复绿;保存或通知后即时刷新。 + +--- + +## 10. 单行回复 + +弹窗维护 1..N 批:交期必填有效日期,数量 > 0,备注 ≤ 200;各批次数量合计必须等于订单数量,否则不能保存(2026-09-23 增补);已填批次的交期/数量缺填、同一订单单号:项次的不同批次交期重复,均实时提示并随填写内容切换(2026-09-23 增补;交期重复后端 BATCH_INVALID 既有校验)。可增删批次,可快速统一交期。锁定行不可编辑。行上徽标展示「订单数量:X 单位」(2026-09-23 由「未交 X」改来)。 + +--- + +## 11. 联合回复与批量通知 + +1. 勾选多行 →「+ 联合回复交期」→ 按行填批次 → **保存回复**(只写批次,不通知、不锁定);每行各批次合计必须等于订单数量,不等的行按行保存失败(2026-09-23 增补)。 +2. 工具栏另设「批量通知」:对当前勾选中「已有批次且未锁定」的行逐行发送通知并锁定。 +3. 无批次或已锁定的勾选行跳过;全部失败则提示,部分成功则成功行锁定、失败行保持未锁定。 +4. 行内不再提供发送按钮,通知统一走工具栏「批量通知」,单行/锁定/失败规则相同。 + +--- + +## 12. 状态机 + +| 状态 | 判定 | +| --- | --- | +| 未回复 | 无任何已保存批次 | +| 部分回复 | 已有批次,尚未通知锁定 | +| 已回复 | 已发送通知并锁定 | + +已回复**必须**已通知锁定。批次数量是否盖住未交、未交是否为 0,都不单独变成已回复。 + +筛选「未完全回复」= 上表未回复 ∪ 部分回复。 + +--- + +## 13. 通知与锁定 + +- 渠道:企业微信;**复用平台既有通知**(`send_wecom_event_message`),不单独做卡片样式/按钮/模板。 +- 接收人:该订单业务员(`oea14` 对应 HXOPS `User.employee_id`,再取 `wecom_userid`)。对得上。匹配失败则该行通知失败、不锁定。 +- 正文参数:`您有订单号:项次{订单单号}:{项次}的订单需要填写/确认/查看交期。`(只作 content,卡片壳走平台。) +- 发送成功后行级锁定;失败不锁定。 +- 回执走既有企微审计,只留痕,不改状态。 + +### 13.1 定时提醒(2026-09-21 增补) + +| 提醒 | 触发 | 收件人 | 天数配置 | +| --- | --- | --- | --- | +| 同步完成提醒 | 每天 07:00 排程同步成功后 | 生管(任务参数「同步完成提醒收件人」,可从全部用户搜索选择;留空回退「通知人」) | — | +| 出货提醒 | 已回复行的回复交期距今 ≤ N 天 | 对应订单业务员(按人聚合成一条) | 默认 3,排程任务参数可配 | +| 未回复再提醒 | 订单日期距今超 N 天仍未回复(同一行每 N 天最多提醒一次;2026-09-23 明确以 ERP 订单日期计超期,非入库时间) | 生管(任务参数「未回复提醒收件人」,按收件人聚合成一条) | 默认 3,排程任务参数可配 | + +实现:新排程 `order-delivery-remind`(日批 07:10,紧随同步)。天数在管理端排程表单「任务参数」修改(`ship_remind_advance_days` / `unreplied_remind_days`);两类提醒由任务参数 `ship_remind_enabled` / `unreplied_remind_enabled`(布尔,默认开)**独立启停**;生管收件人在排程表单「任务参数 → 未回复提醒收件人(生管)」多选配置(候选=全部启用用户,支持按姓名/工号/部门搜索;留空回退「通知人」兼容旧配置)——与平台运行结果通知的「通知人」**互相独立**(2026-09-22 增补,两类通知人分离)。出货提醒同一(行,交期)只发一次,发送失败次日自动补发;两类提醒逐行写审计(`ship_remind` / `unreplied_remind`),只读业务数据、不改批次/锁定。 + +--- + +## 14. 审计 + +记录保存批次、发送通知、锁定、同步。字段:操作人、时间、动作、订单单号、项次、必要快照。 + +--- + +## 15. 非功能 + +- 每天 **Asia/Shanghai 07:00** 自动全量同步,生管可手动全量刷新。页面展示最近同步时间。(2026-09-29 更新:到期排程由独立 worker 进程 `workers/worker_scheduler.py` / 生产 `hxops-schedule-worker` 容器执行;合并 dev 主线后 Web 进程不再兜底扫描,本地需另起 worker 进程。) +- 通知成功与锁定同一事务,禁止「已通知未锁定」。 +- 正式产品四语言 i18n。 + +--- + +## 16. 已关闭的原开放问题 + +| 原编号 | 结论 | +| --- | --- | +| Q-01 | 已回复 = 已通知并锁定 | +| Q-02 | 联合回复只保存;另用批量通知 | +| Q-03 | 应用管理注册 iframe 应用(不接 Dify),聊天壳内整页打开操作页;不在货代发货通知下加菜单,不做对话式填写 | +| Q-04 / Q-05 | 取消订单类型、已转请购、排定交货日 | +| Q-07 / D-03 | `oea14` 能对上 HXOPS 工号 / 企微 | +| Q-08 | 企微复用 `send_wecom_event_message`;正文参数见 §13,不单独定卡片样式 | +| D-01 / D-02 | 已审核 `oeaconf='Y'` + 已核准 `oea49='1'` + 未结案 `oeb70='N'`;每天 07:00 + 手动 | +| D-04 | 业务员、部门显示名称 | +| D-07 | 操作权限用用户功能权限 `manage` / `access`;部门仅可选批量发放,不作每次请求的门禁 | +| D-08 | 一期不按单别过滤、无单别管理配置,默认同步全部合格订单;后期再做白名单(方案 A:同步 WHERE + 新勾选增量同步;操作页始终不出单别列) | + +--- + +## 17. 验收要点 + +1. 勾选 `manage` 可回复/通知/同步;仅 `access` 只读;两键都无则无入口。`admin` 默认可写。 +2. 列表无订单类型、单别、已转请购、排定交货日;列顺序按 §8(2026-09-21 修订):客户编号→订单日期→订单单号:项次→产品编号→客户产品编号→数量→约定交货日→交期回复状态→交期回复→交期回复人员→业务员→客户订单→规格→单位;产品编号与品名、业务员与部门均为上下两行合并展示(同客户编号+简称样式)。 +3. 同步范围:`oeaconf='Y'` 且 `oea49='1'` 且 `oeb70` 不为已结案;一期不按单别过滤;07:00 与手动刷新都可跑;到期排程由独立 worker 进程触发(2026-09-29 合并 dev 主线,Web 进程不再兜底扫描)。 +4. 一期无单别白名单管理页;列表不出单别列。 +5. 状态筛选仅「全部 / 已回复 / 未完全回复」;未完全回复同时命中未回复与部分回复。 +6. 无批次 = 未回复,不能通知。 +7. 有批次未通知 = 部分回复,可修改。 +8. 通知成功 = 已回复且锁定,不能再改批次。 +9. 联合回复保存后仍是部分回复(属未完全回复);点批量通知成功后才锁定。 +10. 企微走平台既有通知;正文为「您有订单号:项次{单号}:{项次}的订单需要填写/确认/查看交期。」;不自绘卡片。 +11. 通知失败不锁定;回执不改状态。 +12. 不写 ERP。 +13. (2026-09-21)07:00 同步成功后按排程通知配置提醒生管;发送失败不影响同步结果,且不重复收到通用「排程执行结果」通知。 +14. (2026-09-21)已回复行交期前 N 天业务员收到出货提醒,同一(行,交期)只提醒一次、发送失败次日补发;超 N 天未回复的行每 N 天再次提醒生管;两类提醒可在排程任务参数中独立启停、天数可改。 diff --git a/docs/features/order-delivery-reply/order-delivery-reply-prototype.html b/docs/features/order-delivery-reply/order-delivery-reply-prototype.html new file mode 100644 index 00000000..a30cfd13 --- /dev/null +++ b/docs/features/order-delivery-reply/order-delivery-reply-prototype.html @@ -0,0 +1,732 @@ + + + + + + + +交期回复 - 原型设计 + + + +
+ +
+ 交期回复 +

订单交期回复

+ Order Delivery Reply · 多订单联合回复 + 单产品拆分交期分批回复 + + 原型 v5 | 未交=橙 | 已回复=已通知锁定 | 联合回复只保存 +
+ + +
+ 口径:未交数量 = 数量 − 已交;未交 > 0 显橙色,未交 = 0 显灰色。 + |交期回复状态:未回复=红、部分回复=橙(已填未通知)、已回复=绿(已通知并锁定)。 + |联合回复只保存批次;勾选后点「批量通知」才发送并锁定。 + |拆分「交期+数量」允许超额,仅橙色提醒、不拦截保存。 +
+ + + + +
+ + +
+
+ + 已勾选 0 行 + + + + 勾选后可联合填写并保存;保存后点「批量通知」才发给业务员并锁定。 +
+ +
+ + + + + + + + + + +
订单单号:项次订单日期客户编号业务员部门客户订单产品编号品名规格客户产品编号约定交货日单位数量已交数量未交数量交期回复状态交期回复通知业务部门交期回复人员
+
+ +
+
+ +
+ 未交数量 = 数量 − 已交;待回复数量 = 未交数量 − 已回复数量。 + 交期回复状态随保存即时更新;点击「N 批」可展开查看每批交期与备注。 +
+
+ + +
+ +
+ + + + diff --git a/docs/features/order-delivery-reply/technical-design.md b/docs/features/order-delivery-reply/technical-design.md new file mode 100644 index 00000000..8cd4b62b --- /dev/null +++ b/docs/features/order-delivery-reply/technical-design.md @@ -0,0 +1,322 @@ +# 订单交期回复 — 技术设计 + +| 项目 | 说明 | +|------|------| +| 版本 | v1.0(2026-09-21;增补 07:00 同步兜底触发、同步完成提醒生管、每日出货/未回复提醒排程与新列顺序) | +| 状态 | 已拍板,可按本文实现 | +| 需求基线 | [demand.md](demand.md) v0.9(§8 列顺序 2026-09-21 修订、§13.1 定时提醒增补) | +| 原型 | [order-delivery-reply-prototype.html](order-delivery-reply-prototype.html) | + +已定:一期同步 `oeaconf='Y'` 且 `oea49='1'` 且 `oeb70='N'` 且 `NVL(oeb24,0)=0`(完全未交)的**全部**合格订单行,**不按单别过滤**;不做单别白名单管理配置(后期再加)。每天 07:00(北京时间)+ 手动刷新。业务员/部门显示名称且工号能对上企微;已回复必须已通知锁定;联合回复只保存,另用批量通知;企微**复用** `send_wecom_event_message`,本 Agent 不单独定卡片样式。**操作权限按用户功能权限**,不按部门名称每次判定。筛选为全部 / 已回复 / 未完全回复。列表**不出**单别列。取消订单类型、已转请购、排定交货日。客户取 `OCC_FILE`。 + +--- + +## 1. 设计目标 + +1. ERP Oracle **只读**。本地 Postgres 存 ERP 快照 + 批次 / 锁定 / 通知 / 审计。 +2. 工作台只读本地库。同步只更新快照上的 ERP 列,不得覆盖回复与锁定。 +3. 禁止对 ERP 做 INSERT / UPDATE / DELETE。 +4. 一期:工作台独立页 + Flask API,复用 User、排程、企微;不新开 FastAPI。 + +--- + +## 2. 总体架构 + +```mermaid +flowchart LR + erpOracle[ERP_Oracle_HXJM] -->|只读SELECT| syncJob[同步服务] + syncJob -->|upsert快照列| localPg[本地Postgres] + localPg --> api[Flask_API] + api --> ui[工作台] + ui -->|保存批次_通知锁定| api + api -->|企微通知| wecom[企业微信] +``` + +| 层 | 落点 | +| --- | --- | +| ERP | `HXJM.OEA_FILE` / `OEB_FILE` / `IMA_FILE` / `OCC_FILE` / `GEN_FILE` / `GEM_FILE`;连接复用 `ERP_DB_*` | +| 同步 | `app/services/order_delivery_reply/`;07:00 + 手动全量;一期拉全部合格订单,不按单别过滤 | +| 本地库 | 新表 + Alembic | +| API | Flask Blueprint `/api/order-delivery-reply/`;列表读已同步快照 | +| 前端 | `frontend/src/features/order-delivery-reply/`(操作页 + api + constants);路由/侧栏/聊天侧栏入口/首页入口卡片见 §8 | +| 企微 | 复用 `wecom_notify.send_wecom_event_message`(平台统一 textcard);本 Agent 不自绘卡片 | + +页面展示最近同步时间。同步失败保留上次快照并明示失败。 + +--- + +## 3. ERP 取数 + +### 3.1 连接 + +与 Text2SQL / 立账检核相同:`ERP_DB_DSN`、`ERP_DB_USER` / `ERP_USERNAME`、`ERP_DB_PASSWORD` / `ERP_PASSWORD`;**缺省回退合同付款预警的共享配置 `CONTRACT_PAYMENT_ERP_USERNAME` / `CONTRACT_PAYMENT_ERP_PASSWORD`**(`.env.shared`,hxjm 账号同一 topprod 连接)。DSN 与口令不进仓库。复用 `Text2SQLService._init_oracle_client`(thin 优先、失败切 thick)。 + +### 3.2 关联 + +| 条件 | 含义 | +| --- | --- | +| `oea01 = oeb01` | 订单头 ↔ 身 | +| `oeb04 = ima01` 且 `oeb06 = ima02` | 料件;LEFT JOIN,无料件仍保留行 | +| `oea03 = occ01` | 客户主档。对照表写 `oea03=ooc01`,按 `OCC_FILE.occ01` | +| `oea14 = gen01` | 业务员姓名 `gen02` | +| `oea15 = gem01` | 部门名称 `gem02` | + +员工 / 部门表优先 `HXJM.GEN_FILE` / `HXJM.GEM_FILE`。若套账无表,回退已验证的 `ERP_VIEW_USER.ERP_GEN_FILE_V` / `ERP_GEM_FILE_V`(`gen01`/`gen02`、`gem01`/`gem02` 同义)。 + +### 3.3 字段映射 + +| 系统字段 | 取值列 | 来源表 | 转换 | +| --- | --- | --- | --- | +| 订单单号 | `oea01` | `OEA_FILE` | 字符串 | +| 订单日期 | `oea02` | `OEA_FILE` | → `date` | +| 客户编号 | `oea03` | `OEA_FILE` | 字符串 | +| 客户简称 | `occ02` | `OCC_FILE` | 字符串;LEFT JOIN 可空 | +| 公司全名 | `occ18` | `OCC_FILE` | 字符串;可空 | +| 业务员工号 | `oea14` | `OEA_FILE` | 字符串;对 HXOPS `User.employee_id` | +| 业务员姓名 | `gen02` | `GEN_FILE` | 列表展示此列 | +| 部门编码 | `oea15` | `OEA_FILE` | 字符串 | +| 部门名称 | `gem02` | `GEM_FILE` | 列表展示此列 | +| 客户订单 | `oea10` | `OEA_FILE` | 可空 | +| 项次 | `oeb03` | `OEB_FILE` | int | +| 产品编号 | `oeb04` | `OEB_FILE` | 字符串 | +| 品名 | `oeb06` | `OEB_FILE` | 字符串 | +| 规格 | `ima021` | `IMA_FILE` | 可空 | +| 客户产品编号 | `oeb11` | `OEB_FILE` | 可空 | +| 约定交货日 | `oeb15` | `OEB_FILE` | → `date` | +| 单位 | `oeb05` | `OEB_FILE` | 字符串 | +| 数量 | `oeb12` | `OEB_FILE` | Numeric | +| 已交数量 | `oeb24` | `OEB_FILE` | Numeric;空当 0 | + +未交数量 = `数量 − 已交数量`,计算列。 + +**取消、不同步、不上列表:** 订单类型、已转请购 / 已转采购、排定交货日。 + +### 3.4 同步过滤(已拍板) + +业务:只拉 **已审核、已核准、未结案** 的订单行。现场已确认: + +| 业务条件 | ERP 口径 | +| --- | --- | +| 已审核 | `a.oeaconf = 'Y'` | +| 已核准 | `a.oea49 = '1'` | +| 未结案 | `oeb70` 结案否(Y/N),`NVL(b.oeb70, 'N') = 'N'` | +| 完全未交 | 已交数量为 0,`NVL(b.oeb24, 0) = 0`(2026-09-17 增补) | + +上表四者同时满足(AND)。一期**不按单别缩小同步**,凡合格行都进本地快照(含样品/退货等单别)。 + +本轮未命中、但本地已有批次或已锁定的行:不删除,`erp_missing = true`,默认列表不展示,可提示「已不在同步范围」。 + +### 3.5 标准 SELECT + +```sql +SELECT + a.oea01 AS order_no, + b.oeb03 AS line_no, + a.oea02 AS order_date, + a.oea03 AS customer_no, + d.occ02 AS customer_short_name, + d.occ18 AS customer_full_name, + a.oea14 AS salesperson_code, + e.gen02 AS salesperson_name, + a.oea15 AS dept_code, + f.gem02 AS dept_name, + a.oea10 AS customer_po, + b.oeb04 AS part_no, + b.oeb06 AS part_name, + c.ima021 AS spec, + b.oeb11 AS customer_part_no, + b.oeb15 AS agreed_date, + b.oeb05 AS unit, + b.oeb12 AS qty, + NVL(b.oeb24, 0) AS delivered_qty +FROM HXJM.OEA_FILE a +INNER JOIN HXJM.OEB_FILE b ON a.oea01 = b.oeb01 +LEFT JOIN HXJM.IMA_FILE c ON b.oeb04 = c.ima01 AND b.oeb06 = c.ima02 +LEFT JOIN HXJM.OCC_FILE d ON a.oea03 = d.occ01 +LEFT JOIN HXJM.GEN_FILE e ON a.oea14 = e.gen01 +LEFT JOIN HXJM.GEM_FILE f ON a.oea15 = f.gem01 +WHERE a.oeaconf = 'Y' + AND a.oea49 = '1' + AND NVL(b.oeb70, 'N') = 'N' + AND NVL(b.oeb24, 0) = 0 +``` + +同步服务与 [`backend/scripts/order_delivery_query.py`](../../../backend/scripts/order_delivery_query.py) 共用同一 SQL 常量。后期单别白名单再给 WHERE 追加 `IN` 启用编码。 + +--- + +## 4. 本地库 + +```mermaid +erDiagram + order_delivery_erp_lines ||--o{ order_delivery_batches : has + order_delivery_erp_lines ||--o| order_delivery_line_states : has + order_delivery_erp_lines ||--o{ order_delivery_audit_events : has + order_delivery_sync_runs ||--o{ order_delivery_erp_lines : writes +``` + +| 表 | 谁写 | +| --- | --- | +| `order_delivery_erp_lines` | 仅同步 | +| `order_delivery_batches` | 仅保存回复 | +| `order_delivery_line_states` | 仅通知成功路径 | +| `order_delivery_audit_events` | 保存 / 通知 / 锁定 / 同步 | +| `order_delivery_sync_runs` | 同步作业 | + +### 4.1 `order_delivery_erp_lines` + +唯一键 `(order_no, line_no)`。 + +相对 v0.1 增加:`customer_short_name`、`customer_full_name`、`salesperson_name`、`dept_name`、`slip_code`。仍存 `salesperson_code`、`dept_code` 供企微映射与排错。同步 upsert **只更新本节 ERP 列**。 + +`slip_code`:从 `oea01` 取连字符前的单别(`8301-1605280014` → `8301`)。一期只落库预留,**不展示、不过滤、无管理端勾选**。后期白名单可直接用此列。 + +### 4.2 批次 / 状态 / 审计 + +与 v0.1 相同:未锁定按行整表替换批次;锁定后拒绝写入。 + +读时推导行状态:无批次 → 未回复;有批次未 `locked` → 部分回复;`locked` → 已回复。 + +列表筛选 `status`:`已回复` 只返回已锁定行;`未完全回复` 返回未回复 ∪ 部分回复。默认只列 `erp_missing = false` 的行。一期不按单别裁行。 + +--- + +## 5. 同步作业与定时提醒 + +- **定时全量:** `ScheduleTask` cron `0 7 * * *`,时区 `Asia/Shanghai`;拉全部已审核+已核准+未结案行。 +- **手动全量:** 生管 POST `/sync`,范围同上。 +- **到期排程触发(2026-09-29 更新):** 排程扫描由独立进程 `workers/worker_scheduler.py`(compose `hxops-schedule-worker` 容器)执行——只跑 `run.py` 的本地环境不会有进程自动触发 07:00/07:10,需另起 worker 进程或手动执行。本功能 2026-09-21 曾加过 Web 进程内兜底扫描(`services/schedule/web_scanner.py`,`SCHEDULE_WEB_SCANNER_ENABLED`),2026-09-29 合并 dev 主线(Wave 4 scheduler 迁移)后 `create_app` 不再启动它(模块保留备用)。 +- **同步完成提醒生管(2026-09-21):** 排程同步成功后按任务 `notify_enabled` + `notify_user_ids_json`(管理端排程表单现成字段)给生管发企微「今日订单交期数据已同步完成(共 N 行),请及时查看并回复交期。」,并写 `run.response_summary_json.domain_notification_managed=true` 抑制通用「排程执行结果」通知避免双重打扰;通知失败只记入运行 errors,不改变同步成功状态。 +- **每日提醒排程(2026-09-21):** `order-delivery-remind`(日批 07:10,种子 `SCH-ORDER-DELIVERY-REMIND`),实现见 `services/order_delivery_reply/reminder_service.py`: + - **启停开关(2026-09-21 增补):** 任务参数 `ship_remind_enabled` / `unreplied_remind_enabled`(布尔,默认开)**独立启停**两类提醒;关闭的一侧跳过(summary 记 `skipped=disabled`),不影响另一侧。 + - **出货提醒:** 已锁定(已回复)行批次 `planned_date` 落在 [今天, 今天+N](N=`ship_remind_advance_days`,默认 3)→ 按业务员聚合一条企微提醒安排出货;同一 (行,交期) 以 `audit_events action=ship_remind payload.ok=true` 去重,发送失败不落成功记录、次日自动补发;业务员工号对不上企微的记失败审计并在运行 errors 提示。 + - **未回复再提醒:** 未锁定行订单日期(快照 `order_date`,取 ERP `oea02`;2026-09-23 由快照首次入库 `created_at` 改来)距今 ≥ N(N=`unreplied_remind_days`,默认 3)→ 按收件人聚合一条企微提醒生管(订单日期为空不参与);收件人取任务参数 `unreplied_remind_user_ids`(留空回退本任务 `notify_enabled` + `notify_user_ids_json`);同一行距上次成功提醒 ≥ N 天才再次提醒(节奏锚点同为审计,`ok=true` 才计入)。 + - 两个扫描互相独立:单侧异常回滚后继续另一侧,错误计入运行 errors;提醒只读业务数据 + 写审计,绝不改批次/锁定。 + - **配置复用:** 开关与天数在管理端排程表单「任务参数」修改(boolean/number 字段);生管收件人在排程表单「通知开关 + 通知人」配置——不新增配置页面。 +- 同时只跑一个同步。Oracle 按 `oea01` 分页。失败保留快照并记 `sync_runs`。 +- - **收件人分离(2026-09-22):** 未回复提醒的生管收件人改用任务参数 `unreplied_remind_user_ids`(multi_select,候选 `hxops_users`=全部启用用户,表单内支持按姓名/工号/部门关键词搜索),与平台运行结果通知的「通知人」(`notify_user_ids_json`)互相独立;参数留空回退通知人兼容旧配置。 +- **天数钳制(2026-09-22):** 提醒天数统一钳制 0-3650——表单误填巨大值时 `today + timedelta(N)` 溢出抛 `OverflowError: date value out of range`,导致 2026-09-22 出货提醒扫描失败(未回复提醒不受影响)。 + +--- + +## 6. API + +统一 `{ success, data, request_id }`,失败 `raise AppError`。 + +| 方法 | 路径 | 作用 | +| --- | --- | --- | +| GET | `/lines` | 筛选分页。查询条件见下;只返回未 `erp_missing` 的已同步行 | +| POST | `/admin/permissions/grant-by-department` | 可选:按部门给成员批量写入功能权限(一次性发放,之后仍按用户勾选判定) | +| GET | `/lines/:orderNo/:lineNo` | 单行 + 批次 + 状态 | +| PUT | `/lines/:orderNo/:lineNo/batches` | 保存该行批次;各批次合计必须等于订单数量(422 `BATCH_QTY_TOTAL_MISMATCH`),锁定 409 | +| POST | `/lines/:orderNo/:lineNo/notify` | 单行通知;成功则锁定(前端不出行内按钮,接口保留:批量通知逐行复用同一服务入口,也可外部调用) | +| POST | `/batch-reply` | 联合回复,**只保存批次** | +| POST | `/notify-batch` | 批量通知勾选行;无批次或已锁定跳过 | +| POST | `/sync` | 手动同步 | +| GET | `/sync/latest` | 最近一次同步 | + +GET `/lines` 查询:`keyword`(合并搜索:订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号/业务员(姓名、工号)/交期回复人员(姓名、工号,行状态快照 EXISTS,2026-09-23 增补)OR 命中)、`order_date`、`status`(空=`全部` / `已回复` / `未完全回复`)、`page`、`page_size`。默认排序 `order_date, customer_no, order_no, line_no, part_no` 升序。`page_size` 默认 50。全选仅本页。 + +直链打开 `erp_missing` 的行:按不存在处理,不在工作台展示。 + +`notify` / `notify-batch`:通知与锁定同一事务。单行失败不回滚其它行。 + +--- + +## 7. 通知与权限 + +### 7.1 企微 + +`salesperson_code` → `User.employee_id` → `wecom_userid`。已确认能对上。对不上则该行失败、不锁定。 + +走平台既有 `send_wecom_event_message`:textcard 壳、按钮「查看详情」、跳转 URL 拼装、`WecomNotifyAudit` 回执,全部用现成实现。本 Agent **只传业务参数**,不另定卡片样式、按钮文案、markdown、图文或模板卡片。 + +| 参数 | 取值 | +| --- | --- | +| `event_type` | `order_delivery_reply_notify`(下划线命名;已加入 `WECOM_NOTIFY_EVENTS` 默认清单,与其它事件同一配置。2026-09-21 修正:此前文档误写为点号 `order_delivery_reply.notify`,与代码不符) | +| `title` | `订单交期回复` | +| `content` | `您有订单号:项次{order_no}:{line_no}的订单需要填写/确认/查看交期。` | +| `jump_path` | 工作台路由,带该行查询参数 | + +批量通知按行各调一次同一接口。发送成败以该函数返回为准;回执只记既有审计,不改交期回复状态。 + +**定时提醒复用同一 `event_type`**,文案与触发规则见 §5「同步完成提醒生管 / 每日提醒排程」(同步完成、出货提醒、未回复再提醒三类;卡片同样跳工作台,逐行写 `ship_remind` / `unreplied_remind` 审计)。 + +### 7.2 功能权限 + +操作权限挂在用户 `feature_permissions` 上,与合同付款预警的 `contract_payment.access` 同一套机制。**每次请求只看用户勾选,不拿 `User.department` 当门禁。** 不新增 `User.role`。 + +| 键 | 默认 | 能力 | +| --- | --- | --- | +| `order_delivery_reply.manage` | `admin` 开,其他人关 | 查看已同步订单;回复批次;单行/批量通知;手动同步 | +| `order_delivery_reply.access` | `admin` 开,其他人关 | 查看已同步订单;只读 | + +判定:`manage` 命中 → 可写(同时视为有 `access`);否则仅 `access` → 只读;否则无菜单、API 403。侧栏与路由只负责展示,后端仍 403。 + +菜单与 GET 需 `access` 或 `manage`;保存 / 通知 / 同步需 `manage`。 + +企微收件人仍按订单业务员 `oea14` → `User.employee_id`,与这两个勾选无关。具备 `access` 的人看**已同步全量**,不按「是否本人业务员」裁行。 + +用户管理表单提供上述两键勾选(文案四语言)。人多时管理员可选用部门批量授权:选部门 + 授予 `manage` 或 `access`,把勾选写到当时该部门成员的用户记录上。这是一次性发放;调岗后权限不会因部门字段变化自动增减,需再勾或再跑一次发放。 + +--- + +## 8. 前端 + +`frontend/src/features/order-delivery-reply/`:`constants.ts`(权限键)、`api/orderDeliveryReply.api.ts`(统一 `requestJson`)、`views/OrderDeliveryReplyPage.vue`(操作页)。交互以更新后的原型 v5 为准。工具栏:「联合回复交期」与「批量通知」分开;**通知唯一入口为「批量通知」**,列表不出「通知业务部门」列(行内不设发送按钮;已通知对象与时间并入「交期回复人员」列)。状态徽标按需求 §12,不用旧原型按数量覆盖的脚本。 + +列表(2026-09-21 修订列顺序,独立「部门」「品名」列取消)按序为:勾选、客户编号(副文案客户简称,全名 title)、订单日期、订单单号:项次、产品编号(副文案品名)、客户产品编号、数量、约定交货日、交期回复状态、交期回复、交期回复人员、业务员(副文案部门)、客户订单、规格、单位。表格浏览体验(2026-09-21):页面高度收敛至视口(滚动全部发生在表格容器内 → 列头 sticky 固定、横向滚动条常驻表格底缘);左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,冻结单元格实色背景防透出,宽度已收窄至 2/8/6/10rem);行高紧凑(表体 py-1.5,产品编号/品名/规格/客户订单/客户简称长文本单行截断 + title 悬停看全文,交期回复批次条不折行);筛选区与工具栏字号与表格统一(text-sm 14px,状态徽标例外保持 text-xs 12px 加粗)并压缩高度。列项与顺序不变。不渲染订单类型、单别、已转请购、排定交货日,亦不出「已交数量 / 未交数量」列(`NVL(oeb24,0)=0` 过滤后无信息量;未交口径仍由后端计算,供回复弹窗数量守恒校验——各批次合计必须等于订单数量,2026-09-23 由「超额仅提醒」修订);表头与工具栏提示不换行(`whitespace-nowrap`,避免窄列中文竖排)。分页复用共享 `PaginationBar`(与管理控制台-数据报表同一组件:摘要 + 每页条数 20/50/100/200 + 页码按钮)。客户列:编号 + 简称,全名作 title;产品编号列:编号 + 品名;业务员列:姓名 + 部门,同款上下两行合并展示。仅 `access` 时隐藏回复、通知、同步按钮与手动刷新。用户管理勾选两键功能权限。一期无单别管理页。 + +### 8.1 路由与入口 + +- **路由**:`workspace-order-delivery-reply`(`workspace.routes.ts`),`meta.requiresFeaturePermission = order_delivery_reply.access`,由既有 `guards.ts` 守卫;路径常量 `WORKSPACE_PATHS.orderDeliveryReply`。 +- **工作台侧栏**:**不设菜单项**(需求 Q-03 修订:不在「货代发货通知」分组下挂入口,导航一律走应用入口)。 +- **应用入口(R-ENTRY-02)**:注册到应用管理——`app_seed.py` 幂等创建 `Agent(agent_code='order_delivery_reply', runtime_provider='iframe', iframe_url='/apps/order-delivery-reply')`(**不接 Dify**,`dify_app_id/api_key` 为空);admin 自动可见全部启用应用,普通用户经用户管理 Agent 权限授权后可见;点击进入 `/chat/{id}` 由聊天壳按 iframe provider 整页渲染免布局嵌入路由 `app-order-delivery-reply`(`routes/index.ts` 顶层注册,同页组件 + 同功能权限守卫)。管理员可在应用管理改名称/描述/图标/排序,但不应把 runtime_provider 改回 dify。页面与 API 仍受 access/manage 功能权限守卫(两层各司其职:Agent 权限管入口可见性,功能权限管页面/接口)。 +- **企微直达**:四类卡片 `jump_path` 均为 `/apps/order-delivery-reply`(免布局嵌入路由,企微内打开不带工作台侧栏;2026-09-22 由 /workspace 路由改来),带查询参数定位「该 Agent 对应的内容及位置」,点击后未登录先走 `/login?redirect=深链`、登录成功原样回跳: + - 行级通知卡:`order_no` + `line_no` → 页面自动填关键词筛选、按行滚动定位并高亮 8 秒(提示 toast); + - 未回复提醒卡:`status=not_fully_replied` → 还原「未完全回复」筛选; + - 出货提醒卡:`status=replied` → 还原「已回复」筛选; + - 同步完成提醒卡:`status=not_fully_replied` → 还原「未完全回复」筛选(生管待回复行)。 + 所有卡片另带 `wecom_trace`,操作页加载后调 `/api/user/wecom/deeplink-opened` 上报打开回执(与工作台 deeplink 同一接口,失败静默)。 + +### 8.2 提示与刷新(需求 §9 即时刷新) + +- 保存/单行通知/批量通知/手动同步完成后均重新拉取列表与最近同步时间。 +- 单行通知失败:catch `BusinessError` → `useMessage().error()`(errors.json 四语言文案,累计 14 个 `ORDER_DELIVERY_REPLY.*` 键)。 +- 批量通知按 `succeeded/failed/skipped` 分级:部分成功 warning 汇总(含失败行明细)、全部失败 error、全成功 success。 +- 联合回复保存提示明确「未通知,可继续修改」。 + +### 8.3 i18n + +页面文案集中于 `locales/*/workspace.json` 的 `workspace.orderDeliveryReply.*`(约 91 键/语言,含 nav 键与入口副标题 `entryHint`),四语言同步;禁止硬编码中文。 + +--- + +## 9. 实现顺序(2026-09-17 一期落地;2026-09-21 增补第 8 项) + +1. 模型 + 迁移 + 同步(含 WHERE 与客户/姓名 JOIN) +2. GET 列表 +3. 保存批次与状态 +4. 单行通知 + 锁定 + 审计 +5. 联合回复保存 + 批量通知 +6. 07:00 排程 +7. 功能权限键 + 用户表单勾选 + 菜单守卫(可选部门批量发放) +8. (2026-09-21)07:00 到期排程 Web 进程内兜底扫描(`SCHEDULE_WEB_SCANNER_ENABLED`)+ 同步完成提醒生管 + `order-delivery-remind` 日批提醒(出货/未回复,布尔开关独立启停 + 天数可配)+ 工作台列顺序修订与合并展示 + +--- + +## 10. 风险 + +| 风险 | 处理 | +| --- | --- | +| `HXJM.GEN_FILE` 不存在 | 回退 `ERP_GEN_FILE_V` | +| 新员工未勾权限 | 无入口;可用用户管理单人勾选或部门批量发放 | +| 同步覆盖回复 | upsert 白名单仅 ERP 列 | + +--- + +## 11. 不在本期 / 后期 + +回写 ERP、解锁、对话式填交期(Chat 内直接填写批次)、邮件、撤回企微、订单类型列 / 已转请购 / 排定交货日、工作台单别列、每次请求按部门名称判定操作权限(已废止)、本 Agent 自绘企微卡片样式、v2 侧栏统计、独立 FastAPI。聊天侧栏与工作台首页的**跳转入口**已纳入一期(R-ENTRY-02):前端固定入口项,点击路由到工作台操作页,不新增 Dify 应用。 + +**后期:单别白名单管理配置。** 一期不做该页、不做同步 `IN` 过滤。后续加上时沿用已拍板的方案 A:配置表 `order_delivery_slip_settings`;GET/PUT `/admin/slips`;同步 WHERE 带启用 `slip_code`;空名单不拉行;新勾选保存后增量同步这些单别;取消勾选立即从列表隐藏并标 `erp_missing`;操作页始终不出单别列。预留列 `slip_code` 一期已写入快照。 diff --git a/docs/funclist.md b/docs/funclist.md index 01557349..a9c8613a 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -1,5 +1,21 @@ # 智能HR请假管理功能清单 +## 订单交期回复 Agent + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| ERP 订单行同步 | 已实现 | 每天 07:00(Asia/Shanghai)排程 + 生管手动全量同步,同步成功后按任务参数「同步完成提醒收件人」提醒生管(与「通知人」互相独立,留空回退通知人);到期排程由独立 worker 进程执行(`workers/worker_scheduler.py` / 生产 `hxops-schedule-worker` 容器;2026-09-29 合并 dev 主线后 Web 进程不再兜底扫描);只拉已审核(`oeaconf='Y'`)+ 已核准(`oea49='1'`)+ 未结案(`oeb70≠Y`)+ 完全未交(`NVL(oeb24,0)=0`,已有交货的行不同步)的订单行到本地快照(`order_delivery_erp_lines`),upsert 仅更新 ERP 列白名单不覆盖回复;本轮未命中行标 `erp_missing` 不删除;失败保留上次快照并展示最近同步时间。 | +| 同步完成提醒生管 | 已实现 | 07:00 排程同步成功后,按该排程任务的「通知开关 + 通知人」(管理端排程表单现成配置,人员可配置)给生管发企微提醒查看当天交期回复(复用 `send_wecom_event_message`,事件 `order_delivery_reply_notify`);通知失败不影响同步结果;已置 `domain_notification_managed` 抑制通用排程完成通知避免双重打扰。 | +| 订单行查询台 | 已实现 | 工作台操作页筛选分页:**关键词合并搜索**(订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号/业务员/交期回复人员命中任一,2026-09-21 由三框合并、2026-09-23 增补人员搜索)+ 订单日期 + 状态(全部·已回复·未完全回复),默认排序订单日期→客户→单号→项次,分页默认 50;列顺序:客户编号(副文案简称) → 订单日期 → 订单单号:项次 → 产品编号(副文案品名) → 客户产品编号 → 数量 → 约定交货日 → 交期回复状态 → 交期回复 → 交期回复人员 → 业务员(副文案部门) → 客户订单 → 规格 → 单位(独立的部门列/品名列已取消,与业务员/产品编号合并展示);表格浏览体验:页面高度收敛至视口(列头固定、横向滚动条常驻)、左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,已收窄)、行高紧凑(长文本截断悬停看全文、批次条不折行)、筛选区与工具栏字号与表格统一并压缩高度(全页 text-sm 14px,状态徽标例外 text-xs 12px 加粗);列表不出已交/未交两列(完全未交过滤后无信息量);行状态读时推导未回复/部分回复/已回复;列表不出单别、订单类型、已转请购、排定交货日。 | +| 每日提醒(出货 + 未回复) | 已实现 | 新排程 `order-delivery-remind`(日批 07:10,种子 `SCH-ORDER-DELIVERY-REMIND`):① 已回复(已锁定)行的回复交期距今 ≤「出货提醒提前天数」(默认 3,任务参数可配)时按业务员聚合发一条企微提醒安排出货,同一(行,交期)只提醒一次、发送失败次日自动补发;② 超过「未回复再次提醒天数」(默认 3,任务参数可配)仍未回复的行按收件人聚合一并企微提醒生管(收件人=任务参数「未回复提醒收件人」多选,候选全部启用用户可搜索,与运行结果通知的「通知人」互相独立,留空回退通知人),同一行每 N 天最多提醒一次;两类提醒由任务参数 `ship_remind_enabled` / `unreplied_remind_enabled`(布尔,默认开)独立启停;提醒逐行写审计 `ship_remind` / `unreplied_remind`,只读业务数据不改批次/锁定;提醒天数钳制 0-3650(防日期溢出崩溃,2026-09-22 修复)。 | +| 单行 / 拆分回复 | 已实现 | 弹窗维护 1..20 批「交期 + 数量 + 备注」,交期必填、数量>0、备注≤200、交期不重复,支持快速统一交期;行徽标展示「订单数量:X 单位」;**数量守恒**:各批次合计必须等于订单数量才能保存;缺交期/缺数量、同单批次交期重复均按批次序号实时提示并随填写切换(2026-09-23 由「超额仅提醒」修订,后端 422 `BATCH_QTY_TOTAL_MISMATCH` / `BATCH_INVALID` 兜底);未锁定行整表替换批次;已锁定行 409。 | +| 联合回复与批量通知 | 已实现 | 勾选多行(全选仅本页)「联合回复交期」逐行保存批次(单次≤200 行,单行失败不回滚其它行;每行各批次合计须等于订单数量,不等行按行失败);通知唯一入口为工具栏「批量通知」(列表不出通知列,已通知对象与时间并入「交期回复人员」列),对已有批次且未锁定的行逐行发送并锁定,无批次/已锁定跳过并汇总提示。 | +| 企微通知与行级锁定 | 已实现 | 复用平台 `send_wecom_event_message`(textcard 壳 + 既有回执审计,不自绘卡片);收件人按订单业务员 `oea14`→`User.employee_id`→企微 userid,对不上该行失败不锁定;发送成功与 locked 同事务(禁止已通知未锁定);正文「您有订单号:项次{单号}:{项次}的订单需要填写/确认/查看交期。」;四类卡片按类型带参直达操作页(行通知带单号+项次定位高亮、提醒卡带状态筛选),未登录先登录后原样回跳。 | +| 功能权限与审计 | 已实现 | 用户功能权限 `order_delivery_reply.manage`(生管可写)/ `access`(业务只读),admin 默认开,用户管理表单勾选(四语言),可选按部门一次性批量发放;保存/通知/锁定/同步/出货提醒/未回复提醒六类审计(`order_delivery_audit_events`)。单别白名单管理为后期(`slip_code` 已落库预留)。 | +| 入口(独立应用) | 已实现 | 应用管理注册内置 iframe 应用(`agent_code=order_delivery_reply`,不接 Dify):出现在应用管理/全部应用/聊天侧栏,点击在聊天壳内整页打开操作页(免布局嵌入路由);入口可见性走 Agent 权限(admin 自动可见),页面与 API 仍受 `access`/`manage` 功能权限守卫;工作台侧栏货代分组不设菜单项。 | + +需求权威:[docs/features/order-delivery-reply/demand.md](features/order-delivery-reply/demand.md)。 + ## 可配置权限组(2026-09) | 功能项 | 状态 | 说明 | @@ -10,6 +26,7 @@ | 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 | | 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 | + ## 合同付款预警 Agent | 功能项 | 状态 | 说明 | diff --git a/frontend/src/app/router/routes/index.ts b/frontend/src/app/router/routes/index.ts index 7e7d894d..170a36db 100644 --- a/frontend/src/app/router/routes/index.ts +++ b/frontend/src/app/router/routes/index.ts @@ -8,6 +8,7 @@ import { authRoutes } from './auth.routes'; import { chatRoutes } from './chat.routes'; import { kbRoutes } from './kb.routes'; import { workspaceRoutes } from './workspace.routes'; +import { orderDeliveryReplyEmbedRoute } from './workspace.routes'; import { useAuthStore } from '@/features/auth/stores/auth.store'; import { DEFAULT_CHAT_AGENT_ID } from '@/shared/constants/routes'; @@ -21,6 +22,7 @@ export const appRoutes: RouteRecordRaw[] = [ }, }, ...authRoutes, + orderDeliveryReplyEmbedRoute, ...workspaceRoutes, ...chatRoutes, ...adminRoutes, diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index a3a1831c..83b6cb05 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -5,10 +5,20 @@ * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款、立账凭证旧地址重定向到 Chat Agent。 */ import type { RouteRecordRaw } from 'vue-router'; +import { ORDER_DELIVERY_REPLY_ACCESS_PERMISSION } from '@/features/order-delivery-reply/constants'; +// 合同付款 / 立账凭证旧工作台地址 → 聊天 Agent 重定向壳(dev 侧重构引入)。 const contractPaymentChatRedirect = () => import('@/features/contract-payment/views/ContractPaymentChatRedirect.vue'); const voucherCheckChatRedirect = () => import('@/features/voucher-check/views/VoucherCheckChatRedirect.vue'); +// 订单交期回复嵌入路由:应用管理 iframe 应用的目标(无工作台布局壳,聊天壳内整页渲染)。 +export const orderDeliveryReplyEmbedRoute: RouteRecordRaw = { + path: '/apps/order-delivery-reply', + name: 'app-order-delivery-reply', + component: () => import('@/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue'), + meta: { title: 'workspace.nav.orderDeliveryReply', requiresFeaturePermission: ORDER_DELIVERY_REPLY_ACCESS_PERMISSION }, +}; + export const workspaceRoutes: RouteRecordRaw[] = [ { path: '/workspace', @@ -92,6 +102,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [ component: voucherCheckChatRedirect, meta: { title: 'workspace.voucherCheck.detailTitle' }, }, + { + path: 'order-delivery-reply', + name: 'workspace-order-delivery-reply', + component: () => import('@/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue'), + meta: { title: 'workspace.nav.orderDeliveryReply', requiresFeaturePermission: ORDER_DELIVERY_REPLY_ACCESS_PERMISSION }, + }, { path: 'contract-payment', name: 'workspace-contract-payment', diff --git a/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue b/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue index 23bc5f09..34b6fa3d 100644 --- a/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue +++ b/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue @@ -133,6 +133,20 @@ const loadOptions = async (source: string): Promise => { } }; +/** multi_select 选项本地搜索词(按字段 key 隔离)。 */ +const multiSearch = reactive>({}); + +/** multi_select 选项按关键词过滤(匹配 label/描述,大小写不敏感)。 */ +const filteredMultiOptions = (field: PlatformTaskParamField) => { + const keyword = (multiSearch[field.key] || '').trim().toLowerCase(); + const all = optionsCache[field.options_source || ''] || []; + if (!keyword) return all; + return all.filter((o) => + String(o.label || '').toLowerCase().includes(keyword) || + String(o.description || '').toLowerCase().includes(keyword), + ); +}; + /** multi_select 勾选切换。 */ const toggleMultiValue = (key: string, value: string | number): void => { const current: Array = Array.isArray(params.value[key]) ? [...params.value[key]] : []; @@ -323,6 +337,12 @@ watch( v-else-if="field.type === 'multi_select'" class="max-h-52 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2" > +

{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}

@@ -332,8 +352,14 @@ watch( > {{ $t('admin.schedule.form.dynamicParamsNoOptions') }}

+

+ {{ $t('admin.schedule.form.dynamicParamsSearchNoMatch') }} +

+ + +
-
-
-
-
+
+
+
+
{{ getUserAvatarLabel(userProfile.profileUser) }}
diff --git a/frontend/src/features/workspace/constants/routes.ts b/frontend/src/features/workspace/constants/routes.ts index cf86cf67..f7903444 100644 --- a/frontend/src/features/workspace/constants/routes.ts +++ b/frontend/src/features/workspace/constants/routes.ts @@ -19,6 +19,7 @@ export const WORKSPACE_PATHS = { accountingVoucherCheck: '/workspace/accounting-voucher-check', accountingVoucherCheckDetail: (runId: number | string) => `/workspace/accounting-voucher-check/runs/${runId}`, contractPayment: '/workspace/contract-payment', + orderDeliveryReply: '/workspace/order-delivery-reply', contractPaymentReview: '/workspace/contract-payment/review', contractPaymentWeeklyBatches: '/workspace/contract-payment/weekly-batches', contractPaymentDetail: (contractId: number) => `/workspace/contract-payment/contracts/${contractId}`, @@ -38,6 +39,7 @@ export const LEGACY_VIEW_TO_PATH: Record = { shipping_notice: WORKSPACE_PATHS.shippingNotice, accounting_voucher_check: WORKSPACE_PATHS.accountingVoucherCheck, contract_payment: WORKSPACE_PATHS.contractPayment, + order_delivery_reply: WORKSPACE_PATHS.orderDeliveryReply, history: WORKSPACE_PATHS.history, }; diff --git a/frontend/src/locales/en/admin.json b/frontend/src/locales/en/admin.json index e06e91f2..11dd1621 100644 --- a/frontend/src/locales/en/admin.json +++ b/frontend/src/locales/en/admin.json @@ -47,7 +47,8 @@ "linkedServices": "Linked Services", "procurementContract": "Procurement Contract Review", "trainingConfig": "Training Config", - "integrationConnector": "Integration Connector" + "integrationConnector": "Integration Connector", + "contractPayment": "Contract Payment Alerts" }, "shippingOrderExtractionRuns": { "eyebrow": "READ-ONLY RUN DIAGNOSTICS", @@ -1139,7 +1140,12 @@ "status": "Status", "enable": "Enable", "disable": "Disable", - "save": "Save" + "save": "Save", + "guideUsage": "Material Usage", + "generalGuide": "General Guide", + "trainingVideo": "Employee Training Video", + "trainingExamPdf": "Employee Training Exam PDF", + "guideUsageHint": "The training workspace prioritizes \"Employee Training Video\" and \"Employee Training Exam PDF\" materials." }, "dash": { "activeAgents": "Active Agents", @@ -1208,6 +1214,10 @@ "trainingLeanTeamManage": "Lean training team management", "contractPaymentAccess": "Contract payment alert access", "contractPaymentAccessHint": "Allows this user to open the contract payment workbench (ledger, review, weekly batches). Syncing OA, scanning alerts, and sending weekly alerts remain admin-only.", + "orderDeliveryReplyManage": "Order Delivery Reply Manage", + "orderDeliveryReplyManageHint": "Grants replying delivery batches, sending/batch notifications and manual ERP sync (production planning).", + "orderDeliveryReplyAccess": "Order Delivery Reply Access", + "orderDeliveryReplyAccessHint": "Grants read-only access to synced orders and replies (business users); managing requires the manage permission.", "password": "Password", "passwordHint": "(leave blank to keep)", "noAgents": "No agents available." @@ -1249,7 +1259,11 @@ "delete": "Delete", "viewMembers": "View department members" }, - "members": { "title": "{name} Members", "count": "{count} members", "empty": "No members" }, + "members": { + "title": "{name} Members", + "count": "{count} members", + "empty": "No members" + }, "fields": { "name": "Name", "namePlaceholder": "e.g. IT Department", @@ -1796,7 +1810,12 @@ "employeeIdSource": "Employee ID Source", "mobileNormalize": "Normalize mobile number", "publicBaseUrl": "Public HTTPS base (extranet)", - "userSelect": "Select user" + "userSelect": "Select user", + "callbackToken": "Callback Token", + "encodingAesKey": "EncodingAESKey", + "callbackUrl": "Callback URL", + "homepageUrl": "Homepage URL", + "trustedDomain": "Trusted Domain" }, "bindModes": { "match_rules": "Match automatically", @@ -1909,8 +1928,23 @@ "filterName": "Filter by Name/Username", "filterDept": "Filter by Department", "allRoles": "All Roles", - "views": { "apps": "By Application", "members": "By Member" }, - "appHeaders": { "app": "Application", "type": "Type", "authorized": "Authorized", "actions": "Actions", "viewMembers": "View members", "accessHint": "Open member permissions", "memberHint": "Add or remove access to this application", "memberSearch": "Search name, username, employee ID, or department", "addMember": "Grant access", "removeMember": "Remove access", "noMembers": "No matching members" }, + "views": { + "apps": "By Application", + "members": "By Member" + }, + "appHeaders": { + "app": "Application", + "type": "Type", + "authorized": "Authorized", + "actions": "Actions", + "viewMembers": "View members", + "accessHint": "Open member permissions", + "memberHint": "Add or remove access to this application", + "memberSearch": "Search name, username, employee ID, or department", + "addMember": "Grant access", + "removeMember": "Remove access", + "noMembers": "No matching members" + }, "headers": { "user": "User", "realName": "Real Name", @@ -2147,7 +2181,7 @@ "tokens_completion": "Completion Tokens", "total_tokens": "Total Tokens", "latency_ms": "Latency (ms)", - "latency": "Latency", + "latency": "Latency (ms)", "cost": "Cost", "ip": "IP", "user_agent": "User Agent", @@ -2166,7 +2200,6 @@ "source_page": "Source Page", "risk_status": "Risk Status", "risk_score": "Risk Score", - "latency": "Latency (ms)", "is_empty_answer": "Empty Answer", "is_system_failure": "System Failure", "feedback_score": "Rating", @@ -2183,7 +2216,8 @@ "agents": "App Ops", "ops_overview": "Ops Overview", "issue_analysis": "Issue Analysis", - "usage_analysis": "Usage Analytics" + "usage_analysis": "Usage Analytics", + "permission_requests": "Permission Requests" }, "feedbackValues": { "types": { @@ -2391,6 +2425,14 @@ "topApp": "App to optimize", "topAppHint": "Attention signal share {ratio}%" } + }, + "usageRangeLabel": "Time range", + "usageRanges": { + "7d": "Last 7 days", + "30d": "Last 30 days", + "90d": "Last 3 months", + "180d": "Last 6 months", + "365d": "Last 12 months" } }, "batchEdit": { @@ -2650,7 +2692,9 @@ "voucherCheckNotifyMissing": "Notify on missing materials", "voucherCheckNotifyMissingHint": "Master switch. Set missing-file recipients in Chat “Accounting voucher check → Notification config” by file type. The schedule people picker is only for failure alerts.", "voucherCheckNotifyFailure": "Failure alert", - "voucherCheckNotifyFailureHint": "Technical failures go to the people selected below." + "voucherCheckNotifyFailureHint": "Technical failures go to the people selected below.", + "dynamicParamsSearchPlaceholder": "Search options (name / ID / dept)…", + "dynamicParamsSearchNoMatch": "No matching options" }, "testRun": { "title": "Test run — {name}", @@ -2734,7 +2778,8 @@ "notConfiguredUseDefault": "(Not configured; using Dify workflow default prompt)", "notEnabledTest": "Dify was not enabled for this test", "notEnabledRun": "Dify Agent was not enabled for this run" - } + }, + "excelExportFailedHint": "Inventory source succeeded, but schedule Excel generation failed" }, "shippingIdentityRules": { "eyebrow": "Shipping customer governance", @@ -4380,7 +4425,8 @@ "rejected": "Rejected", "needs_review": "Needs review" }, - "confirmRequiresNativePreview": "Load the native PDF preview before confirming a visual binding" + "confirmRequiresNativePreview": "Load the native PDF preview before confirming a visual binding", + "createBlockersTitle": "Pre-creation Blockers" }, "xfaAutoMark": { "title": "Auto-mark suggestions", @@ -5422,7 +5468,17 @@ "trainingAgentRequired": "The Employee Training agent was not found, so a video resource cannot be created", "videoUploaded": "Training video uploaded and added to configuration resources", "videoUploadFailed": "Failed to upload training video" - } + }, + "eyebrow": "Training Operations Center", + "pageHint": "Configuration changes take effect after saving", + "footerHint": "All configuration items can be adjusted after saving", + "stats": { + "total": "Total Configs", + "published": "Published", + "resources": "Current Materials", + "levels": "Configured Levels" + }, + "questionBankTitle": "Onboarding Question Bank" }, "integrationConnector": { "title": "Integration Connector", diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index 82a0852f..38d051f3 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -1188,7 +1188,11 @@ "departmentLabel": "Department", "allStatuses": "All statuses", "allDepartments": "All departments", - "noLimit": "No limit" + "noLimit": "No limit", + "typeLabel": "Training Type", + "allTypes": "All Training", + "typeOnboarding": "Onboarding Training", + "typeSafety": "Safety Training" }, "columns": { "joinDate": "Join date", @@ -1543,6 +1547,75 @@ "Which employees have not finished training?", "I want this month training score statistics" ] + }, + "safety": { + "tabs": { + "onboarding": "入职培训", + "safety": "安全培训" + }, + "progressTitle": "三级安全教育培训进度", + "progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。", + "steps": { + "company": "01 · 公司级", + "department": "02 · 部门级", + "team": "03 · 班组级", + "exam": "04 · 统一考试" + }, + "stepStatus": { + "watchVideo": "观看视频", + "examReq": "≥90 分及格", + "completed": "已完成", + "inProgress": "进行中", + "pending": "待学习", + "examPending": "需先学完三级" + }, + "videoPanelTitle": "{level} 第{step}步", + "videoPanelSubtitle": "观看安全教育培训视频", + "videoPanelPassLine": "及格线:≥ 90分方可进入考试", + "videoTitle": "部门安全生产管理制度宣导", + "videoDuration": "时长 35 分钟 · 已完成 12%", + "materialsTitle": "培训资料清单 (共 3 个文件/视频)", + "materials": { + "m1": "部门安全生产管理制度宣导.mp4", + "m2": "危险化学品安全操作规程.pdf", + "m3": "消防应急疏散演练视频.mp4" + }, + "flowTitle": "学习与考试流程", + "flowSteps": { + "company": "公司级安全教育", + "department": "部门级安全教育", + "team": "班组级安全教育", + "exam": "统一考试 ≥90分" + }, + "summaryTitle": "培训总结", + "summaryContent": { + "company": [ + "1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。", + "2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。", + "3企业安全生产规章制度、安全纪律和劳动纪律。", + "4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。", + "5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;", + "6安全生产正反方面的经验和教训,及重大事故安全案例教训。", + "7从业人员安全生产权利和义务;" + ], + "department": [ + "1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。", + "2公司、部门安全生产状况、管理制度规定和安全注意事项。", + "3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。", + "4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识", + "5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。", + "6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。", + "7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。", + "8有关事故案例。" + ], + "team": [ + "1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。", + "2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。", + "3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。", + "4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。", + "5本岗位发现紧急情况应采取的应救措施和报告办法。" + ] + } } }, "shippingOrderReview": { @@ -2679,7 +2752,8 @@ "inventory_source_unresolved": "Inventory source unresolved", "effective_reservation_missing": "A valid reservation number is missing", "unknown": "The system found an item that needs confirmation" - } + }, + "autoCreateBlocked": "Manual creation qualified, but auto-creation is not; after confirmation it will proceed manually." }, "inventoryCandidates": { "title": "Manual inventory selection", diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index 5af1f498..b25e9963 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -1,6 +1,21 @@ { "generic": "Request failed.", "codes": { + "ORDER_DELIVERY_REPLY.FORBIDDEN": "You do not have permission to view order delivery replies. Contact an administrator.", + "ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "Order delivery line not found or no longer in sync scope.", + "ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "Only platform administrators can grant permissions by department.", + "ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "Please specify the department to grant permissions to.", + "ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "Permission type must be manage or access.", + "ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "Batch reply requires at least one line and at most 200 per request.", + "ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "Batch notify requires at least one line and at most 200 per request.", + "ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "The salesperson has no linked account or WeCom binding; notification cannot be sent.", + "ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "WeCom notification failed. The line remains unlocked; please retry later.", + "ORDER_DELIVERY_REPLY.LINE_LOCKED": "The delivery schedule of this line is locked after notification and cannot be modified.", + "ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "You do not have manage permission for order delivery replies.", + "ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "Please provide at least one delivery batch.", + "ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "Too many batches for a single line.", + "ORDER_DELIVERY_REPLY.BATCH_INVALID": "Invalid batch format. Check the date, quantity, or remark.", + "ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "The total of all batch quantities must equal the order quantity. Please adjust and save again.", "SHIPPING.NOTICE_ODM_CHOICE_INVALID": "The selected ODM ID is not among the feasible candidates. Please choose again.", "SHIPPING.FULFILLMENT_POLICY_INVALID": "The fulfillment policy or field capability binding is invalid.", "SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "The fulfillment policy was not found.", diff --git a/frontend/src/locales/en/workspace.json b/frontend/src/locales/en/workspace.json index 2cab7882..fa73bcff 100644 --- a/frontend/src/locales/en/workspace.json +++ b/frontend/src/locales/en/workspace.json @@ -113,7 +113,8 @@ "contractPayment": "Contract Payment Alerts", "contractPaymentLedger": "Contract Ledger", "contractPaymentReview": "Contracts for Confirmation", - "contractPaymentWeeklyBatches": "Weekly Summary Batches" + "contractPaymentWeeklyBatches": "Weekly Summary Batches", + "orderDeliveryReply": "Order Delivery Reply" }, "kb": { "accessDenied": "Administrator access is required to open the knowledge base." @@ -202,7 +203,21 @@ "resend": "Resend to WeCom", "failedUnits": "Failed receipt units", "retry": "Retry with reason", - "retryReasonPrompt": "Enter the reason for retrying {target}" + "retryReasonPrompt": "Enter the reason for retrying {target}", + "batch": { + "selectAll": "全選目前頁通知單", + "selected": "已選 {count} 張", + "download": "批次下載 Excel", + "confirm": "批次確認已上傳", + "rpa": "批次啟動 RPA", + "downloadStarted": "已開始下載所選發貨通知 Excel", + "success": "{action}:已處理 {count} 張通知單", + "partialResult": "{action}:成功 {accepted} 張,阻斷 {blocked} 張,請查看重新整理後的通知狀態。", + "lines": "項次", + "parts": "料號", + "quantities": "本次發貨 / 可用庫存", + "uploadStatus": "貨代狀態" + } }, "shippingNotice": { "title": "Shipping Notice Tasks", @@ -968,5 +983,100 @@ "notifyExcel": "Excel", "downloadExcel": "Download Excel", "downloadExcelFailed": "Failed to download Excel" + }, + "orderDeliveryReply": { + "deepLinkLocated": "Located the order line from the notification: {order}:{item}", + "search": "Search", + "reset": "Reset", + "saving": "Saving…", + "syncNow": "Refresh now", + "syncing": "Syncing…", + "syncNever": "Never synced", + "syncAt": "Last sync: {time}", + "syncRunning": "Sync in progress…", + "syncFailedAt": "Last sync failed ({time}); list shows the last successful snapshot", + "syncDone": "Sync completed, {count} lines", + "syncSkipped": "A sync is already running; try again later", + "syncFailedTitle": "Sync failed; last snapshot kept", + "filterKeyword": "Keyword (order / product / customer / salesperson / replier)", + "filterKeywordPh": "Search by order no., part no., name, customer part no., customer, salesperson, or reply person", + "filterOrderDate": "Order Date", + "filterStatus": "Reply Status", + "statusAll": "All", + "statusReplied": "Replied", + "statusNotFully": "Not fully replied", + "statusNotReplied": "Not replied", + "statusPartial": "Partially replied", + "totalCount": "{count} product lines", + "selectAll": "Select all (this page)", + "selectedCount": "{count} lines selected", + "batchReply": "+ Batch reply", + "batchNotify": "Batch notify", + "toolbarHint": "Batch reply only saves; click \"Batch notify\" to send and lock.", + "colOrderLine": "Order : Item", + "colOrderDate": "Order Date", + "colCustomer": "Customer", + "colSalesperson": "Salesperson", + "colDept": "Department", + "colCustomerPo": "Customer PO", + "colPartNo": "Part No.", + "colPartName": "Part Name", + "colSpec": "Spec", + "colCustomerPartNo": "Customer Part No.", + "colAgreedDate": "Agreed Date", + "colUnit": "Unit", + "colQty": "Qty", + "colDelivered": "Delivered", + "colUndelivered": "Undelivered", + "colStatus": "Reply Status", + "colReply": "Delivery Reply", + "colNotify": "Notify", + "colReplyPerson": "Replied By", + "batchCount": "{count} batches", + "repliedOf": "replied {replied}/{remain}", + "overTag": "OVER", + "collapse": "Collapse ▲", + "expand": "+{count} more ▾", + "lockedTag": "Locked", + "replyAction": "Reply", + "editReplyAction": "Edit reply", + "notifiedTag": "Notified {name}", + "replyFirst": "Reply first", + "notifyAction": "Send notification", + "pendingNotify": "Recorded after notify", + "empty": "No matching order lines", + "pageInfo": "Page {page} / {pages}", + "modalTitleSingle": "Reply · {order} / item {item}", + "modalTitleBatch": "Batch reply ({count} lines)", + "quickDate": "Quick unified date", + "applyQuickDate": "Apply to all", + "modalHint": "Fill one date, or split into multiple date+qty batches; the batch quantity total must equal the order quantity.", + "itemLabel": "Item {item}", + "qtyPh": "Qty", + "remarkPh": "Remark (optional)", + "removeBatch": "Remove batch", + "addBatch": "+ Add batch (date + qty + remark)", + "saveReply": "Save reply", + "noValidBatches": "Fill a date and quantity for at least one line", + "saveSingleDone": "Batches saved (not notified; still editable)", + "saveBatchDone": "Saved batches for {ok} lines (not notified)", + "saveBatchPartial": "Saved: {ok} ok, {fail} failed: {detail}", + "saveFailedTitle": "Save failed", + "loadFailed": "Failed to load order lines", + "notifyConfirm": "Send to salesperson \"{salesperson}\"?\nYou have order {order}:{item} to fill/confirm/check delivery.\nThe schedule will be locked after sending.", + "notifyDone": "Notified and locked: {order}:{item}", + "notifyBatchConfirm": "Send notifications for {count} lines; successful lines will be locked. Continue?", + "notifyPartial": "Partial success: {ok} ok, {fail} failed, {skip} skipped. Failed: {detail}", + "notifyAllFailed": "All failed ({fail} lines): {detail}", + "notifyBatchDone": "Notified and locked {ok} lines, skipped {skip}", + "notifyFailedTitle": "Notification failed; line not locked", + "entryHint": "Query orders, reply delivery, notify sales", + "notNotified": "Not notified", + "orderQtyLabel": "Order qty: {qty} {unit}", + "batchMissingDate": "Batch {batches}: delivery date missing", + "batchMissingQty": "Batch {batches}: quantity missing", + "qtyTotalMismatchLine": "Batch total {total} must equal order quantity {qty}", + "saveBlocked": "These lines are incomplete and cannot be saved: {detail}", + "batchDuplicateDate": "Different batches of the same order line cannot have the same delivery date (duplicates: {dates})" } } diff --git a/frontend/src/locales/th/admin.json b/frontend/src/locales/th/admin.json index 74c16744..26e65c57 100644 --- a/frontend/src/locales/th/admin.json +++ b/frontend/src/locales/th/admin.json @@ -47,7 +47,8 @@ "platformApps": "แอปแพลตฟอร์ม", "procurementContract": "ตรวจสอบสัญญาจัดซื้อ", "trainingConfig": "การกำหนดค่าการฝึกอบรม", - "integrationConnector": "ตัวเชื่อมต่อระบบ" + "integrationConnector": "ตัวเชื่อมต่อระบบ", + "contractPayment": "合同付款预警" }, "shippingOrderExtractionRuns": { "eyebrow": "การวินิจฉัยการทำงานแบบอ่านอย่างเดียว", @@ -1139,7 +1140,12 @@ "status": "สถานะ", "enable": "เปิดใช้", "disable": "ปิดใช้", - "save": "บันทึก" + "save": "บันทึก", + "guideUsage": "资料用途", + "generalGuide": "通用指南", + "trainingVideo": "员工培训视频", + "trainingExamPdf": "员工培训试题 PDF", + "guideUsageHint": "培训工作区会优先读取“员工培训视频”和“员工培训试题 PDF”这两类资料。" }, "dash": { "activeAgents": "ตัวแทนที่ใช้งานอยู่", @@ -1208,6 +1214,10 @@ "trainingLeanTeamManage": "จัดการการฝึกอบรม Lean ระดับทีม", "contractPaymentAccess": "สิทธิ์แจ้งเตือนการชำระเงินตามสัญญา", "contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) ได้ การซิงก์ OA สแกนแจ้งเตือน และส่งสรุปรายสัปดาห์ใช้ได้เฉพาะผู้ดูแลระบบ", + "orderDeliveryReplyManage": "จัดการการตอบกลับกำหนดส่ง", + "orderDeliveryReplyManageHint": "เปิดสิทธิ์บันทึกงวดการส่ง ส่ง/แจ้งเตือนหลายรายการ และซิงค์ ERP ด้วยตนเอง (ฝ่ายวางแผนการผลิต)", + "orderDeliveryReplyAccess": "ดูการตอบกลับกำหนดส่ง", + "orderDeliveryReplyAccessHint": "เปิดสิทธิ์ดูอย่างอ่านอย่างเดียวสำหรับคำสั่งซื้อที่ซิงค์แล้ว (เจ้าหน้าที่ธุรกิจ)", "password": "รหัสผ่าน", "passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)", "noAgents": "ไม่มีตัวแทนที่ใช้ได้" @@ -1241,11 +1251,13 @@ "name": "ชื่อ", "code": "รหัส", "company": "บริษัท", - "actions": "การกระทำ" + "actions": "การกระทำ", + "members": "Members" }, "actions": { "edit": "แก้ไข", - "delete": "ลบ" + "delete": "ลบ", + "viewMembers": "View department members" }, "fields": { "name": "ชื่อ", @@ -1260,6 +1272,11 @@ "confirmDelete": "ลบแผนกนี้หรือไม่?", "msg": { "nameRequired": "กรุณากรอกชื่อแผนก" + }, + "members": { + "title": "{name} Members", + "count": "{count} members", + "empty": "No members" } }, "agent": { @@ -1792,12 +1809,13 @@ "firstLoginInputFields": "ฟิลด์ที่ใช้กรอกในครั้งแรก", "employeeIdSource": "แหล่งที่มาของรหัสพนักงาน", "mobileNormalize": "ปรับรูปแบบเบอร์โทรศัพท์", - "callbackToken": "Callback Token", + "callbackToken": "โทเคนคอลแบ็ก", "encodingAesKey": "EncodingAESKey", - "callbackUrl": "Callback URL", - "homepageUrl": "Application Homepage URL", - "trustedDomain": "Trusted Domain", - "publicBaseUrl": "Public HTTPS base" + "callbackUrl": "URL คอลแบ็ก", + "homepageUrl": "URL หน้าแรกแอป", + "trustedDomain": "โดเมนที่เชื่อถือ", + "publicBaseUrl": "Public HTTPS base", + "userId": "User ID (user_id)" }, "bindModes": { "match_rules": "จับคู่อัตโนมัติ", @@ -1910,8 +1928,23 @@ "filterName": "กรองตามชื่อ/ชื่อผู้ใช้", "filterDept": "กรองตามแผนก", "allRoles": "ทุกบทบาท", - "views": { "apps": "ตามแอปพลิเคชัน", "members": "ตามสมาชิก" }, - "appHeaders": { "app": "แอปพลิเคชัน", "type": "ประเภท", "authorized": "ผู้ได้รับอนุญาต", "actions": "การดำเนินการ", "viewMembers": "ดูสมาชิก", "accessHint": "เปิดสิทธิ์ของสมาชิก", "memberHint": "เพิ่มหรือลบสิทธิ์ของแอปนี้", "memberSearch": "ค้นหาชื่อ ชื่อผู้ใช้ รหัสพนักงาน หรือแผนก", "addMember": "มอบสิทธิ์", "removeMember": "ยกเลิกสิทธิ์", "noMembers": "ไม่พบสมาชิกที่ตรงกัน" }, + "views": { + "apps": "ตามแอปพลิเคชัน", + "members": "ตามสมาชิก" + }, + "appHeaders": { + "app": "แอปพลิเคชัน", + "type": "ประเภท", + "authorized": "ผู้ได้รับอนุญาต", + "actions": "การดำเนินการ", + "viewMembers": "ดูสมาชิก", + "accessHint": "เปิดสิทธิ์ของสมาชิก", + "memberHint": "เพิ่มหรือลบสิทธิ์ของแอปนี้", + "memberSearch": "ค้นหาชื่อ ชื่อผู้ใช้ รหัสพนักงาน หรือแผนก", + "addMember": "มอบสิทธิ์", + "removeMember": "ยกเลิกสิทธิ์", + "noMembers": "ไม่พบสมาชิกที่ตรงกัน" + }, "headers": { "user": "ผู้ใช้", "realName": "ชื่อจริง", @@ -2148,7 +2181,7 @@ "tokens_completion": "โทเค็นผลลัพธ์", "total_tokens": "โทเค็นรวม", "latency_ms": "ความหน่วง (ms)", - "latency": "ความหน่วง", + "latency": "เวลาแฝง (ms)", "cost": "ค่าใช้จ่าย", "ip": "IP", "user_agent": "User Agent", @@ -2164,13 +2197,15 @@ "reset_token_expiry": "เวลาหมดอายุโทเค็นรีเซ็ต", "risk_status": "สถานะความเสี่ยง", "risk_score": "คะแนนความเสี่ยง", - "latency": "เวลาแฝง (ms)", "is_empty_answer": "คำตอบว่าง", "is_system_failure": "ระบบล้มเหลว", "feedback_score": "คะแนน", "feedback_comment": "หมายเหตุคะแนน", "negative_feedback_count": "จำนวนข้อเสนอแนะเชิงลบ", - "actions": "การทำงาน" + "actions": "การทำงาน", + "feedback_module": "Feedback Module", + "feedback_type": "Feedback Type", + "source_page": "Source Page" }, "tables": { "users": "ผู้ใช้", @@ -2181,7 +2216,8 @@ "agents": "แอปปฏิบัติการ", "ops_overview": "ภาพรวมการดำเนินงาน", "issue_analysis": "การวิเคราะห์ปัญหา", - "usage_analysis": "วิเคราะห์การใช้งาน" + "usage_analysis": "วิเคราะห์การใช้งาน", + "permission_requests": "คำขอสิทธิ์" }, "usageIntro": "ดูแนวโน้มการเรียกใช้แอป AI ผู้ใช้ที่ใช้งาน แอปที่ใช้น้อย และช่วงพีคผิดปกติ", "usageTotalSessions": "จำนวนแชทรวม", @@ -2371,6 +2407,32 @@ "topApp": "แอปที่ควรปรับปรุง", "topAppHint": "สัดส่วนสัญญาณที่ต้องให้ความสนใจ {ratio}%" } + }, + "usageRangeLabel": "ช่วงเวลา", + "usageRanges": { + "7d": "7 วันล่าสุด", + "30d": "30 วันล่าสุด", + "90d": "3 เดือนล่าสุด", + "180d": "6 เดือนล่าสุด", + "365d": "12 เดือนล่าสุด" + }, + "feedbackValues": { + "types": { + "feature_suggestion": "Feature Suggestion", + "issue_feedback": "Issue Feedback", + "experience_optimization": "Experience Optimization" + }, + "modules": { + "knowledge_base": "Knowledge Base", + "general": "General", + "workflow": "Workflow", + "account_permission": "Account & Permissions" + }, + "pages": { + "workspace": "Workspace", + "chat": "Chat", + "unknown": "Unknown" + } } }, "batchEdit": { @@ -2517,7 +2579,35 @@ "voucherCheckNotifyMissing": "แจ้งเตือนเมื่อขาดเอกสาร", "voucherCheckNotifyMissingHint": "สวิตช์หลัก กำหนดผู้รับไฟล์ขาดในแชท 「ตรวจเอกสารบัญชี → ตั้งค่าการแจ้งเตือน」 ตามประเภทไฟล์ การเลือกคนด้านล่างใช้สำหรับแจ้งเตือนเมื่อล้มเหลวเท่านั้น", "voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว", - "voucherCheckNotifyFailureHint": "เมื่อล้มเหลวทางเทคนิคจะส่งให้ผู้ที่เลือกด้านล่าง" + "voucherCheckNotifyFailureHint": "เมื่อล้มเหลวทางเทคนิคจะส่งให้ผู้ที่เลือกด้านล่าง", + "editTitle": "Edit schedule", + "createTitle": "Add schedule", + "name": "Schedule name", + "namePlaceholder": "e.g. RoHS auto review schedule", + "owner": "Schedule owner", + "noUsers": "No users available", + "selectOwner": "Select an owner", + "faqHotAggregate": "FAQ hot aggregate", + "querying": "Querying...", + "testQuery": "Test query", + "expandConfig": "Expand config", + "collapseConfig": "Collapse config", + "dataSourceSection": "Data source config", + "waitSeconds": "Wait time (seconds)", + "noAgents": "No agents available", + "agentDisabled": "Disabled", + "minuteInterval": "Minute interval", + "minuteOfHour": "Minute of hour", + "weekday": "Weekday", + "notifyEnabled": "Enable notifications", + "selectNotifyUsers": "Select notification recipients...", + "enableOnCreate": "Enable after creation", + "cancel": "Cancel", + "saving": "Saving...", + "saveChanges": "Save changes", + "createSchedule": "Create schedule", + "dynamicParamsSearchPlaceholder": "ค้นหาตัวเลือก (ชื่อ/รหัส/แผนก)…", + "dynamicParamsSearchNoMatch": "ไม่มีตัวเลือกที่ตรง" }, "status": { "all": "ทุกสถานะ", @@ -2554,7 +2644,25 @@ "noKbGroupHint": "โปรดเปิดใช้การซิงค์คลังความรู้และเลือกกลุ่มในการแก้ไขตารางเวลาก่อน", "kbSyncNoStatus": "มีการขอเขียนคลังความรู้แล้ว แต่ไม่ได้รับสถานะซิงค์ โปรดตรวจการตั้งค่าคลังความรู้หรือบันทึก backend", "baseFetchSqlReadonly": "SQL ดึงข้อมูลพื้นฐาน (base_fetch_sql) — อ่านอย่างเดียว", - "limitRows": "จำกัดจำนวนแถว (limit)" + "limitRows": "จำกัดจำนวนแถว (limit)", + "title": "Test run — {name}", + "subtitle": "Edit WHERE clause, limit rows, run quickly and inspect each step", + "close": "Close", + "running": "Running...", + "start": "Start test run", + "waitingHint": "Dify calls may take a while, please wait...", + "total": "Total", + "success": "Success", + "failed": "Failed", + "skipped": "Skipped", + "limitSummary": "Limit {limit} rows | Dify Agent ID: {agentId}", + "noAgent": "None", + "stepLogs": "Step logs", + "viewSql": "View execution SQL", + "errors": "Errors ({count})", + "queryResult": "Query result", + "resultSummary": "{total} total, showing {showing}", + "viewGeneratedSql": "View generated SQL" }, "deleteDialogTitle": "ลบตารางเวลา", "excelExportFailedHint": "แหล่งสต็อกสำเร็จแล้ว แต่การส่งออก Excel ของตารางเวลาล้มเหลว", @@ -2572,8 +2680,19 @@ "receiptRawZip": "ใบรับดิบ", "columns": { "skippedCount": "ข้าม", - "skippedCountReceipt": "ไม่มีใบรับ/ข้าม", - "skippedCountInventory": "ไม่มีสต็อก/ข้าม" +"runNo": "Run ID", +"startedAt": "Started at", +"finishedAt": "Finished at", +"status": "Status", +"totalCount": "Processed", +"successCount": "Success", +"failedCount": "Failed", +"excelExportFailedHint": "Inventory sources succeeded, but schedule Excel export failed", +"wecomNotified": "WeCom notify", +"detail": "Detail", +"log": "Log", +"skippedCountReceipt": "ไม่มีใบรับ/ข้าม", +"skippedCountInventory": "ไม่มีสต็อก/ข้าม" }, "deleteConfirmMessage": "ยืนยันการลบตารางเวลา \"{name}\"?", "msg": { @@ -2587,8 +2706,9 @@ "runNowWaitTimeout": "รอการรันเสร็จสิ้นเกินเวลาที่กำหนด (ประมาณ 15 นาที) หยุดรีเฟรชอัตโนมัติแล้ว โปรดค้นหาบันทึกด้วยตนเอง", "downloadExcelFailed": "ดาวน์โหลด Excel ล้มเหลว", "downloadInventoryRawZipFailed": "ดาวน์โหลด ZIP สต็อกดิบล้มเหลว", - "downloadReceiptRawZipFailed": "ดาวน์โหลด ZIP ใบรับดิบล้มเหลว", - "deleteFailed": "ลบตารางเวลาล้มเหลว" +"deleteFailed": "ลบตารางเวลาล้มเหลว", +"testQueryFailed": "Test query failed", +"downloadReceiptRawZipFailed": "ดาวน์โหลด ZIP ใบรับดิบล้มเหลว" }, "difySnapshot": { "title": "สแนปช็อตการทำงาน Dify (ตรวจสอบ)", @@ -2600,6 +2720,65 @@ "notConfiguredUseDefault": "(ยังไม่ได้ตั้งค่า ใช้ prompt เริ่มต้นใน Dify workflow)", "notEnabledTest": "การทดสอบนี้ไม่ได้เปิดใช้ Dify", "notEnabledRun": "การรันนี้ไม่ได้เปิดใช้ Dify Agent" + }, + "overviewTitle": "Schedule Management Overview", + "workbenchTitle": "Schedule Management Workbench", + "overviewSubtitle": "Click a schedule card to open the workbench.", + "workbenchSubtitle": "Schedule list on the left, run records on the right.", + "refresh": "Refresh schedules", + "stats": { + "total": "Total schedules", + "enabled": "Enabled", + "disabled": "Disabled", + "running": "Running" + }, + "sectionOverview": "Schedule Management Overview", + "switchByCard": "Switch by card", + "addTitle": "Add schedule", + "addHint": "Click the button to fill in schedule fields in a dialog.", + "addButton": "Add schedule", + "emptyList": "No schedules yet. Create one first.", + "loading": "Loading...", + "enabled": "Enabled", + "disabled": "Disabled", + "scheduleNo": "No.", + "config": "Config", + "owner": "Owner", + "lastRun": "Last run", + "nextRun": "Next run", + "nextRunDisabled": "Disabled", + "nextRunPending": "Not computed (save or restart schedule)", + "noSelection": "No schedule selected", + "selectedHint": "Selected schedule · Last run {time}", + "runBatches": "Run batches", + "totalProcessed": "Total processed", + "totalSuccess": "Total success", + "totalFailed": "Total failed", + "listTitle": "Schedule list", + "recordsTitle": "{name} · Run records", + "recordsSubtitle": "Run record details are shown below.", + "noSelectionHint": "Select a schedule from the list on the left first.", + "filterStart": "Start", + "filterEnd": "End", + "query": "Search", + "reset": "Reset", + "queryingRuns": "Loading records...", + "noRunRecords": "No run records yet.", + "runLogs": "Run logs", + "stepsCount": "{count} steps", + "viewDetail": "View details", + "resizeColumn": "Drag to resize {label} column", + "notified": "Notified", + "notifyError": "Error", + "download": "Download", + "log": "Log", + "actions": { + "edit": "Edit", + "start": "Start", + "pause": "Pause", + "run": "Run", + "test": "Test", + "delete": "Delete" } }, "shippingIdentityRules": { @@ -4246,7 +4425,8 @@ "rejected": "ปฏิเสธแล้ว", "needs_review": "ต้องตรวจ" }, - "confirmRequiresNativePreview": "โหลดตัวอย่าง PDF ดั้งเดิมก่อนยืนยันการผูกภาพ" + "confirmRequiresNativePreview": "โหลดตัวอย่าง PDF ดั้งเดิมก่อนยืนยันการผูกภาพ", + "createBlockersTitle": "创建前阻断项" }, "xfaAutoMark": { "title": "คำแนะนำทำเครื่องหมายอัตโนมัติ", @@ -5288,7 +5468,17 @@ "trainingAgentRequired": "ไม่พบ Agent การฝึกอบรมพนักงาน จึงไม่สามารถสร้างทรัพยากรวิดีโอได้", "videoUploaded": "อัปโหลดวิดีโอการฝึกอบรมและเพิ่มในทรัพยากรการกำหนดค่าแล้ว", "videoUploadFailed": "อัปโหลดวิดีโอการฝึกอบรมไม่สำเร็จ" - } + }, + "eyebrow": "培训运营中心", + "pageHint": "配置变更将在保存后生效", + "footerHint": "所有配置项均支持保存后继续调整", + "stats": { + "total": "配置总数", + "published": "已发布", + "resources": "当前资料", + "levels": "已配置级别" + }, + "questionBankTitle": "入职培训题库" }, "integrationConnector": { "title": "ตัวเชื่อมต่อระบบ", diff --git a/frontend/src/locales/th/auth.json b/frontend/src/locales/th/auth.json index 7b05cc91..efa343ba 100644 --- a/frontend/src/locales/th/auth.json +++ b/frontend/src/locales/th/auth.json @@ -129,7 +129,17 @@ "notInScopeAction": "ให้ผู้ดูแลเพิ่มสมาชิกคนนี้หรือแผนกของสมาชิกเข้าไปในขอบเขตการมองเห็นของแอป WeCom", "retryLogin": "เริ่มต้นการเข้าสู่ระบบ WeCom ใหม่อีกครั้ง", "contactAdmin": "กรุณาติดต่อผู้ดูแลระบบเพื่อขอความช่วยเหลือ" - } + }, + "newPassword": "New Password", + "passwordResetSuccess": "Password reset successfully. Please login.", + "featuredAgents": "Featured AI Agents", + "pleaseLoginFirst": "Please login to access this agent.", + "userNotFound": "User not found", + "incorrectPassword": "Incorrect password", + "accountDisabled": "Account is disabled", + "dbConnectionFailed": "Database connection failed. Please check if the database service is running.", + "internalError": "Internal server error. Please try again later.", + "passwordResetEmailSent": "If the account exists, a reset link has been sent to your email." }, "landing": { "hero": { @@ -156,7 +166,8 @@ "realName": "ชื่อจริง", "employeeId": "รหัสพนักงาน", "phone": "หมายเลขโทรศัพท์" - } + }, + "emailRequired": "Email is required" }, "resetPassword": { "title": "รีเซ็ตรหัสผ่าน", diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index ea6e0c45..2996c1e7 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -1188,7 +1188,11 @@ "departmentLabel": "แผนก", "allStatuses": "ทุกสถานะ", "allDepartments": "ทุกแผนก", - "noLimit": "ไม่จำกัด" + "noLimit": "ไม่จำกัด", + "typeLabel": "培训类型", + "allTypes": "全部培训", + "typeOnboarding": "入职培训", + "typeSafety": "安全培训" }, "columns": { "joinDate": "วันที่เริ่มงาน", @@ -1543,6 +1547,75 @@ "พนักงานคนไหนยังไม่จบการอบรม?", "อยากดูสถิติคะแนนอบรมเดือนนี้" ] + }, + "safety": { + "tabs": { + "onboarding": "入职培训", + "safety": "安全培训" + }, + "progressTitle": "三级安全教育培训进度", + "progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。", + "steps": { + "company": "01 · 公司级", + "department": "02 · 部门级", + "team": "03 · 班组级", + "exam": "04 · 统一考试" + }, + "stepStatus": { + "watchVideo": "观看视频", + "examReq": "≥90 分及格", + "completed": "已完成", + "inProgress": "进行中", + "pending": "待学习", + "examPending": "需先学完三级" + }, + "videoPanelTitle": "{level} 第{step}步", + "videoPanelSubtitle": "观看安全教育培训视频", + "videoPanelPassLine": "及格线:≥ 90分方可进入考试", + "videoTitle": "部门安全生产管理制度宣导", + "videoDuration": "时长 35 分钟 · 已完成 12%", + "materialsTitle": "培训资料清单 (共 3 个文件/视频)", + "materials": { + "m1": "部门安全生产管理制度宣导.mp4", + "m2": "危险化学品安全操作规程.pdf", + "m3": "消防应急疏散演练视频.mp4" + }, + "flowTitle": "学习与考试流程", + "flowSteps": { + "company": "公司级安全教育", + "department": "部门级安全教育", + "team": "班组级安全教育", + "exam": "统一考试 ≥90分" + }, + "summaryTitle": "培训总结", + "summaryContent": { + "company": [ + "1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。", + "2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。", + "3企业安全生产规章制度、安全纪律和劳动纪律。", + "4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。", + "5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;", + "6安全生产正反方面的经验和教训,及重大事故安全案例教训。", + "7从业人员安全生产权利和义务;" + ], + "department": [ + "1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。", + "2公司、部门安全生产状况、管理制度规定和安全注意事项。", + "3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。", + "4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识", + "5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。", + "6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。", + "7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。", + "8有关事故案例。" + ], + "team": [ + "1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。", + "2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。", + "3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。", + "4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。", + "5本岗位发现紧急情况应采取的应救措施和报告办法。" + ] + } } }, "shippingOrderReview": { @@ -2679,7 +2752,8 @@ "inventory_source_unresolved": "ยังไม่ระบุแหล่งสต็อก", "effective_reservation_missing": "ไม่มีหมายเลขการจองที่ถูกต้อง", "unknown": "ระบบพบรายการที่ต้องยืนยันด้วยตนเอง" - } + }, + "autoCreateBlocked": "人工建单资格已通过,但自动建单资格未通过;确认后将由人工推进。" }, "inventoryCandidates": { "title": "เลือกแหล่งสต็อกด้วยตนเอง", diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index d2bf2b40..a8db3b22 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -1,6 +1,21 @@ { "generic": "คำขอล้มเหลว", "codes": { + "ORDER_DELIVERY_REPLY.FORBIDDEN": "คุณไม่มีสิทธิ์ดูการตอบกลับกำหนดส่งคำสั่งซื้อ โปรดติดต่อผู้ดูแลระบบ", + "ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "ไม่พบรายการคำสั่งซื้อ หรือไม่อยู่ในขอบเขตการซิงค์แล้ว", + "ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ออกสิทธิ์ตามแผนกได้", + "ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "โปรดระบุแผนกที่จะออกสิทธิ์", + "ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "ประเภทสิทธิ์ต้องเป็น manage หรือ access", + "ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "การตอบกลับหลายรายการต้องมีอย่างน้อยหนึ่งรายการ และไม่เกิน 200 รายการต่อครั้ง", + "ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "การแจ้งเตือนหลายรายการต้องมีอย่างน้อยหนึ่งรายการ และไม่เกิน 200 รายการต่อครั้ง", + "ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "พนักงานขายไม่ได้เชื่อมโยงบัญชีระบบหรือยังไม่ได้ผูก WeCom จึงส่งแจ้งเตือนไม่ได้", + "ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "ส่งแจ้งเตือน WeCom ไม่สำเร็จ รายการยังไม่ถูกล็อก โปรดลองอีกครั้ง", + "ORDER_DELIVERY_REPLY.LINE_LOCKED": "กำหนดส่งของรายการนี้ถูกล็อกหลังแจ้งแล้ว ไม่สามารถแก้ไขได้", + "ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการตอบกลับกำหนดส่งคำสั่งซื้อ", + "ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "กรุณาระบุอย่างน้อยหนึ่งงวดการส่งมอบ", + "ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "จำนวนงวดเกินขีดจำกัดของรายการเดียว", + "ORDER_DELIVERY_REPLY.BATCH_INVALID": "รูปแบบงวดไม่ถูกต้อง โปรดตรวจสอบวันที่ จำนวน หรือหมายเหตุ", + "ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "ผลรวมจำนวนทุกงวดต้องเท่ากับจำนวนของคำสั่งซื้อ โปรดปรับแล้วบันทึกอีกครั้ง", "SHIPPING.NOTICE_ODM_CHOICE_INVALID": "ODM ID ที่เลือกไม่อยู่ในตัวเลือกที่ทำได้ โปรดเลือกใหม่", "SHIPPING.FULFILLMENT_POLICY_INVALID": "นโยบายการปฏิบัติตามหรือการผูกความสามารถของฟิลด์ไม่ถูกต้อง", "SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "ไม่พบนโยบายการปฏิบัติตาม", diff --git a/frontend/src/locales/th/workspace.json b/frontend/src/locales/th/workspace.json index 8bae2250..2360cfc4 100644 --- a/frontend/src/locales/th/workspace.json +++ b/frontend/src/locales/th/workspace.json @@ -104,7 +104,8 @@ "contractPayment": "การแจ้งเตือนการชำระเงินตามสัญญา", "contractPaymentLedger": "ทะเบียนสัญญา", "contractPaymentReview": "สัญญาที่รอยืนยัน", - "contractPaymentWeeklyBatches": "ชุดสรุปรายสัปดาห์" + "contractPaymentWeeklyBatches": "ชุดสรุปรายสัปดาห์", + "orderDeliveryReply": "ตอบกลับกำหนดส่งคำสั่งซื้อ" }, "receiptReports": { "title": "ไฟล์รับสินค้า", @@ -904,5 +905,178 @@ "notifyExcel": "Excel", "downloadExcel": "ดาวน์โหลด Excel", "downloadExcelFailed": "ดาวน์โหลด Excel ไม่สำเร็จ" + }, + "orderDeliveryReply": { + "deepLinkLocated": "พบบรรทัดคำสั่งขายจากการแจ้งเตือนแล้ว: {order}:{item}", + "search": "ค้นหา", + "reset": "ล้าง", + "saving": "กำลังบันทึก…", + "syncNow": "รีเฟรชตอนนี้", + "syncing": "กำลังซิงค์…", + "syncNever": "ยังไม่เคยซิงค์", + "syncAt": "ซิงค์ล่าสุด: {time}", + "syncRunning": "กำลังซิงค์…", + "syncFailedAt": "ซิงค์ล่าสุดล้มเหลว ({time}) รายการเป็นภาพรวมครั้งล่าสุดที่สำเร็จ", + "syncDone": "ซิงค์สำเร็จ รวม {count} รายการ", + "syncSkipped": "มีการซิงค์กำลังทำงานอยู่ โปรดลองอีกครั้งภายหลัง", + "syncFailedTitle": "ซิงค์ล้มเหลว ยังคงภาพรวมเดิมไว้", + "filterKeyword": "คำค้นหา (คำสั่งซื้อ / ผลิตภัณฑ์ / ลูกค้า / พนักงานขาย / ผู้ตอบกำหนดส่ง)", + "filterKeywordPh": "ค้นหาด้วยเลขที่คำสั่งซื้อ รหัสสินค้า ชื่อสินค้า รหัสสินค้าลูกค้า ลูกค้า พนักงานขาย หรือผู้ตอบกำหนดส่งได้", + "filterOrderDate": "วันที่สั่งซื้อ", + "filterStatus": "สถานะการตอบกลับ", + "statusAll": "ทั้งหมด", + "statusReplied": "ตอบกลับแล้ว", + "statusNotFully": "ยังตอบไม่ครบ", + "statusNotReplied": "ยังไม่ตอบกลับ", + "statusPartial": "ตอบบางส่วน", + "totalCount": "รวม {count} รายการสินค้า", + "selectAll": "เลือกทั้งหมด (หน้านี้)", + "selectedCount": "เลือกแล้ว {count} รายการ", + "batchReply": "+ ตอบกลับหลายรายการ", + "batchNotify": "แจ้งเตือนหลายรายการ", + "toolbarHint": "การตอบกลับหลายรายการเป็นเพียงบันทึก ต้องกดแจ้งเตือนจึงจะส่งและล็อก", + "colOrderLine": "เลขที่ : รายการ", + "colOrderDate": "วันที่สั่งซื้อ", + "colCustomer": "ลูกค้า", + "colSalesperson": "พนักงานขาย", + "colDept": "แผนก", + "colCustomerPo": "PO ลูกค้า", + "colPartNo": "รหัสสินค้า", + "colPartName": "ชื่อสินค้า", + "colSpec": "สเปก", + "colCustomerPartNo": "รหัสสินค้าลูกค้า", + "colAgreedDate": "กำหนดส่งตามข้อตกลง", + "colUnit": "หน่วย", + "colQty": "จำนวน", + "colDelivered": "ส่งแล้ว", + "colUndelivered": "ยังไม่ส่ง", + "colStatus": "สถานะตอบกลับ", + "colReply": "การตอบกลับกำหนดส่ง", + "colNotify": "แจ้งเตือน", + "colReplyPerson": "ผู้ตอบกลับ", + "batchCount": "{count} งวด", + "repliedOf": "ตอบแล้ว {replied}/{remain}", + "overTag": "เกิน", + "collapse": "ย่อ ▲", + "expand": "+{count} งวด ▾", + "lockedTag": "ล็อกแล้ว", + "replyAction": "ตอบกลับ", + "editReplyAction": "แก้ไขการตอบกลับ", + "notifiedTag": "แจ้งแล้ว {name}", + "replyFirst": "กรุณาตอบกลับก่อน", + "notifyAction": "ส่งการแจ้งเตือน", + "pendingNotify": "บันทึกหลังแจ้งเตือน", + "empty": "ไม่พบรายการที่ตรงเงื่อนไข", + "pageInfo": "หน้า {page} / {pages}", + "modalTitleSingle": "ตอบกลับ · {order} / รายการ {item}", + "modalTitleBatch": "ตอบกลับหลายรายการ ({count} รายการ)", + "quickDate": "วันที่รวมด่วน", + "applyQuickDate": "ใช้กับทั้งหมด", + "modalHint": "กรอกวันที่เดียว หรือแยกเป็นหลายงวด (วันที่+จำนวน) ได้ โดยผลรวมจำนวนทุกงวดต้องเท่ากับจำนวนของคำสั่งซื้อ", + "itemLabel": "รายการ {item}", + "qtyPh": "จำนวน", + "remarkPh": "หมายเหตุ (ไม่บังคับ)", + "removeBatch": "ลบงวดนี้", + "addBatch": "+ เพิ่มงวด (วันที่ + จำนวน + หมายเหตุ)", + "saveReply": "บันทึกการตอบกลับ", + "noValidBatches": "กรุณากรอกวันที่และจำนวนอย่างน้อยหนึ่งรายการ", + "saveSingleDone": "บันทึกงวดแล้ว (ยังไม่แจ้งเตือน แก้ไขได้)", + "saveBatchDone": "บันทึก {ok} รายการแล้ว (ยังไม่แจ้งเตือน)", + "saveBatchPartial": "บันทึกแล้ว: สำเร็จ {ok} ล้มเหลว {fail}: {detail}", + "saveFailedTitle": "บันทึกไม่สำเร็จ", + "loadFailed": "โหลดรายการไม่สำเร็จ", + "notifyConfirm": "ยืนยันส่งถึงพนักงานขาย \"{salesperson}\"?\nคุณมีคำสั่งซื้อ {order}:{item} ที่ต้องกรอก/ยืนยัน/ตรวจสอบกำหนดส่ง\nหลังส่งแล้วกำหนดส่งจะถูกล็อก", + "notifyDone": "แจ้งเตือนและล็อกแล้ว: {order}:{item}", + "notifyBatchConfirm": "จะส่งแจ้งเตือน {count} รายการ รายการที่ส่งสำเร็จจะถูกล็อก ดำเนินการต่อ?", + "notifyPartial": "สำเร็จบางส่วน: สำเร็จ {ok} ล้มเหลว {fail} ข้าม {skip} รายการ ที่ล้มเหลว: {detail}", + "notifyAllFailed": "ล้มเหลวทั้งหมด ({fail} รายการ): {detail}", + "notifyBatchDone": "แจ้งเตือนและล็อก {ok} รายการ ข้าม {skip} รายการ", + "notifyFailedTitle": "ส่งแจ้งเตือนไม่สำเร็จ รายการยังไม่ถูกล็อก", + "entryHint": "ค้นคำสั่งซื้อ ตอบกำหนดส่ง แจ้งพนักงานขาย", + "notNotified": "ยังไม่แจ้ง", + "orderQtyLabel": "จำนวนคำสั่งซื้อ: {qty} {unit}", + "batchMissingDate": "งวดที่ {batches}: ยังไม่ได้กรอกวันที่", + "batchMissingQty": "งวดที่ {batches}: ยังไม่ได้กรอกจำนวน", + "qtyTotalMismatchLine": "ผลรวมทุกงวด {total} ต้องเท่ากับจำนวนคำสั่งซื้อ {qty}", + "saveBlocked": "รายการต่อไปนี้กรอกไม่ครบถ้วน จึงบันทึกไม่ได้: {detail}", + "batchDuplicateDate": "งวดต่างๆ ของคำสั่งซื้อ:รายการเดียวกันต้องไม่มีวันที่กำหนดส่งเดียวกัน (ซ้ำ: {dates})" + }, + "lang": { + "zhCN": "Simplified Chinese", + "zhTW": "Traditional Chinese" + }, + "schedule": { + "title": "Schedule Runs", + "refresh": "Refresh", + "batch": { + "selectAll": "Select all notices on this page", + "selected": "{count} selected", + "download": "Download Excel", + "confirm": "Confirm uploaded", + "rpa": "Start RPA upload", + "downloadStarted": "Downloading the selected shipping-notice Excel files.", + "success": "{action}: {count} notice(s) processed.", + "partialResult": "{action}: {accepted} accepted and {blocked} blocked. Refresh to see the latest notice status.", + "lines": "Lines", + "parts": "Parts", + "quantities": "Shipment / available", + "uploadStatus": "Freight status" + }, + "uploadNotices": "Upload shipping notices", + "search": "Search", + "reset": "Reset", + "loading": "Loading...", + "empty": "No schedule runs", + "download": "Download", + "noPendingData": "No pending data", + "filters": { + "name": "Schedule Name", + "namePlaceholder": "Enter schedule name", + "start": "Start Time", + "end": "End Time", + "status": "Status" + }, + "columns": { + "name": "Schedule Name", + "runNo": "Run No.", + "triggerType": "Trigger", + "start": "Start Time", + "end": "End Time", + "duration": "Duration", + "status": "Status", + "total": "Total", + "success": "Success", + "failed": "Failed", + "detail": "Detail" + }, + "trigger": { + "manual": "Manual", + "test": "Test", + "timed": "Scheduled" + }, + "status": { + "all": "All", + "success": "Success", + "partialFailed": "Partial Success", + "failed": "Failed", + "running": "Running", + "queued": "Queued" + }, + "msg": { + "downloadExcelFailed": "Failed to download Excel" + } + }, + "profile": { + "msg": { + "loadFailed": "Failed to load profile", + "saveFailed": "Failed to save profile", + "saved": "Profile saved", + "changePasswordFailed": "Failed to change password" + } + }, + "msg": { + "casdoorNotMatchedContactAdmin": "Casdoor login succeeded, but no local account matched. Please contact the administrator.", + "casdoorNotMatchedNeedLocalUser": "Casdoor login succeeded, but no local account matched. Ask the administrator to create a local user with the same username or email.", + "localAccountDisabled": "This local account is disabled. Please contact the administrator." } } diff --git a/frontend/src/locales/zh-CN/admin.json b/frontend/src/locales/zh-CN/admin.json index 431c6034..c953ffba 100644 --- a/frontend/src/locales/zh-CN/admin.json +++ b/frontend/src/locales/zh-CN/admin.json @@ -1342,6 +1342,10 @@ "trainingLeanTeamManage": "精益培训班组管理", "contractPaymentAccess": "合同付款预警访问", "contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总)。同步 OA、扫描预警和发送预警仅管理员可用。", + "orderDeliveryReplyManage": "订单交期回复操作", + "orderDeliveryReplyManageHint": "勾选后可回复交期批次、发送/批量通知业务员并手动同步 ERP 订单(生管)。", + "orderDeliveryReplyAccess": "订单交期回复查看", + "orderDeliveryReplyAccessHint": "勾选后可只读查看已同步订单与回复结果(业务人员);回复与通知需另勾「操作」权限。", "password": "密码", "passwordHint": "(留空表示不修改)", "noAgents": "暂无可用应用" @@ -1383,7 +1387,11 @@ "delete": "删除", "viewMembers": "查看部门员工" }, - "members": { "title": "{name}员工", "count": "共 {count} 人", "empty": "暂无员工" }, + "members": { + "title": "{name}员工", + "count": "共 {count} 人", + "empty": "暂无员工" + }, "fields": { "name": "名称", "namePlaceholder": "例如:信息技术部", @@ -1929,7 +1937,13 @@ "firstLoginInputFields": "首次登录可输入字段", "employeeIdSource": "工号来源字段", "mobileNormalize": "手机号归一化", - "publicBaseUrl": "外网 HTTPS 基地址" + "publicBaseUrl": "外网 HTTPS 基地址", + "callbackToken": "回调Token", + "encodingAesKey": "EncodingAESKey", + "callbackUrl": "回调URL", + "homepageUrl": "应用主页URL", + "trustedDomain": "可信域名", + "userId": "用户 ID(user_id)" }, "bindModes": { "match_rules": "按规则自动匹配", @@ -2042,8 +2056,23 @@ "filterName": "筛选 姓名/用户名", "filterDept": "筛选 部门", "allRoles": "所有角色", - "views": { "apps": "按应用查看", "members": "按成员查看" }, - "appHeaders": { "app": "应用", "type": "类型", "authorized": "已授权人数", "actions": "操作", "viewMembers": "查看成员", "accessHint": "点击查看成员权限", "memberHint": "可添加或取消此应用的访问权限", "memberSearch": "搜索姓名、用户名、工号或部门", "addMember": "添加权限", "removeMember": "取消权限", "noMembers": "没有匹配的人员" }, + "views": { + "apps": "按应用查看", + "members": "按成员查看" + }, + "appHeaders": { + "app": "应用", + "type": "类型", + "authorized": "已授权人数", + "actions": "操作", + "viewMembers": "查看成员", + "accessHint": "点击查看成员权限", + "memberHint": "可添加或取消此应用的访问权限", + "memberSearch": "搜索姓名、用户名、工号或部门", + "addMember": "添加权限", + "removeMember": "取消权限", + "noMembers": "没有匹配的人员" + }, "headers": { "user": "用户", "realName": "真实姓名", @@ -2280,7 +2309,7 @@ "tokens_completion": "补全 Token", "total_tokens": "总 Token", "latency_ms": "延迟(毫秒)", - "latency": "延迟", + "latency": "耗时(毫秒)", "cost": "费用", "ip": "IP", "user_agent": "用户代理", @@ -2296,13 +2325,15 @@ "reset_token_expiry": "重置令牌过期时间", "risk_status": "风险状态", "risk_score": "风险分", - "latency": "耗时(毫秒)", "is_empty_answer": "空回答", "is_system_failure": "系统失败", "feedback_score": "评分", "feedback_comment": "评分备注", "negative_feedback_count": "负面反馈数", - "actions": "操作" + "actions": "操作", + "feedback_module": "反馈模块", + "feedback_type": "反馈类型", + "source_page": "来源页面" }, "tables": { "users": "用户", @@ -2313,7 +2344,8 @@ "agents": "应用运营", "ops_overview": "运营总览", "issue_analysis": "问题分析", - "usage_analysis": "使用分析" + "usage_analysis": "使用分析", + "permission_requests": "权限申请" }, "usageIntro": "查看 AI 应用调用趋势、活跃用户、低使用应用与异常高峰。", "usageTotalSessions": "对话总量", @@ -2503,6 +2535,32 @@ "topApp": "优先优化应用", "topAppHint": "需要关注信号占比 {ratio}%" } + }, + "usageRangeLabel": "统计范围", + "usageRanges": { + "7d": "近一周", + "30d": "近一月", + "90d": "近三月", + "180d": "近半年", + "365d": "近一年" + }, + "feedbackValues": { + "types": { + "feature_suggestion": "功能建议", + "issue_feedback": "问题反馈", + "experience_optimization": "体验优化" + }, + "modules": { + "knowledge_base": "知识库", + "general": "通用", + "workflow": "工作流", + "account_permission": "账号与权限" + }, + "pages": { + "workspace": "工作台", + "chat": "聊天", + "unknown": "未知" + } } }, "batchEdit": { @@ -2762,7 +2820,9 @@ "voucherCheckNotifyMissing": "缺资料通知", "voucherCheckNotifyMissingHint": "总开关。缺件接收人请到 Chat「立账凭证 → 通知配置」按文件类型设置;排程选人只用于技术失败告警。", "voucherCheckNotifyFailure": "失败告警", - "voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。" + "voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。", + "dynamicParamsSearchPlaceholder": "搜索选项(姓名/工号/部门)…", + "dynamicParamsSearchNoMatch": "没有匹配的选项" }, "testRun": { "title": "测试执行 — {name}", @@ -2846,7 +2906,8 @@ "notConfiguredUseDefault": "(未配置,使用 Dify 编排内默认提示词)", "notEnabledTest": "本次测试未启用 Dify", "notEnabledRun": "本次执行未启用 Dify Agent" - } + }, + "excelExportFailedHint": "库存来源已成功,但排程 Excel 生成失败" }, "shippingIdentityRules": { "eyebrow": "货代客户治理", diff --git a/frontend/src/locales/zh-CN/auth.json b/frontend/src/locales/zh-CN/auth.json index 80602878..c4e28d7c 100644 --- a/frontend/src/locales/zh-CN/auth.json +++ b/frontend/src/locales/zh-CN/auth.json @@ -1,188 +1,189 @@ { - "title": "企业级 AI 网关", - "login": { - "username": "用户名", - "password": "密码", - "submit": "登录", - "registerLink": "点击注册", - "noAccount": "没有账号?", - "subtitle": "欢迎回来!请输入您的详细信息。", - "placeholder": { - "username": "请输入用户名", - "password": "密码" + "title": "企业级 AI 网关", + "login": { + "username": "用户名", + "password": "密码", + "submit": "登录", + "registerLink": "点击注册", + "noAccount": "没有账号?", + "subtitle": "欢迎回来!请输入您的详细信息。", + "placeholder": { + "username": "请输入用户名", + "password": "密码" + }, + "failed": "登录失败", + "inputError": "请输入用户名和密码", + "usernameRequired": "用户名不能为空", + "usernameRequiredHint": "请输入用户名", + "passwordRequired": "密码不能为空", + "passwordRequiredHint": "请输入密码", + "loginRequired": "请先登录", + "sessionExpired": "登录已失效", + "sessionExpiredHint": "请重新登录后继续使用。", + "requestFailed": "登录请求失败", + "forgotPassword": "忘记密码?", + "newPassword": "新密码", + "passwordResetSuccess": "密码重置成功,请重新登录。", + "featuredAgents": "推荐 AI 应用", + "pleaseLoginFirst": "请先登录以使用此应用。", + "userNotFound": "用户不存在", + "incorrectPassword": "密码错误", + "accountDisabled": "账号已禁用", + "dbConnectionFailed": "数据库连接失败,请检查数据库服务是否运行。", + "internalError": "服务器内部错误,请稍后重试。", + "rememberMe": "记住我", + "forgotPasswordDesc": "输入工号和用户名,重置链接将发送到您的企业微信", + "findPassword": "找回密码", + "employeeIdRequired": "请输入工号", + "passwordResetWecomSent": "若账号存在且已绑定企业微信,重置链接已发送到您的企业微信。", + "passwordResetEmailSent": "若账号存在,重置链接已发送到您的邮箱。", + "passwordResetRequestFailed": "请求密码重置失败", + "passwordResetRateLimited": "操作过于频繁,请 {minutes} 分钟后再试", + "announcements": "公告", + "casdoorLogin": "Casdoor 登录", + "casdoorErrors": { + "invalidCredentials": "用户名或密码错误", + "codeExpired": "登录会话已过期,请重新登录", + "stateExpired": "登录会话已过期,请重试", + "accessDenied": "登录已取消或被拒绝", + "configError": "认证服务暂不可用,请联系管理员", + "authFailed": "登录失败,请稍后重试", + "passwordPolicy": "新密码不符合安全要求", + "setPasswordFailed": "修改密码失败,请稍后重试或联系管理员", + "incorrectCurrentPassword": "原:当前密码不正确,新:您输入的原密码有误,请重新输入", + "passwordUnchanged": "新密码不能与当前密码相同", + "userNotInIdp": "您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。" + }, + "casdoorDialogTitles": { + "userNotFound": "未匹配到本地账号", + "userNotInIdp": "认证系统中无此账号", + "accountDisabled": "账号已禁用", + "sessionExpired": "登录会话已过期", + "configError": "认证服务异常", + "accessDenied": "登录未完成", + "loginFailed": "登录失败" + }, + "casdoorDialogDetails": { + "contactAdmin": "若问题持续出现,请联系管理员处理。", + "retryLogin": "请关闭此窗口后重新登录。" + }, + "wecomLogin": "企业微信登录", + "wecomComingSoon": "企业微信登录功能正在开发中,敬请期待", + "wecomConnecting": "正在连接企业微信...", + "wecomStartFailed": "启动企业微信登录失败", + "wecomInvalidState": "企业微信登录状态无效", + "wecomStateExpired": "企业微信登录会话已过期,请重试。", + "wecomBindRequired": "当前企业微信账号未绑定本地用户,请联系管理员。", + "wecomAccountDisabled": "账号已禁用,请联系管理员。", + "wecomLoginFailed": "企业微信登录失败", + "wecomMatchAmbiguous": "该企业微信账号匹配到多个本地账号,请联系管理员处理。", + "wecomMatchAttrMissing": "企业微信缺少必要匹配字段,请联系管理员。", + "wecomRetry": "重新发起企业微信登录", + "wecomTechnicalInfo": "技术信息:{detail}", + "wecomBindPromptTitle": "首次登录请校验并绑定本站账号", + "wecomBindPromptDesc": "当前企业微信身份为 {name}。请输入一个允许的字段,用来绑定你已有的本站账号。", + "wecomBindField": "校验字段", + "wecomBindValue": "校验值", + "wecomBindValuePlaceholder": "请输入你的{field}", + "wecomBindPromptHint": "输入值必须和本站已有账号完全匹配。绑定成功后,当前企业微信账号会自动写回该用户表。", + "wecomBindSubmit": "校验并登录", + "wecomBindInputNotFound": "没有找到与你输入内容匹配的本站账号。", + "wecomBindInputAmbiguous": "你输入的内容匹配到了多个本站账号,请联系管理员处理。", + "wecomBindSessionExpired": "本次企业微信绑定会话已过期,请重新发起企业微信登录。", + "wecomBindConflict": "当前企业微信账号已绑定到其他本站账号。", + "wecomBindFieldNotAllowed": "当前选择的校验字段不被允许。", + "wecomBindValueRequired": "请输入校验值。", + "wecomFieldLabels": { + "employee_id": "工号", + "mobile": "手机号", + "email": "邮箱", + "match_rules": "匹配规则" + }, + "wecomRuleJoin": { + "and": "且", + "or": "或" + }, + "wecomFieldGuides": { + "employee_id": "请管理员检查“工号来源字段”配置,并确认该成员在企业微信里能返回工号。", + "mobile": "请管理员在企业微信通讯录中补齐该成员手机号,或调整匹配规则,不再强依赖手机号。", + "email": "请管理员在企业微信通讯录中维护该成员邮箱,或调整匹配规则。", + "default": "请管理员检查企业微信通讯录字段是否齐全,以及当前匹配规则是否合理。" + }, + "wecomDialogTitles": { + "matchAttrMissing": "企业微信资料不完整", + "matchAmbiguous": "匹配到了多个本站账号", + "bindRequired": "未找到可绑定的本站账号", + "bindInputRequired": "首次绑定前需要人工校验", + "bindConflict": "该企业微信账号已绑定到别的账号", + "notInScope": "当前成员未被该应用授权", + "stateExpired": "企业微信登录已过期", + "accountDisabled": "本地账号已被禁用", + "loginFailed": "企业微信登录失败" + }, + "wecomDialogSummaries": { + "matchAttrMissing": "企业微信没有返回“{field}”,所以系统无法按当前规则自动匹配你的本站账号。", + "matchAmbiguous": "当前企业微信账号匹配到了多个本站账号,系统无法自动判断该登录哪一个。", + "matchAmbiguousWithCount": "当前企业微信账号匹配到了 {count} 个本站账号,系统无法自动判断该登录哪一个。", + "bindRequired": "企业微信侧认证已经成功,但本站没有找到符合当前规则的账号。", + "bindInputRequired": "企业微信侧认证已经成功,请先输入一个本站字段完成首次绑定。", + "bindConflict": "当前企业微信账号已经绑定到其他本站账号。", + "notInScope": "当前成员不在企业微信应用可见范围内,或不是本企业成员。" + }, + "wecomDialogDetails": { + "currentRules": "当前匹配规则:{rules}", + "bindFallback": "如果你已经有本站账号,可以请管理员先手动绑定当前企业微信账号。", + "ambiguousAction": "请管理员清理重复的工号、手机号或邮箱数据,或者收紧匹配规则。", + "bindRequiredAction": "请管理员先创建或绑定本站账号,或者开启自动创建用户。", + "bindInputRequiredAction": "下一步请输入你的工号、手机号或邮箱中的一个,校验成功后就会把当前企业微信账号绑定到已有本站账号。", + "bindConflictAction": "请管理员先解除旧绑定,再重新绑定当前企业微信账号。", + "notInScopeAction": "请管理员到企业微信后台,把该成员或其所在部门加入该应用的可见范围。", + "retryLogin": "请重新发起一次企业微信登录。", + "contactAdmin": "如需帮助,请联系管理员。" + } }, - "failed": "登录失败", - "inputError": "请输入用户名和密码", - "usernameRequired": "用户名不能为空", - "usernameRequiredHint": "请输入用户名", - "passwordRequired": "密码不能为空", - "passwordRequiredHint": "请输入密码", - "loginRequired": "请先登录", - "sessionExpired": "登录已失效", - "sessionExpiredHint": "请重新登录后继续使用。", - "requestFailed": "登录请求失败", - "forgotPassword": "忘记密码?", - "newPassword": "新密码", - "passwordResetSuccess": "密码重置成功,请重新登录。", - "featuredAgents": "推荐 AI 应用", - "pleaseLoginFirst": "请先登录以使用此应用。", - "userNotFound": "用户不存在", - "incorrectPassword": "密码错误", - "accountDisabled": "账号已禁用", - "dbConnectionFailed": "数据库连接失败,请检查数据库服务是否运行。", - "internalError": "服务器内部错误,请稍后重试。", - "rememberMe": "记住我", - "forgotPasswordDesc": "输入工号和用户名,重置链接将发送到您的企业微信", - "findPassword": "找回密码", - "employeeIdRequired": "请输入工号", - "passwordResetWecomSent": "若账号存在且已绑定企业微信,重置链接已发送到您的企业微信。", - "passwordResetEmailSent": "若账号存在,重置链接已发送到您的邮箱。", - "passwordResetRequestFailed": "请求密码重置失败", - "passwordResetRateLimited": "操作过于频繁,请 {minutes} 分钟后再试", - "announcements": "公告", - "casdoorLogin": "Casdoor 登录", - "casdoorErrors": { - "invalidCredentials": "用户名或密码错误", - "codeExpired": "登录会话已过期,请重新登录", - "stateExpired": "登录会话已过期,请重试", - "accessDenied": "登录已取消或被拒绝", - "configError": "认证服务暂不可用,请联系管理员", - "authFailed": "登录失败,请稍后重试", - "passwordPolicy": "新密码不符合安全要求", - "setPasswordFailed": "修改密码失败,请稍后重试或联系管理员", - "incorrectCurrentPassword": "原:当前密码不正确,新:您输入的原密码有误,请重新输入", - "passwordUnchanged": "新密码不能与当前密码相同", - "userNotInIdp": "您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。" + "landing": { + "hero": { + "prefix": "和信精密", + "highlight": "AI智能体 应用平台", + "subtitle": "AI的世界,期望让你开心工作,快乐生活。" + }, + "agent": { + "role": "AI 助手" + } }, - "casdoorDialogTitles": { - "userNotFound": "未匹配到本地账号", - "userNotInIdp": "认证系统中无此账号", - "accountDisabled": "账号已禁用", - "sessionExpired": "登录会话已过期", - "configError": "认证服务异常", - "accessDenied": "登录未完成", - "loginFailed": "登录失败" + "register": { + "title": "注册新账号", + "username": "用户名", + "password": "密码", + "email": "邮箱", + "cancel": "取消", + "submit": "提交注册", + "success": "注册申请已提交,请等待管理员审批", + "failed": "注册失败", + "inputError": "请输入用户名和密码", + "requestFailed": "请求失败", + "fields": { + "realName": "真实姓名", + "employeeId": "工号", + "phone": "手机号" + }, + "emailRequired": "请输入邮箱" }, - "casdoorDialogDetails": { - "contactAdmin": "若问题持续出现,请联系管理员处理。", - "retryLogin": "请关闭此窗口后重新登录。" - }, - "wecomLogin": "企业微信登录", - "wecomComingSoon": "企业微信登录功能正在开发中,敬请期待", - "wecomConnecting": "正在连接企业微信...", - "wecomStartFailed": "启动企业微信登录失败", - "wecomInvalidState": "企业微信登录状态无效", - "wecomStateExpired": "企业微信登录会话已过期,请重试。", - "wecomBindRequired": "当前企业微信账号未绑定本地用户,请联系管理员。", - "wecomAccountDisabled": "账号已禁用,请联系管理员。", - "wecomLoginFailed": "企业微信登录失败", - "wecomMatchAmbiguous": "该企业微信账号匹配到多个本地账号,请联系管理员处理。", - "wecomMatchAttrMissing": "企业微信缺少必要匹配字段,请联系管理员。", - "wecomRetry": "重新发起企业微信登录", - "wecomTechnicalInfo": "技术信息:{detail}", - "wecomBindPromptTitle": "首次登录请校验并绑定本站账号", - "wecomBindPromptDesc": "当前企业微信身份为 {name}。请输入一个允许的字段,用来绑定你已有的本站账号。", - "wecomBindField": "校验字段", - "wecomBindValue": "校验值", - "wecomBindValuePlaceholder": "请输入你的{field}", - "wecomBindPromptHint": "输入值必须和本站已有账号完全匹配。绑定成功后,当前企业微信账号会自动写回该用户表。", - "wecomBindSubmit": "校验并登录", - "wecomBindInputNotFound": "没有找到与你输入内容匹配的本站账号。", - "wecomBindInputAmbiguous": "你输入的内容匹配到了多个本站账号,请联系管理员处理。", - "wecomBindSessionExpired": "本次企业微信绑定会话已过期,请重新发起企业微信登录。", - "wecomBindConflict": "当前企业微信账号已绑定到其他本站账号。", - "wecomBindFieldNotAllowed": "当前选择的校验字段不被允许。", - "wecomBindValueRequired": "请输入校验值。", - "wecomFieldLabels": { - "employee_id": "工号", - "mobile": "手机号", - "email": "邮箱", - "match_rules": "匹配规则" - }, - "wecomRuleJoin": { - "and": "且", - "or": "或" - }, - "wecomFieldGuides": { - "employee_id": "请管理员检查“工号来源字段”配置,并确认该成员在企业微信里能返回工号。", - "mobile": "请管理员在企业微信通讯录中补齐该成员手机号,或调整匹配规则,不再强依赖手机号。", - "email": "请管理员在企业微信通讯录中维护该成员邮箱,或调整匹配规则。", - "default": "请管理员检查企业微信通讯录字段是否齐全,以及当前匹配规则是否合理。" - }, - "wecomDialogTitles": { - "matchAttrMissing": "企业微信资料不完整", - "matchAmbiguous": "匹配到了多个本站账号", - "bindRequired": "未找到可绑定的本站账号", - "bindInputRequired": "首次绑定前需要人工校验", - "bindConflict": "该企业微信账号已绑定到别的账号", - "notInScope": "当前成员未被该应用授权", - "stateExpired": "企业微信登录已过期", - "accountDisabled": "本地账号已被禁用", - "loginFailed": "企业微信登录失败" - }, - "wecomDialogSummaries": { - "matchAttrMissing": "企业微信没有返回“{field}”,所以系统无法按当前规则自动匹配你的本站账号。", - "matchAmbiguous": "当前企业微信账号匹配到了多个本站账号,系统无法自动判断该登录哪一个。", - "matchAmbiguousWithCount": "当前企业微信账号匹配到了 {count} 个本站账号,系统无法自动判断该登录哪一个。", - "bindRequired": "企业微信侧认证已经成功,但本站没有找到符合当前规则的账号。", - "bindInputRequired": "企业微信侧认证已经成功,请先输入一个本站字段完成首次绑定。", - "bindConflict": "当前企业微信账号已经绑定到其他本站账号。", - "notInScope": "当前成员不在企业微信应用可见范围内,或不是本企业成员。" - }, - "wecomDialogDetails": { - "currentRules": "当前匹配规则:{rules}", - "bindFallback": "如果你已经有本站账号,可以请管理员先手动绑定当前企业微信账号。", - "ambiguousAction": "请管理员清理重复的工号、手机号或邮箱数据,或者收紧匹配规则。", - "bindRequiredAction": "请管理员先创建或绑定本站账号,或者开启自动创建用户。", - "bindInputRequiredAction": "下一步请输入你的工号、手机号或邮箱中的一个,校验成功后就会把当前企业微信账号绑定到已有本站账号。", - "bindConflictAction": "请管理员先解除旧绑定,再重新绑定当前企业微信账号。", - "notInScopeAction": "请管理员到企业微信后台,把该成员或其所在部门加入该应用的可见范围。", - "retryLogin": "请重新发起一次企业微信登录。", - "contactAdmin": "如需帮助,请联系管理员。" + "resetPassword": { + "title": "重置密码", + "desc": "请在下方输入新密码", + "newPassword": "新密码", + "confirmPassword": "确认密码", + "newPasswordPlaceholder": "请输入新密码", + "confirmPasswordPlaceholder": "请再次输入新密码", + "submit": "重置密码", + "submitting": "正在重置...", + "backToLogin": "返回登录", + "fillAllFields": "请填写所有字段", + "passwordMismatch": "两次输入的密码不一致", + "successRedirect": "密码重置成功,即将跳转到登录页...", + "failed": "密码重置失败", + "invalidLink": "重置链接无效或缺少 token,请重新申请找回密码", + "tokenInvalid": "链接已失效或已过期(可能已使用过或重新申请过),请回到登录页重新发起找回密码" } - }, - "landing": { - "hero": { - "prefix": "和信精密", - "highlight": "AI智能体 应用平台", - "subtitle": "AI的世界,期望让你开心工作,快乐生活。" - }, - "agent": { - "role": "AI 助手" - } - }, - "register": { - "title": "注册新账号", - "username": "用户名", - "password": "密码", - "email": "邮箱", - "cancel": "取消", - "submit": "提交注册", - "success": "注册申请已提交,请等待管理员审批", - "failed": "注册失败", - "inputError": "请输入用户名和密码", - "requestFailed": "请求失败", - "fields": { - "realName": "真实姓名", - "employeeId": "工号", - "phone": "手机号" - } - }, - "resetPassword": { - "title": "重置密码", - "desc": "请在下方输入新密码", - "newPassword": "新密码", - "confirmPassword": "确认密码", - "newPasswordPlaceholder": "请输入新密码", - "confirmPasswordPlaceholder": "请再次输入新密码", - "submit": "重置密码", - "submitting": "正在重置...", - "backToLogin": "返回登录", - "fillAllFields": "请填写所有字段", - "passwordMismatch": "两次输入的密码不一致", - "successRedirect": "密码重置成功,即将跳转到登录页...", - "failed": "密码重置失败", - "invalidLink": "重置链接无效或缺少 token,请重新申请找回密码", - "tokenInvalid": "链接已失效或已过期(可能已使用过或重新申请过),请回到登录页重新发起找回密码" - } } diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index 1b1e9dfe..ac3d290c 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -1,6 +1,21 @@ { "generic": "请求失败。", "codes": { + "ORDER_DELIVERY_REPLY.FORBIDDEN": "无订单交期回复查看权限,请联系管理员开通。", + "ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "订单行不存在或已不在同步范围。", + "ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "仅平台管理员可按部门批量发放权限。", + "ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "请填写要发放权限的部门。", + "ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "权限类型须为 manage 或 access。", + "ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "联合回复至少包含一行,且单次不超过 200 行。", + "ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "批量通知至少包含一行,且单次不超过 200 行。", + "ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "订单业务员未关联系统账号或未绑定企微,无法发送通知。", + "ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "企微通知发送失败,该行未锁定,请稍后重试。", + "ORDER_DELIVERY_REPLY.LINE_LOCKED": "该订单行交期已通知锁定,不能修改批次。", + "ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "无订单交期回复操作权限,仅生管可保存或通知。", + "ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "请至少填写一条交期批次。", + "ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "单行批次数量超过上限。", + "ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,请检查交期、数量或备注。", + "ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次数量合计必须等于订单数量,请调整后重新保存。", "SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所选 ODM ID 不在当前可行候选内,请重新选择。", "SHIPPING.FULFILLMENT_POLICY_INVALID": "货代履约策略或字段能力绑定无效。", "SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "未找到货代履约策略。", diff --git a/frontend/src/locales/zh-CN/workspace.json b/frontend/src/locales/zh-CN/workspace.json index 228b7918..12a80c3d 100644 --- a/frontend/src/locales/zh-CN/workspace.json +++ b/frontend/src/locales/zh-CN/workspace.json @@ -113,7 +113,8 @@ "contractPayment": "合同付款预警", "contractPaymentLedger": "合同台账", "contractPaymentReview": "待确认合同", - "contractPaymentWeeklyBatches": "周汇总批次" + "contractPaymentWeeklyBatches": "周汇总批次", + "orderDeliveryReply": "订单交期回复" }, "kb": { "accessDenied": "需要管理员权限才能访问知识库。" @@ -202,7 +203,21 @@ "resend": "重发企微", "failedUnits": "失败的收料单元", "retry": "填写原因后重试", - "retryReasonPrompt": "请填写重试 {target} 的原因" + "retryReasonPrompt": "请填写重试 {target} 的原因", + "batch": { + "selectAll": "全选当前页通知单", + "selected": "已选 {count} 张", + "download": "批量下载 Excel", + "confirm": "批量确认已上传", + "rpa": "批量启动 RPA", + "downloadStarted": "已开始下载所选发货通知 Excel", + "success": "{action}:已处理 {count} 张通知单", + "partialResult": "{action}:成功 {accepted} 张,阻断 {blocked} 张,请查看刷新后的通知状态。", + "lines": "项次", + "parts": "料号", + "quantities": "本次发货 / 可用库存", + "uploadStatus": "货代状态" + } }, "shippingNotice": { "title": "货代发货通知", @@ -968,5 +983,100 @@ "notifyExcel": "Excel", "downloadExcel": "下载 Excel", "downloadExcelFailed": "下载 Excel 失败" + }, + "orderDeliveryReply": { + "deepLinkLocated": "已定位到通知对应的订单行 {order}:{item}", + "search": "查询", + "reset": "重置", + "saving": "保存中…", + "syncNow": "手动刷新", + "syncing": "同步中…", + "syncNever": "尚未同步", + "syncAt": "最近同步:{time}", + "syncRunning": "同步进行中…", + "syncFailedAt": "上次同步失败({time}),列表为上次成功快照", + "syncDone": "同步完成,共 {count} 行", + "syncSkipped": "已有同步正在进行,请稍后再试", + "syncFailedTitle": "同步失败,已保留上次快照", + "filterKeyword": "关键词(订单 / 产品 / 客户 / 业务员 / 回复人员)", + "filterKeywordPh": "订单单号、产品编号、品名、客户料号、客户编号、业务员、交期回复人员均可搜索", + "filterOrderDate": "订单日期", + "filterStatus": "交期回复状态", + "statusAll": "全部", + "statusReplied": "已回复", + "statusNotFully": "未完全回复", + "statusNotReplied": "未回复", + "statusPartial": "部分回复", + "totalCount": "共 {count} 条产品行", + "selectAll": "全选(本页)", + "selectedCount": "已勾选 {count} 行", + "batchReply": "+ 联合回复交期", + "batchNotify": "批量通知", + "toolbarHint": "联合回复只保存批次;点「批量通知」才发送并锁定。", + "colOrderLine": "订单单号:项次", + "colOrderDate": "订单日期", + "colCustomer": "客户编号", + "colSalesperson": "业务员", + "colDept": "部门", + "colCustomerPo": "客户订单", + "colPartNo": "产品编号", + "colPartName": "品名", + "colSpec": "规格", + "colCustomerPartNo": "客户产品编号", + "colAgreedDate": "约定交货日", + "colUnit": "单位", + "colQty": "数量", + "colDelivered": "已交数量", + "colUndelivered": "未交数量", + "colStatus": "交期回复状态", + "colReply": "交期回复", + "colNotify": "通知业务部门", + "colReplyPerson": "交期回复人员", + "batchCount": "{count} 批", + "repliedOf": "已回复 {replied}/{remain}", + "overTag": "超", + "collapse": "收起 ▲", + "expand": "+{count} 批 ▾", + "lockedTag": "交期已锁定", + "replyAction": "回复交期", + "editReplyAction": "修改回复", + "notifiedTag": "已通知 {name}", + "replyFirst": "请先回复交期", + "notifyAction": "发送通知业务部门", + "pendingNotify": "待通知后记录", + "empty": "没有符合条件的订单行", + "pageInfo": "第 {page} / {pages} 页", + "modalTitleSingle": "回复交期 · {order} / 项次 {item}", + "modalTitleBatch": "联合回复交期({count} 行)", + "quickDate": "快速统一交期", + "applyQuickDate": "应用到全部", + "modalHint": "可填 1 个交期,或点「增加批次」拆成多个「交期+数量」;各批次数量合计须等于订单数量。", + "itemLabel": "项次 {item}", + "qtyPh": "数量", + "remarkPh": "备注(可选)", + "removeBatch": "删除本行批次", + "addBatch": "+ 增加拆分批次(交期 + 数量 + 备注)", + "saveReply": "保存回复", + "noValidBatches": "请至少为一行填写交期和数量", + "saveSingleDone": "交期批次已保存(未通知,可继续修改)", + "saveBatchDone": "已保存 {ok} 行交期批次(未通知)", + "saveBatchPartial": "保存完成:成功 {ok} 行,失败 {fail} 行:{detail}", + "saveFailedTitle": "保存失败", + "loadFailed": "加载订单行失败", + "notifyConfirm": "确认向业务员「{salesperson}」发送?\n您有订单号:项次{order}:{item}的订单需要填写/确认/查看交期。\n发送后交期将锁定。", + "notifyDone": "已通知并锁定:{order}:{item}", + "notifyBatchConfirm": "将向 {count} 行对应业务员发送交期通知,发送成功的行将锁定。继续?", + "notifyPartial": "部分成功:成功 {ok} 行,失败 {fail} 行,跳过 {skip} 行。失败:{detail}", + "notifyAllFailed": "全部失败({fail} 行):{detail}", + "notifyBatchDone": "已通知并锁定 {ok} 行,跳过 {skip} 行", + "notifyFailedTitle": "通知发送失败,该行未锁定", + "entryHint": "查单 → 填交期 → 通知业务员", + "notNotified": "未通知", + "orderQtyLabel": "订单数量:{qty} {unit}", + "batchMissingDate": "第 {batches} 批未填交期", + "batchMissingQty": "第 {batches} 批未填数量", + "qtyTotalMismatchLine": "各批次合计 {total},须等于订单数量 {qty}", + "saveBlocked": "以下行填写未完成,无法保存:{detail}", + "batchDuplicateDate": "同一订单单号:项次的不同批次交期时间不能相同(重复:{dates})" } } diff --git a/frontend/src/locales/zh-TW/admin.json b/frontend/src/locales/zh-TW/admin.json index 81e4952a..e828e56e 100644 --- a/frontend/src/locales/zh-TW/admin.json +++ b/frontend/src/locales/zh-TW/admin.json @@ -47,7 +47,8 @@ "platformApps": "平台應用說明", "procurementContract": "採購合同審查", "trainingConfig": "培訓配置", - "integrationConnector": "整合連接器" + "integrationConnector": "整合連接器", + "contractPayment": "合同付款预警" }, "shippingOrderExtractionRuns": { "eyebrow": "唯讀執行診斷", @@ -1213,6 +1214,10 @@ "trainingLeanTeamManage": "精益培訓班組管理", "contractPaymentAccess": "合約付款預警存取", "contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總)。同步 OA、掃描預警與發送預警僅管理員可用。", + "orderDeliveryReplyManage": "訂單交期回覆操作", + "orderDeliveryReplyManageHint": "勾選後可回覆交期批次、發送/批量通知業務員並手動同步 ERP 訂單(生管)。", + "orderDeliveryReplyAccess": "訂單交期回覆查看", + "orderDeliveryReplyAccessHint": "勾選後可唯讀查看已同步訂單與回覆結果(業務人員);回覆與通知需另勾「操作」權限。", "password": "密碼", "passwordHint": "(留空表示不修改)", "noAgents": "暫無可用應用" @@ -1246,11 +1251,13 @@ "name": "名稱", "code": "編碼", "company": "公司", - "actions": "操作" + "actions": "操作", + "members": "Members" }, "actions": { "edit": "編輯", - "delete": "刪除" + "delete": "刪除", + "viewMembers": "View department members" }, "fields": { "name": "名稱", @@ -1265,6 +1272,11 @@ "confirmDelete": "確定刪除該部門嗎?", "msg": { "nameRequired": "部門名稱必填" + }, + "members": { + "title": "{name} Members", + "count": "{count} members", + "empty": "No members" } }, "agent": { @@ -1797,12 +1809,13 @@ "firstLoginInputFields": "首次登入可輸入字段", "employeeIdSource": "工號來源字段", "mobileNormalize": "手機號歸一化", - "callbackToken": "回調 Token", + "callbackToken": "回呼Token", "encodingAesKey": "EncodingAESKey", - "callbackUrl": "回調URL", + "callbackUrl": "回呼URL", "homepageUrl": "應用主頁URL", - "trustedDomain": "可信域名", - "publicBaseUrl": "外網 HTTPS 基地址" + "trustedDomain": "可信任網域", + "publicBaseUrl": "外網 HTTPS 基地址", + "userId": "User ID (user_id)" }, "bindModes": { "match_rules": "按規則自動匹配", @@ -1915,8 +1928,23 @@ "filterName": "篩選 姓名/用戶名", "filterDept": "篩選 部門", "allRoles": "所有角色", - "views": { "apps": "按應用查看", "members": "按成員查看" }, - "appHeaders": { "app": "應用", "type": "類型", "authorized": "已授權人數", "actions": "操作", "viewMembers": "查看成員", "accessHint": "點擊查看成員權限", "memberHint": "可新增或取消此應用的存取權限", "memberSearch": "搜尋姓名、用戶名、工號或部門", "addMember": "新增權限", "removeMember": "取消權限", "noMembers": "沒有符合的成員" }, + "views": { + "apps": "按應用查看", + "members": "按成員查看" + }, + "appHeaders": { + "app": "應用", + "type": "類型", + "authorized": "已授權人數", + "actions": "操作", + "viewMembers": "查看成員", + "accessHint": "點擊查看成員權限", + "memberHint": "可新增或取消此應用的存取權限", + "memberSearch": "搜尋姓名、用戶名、工號或部門", + "addMember": "新增權限", + "removeMember": "取消權限", + "noMembers": "沒有符合的成員" + }, "headers": { "user": "用戶", "realName": "真實姓名", @@ -2153,7 +2181,7 @@ "tokens_completion": "補全 Token", "total_tokens": "總 Token", "latency_ms": "延遲(毫秒)", - "latency": "延遲", + "latency": "耗時(毫秒)", "cost": "費用", "ip": "IP", "user_agent": "用戶代理", @@ -2169,13 +2197,15 @@ "reset_token_expiry": "重置令牌過期時間", "risk_status": "風險狀態", "risk_score": "風險分", - "latency": "耗時(毫秒)", "is_empty_answer": "空回答", "is_system_failure": "系統失敗", "feedback_score": "評分", "feedback_comment": "評分備註", "negative_feedback_count": "負面反饋數", - "actions": "操作" + "actions": "操作", + "feedback_module": "Feedback Module", + "feedback_type": "Feedback Type", + "source_page": "Source Page" }, "tables": { "users": "用戶", @@ -2186,7 +2216,8 @@ "agents": "應用運營", "ops_overview": "營運總覽", "issue_analysis": "問題分析", - "usage_analysis": "使用分析" + "usage_analysis": "使用分析", + "permission_requests": "權限申請" }, "usageIntro": "查看 AI 應用呼叫趨勢、活躍使用者、低使用應用與異常高峰。", "usageTotalSessions": "對話總量", @@ -2376,6 +2407,32 @@ "topApp": "優先優化應用", "topAppHint": "需要關注信號占比 {ratio}%" } + }, + "usageRangeLabel": "統計範圍", + "usageRanges": { + "7d": "近一週", + "30d": "近一月", + "90d": "近三月", + "180d": "近半年", + "365d": "近一年" + }, + "feedbackValues": { + "types": { + "feature_suggestion": "Feature Suggestion", + "issue_feedback": "Issue Feedback", + "experience_optimization": "Experience Optimization" + }, + "modules": { + "knowledge_base": "Knowledge Base", + "general": "General", + "workflow": "Workflow", + "account_permission": "Account & Permissions" + }, + "pages": { + "workspace": "Workspace", + "chat": "Chat", + "unknown": "Unknown" + } } }, "batchEdit": { @@ -2522,7 +2579,35 @@ "voucherCheckNotifyMissing": "缺資料通知", "voucherCheckNotifyMissingHint": "總開關。缺件接收人請到 Chat「立帳憑證 → 通知設定」依檔案類型設定;排程選人只用於技術失敗告警。", "voucherCheckNotifyFailure": "失敗告警", - "voucherCheckNotifyFailureHint": "技術失敗會發給下方「選擇通知人員」。" + "voucherCheckNotifyFailureHint": "技術失敗會發給下方「選擇通知人員」。", + "editTitle": "Edit schedule", + "createTitle": "Add schedule", + "name": "Schedule name", + "namePlaceholder": "e.g. RoHS auto review schedule", + "owner": "Schedule owner", + "noUsers": "No users available", + "selectOwner": "Select an owner", + "faqHotAggregate": "FAQ hot aggregate", + "querying": "Querying...", + "testQuery": "Test query", + "expandConfig": "Expand config", + "collapseConfig": "Collapse config", + "dataSourceSection": "Data source config", + "waitSeconds": "Wait time (seconds)", + "noAgents": "No agents available", + "agentDisabled": "Disabled", + "minuteInterval": "Minute interval", + "minuteOfHour": "Minute of hour", + "weekday": "Weekday", + "notifyEnabled": "Enable notifications", + "selectNotifyUsers": "Select notification recipients...", + "enableOnCreate": "Enable after creation", + "cancel": "Cancel", + "saving": "Saving...", + "saveChanges": "Save changes", + "createSchedule": "Create schedule", + "dynamicParamsSearchPlaceholder": "搜尋選項(姓名/工號/部門)…", + "dynamicParamsSearchNoMatch": "沒有符合的選項" }, "status": { "all": "全部狀態", @@ -2559,7 +2644,25 @@ "noKbGroupHint": "請先在排程編輯中啟用知識庫同步並選擇分組。", "kbSyncNoStatus": "已請求寫入知識庫,但未返回同步狀態,請檢查排程知識庫配置或後端日誌。", "baseFetchSqlReadonly": "基礎查詢 SQL (base_fetch_sql) — 唯讀", - "limitRows": "限制行數 (limit)" + "limitRows": "限制行數 (limit)", + "title": "Test run — {name}", + "subtitle": "Edit WHERE clause, limit rows, run quickly and inspect each step", + "close": "Close", + "running": "Running...", + "start": "Start test run", + "waitingHint": "Dify calls may take a while, please wait...", + "total": "Total", + "success": "Success", + "failed": "Failed", + "skipped": "Skipped", + "limitSummary": "Limit {limit} rows | Dify Agent ID: {agentId}", + "noAgent": "None", + "stepLogs": "Step logs", + "viewSql": "View execution SQL", + "errors": "Errors ({count})", + "queryResult": "Query result", + "resultSummary": "{total} total, showing {showing}", + "viewGeneratedSql": "View generated SQL" }, "deleteDialogTitle": "刪除排程", "excelExportFailedHint": "庫存來源已成功,但排程 Excel 生成失敗", @@ -2577,8 +2680,19 @@ "receiptRawZip": "原始收料", "columns": { "skippedCount": "跳過", - "skippedCountReceipt": "無收料/跳過", - "skippedCountInventory": "無庫存/跳過" +"runNo": "Run ID", +"startedAt": "Started at", +"finishedAt": "Finished at", +"status": "Status", +"totalCount": "Processed", +"successCount": "Success", +"failedCount": "Failed", +"excelExportFailedHint": "Inventory sources succeeded, but schedule Excel export failed", +"wecomNotified": "WeCom notify", +"detail": "Detail", +"log": "Log", +"skippedCountReceipt": "無收料/跳過", +"skippedCountInventory": "無庫存/跳過" }, "deleteConfirmMessage": "確認刪除排程「{name}」?", "msg": { @@ -2592,8 +2706,9 @@ "runNowWaitTimeout": "等待執行完成逾時(約 15 分鐘),已停止自動重新整理,可手動查詢記錄", "downloadExcelFailed": "下載 Excel 失敗", "downloadInventoryRawZipFailed": "下載原始庫存包失敗", - "downloadReceiptRawZipFailed": "下載原始收料包失敗", - "deleteFailed": "刪除排程失敗" +"deleteFailed": "刪除排程失敗", +"testQueryFailed": "Test query failed", +"downloadReceiptRawZipFailed": "下載原始收料包失敗" }, "difySnapshot": { "title": "Dify 執行快照(審計)", @@ -2605,6 +2720,65 @@ "notConfiguredUseDefault": "(未配置,使用 Dify 編排內預設提示詞)", "notEnabledTest": "本次測試未啟用 Dify", "notEnabledRun": "本次執行未啟用 Dify Agent" + }, + "overviewTitle": "Schedule Management Overview", + "workbenchTitle": "Schedule Management Workbench", + "overviewSubtitle": "Click a schedule card to open the workbench.", + "workbenchSubtitle": "Schedule list on the left, run records on the right.", + "refresh": "Refresh schedules", + "stats": { + "total": "Total schedules", + "enabled": "Enabled", + "disabled": "Disabled", + "running": "Running" + }, + "sectionOverview": "Schedule Management Overview", + "switchByCard": "Switch by card", + "addTitle": "Add schedule", + "addHint": "Click the button to fill in schedule fields in a dialog.", + "addButton": "Add schedule", + "emptyList": "No schedules yet. Create one first.", + "loading": "Loading...", + "enabled": "Enabled", + "disabled": "Disabled", + "scheduleNo": "No.", + "config": "Config", + "owner": "Owner", + "lastRun": "Last run", + "nextRun": "Next run", + "nextRunDisabled": "Disabled", + "nextRunPending": "Not computed (save or restart schedule)", + "noSelection": "No schedule selected", + "selectedHint": "Selected schedule · Last run {time}", + "runBatches": "Run batches", + "totalProcessed": "Total processed", + "totalSuccess": "Total success", + "totalFailed": "Total failed", + "listTitle": "Schedule list", + "recordsTitle": "{name} · Run records", + "recordsSubtitle": "Run record details are shown below.", + "noSelectionHint": "Select a schedule from the list on the left first.", + "filterStart": "Start", + "filterEnd": "End", + "query": "Search", + "reset": "Reset", + "queryingRuns": "Loading records...", + "noRunRecords": "No run records yet.", + "runLogs": "Run logs", + "stepsCount": "{count} steps", + "viewDetail": "View details", + "resizeColumn": "Drag to resize {label} column", + "notified": "Notified", + "notifyError": "Error", + "download": "Download", + "log": "Log", + "actions": { + "edit": "Edit", + "start": "Start", + "pause": "Pause", + "run": "Run", + "test": "Test", + "delete": "Delete" } }, "shippingIdentityRules": { @@ -4251,7 +4425,8 @@ "rejected": "已駁回", "needs_review": "待複核" }, - "confirmRequiresNativePreview": "請先載入原生 PDF 預覽後再確認視覺綁定" + "confirmRequiresNativePreview": "請先載入原生 PDF 預覽後再確認視覺綁定", + "createBlockersTitle": "创建前阻断项" }, "xfaAutoMark": { "title": "自動標記建議", @@ -5293,7 +5468,17 @@ "trainingAgentRequired": "未找到員工培訓 Agent,無法建立影片資源", "videoUploaded": "培訓影片已上傳並加入配置資源", "videoUploadFailed": "培訓影片上傳失敗" - } + }, + "eyebrow": "培训运营中心", + "pageHint": "配置变更将在保存后生效", + "footerHint": "所有配置项均支持保存后继续调整", + "stats": { + "total": "配置总数", + "published": "已发布", + "resources": "当前资料", + "levels": "已配置级别" + }, + "questionBankTitle": "入职培训题库" }, "integrationConnector": { "title": "整合連接器", diff --git a/frontend/src/locales/zh-TW/auth.json b/frontend/src/locales/zh-TW/auth.json index c3e1f74e..dd5f65b5 100644 --- a/frontend/src/locales/zh-TW/auth.json +++ b/frontend/src/locales/zh-TW/auth.json @@ -129,7 +129,17 @@ "notInScopeAction": "請管理員到企業微信後台,把該成員或其所在部門加入該應用的可見範圍。", "retryLogin": "請重新發起一次企業微信登入。", "contactAdmin": "如需協助,請聯繫管理員。" - } + }, + "newPassword": "New Password", + "passwordResetSuccess": "Password reset successfully. Please login.", + "featuredAgents": "Featured AI Agents", + "pleaseLoginFirst": "Please login to access this agent.", + "userNotFound": "User not found", + "incorrectPassword": "Incorrect password", + "accountDisabled": "Account is disabled", + "dbConnectionFailed": "Database connection failed. Please check if the database service is running.", + "internalError": "Internal server error. Please try again later.", + "passwordResetEmailSent": "If the account exists, a reset link has been sent to your email." }, "landing": { "hero": { @@ -156,7 +166,8 @@ "realName": "真實姓名", "employeeId": "工號", "phone": "手機號" - } + }, + "emailRequired": "Email is required" }, "resetPassword": { "title": "重設密碼", diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index edd8c074..8a0939f0 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -1188,7 +1188,11 @@ "departmentLabel": "部門", "allStatuses": "全部狀態", "allDepartments": "全部部門", - "noLimit": "不限" + "noLimit": "不限", + "typeLabel": "培训类型", + "allTypes": "全部培训", + "typeOnboarding": "入职培训", + "typeSafety": "安全培训" }, "columns": { "joinDate": "入職日期", @@ -1543,6 +1547,75 @@ "哪些員工還沒有完成培訓?", "我想查看本月培訓成績統計" ] + }, + "safety": { + "tabs": { + "onboarding": "入职培训", + "safety": "安全培训" + }, + "progressTitle": "三级安全教育培训进度", + "progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。", + "steps": { + "company": "01 · 公司级", + "department": "02 · 部门级", + "team": "03 · 班组级", + "exam": "04 · 统一考试" + }, + "stepStatus": { + "watchVideo": "观看视频", + "examReq": "≥90 分及格", + "completed": "已完成", + "inProgress": "进行中", + "pending": "待学习", + "examPending": "需先学完三级" + }, + "videoPanelTitle": "{level} 第{step}步", + "videoPanelSubtitle": "观看安全教育培训视频", + "videoPanelPassLine": "及格线:≥ 90分方可进入考试", + "videoTitle": "部门安全生产管理制度宣导", + "videoDuration": "时长 35 分钟 · 已完成 12%", + "materialsTitle": "培训资料清单 (共 3 个文件/视频)", + "materials": { + "m1": "部门安全生产管理制度宣导.mp4", + "m2": "危险化学品安全操作规程.pdf", + "m3": "消防应急疏散演练视频.mp4" + }, + "flowTitle": "学习与考试流程", + "flowSteps": { + "company": "公司级安全教育", + "department": "部门级安全教育", + "team": "班组级安全教育", + "exam": "统一考试 ≥90分" + }, + "summaryTitle": "培训总结", + "summaryContent": { + "company": [ + "1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。", + "2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。", + "3企业安全生产规章制度、安全纪律和劳动纪律。", + "4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。", + "5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;", + "6安全生产正反方面的经验和教训,及重大事故安全案例教训。", + "7从业人员安全生产权利和义务;" + ], + "department": [ + "1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。", + "2公司、部门安全生产状况、管理制度规定和安全注意事项。", + "3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。", + "4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识", + "5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。", + "6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。", + "7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。", + "8有关事故案例。" + ], + "team": [ + "1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。", + "2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。", + "3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。", + "4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。", + "5本岗位发现紧急情况应采取的应救措施和报告办法。" + ] + } } }, "shippingOrderReview": { @@ -2679,7 +2752,8 @@ "inventory_source_unresolved": "庫存源未解析", "effective_reservation_missing": "缺少有效的預約單號", "unknown": "系統發現一項需要人工確認的內容" - } + }, + "autoCreateBlocked": "人工建单资格已通过,但自动建单资格未通过;确认后将由人工推进。" }, "inventoryCandidates": { "title": "人工選擇庫存源", diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index 9912c61b..50c75883 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -1,6 +1,21 @@ { "generic": "請求失敗。", "codes": { + "ORDER_DELIVERY_REPLY.FORBIDDEN": "無訂單交期回覆查看權限,請聯絡管理員開通。", + "ORDER_DELIVERY_REPLY.LINE_NOT_FOUND": "訂單行不存在或已不在同步範圍。", + "ORDER_DELIVERY_REPLY.ADMIN_REQUIRED": "僅平台管理員可按部門批量發放權限。", + "ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED": "請填寫要發放權限的部門。", + "ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID": "權限類型須為 manage 或 access。", + "ORDER_DELIVERY_REPLY.BATCH_REPLY_EMPTY": "聯合回覆至少包含一行,且單次不超過 200 行。", + "ORDER_DELIVERY_REPLY.NOTIFY_BATCH_EMPTY": "批量通知至少包含一行,且單次不超過 200 行。", + "ORDER_DELIVERY_REPLY.SALESPERSON_UNMAPPED": "訂單業務員未關聯系統帳號或未綁定企微,無法發送通知。", + "ORDER_DELIVERY_REPLY.NOTIFY_FAILED": "企微通知發送失敗,該行未鎖定,請稍後重試。", + "ORDER_DELIVERY_REPLY.LINE_LOCKED": "該訂單行交期已通知鎖定,不能修改批次。", + "ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN": "無訂單交期回覆操作權限,僅生管可儲存或通知。", + "ORDER_DELIVERY_REPLY.BATCHES_REQUIRED": "請至少填寫一條交期批次。", + "ORDER_DELIVERY_REPLY.BATCH_COUNT_EXCEEDED": "單行批次數量超過上限。", + "ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,請檢查交期、數量或備註。", + "ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次數量合計必須等於訂單數量,請調整後重新保存。", "SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所選 ODM ID 不在當前可行候選內,請重新選擇。", "SHIPPING.FULFILLMENT_POLICY_INVALID": "貨代履約策略或欄位能力綁定無效。", "SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "找不到貨代履約策略。", diff --git a/frontend/src/locales/zh-TW/workspace.json b/frontend/src/locales/zh-TW/workspace.json index 88df47f1..0e0ac5b5 100644 --- a/frontend/src/locales/zh-TW/workspace.json +++ b/frontend/src/locales/zh-TW/workspace.json @@ -113,7 +113,8 @@ "contractPayment": "合約付款預警", "contractPaymentLedger": "合約台帳", "contractPaymentReview": "待確認合約", - "contractPaymentWeeklyBatches": "週彙總批次" + "contractPaymentWeeklyBatches": "週彙總批次", + "orderDeliveryReply": "訂單交期回覆" }, "kb": { "accessDenied": "需要管理員權限才能存取知識庫。" @@ -170,6 +171,20 @@ }, "msg": { "downloadExcelFailed": "下載 Excel 失敗" + }, + "batch": { + "selectAll": "Select all notices on this page", + "selected": "{count} selected", + "download": "Download Excel", + "confirm": "Confirm uploaded", + "rpa": "Start RPA upload", + "downloadStarted": "Downloading the selected shipping-notice Excel files.", + "success": "{action}: {count} notice(s) processed.", + "partialResult": "{action}: {accepted} accepted and {blocked} blocked. Refresh to see the latest notice status.", + "lines": "Lines", + "parts": "Parts", + "quantities": "Shipment / available", + "uploadStatus": "Freight status" } }, "receiptReports": { @@ -968,5 +983,100 @@ "notifyExcel": "Excel", "downloadExcel": "下載 Excel", "downloadExcelFailed": "下載 Excel 失敗" + }, + "orderDeliveryReply": { + "deepLinkLocated": "已定位到通知對應的訂單行 {order}:{item}", + "search": "查詢", + "reset": "重置", + "saving": "儲存中…", + "syncNow": "手動刷新", + "syncing": "同步中…", + "syncNever": "尚未同步", + "syncAt": "最近同步:{time}", + "syncRunning": "同步進行中…", + "syncFailedAt": "上次同步失敗({time}),列表為上次成功快照", + "syncDone": "同步完成,共 {count} 行", + "syncSkipped": "已有同步正在進行,請稍後再試", + "syncFailedTitle": "同步失敗,已保留上次快照", + "filterKeyword": "關鍵詞(訂單 / 產品 / 客戶 / 業務員 / 回覆人員)", + "filterKeywordPh": "訂單單號、產品編號、品名、客戶料號、客戶編號、業務員、交期回覆人員均可搜尋", + "filterOrderDate": "訂單日期", + "filterStatus": "交期回覆狀態", + "statusAll": "全部", + "statusReplied": "已回覆", + "statusNotFully": "未完全回覆", + "statusNotReplied": "未回覆", + "statusPartial": "部分回覆", + "totalCount": "共 {count} 條產品行", + "selectAll": "全選(本頁)", + "selectedCount": "已勾選 {count} 行", + "batchReply": "+ 聯合回覆交期", + "batchNotify": "批量通知", + "toolbarHint": "聯合回覆只儲存批次;點「批量通知」才發送並鎖定。", + "colOrderLine": "訂單單號:項次", + "colOrderDate": "訂單日期", + "colCustomer": "客戶編號", + "colSalesperson": "業務員", + "colDept": "部門", + "colCustomerPo": "客戶訂單", + "colPartNo": "產品編號", + "colPartName": "品名", + "colSpec": "規格", + "colCustomerPartNo": "客戶產品編號", + "colAgreedDate": "約定交貨日", + "colUnit": "單位", + "colQty": "數量", + "colDelivered": "已交數量", + "colUndelivered": "未交數量", + "colStatus": "交期回覆狀態", + "colReply": "交期回覆", + "colNotify": "通知業務部門", + "colReplyPerson": "交期回覆人員", + "batchCount": "{count} 批", + "repliedOf": "已回覆 {replied}/{remain}", + "overTag": "超", + "collapse": "收起 ▲", + "expand": "+{count} 批 ▾", + "lockedTag": "交期已鎖定", + "replyAction": "回覆交期", + "editReplyAction": "修改回覆", + "notifiedTag": "已通知 {name}", + "replyFirst": "請先回覆交期", + "notifyAction": "發送通知業務部門", + "pendingNotify": "待通知後記錄", + "empty": "沒有符合條件的訂單行", + "pageInfo": "第 {page} / {pages} 頁", + "modalTitleSingle": "回覆交期 · {order} / 項次 {item}", + "modalTitleBatch": "聯合回覆交期({count} 行)", + "quickDate": "快速統一交期", + "applyQuickDate": "應用到全部", + "modalHint": "可填 1 個交期,或點「增加批次」拆成多個「交期+數量」;各批次數量合計須等於訂單數量。", + "itemLabel": "項次 {item}", + "qtyPh": "數量", + "remarkPh": "備註(可選)", + "removeBatch": "刪除本行批次", + "addBatch": "+ 增加拆分批次(交期 + 數量 + 備註)", + "saveReply": "儲存回覆", + "noValidBatches": "請至少為一行填寫交期和數量", + "saveSingleDone": "交期批次已儲存(未通知,可繼續修改)", + "saveBatchDone": "已儲存 {ok} 行交期批次(未通知)", + "saveBatchPartial": "儲存完成:成功 {ok} 行,失敗 {fail} 行:{detail}", + "saveFailedTitle": "儲存失敗", + "loadFailed": "載入訂單行失敗", + "notifyConfirm": "確認向業務員「{salesperson}」發送?\n您有訂單號:項次{order}:{item}的訂單需要填寫/確認/查看交期。\n發送後交期將鎖定。", + "notifyDone": "已通知並鎖定:{order}:{item}", + "notifyBatchConfirm": "將向 {count} 行對應業務員發送交期通知,發送成功的行將鎖定。繼續?", + "notifyPartial": "部分成功:成功 {ok} 行,失敗 {fail} 行,跳過 {skip} 行。失敗:{detail}", + "notifyAllFailed": "全部失敗({fail} 行):{detail}", + "notifyBatchDone": "已通知並鎖定 {ok} 行,跳過 {skip} 行", + "notifyFailedTitle": "通知發送失敗,該行未鎖定", + "entryHint": "查單 → 填交期 → 通知業務員", + "notNotified": "未通知", + "orderQtyLabel": "訂單數量:{qty} {unit}", + "batchMissingDate": "第 {batches} 批未填交期", + "batchMissingQty": "第 {batches} 批未填數量", + "qtyTotalMismatchLine": "各批次合計 {total},須等於訂單數量 {qty}", + "saveBlocked": "以下行填寫未完成,無法保存:{detail}", + "batchDuplicateDate": "同一訂單單號:項次的不同批次交期時間不能相同(重複:{dates})" } } diff --git a/frontend/src/shared/api/client.ts b/frontend/src/shared/api/client.ts index 2bffda22..6e8ceab4 100644 --- a/frontend/src/shared/api/client.ts +++ b/frontend/src/shared/api/client.ts @@ -122,6 +122,11 @@ export async function requestJson(url: string, init?: RequestInit): Promise headers.set(k, v as string)); + // 带 body 的请求若未显式声明类型,统一补 JSON 头:否则 Flask get_json(silent=True) + // 会因 Content-Type 非 JSON 解析出 None,把有效载荷当空 body 处理(如订单交期回复保存被误判 400)。 + if (init?.body && !headers.has('Content-Type')) { + headers.set('Content-Type', 'application/json'); + } const res = await fetch(url, { ...init, headers }); let data: any = null; diff --git a/frontend/src/shared/utils/auth.ts b/frontend/src/shared/utils/auth.ts index 5b60cfb8..1eb33020 100644 --- a/frontend/src/shared/utils/auth.ts +++ b/frontend/src/shared/utils/auth.ts @@ -6,6 +6,9 @@ */ export type FeaturePermissions = { training_hr_manage?: boolean; + 'contract_payment.access'?: boolean; + 'order_delivery_reply.manage'?: boolean; + 'order_delivery_reply.access'?: boolean; [key: string]: boolean | undefined; };