output_presenter.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. import json
  2. import logging
  3. import math
  4. from urllib.parse import urlparse
  5. from constants import DEVICE_INVALID_MESSAGE
  6. logger = logging.getLogger(__name__)
  7. # Builds AI-safe MCP results for the explicitly supported tool set.
  8. class OutputPresenter:
  9. TABLE_TOOLS = frozenset((
  10. 'query_order_exact',
  11. 'query_track',
  12. 'query_customs_declaration_files',
  13. 'query_outbound_list',
  14. 'query_customer_list',
  15. ))
  16. PAYMENT_FOLLOWUP_TOOLS = frozenset(('query_customer_payment_followup',))
  17. PAYMENT_DETAIL_TOOLS = frozenset((
  18. 'query_customer_unverified_bill_details',
  19. ))
  20. DETAIL_TOOLS = frozenset(('query_outbound_detail',))
  21. ORDER_DETAIL_TOOLS = frozenset(('query_order_detail',))
  22. OPTION_TOOLS = frozenset((
  23. 'list_order_filter_options',
  24. 'list_outbound_filter_options',
  25. 'list_pending_outbound_export_filter_options',
  26. 'list_customer_filter_options',
  27. ))
  28. EXPORT_TOOLS = frozenset((
  29. 'export_pending_outbound_orders',
  30. 'export_out_of_province_port_data',
  31. ))
  32. TASK_TOOLS = frozenset(('query_export_task',))
  33. SAFE_TOOLS = (
  34. TABLE_TOOLS | DETAIL_TOOLS | ORDER_DETAIL_TOOLS | PAYMENT_FOLLOWUP_TOOLS
  35. | PAYMENT_DETAIL_TOOLS
  36. | OPTION_TOOLS | EXPORT_TOOLS | TASK_TOOLS
  37. )
  38. ORDER_DETAIL_SECTIONS = {
  39. 'overview': '订单概览',
  40. 'packages': '箱单信息',
  41. 'package_items': '箱单商品',
  42. 'dw_auth': 'DW授权信息',
  43. 'attachments': '附件信息',
  44. 'inbound': '入库信息',
  45. 'checks': '查验信息',
  46. 'tracks': '订单轨迹',
  47. 'operation_logs': '操作日志',
  48. 'cost_logs': '应收与结算日志',
  49. 'delivery': '派送信息',
  50. 'all': '全部',
  51. }
  52. ORDER_DETAIL_FIELDS = {
  53. 'overview': {
  54. 'order_info': {
  55. 'order_number': '订单号', 'reference_number': '客户参考号',
  56. 'customer_name': '客户名称', 'departure_country': '起运国',
  57. 'destination_country': '目的国', 'package_method': '包装类型',
  58. 'product_name': '物流产品', 'forecast_pwv': '预报件重体',
  59. 'inbound_pwv': '入库件重体',
  60. 'receivable_charge_weight': '应收计费重/体积',
  61. 'settlement_charge_weight': '结算计费重/体积',
  62. 'declaration_type': '报关类型', 'pre_recording': '是否需要预录单',
  63. 'idcard_name': '企业/个人姓名',
  64. 'idcard_number': '社会信用代码/身份证号',
  65. 'outbound_number': '排舱单号', 'container_mode': '直送柜/拼柜',
  66. 'track_map_available': '是否可查看轨迹地图', 'insurance': '购买保险',
  67. 'delivery_way': '派送方式', 'return_shipping_surcharge': '退运附加',
  68. 'work_order_count': '工单数量', 'bill_remark': '账单备注',
  69. 'remark': '订单备注',
  70. },
  71. 'freight_info': {
  72. 'estimated_inbound_time': '预计入库时间', 'cargo_type': '货物类型',
  73. 'pickup_way': '交货方式', 'warehouse': '交货仓库',
  74. 'pickup_address': '提货地址', 'pickup_contact': '提货联系人',
  75. 'pickup_phone': '提货联系电话', 'delivery_type': '派送类型',
  76. 'delivery_address': '派送地址', 'delivery_remark': '派送备注',
  77. 'oversea_warehouse': '海外仓',
  78. },
  79. 'package_summary': {
  80. 'box_count': '箱数', 'total_weight': '重量', 'weight_unit': '重量单位',
  81. 'total_volume': '体积', 'sku_count': 'SKU数量',
  82. 'clearance_total_price': '清关总价', 'clearance_currency': '清关币种',
  83. 'purchase_total_price': '采购总价', 'purchase_currency': '采购币种',
  84. },
  85. 'trader_info': {
  86. 'exporter': '出口商', 'importer': '进口商',
  87. 'coo_required': '是否做产地证',
  88. },
  89. },
  90. 'packages': {
  91. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  92. 'sku_summary': 'SKU', 'product_name_summary': '商品名',
  93. 'box_quantity': '箱数', 'box_length_cm': '单箱长(CM)',
  94. 'box_width_cm': '单箱宽(CM)', 'box_height_cm': '单箱高(CM)',
  95. 'gross_weight_kg': '单箱毛重量(KG)', 'net_weight_kg': '单箱净重量(KG)',
  96. 'is_over_length': '长度是否超限', 'is_over_width': '宽度是否超限',
  97. 'is_over_height': '高度是否超限', 'is_over_weight': '重量是否超限',
  98. },
  99. 'package_items': {
  100. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  101. 'box_specification': '箱规', 'box_specification_unit': '箱规单位',
  102. 'package_gross_weight_kg': '箱单单箱毛重(KG)',
  103. 'package_net_weight_kg': '箱单单箱净重(KG)',
  104. 'inspection_result': '查验结果', 'exception_reason': '异常原因',
  105. 'inspection_photo_count': '查验图片数量', 'sku': 'SKU',
  106. 'units_per_box': '单箱个数', 'declaration_type': '报关类型',
  107. 'box_number': '箱号', 'item_gross_weight_kg': '商品单箱毛重量(KG)',
  108. 'item_net_weight_kg': '商品单箱净重量(KG)', 'chinese_name': '中文品名',
  109. 'english_name': '英文名称', 'brand_type': '品牌类型', 'brand': '品牌',
  110. 'model': '型号', 'material_cn': '材质(CN)', 'material_en': '材质(EN)',
  111. 'purpose_cn': '用途', 'goods_attributes': '商品属性',
  112. 'declaration_hs_code': '报关编码', 'clearance_hs_code': '清关编码',
  113. 'material_ratio': '材质占比', 'clearance_unit_price': '清关单价',
  114. 'clearance_currency': '清关币种', 'purchase_unit_price': '采购单价',
  115. 'purchase_currency': '采购币种', 'product_image_count': '商品图片数量',
  116. 'remark': '备注',
  117. },
  118. 'dw_auth': {
  119. 'fba_id': 'FBAID', 'dw_start': 'DW开始时间', 'dw_end': 'DW结束时间',
  120. 'dw_display': 'DW', 'authorization_status': '客户授权状态',
  121. },
  122. 'attachments': {
  123. 'category': '附件分类', 'file_name': '文件名称',
  124. 'file_extension': '文件类型', 'is_image': '是否图片',
  125. 'preview_url': '预览链接', 'download_url': '下载链接',
  126. 'cost_name': '收费项目',
  127. },
  128. 'inbound_summary': {
  129. 'inbound_status': '入库状态', 'inbound_time': '入库时间',
  130. 'inbound_operator': '操作人', 'warehouse': '仓库',
  131. 'abnormal_reason': '异常原因', 'inbound_photo_count': '入库图片数量',
  132. 'forecast_pwv_summary': '预报件重体', 'inbound_pwv_summary': '入库件重体',
  133. },
  134. 'inbound': {
  135. 'has_label': '是否贴标', 'shipment_id': 'SHIPMENT ID',
  136. 'inbound_quantity': '入库件数',
  137. 'measurement_photo_count': '测量图片数量',
  138. 'box_specification': '入库箱规', 'weight_mode': None, 'weight': None,
  139. 'weight_unit': '重量单位', 'is_over_length': '长度是否超限',
  140. 'is_over_width': '宽度是否超限', 'is_over_height': '高度是否超限',
  141. 'is_over_weight': '重量是否超限', 'operated_at': '操作时间',
  142. },
  143. 'checks': {
  144. 'shipment_id': '货件编号', 'sku': 'SKU', 'box_number': '箱号',
  145. 'box_quantity': '箱数', 'box_specification': '箱规',
  146. 'inspection_result': '查验结果',
  147. 'inspection_photo_count': '查验图片数量', 'remark': '备注',
  148. 'inspector': '查验人', 'inspected_at': '查验时间',
  149. },
  150. 'tracks': {
  151. 'track_type': '轨迹类型', 'status': '轨迹节点', 'location': '轨迹地点',
  152. 'occurred_at': '时间', 'tracking_number': '跟踪号',
  153. 'shipment_id': 'SHIPMENT ID', 'content': '轨迹内容',
  154. },
  155. 'operation_logs': {
  156. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  157. },
  158. 'cost_logs': {
  159. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  160. },
  161. 'delivery_summary': {
  162. 'master_tracking_number': '主跟踪号', 'sub_order_count': '子单数量',
  163. },
  164. 'delivery': {'sub_tracking_number': '子跟踪号'},
  165. }
  166. ORDER_DETAIL_STATUS_FIELDS = {
  167. 'stage': '阶段', 'label': '节点', 'state': '状态',
  168. 'occurred_at': '时间', 'time_kind': '时间类型',
  169. }
  170. ORDER_DETAIL_STATES = {
  171. 'completed': '已完成', 'in_progress': '进行中',
  172. 'pending': '待完成', 'hidden': '不展示',
  173. }
  174. ORDER_DETAIL_TIME_KINDS = {
  175. 'actual': '实际', 'estimated': '预计', 'empty': '暂无',
  176. }
  177. TABLE_COLUMNS = {
  178. 'query_order_exact': {
  179. 'order_number': ('订单号',),
  180. 'reference_number': ('客户参考号',),
  181. 'status_txt_name': ('状态',),
  182. 'check_status_txt_name': ('是否已查验',),
  183. 'customer_name': ('客户名称',),
  184. 'customer_account_type_name': ('客户属性',),
  185. 'inbound_date': ('入库时间',),
  186. 'wo_num': ('未完成工单',),
  187. 'product_name': ('物流产品',),
  188. 'inbound_pieces': ('件数',),
  189. 'inbound_volume': ('体积(CBM)',),
  190. 'inbound_weight': ('重量(KG)',),
  191. 'pro_cn_name': ('品名',),
  192. 'export_declaration_type': ('报关方式',),
  193. 'merge_declare_number': ('合并报关单号',),
  194. 'delivery_address': ('派送地址',),
  195. 'container_code': ('柜号',),
  196. 'out_status_txt': ('排舱单状态',),
  197. 'hinge_of_destination': ('目的港',),
  198. 'etd': ('ETD',),
  199. 'atd': ('ATD',),
  200. 'eta': ('ETA',),
  201. 'ata': ('ATA',),
  202. 'release_time': ('清关放行时间',),
  203. 'oversea_inbound_date': ('海外入库时间',),
  204. 'appt_time': ('APPT时间',),
  205. 'est_loading_time': ('预计装柜时间',),
  206. 'pickup_time': ('海外提柜时间',),
  207. 'delivery_way_title': ('派送方式',),
  208. 'tracking_number': ('快递单号', '承运商跟踪号码'),
  209. 'shipment_id': ('Shipment ID',),
  210. 'goods_attribute': ('商品属性',),
  211. 'sku': ('SKU',),
  212. 'sales_user': ('商务经理',),
  213. 'service_user': ('客户经理',),
  214. 'department_name': ('事业部',),
  215. 'remark': ('订单备注',),
  216. 'importer_name': ('进口商',),
  217. 'warehouse_name': ('交货仓库',),
  218. 'paid_status_name': ('付款状态',),
  219. },
  220. 'query_track': {
  221. 'status': ('轨迹节点', '轨迹状态,如:开始集港、离港放行、清关、配送等'),
  222. 'location': ('轨迹地点', '发生地点'),
  223. 'time': ('时间', '轨迹发生时间(已转换为用户时区)'),
  224. 'content': ('轨迹内容', '详细描述'),
  225. 'tracking_number': ('跟踪号', '快递单号'),
  226. 'shipment_id': ('Shipment ID', '包裹ID'),
  227. },
  228. 'query_customs_declaration_files': {
  229. 'outbound_number': ('排舱单号',),
  230. 'order_number': ('订单号',),
  231. 'file_name': ('文件名',),
  232. 'file_type': ('文件类型',),
  233. 'file_url': ('文件链接',),
  234. },
  235. 'query_outbound_list': {
  236. 'outbound_number': ('排舱单号',),
  237. 'direct_send': ('直送柜',),
  238. 'remark': ('备注',),
  239. 'cargo_type': ('超长超重',),
  240. 'warehouse_name': ('集货仓库',),
  241. 'status': ('状态',),
  242. 'so_number': ('SO号',),
  243. 'container_code': ('柜号',),
  244. 'seal_number': ('封条号',),
  245. 'container_type': ('柜型',),
  246. 'shipping_method': ('运输方式',),
  247. 'total_volume': ('体积(CBM)',),
  248. 'total_weight': ('重量(KG)',),
  249. 'ship_schedule': ('船期',),
  250. 'closing_time': ('截关时间',),
  251. 'est_loading_time': ('预计装柜时间',),
  252. 'operator': ('操作人',),
  253. 'operation_modes': ('拖报清方式',),
  254. 'operation_time': ('操作时间',),
  255. 'ship_company': ('船司',),
  256. 'vessel_name': ('船名航次',),
  257. 'cutoff_time_si': ('截SI时间',),
  258. 'clearance_port': ('清关口岸',),
  259. 'loading_port': ('起运港',),
  260. 'destination_port': ('目的港',),
  261. 'transit_port': ('中转港',),
  262. 'etd': ('ETD',),
  263. 'eta': ('ETA',),
  264. 'has_fda': ('是否含FDA认证商品',),
  265. 'has_cpsc': ('是否含CPSC商品',),
  266. 'has_food': ('是否含食品',),
  267. },
  268. 'query_outbound_detail': {
  269. 'order_number': ('订单号',),
  270. 'cargo_type': ('超长超重',),
  271. 'customs_files': ('报关资料',),
  272. 'reference_number': ('客户参考号',),
  273. 'customer_name': ('客户名称',),
  274. 'declaration_type': ('报关方式',),
  275. 'merge_declare_number': ('合并报关单号',),
  276. 'order_remark': ('订单备注',),
  277. 'bl_number': ('提单号',),
  278. 'container_code': ('柜号',),
  279. 'customer_service': ('客户经理',),
  280. 'est_inbound_date': ('预计入库时间',),
  281. 'inbound_date': ('实际入库时间',),
  282. 'status': ('状态',),
  283. 'pieces': ('预报件数 / 入库件数',),
  284. 'weight': ('预报实重(KG) / 入库实重(KG)',),
  285. 'volume': ('预报体积(m³) / 入库体积(m³)',),
  286. 'pickup_place': ('交货地',),
  287. 'product_name': ('物流产品',),
  288. 'goods_name': ('品名',),
  289. 'closing_time': ('截关时间',),
  290. 'clearance_remark': ('报关备注',),
  291. 'import_clearance_remark': ('清关备注',),
  292. 'delivery_address': ('派送地址',),
  293. 'delivery_type': ('派送类型',),
  294. 'delivery_way': ('派送方式',),
  295. 'channel': ('派送渠道',),
  296. 'country_name': ('目的国',),
  297. 'importer_name': ('进口商',),
  298. 'vat_type': ('清关税号',),
  299. 'packing_type': ('货物类型',),
  300. 'is_abnormal': ('是否问题件',),
  301. 'package_method': ('包装类型',),
  302. 'order_reply': ('到货回复',),
  303. 'is_must_load': ('订单是否必装',),
  304. 'has_fda': ('是否含FDA认证商品',),
  305. 'has_cpsc': ('是否含CPSC商品',),
  306. 'has_food': ('是否含食品',),
  307. },
  308. 'query_customer_list': {
  309. 'customer_name': ('客户名称',),
  310. 'customer_code': ('客户代码',),
  311. 'create_time': ('开户时间',),
  312. 'business_type': ('业务类型',),
  313. 'customer_attribute': ('客户属性',),
  314. 'customer_source': ('客户来源',),
  315. 'first_inbound_date': ('首次成交时间',),
  316. 'last_inbound_date': ('最后一次走货时间',),
  317. 'active_status': ('活跃状态',),
  318. 'contract_status': ('合同状态',),
  319. 'contract_validity': ('合同有效期',),
  320. 'credit_limit': ('信用额度',),
  321. 'currency_code': ('结算币种',),
  322. 'billing_modes': ('结算模式(分业务类型)',),
  323. 'sales_name': ('商务经理',),
  324. 'merchandiser_name': ('客户经理',),
  325. 'department_name': ('事业部',),
  326. },
  327. }
  328. PAYMENT_FOLLOWUP_COLUMNS = {
  329. 'customer_name': '客户名称',
  330. 'settlement_currency': '结算币种',
  331. 'billed_unverified_amount': '已出账未核销金额',
  332. 'unbilled_amount': '未出账金额',
  333. 'overdue_unpaid_amount': '逾期未回款金额',
  334. 'billed_unverified_amount_cny': '已出账未核销金额(人民币)',
  335. 'unbilled_amount_cny': '未出账金额(人民币)',
  336. 'overdue_unpaid_amount_cny': '逾期未回款金额(人民币)',
  337. 'unverified_receivable_monthly_summary': '未回款月份汇总',
  338. 'receipt_unverified_amount': '收款单未核销金额',
  339. 'current_balance': '当前余额',
  340. 'credit_limit': '信用额度',
  341. 'bad_debt_total': '坏账合计',
  342. 'contract_status': '合同状态',
  343. }
  344. PAYMENT_FOLLOWUP_DETAIL_COLUMNS = {
  345. 'bill_month': '账单月份',
  346. 'bill_no': '账单号',
  347. 'business_type': '业务类型',
  348. 'settlement_mode': '结算模式',
  349. 'unverified_amount': '未核销金额',
  350. 'customer_receivable_date': '客户应收款日期',
  351. }
  352. PAYMENT_FOLLOWUP_MONTHLY_COLUMNS = {
  353. 'receivable_month': '应收月份',
  354. 'unverified_amount': '未核销金额',
  355. 'is_overdue': '是否逾期',
  356. }
  357. OUTBOUND_DETAIL_SUMMARY = {
  358. 'bl_number': '提单号',
  359. 'container_code': '柜号',
  360. 'container_type': '柜型',
  361. 'total_volume': '总体积',
  362. 'total_weight': '总重量',
  363. 'total_pieces': '总件数',
  364. 'sku': 'SKU',
  365. 'buy_declaration_count': '买单报关数量',
  366. 'general_declaration_count': '一般贸易报关数量',
  367. 'must_load': '必装单量/体积',
  368. 'backup_load': '备装单量/体积',
  369. }
  370. FIELD_LABELS = {
  371. 'query_order_exact': {
  372. 'order_number': '订单号',
  373. 'order_numbers': '订单号',
  374. 'reference_number': '客户参考号',
  375. 'reference_numbers': '客户参考号',
  376. 'tracking_number': '快递单号',
  377. 'tracking_numbers': '快递单号',
  378. 'outbound_number': '排舱单号',
  379. 'outbound_numbers': '排舱单号',
  380. 'container_code': '柜号',
  381. 'container_codes': '柜号',
  382. 'so_number': 'SO号',
  383. 'so_numbers': 'SO号',
  384. 'shipment_id': 'Shipment ID',
  385. 'receiver_country': '收货国家',
  386. 'product_ids': '物流产品',
  387. 'customer_ids': '客户',
  388. 'sales_id': '销售人员',
  389. 'warehouse_ids': '仓库',
  390. 'department_id': '事业部',
  391. 'inbound_date_start': '入库开始日期',
  392. 'inbound_date_end': '入库结束日期',
  393. 'outbound_date_start': '出库开始日期',
  394. 'outbound_date_end': '出库结束日期',
  395. 'page': '页码',
  396. 'limit': '每页数量',
  397. },
  398. 'query_track': {
  399. 'order_id': '订单ID',
  400. 'order_number': '订单号',
  401. 'tracking_number': '快递单号',
  402. 'page': '页码',
  403. 'limit': '每页数量',
  404. },
  405. 'query_customs_declaration_files': {
  406. 'outbound_numbers': '排舱单号',
  407. 'order_numbers': '订单号',
  408. 'page': '页码',
  409. 'limit': '每页数量',
  410. },
  411. 'query_outbound_list': {
  412. 'outbound_numbers': '排舱单号',
  413. 'order_numbers': '订单号',
  414. 'container_codes': '柜号',
  415. 'so_numbers': 'SO号',
  416. 'bl_numbers': '提单号',
  417. 'outbound_status': '排舱状态',
  418. 'shipping_method': '运输方式',
  419. 'warehouse_id': '集货仓库',
  420. 'is_direct_send': '是否直送柜',
  421. 'page': '页码',
  422. 'limit': '每页数量',
  423. },
  424. 'query_outbound_detail': {
  425. 'outbound_number': '排舱单号',
  426. 'page': '页码',
  427. 'limit': '每页数量',
  428. },
  429. 'query_order_detail': {
  430. 'order_number': '订单号', 'section': '详情模块',
  431. 'page': '页码', 'limit': '每页数量',
  432. },
  433. 'list_order_filter_options': {
  434. 'filter_type': '筛选项类型',
  435. 'keyword': '关键词',
  436. 'page': '页码',
  437. 'limit': '每页数量',
  438. },
  439. 'list_outbound_filter_options': {
  440. 'filter_type': '筛选类别',
  441. 'keyword': '显示名称',
  442. 'page': '页码',
  443. 'limit': '每页数量',
  444. },
  445. 'list_pending_outbound_export_filter_options': {
  446. 'filter_type': '筛选项类型',
  447. 'product_type_id': '产品分类',
  448. 'keyword': '关键词',
  449. 'page': '页码',
  450. 'limit': '每页数量',
  451. },
  452. 'query_customer_list': {
  453. 'customer_id': '客户名称',
  454. 'department_id': '事业部',
  455. 'sales_id': '商务经理',
  456. 'merchandiser_id': '客户经理',
  457. 'page': '页码',
  458. 'limit': '每页数量',
  459. },
  460. 'query_customer_payment_followup': {
  461. 'customer_id': '客户名称',
  462. 'department_id': '事业部',
  463. 'sales_id': '商务经理',
  464. 'merchandiser_id': '客户经理',
  465. 'has_unverified_receivable_only': '只看有应收未核销费用的客户',
  466. 'page': '页码',
  467. 'limit': '每页数量',
  468. },
  469. 'query_customer_unverified_bill_details': {
  470. 'customer_id': '客户名称',
  471. 'page': '页码',
  472. 'limit': '每页数量',
  473. },
  474. 'list_customer_filter_options': {
  475. 'filter_type': '筛选项类型',
  476. 'keyword': '关键词',
  477. 'page': '页码',
  478. 'limit': '每页数量',
  479. },
  480. 'export_pending_outbound_orders': {
  481. 'number': '单号',
  482. 'product_type_id': '产品分类',
  483. 'product_id': '物流产品',
  484. 'order_warehouse_id': '集货仓库',
  485. 'receiver_country': '目的国',
  486. 'is_remove': '是否装柜剔除',
  487. 'address': '派送地址',
  488. 'inbound_date': '入库时间',
  489. 'status': '订单状态',
  490. 'merge_declare_number': '合并报关单号',
  491. 'importer_id': '进口商',
  492. 'packing_type': '货物类型',
  493. 'is_battery': '带电属性',
  494. 'is_magnetic': '带磁属性',
  495. 'is_wood': '带木属性',
  496. 'is_other': '其他商品属性',
  497. 'is_fda': 'FDA产品属性',
  498. 'is_toy': '玩具属性',
  499. 'is_ultra_limit': '超长超重属性',
  500. 'is_sensitive': '敏感货属性',
  501. 'is_food': '食品属性',
  502. 'no_property': '无属性',
  503. },
  504. 'export_out_of_province_port_data': {
  505. 'outbound_numbers': '排舱单号',
  506. 'container_codes': '柜号',
  507. 'bl_numbers': '提单号',
  508. 'so_numbers': 'SO号',
  509. 'file_type': '资料类型',
  510. },
  511. 'query_export_task': {
  512. 'task_ref': '导出任务引用',
  513. },
  514. }
  515. ERROR_MESSAGES = {
  516. 'MCP_1101': '设备配置已失效,请重新生成配置',
  517. 'MCP_1102': '设备会话已过期,请重新连接',
  518. 'MCP_1103': '员工账号不可用,请联系管理员',
  519. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  520. 'MCP_1201': '工具当前不可用',
  521. 'MCP_1202': '工具当前不可用',
  522. 'MCP_1301': '没有权限使用此工具',
  523. 'MCP_1501': '目标数据不可用',
  524. 'MCP_1502': '结果过多,请缩小查询范围',
  525. 'MCP_1601': '没有可导出的数据',
  526. 'MCP_9001': '工具调用失败,请稍后重试',
  527. }
  528. NON_RETRYABLE_CODES = frozenset((
  529. 'MCP_1101',
  530. 'MCP_1102',
  531. 'MCP_1103',
  532. 'MCP_1104',
  533. 'MCP_1201',
  534. 'MCP_1202',
  535. 'MCP_1301',
  536. 'MCP_1401',
  537. 'MCP_1501',
  538. 'MCP_1502',
  539. 'MCP_1601',
  540. ))
  541. def handles(self, tool_name):
  542. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  543. # Convert a backend envelope into text and structured display data.
  544. def present(self, tool_name, tool_result):
  545. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  546. return self._format_error()
  547. code = str(tool_result.get('code') or '').strip()
  548. meta = self._build_meta(tool_result.get('meta'))
  549. if code not in ('MCP_0000', '0'):
  550. return self._business_error(
  551. tool_name,
  552. code or 'MCP_9001',
  553. tool_result.get('msg'),
  554. meta,
  555. )
  556. data = tool_result.get('data')
  557. if not isinstance(data, dict):
  558. return self._format_error(meta)
  559. if tool_name in self.DETAIL_TOOLS:
  560. return self._present_outbound_detail(
  561. tool_name,
  562. data,
  563. tool_result.get('meta'),
  564. meta,
  565. )
  566. if tool_name in self.ORDER_DETAIL_TOOLS:
  567. return self._present_order_detail(data, tool_result.get('meta'), meta)
  568. if tool_name in self.PAYMENT_FOLLOWUP_TOOLS:
  569. return self._present_customer_payment_followup(
  570. data, tool_result.get('meta'), meta
  571. )
  572. if tool_name in self.PAYMENT_DETAIL_TOOLS:
  573. return self._present_customer_unverified_bill_details(
  574. data, tool_result.get('meta'), meta
  575. )
  576. if tool_name in self.TABLE_TOOLS:
  577. return self._present_table(
  578. tool_name,
  579. data,
  580. tool_result.get('meta'),
  581. meta,
  582. )
  583. if tool_name in self.OPTION_TOOLS:
  584. if tool_name == 'list_customer_filter_options':
  585. return self._present_customer_options(
  586. data, tool_result.get('meta'), meta
  587. )
  588. return self._present_options(data, tool_result.get('meta'), meta)
  589. if tool_name in self.EXPORT_TOOLS:
  590. return self._present_export_submission(data, meta)
  591. return self._present_export_task(data, meta)
  592. def _present_order_detail(self, data, raw_meta, meta):
  593. if set(data) != {'section', 'order_number', 'payload'}:
  594. return self._format_error(meta)
  595. section = data.get('section')
  596. order_number = data.get('order_number')
  597. payload = data.get('payload')
  598. if (
  599. section not in self.ORDER_DETAIL_SECTIONS
  600. or not isinstance(order_number, str) or not order_number.strip()
  601. or not isinstance(payload, dict)
  602. ):
  603. return self._format_error(meta)
  604. content = {
  605. '订单号': order_number.strip(),
  606. '详情模块': self.ORDER_DETAIL_SECTIONS[section],
  607. }
  608. if section == 'all':
  609. all_content = self._present_order_detail_all(payload)
  610. if all_content is None:
  611. return self._format_error(meta)
  612. content.update(all_content)
  613. elif section == 'overview':
  614. expected = {
  615. 'status_nodes', 'order_info', 'freight_info',
  616. 'package_summary', 'trader_info',
  617. }
  618. if set(payload) != expected or not isinstance(payload['status_nodes'], list):
  619. return self._format_error(meta)
  620. nodes = []
  621. for row in payload['status_nodes']:
  622. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  623. if translated is None:
  624. return self._format_error(meta)
  625. state = row.get('state')
  626. time_kind = row.get('time_kind')
  627. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  628. return self._format_error(meta)
  629. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  630. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  631. nodes.append(translated)
  632. content['状态节点'] = nodes
  633. for raw_key, chinese_key in (
  634. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  635. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  636. ):
  637. translated = self._translate_exact(
  638. payload.get(raw_key),
  639. self.ORDER_DETAIL_FIELDS['overview'][raw_key],
  640. )
  641. if translated is None:
  642. return self._format_error(meta)
  643. content[chinese_key] = translated
  644. elif section == 'inbound':
  645. if set(payload) != {'summary', 'records'}:
  646. return self._format_error(meta)
  647. summary = self._translate_exact(
  648. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  649. )
  650. records = self._translate_order_detail_rows(section, payload.get('records'))
  651. if summary is None or records is None:
  652. return self._format_error(meta)
  653. content['入库概况'] = summary
  654. content['明细'] = records
  655. pagination = self._order_detail_pagination(raw_meta)
  656. if pagination is None:
  657. return self._format_error(meta)
  658. content['分页'] = pagination
  659. elif section == 'delivery':
  660. if set(payload) != {'summary', 'records'}:
  661. return self._format_error(meta)
  662. summary = self._translate_exact(
  663. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  664. )
  665. records = self._translate_order_detail_rows(section, payload.get('records'))
  666. if summary is None or records is None:
  667. return self._format_error(meta)
  668. content['派送汇总'] = summary
  669. content['明细'] = records
  670. pagination = self._order_detail_pagination(raw_meta)
  671. if pagination is None:
  672. return self._format_error(meta)
  673. content['分页'] = pagination
  674. else:
  675. if set(payload) != {'records'}:
  676. return self._format_error(meta)
  677. records = self._translate_order_detail_rows(section, payload.get('records'))
  678. pagination = self._order_detail_pagination(raw_meta)
  679. if records is None or pagination is None:
  680. return self._format_error(meta)
  681. content['明细'] = records
  682. content['分页'] = pagination
  683. text = json.dumps(content, ensure_ascii=False, indent=2)
  684. return self._success_result(content, text, meta)
  685. def _present_order_detail_all(self, payload):
  686. expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
  687. if set(payload) != expected_sections:
  688. return None
  689. overview = payload.get('overview')
  690. if not isinstance(overview, dict) or set(overview) != {
  691. 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
  692. } or not isinstance(overview['status_nodes'], list):
  693. return None
  694. overview_content = {'状态节点': []}
  695. for row in overview['status_nodes']:
  696. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  697. if translated is None:
  698. return None
  699. state = row.get('state')
  700. time_kind = row.get('time_kind')
  701. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  702. return None
  703. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  704. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  705. overview_content['状态节点'].append(translated)
  706. for raw_key, chinese_key in (
  707. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  708. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  709. ):
  710. translated = self._translate_exact(
  711. overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
  712. )
  713. if translated is None:
  714. return None
  715. overview_content[chinese_key] = translated
  716. result = {'订单概览': overview_content}
  717. for section, label in self.ORDER_DETAIL_SECTIONS.items():
  718. if section in ('overview', 'all'):
  719. continue
  720. translated = self._present_order_detail_all_section(section, payload.get(section))
  721. if translated is None:
  722. return None
  723. result[label] = translated
  724. return result
  725. def _present_order_detail_all_section(self, section, payload):
  726. if not isinstance(payload, dict) or 'pagination' not in payload:
  727. return None
  728. pagination = self._order_detail_pagination(payload.get('pagination'))
  729. if pagination is None:
  730. return None
  731. if section == 'inbound':
  732. if set(payload) != {'summary', 'records', 'pagination'}:
  733. return None
  734. summary = self._translate_exact(
  735. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  736. )
  737. records = self._translate_order_detail_rows(section, payload.get('records'))
  738. if summary is None or records is None:
  739. return None
  740. return {'入库概况': summary, '明细': records, '分页': pagination}
  741. if section == 'delivery':
  742. if set(payload) != {'summary', 'records', 'pagination'}:
  743. return None
  744. summary = self._translate_exact(
  745. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  746. )
  747. records = self._translate_order_detail_rows(section, payload.get('records'))
  748. if summary is None or records is None:
  749. return None
  750. return {'派送汇总': summary, '明细': records, '分页': pagination}
  751. if set(payload) != {'records', 'pagination'}:
  752. return None
  753. records = self._translate_order_detail_rows(section, payload.get('records'))
  754. if records is None:
  755. return None
  756. return {'明细': records, '分页': pagination}
  757. def _translate_order_detail_rows(self, section, records):
  758. if not isinstance(records, list):
  759. return None
  760. mapping = self.ORDER_DETAIL_FIELDS.get(section)
  761. if not isinstance(mapping, dict):
  762. return None
  763. translated_rows = []
  764. for row in records:
  765. translated = self._translate_exact(row, mapping)
  766. if translated is None:
  767. return None
  768. if section == 'inbound':
  769. mode = row.get('weight_mode')
  770. if mode not in ('single_box', 'total'):
  771. return None
  772. translated[
  773. '单箱入库重量' if mode == 'single_box' else '总重量KG'
  774. ] = row.get('weight', '')
  775. translated_rows.append(translated)
  776. return translated_rows
  777. @staticmethod
  778. def _translate_exact(value, mapping):
  779. if not isinstance(value, dict) or set(value) != set(mapping):
  780. return None
  781. result = {}
  782. for key, label in mapping.items():
  783. if label is None:
  784. continue
  785. item = value.get(key, '')
  786. if isinstance(item, (dict, list)):
  787. return None
  788. result[label] = '' if item is None else item
  789. return result
  790. @staticmethod
  791. def _order_detail_pagination(raw_meta):
  792. if not isinstance(raw_meta, dict):
  793. return None
  794. if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
  795. return None
  796. page = raw_meta.get('page')
  797. limit = raw_meta.get('limit')
  798. has_more = raw_meta.get('has_more')
  799. if isinstance(page, bool) or not isinstance(page, int) or page < 1:
  800. return None
  801. if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
  802. return None
  803. if not isinstance(has_more, bool):
  804. return None
  805. return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
  806. # Map local tool exceptions without exposing internal error details.
  807. def present_exception(self, tool_name, exception):
  808. if not self.handles(tool_name):
  809. return self._format_error()
  810. message = str(exception or '').strip()
  811. if isinstance(exception, ValueError):
  812. label = self._find_field_label(tool_name, message)
  813. return self._error_result(
  814. 'MCP_1401',
  815. self._parameter_message(label),
  816. False,
  817. )
  818. if message == DEVICE_INVALID_MESSAGE:
  819. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  820. if message.lower().startswith('tool disabled'):
  821. return self._error_result('MCP_1202', '工具当前不可用', False)
  822. return self._error_result(
  823. 'MCP_9001',
  824. '工具调用失败,请稍后重试',
  825. True,
  826. )
  827. def _present_table(self, tool_name, data, raw_meta, meta):
  828. columns = data.get('columns')
  829. records = data.get('records')
  830. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  831. return self._format_error(meta)
  832. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  833. if not isinstance(allowed_columns, dict):
  834. return self._format_error(meta)
  835. if tool_name == 'query_customer_list':
  836. expected = list(allowed_columns.keys())
  837. actual = [
  838. column.get('key') if isinstance(column, dict) else None
  839. for column in columns
  840. ]
  841. if actual != expected or self._customer_pagination(raw_meta) is None:
  842. return self._format_error(meta)
  843. headers = []
  844. keys = []
  845. for column in columns:
  846. if not isinstance(column, dict):
  847. return self._format_error(meta)
  848. key = column.get('key')
  849. label = column.get('name')
  850. if not isinstance(key, str) or not key.strip():
  851. return self._format_error(meta)
  852. if not isinstance(label, str) or not label.strip():
  853. return self._format_error(meta)
  854. key = key.strip()
  855. definition = allowed_columns.get(key)
  856. if not isinstance(definition, tuple) or not definition:
  857. return self._format_error(meta)
  858. keys.append(key)
  859. header = {'label': definition[0]}
  860. if len(definition) > 1:
  861. header['description'] = definition[1]
  862. headers.append(header)
  863. rows = []
  864. for record in records:
  865. if not isinstance(record, dict):
  866. return self._format_error(meta)
  867. if tool_name == 'query_customer_list' and set(record) != set(keys):
  868. return self._format_error(meta)
  869. row = []
  870. for key in keys:
  871. value = '' if record.get(key) is None else record.get(key, '')
  872. if tool_name == 'query_customer_list' and key == 'billing_modes':
  873. value = self._customer_billing_modes(value)
  874. if value is None:
  875. return self._format_error(meta)
  876. elif tool_name == 'query_customer_list' and isinstance(value, (dict, list)):
  877. return self._format_error(meta)
  878. row.append(value)
  879. rows.append(row)
  880. content = {
  881. 'summary': self._safe_text(data.get('summary')),
  882. 'headers': headers,
  883. 'rows': rows,
  884. }
  885. if tool_name == 'query_customer_list':
  886. content['display_rules'] = {
  887. 'mode': 'complete',
  888. 'allow_summary': False,
  889. 'allow_omit_records': False,
  890. 'allow_omit_empty_fields': False,
  891. 'allow_rename_fields': False,
  892. 'preserve_record_order': True,
  893. 'required_field_count': len(headers),
  894. 'returned_record_count': len(rows),
  895. 'required_value_count': len(headers) * len(rows),
  896. 'instruction': '最终回复必须逐条展示全部记录及全部17个字段,不得摘要、省略或改写',
  897. }
  898. tips = self._safe_tips(data.get('tips'))
  899. if tips:
  900. content['tips'] = tips
  901. pagination = self._build_pagination(raw_meta)
  902. if pagination:
  903. content['pagination'] = pagination
  904. return self._success_result(
  905. content,
  906. self._render_table(
  907. content,
  908. require_complete=tool_name == 'query_customer_list',
  909. ),
  910. meta,
  911. )
  912. def _present_customer_payment_followup(self, data, raw_meta, meta):
  913. if set(data) != {'columns', 'records'}:
  914. return self._format_error(meta)
  915. columns = data.get('columns')
  916. records = data.get('records')
  917. pagination = self._customer_pagination(raw_meta)
  918. expected_keys = list(self.PAYMENT_FOLLOWUP_COLUMNS)
  919. if not isinstance(columns, list) or not isinstance(records, list):
  920. return self._format_error(meta)
  921. actual_keys = []
  922. for column in columns:
  923. if (
  924. not isinstance(column, dict)
  925. or set(column) != {'key', 'name'}
  926. or not isinstance(column.get('key'), str)
  927. or not isinstance(column.get('name'), str)
  928. or not column.get('name').strip()
  929. ):
  930. return self._format_error(meta)
  931. actual_keys.append(column['key'])
  932. if actual_keys != expected_keys or pagination is None:
  933. return self._format_error(meta)
  934. amount_keys = {
  935. 'billed_unverified_amount', 'unbilled_amount',
  936. 'overdue_unpaid_amount', 'billed_unverified_amount_cny',
  937. 'unbilled_amount_cny', 'overdue_unpaid_amount_cny',
  938. 'receipt_unverified_amount', 'current_balance',
  939. 'credit_limit', 'bad_debt_total',
  940. }
  941. text_keys = {'customer_name', 'settlement_currency', 'contract_status'}
  942. rows = []
  943. for record in records:
  944. if not isinstance(record, dict) or set(record) != set(expected_keys):
  945. return self._format_error(meta)
  946. row = []
  947. for key in expected_keys:
  948. value = record[key]
  949. if key in amount_keys:
  950. if (
  951. isinstance(value, bool)
  952. or not isinstance(value, (int, float))
  953. or not math.isfinite(float(value))
  954. ):
  955. return self._format_error(meta)
  956. elif key in text_keys:
  957. if not isinstance(value, str):
  958. return self._format_error(meta)
  959. else:
  960. value = self._payment_followup_monthly_summaries(value)
  961. if value is None:
  962. return self._format_error(meta)
  963. row.append(value)
  964. rows.append(row)
  965. headers = [
  966. {'label': self.PAYMENT_FOLLOWUP_COLUMNS[key]}
  967. for key in expected_keys
  968. ]
  969. content = {
  970. 'headers': headers,
  971. 'rows': rows,
  972. 'pagination': pagination,
  973. 'display_rules': {
  974. 'mode': 'complete',
  975. 'allow_summary': False,
  976. 'allow_omit_records': False,
  977. 'allow_omit_empty_fields': False,
  978. 'allow_rename_fields': False,
  979. 'preserve_record_order': True,
  980. 'required_field_count': len(headers),
  981. 'returned_record_count': len(rows),
  982. 'required_value_count': len(headers) * len(rows),
  983. 'instruction': '最终回复必须逐条展示全部客户、全部字段和全部未回款月份汇总',
  984. },
  985. }
  986. return self._success_result(
  987. content,
  988. self._render_table(content, require_complete=True),
  989. meta,
  990. )
  991. def _payment_followup_monthly_summaries(self, summaries):
  992. if not isinstance(summaries, list):
  993. return None
  994. expected = set(self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS)
  995. translated = []
  996. for summary in summaries:
  997. if not isinstance(summary, dict) or set(summary) != expected:
  998. return None
  999. amount = summary.get('unverified_amount')
  1000. if (
  1001. isinstance(amount, bool)
  1002. or not isinstance(amount, (int, float))
  1003. or not math.isfinite(float(amount))
  1004. ):
  1005. return None
  1006. if (
  1007. not isinstance(summary.get('receivable_month'), str)
  1008. or not isinstance(summary.get('is_overdue'), bool)
  1009. ):
  1010. return None
  1011. item = {}
  1012. for key, label in self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS.items():
  1013. value = summary[key]
  1014. item[label] = value
  1015. translated.append(item)
  1016. return translated
  1017. def _present_customer_unverified_bill_details(self, data, raw_meta, meta):
  1018. if set(data) != {'columns', 'records'}:
  1019. return self._format_error(meta)
  1020. columns = data.get('columns')
  1021. records = data.get('records')
  1022. pagination = self._customer_pagination(raw_meta)
  1023. expected_keys = list(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1024. if not isinstance(columns, list) or not isinstance(records, list):
  1025. return self._format_error(meta)
  1026. actual_keys = []
  1027. for column in columns:
  1028. if (
  1029. not isinstance(column, dict)
  1030. or set(column) != {'key', 'name'}
  1031. or not isinstance(column.get('key'), str)
  1032. or not isinstance(column.get('name'), str)
  1033. or not column.get('name').strip()
  1034. ):
  1035. return self._format_error(meta)
  1036. actual_keys.append(column['key'])
  1037. if actual_keys != expected_keys or pagination is None:
  1038. return self._format_error(meta)
  1039. translated = self._payment_followup_details(records)
  1040. if translated is None:
  1041. return self._format_error(meta)
  1042. headers = [
  1043. {'label': self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS[key]}
  1044. for key in expected_keys
  1045. ]
  1046. rows = [[item[header['label']] for header in headers] for item in translated]
  1047. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1048. return self._success_result(content, self._render_table(content), meta)
  1049. def _payment_followup_details(self, details):
  1050. expected = set(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1051. translated = []
  1052. for detail in details:
  1053. if not isinstance(detail, dict) or set(detail) != expected:
  1054. return None
  1055. amount = detail.get('unverified_amount')
  1056. if (
  1057. isinstance(amount, bool)
  1058. or not isinstance(amount, (int, float))
  1059. or not math.isfinite(float(amount))
  1060. ):
  1061. return None
  1062. item = {}
  1063. for key, label in self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS.items():
  1064. value = detail[key]
  1065. if key != 'unverified_amount' and not isinstance(value, str):
  1066. return None
  1067. item[label] = value
  1068. translated.append(item)
  1069. return translated
  1070. @staticmethod
  1071. def _customer_billing_modes(value):
  1072. if not isinstance(value, list):
  1073. return None
  1074. result = []
  1075. business_types = set()
  1076. for item in value:
  1077. if not isinstance(item, dict) or set(item) != {
  1078. 'business_type', 'settlement_mode',
  1079. }:
  1080. return None
  1081. business_type = item.get('business_type')
  1082. settlement_mode = item.get('settlement_mode')
  1083. if (
  1084. not isinstance(business_type, str) or not business_type.strip()
  1085. or not isinstance(settlement_mode, str) or not settlement_mode.strip()
  1086. or business_type in business_types
  1087. ):
  1088. return None
  1089. business_types.add(business_type)
  1090. result.append({
  1091. '业务类型': business_type.strip(),
  1092. '结算模式': settlement_mode.strip(),
  1093. })
  1094. return result
  1095. def _present_customer_options(self, data, raw_meta, meta):
  1096. if set(data) != {'records'}:
  1097. return self._format_error(meta)
  1098. records = data.get('records')
  1099. pagination = self._customer_pagination(raw_meta)
  1100. if not isinstance(records, list) or pagination is None:
  1101. return self._format_error(meta)
  1102. rows = []
  1103. for record in records:
  1104. if not isinstance(record, dict) or set(record) != {'value', 'label', 'code'}:
  1105. return self._format_error(meta)
  1106. value = record.get('value')
  1107. label = record.get('label')
  1108. code = record.get('code')
  1109. if (
  1110. isinstance(value, bool) or not isinstance(value, int) or value < 1
  1111. or not isinstance(label, str) or not label.strip()
  1112. or not isinstance(code, str)
  1113. ):
  1114. return self._format_error(meta)
  1115. rows.append([value, label.strip(), code.strip()])
  1116. content = {
  1117. 'headers': [
  1118. {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
  1119. ],
  1120. 'rows': rows,
  1121. 'pagination': pagination,
  1122. }
  1123. return self._success_result(content, self._render_table(content), meta)
  1124. @staticmethod
  1125. def _customer_pagination(raw_meta):
  1126. if not isinstance(raw_meta, dict):
  1127. return None
  1128. required = {'page', 'limit', 'has_more'}
  1129. if (
  1130. not required.issubset(raw_meta)
  1131. or not set(raw_meta).issubset(required | {'request_id'})
  1132. ):
  1133. return None
  1134. page = raw_meta.get('page')
  1135. limit = raw_meta.get('limit')
  1136. has_more = raw_meta.get('has_more')
  1137. if (
  1138. isinstance(page, bool) or not isinstance(page, int)
  1139. or page < 1 or page > 100
  1140. or isinstance(limit, bool) or not isinstance(limit, int)
  1141. or limit < 1 or limit > 100
  1142. or not isinstance(has_more, bool)
  1143. ):
  1144. return None
  1145. return {'page': page, 'limit': limit, 'has_more': has_more}
  1146. def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
  1147. summary = data.get('summary')
  1148. columns = data.get('columns')
  1149. records = data.get('records')
  1150. if not isinstance(summary, dict):
  1151. return self._format_error(meta)
  1152. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  1153. return self._format_error(meta)
  1154. if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
  1155. return self._format_error(meta)
  1156. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  1157. headers = []
  1158. keys = []
  1159. for column in columns:
  1160. if not isinstance(column, dict):
  1161. return self._format_error(meta)
  1162. key = column.get('key')
  1163. definition = allowed_columns.get(key) if isinstance(key, str) else None
  1164. if not isinstance(definition, tuple) or not definition:
  1165. return self._format_error(meta)
  1166. keys.append(key)
  1167. headers.append({'label': definition[0]})
  1168. rows = []
  1169. for record in records:
  1170. if not isinstance(record, dict):
  1171. return self._format_error(meta)
  1172. row = []
  1173. for key in keys:
  1174. value = '' if record.get(key) is None else record.get(key, '')
  1175. if key == 'customs_files':
  1176. if not isinstance(value, list):
  1177. return self._format_error(meta)
  1178. files = []
  1179. for item in value:
  1180. if not isinstance(item, dict):
  1181. return self._format_error(meta)
  1182. files.append({
  1183. '文件名称': item.get('file_name', ''),
  1184. '文件类型': item.get('file_type', ''),
  1185. '文件链接': item.get('file_url', ''),
  1186. })
  1187. value = files
  1188. row.append(value)
  1189. rows.append(row)
  1190. summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
  1191. content = {
  1192. 'summary': {
  1193. 'headers': [
  1194. {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
  1195. for key in summary_keys
  1196. ],
  1197. 'row': [summary.get(key, '') for key in summary_keys],
  1198. },
  1199. 'details': {
  1200. 'headers': headers,
  1201. 'rows': rows,
  1202. },
  1203. }
  1204. tips = self._safe_tips(data.get('tips'))
  1205. if tips:
  1206. content['details']['tips'] = tips
  1207. pagination = self._build_pagination(raw_meta)
  1208. if pagination:
  1209. content['details']['pagination'] = pagination
  1210. return self._success_result(
  1211. content,
  1212. self._render_outbound_detail(content),
  1213. meta,
  1214. )
  1215. @classmethod
  1216. def _render_outbound_detail(cls, content):
  1217. lines = ['排舱汇总:']
  1218. summary = content['summary']
  1219. for header, value in zip(summary['headers'], summary['row']):
  1220. lines.append('- {0}: {1}'.format(header['label'], value))
  1221. lines.append('订单明细:')
  1222. details = content['details']
  1223. lines.append('表头共 {0} 列:'.format(len(details['headers'])))
  1224. for index, header in enumerate(details['headers'], start=1):
  1225. lines.append('{0}. {1}'.format(index, header['label']))
  1226. for index, row in enumerate(details['rows'], start=1):
  1227. lines.append('记录 {0}:'.format(index))
  1228. for header, value in zip(details['headers'], row):
  1229. if isinstance(value, (dict, list)):
  1230. value = json.dumps(value, ensure_ascii=False)
  1231. lines.append('- {0}: {1}'.format(header['label'], value))
  1232. tips = details.get('tips') or []
  1233. if tips:
  1234. lines.append('提示:{0}'.format(';'.join(tips)))
  1235. return '\n'.join(lines)
  1236. def _present_options(self, data, raw_meta, meta):
  1237. records = data.get('records')
  1238. if not isinstance(records, list):
  1239. return self._format_error(meta)
  1240. rows = []
  1241. for record in records:
  1242. if not isinstance(record, dict):
  1243. return self._format_error(meta)
  1244. rows.append([
  1245. record.get('value', ''),
  1246. self._safe_text(record.get('label')),
  1247. self._safe_text(record.get('code')),
  1248. ])
  1249. content = {
  1250. 'headers': [
  1251. {'label': '可传值'},
  1252. {'label': '显示名称'},
  1253. {'label': '业务编码'},
  1254. ],
  1255. 'rows': rows,
  1256. }
  1257. pagination = self._build_pagination(raw_meta)
  1258. if pagination:
  1259. content['pagination'] = pagination
  1260. return self._success_result(content, self._render_table(content), meta)
  1261. def _present_export_submission(self, data, meta):
  1262. expected = {'task_ref', 'status', 'retry_after_seconds'}
  1263. if set(data) != expected:
  1264. return self._format_error(meta)
  1265. task_ref = data.get('task_ref')
  1266. retry_after = data.get('retry_after_seconds')
  1267. if (
  1268. not isinstance(task_ref, str) or not task_ref.strip()
  1269. or data.get('status') != 'queued'
  1270. or isinstance(retry_after, bool)
  1271. or not isinstance(retry_after, int)
  1272. or retry_after <= 0
  1273. ):
  1274. return self._format_error(meta)
  1275. task = {
  1276. 'task_ref': task_ref.strip(),
  1277. 'status': 'queued',
  1278. 'retry_after_seconds': retry_after,
  1279. }
  1280. content = {
  1281. 'message': '导出任务已提交',
  1282. 'task': task,
  1283. }
  1284. text = (
  1285. '导出任务已提交\n'
  1286. '- 任务引用: {0}\n'
  1287. '- 建议 {1} 秒后单独查询任务状态'
  1288. ).format(task['task_ref'], retry_after)
  1289. return self._success_result(content, text, meta)
  1290. def _present_export_task(self, data, meta):
  1291. task_ref = data.get('task_ref')
  1292. status = data.get('status')
  1293. if (
  1294. not isinstance(task_ref, str)
  1295. or not task_ref.strip()
  1296. or status not in ('queued', 'running', 'completed', 'failed')
  1297. ):
  1298. return self._format_error(meta)
  1299. task = {'task_ref': task_ref.strip(), 'status': status}
  1300. if status in ('queued', 'running'):
  1301. if set(data) != {'task_ref', 'status', 'retry_after_seconds'}:
  1302. return self._format_error(meta)
  1303. retry_after = data.get('retry_after_seconds')
  1304. if (
  1305. isinstance(retry_after, bool)
  1306. or not isinstance(retry_after, int)
  1307. or retry_after <= 0
  1308. ):
  1309. return self._format_error(meta)
  1310. task['retry_after_seconds'] = retry_after
  1311. label = '等待中' if status == 'queued' else '生成中'
  1312. content = {'message': '导出任务{0}'.format(label), 'task': task}
  1313. text = (
  1314. '导出任务{0}\n- 任务引用: {1}\n- 建议 {2} 秒后再次查询'
  1315. ).format(label, task['task_ref'], retry_after)
  1316. return self._success_result(content, text, meta)
  1317. if status == 'failed':
  1318. if set(data) != {'task_ref', 'status'}:
  1319. return self._format_error(meta)
  1320. content = {'message': '导出任务失败,请重新提交', 'task': task}
  1321. text = '导出任务失败,请重新提交'
  1322. return self._success_result(content, text, meta)
  1323. if set(data) != {'task_ref', 'status', 'files'}:
  1324. return self._format_error(meta)
  1325. files = data.get('files')
  1326. if not isinstance(files, list) or not files:
  1327. return self._format_error(meta)
  1328. safe_files = []
  1329. for item in files:
  1330. if not isinstance(item, dict) or set(item) != {'label', 'url'}:
  1331. return self._format_error(meta)
  1332. label = item.get('label')
  1333. url = item.get('url')
  1334. if (
  1335. not isinstance(label, str) or not label.strip()
  1336. or not self._valid_http_url(url)
  1337. ):
  1338. return self._format_error(meta)
  1339. safe_files.append({'label': label.strip(), 'url': url.strip()})
  1340. content = {
  1341. 'message': '文件已生成',
  1342. 'task': task,
  1343. 'files': safe_files,
  1344. }
  1345. lines = ['文件已生成']
  1346. for item in safe_files:
  1347. lines.append('- {0}: {1}'.format(item['label'], item['url']))
  1348. return self._success_result(content, '\n'.join(lines), meta)
  1349. def _valid_http_url(self, value):
  1350. if not isinstance(value, str) or not value.strip():
  1351. return False
  1352. if value != value.strip() or '\\' in value or any(
  1353. character.isspace() or ord(character) < 32 or ord(character) == 127
  1354. for character in value
  1355. ):
  1356. return False
  1357. try:
  1358. parsed = urlparse(value)
  1359. port = parsed.port
  1360. return (
  1361. parsed.scheme in ('http', 'https')
  1362. and bool(parsed.hostname)
  1363. and parsed.username is None
  1364. and parsed.password is None
  1365. and (port is None or 0 < port <= 65535)
  1366. )
  1367. except ValueError:
  1368. return False
  1369. def _business_error(self, tool_name, code, raw_message, meta):
  1370. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  1371. logger.warning(
  1372. 'Unknown MCP business error code',
  1373. extra={
  1374. 'request_id': meta.get('request_id', ''),
  1375. 'tool_code': tool_name,
  1376. 'backend_code': code,
  1377. 'response_code': 'MCP_9001',
  1378. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  1379. },
  1380. )
  1381. code = 'MCP_9001'
  1382. if code == 'MCP_1401':
  1383. label = self._find_field_label(tool_name, raw_message)
  1384. message = self._parameter_message(label)
  1385. else:
  1386. message = self.ERROR_MESSAGES[code]
  1387. retryable = code not in self.NON_RETRYABLE_CODES
  1388. return self._error_result(code, message, retryable, meta)
  1389. def _find_field_label(self, tool_name, raw_message):
  1390. message = str(raw_message or '')
  1391. fields = self.FIELD_LABELS.get(tool_name, {})
  1392. for field in sorted(fields, key=len, reverse=True):
  1393. if field in message:
  1394. return fields[field]
  1395. return ''
  1396. @staticmethod
  1397. def _parameter_message(label):
  1398. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  1399. @staticmethod
  1400. def _build_meta(raw_meta):
  1401. if not isinstance(raw_meta, dict):
  1402. return {}
  1403. request_id = raw_meta.get('request_id')
  1404. if not isinstance(request_id, str) or not request_id.strip():
  1405. return {}
  1406. return {'request_id': request_id.strip()}
  1407. @staticmethod
  1408. def _build_pagination(raw_meta):
  1409. if not isinstance(raw_meta, dict):
  1410. return {}
  1411. return {
  1412. key: raw_meta[key]
  1413. for key in ('page', 'limit', 'has_more', 'total')
  1414. if key in raw_meta
  1415. }
  1416. @staticmethod
  1417. def _safe_text(value):
  1418. if value is None:
  1419. return ''
  1420. return str(value).strip()
  1421. @classmethod
  1422. def _safe_tips(cls, value):
  1423. if not isinstance(value, list):
  1424. return []
  1425. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  1426. @classmethod
  1427. def _render_table(cls, content, require_complete=False):
  1428. headers = content.get('headers') or []
  1429. rows = content.get('rows') or []
  1430. lines = []
  1431. if require_complete:
  1432. lines.append('完整客户数据,禁止摘要、合并、隐藏字段或省略空字段。')
  1433. lines.append(
  1434. '本页记录数:{0};每条字段数:{1};应展示字段值总数:{2}。'.format(
  1435. len(rows), len(headers), len(rows) * len(headers)
  1436. )
  1437. )
  1438. summary = cls._safe_text(content.get('summary'))
  1439. if summary:
  1440. lines.append(summary)
  1441. lines.append('表头共 {0} 列:'.format(len(headers)))
  1442. for index, header in enumerate(headers, start=1):
  1443. lines.append('{0}. {1}'.format(index, header['label']))
  1444. for index, row in enumerate(rows, start=1):
  1445. lines.append('记录 {0}:'.format(index))
  1446. for header, value in zip(headers, row):
  1447. if isinstance(value, (dict, list)):
  1448. value = json.dumps(value, ensure_ascii=False)
  1449. lines.append('- {0}: {1}'.format(header['label'], value))
  1450. tips = content.get('tips') or []
  1451. if tips:
  1452. lines.append('提示:{0}'.format(';'.join(tips)))
  1453. if require_complete:
  1454. lines.append(
  1455. '展示完整性校验:已提供{0}条客户的全部{1}个字段。'.format(
  1456. len(rows), len(headers)
  1457. )
  1458. )
  1459. return '\n'.join(lines)
  1460. @staticmethod
  1461. def _success_result(content, text, meta):
  1462. return {
  1463. 'structured_content': content,
  1464. 'text': text,
  1465. 'is_error': False,
  1466. 'meta': meta,
  1467. }
  1468. @staticmethod
  1469. def _error_result(code, message, retryable, meta=None):
  1470. return {
  1471. 'structured_content': {
  1472. 'code': code,
  1473. 'message': message,
  1474. 'retryable': retryable,
  1475. },
  1476. 'text': '{0}: {1}'.format(code, message),
  1477. 'is_error': True,
  1478. 'meta': meta or {},
  1479. }
  1480. @classmethod
  1481. def _format_error(cls, meta=None):
  1482. return cls._error_result(
  1483. 'MCP_9001',
  1484. '工具返回格式异常',
  1485. True,
  1486. meta,
  1487. )