""" services/shipping_notice/excel_template.py 用途:管理发货 Excel 模板草稿、映射定义、发布版本与受管模板文件。 依赖:openpyxl、ShippingExcelTemplate、订单字段目录、Flask 配置与统一业务异常。 逻辑:上传 xlsx 创建草稿;草稿可改定义;发布时验证工作表、字段引用和映射目标并计算不可变校验和。 """ from __future__ import annotations import hashlib import json import re import uuid from datetime import datetime from io import BytesIO from typing import Any from flask import current_app from openpyxl import load_workbook from openpyxl.utils import get_column_letter from werkzeug.datastructures import FileStorage from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, FreightRpaOnhandField, FreightRpaSource, ShippingOrderField, ) from app.services.file_assets.storage import file_asset_storage ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'constant'} ALLOWED_ROW_MODES = {'header', 'line'} ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'} ALLOWED_SYSTEM_FACTS = { 'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'notice_line_no', } def _storage_key(template_code: str, version: int) -> str: """构造长期私有模板对象键,与临时上传资产生命周期隔离。""" return f'shipping-excel-templates/{template_code}/v{version}/{uuid.uuid4().hex}.xlsx' def _checksum_json(value: Any) -> str: payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) return hashlib.sha256(payload.encode('utf-8')).hexdigest() def _payload(item: ShippingExcelTemplate) -> dict[str, Any]: """序列化模板元数据,绝不向管理端暴露服务器存储路径。""" return { 'id': item.id, 'template_code': item.template_code, 'display_name': item.display_name, 'version': item.version, 'status': item.status, 'original_filename': item.original_filename, 'file_checksum': item.file_checksum, 'definition': item.definition_json or {}, 'definition_checksum': item.definition_checksum, 'created_at': item.created_at.isoformat() if item.created_at else None, 'published_at': item.published_at.isoformat() if item.published_at else None, } def list_templates() -> list[dict[str, Any]]: """按编码和版本列出模板,供库存源绑定及草稿编辑。""" rows = ShippingExcelTemplate.query.order_by( ShippingExcelTemplate.template_code, ShippingExcelTemplate.version.desc(), ).all() return [_payload(item) for item in rows] def _next_version(template_code: str) -> int: latest = ShippingExcelTemplate.query.filter_by(template_code=template_code).order_by( ShippingExcelTemplate.version.desc(), ).first() return int(latest.version) + 1 if latest else 1 def create_draft(upload: FileStorage | None, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """ 上传模板文件并创建新草稿版本。 Args: upload: 必须为非空 xlsx 文件;宏工作簿和 CSV 不接受。 data: template_code、display_name 与 JSON definition。 actor_id: 当前管理员 ID。 """ code = str(data.get('template_code') or '').strip().upper() name = str(data.get('display_name') or '').strip() filename = str(getattr(upload, 'filename', '') or '').strip() if not code or not name or upload is None or not filename.lower().endswith('.xlsx'): raise ValidationError('template_code, display_name and xlsx file are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID') if not re.fullmatch(r'[A-Z0-9_-]{2,64}', code): raise ValidationError('template_code format is invalid', code='SHIPPING.EXCEL_TEMPLATE_INVALID') if ShippingExcelTemplate.query.filter_by(template_code=code, status='draft').count(): raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS') raw = upload.read() if not raw: raise ValidationError('Template file is empty', code='SHIPPING.EXCEL_TEMPLATE_INVALID') max_mb = max(int(current_app.config.get('SHIPPING_EXCEL_TEMPLATE_MAX_SIZE_MB') or 20), 1) if len(raw) > max_mb * 1024 * 1024: raise ValidationError('Template file exceeds size limit', code='SHIPPING.EXCEL_TEMPLATE_INVALID') try: workbook = load_workbook(BytesIO(raw), read_only=True) workbook.close() except Exception as exc: raise ValidationError('Template file is not a valid xlsx workbook', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc definition = data.get('definition') if isinstance(data.get('definition'), dict) else {} version = _next_version(code) storage_key = _storage_key(code, version) file_asset_storage.upload_bytes( storage_key=storage_key, data=raw, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) item = ShippingExcelTemplate( template_code=code, display_name=name, version=version, status='draft', storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename[:255], file_checksum=hashlib.sha256(raw).hexdigest(), definition_json=definition, created_by=actor_id, ) try: db.session.add(item) db.session.commit() except Exception: db.session.rollback() try: file_asset_storage.delete_object(storage_key) except Exception: pass raise return _payload(item) def update_draft(template_id: int, data: dict[str, Any]) -> dict[str, Any]: """更新草稿显示名称和映射定义;发布版本禁止原地修改。""" item = db.session.get(ShippingExcelTemplate, template_id) if item is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') if item.status != 'draft': raise ConflictError('Published template is immutable', code='SHIPPING.EXCEL_TEMPLATE_IMMUTABLE') name = str(data.get('display_name') or '').strip() definition = data.get('definition') if not name or not isinstance(definition, dict): raise ValidationError('display_name and definition are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID') item.display_name = name item.definition_json = definition db.session.commit() return _payload(item) def _workbook_layout(raw: bytes, definition: dict[str, Any]) -> dict[str, list[dict[str, Any]]]: """读取受管模板的工作表和首行栏位,供编辑器重新加载已保存文件的结构。""" workbook = load_workbook(BytesIO(raw), read_only=True, data_only=False) try: header_rows: dict[str, int] = {} for mapping in definition.get('mappings', []): if not isinstance(mapping, dict): continue sheet_name = str(mapping.get('sheet') or '') start_row = int(mapping.get('start_row') or 1) candidate_row = max(start_row - 1, 1) header_rows[sheet_name] = min(header_rows.get(sheet_name, candidate_row), candidate_row) layout: dict[str, list[dict[str, Any]]] = {} for sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] if sheet.max_column is None: sheet.calculate_dimension(force=True) header_row = header_rows.get(sheet_name, 1) max_column = int(sheet.max_column or 0) columns: list[dict[str, Any]] = [] for column_index in range(1, max_column + 1): value = sheet.cell(header_row, column_index).value column = get_column_letter(column_index) columns.append({'index': column_index, 'label': f'{column} - {value}' if value else column}) layout[sheet_name] = columns return layout finally: workbook.close() def get_layout(template_id: int) -> dict[str, Any]: """返回已保存模板的工作表和目标列信息,不要求用户重新上传文件。""" item = db.session.get(ShippingExcelTemplate, template_id) if item is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') raw = file_asset_storage.get_bytes(item.storage_key) if hashlib.sha256(raw).hexdigest() != item.file_checksum: raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') return {'template_id': item.id, 'sheets': _workbook_layout(raw, item.definition_json or {})} def create_draft_from_existing(template_id: int, *, actor_id: int | None) -> dict[str, Any]: """复制已保存模板文件和映射定义,创建可编辑的新草稿版本。""" source = db.session.get(ShippingExcelTemplate, template_id) if source is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') if source.status not in {'draft', 'published', 'retired'}: raise ConflictError('Template status cannot create a new version', code='SHIPPING.EXCEL_TEMPLATE_VERSION_INVALID') if ShippingExcelTemplate.query.filter_by(template_code=source.template_code, status='draft').count(): raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS') raw = file_asset_storage.get_bytes(source.storage_key) if hashlib.sha256(raw).hexdigest() != source.file_checksum: raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') version = _next_version(source.template_code) storage_key = _storage_key(source.template_code, version) file_asset_storage.upload_bytes( storage_key=storage_key, data=raw, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) item = ShippingExcelTemplate( template_code=source.template_code, display_name=source.display_name, version=version, status='draft', storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=source.original_filename, file_checksum=hashlib.sha256(raw).hexdigest(), definition_json=json.loads(json.dumps(source.definition_json or {}, ensure_ascii=False)), created_by=actor_id, ) try: db.session.add(item) db.session.commit() except Exception: db.session.rollback() try: file_asset_storage.delete_object(storage_key) except Exception: pass raise return _payload(item) def clone_as_new_template(template_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """复制任意已有模板为独立模板草稿,新编码从 v1 开始且不影响来源模板。""" source = db.session.get(ShippingExcelTemplate, template_id) if source is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') code = str(data.get('template_code') or '').strip().upper() name = str(data.get('display_name') or '').strip() if not code or not name or not re.fullmatch(r'[A-Z0-9_-]{2,64}', code): raise ValidationError('template_code and display_name are invalid', code='SHIPPING.EXCEL_TEMPLATE_INVALID') if ShippingExcelTemplate.query.filter_by(template_code=code).count(): raise ConflictError('Template code already exists', code='SHIPPING.EXCEL_TEMPLATE_CODE_EXISTS') raw = file_asset_storage.get_bytes(source.storage_key) if hashlib.sha256(raw).hexdigest() != source.file_checksum: raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') storage_key = _storage_key(code, 1) file_asset_storage.upload_bytes( storage_key=storage_key, data=raw, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) item = ShippingExcelTemplate( template_code=code, display_name=name, version=1, status='draft', storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=source.original_filename, file_checksum=hashlib.sha256(raw).hexdigest(), definition_json=json.loads(json.dumps(source.definition_json or {}, ensure_ascii=False)), created_by=actor_id, ) try: db.session.add(item) db.session.commit() except Exception: db.session.rollback() try: file_asset_storage.delete_object(storage_key) except Exception: pass raise return _payload(item) def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]: """验证模板定义、实际工作表和稳定字段引用,返回规范化定义。""" definition = item.definition_json if isinstance(item.definition_json, dict) else {} mappings = definition.get('mappings') filename_pattern = str(definition.get('filename_pattern') or '').strip() if not isinstance(mappings, list) or not mappings: raise ValidationError('Template mappings are required', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') # An empty published rule deliberately delegates naming to the controlled environment fallback. if filename_pattern: try: rendered_name = filename_pattern.format( task_no='TASK', business_no='BUSINESS', source_code='SOURCE', ts='20260101000000', date='20260101', customer_short_code='CUSTOMER', business_date='260602', sequence='01', ) except (KeyError, ValueError) as exc: raise ValidationError('Template filename_pattern is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc if not rendered_name.strip(): raise ValidationError('Template filename_pattern is empty', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') raw = file_asset_storage.get_bytes(item.storage_key) if hashlib.sha256(raw).hexdigest() != item.file_checksum: raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') wb = load_workbook(BytesIO(raw), read_only=True) sheet_names = set(wb.sheetnames) wb.close() published_field_ids: set[str] = set() if any(isinstance(mapping, dict) and mapping.get('source_kind') == 'order_field' for mapping in mappings): from app.services.shipping_notice.order_schema import service as order_schema_service published_field_ids = { str(field.get('field_id') or '') for field in order_schema_service.get_published_contract().get('fields', []) } normalized: list[dict[str, Any]] = [] seen_targets: set[tuple[str, str, int]] = set() for index, raw in enumerate(mappings): if not isinstance(raw, dict): raise ValidationError('Template mapping must be an object', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') sheet = str(raw.get('sheet') or '').strip() row_mode = str(raw.get('row_mode') or '').strip().lower() source_kind = str(raw.get('source_kind') or '').strip().lower() source_key = str(raw.get('source_key') or '').strip() formatter = str(raw.get('formatter') or 'text').strip().lower() try: start_row = int(raw.get('start_row')) target_column = int(raw.get('target_column')) except (TypeError, ValueError) as exc: raise ValidationError('Template target row and column must be integers', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc if sheet not in sheet_names or row_mode not in ALLOWED_ROW_MODES or source_kind not in ALLOWED_SOURCE_KINDS: raise ValidationError('Template mapping metadata is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID', details={'index': index}) if start_row < 1 or target_column < 1 or formatter not in ALLOWED_FORMATTERS: raise ValidationError('Template mapping target or formatter is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') if source_kind == 'order_field': field = db.session.get(ShippingOrderField, source_key) allowed_scopes = {'header'} if row_mode == 'header' else {'header', 'line'} if field is None or field.status != 'active' or field.scope not in allowed_scopes or field.id not in published_field_ids: raise ValidationError('Order field is invalid for mapping scope', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') elif source_kind == 'inventory_field': try: inventory_field_id = int(source_key) except (TypeError, ValueError) as exc: raise ValidationError('Inventory field is invalid', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') from exc inventory_field = db.session.get(FreightRpaOnhandField, inventory_field_id) if inventory_field is None or inventory_field.status != 'active': raise ValidationError('Inventory field is unavailable', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') source_key = str(inventory_field.id) elif source_kind == 'system_fact' and source_key not in ALLOWED_SYSTEM_FACTS: raise ValidationError('System fact is not allowed', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') elif source_kind != 'constant' and not source_key: raise ValidationError('source_key is required', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') target = (sheet, row_mode, target_column) if target in seen_targets: raise ValidationError('Duplicate template target column', code='SHIPPING.EXCEL_TEMPLATE_TARGET_DUPLICATE') seen_targets.add(target) normalized.append({ 'sheet': sheet, 'row_mode': row_mode, 'start_row': start_row, 'target_column': target_column, 'source_kind': source_kind, 'source_key': source_key, 'formatter': formatter, }) return {'filename_pattern': filename_pattern, 'mappings': normalized} def publish(template_id: int, *, actor_id: int | None) -> dict[str, Any]: """验证并发布模板版本;发布后文件和定义均不可变。""" item = db.session.get(ShippingExcelTemplate, template_id) if item is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') if item.status != 'draft': raise ConflictError('Only draft template can be published', code='SHIPPING.EXCEL_TEMPLATE_PUBLISH_INVALID') definition = _validate_definition(item) item.definition_json = definition item.definition_checksum = _checksum_json(definition) item.status = 'published' item.published_by = actor_id item.published_at = datetime.utcnow() db.session.commit() return _payload(item) def retire(template_id: int) -> dict[str, Any]: """退役不再供新库存源绑定的模板;现有产物引用保持不变。""" item = db.session.get(ShippingExcelTemplate, template_id) if item is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') if item.status != 'published': raise ConflictError('Only published template can be retired', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_INVALID') if FreightRpaSource.query.filter_by(excel_template_id=item.id).count(): raise ConflictError('Rebind inventory sources first', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED') item.status = 'retired' db.session.commit() return _payload(item) def delete_draft(template_id: int) -> None: """删除未发布草稿及其受管文件;已有 Artifact 的模板永远不可删除。""" item = db.session.get(ShippingExcelTemplate, template_id) if item is None: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') if item.status != 'draft' or ShippingExportArtifact.query.filter_by(template_id=item.id).count(): raise ConflictError('Only unused draft can be deleted', code='SHIPPING.EXCEL_TEMPLATE_DELETE_BLOCKED') storage_key = item.storage_key raw = file_asset_storage.get_bytes(storage_key) file_asset_storage.delete_object(storage_key) try: db.session.delete(item) db.session.commit() except Exception: db.session.rollback() file_asset_storage.upload_bytes( storage_key=storage_key, data=raw, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) raise