Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:30:09 +08:00
1 parent 85d27e9ffa
commit 91b7233872
812 files changed
+73763 -18908

No files matched your search

+212 -59
View File
@@ -4,7 +4,9 @@ services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
"""
@@ -29,16 +31,55 @@ from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
ShippingOrderTask,
ShippingCustomer,
)
from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
codes = [
str(row[0]).strip().upper()
for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).distinct().all()
if row[0]
]
return codes[0] if len(codes) == 1 else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
).distinct().all()
]
return ids[0] if len(ids) == 1 else None
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
"""
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
@@ -73,16 +114,7 @@ def _storage_root() -> Path:
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。"""
if notice.order_snapshot_id:
return notice
if notice.order_task_id:
source = ShippingNotice.query.filter(
ShippingNotice.order_task_id == int(notice.order_task_id),
ShippingNotice.order_snapshot_id.isnot(None),
).order_by(ShippingNotice.id.asc()).first()
if source is not None:
return source
"""返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。"""
return notice
@@ -90,7 +122,9 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task)
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
@@ -122,9 +156,10 @@ def _system_fact(
task: ShippingNotice,
key: str,
*,
export_sequence: int | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None,
) -> Any:
"""
@@ -133,18 +168,16 @@ def _system_fact(
Args:
task: 发货任务。
key: 系统事实键;仅允许白名单内键。
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
Returns:
对应系统事实值;未知键返回 None。
"""
values = {
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no,
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'warehouse_id': notice_line_warehouse_id,
'inventory_source_code': _notice_source_code(task),
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence,
'notice_line_no': notice_line_no,
}
return values.get(key)
@@ -164,6 +197,34 @@ def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bo
)
def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None:
"""
从表头可写的 Notice 行推导唯一 Warehouse ID。
核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头,
多库位冲突时失败,避免把某一行的库位误写到整单表头。
Args:
notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。
Returns:
唯一非空库位码;全部为空时返回 None。
Raises:
ValueError: 多行存在多个不同库位。
"""
warehouses = {
str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper()
for line in (notice_lines or [])
if str(getattr(line, 'inventory_warehouse_id', None) or '').strip()
}
if len(warehouses) > 1:
raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头')
if len(warehouses) == 1:
return next(iter(warehouses))
return None
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
@@ -191,9 +252,11 @@ def _format_value(value: Any, formatter: str) -> Any:
def _mapping_value(
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
header_values: dict[str, Any] | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> Any:
@@ -201,9 +264,7 @@ def _mapping_value(
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。
Args:
mapping: 已发布模板映射项。
@@ -211,7 +272,6 @@ def _mapping_value(
order_values: 当前行或表头订单字段值(field_id 为键)。
inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
Returns:
@@ -224,13 +284,7 @@ def _mapping_value(
field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no':
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no
value = resolve_order_line_no(
field_values=order_values,
field_id_by_code=field_id_by_code,
fallback_sequence=export_sequence,
)['value']
value = notice_line_no
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
@@ -238,13 +292,12 @@ def _mapping_value(
elif kind == 'system_fact':
value = _system_fact(
task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no,
notice_no=notice_no,
notice_line_no=notice_line_no,
notice_line_warehouse_id=notice_line_warehouse_id,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
else:
value = key
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
@@ -263,6 +316,50 @@ def _match_text(value: Any) -> str:
return str(value).strip().casefold()
def _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines: list[dict[str, Any]],
*,
inventory_field_keys: list[str],
wanted_keys: set[tuple[str, ...]],
) -> list[dict[str, Any]]:
"""
仅保留与本单导出行 match_keys 命中的库存行。
核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入
逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。
Args:
inventory_lines: 活动库存快照行。
inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。
wanted_keys: 本单导出行规范化后的键元组集合。
Returns:
子集库存行;无候选时为空列表。
"""
if not inventory_lines or not inventory_field_keys or not wanted_keys:
return []
return [
row for row in inventory_lines
if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys
]
def _wanted_order_match_keys(
order_lines: list[dict[str, Any]],
*,
order_field_ids: list[str],
) -> set[tuple[str, ...]]:
"""从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。"""
wanted: set[tuple[str, ...]] = set()
if not order_lines or not order_field_ids:
return wanted
for order_line in order_lines:
key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids)
if all(key):
wanted.add(key)
return wanted
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
@@ -447,13 +544,20 @@ def _filename(
if not pattern:
raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
customer_short_code = ''
if isinstance(owner, ShippingOrderTask):
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
facts = customer_resolution_facts(owner)
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
customer_short_code = str(getattr(customer, 'short_code', None) or '')
values = {
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no or task.task_no,
'source_code': task.inventory_source_code or '',
'source_code': _notice_source_code(task) or '',
'ts': now,
'date': now[:8],
'customer_short_code': task.customer_short_code_snapshot or '',
'customer_short_code': customer_short_code,
'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '',
'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '',
}
@@ -474,7 +578,7 @@ def _input_checksum(
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task),
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
'notice_id': notice_id,
}
@@ -499,24 +603,22 @@ def generate_shipment_excel(
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(task.inventory_source_code or '').strip().upper()
source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
# [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==None,
# 在严格全行 matched 前提下可退回到第一条 line_match 的 inventory_source_code(保证不绕过断言)。
first_match = db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).limit(1).first()
source_code_candidate = str(first_match[0]).strip().upper() if first_match and first_match[0] else ''
source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None
source = None
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
template = source.excel_template
@@ -528,13 +630,10 @@ def generate_shipment_excel(
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
raise ValueError('发货 Excel 模板没有已发布的字段映射')
# Fixed Sources receive task Warehouse ID from configuration; dynamic Sources
# resolve it only after Reservation ID + Part Number matches. This requirement
# applies only when the published template actually consumes that system fact.
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
@@ -590,7 +689,7 @@ def generate_shipment_excel(
)
except ConflictError:
raise
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
# [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。
line_values = []
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
if line.id not in available_line_ids:
@@ -598,12 +697,40 @@ def generate_shipment_excel(
row = dict(values)
row['__order_line_index'] = source_index
line_values.append(row)
for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
# [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part)
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all()
} if match_field_ids else {}
order_field_ids: list[str] = []
inventory_field_keys: list[str] = []
for item in match_keys:
if not isinstance(item, dict):
continue
inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip())
if not inv_key:
continue
order_field_ids.append(str(item.get('order_field_id') or ''))
inventory_field_keys.append(inv_key)
if order_field_ids and inventory_field_keys:
wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids)
inventory_lines = _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines,
inventory_field_keys=inventory_field_keys,
wanted_keys=wanted_keys,
)
release_overrides_by_line = _release_overrides_for_export_lines(
line_values=line_values,
release_overrides_by_source_line=release_overrides_by_source_line,
@@ -656,15 +783,32 @@ def generate_shipment_excel(
}
for sheet, start_row in data_start_rows.items():
_clear_template_data_rows(wb[sheet], start_row)
# [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。
notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
header_warehouse_id: str | None = None
header_warehouse_resolved = False
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
column = int(mapping['target_column'])
if mapping['row_mode'] == 'header':
# PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。
mapping_warehouse_id = None
if _template_requires_system_warehouse_id([mapping]):
if not header_warehouse_resolved:
header_warehouse_id = _unique_notice_warehouse_id(notice_lines)
header_warehouse_resolved = True
if not header_warehouse_id:
raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头')
mapping_warehouse_id = header_warehouse_id
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
notice_line_no=None,
notice_line_warehouse_id=mapping_warehouse_id,
field_id_by_code=field_id_by_code,
)
continue
@@ -675,7 +819,16 @@ def generate_shipment_excel(
ws.cell(start_row + index, column).value = _mapping_value(
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values,
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
notice_line_no=(
int(notice_lines[index].line_no)
if index < len(notice_lines) and notice_lines[index].line_no is not None
else None
),
notice_line_warehouse_id=(
notice_lines[index].inventory_warehouse_id
if index < len(notice_lines)
else None
),
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
@@ -691,7 +844,7 @@ def generate_shipment_excel(
artifact_no=artifact_no, task_id=task.id,
template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task),
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
notice_id=int(task.id),