feat(rpa): 收料配置与库存同构并统一站点启停
- 删除收料配置 enabled 与 warehouse_ids_json 列(迁移 rc1a2b3c4d5e、rc2b3c4d5e6f,含存量清单转 Warehouse 条件的数据保全) - Warehouse 改为查询条件(多值即逐仓拆分维度),排程/按需触发运行时派生仓库清单并在单元快照剥离该条件 - 站点开关即总开关:四处收料门禁只看站点 enabled;校验要求 DBS 恰一条非空 Warehouse 条件,日期禁填不变 - 站点抽屉改纵向折叠卡片与统一「保存更改」,就绪卡压缩为单行状态条并下移 - technical.md 同步设计边界与接口契约
This commit is contained in:
1 parent
eed1068ae3
commit
2199370065
18 files changed
+412
-223
No files matched your search
@@ -29,7 +29,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
inventory_source_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
|
||||
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
|
||||
@@ -40,10 +40,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
|
||||
warehouse_ids_json: Mapped[list[str]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
|
||||
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
|
||||
return dict(value)
|
||||
|
||||
|
||||
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
|
||||
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
|
||||
value = data.get(field, [])
|
||||
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
||||
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
result: list[str] = []
|
||||
for item in value:
|
||||
normalized = item.strip()
|
||||
if normalized and normalized not in result:
|
||||
result.append(normalized)
|
||||
return result
|
||||
|
||||
|
||||
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
|
||||
value = data.get('login_config_json', {})
|
||||
@@ -269,19 +256,18 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
return {
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
|
||||
'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
|
||||
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
|
||||
enabled = _bool(data, 'enabled', True)
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
@@ -289,19 +275,22 @@ def _validate_receipt_report_config(
|
||||
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
|
||||
raw_path = _json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
if enabled and not raw_warehouses:
|
||||
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
return enabled, path, parameters, raw_warehouses
|
||||
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
|
||||
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
|
||||
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
|
||||
if len(warehouse_conditions) != 1 or not any(warehouse_values):
|
||||
raise ValidationError(
|
||||
'DBS receipt report requires exactly one Warehouse query condition with values',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if raw_warehouses:
|
||||
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
@@ -309,7 +298,7 @@ def _validate_receipt_report_config(
|
||||
'Crane receipt report does not support query parameters',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return enabled, {'report_name': 'Inbound Details'}, [], []
|
||||
return {'report_name': 'Inbound Details'}, []
|
||||
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
@@ -327,7 +316,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
|
||||
path, parameters = _validate_receipt_report_config(source, data)
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
|
||||
before = _receipt_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
@@ -337,10 +326,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.enabled = enabled
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.warehouse_ids_json = warehouses
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
|
||||
@@ -40,7 +40,7 @@ class ShippingReceiptFileRepository:
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
return None
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is None or config.parsing_profile_id is None:
|
||||
return None
|
||||
profile = config.parsing_profile
|
||||
|
||||
@@ -24,23 +24,25 @@ def _build_trigger_unit(
|
||||
) -> dict[str, Any]:
|
||||
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RuntimeError(f'source not enabled: {source_code}')
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is None:
|
||||
raise RuntimeError(f'receipt config missing: {source_code}')
|
||||
profile = source.rpa_profile
|
||||
if profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
|
||||
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
|
||||
warehouse_id = str(warehouses[0]) if warehouses else None
|
||||
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version,
|
||||
'connector_type': source.connector_type,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'query_parameters_json': receipt_unit_parameters(config),
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
|
||||
|
||||
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
|
||||
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
|
||||
@@ -28,7 +28,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
|
||||
wanted = _wanted_source_codes(task)
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
).filter(ShippingInventorySource.enabled.is_(True)).all()
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': receipt_unit_parameters(config),
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
@@ -78,7 +78,8 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
for source, config in _eligible_sources(task):
|
||||
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
|
||||
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
|
||||
unit.schedule_run_id = run.id
|
||||
|
||||
@@ -57,7 +57,7 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
).filter(ShippingInventorySource.enabled.is_(True)).all()
|
||||
return [{
|
||||
'label': source.display_name or source.source_code, 'value': source.source_code,
|
||||
'description': f'{source.connector_type} · 收料已配置',
|
||||
|
||||
@@ -914,14 +914,12 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'snapshot_after_ref',
|
||||
'path_id_hash',
|
||||
'revision_no',
|
||||
# 独立收料报表配置快照:路径、受控条件与仓库清单均不含 selector、凭据或日期筛选。
|
||||
# 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。
|
||||
'inventory_source_id',
|
||||
'connector_type',
|
||||
'enabled',
|
||||
'config_version',
|
||||
'report_path_json',
|
||||
'query_parameters_json',
|
||||
'warehouse_ids_json',
|
||||
'file_id',
|
||||
'recipient_user_id',
|
||||
'message_type',
|
||||
|
||||
@@ -18,6 +18,35 @@ def receipt_trigger_dir() -> Path | None:
|
||||
return Path(value) if value else None
|
||||
|
||||
|
||||
def receipt_warehouse_values(config: Any) -> list[str]:
|
||||
"""从收料配置的查询条件中提取 Warehouse 条件值(去空去重,保持顺序)。
|
||||
|
||||
Warehouse 条件即逐仓拆分维度(与库存配置同构,不单独持久化仓库清单);
|
||||
排程/触发按返回值逐仓展开执行单元。DBS 配置由校验保证恰一条非空条件。
|
||||
"""
|
||||
values: list[str] = []
|
||||
for item in (config.query_parameters_json or []):
|
||||
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
|
||||
continue
|
||||
for raw in (item.get('values') or []):
|
||||
cleaned = str(raw or '').strip()
|
||||
if cleaned and cleaned not in values:
|
||||
values.append(cleaned)
|
||||
return values
|
||||
|
||||
|
||||
def receipt_unit_parameters(config: Any) -> list[dict[str, Any]]:
|
||||
"""构建单个执行单元的受控条件:剥离 Warehouse 条件。
|
||||
|
||||
Worker 会按单元的 warehouse_id 自动追加单值 Warehouse 条件,
|
||||
快照里保留用户维护的 Warehouse 条件会与之重复冲突。
|
||||
"""
|
||||
return [
|
||||
dict(item) for item in (config.query_parameters_json or [])
|
||||
if not (isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse')
|
||||
]
|
||||
|
||||
|
||||
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
|
||||
trigger_dir = receipt_trigger_dir()
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
backend/migrations/versions/rc1a2b3c4d5e_drop_receipt_config_enabled.py
|
||||
|
||||
用途:删除收料报表配置的独立 enabled 列,站点启停即库存+收料统一开关。
|
||||
依赖:Alembic revision dd22ee33ff44;shipping_receipt_report_configs 已存在。
|
||||
逻辑:收料是否运行改为只看库存站点 enabled 与配置是否存在;四处后端门禁同步去掉该列过滤。
|
||||
|
||||
Revision ID: rc1a2b3c4d5e
|
||||
Revises: dd22ee33ff44
|
||||
Create Date: 2026-09-18 11:30:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "rc1a2b3c4d5e"
|
||||
down_revision = "dd22ee33ff44"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""删除 shipping_receipt_report_configs.enabled;启用语义统一归属库存站点。"""
|
||||
op.drop_column("shipping_receipt_report_configs", "enabled")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复 enabled 列并统一置 true;历史双开关状态无法无损还原。"""
|
||||
op.add_column(
|
||||
"shipping_receipt_report_configs",
|
||||
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
backend/migrations/versions/rc2b3c4d5e6f_drop_receipt_warehouse_list.py
|
||||
|
||||
用途:删除收料配置的 warehouse_ids_json 列,仓库清单改为查询条件中的 Warehouse 条件。
|
||||
依赖:Alembic revision rc1a2b3c4d5e;shipping_receipt_report_configs 与 shipping_inventory_sources 已存在。
|
||||
逻辑:升级时先把存量 DBS 配置的仓库清单注入为一条 Warehouse 查询条件(数据保全)再删列;
|
||||
降级时从 Warehouse 条件反提清单尽力恢复,条件本身保留。
|
||||
|
||||
Revision ID: rc2b3c4d5e6f
|
||||
Revises: rc1a2b3c4d5e
|
||||
Create Date: 2026-09-18 12:20:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "rc2b3c4d5e6f"
|
||||
down_revision = "rc1a2b3c4d5e"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _as_list(raw: Any) -> list:
|
||||
"""把 JSON 列读成 list;驱动可能返回 list 或字符串。"""
|
||||
if raw is None:
|
||||
return []
|
||||
if isinstance(raw, list):
|
||||
return list(raw)
|
||||
if isinstance(raw, str):
|
||||
text = raw.strip()
|
||||
if not text:
|
||||
return []
|
||||
loaded = json.loads(text)
|
||||
return list(loaded) if isinstance(loaded, list) else []
|
||||
return []
|
||||
|
||||
|
||||
def _warehouse_values(parameters: list) -> list[str]:
|
||||
"""提取查询条件里的 Warehouse 值(去空去重,保持顺序)。"""
|
||||
values: list[str] = []
|
||||
for item in parameters:
|
||||
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
|
||||
continue
|
||||
for value in (item.get('values') or []):
|
||||
cleaned = str(value or '').strip()
|
||||
if cleaned and cleaned not in values:
|
||||
values.append(cleaned)
|
||||
return values
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""先把存量 DBS 仓库清单转为 Warehouse 查询条件,再删除 warehouse_ids_json 列。"""
|
||||
conn = op.get_bind()
|
||||
rows = conn.execute(sa.text(
|
||||
"SELECT c.id, c.query_parameters_json, c.warehouse_ids_json"
|
||||
" FROM shipping_receipt_report_configs c"
|
||||
" JOIN shipping_inventory_sources s ON s.id = c.inventory_source_id"
|
||||
" WHERE s.connector_type = 'dbs'"
|
||||
)).mappings().all()
|
||||
for row in rows:
|
||||
parameters = _as_list(row['query_parameters_json'])
|
||||
warehouses = [str(v or '').strip() for v in _as_list(row['warehouse_ids_json']) if str(v or '').strip()]
|
||||
has_warehouse_condition = any(
|
||||
isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse'
|
||||
for item in parameters
|
||||
)
|
||||
if warehouses and not has_warehouse_condition:
|
||||
parameters.append({
|
||||
'name': 'Warehouse', 'mode': 'single' if len(warehouses) == 1 else 'multi_text',
|
||||
'values': warehouses, 'required': False, 'select_all': False,
|
||||
})
|
||||
conn.execute(
|
||||
sa.text("UPDATE shipping_receipt_report_configs SET query_parameters_json = CAST(:params AS JSON) WHERE id = :id"),
|
||||
{'params': json.dumps(parameters), 'id': row['id']},
|
||||
)
|
||||
op.drop_column('shipping_receipt_report_configs', 'warehouse_ids_json')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复 warehouse_ids_json 列并从 Warehouse 条件尽力反提;条件本身保留。"""
|
||||
op.add_column(
|
||||
'shipping_receipt_report_configs',
|
||||
sa.Column('warehouse_ids_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'")),
|
||||
)
|
||||
conn = op.get_bind()
|
||||
rows = conn.execute(sa.text(
|
||||
"SELECT c.id, c.query_parameters_json"
|
||||
" FROM shipping_receipt_report_configs c"
|
||||
" JOIN shipping_inventory_sources s ON s.id = c.inventory_source_id"
|
||||
" WHERE s.connector_type = 'dbs'"
|
||||
)).mappings().all()
|
||||
for row in rows:
|
||||
warehouses = _warehouse_values(_as_list(row['query_parameters_json']))
|
||||
if warehouses:
|
||||
conn.execute(
|
||||
sa.text("UPDATE shipping_receipt_report_configs SET warehouse_ids_json = CAST(:warehouses AS JSON) WHERE id = :id"),
|
||||
{'warehouses': json.dumps(warehouses), 'id': row['id']},
|
||||
)
|
||||
@@ -22,9 +22,9 @@ def receipt_source():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
assert source is not None
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[], warehouse_ids_json=[],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
|
||||
)
|
||||
from app import db
|
||||
|
||||
@@ -51,6 +51,8 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
assert result['callback_id']
|
||||
assert result['trigger_path'].endswith('.json')
|
||||
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
|
||||
# 关键断言:按需触发取 Warehouse 条件的第一个仓作为拆分维度。
|
||||
assert calls['units'][0]['warehouse_id'] == 'AWSDU'
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
|
||||
|
||||
@@ -29,15 +29,16 @@ def _create_users() -> None:
|
||||
|
||||
|
||||
def _dbs_payload() -> dict:
|
||||
"""构造 DBS 收料配置;日期未出现表示保持系统页面默认 NULL。"""
|
||||
"""构造 DBS 收料配置;Warehouse 条件即逐仓拆分维度,日期未出现表示保持系统页面默认 NULL。"""
|
||||
return {
|
||||
'enabled': True,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
},
|
||||
'warehouse_ids_json': ['AWSDU', 'AWSDU-02'],
|
||||
'query_parameters_json': [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}],
|
||||
'query_parameters_json': [
|
||||
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU', 'AWSDU-02'], 'required': False, 'select_all': False},
|
||||
{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +66,9 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
assert config['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
# 关键断言:Warehouse 条件原样保存,作为逐仓拆分维度的唯一持久化位置。
|
||||
warehouse_condition = next(item for item in config['query_parameters_json'] if item['name'] == 'Warehouse')
|
||||
assert warehouse_condition['values'] == ['AWSDU', 'AWSDU-02']
|
||||
assert config['report_path_json']['report_group'] == 'Inbound'
|
||||
|
||||
with app.app_context():
|
||||
@@ -78,7 +81,7 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).one()
|
||||
assert audit.before_snapshot_json is None
|
||||
assert audit.after_snapshot_json['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02']
|
||||
|
||||
|
||||
def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client):
|
||||
@@ -120,9 +123,40 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
# 关键断言:Warehouse 条件即逐仓拆分维度——缺失、重复、空值都必须拒绝。
|
||||
missing_warehouse = _dbs_payload()
|
||||
missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=missing_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
duplicate_warehouse = _dbs_payload()
|
||||
duplicate_warehouse['query_parameters_json'] = [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU-02'], 'required': False, 'select_all': False},
|
||||
]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=duplicate_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
empty_warehouse = _dbs_payload()
|
||||
empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=empty_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_crane = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Other Report'},
|
||||
'warehouse_ids_json': ['NOT-ALLOWED'], 'query_parameters_json': [],
|
||||
'report_path_json': {'report_name': 'Other Report'},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
@@ -153,7 +187,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
crane_id = crane_source.id
|
||||
|
||||
default_query = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Inbound Details'}, 'warehouse_ids_json': [],
|
||||
'report_path_json': {'report_name': 'Inbound Details'},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
|
||||
@@ -19,9 +19,9 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
|
||||
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, enabled=True, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, warehouse_ids_json=['A', 'B']),])
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}]),])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, enabled=True, report_path_json={'report_name': 'Inbound Details'}, warehouse_ids_json=[]))
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[]))
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]})
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
|
||||
@@ -45,10 +45,12 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
|
||||
}
|
||||
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
|
||||
assert dbs_unit['warehouse_id'] == 'A'
|
||||
# 关键断言:单元快照必须剥离 Warehouse 条件,Worker 才能按 warehouse_id 自动追加不重复。
|
||||
assert all(item['name'] != 'Warehouse' for item in dbs_unit['query_parameters_json'])
|
||||
|
||||
|
||||
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
"""动态排程选项只暴露库存站点已启用且收料配置也启用的站点。"""
|
||||
"""动态排程选项只暴露库存站点已启用且已配置收料的站点。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
@@ -56,9 +58,9 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
|
||||
warehouse_ids_json=['A'],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -20,15 +20,13 @@ def _receipt_config(source_id: int):
|
||||
|
||||
return ShippingReceiptReportConfig(
|
||||
inventory_source_id=source_id,
|
||||
enabled=True,
|
||||
report_path_json={
|
||||
'program_group': 'Bison',
|
||||
'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound',
|
||||
'report_name': 'Receipt Detail',
|
||||
},
|
||||
query_parameters_json=[],
|
||||
warehouse_ids_json=['AWSDU'],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user