From a06ff79d7c6ad52f9c631fef630f1fb5580a6553 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 21 Sep 2026 13:40:10 +0800 Subject: [PATCH] =?UTF-8?q?refactor(shipping-notice):=20=E6=94=B6=E6=96=99?= =?UTF-8?q?RPA=E9=80=9A=E7=9F=A5=E5=B9=B6=E5=85=A5=E6=8E=92=E7=A8=8B?= =?UTF-8?q?=E9=80=9A=E7=94=A8=E5=87=BA=E5=8F=A3=E4=B8=8E=E5=BA=93=E5=AD=98?= =?UTF-8?q?=E5=90=8C=E9=97=A8=E7=A6=81=E4=B8=80=E6=AC=A1=E6=80=A7=E5=8F=91?= =?UTF-8?q?=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - run 终态归集后经 _notify_schedule_run_wecom 一次性发 textcard+全部收料文件,移除回调逐文件即时推送 - 门禁/审计/wecom_notified 记账与库存排程同链;WECOM_NOTIFY_EVENTS 须含 schedule_completed - 删除独立汇总函数 deliver_schedule_receipt_summary;deliver_receipt_file 仅保留管理员重发通道 - 同步 technical.md 通知描述与门禁说明;新增一次性发送与统一门禁测试 --- .../schedule/freight_receipt_rpa_finalize.py | 12 +- .../services/schedule/scheduler_service.py | 71 +++++++++++- .../receipt_report_notification.py | 68 ++--------- .../test_freight_receipt_rpa_notifications.py | 106 ++++++++++++++++++ ...test_shipping_notice_inventory_schedule.py | 2 + docs/features/shipping-notice/technical.md | 8 +- 6 files changed, 202 insertions(+), 65 deletions(-) diff --git a/backend/app/services/schedule/freight_receipt_rpa_finalize.py b/backend/app/services/schedule/freight_receipt_rpa_finalize.py index 5ffaa84b..4891e20e 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_finalize.py +++ b/backend/app/services/schedule/freight_receipt_rpa_finalize.py @@ -71,8 +71,16 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count} db.session.commit() - from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary - deliver_schedule_receipt_summary(run.id) + # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。 + try: + task = run.task + if task is not None and task.notify_enabled: + from app.services.schedule.scheduler_service import _notify_schedule_run_wecom + + _notify_schedule_run_wecom(task, run) + db.session.commit() + except Exception as wecom_exc: + current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc) return {'finalized': True, 'status': run.status} diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index 8ceab5b4..c85d82da 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -18,11 +18,12 @@ from typing import Any from flask import current_app from app import db -from app.models import ScheduleRun, ScheduleTask, User +from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User from app.services.schedule.cron_util import normalize_cron_expr from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot from app.services.schedule.excel_service import export_schedule_result_excel -from app.services.schedule import resolve_schedule_executor, resolve_schedule_header +from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path +from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY from app.services.schedule.shipping_inventory_rpa_finalize import ( apply_deferred_schedule_run_state, is_awaiting_rpa_schedule_run, @@ -118,6 +119,36 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) return params +def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]: + """ + 收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。 + + 核心逻辑:库存与收料 RPA 共用同一企微通知出口(_notify_schedule_run_wecom), + 本函数是收料侧的唯一分叉点——按 platform_api_path 识别收料排程,返回该 run + 全部单元已归档且未被清理(archive_deleted_at 为空)的报表文件。 + """ + from app.models import ShippingReceiptRpaUnitRun + + task = run.task + if ( + task is None + or task.schedule_type != 'platform_job' + or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY + ): + return [] + return ( + ShippingReceiptReportFile.query.join( + ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id, + ) + .filter( + ShippingReceiptRpaUnitRun.schedule_run_id == run.id, + ShippingReceiptReportFile.archive_deleted_at.is_(None), + ) + .order_by(ShippingReceiptReportFile.id) + .all() + ) + + def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: """ 组装排程完成企微 textcard 正文。 @@ -140,6 +171,9 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: if inventory_raw_zip_available_from_summary(summary): description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载' + receipt_files = _receipt_report_files_for_run(run) + if receipt_files: + description += f'\n收料报表文件 {len(receipt_files)} 份:已随本通知发送' return description @@ -148,6 +182,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: 排程完成后的通用企微通知。 核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核), 则跳过以免与领域缺件/失败告警重复。 + 库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包; + 收料附加该 run 全部单元的收料报表文件(见 _receipt_report_files_for_run)。 """ from app.services.wecom_notify import ( upload_wecom_temp_media, @@ -208,6 +244,21 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: run.run_no, exc, ) + receipt_media: list[tuple[str, str]] = [] + for receipt_file in _receipt_report_files_for_run(run): + try: + from app.services.file_assets.storage import file_asset_storage + + receipt_media_id = upload_wecom_temp_media( + file_asset_storage.get_bytes(receipt_file.storage_key), receipt_file.original_filename, + ) + receipt_media.append((receipt_media_id, receipt_file.original_filename)) + except Exception as exc: + current_app.logger.warning( + '[wecom-schedule] receipt file media upload failed for run %s file %s: %s', + run.run_no, receipt_file.id, exc, + ) + textcard_ok_count = 0 errors = [] @@ -263,6 +314,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: except Exception as exc: errors.append(f'{u.real_name or u.username}: raw zip exception={exc}') + for receipt_media_id, receipt_filename in receipt_media: + try: + receipt_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_receipt_file', u, + title, f'[收料报表] {receipt_filename}', uuid.uuid4().hex, + ) + receipt_data = send_wecom_file_message(u.wecom_userid, receipt_media_id) + if receipt_data.get('errcode') == 0: + receipt_audit.status = 'sent' + else: + receipt_audit.error_code = str(receipt_data.get('errcode')) + receipt_audit.error_message = str(receipt_data.get('errmsg', 'unknown'))[:255] + errors.append(f'{u.real_name or u.username}: receipt file errcode={receipt_data.get("errcode")}') + except Exception as exc: + errors.append(f'{u.real_name or u.username}: receipt file exception={exc}') + if textcard_ok_count > 0: run.wecom_notified = True run.wecom_notified_at = datetime.utcnow() diff --git a/backend/app/services/shipping_notice/receipt_report_notification.py b/backend/app/services/shipping_notice/receipt_report_notification.py index cc7ab019..0247650b 100644 --- a/backend/app/services/shipping_notice/receipt_report_notification.py +++ b/backend/app/services/shipping_notice/receipt_report_notification.py @@ -1,4 +1,13 @@ -"""收料报表的企微文件及汇总投递服务。""" +"""收料报表企微通知的管理员重发通道。 + +用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送 + textcard 汇总 + 全部收料文件(scheduler_service._notify_schedule_run_wecom, + 与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的 + 强制重发能力(POST /receipt-report-files//resend),不触发 RPA。 +依赖:models、file_asset_storage、audit_service、wecom_notify。 +逻辑:deliver_receipt_file 幂等投递单文件并落 ShippingReceiptNotificationDelivery + 与 shipping 审计;force=True 供管理员补偿重发,绕过成功幂等但仍受通知开关约束。 +""" from __future__ import annotations @@ -8,7 +17,7 @@ from app import db from app.models import ShippingReceiptNotificationDelivery, ShippingReceiptReportFile, User from app.services.file_assets.storage import file_asset_storage from app.services.shipping_notice.audit_service import append_shipping_audit_event -from app.services.wecom_notify import send_wecom_file_message, send_wecom_textcard_message, upload_wecom_temp_media +from app.services.wecom_notify import send_wecom_file_message, upload_wecom_temp_media def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]: @@ -82,58 +91,3 @@ def deliver_receipt_file(file_id: int, *, force: bool = False) -> dict: ) db.session.commit() return {'success_count': success_count, 'failed_count': failed_count} - - -def deliver_schedule_receipt_summary(schedule_run_id: int) -> dict: - """所有收料单元结束后向接收人发送汇总;无数据不附空文件。""" - from app.models import ScheduleRun, ShippingReceiptRpaUnitRun - - run = db.session.get(ScheduleRun, schedule_run_id) - task = run.task if run else None - if run is None or task is None or not task.notify_enabled: - return {'success_count': 0, 'failed_count': 0} - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() - success = sum(unit.status == 'success' for unit in units) - empty = sum(unit.status == 'empty' for unit in units) - failed = sum(unit.status == 'failed' for unit in units) - results = {'success_count': 0, 'failed_count': 0} - for user_id in sorted({int(item) for item in (task.notify_user_ids_json or []) if str(item).isdigit()}): - key = f'receipt:summary:{run.id}:user:{user_id}' - delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none() - if delivery and delivery.status == 'success': - results['success_count'] += 1 - continue - if delivery is None: - delivery = ShippingReceiptNotificationDelivery(unit_run_id=None, report_file_id=None, recipient_user_id=user_id, message_type='summary', idempotency_key=key) - db.session.add(delivery); db.session.flush() - user = db.session.get(User, user_id) - if user is None or not user.wecom_userid: - delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'; results['failed_count'] += 1 - append_shipping_audit_event( - event_type='shipping_receipt_summary_notification_attempted', aggregate_type='shipping_receipt_schedule_run', - aggregate_id=str(run.id), actor_type='system', owner_user_id=user_id, result='failure', - before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'error_code': delivery.error_code}, - metadata={'delivery_id': delivery.id, 'message_type': 'summary'}, - ) - continue - try: - response = send_wecom_textcard_message(user.wecom_userid, '收料报表导出结果', f'成功文件 {success},无数据 {empty},失败 {failed}。', '') - if int(response.get('errcode', -1)) != 0: - raise RuntimeError(str(response.get('errmsg') or response.get('errcode'))) - delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.response_summary_json = {'errcode': 0, 'success_files': success, 'empty_units': empty, 'failed_units': failed}; results['success_count'] += 1 - append_shipping_audit_event( - event_type='shipping_receipt_summary_notification_attempted', aggregate_type='shipping_receipt_schedule_run', - aggregate_id=str(run.id), actor_type='system', owner_user_id=user_id, result='success', - before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None}, - metadata={'delivery_id': delivery.id, 'message_type': 'summary', 'success_files': success, 'empty_units': empty, 'failed_units': failed}, - ) - except Exception as exc: - delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]; results['failed_count'] += 1 - append_shipping_audit_event( - event_type='shipping_receipt_summary_notification_attempted', aggregate_type='shipping_receipt_schedule_run', - aggregate_id=str(run.id), actor_type='system', owner_user_id=user_id, result='failure', - before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message}, - metadata={'delivery_id': delivery.id, 'message_type': 'summary'}, - ) - db.session.commit() - return results diff --git a/backend/tests/test_freight_receipt_rpa_notifications.py b/backend/tests/test_freight_receipt_rpa_notifications.py index 87739e0f..8b05ef53 100644 --- a/backend/tests/test_freight_receipt_rpa_notifications.py +++ b/backend/tests/test_freight_receipt_rpa_notifications.py @@ -63,3 +63,109 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch): # 审计结果遵循统一枚举;业务投递状态仍保留为 failed。 assert audit.result == 'failure' assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND' + + +def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True): + """构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。""" + from app.models import ( + ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, + ShippingReceiptRpaUnitRun, + ) + + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + db.session.add(task); db.session.flush() + run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None) + db.session.add(run); db.session.flush() + unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={}) + db.session.add(unit); db.session.flush() + report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64) + db.session.add(report_file) + db.session.commit() + return task, run, report_file + + +def _patch_unified_wecom(monkeypatch, *, enabled_events: bool): + """拦截通用排程出口的企微调用,返回可断言的捕获列表。""" + textcards: list[tuple[str, str]] = [] + media_uploads: list[str] = [] + file_sends: list[str] = [] + + def _fake_send_textcard(_userid, _title, description, _jump_url): + textcards.append((_title, description)) + return {'errcode': 0} + + monkeypatch.setattr('app.services.wecom_notify.send_wecom_textcard_message', _fake_send_textcard) + if enabled_events: + monkeypatch.setattr('app.services.wecom_notify._get_enabled_events', lambda: {'schedule_completed'}) + monkeypatch.setattr('app.services.wecom_notify.upload_wecom_temp_media', lambda _data, filename: media_uploads.append(filename) or f'media-{len(media_uploads)}') + monkeypatch.setattr('app.services.wecom_notify.send_wecom_file_message', lambda _userid, media_id: file_sends.append(media_id) or {'errcode': 0}) + monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'receipt-data') + return textcards, media_uploads, file_sends + + +def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch): + """收料 run 终态后经通用排程出口一次性发 textcard+全部收料文件;重复归集不重发。""" + from app import db + from app.models import User + from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + + with app.app_context(): + recipient = User(username='receipt-one-shot', email='one-shot@example.com', role='user', status='active', wecom_userid='one-shot-user') + db.session.add(recipient); db.session.flush() + task, run, _report_file = _make_receipt_run_fixture(db, 'SCH-RECEIPT-ONESHOT', 'RUN-RECEIPT-ONESHOT', 'receipt-oneshot-callback') + task.notify_enabled = True + task.notify_user_ids_json = [recipient.id] + db.session.commit() + + app.config['WECOM_NOTIFY_ENABLED'] = True + app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com' + textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=True) + + outcome = finalize_receipt_schedule_run_if_complete(run.id) + + # [断言意图] 一次性出口:单条 textcard + 单文件消息,与库存排程同通道同门禁。 + assert outcome == {'finalized': True, 'status': 'success'} + assert len(textcards) == 1 + assert '收料报表文件 1 份:已随本通知发送' in textcards[0][1] + assert media_uploads == ['receipt.xlsx'] + assert file_sends == ['media-1'] + assert run.wecom_notified is True + + # [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。 + outcome_again = finalize_receipt_schedule_run_if_complete(run.id) + assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'} + assert len(textcards) == 1 and len(file_sends) == 1 + + +def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch): + """收料通知与库存共用门禁:事件未启用或接收人未绑定企微时不发送并记录原因。""" + from app import db + from app.models import User + from app.services.schedule.scheduler_service import _notify_schedule_run_wecom + + with app.app_context(): + app.config['WECOM_NOTIFY_ENABLED'] = True + textcards, _media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=False) + + bound_user = User(username='receipt-gate-bound', email='gate-bound@example.com', role='user', status='active', wecom_userid='gate-bound-user') + unbound_user = User(username='receipt-gate-unbound', email='gate-unbound@example.com', role='user', status='active') + db.session.add_all([bound_user, unbound_user]); db.session.flush() + task_a, run_a, _f = _make_receipt_run_fixture(db, 'SCH-RECEIPT-GATE-A', 'RUN-RECEIPT-GATE-A', 'receipt-gate-a') + task_a.notify_user_ids_json = [bound_user.id] + task_b, run_b, _g = _make_receipt_run_fixture(db, 'SCH-RECEIPT-GATE-B', 'RUN-RECEIPT-GATE-B', 'receipt-gate-b') + task_b.notify_user_ids_json = [unbound_user.id] + db.session.commit() + + # [断言意图] ①schedule_completed 不在 WECOM_NOTIFY_EVENTS 内 → 整体拦截并留因。 + app.config['WECOM_NOTIFY_EVENTS'] = '' + _notify_schedule_run_wecom(task_a, run_a) + assert textcards == [] and file_sends == [] + assert run_a.wecom_notify_error == 'event schedule_completed disabled' + + # [断言意图] ②事件放行但接收人无 wecom_userid → 不发送并留因,与库存口径一致。 + app.config['WECOM_NOTIFY_EVENTS'] = 'schedule_completed' + _notify_schedule_run_wecom(task_b, run_b) + assert textcards == [] and file_sends == [] + assert run_b.wecom_notify_error == 'no wecom_userid bound users in notify list' + diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py index 07e39fd6..9b69af68 100644 --- a/backend/tests/test_shipping_notice_inventory_schedule.py +++ b/backend/tests/test_shipping_notice_inventory_schedule.py @@ -688,6 +688,8 @@ def test_build_schedule_run_wecom_description_includes_skipped_count(): skipped_count=1, failed_count=0, response_summary_json=None, + # 收料文件附加行读取 run.task 识别收料排程;非收料场景显式置 None。 + task=None, ) text = _build_schedule_run_wecom_description(run) assert "跳过: 1" in text diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index dd4fd189..d33d4e91 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -3058,7 +3058,7 @@ FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900 - 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。 - 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 -- 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。 +- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ 该 run 全部收料文件消息;回调时不再逐文件即时推送。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。 排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `data\freight_rpa\receipt\logs\worker.log` 巡检。 @@ -3071,7 +3071,7 @@ FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900 - Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`); - `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`; - 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象; - - 接收人企微收到文件消息与汇总,工作台「收料文件」可查看并下载。 + - 接收人企微一次性收到 textcard 汇总与全部收料文件消息(与库存排程同一出口),工作台「收料文件」可查看并下载。 4. 失败路径:制造一个失败单元(如停用对应 RPA Profile),确认排程终态 `failed` / `partial_failed`、管理端失败单元可查、带原因重试生成新单元且以 `retry_of_id` 关联旧单元;通知重发不触发重新导出。 5. 隔离确认:收料文件不出现在 `inventory_drop`,不产生任何 `ShippingInventoryFile` / 库存快照 / 库存匹配记录。 @@ -3459,7 +3459,7 @@ API 层 - **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。 - 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai) - 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key -- **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.` 的合并结果核对 ②③(DB 优先于 env 文件)。 +- **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认;2026-09-21 起收料排程并入同一出口,门禁/审计/`wecom_notified` 记账完全一致,仅附件不同——库存附 Excel+原始库存包、收料附该 run 全部收料文件):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.` 的合并结果核对 ②③(DB 优先于 env 文件)。 - **库存 RPA 企微/下载文件名**(2026-09-09):展示名统一为 `库存RPA-{yyyyMMdd}-{HHmm}-结果.xlsx` 与 `库存RPA-{yyyyMMdd}-{HHmm}-库存.zip`(`HHmm` 按任务 `schedule_timezone`,缺省 Asia/Shanghai,勿直接用 UTC/`run_no` 内嵌时刻);完整 `run_no` 只留在 textcard 与磁盘归档键 `{run_no}.zip`。ZIP 包内条目为 `{序号}_{source_code}.xlsx`(无 source_code 时回退仓码);`warehouse_id` / `inventory_file_no` 仅写入 `manifest.json`。 - **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_inventory_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。 @@ -3730,7 +3730,7 @@ Case 状态:`unreviewed`、`draft`、`ready`、`confirming`、`confirmed`、`n - 嵌套标注采用固定语义层级:明细字段高于物理行容器,表头只展示列级字段,不显示内部表头行容器。物理行内部不吞掉字段点击,管理员通过物理行标签、边缘或已选中的缩放手柄操作父区域。 # 独立收料报表 RPA -收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径与受控查询条件(Warehouse 条件即逐仓拆分维度,不单独持久化仓库清单);`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系;`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存企微投递幂等事实。 +收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径与受控查询条件(Warehouse 条件即逐仓拆分维度,不单独持久化仓库清单);`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系(按需触发无排程时 `schedule_run_id` 为 NULL);`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存管理员重发通道的投递幂等事实(正常通知自 2026-09-21 起走通用排程出口,由 `schedule_runs.wecom_notified` 记账)。 DBS 每个 Warehouse 单独导出且不填报表日期。**Warehouse 即逐仓拆分维度,配置与库存完全同构**:仓库维护在查询条件的 Warehouse 条件里(支持多值,逗号分隔),不单独持久化仓库清单;排程/按需触发时由后端运行时从该条件派生仓库清单(`receipt_rpa.receipt_warehouse_values`),一仓展开一个执行单元、一个归档文件,并把单元快照中的 Warehouse 条件剥离(`receipt_rpa.receipt_unit_parameters`)——收料 Worker(`receipt_dbs_export.py`)执行时再把当前 `warehouse_id` 作为必填单值条件自动追加,单元快照若保留该条件会重复冲突。校验要求 DBS 收料配置恰一条非空 Warehouse 条件(`shipping_inventory_service._validate_receipt_report_config`)。报表日期固定不筛选同理属于受控边界:跨日排程不筛日期,避免管理端误传日期导致导出漏数。Crane 固定 `Inbound Details`,按本次唯一 Description 等待并下载匹配项,禁止取“最新历史报表”。重试创建新的单元并以 `retry_of_id` 关联旧失败单元,绝不覆盖历史。库存 Worker 与收料 Worker 可在不同专用目录下并行运行,但首版不复用跨排程登录会话。