output_presenter.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. import json
  2. import logging
  3. from constants import DEVICE_INVALID_MESSAGE
  4. logger = logging.getLogger(__name__)
  5. # Builds AI-safe MCP results for the explicitly supported tool set.
  6. class OutputPresenter:
  7. TABLE_TOOLS = frozenset((
  8. 'query_order_exact',
  9. 'query_track',
  10. 'query_customs_declaration_files',
  11. 'query_outbound_list',
  12. ))
  13. DETAIL_TOOLS = frozenset(('query_outbound_detail',))
  14. ORDER_DETAIL_TOOLS = frozenset(('query_order_detail',))
  15. OPTION_TOOLS = frozenset((
  16. 'list_order_filter_options',
  17. 'list_outbound_filter_options',
  18. 'list_pending_outbound_export_filter_options',
  19. ))
  20. EXPORT_TOOLS = frozenset((
  21. 'export_pending_outbound_orders',
  22. 'export_out_of_province_port_data',
  23. ))
  24. SAFE_TOOLS = (
  25. TABLE_TOOLS | DETAIL_TOOLS | ORDER_DETAIL_TOOLS
  26. | OPTION_TOOLS | EXPORT_TOOLS
  27. )
  28. ORDER_DETAIL_SECTIONS = {
  29. 'overview': '订单概览',
  30. 'packages': '箱单信息',
  31. 'package_items': '箱单商品',
  32. 'dw_auth': 'DW授权信息',
  33. 'attachments': '附件信息',
  34. 'inbound': '入库信息',
  35. 'checks': '查验信息',
  36. 'tracks': '订单轨迹',
  37. 'operation_logs': '操作日志',
  38. 'cost_logs': '应收与结算日志',
  39. 'delivery': '派送信息',
  40. 'all': '全部',
  41. }
  42. ORDER_DETAIL_FIELDS = {
  43. 'overview': {
  44. 'order_info': {
  45. 'order_number': '订单号', 'reference_number': '客户参考号',
  46. 'customer_name': '客户名称', 'departure_country': '起运国',
  47. 'destination_country': '目的国', 'package_method': '包装类型',
  48. 'product_name': '物流产品', 'forecast_pwv': '预报件重体',
  49. 'inbound_pwv': '入库件重体',
  50. 'receivable_charge_weight': '应收计费重/体积',
  51. 'settlement_charge_weight': '结算计费重/体积',
  52. 'declaration_type': '报关类型', 'pre_recording': '是否需要预录单',
  53. 'idcard_name': '企业/个人姓名',
  54. 'idcard_number': '社会信用代码/身份证号',
  55. 'outbound_number': '排舱单号', 'container_mode': '直送柜/拼柜',
  56. 'track_map_available': '是否可查看轨迹地图', 'insurance': '购买保险',
  57. 'delivery_way': '派送方式', 'return_shipping_surcharge': '退运附加',
  58. 'work_order_count': '工单数量', 'bill_remark': '账单备注',
  59. 'remark': '订单备注',
  60. },
  61. 'freight_info': {
  62. 'estimated_inbound_time': '预计入库时间', 'cargo_type': '货物类型',
  63. 'pickup_way': '交货方式', 'warehouse': '交货仓库',
  64. 'pickup_address': '提货地址', 'pickup_contact': '提货联系人',
  65. 'pickup_phone': '提货联系电话', 'delivery_type': '派送类型',
  66. 'delivery_address': '派送地址', 'delivery_remark': '派送备注',
  67. 'oversea_warehouse': '海外仓',
  68. },
  69. 'package_summary': {
  70. 'box_count': '箱数', 'total_weight': '重量', 'weight_unit': '重量单位',
  71. 'total_volume': '体积', 'sku_count': 'SKU数量',
  72. 'clearance_total_price': '清关总价', 'clearance_currency': '清关币种',
  73. 'purchase_total_price': '采购总价', 'purchase_currency': '采购币种',
  74. },
  75. 'trader_info': {
  76. 'exporter': '出口商', 'importer': '进口商',
  77. 'coo_required': '是否做产地证',
  78. },
  79. },
  80. 'packages': {
  81. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  82. 'sku_summary': 'SKU', 'product_name_summary': '商品名',
  83. 'box_quantity': '箱数', 'box_length_cm': '单箱长(CM)',
  84. 'box_width_cm': '单箱宽(CM)', 'box_height_cm': '单箱高(CM)',
  85. 'gross_weight_kg': '单箱毛重量(KG)', 'net_weight_kg': '单箱净重量(KG)',
  86. 'is_over_length': '长度是否超限', 'is_over_width': '宽度是否超限',
  87. 'is_over_height': '高度是否超限', 'is_over_weight': '重量是否超限',
  88. },
  89. 'package_items': {
  90. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  91. 'box_specification': '箱规', 'box_specification_unit': '箱规单位',
  92. 'package_gross_weight_kg': '箱单单箱毛重(KG)',
  93. 'package_net_weight_kg': '箱单单箱净重(KG)',
  94. 'inspection_result': '查验结果', 'exception_reason': '异常原因',
  95. 'inspection_photo_count': '查验图片数量', 'sku': 'SKU',
  96. 'units_per_box': '单箱个数', 'declaration_type': '报关类型',
  97. 'box_number': '箱号', 'item_gross_weight_kg': '商品单箱毛重量(KG)',
  98. 'item_net_weight_kg': '商品单箱净重量(KG)', 'chinese_name': '中文品名',
  99. 'english_name': '英文名称', 'brand_type': '品牌类型', 'brand': '品牌',
  100. 'model': '型号', 'material_cn': '材质(CN)', 'material_en': '材质(EN)',
  101. 'purpose_cn': '用途', 'goods_attributes': '商品属性',
  102. 'declaration_hs_code': '报关编码', 'clearance_hs_code': '清关编码',
  103. 'material_ratio': '材质占比', 'clearance_unit_price': '清关单价',
  104. 'clearance_currency': '清关币种', 'purchase_unit_price': '采购单价',
  105. 'purchase_currency': '采购币种', 'product_image_count': '商品图片数量',
  106. 'remark': '备注',
  107. },
  108. 'dw_auth': {
  109. 'fba_id': 'FBAID', 'dw_start': 'DW开始时间', 'dw_end': 'DW结束时间',
  110. 'dw_display': 'DW', 'authorization_status': '客户授权状态',
  111. },
  112. 'attachments': {
  113. 'category': '附件分类', 'file_name': '文件名称',
  114. 'file_extension': '文件类型', 'is_image': '是否图片',
  115. 'preview_url': '预览链接', 'download_url': '下载链接',
  116. 'cost_name': '收费项目',
  117. },
  118. 'inbound_summary': {
  119. 'inbound_status': '入库状态', 'inbound_time': '入库时间',
  120. 'inbound_operator': '操作人', 'warehouse': '仓库',
  121. 'abnormal_reason': '异常原因', 'inbound_photo_count': '入库图片数量',
  122. 'forecast_pwv_summary': '预报件重体', 'inbound_pwv_summary': '入库件重体',
  123. },
  124. 'inbound': {
  125. 'has_label': '是否贴标', 'shipment_id': 'SHIPMENT ID',
  126. 'inbound_quantity': '入库件数',
  127. 'measurement_photo_count': '测量图片数量',
  128. 'box_specification': '入库箱规', 'weight_mode': None, 'weight': None,
  129. 'weight_unit': '重量单位', 'is_over_length': '长度是否超限',
  130. 'is_over_width': '宽度是否超限', 'is_over_height': '高度是否超限',
  131. 'is_over_weight': '重量是否超限', 'operated_at': '操作时间',
  132. },
  133. 'checks': {
  134. 'shipment_id': '货件编号', 'sku': 'SKU', 'box_number': '箱号',
  135. 'box_quantity': '箱数', 'box_specification': '箱规',
  136. 'inspection_result': '查验结果',
  137. 'inspection_photo_count': '查验图片数量', 'remark': '备注',
  138. 'inspector': '查验人', 'inspected_at': '查验时间',
  139. },
  140. 'tracks': {
  141. 'track_type': '轨迹类型', 'status': '轨迹节点', 'location': '轨迹地点',
  142. 'occurred_at': '时间', 'tracking_number': '跟踪号',
  143. 'shipment_id': 'SHIPMENT ID', 'content': '轨迹内容',
  144. },
  145. 'operation_logs': {
  146. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  147. },
  148. 'cost_logs': {
  149. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  150. },
  151. 'delivery_summary': {
  152. 'master_tracking_number': '主跟踪号', 'sub_order_count': '子单数量',
  153. },
  154. 'delivery': {'sub_tracking_number': '子跟踪号'},
  155. }
  156. ORDER_DETAIL_STATUS_FIELDS = {
  157. 'stage': '阶段', 'label': '节点', 'state': '状态',
  158. 'occurred_at': '时间', 'time_kind': '时间类型',
  159. }
  160. ORDER_DETAIL_STATES = {
  161. 'completed': '已完成', 'in_progress': '进行中',
  162. 'pending': '待完成', 'hidden': '不展示',
  163. }
  164. ORDER_DETAIL_TIME_KINDS = {
  165. 'actual': '实际', 'estimated': '预计', 'empty': '暂无',
  166. }
  167. TABLE_COLUMNS = {
  168. 'query_order_exact': {
  169. 'order_number': ('订单号',),
  170. 'reference_number': ('客户参考号',),
  171. 'status_txt_name': ('状态',),
  172. 'check_status_txt_name': ('是否已查验',),
  173. 'customer_name': ('客户名称',),
  174. 'customer_account_type_name': ('客户属性',),
  175. 'inbound_date': ('入库时间',),
  176. 'wo_num': ('未完成工单',),
  177. 'product_name': ('物流产品',),
  178. 'inbound_pieces': ('件数',),
  179. 'inbound_volume': ('体积(CBM)',),
  180. 'inbound_weight': ('重量(KG)',),
  181. 'pro_cn_name': ('品名',),
  182. 'export_declaration_type': ('报关方式',),
  183. 'merge_declare_number': ('合并报关单号',),
  184. 'delivery_address': ('派送地址',),
  185. 'container_code': ('柜号',),
  186. 'out_status_txt': ('排舱单状态',),
  187. 'hinge_of_destination': ('目的港',),
  188. 'etd': ('ETD',),
  189. 'atd': ('ATD',),
  190. 'eta': ('ETA',),
  191. 'ata': ('ATA',),
  192. 'release_time': ('清关放行时间',),
  193. 'oversea_inbound_date': ('海外入库时间',),
  194. 'appt_time': ('APPT时间',),
  195. 'est_loading_time': ('预计装柜时间',),
  196. 'pickup_time': ('海外提柜时间',),
  197. 'delivery_way_title': ('派送方式',),
  198. 'tracking_number': ('快递单号', '承运商跟踪号码'),
  199. 'shipment_id': ('Shipment ID',),
  200. 'goods_attribute': ('商品属性',),
  201. 'sku': ('SKU',),
  202. 'sales_user': ('商务经理',),
  203. 'service_user': ('客户经理',),
  204. 'department_name': ('事业部',),
  205. 'remark': ('订单备注',),
  206. 'importer_name': ('进口商',),
  207. 'warehouse_name': ('交货仓库',),
  208. 'paid_status_name': ('付款状态',),
  209. },
  210. 'query_track': {
  211. 'status': ('轨迹节点', '轨迹状态,如:开始集港、离港放行、清关、配送等'),
  212. 'location': ('轨迹地点', '发生地点'),
  213. 'time': ('时间', '轨迹发生时间(已转换为用户时区)'),
  214. 'content': ('轨迹内容', '详细描述'),
  215. 'tracking_number': ('跟踪号', '快递单号'),
  216. 'shipment_id': ('Shipment ID', '包裹ID'),
  217. },
  218. 'query_customs_declaration_files': {
  219. 'outbound_number': ('排舱单号',),
  220. 'order_number': ('订单号',),
  221. 'file_name': ('文件名',),
  222. 'file_type': ('文件类型',),
  223. 'file_url': ('文件链接',),
  224. },
  225. 'query_outbound_list': {
  226. 'outbound_number': ('排舱单号',),
  227. 'direct_send': ('直送柜',),
  228. 'remark': ('备注',),
  229. 'cargo_type': ('超长超重',),
  230. 'warehouse_name': ('集货仓库',),
  231. 'status': ('状态',),
  232. 'so_number': ('SO号',),
  233. 'container_code': ('柜号',),
  234. 'seal_number': ('封条号',),
  235. 'container_type': ('柜型',),
  236. 'shipping_method': ('运输方式',),
  237. 'total_volume': ('体积(CBM)',),
  238. 'total_weight': ('重量(KG)',),
  239. 'ship_schedule': ('船期',),
  240. 'closing_time': ('截关时间',),
  241. 'est_loading_time': ('预计装柜时间',),
  242. 'operator': ('操作人',),
  243. 'operation_modes': ('拖报清方式',),
  244. 'operation_time': ('操作时间',),
  245. },
  246. 'query_outbound_detail': {
  247. 'order_number': ('订单号',),
  248. 'cargo_type': ('超长超重',),
  249. 'customs_files': ('报关资料',),
  250. 'reference_number': ('客户参考号',),
  251. 'customer_name': ('客户名称',),
  252. 'declaration_type': ('报关方式',),
  253. 'merge_declare_number': ('合并报关单号',),
  254. 'order_remark': ('订单备注',),
  255. 'bl_number': ('提单号',),
  256. 'container_code': ('柜号',),
  257. 'customer_service': ('客户经理',),
  258. 'est_inbound_date': ('预计入库时间',),
  259. 'inbound_date': ('实际入库时间',),
  260. 'status': ('状态',),
  261. 'pieces': ('预报件数 / 入库件数',),
  262. 'weight': ('预报实重(KG) / 入库实重(KG)',),
  263. 'volume': ('预报体积(m³) / 入库体积(m³)',),
  264. 'pickup_place': ('交货地',),
  265. 'product_name': ('物流产品',),
  266. 'goods_name': ('品名',),
  267. 'closing_time': ('截关时间',),
  268. 'clearance_remark': ('报关备注',),
  269. 'import_clearance_remark': ('清关备注',),
  270. 'delivery_address': ('派送地址',),
  271. 'delivery_type': ('派送类型',),
  272. 'delivery_way': ('派送方式',),
  273. 'channel': ('派送渠道',),
  274. 'country_name': ('目的国',),
  275. 'importer_name': ('进口商',),
  276. 'vat_type': ('清关税号',),
  277. 'packing_type': ('货物类型',),
  278. 'is_abnormal': ('是否问题件',),
  279. 'package_method': ('包装类型',),
  280. 'order_reply': ('到货回复',),
  281. },
  282. }
  283. OUTBOUND_DETAIL_SUMMARY = {
  284. 'bl_number': '提单号',
  285. 'container_code': '柜号',
  286. 'container_type': '柜型',
  287. 'total_volume': '总体积',
  288. 'total_weight': '总重量',
  289. 'total_pieces': '总件数',
  290. 'sku': 'SKU',
  291. 'buy_declaration_count': '买单报关数量',
  292. 'general_declaration_count': '一般贸易报关数量',
  293. 'must_load': '必装单量/体积',
  294. 'backup_load': '备装单量/体积',
  295. }
  296. FIELD_LABELS = {
  297. 'query_order_exact': {
  298. 'order_number': '订单号',
  299. 'order_numbers': '订单号',
  300. 'reference_number': '客户参考号',
  301. 'reference_numbers': '客户参考号',
  302. 'tracking_number': '快递单号',
  303. 'tracking_numbers': '快递单号',
  304. 'outbound_number': '排舱单号',
  305. 'outbound_numbers': '排舱单号',
  306. 'container_code': '柜号',
  307. 'container_codes': '柜号',
  308. 'so_number': 'SO号',
  309. 'so_numbers': 'SO号',
  310. 'shipment_id': 'Shipment ID',
  311. 'receiver_country': '收货国家',
  312. 'product_ids': '物流产品',
  313. 'customer_ids': '客户',
  314. 'sales_id': '销售人员',
  315. 'warehouse_ids': '仓库',
  316. 'department_id': '事业部',
  317. 'inbound_date_start': '入库开始日期',
  318. 'inbound_date_end': '入库结束日期',
  319. 'outbound_date_start': '出库开始日期',
  320. 'outbound_date_end': '出库结束日期',
  321. 'page': '页码',
  322. 'limit': '每页数量',
  323. },
  324. 'query_track': {
  325. 'order_id': '订单ID',
  326. 'order_number': '订单号',
  327. 'tracking_number': '快递单号',
  328. 'page': '页码',
  329. 'limit': '每页数量',
  330. },
  331. 'query_customs_declaration_files': {
  332. 'outbound_numbers': '排舱单号',
  333. 'order_numbers': '订单号',
  334. 'page': '页码',
  335. 'limit': '每页数量',
  336. },
  337. 'query_outbound_list': {
  338. 'outbound_numbers': '排舱单号',
  339. 'order_numbers': '订单号',
  340. 'container_codes': '柜号',
  341. 'so_numbers': 'SO号',
  342. 'bl_numbers': '提单号',
  343. 'outbound_status': '排舱状态',
  344. 'shipping_method': '运输方式',
  345. 'warehouse_id': '集货仓库',
  346. 'is_direct_send': '是否直送柜',
  347. 'page': '页码',
  348. 'limit': '每页数量',
  349. },
  350. 'query_outbound_detail': {
  351. 'outbound_number': '排舱单号',
  352. 'page': '页码',
  353. 'limit': '每页数量',
  354. },
  355. 'query_order_detail': {
  356. 'order_number': '订单号', 'section': '详情模块',
  357. 'page': '页码', 'limit': '每页数量',
  358. },
  359. 'list_order_filter_options': {
  360. 'filter_type': '筛选项类型',
  361. 'keyword': '关键词',
  362. 'page': '页码',
  363. 'limit': '每页数量',
  364. },
  365. 'list_outbound_filter_options': {
  366. 'filter_type': '筛选类别',
  367. 'keyword': '显示名称',
  368. 'page': '页码',
  369. 'limit': '每页数量',
  370. },
  371. 'list_pending_outbound_export_filter_options': {
  372. 'filter_type': '筛选项类型',
  373. 'product_type_id': '产品分类',
  374. 'keyword': '关键词',
  375. 'page': '页码',
  376. 'limit': '每页数量',
  377. },
  378. 'export_pending_outbound_orders': {
  379. 'number': '单号',
  380. 'product_type_id': '产品分类',
  381. 'product_id': '物流产品',
  382. 'order_warehouse_id': '集货仓库',
  383. 'receiver_country': '目的国',
  384. 'is_remove': '是否装柜剔除',
  385. 'address': '派送地址',
  386. 'inbound_date': '入库时间',
  387. 'status': '订单状态',
  388. 'merge_declare_number': '合并报关单号',
  389. 'importer_id': '进口商',
  390. 'packing_type': '货物类型',
  391. 'is_battery': '带电属性',
  392. 'is_magnetic': '带磁属性',
  393. 'is_wood': '带木属性',
  394. 'is_other': '其他商品属性',
  395. 'is_fda': 'FDA产品属性',
  396. 'is_toy': '玩具属性',
  397. 'is_ultra_limit': '超长超重属性',
  398. 'is_sensitive': '敏感货属性',
  399. 'is_food': '食品属性',
  400. 'no_property': '无属性',
  401. },
  402. 'export_out_of_province_port_data': {
  403. 'outbound_numbers': '排舱单号',
  404. 'container_codes': '柜号',
  405. 'bl_numbers': '提单号',
  406. 'so_numbers': 'SO号',
  407. 'file_type': '资料类型',
  408. },
  409. }
  410. ERROR_MESSAGES = {
  411. 'MCP_1101': '设备配置已失效,请重新生成配置',
  412. 'MCP_1102': '设备会话已过期,请重新连接',
  413. 'MCP_1103': '员工账号不可用,请联系管理员',
  414. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  415. 'MCP_1201': '工具当前不可用',
  416. 'MCP_1202': '工具当前不可用',
  417. 'MCP_1301': '没有权限使用此工具',
  418. 'MCP_1501': '目标数据不可用',
  419. 'MCP_1502': '结果过多,请缩小查询范围',
  420. 'MCP_1601': '没有可导出的数据',
  421. 'MCP_9001': '工具调用失败,请稍后重试',
  422. }
  423. NON_RETRYABLE_CODES = frozenset((
  424. 'MCP_1101',
  425. 'MCP_1102',
  426. 'MCP_1103',
  427. 'MCP_1104',
  428. 'MCP_1201',
  429. 'MCP_1202',
  430. 'MCP_1301',
  431. 'MCP_1401',
  432. 'MCP_1501',
  433. 'MCP_1502',
  434. 'MCP_1601',
  435. ))
  436. def handles(self, tool_name):
  437. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  438. # Convert a backend envelope into text and structured display data.
  439. def present(self, tool_name, tool_result):
  440. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  441. return self._format_error()
  442. code = str(tool_result.get('code') or '').strip()
  443. meta = self._build_meta(tool_result.get('meta'))
  444. if code not in ('MCP_0000', '0'):
  445. return self._business_error(
  446. tool_name,
  447. code or 'MCP_9001',
  448. tool_result.get('msg'),
  449. meta,
  450. )
  451. data = tool_result.get('data')
  452. if not isinstance(data, dict):
  453. return self._format_error(meta)
  454. if tool_name in self.DETAIL_TOOLS:
  455. return self._present_outbound_detail(
  456. tool_name,
  457. data,
  458. tool_result.get('meta'),
  459. meta,
  460. )
  461. if tool_name in self.ORDER_DETAIL_TOOLS:
  462. return self._present_order_detail(data, tool_result.get('meta'), meta)
  463. if tool_name in self.TABLE_TOOLS:
  464. return self._present_table(
  465. tool_name,
  466. data,
  467. tool_result.get('meta'),
  468. meta,
  469. )
  470. if tool_name in self.OPTION_TOOLS:
  471. return self._present_options(data, tool_result.get('meta'), meta)
  472. return self._present_export(data, meta)
  473. def _present_order_detail(self, data, raw_meta, meta):
  474. if set(data) != {'section', 'order_number', 'payload'}:
  475. return self._format_error(meta)
  476. section = data.get('section')
  477. order_number = data.get('order_number')
  478. payload = data.get('payload')
  479. if (
  480. section not in self.ORDER_DETAIL_SECTIONS
  481. or not isinstance(order_number, str) or not order_number.strip()
  482. or not isinstance(payload, dict)
  483. ):
  484. return self._format_error(meta)
  485. content = {
  486. '订单号': order_number.strip(),
  487. '详情模块': self.ORDER_DETAIL_SECTIONS[section],
  488. }
  489. if section == 'all':
  490. all_content = self._present_order_detail_all(payload)
  491. if all_content is None:
  492. return self._format_error(meta)
  493. content.update(all_content)
  494. elif section == 'overview':
  495. expected = {
  496. 'status_nodes', 'order_info', 'freight_info',
  497. 'package_summary', 'trader_info',
  498. }
  499. if set(payload) != expected or not isinstance(payload['status_nodes'], list):
  500. return self._format_error(meta)
  501. nodes = []
  502. for row in payload['status_nodes']:
  503. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  504. if translated is None:
  505. return self._format_error(meta)
  506. state = row.get('state')
  507. time_kind = row.get('time_kind')
  508. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  509. return self._format_error(meta)
  510. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  511. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  512. nodes.append(translated)
  513. content['状态节点'] = nodes
  514. for raw_key, chinese_key in (
  515. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  516. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  517. ):
  518. translated = self._translate_exact(
  519. payload.get(raw_key),
  520. self.ORDER_DETAIL_FIELDS['overview'][raw_key],
  521. )
  522. if translated is None:
  523. return self._format_error(meta)
  524. content[chinese_key] = translated
  525. elif section == 'inbound':
  526. if set(payload) != {'summary', 'records'}:
  527. return self._format_error(meta)
  528. summary = self._translate_exact(
  529. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  530. )
  531. records = self._translate_order_detail_rows(section, payload.get('records'))
  532. if summary is None or records is None:
  533. return self._format_error(meta)
  534. content['入库概况'] = summary
  535. content['明细'] = records
  536. pagination = self._order_detail_pagination(raw_meta)
  537. if pagination is None:
  538. return self._format_error(meta)
  539. content['分页'] = pagination
  540. elif section == 'delivery':
  541. if set(payload) != {'summary', 'records'}:
  542. return self._format_error(meta)
  543. summary = self._translate_exact(
  544. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  545. )
  546. records = self._translate_order_detail_rows(section, payload.get('records'))
  547. if summary is None or records is None:
  548. return self._format_error(meta)
  549. content['派送汇总'] = summary
  550. content['明细'] = records
  551. pagination = self._order_detail_pagination(raw_meta)
  552. if pagination is None:
  553. return self._format_error(meta)
  554. content['分页'] = pagination
  555. else:
  556. if set(payload) != {'records'}:
  557. return self._format_error(meta)
  558. records = self._translate_order_detail_rows(section, payload.get('records'))
  559. pagination = self._order_detail_pagination(raw_meta)
  560. if records is None or pagination is None:
  561. return self._format_error(meta)
  562. content['明细'] = records
  563. content['分页'] = pagination
  564. text = json.dumps(content, ensure_ascii=False, indent=2)
  565. return self._success_result(content, text, meta)
  566. def _present_order_detail_all(self, payload):
  567. expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
  568. if set(payload) != expected_sections:
  569. return None
  570. overview = payload.get('overview')
  571. if not isinstance(overview, dict) or set(overview) != {
  572. 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
  573. } or not isinstance(overview['status_nodes'], list):
  574. return None
  575. overview_content = {'状态节点': []}
  576. for row in overview['status_nodes']:
  577. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  578. if translated is None:
  579. return None
  580. state = row.get('state')
  581. time_kind = row.get('time_kind')
  582. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  583. return None
  584. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  585. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  586. overview_content['状态节点'].append(translated)
  587. for raw_key, chinese_key in (
  588. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  589. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  590. ):
  591. translated = self._translate_exact(
  592. overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
  593. )
  594. if translated is None:
  595. return None
  596. overview_content[chinese_key] = translated
  597. result = {'订单概览': overview_content}
  598. for section, label in self.ORDER_DETAIL_SECTIONS.items():
  599. if section in ('overview', 'all'):
  600. continue
  601. translated = self._present_order_detail_all_section(section, payload.get(section))
  602. if translated is None:
  603. return None
  604. result[label] = translated
  605. return result
  606. def _present_order_detail_all_section(self, section, payload):
  607. if not isinstance(payload, dict) or 'pagination' not in payload:
  608. return None
  609. pagination = self._order_detail_pagination(payload.get('pagination'))
  610. if pagination is None:
  611. return None
  612. if section == 'inbound':
  613. if set(payload) != {'summary', 'records', 'pagination'}:
  614. return None
  615. summary = self._translate_exact(
  616. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  617. )
  618. records = self._translate_order_detail_rows(section, payload.get('records'))
  619. if summary is None or records is None:
  620. return None
  621. return {'入库概况': summary, '明细': records, '分页': pagination}
  622. if section == 'delivery':
  623. if set(payload) != {'summary', 'records', 'pagination'}:
  624. return None
  625. summary = self._translate_exact(
  626. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  627. )
  628. records = self._translate_order_detail_rows(section, payload.get('records'))
  629. if summary is None or records is None:
  630. return None
  631. return {'派送汇总': summary, '明细': records, '分页': pagination}
  632. if set(payload) != {'records', 'pagination'}:
  633. return None
  634. records = self._translate_order_detail_rows(section, payload.get('records'))
  635. if records is None:
  636. return None
  637. return {'明细': records, '分页': pagination}
  638. def _translate_order_detail_rows(self, section, records):
  639. if not isinstance(records, list):
  640. return None
  641. mapping = self.ORDER_DETAIL_FIELDS.get(section)
  642. if not isinstance(mapping, dict):
  643. return None
  644. translated_rows = []
  645. for row in records:
  646. translated = self._translate_exact(row, mapping)
  647. if translated is None:
  648. return None
  649. if section == 'inbound':
  650. mode = row.get('weight_mode')
  651. if mode not in ('single_box', 'total'):
  652. return None
  653. translated[
  654. '单箱入库重量' if mode == 'single_box' else '总重量KG'
  655. ] = row.get('weight', '')
  656. translated_rows.append(translated)
  657. return translated_rows
  658. @staticmethod
  659. def _translate_exact(value, mapping):
  660. if not isinstance(value, dict) or set(value) != set(mapping):
  661. return None
  662. result = {}
  663. for key, label in mapping.items():
  664. if label is None:
  665. continue
  666. item = value.get(key, '')
  667. if isinstance(item, (dict, list)):
  668. return None
  669. result[label] = '' if item is None else item
  670. return result
  671. @staticmethod
  672. def _order_detail_pagination(raw_meta):
  673. if not isinstance(raw_meta, dict):
  674. return None
  675. if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
  676. return None
  677. page = raw_meta.get('page')
  678. limit = raw_meta.get('limit')
  679. has_more = raw_meta.get('has_more')
  680. if isinstance(page, bool) or not isinstance(page, int) or page < 1:
  681. return None
  682. if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
  683. return None
  684. if not isinstance(has_more, bool):
  685. return None
  686. return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
  687. # Map local tool exceptions without exposing internal error details.
  688. def present_exception(self, tool_name, exception):
  689. if not self.handles(tool_name):
  690. return self._format_error()
  691. message = str(exception or '').strip()
  692. if isinstance(exception, ValueError):
  693. label = self._find_field_label(tool_name, message)
  694. return self._error_result(
  695. 'MCP_1401',
  696. self._parameter_message(label),
  697. False,
  698. )
  699. if message == DEVICE_INVALID_MESSAGE:
  700. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  701. if message.lower().startswith('tool disabled'):
  702. return self._error_result('MCP_1202', '工具当前不可用', False)
  703. return self._error_result(
  704. 'MCP_9001',
  705. '工具调用失败,请稍后重试',
  706. True,
  707. )
  708. def _present_table(self, tool_name, data, raw_meta, meta):
  709. columns = data.get('columns')
  710. records = data.get('records')
  711. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  712. return self._format_error(meta)
  713. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  714. if not isinstance(allowed_columns, dict):
  715. return self._format_error(meta)
  716. headers = []
  717. keys = []
  718. for column in columns:
  719. if not isinstance(column, dict):
  720. return self._format_error(meta)
  721. key = column.get('key')
  722. label = column.get('name')
  723. if not isinstance(key, str) or not key.strip():
  724. return self._format_error(meta)
  725. if not isinstance(label, str) or not label.strip():
  726. return self._format_error(meta)
  727. key = key.strip()
  728. definition = allowed_columns.get(key)
  729. if not isinstance(definition, tuple) or not definition:
  730. return self._format_error(meta)
  731. keys.append(key)
  732. header = {'label': definition[0]}
  733. if len(definition) > 1:
  734. header['description'] = definition[1]
  735. headers.append(header)
  736. rows = []
  737. for record in records:
  738. if not isinstance(record, dict):
  739. return self._format_error(meta)
  740. rows.append([
  741. '' if record.get(key) is None else record.get(key, '')
  742. for key in keys
  743. ])
  744. content = {
  745. 'summary': self._safe_text(data.get('summary')),
  746. 'headers': headers,
  747. 'rows': rows,
  748. }
  749. tips = self._safe_tips(data.get('tips'))
  750. if tips:
  751. content['tips'] = tips
  752. pagination = self._build_pagination(raw_meta)
  753. if pagination:
  754. content['pagination'] = pagination
  755. return self._success_result(content, self._render_table(content), meta)
  756. def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
  757. summary = data.get('summary')
  758. columns = data.get('columns')
  759. records = data.get('records')
  760. if not isinstance(summary, dict):
  761. return self._format_error(meta)
  762. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  763. return self._format_error(meta)
  764. if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
  765. return self._format_error(meta)
  766. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  767. headers = []
  768. keys = []
  769. for column in columns:
  770. if not isinstance(column, dict):
  771. return self._format_error(meta)
  772. key = column.get('key')
  773. definition = allowed_columns.get(key) if isinstance(key, str) else None
  774. if not isinstance(definition, tuple) or not definition:
  775. return self._format_error(meta)
  776. keys.append(key)
  777. headers.append({'label': definition[0]})
  778. rows = []
  779. for record in records:
  780. if not isinstance(record, dict):
  781. return self._format_error(meta)
  782. row = []
  783. for key in keys:
  784. value = '' if record.get(key) is None else record.get(key, '')
  785. if key == 'customs_files':
  786. if not isinstance(value, list):
  787. return self._format_error(meta)
  788. files = []
  789. for item in value:
  790. if not isinstance(item, dict):
  791. return self._format_error(meta)
  792. files.append({
  793. '文件名称': item.get('file_name', ''),
  794. '文件类型': item.get('file_type', ''),
  795. '文件链接': item.get('file_url', ''),
  796. })
  797. value = files
  798. row.append(value)
  799. rows.append(row)
  800. summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
  801. content = {
  802. 'summary': {
  803. 'headers': [
  804. {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
  805. for key in summary_keys
  806. ],
  807. 'row': [summary.get(key, '') for key in summary_keys],
  808. },
  809. 'details': {
  810. 'headers': headers,
  811. 'rows': rows,
  812. },
  813. }
  814. tips = self._safe_tips(data.get('tips'))
  815. if tips:
  816. content['details']['tips'] = tips
  817. pagination = self._build_pagination(raw_meta)
  818. if pagination:
  819. content['details']['pagination'] = pagination
  820. return self._success_result(
  821. content,
  822. self._render_outbound_detail(content),
  823. meta,
  824. )
  825. @classmethod
  826. def _render_outbound_detail(cls, content):
  827. lines = ['排舱汇总:']
  828. summary = content['summary']
  829. for header, value in zip(summary['headers'], summary['row']):
  830. lines.append('- {0}: {1}'.format(header['label'], value))
  831. lines.append('订单明细:')
  832. details = content['details']
  833. lines.append('表头共 {0} 列:'.format(len(details['headers'])))
  834. for index, header in enumerate(details['headers'], start=1):
  835. lines.append('{0}. {1}'.format(index, header['label']))
  836. for index, row in enumerate(details['rows'], start=1):
  837. lines.append('记录 {0}:'.format(index))
  838. for header, value in zip(details['headers'], row):
  839. if isinstance(value, (dict, list)):
  840. value = json.dumps(value, ensure_ascii=False)
  841. lines.append('- {0}: {1}'.format(header['label'], value))
  842. tips = details.get('tips') or []
  843. if tips:
  844. lines.append('提示:{0}'.format(';'.join(tips)))
  845. return '\n'.join(lines)
  846. def _present_options(self, data, raw_meta, meta):
  847. records = data.get('records')
  848. if not isinstance(records, list):
  849. return self._format_error(meta)
  850. rows = []
  851. for record in records:
  852. if not isinstance(record, dict):
  853. return self._format_error(meta)
  854. rows.append([
  855. record.get('value', ''),
  856. self._safe_text(record.get('label')),
  857. self._safe_text(record.get('code')),
  858. ])
  859. content = {
  860. 'headers': [
  861. {'label': '可传值'},
  862. {'label': '显示名称'},
  863. {'label': '业务编码'},
  864. ],
  865. 'rows': rows,
  866. }
  867. pagination = self._build_pagination(raw_meta)
  868. if pagination:
  869. content['pagination'] = pagination
  870. return self._success_result(content, self._render_table(content), meta)
  871. def _present_export(self, data, meta):
  872. url = data.get('file_url')
  873. if not isinstance(url, str) or not url.strip():
  874. return self._format_error(meta)
  875. content = {
  876. 'message': '文件已生成',
  877. 'files': [{'label': '导出文件', 'url': url.strip()}],
  878. }
  879. text = '文件已生成\n- 导出文件: {0}'.format(url.strip())
  880. return self._success_result(content, text, meta)
  881. def _business_error(self, tool_name, code, raw_message, meta):
  882. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  883. logger.warning(
  884. 'Unknown MCP business error code',
  885. extra={
  886. 'request_id': meta.get('request_id', ''),
  887. 'tool_code': tool_name,
  888. 'backend_code': code,
  889. 'response_code': 'MCP_9001',
  890. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  891. },
  892. )
  893. code = 'MCP_9001'
  894. if code == 'MCP_1401':
  895. label = self._find_field_label(tool_name, raw_message)
  896. message = self._parameter_message(label)
  897. else:
  898. message = self.ERROR_MESSAGES[code]
  899. retryable = code not in self.NON_RETRYABLE_CODES
  900. return self._error_result(code, message, retryable, meta)
  901. def _find_field_label(self, tool_name, raw_message):
  902. message = str(raw_message or '')
  903. fields = self.FIELD_LABELS.get(tool_name, {})
  904. for field in sorted(fields, key=len, reverse=True):
  905. if field in message:
  906. return fields[field]
  907. return ''
  908. @staticmethod
  909. def _parameter_message(label):
  910. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  911. @staticmethod
  912. def _build_meta(raw_meta):
  913. if not isinstance(raw_meta, dict):
  914. return {}
  915. request_id = raw_meta.get('request_id')
  916. if not isinstance(request_id, str) or not request_id.strip():
  917. return {}
  918. return {'request_id': request_id.strip()}
  919. @staticmethod
  920. def _build_pagination(raw_meta):
  921. if not isinstance(raw_meta, dict):
  922. return {}
  923. return {
  924. key: raw_meta[key]
  925. for key in ('page', 'limit', 'has_more', 'total')
  926. if key in raw_meta
  927. }
  928. @staticmethod
  929. def _safe_text(value):
  930. if value is None:
  931. return ''
  932. return str(value).strip()
  933. @classmethod
  934. def _safe_tips(cls, value):
  935. if not isinstance(value, list):
  936. return []
  937. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  938. @classmethod
  939. def _render_table(cls, content):
  940. headers = content.get('headers') or []
  941. rows = content.get('rows') or []
  942. lines = []
  943. summary = cls._safe_text(content.get('summary'))
  944. if summary:
  945. lines.append(summary)
  946. lines.append('表头共 {0} 列:'.format(len(headers)))
  947. for index, header in enumerate(headers, start=1):
  948. lines.append('{0}. {1}'.format(index, header['label']))
  949. for index, row in enumerate(rows, start=1):
  950. lines.append('记录 {0}:'.format(index))
  951. for header, value in zip(headers, row):
  952. if isinstance(value, (dict, list)):
  953. value = json.dumps(value, ensure_ascii=False)
  954. lines.append('- {0}: {1}'.format(header['label'], value))
  955. tips = content.get('tips') or []
  956. if tips:
  957. lines.append('提示:{0}'.format(';'.join(tips)))
  958. return '\n'.join(lines)
  959. @staticmethod
  960. def _success_result(content, text, meta):
  961. return {
  962. 'structured_content': content,
  963. 'text': text,
  964. 'is_error': False,
  965. 'meta': meta,
  966. }
  967. @staticmethod
  968. def _error_result(code, message, retryable, meta=None):
  969. return {
  970. 'structured_content': {
  971. 'code': code,
  972. 'message': message,
  973. 'retryable': retryable,
  974. },
  975. 'text': '{0}: {1}'.format(code, message),
  976. 'is_error': True,
  977. 'meta': meta or {},
  978. }
  979. @classmethod
  980. def _format_error(cls, meta=None):
  981. return cls._error_result(
  982. 'MCP_9001',
  983. '工具返回格式异常',
  984. True,
  985. meta,
  986. )