feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

+332 -260
View File
@@ -1,311 +1,383 @@
"""
services/shipping_notice/export.py
用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。
依赖:openpyxl、app.models.ShippingTask、path_utils、task_line_store、Flask current_app 配置。
逻辑:由 fulfillment_workflow.generate_excel 调用本文件;订单行经 read_task_order_lines 读取。
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、动态订单 FieldValue、库存快照与 openpyxl。
逻辑:锁定 Source、模板、订单 Schema/Extraction、库存解析 Profile 和库存快照,按白名单映射写入模板。
"""
from __future__ import annotations
from datetime import datetime
import hashlib
import json
import uuid
from datetime import date, datetime
from decimal import Decimal
from pathlib import Path
from shutil import copy2
from typing import Any
from zoneinfo import ZoneInfo
from flask import current_app
from openpyxl import Workbook, load_workbook
from openpyxl import load_workbook
from sqlalchemy import update
from app.models import ShippingTask
from app.path_utils import backend_dir, resolve_backend_relative_path
from app.services.shipping_notice.task_line_store import read_task_order_lines
DEFAULT_HEADERS = [
"客户名称",
"客户代码",
"收货地址",
"要求交期",
"料号",
"发货数量",
"单位",
"备注",
]
HEADER_SHEET = "PVMI Pull Request Header"
DETAIL_SHEET = "PVMI Pull Request Detail"
DATA_START_ROW = 4
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderExtraction,
ShippingOrderFieldValue,
ShippingTask,
)
from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _storage_root() -> Path:
"""发货通知文件存储根目录(exports/notice_uploads/inventory_uploads 的父路径)。"""
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
if root:
return Path(resolve_backend_relative_path(root))
return Path(current_app.instance_path) / "shipping_notice"
def _default_template_path() -> Path | None:
configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip()
"""返回发货通知文件根目录。"""
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
if configured:
path = Path(resolve_backend_relative_path(configured))
if path.is_file():
return path
bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx"
return bundled if bundled.is_file() else None
return Path(resolve_backend_relative_path(configured))
return Path(current_app.instance_path) / 'shipping_notice'
def _is_pvmi_workbook(wb) -> bool:
return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames
def _format_delivery_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
try:
parsed = datetime.strptime(text[:10], fmt)
return parsed.strftime("%m/%d/%Y")
except ValueError:
continue
if len(text) >= 10 and text[4] == "-" and text[7] == "-":
try:
parsed = datetime.strptime(text[:10], "%Y-%m-%d")
return parsed.strftime("%m/%d/%Y")
except ValueError:
pass
return text
def _delivery_date_for_task(task: ShippingTask) -> str:
if task.required_date:
formatted = _format_delivery_date(task.required_date)
if formatted:
return formatted
for line in read_task_order_lines(task):
formatted = _format_delivery_date(line.get("required_date"))
if formatted:
return formatted
return ""
def _resolve_odm_id(task: ShippingTask) -> str:
"""
按订单内部料号与 Reservation 定位当前库存投影中的 ODM ID。
核心逻辑:订单与库存统一按 part_number + reservation_id 配对。
Args:
task: 已关联库存快照的发货任务。
Returns:
首个匹配库存行的 ODM ID;未命中时回退库存中的首个非空值。
"""
notice_lines = read_task_order_lines(task)
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
if not inventory_lines:
return ""
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = (
str(row.get("part_number") or "").strip(),
str(row.get("reservation_id") or "").strip(),
)
inv_by_key[key] = row
for line in notice_lines:
key = (
str(line.get("part_number") or "").strip(),
str(line.get("reservation_id") or "").strip(),
)
matched = inv_by_key.get(key)
if matched:
odm_id = str(matched.get("odm_id") or "").strip()
if odm_id:
return odm_id
for row in inventory_lines:
odm_id = str(row.get("odm_id") or "").strip()
if odm_id:
return odm_id
return ""
def _shipment_warehouse_id(task: ShippingTask) -> str:
"""
解析发货 Excel Header 的 Warehouse ID。
核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。
"""
try:
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
snapshot = serialize_inventory_snapshot_link(task)
except Exception:
snapshot = None
if isinstance(snapshot, dict):
value = str(snapshot.get("warehouse_id") or "").strip()
if value:
def _typed_value(item: ShippingOrderFieldValue) -> Any:
"""从类型化投影读取唯一业务值,禁止回退旧任务固定列。"""
for value in (
item.value_text, item.value_decimal, item.value_integer,
item.value_date, item.value_boolean, item.value_json,
):
if value is not None:
return value
return "AWSDU"
return None
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("po_number"), task.po_number):
text = str(value or "").strip()
if text:
return text
return ""
def _order_values(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""将稳定 field_id 投影为 Header 字典及按订单行 position 排序的字典列表。"""
header: dict[str, Any] = {}
line_positions = {line.id: line.position for line in extraction.lines}
lines: dict[int, dict[str, Any]] = {position: {} for position in line_positions.values()}
for item in extraction.values:
value = _typed_value(item)
if item.line_id is None:
header[item.field_id] = value
elif item.line_id in line_positions:
lines[line_positions[item.line_id]][item.field_id] = value
return header, [lines[position] for position in sorted(lines)]
def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("currency"), getattr(task, "currency", None)):
text = str(value or "").strip().upper()
if text:
return text
return ""
def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""读取任务当前已接受订单解析,并按稳定字段 ID 返回 Header 与明细值。"""
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于库存匹配的订单解析版本')
return _order_values(extraction)
def _line_part_number(line: dict[str, Any]) -> str:
"""返回货代明细使用的内部料号。"""
return str(line.get("part_number") or "").strip()
def _system_fact(task: ShippingTask, key: str) -> Any:
"""读取受控任务事实,模板不能通过任意属性路径访问 ORM。"""
values = {
'task_no': task.task_no,
'business_no': task.shipping_case.business_no if task.shipping_case else None,
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
}
return values.get(key)
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
if ws.max_row < from_row:
return
for row_idx in range(from_row, ws.max_row + 1):
for col_idx in range(1, ws.max_column + 1):
ws.cell(row_idx, col_idx).value = None
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
return ''
if formatter == 'upper':
return str(value).upper()
if formatter == 'lower':
return str(value).lower()
if formatter == 'date_mmddyyyy':
if isinstance(value, (date, datetime)):
return value.strftime('%m/%d/%Y')
text = str(value).strip()
for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d', '%m/%d/%Y'):
try:
return datetime.strptime(text[:10], pattern).strftime('%m/%d/%Y')
except ValueError:
continue
return text
if formatter == 'integer':
return int(Decimal(str(value)))
if formatter == 'decimal':
return float(Decimal(str(value)))
return str(value) if isinstance(value, (Decimal, date, datetime)) else value
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
"""将业务号作为货代主引用写入 PVMI 模板,技术任务号仍用于系统追踪和文件名。"""
wb = load_workbook(filename=str(path))
header_ws = wb[HEADER_SHEET]
detail_ws = wb[DETAIL_SHEET]
_clear_sheet_data_rows(detail_ws)
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task)
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
header_ws.cell(DATA_START_ROW, 2).value = "n"
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
header_ws.cell(DATA_START_ROW, 3).value = "WEL"
if header_ws.cell(DATA_START_ROW, 4).value in (None, ""):
header_ws.cell(DATA_START_ROW, 4).value = "normal"
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
business_ref = task.shipping_case.business_no if task.shipping_case and task.shipping_case.business_no else task.task_no
header_ws.cell(DATA_START_ROW, 7).value = business_ref
notice_lines = read_task_order_lines(task)
if not notice_lines:
notice_lines = [{}]
for index, line in enumerate(notice_lines, start=1):
row_idx = DATA_START_ROW + index - 1
line_no = str(line.get("line_no") or index).strip()
qty = line.get("qty")
amount = line.get("amount")
detail_ws.cell(row_idx, 1).value = business_ref
detail_ws.cell(row_idx, 2).value = line_no
detail_ws.cell(row_idx, 4).value = _line_part_number(line)
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
detail_ws.cell(row_idx, 11).value = _line_currency(task, line)
wb.save(path)
def _mapping_value(
mapping: dict[str, Any], *, task: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None,
) -> Any:
"""按映射来源类型读取值;未知来源已在模板发布时被拒绝。"""
kind = mapping['source_kind']
key = mapping['source_key']
if kind == 'order_field':
value = order_values.get(key)
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':
value = inventory_values.get(str(key))
elif kind == 'system_fact':
value = _system_fact(task, key)
else:
value = key
return _format_value(value, mapping['formatter'])
def _row_values(task: ShippingTask, line: dict | None) -> list:
line = line or {}
return [
task.customer_name or "",
task.customer_code or "",
task.ship_to or "",
task.required_date or "",
line.get("part_number") or "",
line.get("qty") or "",
line.get("uom") or "EA",
line.get("remark") or "",
]
def _match_text(value: Any) -> str:
"""规范化订单与库存匹配键;仅做确定性文本比较,不进行模糊推断。"""
if value is None:
return ''
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
return str(value).strip().casefold()
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
"""填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。"""
wb = load_workbook(filename=str(path))
ws = wb.active
lines = read_task_order_lines(task) or [None]
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
ws.append(DEFAULT_HEADERS)
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
str(item['source_key']) for item in mappings
if item.get('row_mode') == row_mode and item.get('source_kind') == 'inventory_field'
}
ids = {int(item) for item in raw_ids if item.isdigit()}
if len(ids) != len(raw_ids):
raise ValueError('发货模板引用的库存字段无效')
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
).all() if ids else []
if len(rows) != len(ids):
raise ValueError('发货模板引用的库存字段已不存在')
return {str(item.id) for item in rows}
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
"""生成无模板工作簿;技术任务号继续保留在导出文件名与系统记录中。"""
wb = Workbook()
ws = wb.active
ws.title = "Shipment"
ws.append(DEFAULT_HEADERS)
lines = read_task_order_lines(task) or [None]
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
if not rows:
return {}
resolved = dict(rows[0])
for field in required_fields:
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
if len(values) > 1:
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
if values:
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
return resolved
def _sanitize_filename(name: str) -> str:
cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."})
return cleaned or "shipment.xlsx"
def _match_inventory_lines(
order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]],
match_keys: list[dict[str, str]], required_fields: set[str],
) -> list[dict[str, Any]]:
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
if not order_lines:
return []
if not match_keys:
raise ValueError('库存解析模板缺少订单与库存匹配键')
from app.models import ShippingInventoryField
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_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
result: list[dict[str, Any]] = []
for position, order_line in enumerate(order_lines, start=1):
expected = [
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
for item in normalized_keys
]
if any(not value for value, _field in expected):
raise ValueError(f'第 {position} 条订单行缺少库存匹配键值')
matched = [
row for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
]
if not matched:
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
result.append(_collapse_inventory_matches(matched, required_fields))
return result
def _export_filename(task: ShippingTask, ts: str) -> str:
pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip()
if not pattern:
pattern = "shipment_{task_no}_{ts}.xlsx"
def _header_inventory_values(
matched_lines: list[dict[str, Any]], required_fields: set[str],
) -> dict[str, Any]:
"""Header 库存字段必须在所有订单行匹配结果中一致,否则不能生成单一 Header。"""
return _collapse_inventory_matches(matched_lines, required_fields)
def _safe_filename(name: str) -> str:
"""清理配置化文件名,防止路径穿越并强制 xlsx 扩展名。"""
cleaned = ''.join(ch for ch in name if ch.isalnum() or ch in {'-', '_', '.'}).strip('.')
cleaned = cleaned or 'shipment.xlsx'
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
"""按发布规则生成下载名,业务单变量始终取已锁定的客户与编号快照。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '')
now = datetime.utcnow().strftime('%Y%m%d%H%M%S')
shipping_case = task.shipping_case
values = {
'task_no': task.task_no,
'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no,
'source_code': task.inventory_source_code or '',
'ts': now,
'date': now[:8],
'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '',
'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '',
'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '',
}
try:
name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8])
except Exception:
name = f"shipment_{task.task_no}_{ts}.xlsx"
if not str(name).lower().endswith(".xlsx"):
name = f"{name}.xlsx"
return _sanitize_filename(str(name))
return _safe_filename(pattern.format(**values))
except (KeyError, ValueError) as exc:
raise ValueError('发货 Excel 文件名规则无效') from exc
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
def _input_checksum(
task: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate,
extraction: ShippingOrderExtraction, header: dict[str, Any], lines: list[dict[str, Any]],
) -> str:
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
payload = {
'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': extraction.schema_version_id, 'extraction_id': extraction.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExportArtifact]:
"""
基于任务数据生成货代发货 Excel 并写入 exports 目录。
【AI 触发时机】:由 generate_excel Tool 调用;Agent 禁止直接操作文件系统。
核心逻辑:复制 PVMI/legacy 模板 → 填充 Header/Detail 或 legacy 行 → 返回 (绝对路径, 文件名)。
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
Returns:
tuple[str, str]: (export_file_path, export_file_name)。
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
"""
root = _storage_root() / "exports"
root.mkdir(parents=True, exist_ok=True)
source_code = str(task.inventory_source_code or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
# Fixed Sources receive this value from configuration; dynamic Sources receive it
# only after Reservation ID + Part Number resolves a unique inventory Warehouse.
if not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
template = source.excel_template
if template is None or template.status != 'published':
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
raise ValueError('库存源未绑定已发布的库存解析模板')
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于导出的订单解析版本')
header_values, line_values = _order_values(extraction)
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
definition = template.definition_json or {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
raise ValueError('发货 Excel 模板没有已发布的字段映射')
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
matched_inventory_lines = _match_inventory_lines(
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
ts = datetime.utcnow().strftime("%Y%m%d%H%M%S")
filename = _export_filename(task, ts)
path = root / filename
template = _default_template_path()
if template:
copy2(template, path)
wb = load_workbook(filename=str(path), read_only=True)
filename = _filename(task, template)
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
directory.mkdir(parents=True, exist_ok=True)
path = directory / f'{artifact_no}_{filename}'
template_bytes = file_asset_storage.get_bytes(template.storage_key)
if hashlib.sha256(template_bytes).hexdigest() != template.file_checksum:
raise ValueError('发货 Excel 模板文件缺失或校验失败')
try:
path.write_bytes(template_bytes)
wb = load_workbook(path)
try:
is_pvmi = _is_pvmi_workbook(wb)
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
column = int(mapping['target_column'])
if mapping['row_mode'] == 'header':
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
)
continue
row_count = max(len(line_values), 1)
for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1):
ws.cell(row_index, column).value = None
for index in range(row_count):
order_line = line_values[index] if index < len(line_values) else {}
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
ws.cell(start_row + index, column).value = _mapping_value(
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values,
)
wb.save(path)
finally:
wb.close()
if is_pvmi:
_fill_pvmi_template(task, path)
else:
_fill_legacy_template(task, path)
else:
_fill_blank_workbook(task, path)
return str(path), filename
content = path.read_bytes()
db.session.execute(
update(ShippingExportArtifact)
.where(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status == 'ready',
)
.values(status='superseded')
)
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
order_schema_version_id=extraction.schema_version_id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
input_checksum=_input_checksum(task, source, template, extraction, header_values, line_values),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
db.session.add(artifact)
db.session.flush()
return str(path), filename, artifact
except Exception:
if path.is_file():
path.unlink()
raise