test_destination_trailer_tools.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. import importlib
  2. import io
  3. import unittest
  4. from app import GatewayApp
  5. from public_gateway import PublicGatewayApp
  6. from services.output_presenter import OutputPresenter
  7. PROGRESS_COLUMNS = [
  8. ('bl_number', '提单号'), ('container_code', '柜号'),
  9. ('container_type', '柜型'), ('warehouse_name', '仓库名称'),
  10. ('providers_name', '拖车行'), ('trailer_status', '提柜状态'),
  11. ('latest_remark', '最新操作备注'), ('is_direct_send', '直送'),
  12. ('cabinet_type', '整拼类型'), ('vessel_name', '船名航次'),
  13. ('route', '航线'), ('clearance_check', '清关查验'),
  14. ('etd', 'ETD'), ('atd', 'ATD'), ('eta', 'ETA'), ('ata', 'ATA'),
  15. ('loading_port', '起运港'), ('destination_port', '目的港'),
  16. ('wharf_name', '到港码头'),
  17. ('customs_release_status', '海关放行状态'),
  18. ('terminal_release_status', '码头放行状态'),
  19. ('carrier_release_status', '船司放行状态'),
  20. ('pickup_lfd', '提柜LFD'), ('appt_time', 'APPT时间'),
  21. ('delivery_end_time', '卡车实际派送时间'),
  22. ('est_pickup_time', '预计提柜时间'), ('pickup_time', '实际提柜时间'),
  23. ('inbound_date', '到仓时间'), ('container_return_time', '还柜时间'),
  24. ('pickup_prescription', '提柜时效'), ('return_prescription', '还柜时效'),
  25. ('wharf_wait_time', '码头等待时间'), ('amazon_wait_time', '亚马逊等待时间'),
  26. ('bill_status', '应付费用状态'),
  27. ('issue_way', '出单方式'),
  28. ('release_status', '放货状态'),
  29. ('freight_collect', '海运费到付'),
  30. ('is_dg', 'DG'),
  31. ('is_soc', 'SOC'),
  32. ('is_oneway', 'ONEWAY'),
  33. ('appointment_method', '预约方式'),
  34. ('need_appointment_code', '是否需要预约码'),
  35. ('warehouse_special_remark', '仓库特殊备注'),
  36. ]
  37. DO_COLUMNS = [
  38. ('trailer_number', '拖车单号'), ('outbound_number', '出库单号'),
  39. ('container_code', '柜号'), ('container_type', '柜型'),
  40. ('bl_number', '提单号'), ('is_direct_send', '是否直送'),
  41. ('original_do_file', '原DO单'), ('new_do_file', '新DO单'),
  42. ('email_subject', '邮件主题'), ('email_from', '邮件发送人'),
  43. ('received_at', '邮件接收时间'),
  44. ]
  45. FILTER_TYPES = [
  46. '海外提柜类型', '拖车行', '海外仓', '直送柜', '应付费用', '整拼类型', '运输方式',
  47. ]
  48. STAGES = [
  49. '待安排拖车', '待提柜', '待还柜(海)', '已还柜(海)', '已提货(空)', 'DO单制作',
  50. ]
  51. class RecordingApiClient:
  52. def __init__(self):
  53. self.calls = []
  54. def list_enabled_tools(self, request_id=''):
  55. return {
  56. 'code': 'MCP_0000',
  57. 'data': {
  58. 'tool_codes': [
  59. 'query_destination_trailer_list',
  60. 'list_destination_trailer_filter_options',
  61. ],
  62. },
  63. }
  64. def call_tool(self, tool_code, route_path, payload, request_id):
  65. self.calls.append((tool_code, route_path, payload, request_id))
  66. return {'code': 'MCP_0000', 'data': {}, 'meta': {}}
  67. class DestinationTrailerToolContractTest(unittest.TestCase):
  68. def tool_class(self, module_name, class_name):
  69. return getattr(importlib.import_module('tools.' + module_name), class_name)
  70. def test_query_schema_requires_stage_and_forbids_identity(self):
  71. cls = self.tool_class(
  72. 'query_destination_trailer_list', 'QueryDestinationTrailerListTool'
  73. )
  74. metadata = cls().metadata()
  75. schema = metadata['input_schema']
  76. self.assertEqual('query_destination_trailer_list', metadata['name'])
  77. self.assertEqual('/mcp/tools/queryDestinationTrailerList', cls.route_path)
  78. self.assertFalse(schema['additionalProperties'])
  79. self.assertEqual(['trailer_stage'], schema['required'])
  80. self.assertEqual(STAGES, schema['properties']['trailer_stage']['enum'])
  81. self.assertNotIn('default', schema['properties']['trailer_stage'])
  82. for forbidden in ('company_id', 'admin_id', 'is_super', 'outbound_id'):
  83. self.assertNotIn(forbidden, schema['properties'])
  84. self.assertIn('使用场景:', metadata['description'])
  85. self.assertIn('禁止使用:', metadata['description'])
  86. self.assertIn('号码类型不明确时必须先询问用户', metadata['description'])
  87. self.assertIn('不得根据号码格式猜测', metadata['description'])
  88. self.assertIn('不得跨字段或跨工具试查', metadata['description'])
  89. self.assertIn('query_outbound_list', metadata['description'])
  90. self.assertIn('提单号、柜号、日期和其他筛选均为可选', metadata['description'])
  91. self.assertNotIn('必须再有', metadata['description'])
  92. def test_query_forwards_numbers_dates_and_rejects_invalid(self):
  93. cls = self.tool_class(
  94. 'query_destination_trailer_list', 'QueryDestinationTrailerListTool'
  95. )
  96. client = RecordingApiClient()
  97. cls(client).call(
  98. trailer_stage='待提柜',
  99. bl_numbers=[' BL-1 ', 'BL-1'],
  100. container_codes=['CONT-1'],
  101. providers_id=8,
  102. warehouse_id=3,
  103. is_direct_send=0,
  104. bill_status=10,
  105. cabinet_type=1,
  106. shipping_method=2,
  107. eta_start='2026-07-01',
  108. eta_end='2026-07-31',
  109. page=2,
  110. limit=30,
  111. request_id='rq_dt',
  112. )
  113. self.assertEqual(
  114. {
  115. 'trailer_stage': '待提柜',
  116. 'bl_numbers': ['BL-1'],
  117. 'container_codes': ['CONT-1'],
  118. 'providers_id': 8,
  119. 'warehouse_id': 3,
  120. 'is_direct_send': 0,
  121. 'bill_status': 10,
  122. 'cabinet_type': 1,
  123. 'shipping_method': 2,
  124. 'eta_start': '2026-07-01',
  125. 'eta_end': '2026-07-31',
  126. 'page': 2,
  127. 'limit': 30,
  128. },
  129. client.calls[-1][2],
  130. )
  131. self.assertEqual(
  132. '/mcp/tools/queryDestinationTrailerList',
  133. client.calls[-1][1],
  134. )
  135. cls(client).call(trailer_stage='待提柜')
  136. self.assertEqual(
  137. {
  138. 'trailer_stage': '待提柜',
  139. 'page': 1,
  140. 'limit': 20,
  141. },
  142. client.calls[-1][2],
  143. )
  144. cls(client).call(trailer_stage='待提柜', providers_id=8)
  145. with self.assertRaises(RuntimeError):
  146. cls().call(trailer_stage='待提柜')
  147. invalid = (
  148. {'trailer_stage': '全部', 'bl_numbers': ['BL-1']},
  149. {'trailer_stage': '待提柜', 'eta_start': '2026-07-01'},
  150. {
  151. 'trailer_stage': '待提柜',
  152. 'eta_start': '2026-07-01',
  153. 'eta_end': '2026-08-01',
  154. },
  155. {
  156. 'trailer_stage': 'DO单制作',
  157. 'bl_numbers': ['BL-1'],
  158. 'providers_id': 8,
  159. },
  160. {
  161. 'trailer_stage': 'DO单制作',
  162. 'eta_start': '2026-07-01',
  163. 'eta_end': '2026-07-02',
  164. },
  165. )
  166. for arguments in invalid:
  167. with self.subTest(arguments=arguments):
  168. with self.assertRaises(ValueError):
  169. cls(client).call(**arguments)
  170. def test_filter_schema_and_forwarding(self):
  171. cls = self.tool_class(
  172. 'list_destination_trailer_filter_options',
  173. 'ListDestinationTrailerFilterOptionsTool',
  174. )
  175. metadata = cls().metadata()
  176. schema = metadata['input_schema']
  177. self.assertEqual(['filter_type'], schema['required'])
  178. self.assertEqual(FILTER_TYPES, schema['properties']['filter_type']['enum'])
  179. self.assertIn('使用场景:', metadata['description'])
  180. self.assertIn('禁止使用:', metadata['description'])
  181. client = RecordingApiClient()
  182. cls(client).call('拖车行', keyword='美西', page=2, limit=10)
  183. self.assertEqual(
  184. {
  185. 'filter_type': '拖车行',
  186. 'keyword': '美西',
  187. 'page': 2,
  188. 'limit': 10,
  189. },
  190. client.calls[-1][2],
  191. )
  192. with self.assertRaises(ValueError):
  193. cls(client).call('排舱阶段')
  194. with self.assertRaises(RuntimeError):
  195. cls().call('海外提柜类型')
  196. with self.assertRaises(ValueError):
  197. cls(client).call('海外提柜类型', keyword='x' * 101)
  198. with self.assertRaises(ValueError):
  199. cls(client).call('海外提柜类型', page=0)
  200. with self.assertRaises(ValueError):
  201. cls(client).call('海外提柜类型', limit=True)
  202. def test_query_covers_remaining_validation_branches(self):
  203. cls = self.tool_class(
  204. 'query_destination_trailer_list', 'QueryDestinationTrailerListTool'
  205. )
  206. client = RecordingApiClient()
  207. with self.assertRaises(ValueError):
  208. cls(client).call(
  209. trailer_stage='待提柜',
  210. bl_numbers=['X'] * 201,
  211. )
  212. with self.assertRaises(ValueError):
  213. cls(client).call(
  214. trailer_stage='待提柜',
  215. eta_start='2026-07-02',
  216. eta_end='2026-07-01',
  217. )
  218. with self.assertRaises(ValueError):
  219. cls(client).call(
  220. trailer_stage='待提柜',
  221. bl_numbers=['BL-1'],
  222. bill_status=99,
  223. )
  224. with self.assertRaises(ValueError):
  225. cls(client).call(trailer_stage='待提柜', bl_numbers='BL-1')
  226. with self.assertRaises(ValueError):
  227. cls(client).call(trailer_stage='待提柜', bl_numbers=[1])
  228. with self.assertRaises(ValueError):
  229. cls(client).call(trailer_stage='待提柜', bl_numbers=[' '])
  230. with self.assertRaises(ValueError):
  231. cls(client).call(
  232. trailer_stage='待提柜',
  233. eta_start=20260701,
  234. eta_end='2026-07-02',
  235. )
  236. with self.assertRaises(ValueError):
  237. cls(client).call(
  238. trailer_stage='待提柜',
  239. eta_start='2026-99-01',
  240. eta_end='2026-07-02',
  241. )
  242. with self.assertRaises(ValueError):
  243. cls(client).call(
  244. trailer_stage='待提柜',
  245. eta_start='2026-7-01',
  246. eta_end='2026-07-02',
  247. )
  248. with self.assertRaises(ValueError):
  249. cls(client).call(
  250. trailer_stage='待提柜',
  251. bl_numbers=['BL-1'],
  252. providers_id=True,
  253. )
  254. with self.assertRaises(ValueError):
  255. cls(client).call(
  256. trailer_stage='待提柜',
  257. bl_numbers=['BL-1'],
  258. warehouse_id=0,
  259. )
  260. with self.assertRaises(ValueError):
  261. cls(client).call(
  262. trailer_stage='待提柜',
  263. bl_numbers=['BL-1'],
  264. page=0,
  265. )
  266. with self.assertRaises(ValueError):
  267. cls(client).call(
  268. trailer_stage='待提柜',
  269. bl_numbers=['BL-1'],
  270. limit=True,
  271. )
  272. cls(client).call(
  273. trailer_stage='待安排拖车',
  274. pickup_time_start='2026-07-01',
  275. pickup_time_end='2026-07-02',
  276. providers_id=8,
  277. bill_status=20,
  278. )
  279. cls(client).call(trailer_stage='DO单制作', bl_numbers=['BL-1'])
  280. with self.assertRaises(ValueError):
  281. cls(client).call(
  282. trailer_stage='待提柜',
  283. eta_start='20260701',
  284. eta_end='2026-07-02',
  285. )
  286. def test_cli_forwards_optional_trailer_filters(self):
  287. client = RecordingApiClient()
  288. app = GatewayApp(api_client=client)
  289. with self.assertRaises(ValueError):
  290. app.run_cli([
  291. 'call', '--tool', 'query_destination_trailer_list',
  292. ], stdout=io.StringIO())
  293. app.run_cli([
  294. 'call', '--tool', 'query_destination_trailer_list',
  295. '--trailer-stage', '待还柜(海)',
  296. '--container-codes', 'C1',
  297. '--providers-id', '8',
  298. '--warehouse-id', '3',
  299. '--is-direct-send', '1',
  300. '--bill-status', '30',
  301. '--cabinet-type', '2',
  302. '--shipping-method', '2',
  303. '--eta-start', '2026-07-01',
  304. '--eta-end', '2026-07-02',
  305. '--pickup-time-start', '2026-07-03',
  306. '--pickup-time-end', '2026-07-04',
  307. '--container-return-time-start', '2026-07-05',
  308. '--container-return-time-end', '2026-07-06',
  309. ], stdout=io.StringIO())
  310. self.assertEqual(
  311. {
  312. 'trailer_stage': '待还柜(海)',
  313. 'container_codes': ['C1'],
  314. 'providers_id': 8,
  315. 'warehouse_id': 3,
  316. 'is_direct_send': 1,
  317. 'bill_status': 30,
  318. 'cabinet_type': 2,
  319. 'shipping_method': 2,
  320. 'eta_start': '2026-07-01',
  321. 'eta_end': '2026-07-02',
  322. 'pickup_time_start': '2026-07-03',
  323. 'pickup_time_end': '2026-07-04',
  324. 'container_return_time_start': '2026-07-05',
  325. 'container_return_time_end': '2026-07-06',
  326. 'page': 1,
  327. 'limit': 20,
  328. },
  329. client.calls[-1][2],
  330. )
  331. def test_presenter_fails_closed_on_unknown_shape(self):
  332. presenter = OutputPresenter()
  333. meta = {
  334. 'page': 1, 'limit': 20, 'has_more': False, 'request_id': 'rq_x',
  335. }
  336. self.assertTrue(presenter.present('query_destination_trailer_list', {
  337. 'code': 'MCP_0000',
  338. 'data': {'trailer_stage': '待提柜', 'columns': [], 'records': [], 'extra': 1},
  339. 'meta': meta,
  340. })['is_error'])
  341. self.assertTrue(presenter.present('query_destination_trailer_list', {
  342. 'code': 'MCP_0000',
  343. 'data': {
  344. 'trailer_stage': '未知',
  345. 'columns': [],
  346. 'records': [],
  347. },
  348. 'meta': meta,
  349. })['is_error'])
  350. self.assertTrue(presenter.present('query_destination_trailer_list', {
  351. 'code': 'MCP_0000',
  352. 'data': {
  353. 'trailer_stage': '待提柜',
  354. 'columns': [{'key': 'bl_number', 'name': '提单号'}],
  355. 'records': [],
  356. },
  357. 'meta': meta,
  358. })['is_error'])
  359. columns = [{'key': key, 'name': name} for key, name in PROGRESS_COLUMNS]
  360. columns[0] = {'key': 'bl_number', 'name': '错'}
  361. self.assertTrue(presenter.present('query_destination_trailer_list', {
  362. 'code': 'MCP_0000',
  363. 'data': {
  364. 'trailer_stage': '待提柜',
  365. 'columns': columns,
  366. 'records': [],
  367. },
  368. 'meta': meta,
  369. })['is_error'])
  370. record = {key: 'v' for key, _ in PROGRESS_COLUMNS}
  371. record['bl_number'] = 1
  372. self.assertTrue(presenter.present('query_destination_trailer_list', {
  373. 'code': 'MCP_0000',
  374. 'data': {
  375. 'trailer_stage': '待提柜',
  376. 'columns': [
  377. {'key': key, 'name': name} for key, name in PROGRESS_COLUMNS
  378. ],
  379. 'records': [record],
  380. },
  381. 'meta': meta,
  382. })['is_error'])
  383. def test_local_public_registry_cli_and_safe_counts(self):
  384. local = GatewayApp().registered_tool_names()
  385. public = PublicGatewayApp(None, None).registered_tool_names()
  386. self.assertEqual(local, public)
  387. self.assertEqual(51, len(local))
  388. self.assertEqual(50, len(OutputPresenter.SAFE_TOOLS))
  389. self.assertIn('query_destination_trailer_list', local)
  390. self.assertIn('list_destination_trailer_filter_options', local)
  391. client = RecordingApiClient()
  392. app = GatewayApp(api_client=client)
  393. app.run_cli([
  394. 'call', '--tool', 'query_destination_trailer_list',
  395. '--trailer-stage', '待提柜', '--bl-numbers', ' BL-1,BL-2 ',
  396. '--page', '2', '--limit', '30',
  397. ], stdout=io.StringIO())
  398. self.assertEqual(
  399. {
  400. 'trailer_stage': '待提柜',
  401. 'bl_numbers': ['BL-1', 'BL-2'],
  402. 'page': 2,
  403. 'limit': 30,
  404. },
  405. client.calls[-1][2],
  406. )
  407. with self.assertRaises(ValueError):
  408. app.run_cli([
  409. 'call', '--tool', 'list_destination_trailer_filter_options',
  410. ], stdout=io.StringIO())
  411. app.run_cli([
  412. 'call', '--tool', 'list_destination_trailer_filter_options',
  413. '--filter-type', '海外提柜类型',
  414. ], stdout=io.StringIO())
  415. self.assertEqual(
  416. 'list_destination_trailer_filter_options',
  417. client.calls[-1][0],
  418. )
  419. def test_presenter_locks_progress_and_do_columns(self):
  420. presenter = OutputPresenter()
  421. progress_record = {key: 'v' for key, _ in PROGRESS_COLUMNS}
  422. progress_record['trailer_status'] = '待提柜'
  423. progress_record.update({
  424. 'wharf_name': '码头A',
  425. 'customs_release_status': '已放行',
  426. 'terminal_release_status': '未放行',
  427. 'carrier_release_status': '',
  428. 'pickup_lfd': '2026-11-17',
  429. })
  430. result = presenter.present('query_destination_trailer_list', {
  431. 'code': 'MCP_0000',
  432. 'data': {
  433. 'trailer_stage': '待提柜',
  434. 'columns': [
  435. {'key': key, 'name': name} for key, name in PROGRESS_COLUMNS
  436. ],
  437. 'records': [progress_record],
  438. },
  439. 'meta': {
  440. 'page': 1, 'limit': 20, 'has_more': False, 'request_id': 'rq_p',
  441. },
  442. })
  443. self.assertFalse(result['is_error'])
  444. self.assertEqual(43, len(result['structured_content']['headers']))
  445. self.assertEqual('待提柜', result['structured_content']['trailer_stage'])
  446. self.assertEqual(
  447. ['到港码头', '海关放行状态', '码头放行状态', '船司放行状态', '提柜LFD'],
  448. [header['label'] for header in result['structured_content']['headers'][18:23]],
  449. )
  450. self.assertEqual(
  451. ['码头A', '已放行', '未放行', '', '2026-11-17'],
  452. result['structured_content']['rows'][0][18:23],
  453. )
  454. for stage in STAGES[:5]:
  455. with self.subTest(stage=stage):
  456. data = {
  457. 'trailer_stage': stage,
  458. 'columns': [{'key': key, 'name': name} for key, name in PROGRESS_COLUMNS],
  459. 'records': [progress_record],
  460. }
  461. meta = {'page': 1, 'limit': 20, 'has_more': False, 'request_id': 'rq_stage'}
  462. self.assertFalse(presenter.present('query_destination_trailer_list', {
  463. 'code': 'MCP_0000', 'data': data, 'meta': meta,
  464. })['is_error'])
  465. missing_record = dict(progress_record)
  466. del missing_record['pickup_lfd']
  467. data['records'] = [missing_record]
  468. self.assertTrue(presenter.present('query_destination_trailer_list', {
  469. 'code': 'MCP_0000', 'data': data, 'meta': meta,
  470. })['is_error'])
  471. do_record = {key: 'd' for key, _ in DO_COLUMNS}
  472. do_record['is_direct_send'] = '否'
  473. do_record['original_do_file'] = ''
  474. do_record['new_do_file'] = 'https://files.example/do.pdf'
  475. do_ok = presenter.present('query_destination_trailer_list', {
  476. 'code': 'MCP_0000',
  477. 'data': {
  478. 'trailer_stage': 'DO单制作',
  479. 'columns': [
  480. {'key': key, 'name': name} for key, name in DO_COLUMNS
  481. ],
  482. 'records': [do_record],
  483. },
  484. 'meta': {
  485. 'page': 1, 'limit': 20, 'has_more': False, 'request_id': 'rq_d',
  486. },
  487. })
  488. self.assertFalse(do_ok['is_error'])
  489. self.assertEqual(11, len(do_ok['structured_content']['headers']))
  490. bad_url = dict(do_record)
  491. bad_url['new_do_file'] = 'javascript:alert(1)'
  492. bad = presenter.present('query_destination_trailer_list', {
  493. 'code': 'MCP_0000',
  494. 'data': {
  495. 'trailer_stage': 'DO单制作',
  496. 'columns': [
  497. {'key': key, 'name': name} for key, name in DO_COLUMNS
  498. ],
  499. 'records': [bad_url],
  500. },
  501. 'meta': {
  502. 'page': 1, 'limit': 20, 'has_more': False, 'request_id': 'rq_b',
  503. },
  504. })
  505. self.assertTrue(bad['is_error'])
  506. extra = dict(progress_record)
  507. extra['outbound_number'] = 'OB1'
  508. extra_result = presenter.present('query_destination_trailer_list', {
  509. 'code': 'MCP_0000',
  510. 'data': {
  511. 'trailer_stage': '待提柜',
  512. 'columns': [
  513. {'key': key, 'name': name} for key, name in PROGRESS_COLUMNS
  514. ],
  515. 'records': [extra],
  516. },
  517. 'meta': {
  518. 'page': 1, 'limit': 20, 'has_more': False, 'request_id': 'rq_e',
  519. },
  520. })
  521. self.assertTrue(extra_result['is_error'])