feat(shipping-notice): 我的待办改版为表格加抽屉并新增已完成明细报表

- 阶段 tab 收敛 4 个可动作阶段,计数改后端全量聚合
- 通知完成拆明细平铺报表(筛选/分页/12 列导出),批量改情境浮动条
- 同步 i18n 四语言与文档
This commit is contained in:
hugo committed 2026-09-17 15:54:53 +08:00
1 parent 18af972d20
commit d8299ebf20
21 files changed
+3315 -761

No files matched your search

@@ -199,6 +199,7 @@ def workspace_shipping_my_todos():
todo_category=str(request.args.get('todo_category') or '').strip() or None,
customer=str(request.args.get('customer') or '').strip() or None,
task_no=str(request.args.get('task_no') or '').strip() or None,
terminal_kind=str(request.args.get('terminal_kind') or '').strip() or None,
))
@@ -212,6 +213,67 @@ def workspace_shipping_my_todos_count():
return _ok(count_my_todos(user.id, is_admin=is_admin))
def _done_lines_report_params() -> dict[str, Any]:
"""解析明细报表共用筛选参数(客户/料号/发货通知日期范围),供查询与导出复用。"""
return {
'customer': str(request.args.get('customer') or '').strip() or None,
'part_number': str(request.args.get('part_number') or '').strip() or None,
'notice_date_from': str(request.args.get('notice_date_from') or '').strip() or None,
'notice_date_to': str(request.args.get('notice_date_to') or '').strip() or None,
}
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines', methods=['GET'])
def workspace_shipping_done_lines():
"""
分页列出已完成(已核验上传成功)通知的平铺明细行,供「通知完成」子视图报表。
核心逻辑:明细行跨 Notice 混排、不按 OT 聚合;支持 客户 / 料号 /
发货通知日期范围 筛选;行结构为标准 12 字段 + 溯源编号(task_no/business_no)。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import list_done_notice_lines
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
try:
page = int(request.args.get('page') or 1)
page_size = int(request.args.get('page_size') or 20)
except (TypeError, ValueError) as exc:
raise ValidationError('page and page_size must be integers') from exc
return _ok(list_done_notice_lines(
user.id,
is_admin=is_admin,
page=page,
page_size=page_size,
**_done_lines_report_params(),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines/export', methods=['GET'])
def workspace_shipping_done_lines_export():
"""
导出当前筛选下的已完成通知明细 Excel。
核心逻辑:固定 12 列标准格式(客户/客户编号/订单日期/订单项次/料号/数量/
约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 编号不落列;
已用数量 / open qty 无数据源留空。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
stream, filename = build_done_lines_xlsx(
user.id,
is_admin=is_admin,
**_done_lines_report_params(),
)
response = send_file(
stream, as_attachment=True, download_name=filename, mimetype=EXPORT_MIME_TYPE,
)
response.call_on_close(stream.close)
return response
def _batch_task_nos(data: dict) -> list[str]:
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
raw_task_nos = data.get('task_nos')
@@ -0,0 +1,290 @@
"""
backend/app/services/shipping_notice/done_line_report.py
用途:「我的待办」已完成(已核验上传成功)发货通知的平铺明细行报表读模型与专用导出。
依赖:query_service 的可见性与上传成功口径(_visible_tasks_query_for_todos /
_verified_upload_success_sql_expr);shipping_order_snapshot 冻结快照。
逻辑:Notice(uploaded) → OT → Snapshot → SnapshotLine 展开为标准 12 字段行;页面另附
OT/business 编号列便于溯源,导出严格 12 列不落编号。已用数量 / open_qty 当前无
数据源,契约占位为 None(前端与 Excel 均留空)。约定出货日期取行级 required_date
(field_values_json),缺失时回退快照表头 typed 列;订单单号取表头
source_order_number(field_id 键)。支持 客户 / 料号 / 发货通知日期(Notice
创建日期)筛选,按明细行分页;导出复用同一查询,行数受 DONE_LINE_EXPORT_LIMIT 防护。
"""
from __future__ import annotations
from datetime import date, datetime, time
from io import BytesIO
from typing import Any
from zoneinfo import ZoneInfo
from openpyxl import Workbook
from sqlalchemy import asc, desc
from app import db
from app.core.errors import ValidationError
from app.models import (
ShippingNotice,
ShippingOrderField,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
)
from app.services.shipping_notice.query_service import (
_verified_upload_success_sql_expr,
_visible_tasks_query_for_todos,
)
# 导出防护上限:超出即截断(明细行报表场景远低于该量级)。
DONE_LINE_EXPORT_LIMIT = 10000
# 导出固定 12 列中文表头;顺序即业务标准格式,OT 编号不落列。
DONE_REPORT_HEADERS: tuple[str, ...] = (
"客户", "客户编号", "订单日期", "订单项次", "料号", "数量",
"约定出货日期", "客户PO", "已用数量", "open qty", "订单单号", "单价",
)
def _parse_notice_date(value: Any, *, label: str) -> date:
"""解析 YYYY-MM-DD 日期参数;非法输入抛 ValidationError,禁止静默吞掉。"""
text = str(value or '').strip()
if not text:
raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID')
try:
return datetime.strptime(text[:10], '%Y-%m-%d').date()
except ValueError as exc:
raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID') from exc
def _done_lines_query(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
):
"""
构造已完成通知明细行的联表查询(Notice → OT → Snapshot → SnapshotLine)。
核心逻辑:仅取已核验上传成功的正式 Notice;可见性复用待办口径(非管理员仅创建者);
客户按快照 客户名称/客户编号 模糊、料号按 行料号/客户料号 模糊、发货通知日期按
Notice created_at 自然日闭区间过滤。
Raises:
ValidationError: 日期参数非法。
"""
q = (
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(_verified_upload_success_sql_expr())
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderSnapshot, ShippingOrderSnapshot.task_id == ShippingOrderTask.id)
.join(ShippingOrderSnapshotLine, ShippingOrderSnapshotLine.snapshot_id == ShippingOrderSnapshot.id)
)
customer_needle = str(customer or '').strip()
if customer_needle:
like = f"%{customer_needle}%"
q = q.filter(
db.or_(
ShippingOrderSnapshot.customer_name.ilike(like),
ShippingOrderSnapshot.customer_code.ilike(like),
)
)
part_needle = str(part_number or '').strip()
if part_needle:
like = f"%{part_needle}%"
q = q.filter(
db.or_(
ShippingOrderSnapshotLine.part_number.ilike(like),
ShippingOrderSnapshotLine.customer_part_number.ilike(like),
)
)
if notice_date_from:
from_day = notice_date_from if isinstance(notice_date_from, date) else _parse_notice_date(notice_date_from, label='notice_date_from')
q = q.filter(ShippingNotice.created_at >= datetime.combine(from_day, time.min))
if notice_date_to:
to_day = notice_date_to if isinstance(notice_date_to, date) else _parse_notice_date(notice_date_to, label='notice_date_to')
q = q.filter(ShippingNotice.created_at <= datetime.combine(to_day, time.max))
return q
def _report_field_ids() -> dict[tuple[str, str], str]:
"""读取报表所需的标准字段资产 id(field_code+scope 唯一),供 JSON 值回源。"""
rows = ShippingOrderField.query.filter(
ShippingOrderField.field_code.in_(('required_date', 'source_order_number')),
ShippingOrderField.status == 'active',
).all()
return {(row.field_code, row.scope): str(row.id) for row in rows}
def _date_text(value: Any) -> str | None:
"""日期值统一为 YYYY-MM-DD 文本;date 对象取日期部分,字符串截前十位。"""
if value in (None, ''):
return None
if hasattr(value, 'isoformat'):
return str(value.isoformat())[:10]
text = str(value).strip()
return text[:10] or None
def _num_text(value: Any) -> float | None:
"""数量/单价序列化为 JSON number;缺失返回 None(禁止 0 冒充)。"""
if value in (None, ''):
return None
return float(value)
def _serialize_done_line(
notice: ShippingNotice,
snapshot: ShippingOrderSnapshot,
line: ShippingOrderSnapshotLine,
field_ids: dict[tuple[str, str], str],
) -> dict[str, Any]:
"""按标准 12 字段 + 溯源编号序列化一行明细;无数据源字段契约留空。"""
required_date_field_id = field_ids.get(('required_date', 'line'))
required_date = (
(line.field_values_json or {}).get(required_date_field_id)
if required_date_field_id else None
)
if required_date in (None, ''):
required_date = snapshot.required_date
source_order_field_id = field_ids.get(('source_order_number', 'header'))
source_order_number = (
(snapshot.header_values_json or {}).get(source_order_field_id)
if source_order_field_id else None
)
return {
# 溯源编号:仅页面展示,导出不落列。
'task_no': notice.task_no,
'business_no': notice.business_no,
# 标准 12 字段。
'customer_name': snapshot.customer_name,
'customer_code': snapshot.customer_code,
'order_date': _date_text(snapshot.order_date),
'line_no': line.line_no,
'part_number': line.part_number,
'qty': _num_text(line.qty),
'required_date': _date_text(required_date),
'customer_po_number': snapshot.customer_po_number,
'used_qty': None,
'open_qty': None,
'source_order_number': source_order_number,
'unit_price': _num_text(line.unit_price),
}
def list_done_notice_lines(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""
分页列出已完成通知的平铺明细行(跨 Notice 混排,不按 OT 聚合)。
Returns:
{items, page, page_size, total};item 结构见 _serialize_done_line。
"""
normalized_page = max(1, int(page))
normalized_page_size = max(1, min(int(page_size), 100))
q = _done_lines_query(
user_id,
is_admin=is_admin,
customer=customer,
part_number=part_number,
notice_date_from=notice_date_from,
notice_date_to=notice_date_to,
)
total = int(q.count())
field_ids = _report_field_ids()
items: list[dict[str, Any]] = []
if total:
offset = (normalized_page - 1) * normalized_page_size
rows = (
q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine)
.order_by(
desc(ShippingNotice.created_at), desc(ShippingNotice.id),
asc(ShippingOrderSnapshotLine.position),
)
.offset(offset)
.limit(normalized_page_size)
.all()
)
items = [
_serialize_done_line(notice, snapshot, line, field_ids)
for notice, snapshot, line in rows
]
return {
'items': items,
'page': normalized_page,
'page_size': normalized_page_size,
'total': total,
}
def build_done_lines_xlsx(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
) -> tuple[BytesIO, str]:
"""
按当前筛选生成标准 12 列明细 Excel(不落 OT 编号列),返回流与下载文件名。
核心逻辑:与列表同源查询、不分页;超过 DONE_LINE_EXPORT_LIMIT 截断并在文件名
带时间戳,避免同日下载互相覆盖。单元格空值写 None(留空),禁止以 0 伪装。
"""
q = _done_lines_query(
user_id,
is_admin=is_admin,
customer=customer,
part_number=part_number,
notice_date_from=notice_date_from,
notice_date_to=notice_date_to,
)
rows = (
q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine)
.order_by(
desc(ShippingNotice.created_at), desc(ShippingNotice.id),
asc(ShippingOrderSnapshotLine.position),
)
.limit(DONE_LINE_EXPORT_LIMIT)
.all()
)
field_ids = _report_field_ids()
workbook = Workbook()
sheet = workbook.active
sheet.title = '通知明细'
sheet.append(list(DONE_REPORT_HEADERS))
for notice, snapshot, line in rows:
item = _serialize_done_line(notice, snapshot, line, field_ids)
sheet.append([
item['customer_name'],
item['customer_code'],
item['order_date'],
item['line_no'],
item['part_number'],
item['qty'],
item['required_date'],
item['customer_po_number'],
item['used_qty'],
item['open_qty'],
item['source_order_number'],
item['unit_price'],
])
buffer = BytesIO()
workbook.save(buffer)
buffer.seek(0)
stamp = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d_%H%M%S')
filename = f'done-lines-{stamp}.xlsx'
return buffer, filename
@@ -88,6 +88,13 @@ from app.services.shipping_notice.constants import (
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGE_BY_GATE,
LIFECYCLE_STAGE_BY_PROCESSING_STAGE,
)
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_REASON_OWNING_GATE,
)
from app.services.shipping_notice.state_machine import (
UserMode,
resolve_task_ui_state,
@@ -132,6 +139,17 @@ _TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
"done": frozenset({"done"}),
}
# 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」属 done 桶终态,不做筛选维度。
_ACTIONABLE_TODO_STAGES: tuple[str, ...] = (
"intake_parse", "order_review", "fulfillment_prep", "freight_upload",
)
# 无 processing_stage 且人工原因不可映射时的 todo_category 粗兜底(与 Gate 映射语义对齐)。
_TODO_STAGE_BY_CATEGORY_FALLBACK: dict[str, str] = {
"review": "order_review",
"exception": "fulfillment_prep",
"manual_upload": "freight_upload",
}
# 尚未挂 OT、仍需用户/系统关注的 Intake 解析状态(进入我的待办)。
_ORPHAN_INTAKE_TODO_PARSE_STATUSES = frozenset({
"created",
@@ -2762,12 +2780,14 @@ def _todo_tasks_base_query(
customer_needle: str,
customer_like: str,
task_no: str | None,
terminal_kind: str | None = None,
):
"""
构造带精确 category CASE 过滤的 Task 待办查询。
核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed);
done 桶另加终态粗筛。pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
done 桶另加终态粗筛;terminal_kind 进一步拆分 done 子视图(通知完成 / 驳回作废)。
pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
"""
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
@@ -2817,6 +2837,17 @@ def _todo_tasks_base_query(
),
)
)
# [STEP] 终态子视图过滤:前端「通知完成 / 复核驳回·已作废」子 tab 各取所需;
# 口径与分类 CASE 的 done 分支保持一致(上传成功优先,二者互斥)。
if terminal_kind == "upload_complete":
q = q.filter(upload_success)
elif terminal_kind == "reject_void":
q = q.filter(
db.or_(
workflow_review_status == RS_REJECTED,
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
)
)
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
@@ -2825,6 +2856,108 @@ def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
def _classify_todo_lifecycle_stage(
category: str,
*,
pending_human_reason: Any = None,
processing_stage: Any = None,
) -> str | None:
"""
按统一生命周期口径归类待办条目的阶段 tab(仅供计数,不替代 ui_state)。
核心逻辑:与 ``project_lifecycle`` 同优先级——processing_stage 权威 → 人工原因
归属 Gate 兜底 → todo_category 粗兜底;结果若不是四个可动作阶段(如 completed
映射出的 upload_complete)则返回 None,由调用方跳过,避免污染阶段 tab 计数。
Args:
category: 待办分类 CASE 结果(review/exception/manual_upload/in_progress)。
pending_human_reason: OT ``pending_human_reason`` 人工原因码(可空)。
processing_stage: OT ``stage`` 已持久化处理阶段(可空)。
Returns:
四个可动作阶段码之一;不可归入时 None。
"""
stage_key = str(processing_stage or '').strip().lower()
if stage_key in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[stage_key]
else:
gate = PROCESS_GATE_REASON_OWNING_GATE.get(str(pending_human_reason or '').strip())
if gate in LIFECYCLE_STAGE_BY_GATE:
stage = LIFECYCLE_STAGE_BY_GATE[gate]
else:
stage = _TODO_STAGE_BY_CATEGORY_FALLBACK.get(str(category or ''), 'fulfillment_prep')
return stage if stage in _ACTIONABLE_TODO_STAGES else None
def _my_todo_stage_counts(user_id: int, *, is_admin: bool) -> dict[str, int]:
"""
统计待处理桶在四个可动作阶段的分布,供前端阶段筛选 tab 展示全量计数。
核心逻辑:Review Case 走统一生命周期投影(候选有效性裁决 接收解析 vs 订单复核);
孤儿 Intake 恒为接收解析;Notice / OT 分支一次取回「分类 CASE + OT stage +
人工原因」后在 Python 侧归类,避免为计数复制一份 SQL 阶段状态机。
Returns:
{intake_parse, order_review, fulfillment_prep, freight_upload}(含 0 值键)。
"""
counts: dict[str, int] = {code: 0 for code in _ACTIONABLE_TODO_STAGES}
def _bump(stage: str | None) -> None:
if stage in counts:
counts[str(stage)] += 1
# [STEP 1] 开放 Review Case:复用统一投影,禁止另写候选有效性判断。
for case_row in _visible_open_review_cases_query(user_id, is_admin=is_admin).all():
projection = _review_case_lifecycle_projection(case_row)
_bump(str(projection.get('lifecycle_stage') or '').strip() or None)
# [STEP 2] 孤儿 Intake(未建 OT 的解析待办)恒为接收解析。
counts["intake_parse"] += int(
_visible_orphan_intakes_query(user_id, is_admin=is_admin).count()
)
# [STEP 3] Notice 分支:分类 CASE 直接作为列取回,连同 OT stage / 人工原因归类。
category_expr = _task_todo_category_sql_expr()
ot_stage_subquery = select(ShippingOrderTask.stage).where(
ShippingOrderTask.id == ShippingNotice.order_task_id,
).scalar_subquery()
ot_reason_subquery = select(ShippingOrderTask.pending_human_reason).where(
ShippingOrderTask.id == ShippingNotice.order_task_id,
).scalar_subquery()
notice_rows = (
_active_todo_tasks_scope(user_id, is_admin=is_admin)
.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
.with_entities(
category_expr.label("category"),
ot_stage_subquery.label("ot_stage"),
ot_reason_subquery.label("ot_reason"),
)
.all()
)
for category, ot_stage, ot_reason in notice_rows:
_bump(_classify_todo_lifecycle_stage(
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
))
# [STEP 4] OT 分支(库存准备尚未建正式 Notice)同理。
ot_category_expr = _order_task_todo_category_sql_expr()
ot_rows = (
_visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(ot_category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
.with_entities(
ot_category_expr.label("category"),
ShippingOrderTask.stage.label("ot_stage"),
ShippingOrderTask.pending_human_reason.label("ot_reason"),
)
.all()
)
for category, ot_stage, ot_reason in ot_rows:
_bump(_classify_todo_lifecycle_stage(
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
))
return counts
def list_my_todos(
user_id: int,
*,
@@ -2835,6 +2968,7 @@ def list_my_todos(
todo_category: str | None = None,
customer: str | None = None,
task_no: str | None = None,
terminal_kind: str | None = None,
) -> dict[str, Any]:
"""
分页列出「我的待办」:建单前 Review Case + 未建 OT Intake + 建单后 Task。
@@ -2851,6 +2985,7 @@ def list_my_todos(
todo_category: 可选细分类覆盖 bucket。
customer: 客户名/代码/来源文件名/Case 号/PO/Intake 号模糊过滤。
task_no: 精确任务号过滤(仅 Task 项;复核/Intake 项忽略)。
terminal_kind: done 桶终态子视图过滤(upload_complete | reject_void);其余 bucket 忽略。
Returns:
{items, page, page_size, total}
@@ -2869,6 +3004,7 @@ def list_my_todos(
customer_like = f"%{customer_needle}%" if customer_needle else ""
include_review_cases = "review" in allowed and not task_no
include_orphan_intakes = "intake_parse" in allowed and not task_no
normalized_terminal_kind = str(terminal_kind or "").strip().lower() or None
# [STEP 1] 多端投影为统一列:kind / entity_id / sort_at / sort_ref。
branches = []
@@ -2915,6 +3051,7 @@ def list_my_todos(
customer_needle=customer_needle,
customer_like=customer_like,
task_no=task_no,
terminal_kind=normalized_terminal_kind,
)
branches.append(
tasks_q.with_entities(
@@ -3053,14 +3190,17 @@ def list_my_todos(
}
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]:
"""
统计「我的待办」各 bucket 数量,供导航徽标使用。
统计「我的待办」各 bucket 数量,供导航徽标与阶段筛选 tab 使用。
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT。
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT;
阶段 tab 计数与 done 终态拆分见 _my_todo_stage_counts / done_counts 组装。
Returns:
{pending, processing, done, total_pending_badge}
{pending, processing, done, total_pending_badge,
stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload},
done_counts: {upload_complete, reject_void}}
"""
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
@@ -3077,7 +3217,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count()
processing = active.filter(category_expr == "in_progress").count()
processing += ot_active.filter(ot_category == "in_progress").count()
done = (
done_base = (
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(
db.or_(
@@ -3091,11 +3231,19 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
)
)
.filter(category_expr == "done")
.count()
)
done = done_base.count()
# done 拆分:已核验上传成功 vs 复核驳回/作废归档;分类 CASE 中上传成功优先,
# 故二者互斥,reject_void 用差值即无重叠计数。
done_upload = done_base.filter(upload_success).count()
return {
"pending": pending,
"processing": processing,
"done": done,
"total_pending_badge": pending,
"stage_counts": _my_todo_stage_counts(user_id, is_admin=is_admin),
"done_counts": {
"upload_complete": done_upload,
"reject_void": max(0, done - done_upload),
},
}
@@ -0,0 +1,227 @@
"""
backend/tests/test_shipping_done_line_report.py
用途:已完成通知明细行报表(done-lines)查询与专用导出的单测。
依赖:pytest、openpyxl、ShippingNotice/OT/Snapshot/Artifact 夹具、done_line_report。
逻辑:覆盖 12 字段映射(typed 列 + field_values_json 回源与回退)、可见性(非本人不可见、
未上传成功不进报表)、客户/料号/发货通知日期筛选、分页、导出表头与留空行为。
"""
from datetime import date, datetime, timedelta
import pytest
from openpyxl import load_workbook
from app.models import (
ShippingNotice,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
ShippingExportArtifact,
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
)
from app.services.shipping_notice.done_line_report import (
DONE_REPORT_HEADERS,
build_done_lines_xlsx,
list_done_notice_lines,
)
def _seed_report_fixture(db, *, owner: int):
"""最小报表夹具:一张已完成双行通知 + 一张仅 ready 未上传的通知(应被排除)。"""
order = ShippingOrderTask(task_no="OT-DONE-LINE", source_type="direct_pdf", user_id=owner)
pending_order = ShippingOrderTask(task_no="OT-DONE-LINE-PENDING", source_type="direct_pdf", user_id=owner)
notice = ShippingNotice(task_no="SN-DONE-LINE", source_type="manual", user_id=owner)
pending_notice = ShippingNotice(task_no="SN-DONE-LINE-PENDING", source_type="manual", user_id=owner)
db.session.add_all([order, pending_order, notice, pending_notice])
template = ShippingExcelTemplate(
template_code='DONELINE', display_name='DoneLine', version=1, status='published',
storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='DONELINE', display_name='DoneLine', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='DONELINE', display_name='DoneLine')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': []},
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
# 标准字段资产:约定出货日期(行级)与来源单号(表头级),值为 field_id 键 JSON。
db.session.add(ShippingOrderField(
id='f-req-date', field_code='required_date', scope='line', value_type='date',
field_category='order_line', collection_mode='deterministic_context',
asset_kind='system_standard', storage_mode='typed_column', storage_column='required_date',
))
db.session.add(ShippingOrderField(
id='f-source-order', field_code='source_order_number', scope='header', value_type='string',
field_category='order_header', collection_mode='deterministic_context',
asset_kind='system_standard', storage_mode='json_only',
))
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=1,
customer_name='HYVE CS', customer_code='HC001', customer_po_number='306085',
order_date=date(2026, 6, 1), required_date=date(2026, 6, 15),
header_values_json={'f-source-order': '8301-2606010052'},
)
db.session.add(snapshot)
db.session.flush()
db.session.add_all([
ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, line_no=1,
part_number='B3-A08AR10000017-A6', qty=80, unit_price=1525.08,
field_values_json={'f-req-date': '2026-06-15'},
),
ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=2, line_no=2,
part_number='D4-A08AR12000001', qty=1000, unit_price=898.72,
field_values_json={},
),
])
order.order_snapshot_id = snapshot.id
notice.order_task_id = order.id
extraction_two = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='e' * 64, status='accepted',
)
db.session.add(extraction_two)
db.session.flush()
pending_snapshot = ShippingOrderSnapshot(
task_id=pending_order.id, extraction_id=extraction_two.id, schema_version_id=version.id,
order_data_version=1,
customer_name='PENDING CS', customer_code='PC001',
)
db.session.add(pending_snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=pending_snapshot.id, position=1, line_no=1, part_number='X-1', qty=1,
))
pending_order.order_snapshot_id = pending_snapshot.id
pending_notice.order_task_id = pending_order.id
def add_artifact(target, *, artifact_no: str, status: str) -> None:
"""为 Notice 建立报表口径所需的最小 Artifact。"""
db.session.add(ShippingExportArtifact(
artifact_no=artifact_no, task_id=target.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
file_checksum='d' * 64, file_size=1, status=status,
))
add_artifact(notice, artifact_no='ART-DONE-LINE', status='uploaded')
add_artifact(pending_notice, artifact_no='ART-DONE-LINE-PENDING', status='ready')
db.session.commit()
return notice
def test_list_done_notice_lines_maps_standard_fields(app):
"""明细行平铺不按 OT 聚合;12 字段含 JSON 回源与表头回退,无数据源字段留空。"""
with app.app_context():
from app import db
owner = 88
_seed_report_fixture(db, owner=owner)
result = list_done_notice_lines(owner, page=1, page_size=20)
# 断言:仅 uploaded 通知进入报表;两行明细平铺,OT 不聚合。
assert result["total"] == 2
assert {item["line_no"] for item in result["items"]} == {1, 2}
first = next(item for item in result["items"] if item["line_no"] == 1)
# 断言:溯源编号 + 标准 12 字段映射。
assert first["task_no"] == "SN-DONE-LINE"
assert first["customer_name"] == "HYVE CS"
assert first["customer_code"] == "HC001"
assert first["order_date"] == "2026-06-01"
assert first["part_number"] == "B3-A08AR10000017-A6"
assert first["qty"] == 80.0
# 行级 field_values_json 有值时优先于快照表头 typed 列。
assert first["required_date"] == "2026-06-15"
assert first["customer_po_number"] == "306085"
assert first["source_order_number"] == "8301-2606010052"
assert first["unit_price"] == 1525.08
# 已用数量 / open qty 当前无数据源,契约留空。
assert first["used_qty"] is None
assert first["open_qty"] is None
second = next(item for item in result["items"] if item["line_no"] == 2)
# 断言:行级无 required_date 时回退快照表头 typed 列。
assert second["required_date"] == "2026-06-15"
assert second["source_order_number"] == "8301-2606010052"
# 断言:其他用户不可见(非管理员仅创建者)。
assert list_done_notice_lines(999)["total"] == 0
def test_list_done_notice_lines_filters_and_pagination(app):
"""客户/料号/发货通知日期筛选与按明细行分页生效。"""
with app.app_context():
from app import db
owner = 89
_seed_report_fixture(db, owner=owner)
# 客户模糊(大小写不敏感)。
assert list_done_notice_lines(owner, customer="hyve")["total"] == 2
assert list_done_notice_lines(owner, customer="不存在")["total"] == 0
# 料号模糊(命中单行)。
part_page = list_done_notice_lines(owner, part_number="B3-")
assert part_page["total"] == 1
assert part_page["items"][0]["part_number"] == "B3-A08AR10000017-A6"
# 发货通知日期范围:今天闭区间命中;未来区间为空。
today = datetime.utcnow().date()
assert list_done_notice_lines(
owner, notice_date_from=today.isoformat(), notice_date_to=today.isoformat(),
)["total"] == 2
tomorrow = (today + timedelta(days=1)).isoformat()
assert list_done_notice_lines(owner, notice_date_from=tomorrow)["total"] == 0
# 按明细行分页。
page_one = list_done_notice_lines(owner, page=1, page_size=1)
page_two = list_done_notice_lines(owner, page=2, page_size=1)
assert page_one["total"] == 2
assert {page_one["items"][0]["line_no"], page_two["items"][0]["line_no"]} == {1, 2}
def test_build_done_lines_xlsx_writes_fixed_twelve_columns(app):
"""导出严格 12 列标准格式:OT 编号不落列,无数据源列留空。"""
with app.app_context():
from app import db
owner = 90
_seed_report_fixture(db, owner=owner)
stream, filename = build_done_lines_xlsx(owner)
assert filename.startswith("done-lines-") and filename.endswith(".xlsx")
workbook = load_workbook(stream)
sheet = workbook.active
rows = list(sheet.iter_rows(values_only=True))
# 断言:表头为固定 12 列中文标准格式。
assert tuple(rows[0]) == DONE_REPORT_HEADERS
# 断言:两行明细,且不含 OT 编号列;数量/单价写数值,无数据源列留空。
assert len(rows) == 3
first_data = rows[1]
assert first_data[0] == "HYVE CS"
assert first_data[3] == 1
assert first_data[4] == "B3-A08AR10000017-A6"
assert first_data[5] == 80.0
assert first_data[8] is None
assert first_data[9] is None
assert first_data[10] == "8301-2606010052"
assert first_data[11] == 1525.08
@@ -0,0 +1,125 @@
"""
backend/tests/test_shipping_my_todo_stage_counts.py
用途:「我的待办」count 聚合扩展单测(阶段 tab 计数 + 已完成子终态拆分)。
依赖:pytest、ShippingNotice / ShippingOrderTask / Artifact 夹具、query_service.count_my_todos。
逻辑:覆盖 processing_stage 权威 / 人工原因归属 Gate / todo_category 兜底三路阶段归类;
done 桶拆分为已核验上传成功与 复核驳回/作废 两类终态计数。
"""
import pytest
from app.models import (
ShippingNotice,
ShippingOrderTask,
ShippingExportArtifact,
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderExtraction,
)
from app.services.shipping_notice.constants import RS_REJECTED
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
def test_count_my_todos_reports_stage_counts_and_done_breakdown(app):
"""阶段 tab 计数按权威口径归类;done 拆分为上传成功与驳回作废两类。"""
with app.app_context():
from app import db
owner = 77
# [STEP] 四个待处理条目分别覆盖三路归类路径:
# OT.stage 权威(waiting_review→订单复核)、原因映射(upload_rpa_failed→货代上传、
# inventory_source_unresolved→通知准备)、类别兜底(artifact ready 人工上传→货代上传)。
review_task = ShippingOrderTask(
task_no="OT-STAGE-REVIEW", stage="waiting_review",
source_type="direct_pdf", user_id=owner,
)
upload_rpa_task = ShippingOrderTask(
task_no="OT-STAGE-UPLOAD-RPA", pending_human_reason="upload_rpa_failed",
source_type="direct_pdf", user_id=owner,
)
inventory_task = ShippingOrderTask(
task_no="OT-STAGE-INVENTORY", pending_human_reason="inventory_source_unresolved",
source_type="direct_pdf", user_id=owner,
)
rejected_task = ShippingOrderTask(
task_no="OT-STAGE-REJECTED", review_status=RS_REJECTED,
source_type="direct_pdf", user_id=owner,
)
manual_task = ShippingOrderTask(
task_no="OT-STAGE-MANUAL", source_type="direct_pdf", user_id=owner,
)
manual_notice = ShippingNotice(task_no="SN-STAGE-MANUAL", source_type="manual", user_id=owner)
done_notice = ShippingNotice(task_no="SN-STAGE-DONE", source_type="manual", user_id=owner)
rejected_notice = ShippingNotice(task_no="SN-STAGE-REJECTED", source_type="manual", user_id=owner)
db.session.add_all([
review_task, upload_rpa_task, inventory_task, rejected_task, manual_task,
manual_notice, done_notice, rejected_notice,
])
template = ShippingExcelTemplate(
template_code='STAGE', display_name='Stage', version=1, status='published',
storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='STAGE', display_name='Stage', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='STAGE', display_name='Stage')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={},
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
manual_notice.order_task_id = manual_task.id
rejected_notice.order_task_id = rejected_task.id
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
file_checksum='d' * 64, file_size=1, status=status,
)
db.session.add(artifact)
return artifact
# 人工上传待登记(ready→manual_upload);已完成(uploaded→done/upload_complete);
# 驳回终态(ready 但 OT 复核驳回→done/reject_void)。
add_artifact(manual_notice, artifact_no='ART-STAGE-MANUAL', status='ready')
add_artifact(done_notice, artifact_no='ART-STAGE-DONE-UP', status='uploaded')
add_artifact(rejected_notice, artifact_no='ART-STAGE-REJ', status='ready')
db.session.commit()
counts = count_my_todos(owner)
# 断言:四个待处理条目按权威口径落入正确阶段 tab。
assert counts["pending"] == 4
assert counts["stage_counts"] == {
"intake_parse": 0,
"order_review": 1,
"fulfillment_prep": 1,
"freight_upload": 2,
}
# 断言:done 拆分——uploaded Artifact 计上传成功,OT 复核驳回计驳回作废。
assert counts["done"] == 2
assert counts["done_counts"] == {"upload_complete": 1, "reject_void": 1}
# 断言:terminal_kind 子视图过滤——两个终态子 tab 各自只取对应集合,互不重叠。
upload_page = list_my_todos(owner, bucket="done", terminal_kind="upload_complete")
assert {item["task_no"] for item in upload_page["items"]} == {"SN-STAGE-DONE"}
reject_page = list_my_todos(owner, bucket="done", terminal_kind="reject_void")
assert {item["task_no"] for item in reject_page["items"]} == {"SN-STAGE-REJECTED"}
# 无过滤参数时保持既有行为:done 全量。
assert list_my_todos(owner, bucket="done")["total"] == 2