output_presenter.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  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. },
  256. 'query_outbound_detail': {
  257. 'order_number': ('订单号',),
  258. 'cargo_type': ('超长超重',),
  259. 'customs_files': ('报关资料',),
  260. 'reference_number': ('客户参考号',),
  261. 'customer_name': ('客户名称',),
  262. 'declaration_type': ('报关方式',),
  263. 'merge_declare_number': ('合并报关单号',),
  264. 'order_remark': ('订单备注',),
  265. 'bl_number': ('提单号',),
  266. 'container_code': ('柜号',),
  267. 'customer_service': ('客户经理',),
  268. 'est_inbound_date': ('预计入库时间',),
  269. 'inbound_date': ('实际入库时间',),
  270. 'status': ('状态',),
  271. 'pieces': ('预报件数 / 入库件数',),
  272. 'weight': ('预报实重(KG) / 入库实重(KG)',),
  273. 'volume': ('预报体积(m³) / 入库体积(m³)',),
  274. 'pickup_place': ('交货地',),
  275. 'product_name': ('物流产品',),
  276. 'goods_name': ('品名',),
  277. 'closing_time': ('截关时间',),
  278. 'clearance_remark': ('报关备注',),
  279. 'import_clearance_remark': ('清关备注',),
  280. 'delivery_address': ('派送地址',),
  281. 'delivery_type': ('派送类型',),
  282. 'delivery_way': ('派送方式',),
  283. 'channel': ('派送渠道',),
  284. 'country_name': ('目的国',),
  285. 'importer_name': ('进口商',),
  286. 'vat_type': ('清关税号',),
  287. 'packing_type': ('货物类型',),
  288. 'is_abnormal': ('是否问题件',),
  289. 'package_method': ('包装类型',),
  290. 'order_reply': ('到货回复',),
  291. },
  292. 'query_customer_list': {
  293. 'customer_name': ('客户名称',),
  294. 'customer_code': ('客户代码',),
  295. 'create_time': ('开户时间',),
  296. 'business_type': ('业务类型',),
  297. 'customer_attribute': ('客户属性',),
  298. 'customer_source': ('客户来源',),
  299. 'first_inbound_date': ('首次成交时间',),
  300. 'last_inbound_date': ('最后一次走货时间',),
  301. 'active_status': ('活跃状态',),
  302. 'contract_status': ('合同状态',),
  303. 'contract_validity': ('合同有效期',),
  304. 'credit_limit': ('信用额度',),
  305. 'currency_code': ('结算币种',),
  306. 'billing_modes': ('结算模式(分业务类型)',),
  307. 'sales_name': ('商务经理',),
  308. 'merchandiser_name': ('客户经理',),
  309. 'department_name': ('事业部',),
  310. },
  311. }
  312. PAYMENT_FOLLOWUP_COLUMNS = {
  313. 'customer_name': '客户名称',
  314. 'settlement_currency': '结算币种',
  315. 'billed_unverified_amount': '已出账未核销金额',
  316. 'unbilled_amount': '未出账金额',
  317. 'overdue_unpaid_amount': '逾期未回款金额',
  318. 'billed_unverified_amount_cny': '已出账未核销金额(人民币)',
  319. 'unbilled_amount_cny': '未出账金额(人民币)',
  320. 'overdue_unpaid_amount_cny': '逾期未回款金额(人民币)',
  321. 'unverified_receivable_monthly_summary': '未回款月份汇总',
  322. 'receipt_unverified_amount': '收款单未核销金额',
  323. 'current_balance': '当前余额',
  324. 'credit_limit': '信用额度',
  325. 'bad_debt_total': '坏账合计',
  326. 'contract_status': '合同状态',
  327. }
  328. PAYMENT_FOLLOWUP_DETAIL_COLUMNS = {
  329. 'bill_month': '账单月份',
  330. 'bill_no': '账单号',
  331. 'business_type': '业务类型',
  332. 'settlement_mode': '结算模式',
  333. 'unverified_amount': '未核销金额',
  334. 'customer_receivable_date': '客户应收款日期',
  335. }
  336. PAYMENT_FOLLOWUP_MONTHLY_COLUMNS = {
  337. 'receivable_month': '应收月份',
  338. 'unverified_amount': '未核销金额',
  339. 'is_overdue': '是否逾期',
  340. }
  341. OUTBOUND_DETAIL_SUMMARY = {
  342. 'bl_number': '提单号',
  343. 'container_code': '柜号',
  344. 'container_type': '柜型',
  345. 'total_volume': '总体积',
  346. 'total_weight': '总重量',
  347. 'total_pieces': '总件数',
  348. 'sku': 'SKU',
  349. 'buy_declaration_count': '买单报关数量',
  350. 'general_declaration_count': '一般贸易报关数量',
  351. 'must_load': '必装单量/体积',
  352. 'backup_load': '备装单量/体积',
  353. }
  354. FIELD_LABELS = {
  355. 'query_order_exact': {
  356. 'order_number': '订单号',
  357. 'order_numbers': '订单号',
  358. 'reference_number': '客户参考号',
  359. 'reference_numbers': '客户参考号',
  360. 'tracking_number': '快递单号',
  361. 'tracking_numbers': '快递单号',
  362. 'outbound_number': '排舱单号',
  363. 'outbound_numbers': '排舱单号',
  364. 'container_code': '柜号',
  365. 'container_codes': '柜号',
  366. 'so_number': 'SO号',
  367. 'so_numbers': 'SO号',
  368. 'shipment_id': 'Shipment ID',
  369. 'receiver_country': '收货国家',
  370. 'product_ids': '物流产品',
  371. 'customer_ids': '客户',
  372. 'sales_id': '销售人员',
  373. 'warehouse_ids': '仓库',
  374. 'department_id': '事业部',
  375. 'inbound_date_start': '入库开始日期',
  376. 'inbound_date_end': '入库结束日期',
  377. 'outbound_date_start': '出库开始日期',
  378. 'outbound_date_end': '出库结束日期',
  379. 'page': '页码',
  380. 'limit': '每页数量',
  381. },
  382. 'query_track': {
  383. 'order_id': '订单ID',
  384. 'order_number': '订单号',
  385. 'tracking_number': '快递单号',
  386. 'page': '页码',
  387. 'limit': '每页数量',
  388. },
  389. 'query_customs_declaration_files': {
  390. 'outbound_numbers': '排舱单号',
  391. 'order_numbers': '订单号',
  392. 'page': '页码',
  393. 'limit': '每页数量',
  394. },
  395. 'query_outbound_list': {
  396. 'outbound_numbers': '排舱单号',
  397. 'order_numbers': '订单号',
  398. 'container_codes': '柜号',
  399. 'so_numbers': 'SO号',
  400. 'bl_numbers': '提单号',
  401. 'outbound_status': '排舱状态',
  402. 'shipping_method': '运输方式',
  403. 'warehouse_id': '集货仓库',
  404. 'is_direct_send': '是否直送柜',
  405. 'page': '页码',
  406. 'limit': '每页数量',
  407. },
  408. 'query_outbound_detail': {
  409. 'outbound_number': '排舱单号',
  410. 'page': '页码',
  411. 'limit': '每页数量',
  412. },
  413. 'query_order_detail': {
  414. 'order_number': '订单号', 'section': '详情模块',
  415. 'page': '页码', 'limit': '每页数量',
  416. },
  417. 'list_order_filter_options': {
  418. 'filter_type': '筛选项类型',
  419. 'keyword': '关键词',
  420. 'page': '页码',
  421. 'limit': '每页数量',
  422. },
  423. 'list_outbound_filter_options': {
  424. 'filter_type': '筛选类别',
  425. 'keyword': '显示名称',
  426. 'page': '页码',
  427. 'limit': '每页数量',
  428. },
  429. 'list_pending_outbound_export_filter_options': {
  430. 'filter_type': '筛选项类型',
  431. 'product_type_id': '产品分类',
  432. 'keyword': '关键词',
  433. 'page': '页码',
  434. 'limit': '每页数量',
  435. },
  436. 'query_customer_list': {
  437. 'customer_id': '客户名称',
  438. 'department_id': '事业部',
  439. 'sales_id': '商务经理',
  440. 'merchandiser_id': '客户经理',
  441. 'page': '页码',
  442. 'limit': '每页数量',
  443. },
  444. 'query_customer_payment_followup': {
  445. 'customer_id': '客户名称',
  446. 'department_id': '事业部',
  447. 'sales_id': '商务经理',
  448. 'merchandiser_id': '客户经理',
  449. 'has_unverified_receivable_only': '只看有应收未核销费用的客户',
  450. 'page': '页码',
  451. 'limit': '每页数量',
  452. },
  453. 'query_customer_unverified_bill_details': {
  454. 'customer_id': '客户名称',
  455. 'page': '页码',
  456. 'limit': '每页数量',
  457. },
  458. 'list_customer_filter_options': {
  459. 'filter_type': '筛选项类型',
  460. 'keyword': '关键词',
  461. 'page': '页码',
  462. 'limit': '每页数量',
  463. },
  464. 'export_pending_outbound_orders': {
  465. 'number': '单号',
  466. 'product_type_id': '产品分类',
  467. 'product_id': '物流产品',
  468. 'order_warehouse_id': '集货仓库',
  469. 'receiver_country': '目的国',
  470. 'is_remove': '是否装柜剔除',
  471. 'address': '派送地址',
  472. 'inbound_date': '入库时间',
  473. 'status': '订单状态',
  474. 'merge_declare_number': '合并报关单号',
  475. 'importer_id': '进口商',
  476. 'packing_type': '货物类型',
  477. 'is_battery': '带电属性',
  478. 'is_magnetic': '带磁属性',
  479. 'is_wood': '带木属性',
  480. 'is_other': '其他商品属性',
  481. 'is_fda': 'FDA产品属性',
  482. 'is_toy': '玩具属性',
  483. 'is_ultra_limit': '超长超重属性',
  484. 'is_sensitive': '敏感货属性',
  485. 'is_food': '食品属性',
  486. 'no_property': '无属性',
  487. },
  488. 'export_out_of_province_port_data': {
  489. 'outbound_numbers': '排舱单号',
  490. 'container_codes': '柜号',
  491. 'bl_numbers': '提单号',
  492. 'so_numbers': 'SO号',
  493. 'file_type': '资料类型',
  494. },
  495. 'query_export_task': {
  496. 'task_ref': '导出任务引用',
  497. },
  498. }
  499. ERROR_MESSAGES = {
  500. 'MCP_1101': '设备配置已失效,请重新生成配置',
  501. 'MCP_1102': '设备会话已过期,请重新连接',
  502. 'MCP_1103': '员工账号不可用,请联系管理员',
  503. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  504. 'MCP_1201': '工具当前不可用',
  505. 'MCP_1202': '工具当前不可用',
  506. 'MCP_1301': '没有权限使用此工具',
  507. 'MCP_1501': '目标数据不可用',
  508. 'MCP_1502': '结果过多,请缩小查询范围',
  509. 'MCP_1601': '没有可导出的数据',
  510. 'MCP_9001': '工具调用失败,请稍后重试',
  511. }
  512. NON_RETRYABLE_CODES = frozenset((
  513. 'MCP_1101',
  514. 'MCP_1102',
  515. 'MCP_1103',
  516. 'MCP_1104',
  517. 'MCP_1201',
  518. 'MCP_1202',
  519. 'MCP_1301',
  520. 'MCP_1401',
  521. 'MCP_1501',
  522. 'MCP_1502',
  523. 'MCP_1601',
  524. ))
  525. def handles(self, tool_name):
  526. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  527. # Convert a backend envelope into text and structured display data.
  528. def present(self, tool_name, tool_result):
  529. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  530. return self._format_error()
  531. code = str(tool_result.get('code') or '').strip()
  532. meta = self._build_meta(tool_result.get('meta'))
  533. if code not in ('MCP_0000', '0'):
  534. return self._business_error(
  535. tool_name,
  536. code or 'MCP_9001',
  537. tool_result.get('msg'),
  538. meta,
  539. )
  540. data = tool_result.get('data')
  541. if not isinstance(data, dict):
  542. return self._format_error(meta)
  543. if tool_name in self.DETAIL_TOOLS:
  544. return self._present_outbound_detail(
  545. tool_name,
  546. data,
  547. tool_result.get('meta'),
  548. meta,
  549. )
  550. if tool_name in self.ORDER_DETAIL_TOOLS:
  551. return self._present_order_detail(data, tool_result.get('meta'), meta)
  552. if tool_name in self.PAYMENT_FOLLOWUP_TOOLS:
  553. return self._present_customer_payment_followup(
  554. data, tool_result.get('meta'), meta
  555. )
  556. if tool_name in self.PAYMENT_DETAIL_TOOLS:
  557. return self._present_customer_unverified_bill_details(
  558. data, tool_result.get('meta'), meta
  559. )
  560. if tool_name in self.TABLE_TOOLS:
  561. return self._present_table(
  562. tool_name,
  563. data,
  564. tool_result.get('meta'),
  565. meta,
  566. )
  567. if tool_name in self.OPTION_TOOLS:
  568. if tool_name == 'list_customer_filter_options':
  569. return self._present_customer_options(
  570. data, tool_result.get('meta'), meta
  571. )
  572. return self._present_options(data, tool_result.get('meta'), meta)
  573. if tool_name in self.EXPORT_TOOLS:
  574. return self._present_export_submission(data, meta)
  575. return self._present_export_task(data, meta)
  576. def _present_order_detail(self, data, raw_meta, meta):
  577. if set(data) != {'section', 'order_number', 'payload'}:
  578. return self._format_error(meta)
  579. section = data.get('section')
  580. order_number = data.get('order_number')
  581. payload = data.get('payload')
  582. if (
  583. section not in self.ORDER_DETAIL_SECTIONS
  584. or not isinstance(order_number, str) or not order_number.strip()
  585. or not isinstance(payload, dict)
  586. ):
  587. return self._format_error(meta)
  588. content = {
  589. '订单号': order_number.strip(),
  590. '详情模块': self.ORDER_DETAIL_SECTIONS[section],
  591. }
  592. if section == 'all':
  593. all_content = self._present_order_detail_all(payload)
  594. if all_content is None:
  595. return self._format_error(meta)
  596. content.update(all_content)
  597. elif section == 'overview':
  598. expected = {
  599. 'status_nodes', 'order_info', 'freight_info',
  600. 'package_summary', 'trader_info',
  601. }
  602. if set(payload) != expected or not isinstance(payload['status_nodes'], list):
  603. return self._format_error(meta)
  604. nodes = []
  605. for row in payload['status_nodes']:
  606. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  607. if translated is None:
  608. return self._format_error(meta)
  609. state = row.get('state')
  610. time_kind = row.get('time_kind')
  611. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  612. return self._format_error(meta)
  613. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  614. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  615. nodes.append(translated)
  616. content['状态节点'] = nodes
  617. for raw_key, chinese_key in (
  618. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  619. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  620. ):
  621. translated = self._translate_exact(
  622. payload.get(raw_key),
  623. self.ORDER_DETAIL_FIELDS['overview'][raw_key],
  624. )
  625. if translated is None:
  626. return self._format_error(meta)
  627. content[chinese_key] = translated
  628. elif section == 'inbound':
  629. if set(payload) != {'summary', 'records'}:
  630. return self._format_error(meta)
  631. summary = self._translate_exact(
  632. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  633. )
  634. records = self._translate_order_detail_rows(section, payload.get('records'))
  635. if summary is None or records is None:
  636. return self._format_error(meta)
  637. content['入库概况'] = summary
  638. content['明细'] = records
  639. pagination = self._order_detail_pagination(raw_meta)
  640. if pagination is None:
  641. return self._format_error(meta)
  642. content['分页'] = pagination
  643. elif section == 'delivery':
  644. if set(payload) != {'summary', 'records'}:
  645. return self._format_error(meta)
  646. summary = self._translate_exact(
  647. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  648. )
  649. records = self._translate_order_detail_rows(section, payload.get('records'))
  650. if summary is None or records is None:
  651. return self._format_error(meta)
  652. content['派送汇总'] = summary
  653. content['明细'] = records
  654. pagination = self._order_detail_pagination(raw_meta)
  655. if pagination is None:
  656. return self._format_error(meta)
  657. content['分页'] = pagination
  658. else:
  659. if set(payload) != {'records'}:
  660. return self._format_error(meta)
  661. records = self._translate_order_detail_rows(section, payload.get('records'))
  662. pagination = self._order_detail_pagination(raw_meta)
  663. if records is None or pagination is None:
  664. return self._format_error(meta)
  665. content['明细'] = records
  666. content['分页'] = pagination
  667. text = json.dumps(content, ensure_ascii=False, indent=2)
  668. return self._success_result(content, text, meta)
  669. def _present_order_detail_all(self, payload):
  670. expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
  671. if set(payload) != expected_sections:
  672. return None
  673. overview = payload.get('overview')
  674. if not isinstance(overview, dict) or set(overview) != {
  675. 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
  676. } or not isinstance(overview['status_nodes'], list):
  677. return None
  678. overview_content = {'状态节点': []}
  679. for row in overview['status_nodes']:
  680. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  681. if translated is None:
  682. return None
  683. state = row.get('state')
  684. time_kind = row.get('time_kind')
  685. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  686. return None
  687. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  688. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  689. overview_content['状态节点'].append(translated)
  690. for raw_key, chinese_key in (
  691. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  692. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  693. ):
  694. translated = self._translate_exact(
  695. overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
  696. )
  697. if translated is None:
  698. return None
  699. overview_content[chinese_key] = translated
  700. result = {'订单概览': overview_content}
  701. for section, label in self.ORDER_DETAIL_SECTIONS.items():
  702. if section in ('overview', 'all'):
  703. continue
  704. translated = self._present_order_detail_all_section(section, payload.get(section))
  705. if translated is None:
  706. return None
  707. result[label] = translated
  708. return result
  709. def _present_order_detail_all_section(self, section, payload):
  710. if not isinstance(payload, dict) or 'pagination' not in payload:
  711. return None
  712. pagination = self._order_detail_pagination(payload.get('pagination'))
  713. if pagination is None:
  714. return None
  715. if section == 'inbound':
  716. if set(payload) != {'summary', 'records', 'pagination'}:
  717. return None
  718. summary = self._translate_exact(
  719. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  720. )
  721. records = self._translate_order_detail_rows(section, payload.get('records'))
  722. if summary is None or records is None:
  723. return None
  724. return {'入库概况': summary, '明细': records, '分页': pagination}
  725. if section == 'delivery':
  726. if set(payload) != {'summary', 'records', 'pagination'}:
  727. return None
  728. summary = self._translate_exact(
  729. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  730. )
  731. records = self._translate_order_detail_rows(section, payload.get('records'))
  732. if summary is None or records is None:
  733. return None
  734. return {'派送汇总': summary, '明细': records, '分页': pagination}
  735. if set(payload) != {'records', 'pagination'}:
  736. return None
  737. records = self._translate_order_detail_rows(section, payload.get('records'))
  738. if records is None:
  739. return None
  740. return {'明细': records, '分页': pagination}
  741. def _translate_order_detail_rows(self, section, records):
  742. if not isinstance(records, list):
  743. return None
  744. mapping = self.ORDER_DETAIL_FIELDS.get(section)
  745. if not isinstance(mapping, dict):
  746. return None
  747. translated_rows = []
  748. for row in records:
  749. translated = self._translate_exact(row, mapping)
  750. if translated is None:
  751. return None
  752. if section == 'inbound':
  753. mode = row.get('weight_mode')
  754. if mode not in ('single_box', 'total'):
  755. return None
  756. translated[
  757. '单箱入库重量' if mode == 'single_box' else '总重量KG'
  758. ] = row.get('weight', '')
  759. translated_rows.append(translated)
  760. return translated_rows
  761. @staticmethod
  762. def _translate_exact(value, mapping):
  763. if not isinstance(value, dict) or set(value) != set(mapping):
  764. return None
  765. result = {}
  766. for key, label in mapping.items():
  767. if label is None:
  768. continue
  769. item = value.get(key, '')
  770. if isinstance(item, (dict, list)):
  771. return None
  772. result[label] = '' if item is None else item
  773. return result
  774. @staticmethod
  775. def _order_detail_pagination(raw_meta):
  776. if not isinstance(raw_meta, dict):
  777. return None
  778. if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
  779. return None
  780. page = raw_meta.get('page')
  781. limit = raw_meta.get('limit')
  782. has_more = raw_meta.get('has_more')
  783. if isinstance(page, bool) or not isinstance(page, int) or page < 1:
  784. return None
  785. if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
  786. return None
  787. if not isinstance(has_more, bool):
  788. return None
  789. return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
  790. # Map local tool exceptions without exposing internal error details.
  791. def present_exception(self, tool_name, exception):
  792. if not self.handles(tool_name):
  793. return self._format_error()
  794. message = str(exception or '').strip()
  795. if isinstance(exception, ValueError):
  796. label = self._find_field_label(tool_name, message)
  797. return self._error_result(
  798. 'MCP_1401',
  799. self._parameter_message(label),
  800. False,
  801. )
  802. if message == DEVICE_INVALID_MESSAGE:
  803. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  804. if message.lower().startswith('tool disabled'):
  805. return self._error_result('MCP_1202', '工具当前不可用', False)
  806. return self._error_result(
  807. 'MCP_9001',
  808. '工具调用失败,请稍后重试',
  809. True,
  810. )
  811. def _present_table(self, tool_name, data, raw_meta, meta):
  812. columns = data.get('columns')
  813. records = data.get('records')
  814. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  815. return self._format_error(meta)
  816. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  817. if not isinstance(allowed_columns, dict):
  818. return self._format_error(meta)
  819. if tool_name == 'query_customer_list':
  820. expected = list(allowed_columns.keys())
  821. actual = [
  822. column.get('key') if isinstance(column, dict) else None
  823. for column in columns
  824. ]
  825. if actual != expected or self._customer_pagination(raw_meta) is None:
  826. return self._format_error(meta)
  827. headers = []
  828. keys = []
  829. for column in columns:
  830. if not isinstance(column, dict):
  831. return self._format_error(meta)
  832. key = column.get('key')
  833. label = column.get('name')
  834. if not isinstance(key, str) or not key.strip():
  835. return self._format_error(meta)
  836. if not isinstance(label, str) or not label.strip():
  837. return self._format_error(meta)
  838. key = key.strip()
  839. definition = allowed_columns.get(key)
  840. if not isinstance(definition, tuple) or not definition:
  841. return self._format_error(meta)
  842. keys.append(key)
  843. header = {'label': definition[0]}
  844. if len(definition) > 1:
  845. header['description'] = definition[1]
  846. headers.append(header)
  847. rows = []
  848. for record in records:
  849. if not isinstance(record, dict):
  850. return self._format_error(meta)
  851. if tool_name == 'query_customer_list' and set(record) != set(keys):
  852. return self._format_error(meta)
  853. row = []
  854. for key in keys:
  855. value = '' if record.get(key) is None else record.get(key, '')
  856. if tool_name == 'query_customer_list' and key == 'billing_modes':
  857. value = self._customer_billing_modes(value)
  858. if value is None:
  859. return self._format_error(meta)
  860. elif tool_name == 'query_customer_list' and isinstance(value, (dict, list)):
  861. return self._format_error(meta)
  862. row.append(value)
  863. rows.append(row)
  864. content = {
  865. 'summary': self._safe_text(data.get('summary')),
  866. 'headers': headers,
  867. 'rows': rows,
  868. }
  869. if tool_name == 'query_customer_list':
  870. content['display_rules'] = {
  871. 'mode': 'complete',
  872. 'allow_summary': False,
  873. 'allow_omit_records': False,
  874. 'allow_omit_empty_fields': False,
  875. 'allow_rename_fields': False,
  876. 'preserve_record_order': True,
  877. 'required_field_count': len(headers),
  878. 'returned_record_count': len(rows),
  879. 'required_value_count': len(headers) * len(rows),
  880. 'instruction': '最终回复必须逐条展示全部记录及全部17个字段,不得摘要、省略或改写',
  881. }
  882. tips = self._safe_tips(data.get('tips'))
  883. if tips:
  884. content['tips'] = tips
  885. pagination = self._build_pagination(raw_meta)
  886. if pagination:
  887. content['pagination'] = pagination
  888. return self._success_result(
  889. content,
  890. self._render_table(
  891. content,
  892. require_complete=tool_name == 'query_customer_list',
  893. ),
  894. meta,
  895. )
  896. def _present_customer_payment_followup(self, data, raw_meta, meta):
  897. if set(data) != {'columns', 'records'}:
  898. return self._format_error(meta)
  899. columns = data.get('columns')
  900. records = data.get('records')
  901. pagination = self._customer_pagination(raw_meta)
  902. expected_keys = list(self.PAYMENT_FOLLOWUP_COLUMNS)
  903. if not isinstance(columns, list) or not isinstance(records, list):
  904. return self._format_error(meta)
  905. actual_keys = []
  906. for column in columns:
  907. if (
  908. not isinstance(column, dict)
  909. or set(column) != {'key', 'name'}
  910. or not isinstance(column.get('key'), str)
  911. or not isinstance(column.get('name'), str)
  912. or not column.get('name').strip()
  913. ):
  914. return self._format_error(meta)
  915. actual_keys.append(column['key'])
  916. if actual_keys != expected_keys or pagination is None:
  917. return self._format_error(meta)
  918. amount_keys = {
  919. 'billed_unverified_amount', 'unbilled_amount',
  920. 'overdue_unpaid_amount', 'billed_unverified_amount_cny',
  921. 'unbilled_amount_cny', 'overdue_unpaid_amount_cny',
  922. 'receipt_unverified_amount', 'current_balance',
  923. 'credit_limit', 'bad_debt_total',
  924. }
  925. text_keys = {'customer_name', 'settlement_currency', 'contract_status'}
  926. rows = []
  927. for record in records:
  928. if not isinstance(record, dict) or set(record) != set(expected_keys):
  929. return self._format_error(meta)
  930. row = []
  931. for key in expected_keys:
  932. value = record[key]
  933. if key in amount_keys:
  934. if (
  935. isinstance(value, bool)
  936. or not isinstance(value, (int, float))
  937. or not math.isfinite(float(value))
  938. ):
  939. return self._format_error(meta)
  940. elif key in text_keys:
  941. if not isinstance(value, str):
  942. return self._format_error(meta)
  943. else:
  944. value = self._payment_followup_monthly_summaries(value)
  945. if value is None:
  946. return self._format_error(meta)
  947. row.append(value)
  948. rows.append(row)
  949. headers = [
  950. {'label': self.PAYMENT_FOLLOWUP_COLUMNS[key]}
  951. for key in expected_keys
  952. ]
  953. content = {
  954. 'headers': headers,
  955. 'rows': rows,
  956. 'pagination': pagination,
  957. 'display_rules': {
  958. 'mode': 'complete',
  959. 'allow_summary': False,
  960. 'allow_omit_records': False,
  961. 'allow_omit_empty_fields': False,
  962. 'allow_rename_fields': False,
  963. 'preserve_record_order': True,
  964. 'required_field_count': len(headers),
  965. 'returned_record_count': len(rows),
  966. 'required_value_count': len(headers) * len(rows),
  967. 'instruction': '最终回复必须逐条展示全部客户、全部字段和全部未回款月份汇总',
  968. },
  969. }
  970. return self._success_result(
  971. content,
  972. self._render_table(content, require_complete=True),
  973. meta,
  974. )
  975. def _payment_followup_monthly_summaries(self, summaries):
  976. if not isinstance(summaries, list):
  977. return None
  978. expected = set(self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS)
  979. translated = []
  980. for summary in summaries:
  981. if not isinstance(summary, dict) or set(summary) != expected:
  982. return None
  983. amount = summary.get('unverified_amount')
  984. if (
  985. isinstance(amount, bool)
  986. or not isinstance(amount, (int, float))
  987. or not math.isfinite(float(amount))
  988. ):
  989. return None
  990. if (
  991. not isinstance(summary.get('receivable_month'), str)
  992. or not isinstance(summary.get('is_overdue'), bool)
  993. ):
  994. return None
  995. item = {}
  996. for key, label in self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS.items():
  997. value = summary[key]
  998. item[label] = value
  999. translated.append(item)
  1000. return translated
  1001. def _present_customer_unverified_bill_details(self, data, raw_meta, meta):
  1002. if set(data) != {'columns', 'records'}:
  1003. return self._format_error(meta)
  1004. columns = data.get('columns')
  1005. records = data.get('records')
  1006. pagination = self._customer_pagination(raw_meta)
  1007. expected_keys = list(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1008. if not isinstance(columns, list) or not isinstance(records, list):
  1009. return self._format_error(meta)
  1010. actual_keys = []
  1011. for column in columns:
  1012. if (
  1013. not isinstance(column, dict)
  1014. or set(column) != {'key', 'name'}
  1015. or not isinstance(column.get('key'), str)
  1016. or not isinstance(column.get('name'), str)
  1017. or not column.get('name').strip()
  1018. ):
  1019. return self._format_error(meta)
  1020. actual_keys.append(column['key'])
  1021. if actual_keys != expected_keys or pagination is None:
  1022. return self._format_error(meta)
  1023. translated = self._payment_followup_details(records)
  1024. if translated is None:
  1025. return self._format_error(meta)
  1026. headers = [
  1027. {'label': self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS[key]}
  1028. for key in expected_keys
  1029. ]
  1030. rows = [[item[header['label']] for header in headers] for item in translated]
  1031. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1032. return self._success_result(content, self._render_table(content), meta)
  1033. def _payment_followup_details(self, details):
  1034. expected = set(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1035. translated = []
  1036. for detail in details:
  1037. if not isinstance(detail, dict) or set(detail) != expected:
  1038. return None
  1039. amount = detail.get('unverified_amount')
  1040. if (
  1041. isinstance(amount, bool)
  1042. or not isinstance(amount, (int, float))
  1043. or not math.isfinite(float(amount))
  1044. ):
  1045. return None
  1046. item = {}
  1047. for key, label in self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS.items():
  1048. value = detail[key]
  1049. if key != 'unverified_amount' and not isinstance(value, str):
  1050. return None
  1051. item[label] = value
  1052. translated.append(item)
  1053. return translated
  1054. @staticmethod
  1055. def _customer_billing_modes(value):
  1056. if not isinstance(value, list):
  1057. return None
  1058. result = []
  1059. business_types = set()
  1060. for item in value:
  1061. if not isinstance(item, dict) or set(item) != {
  1062. 'business_type', 'settlement_mode',
  1063. }:
  1064. return None
  1065. business_type = item.get('business_type')
  1066. settlement_mode = item.get('settlement_mode')
  1067. if (
  1068. not isinstance(business_type, str) or not business_type.strip()
  1069. or not isinstance(settlement_mode, str) or not settlement_mode.strip()
  1070. or business_type in business_types
  1071. ):
  1072. return None
  1073. business_types.add(business_type)
  1074. result.append({
  1075. '业务类型': business_type.strip(),
  1076. '结算模式': settlement_mode.strip(),
  1077. })
  1078. return result
  1079. def _present_customer_options(self, data, raw_meta, meta):
  1080. if set(data) != {'records'}:
  1081. return self._format_error(meta)
  1082. records = data.get('records')
  1083. pagination = self._customer_pagination(raw_meta)
  1084. if not isinstance(records, list) or pagination is None:
  1085. return self._format_error(meta)
  1086. rows = []
  1087. for record in records:
  1088. if not isinstance(record, dict) or set(record) != {'value', 'label', 'code'}:
  1089. return self._format_error(meta)
  1090. value = record.get('value')
  1091. label = record.get('label')
  1092. code = record.get('code')
  1093. if (
  1094. isinstance(value, bool) or not isinstance(value, int) or value < 1
  1095. or not isinstance(label, str) or not label.strip()
  1096. or not isinstance(code, str)
  1097. ):
  1098. return self._format_error(meta)
  1099. rows.append([value, label.strip(), code.strip()])
  1100. content = {
  1101. 'headers': [
  1102. {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
  1103. ],
  1104. 'rows': rows,
  1105. 'pagination': pagination,
  1106. }
  1107. return self._success_result(content, self._render_table(content), meta)
  1108. @staticmethod
  1109. def _customer_pagination(raw_meta):
  1110. if not isinstance(raw_meta, dict):
  1111. return None
  1112. required = {'page', 'limit', 'has_more'}
  1113. if (
  1114. not required.issubset(raw_meta)
  1115. or not set(raw_meta).issubset(required | {'request_id'})
  1116. ):
  1117. return None
  1118. page = raw_meta.get('page')
  1119. limit = raw_meta.get('limit')
  1120. has_more = raw_meta.get('has_more')
  1121. if (
  1122. isinstance(page, bool) or not isinstance(page, int)
  1123. or page < 1 or page > 100
  1124. or isinstance(limit, bool) or not isinstance(limit, int)
  1125. or limit < 1 or limit > 100
  1126. or not isinstance(has_more, bool)
  1127. ):
  1128. return None
  1129. return {'page': page, 'limit': limit, 'has_more': has_more}
  1130. def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
  1131. summary = data.get('summary')
  1132. columns = data.get('columns')
  1133. records = data.get('records')
  1134. if not isinstance(summary, dict):
  1135. return self._format_error(meta)
  1136. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  1137. return self._format_error(meta)
  1138. if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
  1139. return self._format_error(meta)
  1140. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  1141. headers = []
  1142. keys = []
  1143. for column in columns:
  1144. if not isinstance(column, dict):
  1145. return self._format_error(meta)
  1146. key = column.get('key')
  1147. definition = allowed_columns.get(key) if isinstance(key, str) else None
  1148. if not isinstance(definition, tuple) or not definition:
  1149. return self._format_error(meta)
  1150. keys.append(key)
  1151. headers.append({'label': definition[0]})
  1152. rows = []
  1153. for record in records:
  1154. if not isinstance(record, dict):
  1155. return self._format_error(meta)
  1156. row = []
  1157. for key in keys:
  1158. value = '' if record.get(key) is None else record.get(key, '')
  1159. if key == 'customs_files':
  1160. if not isinstance(value, list):
  1161. return self._format_error(meta)
  1162. files = []
  1163. for item in value:
  1164. if not isinstance(item, dict):
  1165. return self._format_error(meta)
  1166. files.append({
  1167. '文件名称': item.get('file_name', ''),
  1168. '文件类型': item.get('file_type', ''),
  1169. '文件链接': item.get('file_url', ''),
  1170. })
  1171. value = files
  1172. row.append(value)
  1173. rows.append(row)
  1174. summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
  1175. content = {
  1176. 'summary': {
  1177. 'headers': [
  1178. {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
  1179. for key in summary_keys
  1180. ],
  1181. 'row': [summary.get(key, '') for key in summary_keys],
  1182. },
  1183. 'details': {
  1184. 'headers': headers,
  1185. 'rows': rows,
  1186. },
  1187. }
  1188. tips = self._safe_tips(data.get('tips'))
  1189. if tips:
  1190. content['details']['tips'] = tips
  1191. pagination = self._build_pagination(raw_meta)
  1192. if pagination:
  1193. content['details']['pagination'] = pagination
  1194. return self._success_result(
  1195. content,
  1196. self._render_outbound_detail(content),
  1197. meta,
  1198. )
  1199. @classmethod
  1200. def _render_outbound_detail(cls, content):
  1201. lines = ['排舱汇总:']
  1202. summary = content['summary']
  1203. for header, value in zip(summary['headers'], summary['row']):
  1204. lines.append('- {0}: {1}'.format(header['label'], value))
  1205. lines.append('订单明细:')
  1206. details = content['details']
  1207. lines.append('表头共 {0} 列:'.format(len(details['headers'])))
  1208. for index, header in enumerate(details['headers'], start=1):
  1209. lines.append('{0}. {1}'.format(index, header['label']))
  1210. for index, row in enumerate(details['rows'], start=1):
  1211. lines.append('记录 {0}:'.format(index))
  1212. for header, value in zip(details['headers'], row):
  1213. if isinstance(value, (dict, list)):
  1214. value = json.dumps(value, ensure_ascii=False)
  1215. lines.append('- {0}: {1}'.format(header['label'], value))
  1216. tips = details.get('tips') or []
  1217. if tips:
  1218. lines.append('提示:{0}'.format(';'.join(tips)))
  1219. return '\n'.join(lines)
  1220. def _present_options(self, data, raw_meta, meta):
  1221. records = data.get('records')
  1222. if not isinstance(records, list):
  1223. return self._format_error(meta)
  1224. rows = []
  1225. for record in records:
  1226. if not isinstance(record, dict):
  1227. return self._format_error(meta)
  1228. rows.append([
  1229. record.get('value', ''),
  1230. self._safe_text(record.get('label')),
  1231. self._safe_text(record.get('code')),
  1232. ])
  1233. content = {
  1234. 'headers': [
  1235. {'label': '可传值'},
  1236. {'label': '显示名称'},
  1237. {'label': '业务编码'},
  1238. ],
  1239. 'rows': rows,
  1240. }
  1241. pagination = self._build_pagination(raw_meta)
  1242. if pagination:
  1243. content['pagination'] = pagination
  1244. return self._success_result(content, self._render_table(content), meta)
  1245. def _present_export_submission(self, data, meta):
  1246. expected = {'task_ref', 'status', 'retry_after_seconds'}
  1247. if set(data) != expected:
  1248. return self._format_error(meta)
  1249. task_ref = data.get('task_ref')
  1250. retry_after = data.get('retry_after_seconds')
  1251. if (
  1252. not isinstance(task_ref, str) or not task_ref.strip()
  1253. or data.get('status') != 'queued'
  1254. or isinstance(retry_after, bool)
  1255. or not isinstance(retry_after, int)
  1256. or retry_after <= 0
  1257. ):
  1258. return self._format_error(meta)
  1259. task = {
  1260. 'task_ref': task_ref.strip(),
  1261. 'status': 'queued',
  1262. 'retry_after_seconds': retry_after,
  1263. }
  1264. content = {
  1265. 'message': '导出任务已提交',
  1266. 'task': task,
  1267. }
  1268. text = (
  1269. '导出任务已提交\n'
  1270. '- 任务引用: {0}\n'
  1271. '- 建议 {1} 秒后单独查询任务状态'
  1272. ).format(task['task_ref'], retry_after)
  1273. return self._success_result(content, text, meta)
  1274. def _present_export_task(self, data, meta):
  1275. task_ref = data.get('task_ref')
  1276. status = data.get('status')
  1277. if (
  1278. not isinstance(task_ref, str)
  1279. or not task_ref.strip()
  1280. or status not in ('queued', 'running', 'completed', 'failed')
  1281. ):
  1282. return self._format_error(meta)
  1283. task = {'task_ref': task_ref.strip(), 'status': status}
  1284. if status in ('queued', 'running'):
  1285. if set(data) != {'task_ref', 'status', 'retry_after_seconds'}:
  1286. return self._format_error(meta)
  1287. retry_after = data.get('retry_after_seconds')
  1288. if (
  1289. isinstance(retry_after, bool)
  1290. or not isinstance(retry_after, int)
  1291. or retry_after <= 0
  1292. ):
  1293. return self._format_error(meta)
  1294. task['retry_after_seconds'] = retry_after
  1295. label = '等待中' if status == 'queued' else '生成中'
  1296. content = {'message': '导出任务{0}'.format(label), 'task': task}
  1297. text = (
  1298. '导出任务{0}\n- 任务引用: {1}\n- 建议 {2} 秒后再次查询'
  1299. ).format(label, task['task_ref'], retry_after)
  1300. return self._success_result(content, text, meta)
  1301. if status == 'failed':
  1302. if set(data) != {'task_ref', 'status'}:
  1303. return self._format_error(meta)
  1304. content = {'message': '导出任务失败,请重新提交', 'task': task}
  1305. text = '导出任务失败,请重新提交'
  1306. return self._success_result(content, text, meta)
  1307. if set(data) != {'task_ref', 'status', 'files'}:
  1308. return self._format_error(meta)
  1309. files = data.get('files')
  1310. if not isinstance(files, list) or not files:
  1311. return self._format_error(meta)
  1312. safe_files = []
  1313. for item in files:
  1314. if not isinstance(item, dict) or set(item) != {'label', 'url'}:
  1315. return self._format_error(meta)
  1316. label = item.get('label')
  1317. url = item.get('url')
  1318. if (
  1319. not isinstance(label, str) or not label.strip()
  1320. or not self._valid_http_url(url)
  1321. ):
  1322. return self._format_error(meta)
  1323. safe_files.append({'label': label.strip(), 'url': url.strip()})
  1324. content = {
  1325. 'message': '文件已生成',
  1326. 'task': task,
  1327. 'files': safe_files,
  1328. }
  1329. lines = ['文件已生成']
  1330. for item in safe_files:
  1331. lines.append('- {0}: {1}'.format(item['label'], item['url']))
  1332. return self._success_result(content, '\n'.join(lines), meta)
  1333. def _valid_http_url(self, value):
  1334. if not isinstance(value, str) or not value.strip():
  1335. return False
  1336. if value != value.strip() or '\\' in value or any(
  1337. character.isspace() or ord(character) < 32 or ord(character) == 127
  1338. for character in value
  1339. ):
  1340. return False
  1341. try:
  1342. parsed = urlparse(value)
  1343. port = parsed.port
  1344. return (
  1345. parsed.scheme in ('http', 'https')
  1346. and bool(parsed.hostname)
  1347. and parsed.username is None
  1348. and parsed.password is None
  1349. and (port is None or 0 < port <= 65535)
  1350. )
  1351. except ValueError:
  1352. return False
  1353. def _business_error(self, tool_name, code, raw_message, meta):
  1354. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  1355. logger.warning(
  1356. 'Unknown MCP business error code',
  1357. extra={
  1358. 'request_id': meta.get('request_id', ''),
  1359. 'tool_code': tool_name,
  1360. 'backend_code': code,
  1361. 'response_code': 'MCP_9001',
  1362. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  1363. },
  1364. )
  1365. code = 'MCP_9001'
  1366. if code == 'MCP_1401':
  1367. label = self._find_field_label(tool_name, raw_message)
  1368. message = self._parameter_message(label)
  1369. else:
  1370. message = self.ERROR_MESSAGES[code]
  1371. retryable = code not in self.NON_RETRYABLE_CODES
  1372. return self._error_result(code, message, retryable, meta)
  1373. def _find_field_label(self, tool_name, raw_message):
  1374. message = str(raw_message or '')
  1375. fields = self.FIELD_LABELS.get(tool_name, {})
  1376. for field in sorted(fields, key=len, reverse=True):
  1377. if field in message:
  1378. return fields[field]
  1379. return ''
  1380. @staticmethod
  1381. def _parameter_message(label):
  1382. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  1383. @staticmethod
  1384. def _build_meta(raw_meta):
  1385. if not isinstance(raw_meta, dict):
  1386. return {}
  1387. request_id = raw_meta.get('request_id')
  1388. if not isinstance(request_id, str) or not request_id.strip():
  1389. return {}
  1390. return {'request_id': request_id.strip()}
  1391. @staticmethod
  1392. def _build_pagination(raw_meta):
  1393. if not isinstance(raw_meta, dict):
  1394. return {}
  1395. return {
  1396. key: raw_meta[key]
  1397. for key in ('page', 'limit', 'has_more', 'total')
  1398. if key in raw_meta
  1399. }
  1400. @staticmethod
  1401. def _safe_text(value):
  1402. if value is None:
  1403. return ''
  1404. return str(value).strip()
  1405. @classmethod
  1406. def _safe_tips(cls, value):
  1407. if not isinstance(value, list):
  1408. return []
  1409. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  1410. @classmethod
  1411. def _render_table(cls, content, require_complete=False):
  1412. headers = content.get('headers') or []
  1413. rows = content.get('rows') or []
  1414. lines = []
  1415. if require_complete:
  1416. lines.append('完整客户数据,禁止摘要、合并、隐藏字段或省略空字段。')
  1417. lines.append(
  1418. '本页记录数:{0};每条字段数:{1};应展示字段值总数:{2}。'.format(
  1419. len(rows), len(headers), len(rows) * len(headers)
  1420. )
  1421. )
  1422. summary = cls._safe_text(content.get('summary'))
  1423. if summary:
  1424. lines.append(summary)
  1425. lines.append('表头共 {0} 列:'.format(len(headers)))
  1426. for index, header in enumerate(headers, start=1):
  1427. lines.append('{0}. {1}'.format(index, header['label']))
  1428. for index, row in enumerate(rows, start=1):
  1429. lines.append('记录 {0}:'.format(index))
  1430. for header, value in zip(headers, row):
  1431. if isinstance(value, (dict, list)):
  1432. value = json.dumps(value, ensure_ascii=False)
  1433. lines.append('- {0}: {1}'.format(header['label'], value))
  1434. tips = content.get('tips') or []
  1435. if tips:
  1436. lines.append('提示:{0}'.format(';'.join(tips)))
  1437. if require_complete:
  1438. lines.append(
  1439. '展示完整性校验:已提供{0}条客户的全部{1}个字段。'.format(
  1440. len(rows), len(headers)
  1441. )
  1442. )
  1443. return '\n'.join(lines)
  1444. @staticmethod
  1445. def _success_result(content, text, meta):
  1446. return {
  1447. 'structured_content': content,
  1448. 'text': text,
  1449. 'is_error': False,
  1450. 'meta': meta,
  1451. }
  1452. @staticmethod
  1453. def _error_result(code, message, retryable, meta=None):
  1454. return {
  1455. 'structured_content': {
  1456. 'code': code,
  1457. 'message': message,
  1458. 'retryable': retryable,
  1459. },
  1460. 'text': '{0}: {1}'.format(code, message),
  1461. 'is_error': True,
  1462. 'meta': meta or {},
  1463. }
  1464. @classmethod
  1465. def _format_error(cls, meta=None):
  1466. return cls._error_result(
  1467. 'MCP_9001',
  1468. '工具返回格式异常',
  1469. True,
  1470. meta,
  1471. )