output_presenter.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  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. PAYMENT_RECORD_TOOLS = frozenset(('query_customer_payment_records',))
  21. RECEIVABLE_COST_TOOLS = frozenset((
  22. 'query_order_receivable_cost_details',
  23. ))
  24. RECEIVABLE_LIST_TOOLS = frozenset(('query_receivable_cost_list',))
  25. RECEIVABLE_FILTER_TOOLS = frozenset((
  26. 'list_receivable_cost_filter_options',
  27. ))
  28. PAYABLE_COST_TOOLS = frozenset(('query_payable_cost_list',))
  29. PAYABLE_FILTER_TOOLS = frozenset(('list_payable_cost_filter_options',))
  30. PAYABLE_EXPORT_TOOLS = frozenset(('export_payable_cost_list',))
  31. DESTINATION_TRAILER_TOOLS = frozenset(('query_destination_trailer_list',))
  32. ORDER_ABNORMAL_TOOLS = frozenset(('query_order_abnormal_list',))
  33. DETAIL_TOOLS = frozenset(('query_outbound_detail',))
  34. ORDER_DETAIL_TOOLS = frozenset(('query_order_detail',))
  35. OPTION_TOOLS = frozenset((
  36. 'list_order_filter_options',
  37. 'list_outbound_filter_options',
  38. 'list_pending_outbound_export_filter_options',
  39. 'list_customer_filter_options',
  40. 'list_destination_trailer_filter_options',
  41. 'list_order_abnormal_filter_options',
  42. ))
  43. EXPORT_TOOLS = frozenset((
  44. 'export_pending_outbound_orders',
  45. 'export_out_of_province_port_data',
  46. 'export_receivable_cost_list',
  47. 'export_pallet_data',
  48. ))
  49. TASK_TOOLS = frozenset(('query_export_task',))
  50. SAFE_TOOLS = (
  51. TABLE_TOOLS | DETAIL_TOOLS | ORDER_DETAIL_TOOLS | PAYMENT_FOLLOWUP_TOOLS
  52. | PAYMENT_DETAIL_TOOLS | PAYMENT_RECORD_TOOLS | RECEIVABLE_COST_TOOLS
  53. | RECEIVABLE_LIST_TOOLS | RECEIVABLE_FILTER_TOOLS
  54. | PAYABLE_COST_TOOLS | PAYABLE_FILTER_TOOLS | PAYABLE_EXPORT_TOOLS
  55. | DESTINATION_TRAILER_TOOLS
  56. | ORDER_ABNORMAL_TOOLS
  57. | OPTION_TOOLS | EXPORT_TOOLS | TASK_TOOLS
  58. )
  59. ORDER_DETAIL_SECTIONS = {
  60. 'overview': '订单概览',
  61. 'packages': '箱单信息',
  62. 'package_items': '箱单商品',
  63. 'dw_auth': 'DW授权信息',
  64. 'attachments': '附件信息',
  65. 'inbound': '入库信息',
  66. 'checks': '查验信息',
  67. 'tracks': '订单轨迹',
  68. 'operation_logs': '操作日志',
  69. 'cost_logs': '应收与结算日志',
  70. 'delivery': '派送信息',
  71. 'all': '全部',
  72. }
  73. ORDER_DETAIL_FIELDS = {
  74. 'overview': {
  75. 'order_info': {
  76. 'order_number': '订单号', 'reference_number': '客户参考号',
  77. 'customer_name': '客户名称', 'departure_country': '起运国',
  78. 'destination_country': '目的国', 'package_method': '包装类型',
  79. 'product_name': '物流产品', 'forecast_pwv': '预报件重体',
  80. 'inbound_pwv': '入库件重体',
  81. 'receivable_charge_weight': '应收计费重/体积',
  82. 'settlement_charge_weight': '结算计费重/体积',
  83. 'declaration_type': '报关类型', 'pre_recording': '是否需要预录单',
  84. 'idcard_name': '企业/个人姓名',
  85. 'idcard_number': '社会信用代码/身份证号',
  86. 'outbound_number': '排舱单号', 'container_mode': '直送柜/拼柜',
  87. 'track_map_available': '是否可查看轨迹地图', 'insurance': '购买保险',
  88. 'delivery_way': '派送方式', 'return_shipping_surcharge': '退运附加',
  89. 'work_order_count': '工单数量', 'bill_remark': '账单备注',
  90. 'remark': '订单备注',
  91. },
  92. 'freight_info': {
  93. 'estimated_inbound_time': '预计入库时间', 'cargo_type': '货物类型',
  94. 'pickup_way': '交货方式', 'warehouse': '交货仓库',
  95. 'pickup_address': '提货地址', 'pickup_contact': '提货联系人',
  96. 'pickup_phone': '提货联系电话', 'delivery_type': '派送类型',
  97. 'delivery_address': '派送地址', 'delivery_remark': '派送备注',
  98. 'oversea_warehouse': '海外仓',
  99. },
  100. 'package_summary': {
  101. 'box_count': '箱数', 'total_weight': '重量', 'weight_unit': '重量单位',
  102. 'total_volume': '体积', 'sku_count': 'SKU数量',
  103. 'clearance_total_price': '清关总价', 'clearance_currency': '清关币种',
  104. 'purchase_total_price': '采购总价', 'purchase_currency': '采购币种',
  105. },
  106. 'trader_info': {
  107. 'exporter': '出口商', 'importer': '进口商',
  108. 'coo_required': '是否做产地证',
  109. },
  110. },
  111. 'packages': {
  112. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  113. 'sku_summary': 'SKU', 'product_name_summary': '商品名',
  114. 'box_quantity': '箱数', 'box_length_cm': '单箱长(CM)',
  115. 'box_width_cm': '单箱宽(CM)', 'box_height_cm': '单箱高(CM)',
  116. 'gross_weight_kg': '单箱毛重量(KG)', 'net_weight_kg': '单箱净重量(KG)',
  117. 'is_over_length': '长度是否超限', 'is_over_width': '宽度是否超限',
  118. 'is_over_height': '高度是否超限', 'is_over_weight': '重量是否超限',
  119. },
  120. 'package_items': {
  121. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  122. 'box_specification': '箱规', 'box_specification_unit': '箱规单位',
  123. 'package_gross_weight_kg': '箱单单箱毛重(KG)',
  124. 'package_net_weight_kg': '箱单单箱净重(KG)',
  125. 'inspection_result': '查验结果', 'exception_reason': '异常原因',
  126. 'inspection_photo_count': '查验图片数量', 'sku': 'SKU',
  127. 'units_per_box': '单箱个数', 'declaration_type': '报关类型',
  128. 'box_number': '箱号', 'item_gross_weight_kg': '商品单箱毛重量(KG)',
  129. 'item_net_weight_kg': '商品单箱净重量(KG)', 'chinese_name': '中文品名',
  130. 'english_name': '英文名称', 'brand_type': '品牌类型', 'brand': '品牌',
  131. 'model': '型号', 'material_cn': '材质(CN)', 'material_en': '材质(EN)',
  132. 'purpose_cn': '用途', 'goods_attributes': '商品属性',
  133. 'declaration_hs_code': '报关编码', 'clearance_hs_code': '清关编码',
  134. 'material_ratio': '材质占比', 'clearance_unit_price': '清关单价',
  135. 'clearance_currency': '清关币种', 'purchase_unit_price': '采购单价',
  136. 'purchase_currency': '采购币种', 'product_image_count': '商品图片数量',
  137. 'remark': '备注',
  138. },
  139. 'dw_auth': {
  140. 'fba_id': 'FBAID', 'dw_start': 'DW开始时间', 'dw_end': 'DW结束时间',
  141. 'dw_display': 'DW', 'authorization_status': '客户授权状态',
  142. },
  143. 'attachments': {
  144. 'category': '附件分类', 'file_name': '文件名称',
  145. 'file_extension': '文件类型', 'is_image': '是否图片',
  146. 'preview_url': '预览链接', 'download_url': '下载链接',
  147. 'cost_name': '收费项目',
  148. },
  149. 'inbound_summary': {
  150. 'inbound_status': '入库状态', 'inbound_time': '入库时间',
  151. 'inbound_operator': '操作人', 'warehouse': '仓库',
  152. 'abnormal_reason': '异常原因', 'inbound_photo_count': '入库图片数量',
  153. 'forecast_pwv_summary': '预报件重体', 'inbound_pwv_summary': '入库件重体',
  154. },
  155. 'inbound': {
  156. 'has_label': '是否贴标', 'shipment_id': 'SHIPMENT ID',
  157. 'inbound_quantity': '入库件数',
  158. 'measurement_photo_count': '测量图片数量',
  159. 'box_specification': '入库箱规', 'weight_mode': None, 'weight': None,
  160. 'weight_unit': '重量单位', 'is_over_length': '长度是否超限',
  161. 'is_over_width': '宽度是否超限', 'is_over_height': '高度是否超限',
  162. 'is_over_weight': '重量是否超限', 'operated_at': '操作时间',
  163. },
  164. 'checks': {
  165. 'shipment_id': '货件编号', 'sku': 'SKU', 'box_number': '箱号',
  166. 'box_quantity': '箱数', 'box_specification': '箱规',
  167. 'inspection_result': '查验结果',
  168. 'inspection_photo_count': '查验图片数量', 'remark': '备注',
  169. 'inspector': '查验人', 'inspected_at': '查验时间',
  170. },
  171. 'tracks': {
  172. 'track_type': '轨迹类型', 'status': '轨迹节点', 'location': '轨迹地点',
  173. 'occurred_at': '时间', 'tracking_number': '跟踪号',
  174. 'shipment_id': 'SHIPMENT ID', 'content': '轨迹内容',
  175. },
  176. 'operation_logs': {
  177. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  178. },
  179. 'cost_logs': {
  180. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  181. },
  182. 'delivery_summary': {
  183. 'master_tracking_number': '主跟踪号', 'sub_order_count': '子单数量',
  184. },
  185. 'delivery': {'sub_tracking_number': '子跟踪号'},
  186. }
  187. ORDER_DETAIL_STATUS_FIELDS = {
  188. 'stage': '阶段', 'label': '节点', 'state': '状态',
  189. 'occurred_at': '时间', 'time_kind': '时间类型',
  190. }
  191. ORDER_DETAIL_STATES = {
  192. 'completed': '已完成', 'in_progress': '进行中',
  193. 'pending': '待完成', 'hidden': '不展示',
  194. }
  195. ORDER_DETAIL_TIME_KINDS = {
  196. 'actual': '实际', 'estimated': '预计', 'empty': '暂无',
  197. }
  198. TABLE_COLUMNS = {
  199. 'query_order_exact': {
  200. 'order_number': ('订单号',),
  201. 'reference_number': ('客户参考号',),
  202. 'status_txt_name': ('状态',),
  203. 'check_status_txt_name': ('是否已查验',),
  204. 'customer_name': ('客户名称',),
  205. 'customer_account_type_name': ('客户属性',),
  206. 'inbound_date': ('入库时间',),
  207. 'wo_num': ('未完成工单',),
  208. 'product_name': ('物流产品',),
  209. 'inbound_pieces': ('件数',),
  210. 'inbound_volume': ('体积(CBM)',),
  211. 'inbound_weight': ('重量(KG)',),
  212. 'pro_cn_name': ('品名',),
  213. 'export_declaration_type': ('报关方式',),
  214. 'merge_declare_number': ('合并报关单号',),
  215. 'delivery_address': ('派送地址',),
  216. 'container_code': ('柜号',),
  217. 'out_status_txt': ('排舱单状态',),
  218. 'hinge_of_destination': ('目的港',),
  219. 'etd': ('ETD',),
  220. 'atd': ('ATD',),
  221. 'eta': ('ETA',),
  222. 'ata': ('ATA',),
  223. 'release_time': ('清关放行时间',),
  224. 'oversea_inbound_date': ('海外入库时间',),
  225. 'appt_time': ('APPT时间',),
  226. 'est_loading_time': ('预计装柜时间',),
  227. 'pickup_time': ('海外提柜时间',),
  228. 'delivery_way_title': ('派送方式',),
  229. 'tracking_number': ('快递单号', '承运商跟踪号码'),
  230. 'shipment_id': ('Shipment ID',),
  231. 'goods_attribute': ('商品属性',),
  232. 'sku': ('SKU',),
  233. 'sales_user': ('商务经理',),
  234. 'service_user': ('客户经理',),
  235. 'department_name': ('事业部',),
  236. 'remark': ('订单备注',),
  237. 'importer_name': ('进口商',),
  238. 'warehouse_name': ('交货仓库',),
  239. 'paid_status_name': ('付款状态',),
  240. },
  241. 'query_track': {
  242. 'status': ('轨迹节点', '轨迹状态,如:开始集港、离港放行、清关、配送等'),
  243. 'location': ('轨迹地点', '发生地点'),
  244. 'time': ('时间', '轨迹发生时间(已转换为用户时区)'),
  245. 'content': ('轨迹内容', '详细描述'),
  246. 'tracking_number': ('跟踪号', '快递单号'),
  247. 'shipment_id': ('Shipment ID', '包裹ID'),
  248. },
  249. 'query_customs_declaration_files': {
  250. 'outbound_number': ('排舱单号',),
  251. 'order_number': ('订单号',),
  252. 'file_name': ('文件名',),
  253. 'file_type': ('文件类型',),
  254. 'file_url': ('文件链接',),
  255. },
  256. 'query_outbound_list': {
  257. 'outbound_number': ('排舱单号',),
  258. 'direct_send': ('直送柜',),
  259. 'remark': ('备注',),
  260. 'cargo_type': ('超长超重',),
  261. 'warehouse_name': ('集货仓库',),
  262. 'status': ('状态',),
  263. 'so_number': ('SO号',),
  264. 'container_code': ('柜号',),
  265. 'seal_number': ('封条号',),
  266. 'container_type': ('柜型',),
  267. 'cabinet_type': ('整拼类型',),
  268. 'shipping_method': ('运输方式',),
  269. 'total_volume': ('体积(CBM)',),
  270. 'total_weight': ('重量(KG)',),
  271. 'ship_schedule': ('船期',),
  272. 'closing_time': ('截关时间',),
  273. 'est_loading_time': ('预计装柜时间',),
  274. 'operator': ('操作人',),
  275. 'operation_modes': ('拖报清方式',),
  276. 'handle_method': ('操作方式',),
  277. 'operation_time': ('操作时间',),
  278. 'ship_company': ('船司',),
  279. 'vessel_name': ('船名航次',),
  280. 'route': ('航线',),
  281. 'cutoff_time_si': ('截SI时间',),
  282. 'clearance_port': ('清关口岸',),
  283. 'clearance_port_eta': ('清关口岸ETA',),
  284. 'loading_port': ('起运港',),
  285. 'destination_port': ('目的港',),
  286. 'wharf_name': ('到港码头',),
  287. 'transit_port': ('中转港',),
  288. 'etd': ('ETD',),
  289. 'eta': ('ETA',),
  290. 'ata': ('ATA',),
  291. 'clearance_release_time': ('清关放行时间',),
  292. 'overseas_warehouse': ('海外仓',),
  293. 'providers_name': ('拖车行',),
  294. 'has_fda': ('是否含FDA认证商品',),
  295. 'has_cpsc': ('是否含CPSC商品',),
  296. 'has_food': ('是否含食品',),
  297. },
  298. 'query_outbound_detail': {
  299. 'order_number': ('订单号',),
  300. 'cargo_type': ('超长超重',),
  301. 'customs_files': ('报关资料',),
  302. 'reference_number': ('客户参考号',),
  303. 'customer_name': ('客户名称',),
  304. 'declaration_type': ('报关方式',),
  305. 'merge_declare_number': ('合并报关单号',),
  306. 'order_remark': ('订单备注',),
  307. 'bl_number': ('提单号',),
  308. 'container_code': ('柜号',),
  309. 'customer_service': ('客户经理',),
  310. 'est_inbound_date': ('预计入库时间',),
  311. 'inbound_date': ('实际入库时间',),
  312. 'status': ('状态',),
  313. 'pieces': ('预报件数 / 入库件数',),
  314. 'weight': ('预报实重(KG) / 入库实重(KG)',),
  315. 'volume': ('预报体积(m³) / 入库体积(m³)',),
  316. 'pickup_place': ('交货地',),
  317. 'product_name': ('物流产品',),
  318. 'goods_name': ('品名',),
  319. 'closing_time': ('截关时间',),
  320. 'clearance_remark': ('报关备注',),
  321. 'import_clearance_remark': ('清关备注',),
  322. 'delivery_address': ('派送地址',),
  323. 'delivery_type': ('派送类型',),
  324. 'delivery_way': ('派送方式',),
  325. 'channel': ('派送渠道',),
  326. 'country_name': ('目的国',),
  327. 'importer_name': ('进口商',),
  328. 'vat_type': ('清关税号',),
  329. 'packing_type': ('货物类型',),
  330. 'is_abnormal': ('是否问题件',),
  331. 'package_method': ('包装类型',),
  332. 'order_reply': ('到货回复',),
  333. 'is_must_load': ('订单是否必装',),
  334. 'has_fda': ('是否含FDA认证商品',),
  335. 'has_cpsc': ('是否含CPSC商品',),
  336. 'has_food': ('是否含食品',),
  337. },
  338. 'query_customer_list': {
  339. 'customer_name': ('客户名称',),
  340. 'customer_code': ('客户代码',),
  341. 'create_time': ('开户时间',),
  342. 'business_type': ('业务类型',),
  343. 'customer_attribute': ('客户属性',),
  344. 'customer_source': ('客户来源',),
  345. 'first_inbound_date': ('首次成交时间',),
  346. 'last_inbound_date': ('最后一次走货时间',),
  347. 'active_status': ('活跃状态',),
  348. 'contract_status': ('合同状态',),
  349. 'contract_validity': ('合同有效期',),
  350. 'credit_limit': ('信用额度',),
  351. 'currency_code': ('结算币种',),
  352. 'billing_modes': ('结算模式(分业务类型)',),
  353. 'sales_name': ('商务经理',),
  354. 'merchandiser_name': ('客户经理',),
  355. 'department_name': ('事业部',),
  356. },
  357. }
  358. PAYMENT_FOLLOWUP_COLUMNS = {
  359. 'customer_name': '客户名称',
  360. 'settlement_currency': '结算币种',
  361. 'billed_unverified_amount': '已出账未核销金额',
  362. 'unbilled_amount': '未出账金额',
  363. 'overdue_unpaid_amount': '逾期未回款金额',
  364. 'billed_unverified_amount_cny': '已出账未核销金额(人民币)',
  365. 'unbilled_amount_cny': '未出账金额(人民币)',
  366. 'overdue_unpaid_amount_cny': '逾期未回款金额(人民币)',
  367. 'unverified_receivable_monthly_summary': '未回款月份汇总',
  368. 'receipt_unverified_amount': '收款单未核销金额',
  369. 'current_balance': '当前余额',
  370. 'credit_limit': '信用额度',
  371. 'bad_debt_total': '坏账合计',
  372. 'contract_status': '合同状态',
  373. }
  374. PAYMENT_FOLLOWUP_DETAIL_COLUMNS = {
  375. 'bill_month': '账单月份',
  376. 'bill_no': '账单号',
  377. 'business_type': '业务类型',
  378. 'settlement_mode': '结算模式',
  379. 'unverified_amount': '未核销金额',
  380. 'customer_receivable_date': '客户应收款日期',
  381. }
  382. PAYMENT_RECORD_COLUMNS = {
  383. 'customer_name': '客户名称',
  384. 'payment_reference': '收款水单号',
  385. 'original_received_amount': '原币到账金额',
  386. 'actual_received_amount': '实际收款金额',
  387. 'receive_date': '收款日期',
  388. 'verified_amount': '已核销金额',
  389. 'unverified_amount': '未核销金额',
  390. 'payment_approval_status': '收款审核状态',
  391. }
  392. RECEIVABLE_COST_COLUMNS = {
  393. 'order_number': '订单号',
  394. 'customer_name': '客户名称',
  395. 'cost_name': '费用项',
  396. 'cost_customer_name': '费用客户',
  397. 'charge_weight': '计费重',
  398. 'unit_price': '计费单价',
  399. 'quote_currency': '原币币种',
  400. 'receivable_original_amount': '应收原币',
  401. 'receivable_amount_cny': '应收金额(CNY)',
  402. 'settlement_amount_cny': '结算金额(CNY)',
  403. 'cost_confirmation_status': '费用确认状态',
  404. 'closing_status': '关账状态',
  405. 'verification_status': '核销状态',
  406. }
  407. RECEIVABLE_COST_SUMMARY = {
  408. 'order_total_receivable_cny': '订单总应收(CNY)',
  409. 'order_total_settlement_cny': '订单总结算(CNY)',
  410. 'special_approval_amount_cny': '特批金额(CNY)',
  411. 'settlement_gross_profit_cny': '结算毛利(CNY)',
  412. }
  413. RECEIVABLE_LIST_COLUMNS = {
  414. 'main_customer_name': '主客户',
  415. 'sub_customer_name': '子客户',
  416. 'customer_attribute': '客户属性',
  417. 'department_name': '事业部',
  418. 'document_type': '单据类型',
  419. 'warehouse_name': '仓库',
  420. 'business_number': '业务单号',
  421. 'reference_number': '参考号',
  422. 'cost_name': '费用项',
  423. 'original_amount': '原币金额',
  424. 'total_amount': '总金额',
  425. 'billed_amount': '已出账金额',
  426. 'unbilled_amount': '未出账金额',
  427. 'bill_number': '账单编号',
  428. 'verification_status': '核销状态',
  429. 'receipt_number': '收款水单号',
  430. 'receipt_date': '收款日期',
  431. 'sales_name': '商务经理',
  432. 'merchandiser_name': '客户经理',
  433. 'drainage_user_name': '引流人',
  434. 'first_leg_order_status': '头程订单状态',
  435. 'settlement_mode': '结算模式',
  436. 'cost_occurred_at': '费用发生时间',
  437. 'business_occurred_at': '业务发生时间',
  438. }
  439. PAYABLE_COST_COLUMNS = {
  440. 1: (
  441. ('number', '单号'), ('so_number', 'SO号'), ('container_code', '柜号'),
  442. ('bl_number', '提单号'), ('sub_number', '订单号'),
  443. ('business_node_name', '业务节点'), ('providers_name', '物流商'),
  444. ('cost_name', '费用名称'), ('payable_cost_q', '金额'), ('currency', '币种'),
  445. ('company_money_q', '本位币金额'), ('yf_lock', '应付锁定'),
  446. ('trade_date', '费用发生时间'), ('verify_status_text', '核销状态'),
  447. ('remark', '备注'), ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
  448. ),
  449. 2: (
  450. ('number', '单号'), ('sub_number', '跟踪单号'), ('workorder_number', '工单号'),
  451. ('order_type_name', '单据类型'), ('providers_name', '物流商'),
  452. ('cost_name', '费用名称'), ('payable_cost_q', '应付原币金额'),
  453. ('currency', '应付原币币种'), ('company_money_q', '本位币金额%s'),
  454. ('yf_lock', '应付锁定'), ('business_date', '业务发生时间'),
  455. ('trade_date', '费用发生时间'), ('create_date', '操作时间'),
  456. ('verify_status_text', '核销状态'), ('remark', '备注'),
  457. ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
  458. ),
  459. 3: (
  460. ('number', '单号'), ('order_status_text', '包裹状态'),
  461. ('providers_name', '物流商'), ('business_node_name', '费用业务节点'),
  462. ('cost_name', '费用名称'), ('detail_price', '计费单价'),
  463. ('charge_weight', '计费重'), ('quote_cost', '计费金额'),
  464. ('payable_cost_q', '实际应付金额'), ('quote_currency', '原币币种'),
  465. ('company_money_q', '计费本位币金额'), ('yf_lock', '应付锁定'),
  466. ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
  467. ('trade_date', '费用发生时间'), ('verify_status_text', '核销状态'),
  468. ('remark', '财务备注'), ('create_user_name', '操作人'), ('create_date', '录入时间'),
  469. ),
  470. 4: (
  471. ('number', '订单号'), ('business_bill_no', '货代账单号'),
  472. ('providers_name', '物流商'), ('cost_name', '费用名称'),
  473. ('payable_cost_q', '金额'), ('currency', '币种'),
  474. ('company_money_q', '本位币金额'), ('department_name', '事业部'),
  475. ('yf_lock', '应付锁定'), ('trade_date', '费用发生时间'),
  476. ('verify_status_text', '核销状态'), ('business_node_name', '业务节点'),
  477. ('remark', '备注'), ('bill_no', '应付账单编号'),
  478. ('payment_order_number', '付款单号'),
  479. ),
  480. 5: (
  481. ('order_type_name', '单据类型'), ('number', '订单号'), ('warehouse_name', '仓库'),
  482. ('business_node_name', '业务节点'), ('providers_name', '物流商'),
  483. ('cost_name', '费用名称'), ('payable_cost_q', '金额'), ('currency', '币种'),
  484. ('company_money_q', '本位币金额'), ('yf_lock', '应付锁定'),
  485. ('trade_date', '费用发生时间'), ('verify_status_text', '核销状态'),
  486. ('remark', '备注'), ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
  487. ),
  488. 7: (
  489. ('number', '订单号'), ('ep_order_status_text', '订单状态'),
  490. ('business_node_name', '业务节点'), ('providers_name', '物流商'),
  491. ('cost_name', '费用名称'), ('detail_price', '计费单价'),
  492. ('charge_weight', '计费重'), ('quote_cost', '计费金额'),
  493. ('payable_cost_q', '实际应付金额'), ('quote_currency', '原币币种'),
  494. ('company_money_q', '本位币金额'), ('trade_date', '费用发生时间'),
  495. ('remark', '备注'), ('verify_status_text', '核销状态'),
  496. ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
  497. ('create_user_name', '操作人'), ('create_date', '录入时间'),
  498. ),
  499. }
  500. PAYABLE_AMOUNT_KEYS = frozenset((
  501. 'detail_price', 'charge_weight', 'quote_cost', 'payable_cost_q', 'company_money_q',
  502. ))
  503. PAYMENT_FOLLOWUP_MONTHLY_COLUMNS = {
  504. 'receivable_month': '应收月份',
  505. 'unverified_amount': '未核销金额',
  506. 'is_overdue': '是否逾期',
  507. }
  508. DESTINATION_TRAILER_COLUMNS = {
  509. 'progress': (
  510. ('bl_number', '提单号'), ('container_code', '柜号'),
  511. ('container_type', '柜型'), ('warehouse_name', '仓库名称'),
  512. ('providers_name', '拖车行'), ('trailer_status', '提柜状态'),
  513. ('latest_remark', '最新操作备注'), ('is_direct_send', '直送'),
  514. ('cabinet_type', '整拼类型'), ('vessel_name', '船名航次'),
  515. ('route', '航线'), ('clearance_check', '清关查验'),
  516. ('etd', 'ETD'), ('atd', 'ATD'), ('eta', 'ETA'), ('ata', 'ATA'),
  517. ('loading_port', '起运港'), ('destination_port', '目的港'),
  518. ('wharf_name', '到港码头'), ('appt_time', 'APPT时间'),
  519. ('delivery_end_time', '卡车实际派送时间'),
  520. ('est_pickup_time', '预计提柜时间'),
  521. ('pickup_time', '实际提柜时间'), ('inbound_date', '到仓时间'),
  522. ('container_return_time', '还柜时间'),
  523. ('pickup_prescription', '提柜时效'),
  524. ('return_prescription', '还柜时效'),
  525. ('wharf_wait_time', '码头等待时间'),
  526. ('amazon_wait_time', '亚马逊等待时间'),
  527. ('bill_status', '应付费用状态'),
  528. ),
  529. 'do': (
  530. ('trailer_number', '拖车单号'), ('outbound_number', '出库单号'),
  531. ('container_code', '柜号'), ('container_type', '柜型'),
  532. ('bl_number', '提单号'), ('is_direct_send', '是否直送'),
  533. ('original_do_file', '原DO单'), ('new_do_file', '新DO单'),
  534. ('email_subject', '邮件主题'), ('email_from', '邮件发送人'),
  535. ('received_at', '邮件接收时间'),
  536. ),
  537. }
  538. DESTINATION_TRAILER_FILE_KEYS = frozenset(('original_do_file', 'new_do_file'))
  539. DESTINATION_TRAILER_PROGRESS_STAGES = frozenset((
  540. '待安排拖车', '待提柜', '待还柜(海)', '已还柜(海)', '已提货(空)',
  541. ))
  542. ORDER_ABNORMAL_COLUMNS = (
  543. ('order_number', '订单号'), ('customer_name', '客户'),
  544. ('product_name', '物流产品'), ('abnormal_status', '问题件状态'),
  545. ('abnormal_type', '问题件类型'), ('abnormal_desc', '问题件描述'),
  546. ('outbound_status', '排舱单状态'), ('inbound_date', '入库时间'),
  547. ('marker_name', '标记人'),
  548. )
  549. ORDER_ABNORMAL_STATUSES = frozenset((
  550. '待处理', '放行待审核', '包裹放行', '退件待审核', '退件驳回', '已退件',
  551. ))
  552. OUTBOUND_DETAIL_SUMMARY = {
  553. 'bl_number': '提单号',
  554. 'container_code': '柜号',
  555. 'container_type': '柜型',
  556. 'total_volume': '总体积',
  557. 'total_weight': '总重量',
  558. 'total_pieces': '总件数',
  559. 'sku': 'SKU',
  560. 'buy_declaration_count': '买单报关数量',
  561. 'general_declaration_count': '一般贸易报关数量',
  562. 'must_load': '必装单量/体积',
  563. 'backup_load': '备装单量/体积',
  564. }
  565. FIELD_LABELS = {
  566. 'query_order_exact': {
  567. 'order_number': '订单号',
  568. 'order_numbers': '订单号',
  569. 'reference_number': '客户参考号',
  570. 'reference_numbers': '客户参考号',
  571. 'tracking_number': '快递单号',
  572. 'tracking_numbers': '快递单号',
  573. 'outbound_number': '排舱单号',
  574. 'outbound_numbers': '排舱单号',
  575. 'container_code': '柜号',
  576. 'container_codes': '柜号',
  577. 'so_number': 'SO号',
  578. 'so_numbers': 'SO号',
  579. 'shipment_id': 'Shipment ID',
  580. 'receiver_country': '收货国家',
  581. 'product_ids': '物流产品',
  582. 'customer_ids': '客户',
  583. 'sales_id': '销售人员',
  584. 'warehouse_ids': '仓库',
  585. 'department_id': '事业部',
  586. 'inbound_date_start': '入库开始日期',
  587. 'inbound_date_end': '入库结束日期',
  588. 'outbound_date_start': '出库开始日期',
  589. 'outbound_date_end': '出库结束日期',
  590. 'page': '页码',
  591. 'limit': '每页数量',
  592. },
  593. 'query_track': {
  594. 'order_id': '订单ID',
  595. 'order_number': '订单号',
  596. 'tracking_number': '快递单号',
  597. 'page': '页码',
  598. 'limit': '每页数量',
  599. },
  600. 'query_customs_declaration_files': {
  601. 'outbound_numbers': '排舱单号',
  602. 'order_numbers': '订单号',
  603. 'page': '页码',
  604. 'limit': '每页数量',
  605. },
  606. 'query_outbound_list': {
  607. 'outbound_numbers': '排舱单号',
  608. 'order_numbers': '订单号',
  609. 'container_codes': '柜号',
  610. 'so_numbers': 'SO号',
  611. 'bl_numbers': '提单号',
  612. 'outbound_status': '排舱状态',
  613. 'shipping_method': '运输方式',
  614. 'warehouse_id': '集货仓库',
  615. 'is_direct_send': '是否直送柜',
  616. 'page': '页码',
  617. 'limit': '每页数量',
  618. },
  619. 'query_outbound_detail': {
  620. 'outbound_number': '排舱单号',
  621. 'page': '页码',
  622. 'limit': '每页数量',
  623. },
  624. 'query_order_detail': {
  625. 'order_number': '订单号', 'section': '详情模块',
  626. 'page': '页码', 'limit': '每页数量',
  627. },
  628. 'list_order_filter_options': {
  629. 'filter_type': '筛选项类型',
  630. 'keyword': '关键词',
  631. 'page': '页码',
  632. 'limit': '每页数量',
  633. },
  634. 'list_outbound_filter_options': {
  635. 'filter_type': '筛选类别',
  636. 'keyword': '显示名称',
  637. 'page': '页码',
  638. 'limit': '每页数量',
  639. },
  640. 'list_pending_outbound_export_filter_options': {
  641. 'filter_type': '筛选项类型',
  642. 'product_type_id': '产品分类',
  643. 'keyword': '关键词',
  644. 'page': '页码',
  645. 'limit': '每页数量',
  646. },
  647. 'query_customer_list': {
  648. 'customer_id': '客户名称',
  649. 'department_id': '事业部',
  650. 'sales_id': '商务经理',
  651. 'merchandiser_id': '客户经理',
  652. 'page': '页码',
  653. 'limit': '每页数量',
  654. },
  655. 'query_customer_payment_followup': {
  656. 'customer_id': '客户名称',
  657. 'department_id': '事业部',
  658. 'sales_id': '商务经理',
  659. 'merchandiser_id': '客户经理',
  660. 'has_unverified_receivable_only': '只看有应收未核销费用的客户',
  661. 'page': '页码',
  662. 'limit': '每页数量',
  663. },
  664. 'query_customer_unverified_bill_details': {
  665. 'customer_id': '客户名称',
  666. 'page': '页码',
  667. 'limit': '每页数量',
  668. },
  669. 'list_customer_filter_options': {
  670. 'filter_type': '筛选项类型',
  671. 'keyword': '关键词',
  672. 'page': '页码',
  673. 'limit': '每页数量',
  674. },
  675. 'export_pending_outbound_orders': {
  676. 'number': '单号',
  677. 'product_type_id': '产品分类',
  678. 'product_id': '物流产品',
  679. 'order_warehouse_id': '集货仓库',
  680. 'receiver_country': '目的国',
  681. 'is_remove': '是否装柜剔除',
  682. 'address': '派送地址',
  683. 'inbound_date': '入库时间',
  684. 'status': '订单状态',
  685. 'merge_declare_number': '合并报关单号',
  686. 'importer_id': '进口商',
  687. 'packing_type': '货物类型',
  688. 'is_battery': '带电属性',
  689. 'is_magnetic': '带磁属性',
  690. 'is_wood': '带木属性',
  691. 'is_other': '其他商品属性',
  692. 'is_fda': 'FDA产品属性',
  693. 'is_toy': '玩具属性',
  694. 'is_ultra_limit': '超长超重属性',
  695. 'is_sensitive': '敏感货属性',
  696. 'is_food': '食品属性',
  697. 'no_property': '无属性',
  698. },
  699. 'export_out_of_province_port_data': {
  700. 'outbound_numbers': '排舱单号',
  701. 'container_codes': '柜号',
  702. 'bl_numbers': '提单号',
  703. 'so_numbers': 'SO号',
  704. 'file_type': '资料类型',
  705. },
  706. 'export_pallet_data': {
  707. 'container_codes': '柜号',
  708. 'bl_numbers': '提单号',
  709. 'inbound_time_start': '海外仓入库时间开始',
  710. 'inbound_time_end': '海外仓入库时间结束',
  711. },
  712. 'export_receivable_cost_list': {
  713. 'reference_numbers': '参考号',
  714. 'tracking_numbers': '跟踪号',
  715. 'order_numbers': '订单号',
  716. 'bill_numbers': '账单编号',
  717. 'business_date_start': '业务发生开始日期',
  718. 'business_date_end': '业务发生结束日期',
  719. 'customer_id': '主客户',
  720. 'sub_customer_id': '子客户',
  721. 'billing_status': '出账状态',
  722. 'verification_status': '核销状态',
  723. 'document_type': '单据类型',
  724. 'cost_type_id': '费用项',
  725. },
  726. 'query_export_task': {
  727. 'task_ref': '导出任务引用',
  728. },
  729. }
  730. ERROR_MESSAGES = {
  731. 'MCP_1101': '设备配置已失效,请重新生成配置',
  732. 'MCP_1102': '设备会话已过期,请重新连接',
  733. 'MCP_1103': '员工账号不可用,请联系管理员',
  734. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  735. 'MCP_1201': '工具当前不可用',
  736. 'MCP_1202': '工具当前不可用',
  737. 'MCP_1301': '没有权限使用此工具',
  738. 'MCP_1501': '目标数据不可用',
  739. 'MCP_1502': '结果过多,请缩小查询范围',
  740. 'MCP_1601': '没有可导出的数据',
  741. 'MCP_9001': '工具调用失败,请稍后重试',
  742. }
  743. NON_RETRYABLE_CODES = frozenset((
  744. 'MCP_1101',
  745. 'MCP_1102',
  746. 'MCP_1103',
  747. 'MCP_1104',
  748. 'MCP_1201',
  749. 'MCP_1202',
  750. 'MCP_1301',
  751. 'MCP_1401',
  752. 'MCP_1501',
  753. 'MCP_1502',
  754. 'MCP_1601',
  755. ))
  756. def handles(self, tool_name):
  757. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  758. # Convert a backend envelope into text and structured display data.
  759. def present(self, tool_name, tool_result):
  760. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  761. return self._format_error()
  762. code = str(tool_result.get('code') or '').strip()
  763. meta = self._build_meta(tool_result.get('meta'))
  764. if code not in ('MCP_0000', '0'):
  765. return self._business_error(
  766. tool_name,
  767. code or 'MCP_9001',
  768. tool_result.get('msg'),
  769. meta,
  770. )
  771. data = tool_result.get('data')
  772. if not isinstance(data, dict):
  773. return self._format_error(meta)
  774. if tool_name in self.DETAIL_TOOLS:
  775. return self._present_outbound_detail(
  776. tool_name,
  777. data,
  778. tool_result.get('meta'),
  779. meta,
  780. )
  781. if tool_name in self.ORDER_DETAIL_TOOLS:
  782. return self._present_order_detail(data, tool_result.get('meta'), meta)
  783. if tool_name in self.PAYMENT_FOLLOWUP_TOOLS:
  784. return self._present_customer_payment_followup(
  785. data, tool_result.get('meta'), meta
  786. )
  787. if tool_name in self.PAYMENT_DETAIL_TOOLS:
  788. return self._present_customer_unverified_bill_details(
  789. data, tool_result.get('meta'), meta
  790. )
  791. if tool_name in self.PAYMENT_RECORD_TOOLS:
  792. return self._present_customer_payment_records(
  793. data, tool_result.get('meta'), meta
  794. )
  795. if tool_name in self.RECEIVABLE_COST_TOOLS:
  796. return self._present_order_receivable_cost_details(
  797. data, tool_result.get('meta'), meta
  798. )
  799. if tool_name in self.RECEIVABLE_LIST_TOOLS:
  800. return self._present_receivable_cost_list(
  801. data, tool_result.get('meta'), meta
  802. )
  803. if tool_name in self.RECEIVABLE_FILTER_TOOLS:
  804. return self._present_receivable_cost_filter_options(
  805. data, tool_result.get('meta'), meta
  806. )
  807. if tool_name in self.PAYABLE_COST_TOOLS:
  808. return self._present_payable_cost_list(
  809. data, tool_result.get('meta'), meta
  810. )
  811. if tool_name in self.PAYABLE_FILTER_TOOLS:
  812. return self._present_receivable_cost_filter_options(
  813. data, tool_result.get('meta'), meta
  814. )
  815. if tool_name in self.DESTINATION_TRAILER_TOOLS:
  816. return self._present_destination_trailer_list(
  817. data, tool_result.get('meta'), meta
  818. )
  819. if tool_name in self.ORDER_ABNORMAL_TOOLS:
  820. return self._present_order_abnormal_list(
  821. data, tool_result.get('meta'), meta
  822. )
  823. if tool_name in self.TABLE_TOOLS:
  824. return self._present_table(
  825. tool_name,
  826. data,
  827. tool_result.get('meta'),
  828. meta,
  829. )
  830. if tool_name in self.OPTION_TOOLS:
  831. if tool_name == 'list_customer_filter_options':
  832. return self._present_customer_options(
  833. data, tool_result.get('meta'), meta
  834. )
  835. return self._present_options(data, tool_result.get('meta'), meta)
  836. if tool_name in self.EXPORT_TOOLS:
  837. return self._present_export_submission(data, meta)
  838. if tool_name in self.PAYABLE_EXPORT_TOOLS:
  839. return self._present_export_submission(data, meta)
  840. return self._present_export_task(data, meta)
  841. def _present_order_detail(self, data, raw_meta, meta):
  842. if set(data) != {'section', 'order_number', 'payload'}:
  843. return self._format_error(meta)
  844. section = data.get('section')
  845. order_number = data.get('order_number')
  846. payload = data.get('payload')
  847. if (
  848. section not in self.ORDER_DETAIL_SECTIONS
  849. or not isinstance(order_number, str) or not order_number.strip()
  850. or not isinstance(payload, dict)
  851. ):
  852. return self._format_error(meta)
  853. content = {
  854. '订单号': order_number.strip(),
  855. '详情模块': self.ORDER_DETAIL_SECTIONS[section],
  856. }
  857. if section == 'all':
  858. all_content = self._present_order_detail_all(payload)
  859. if all_content is None:
  860. return self._format_error(meta)
  861. content.update(all_content)
  862. elif section == 'overview':
  863. expected = {
  864. 'status_nodes', 'order_info', 'freight_info',
  865. 'package_summary', 'trader_info',
  866. }
  867. if set(payload) != expected or not isinstance(payload['status_nodes'], list):
  868. return self._format_error(meta)
  869. nodes = []
  870. for row in payload['status_nodes']:
  871. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  872. if translated is None:
  873. return self._format_error(meta)
  874. state = row.get('state')
  875. time_kind = row.get('time_kind')
  876. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  877. return self._format_error(meta)
  878. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  879. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  880. nodes.append(translated)
  881. content['状态节点'] = nodes
  882. for raw_key, chinese_key in (
  883. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  884. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  885. ):
  886. translated = self._translate_exact(
  887. payload.get(raw_key),
  888. self.ORDER_DETAIL_FIELDS['overview'][raw_key],
  889. )
  890. if translated is None:
  891. return self._format_error(meta)
  892. content[chinese_key] = translated
  893. elif section == 'inbound':
  894. if set(payload) != {'summary', 'records'}:
  895. return self._format_error(meta)
  896. summary = self._translate_exact(
  897. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  898. )
  899. records = self._translate_order_detail_rows(section, payload.get('records'))
  900. if summary is None or records is None:
  901. return self._format_error(meta)
  902. content['入库概况'] = summary
  903. content['明细'] = records
  904. pagination = self._order_detail_pagination(raw_meta)
  905. if pagination is None:
  906. return self._format_error(meta)
  907. content['分页'] = pagination
  908. elif section == 'delivery':
  909. if set(payload) != {'summary', 'records'}:
  910. return self._format_error(meta)
  911. summary = self._translate_exact(
  912. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  913. )
  914. records = self._translate_order_detail_rows(section, payload.get('records'))
  915. if summary is None or records is None:
  916. return self._format_error(meta)
  917. content['派送汇总'] = summary
  918. content['明细'] = records
  919. pagination = self._order_detail_pagination(raw_meta)
  920. if pagination is None:
  921. return self._format_error(meta)
  922. content['分页'] = pagination
  923. else:
  924. if set(payload) != {'records'}:
  925. return self._format_error(meta)
  926. records = self._translate_order_detail_rows(section, payload.get('records'))
  927. pagination = self._order_detail_pagination(raw_meta)
  928. if records is None or pagination is None:
  929. return self._format_error(meta)
  930. content['明细'] = records
  931. content['分页'] = pagination
  932. text = json.dumps(content, ensure_ascii=False, indent=2)
  933. return self._success_result(content, text, meta)
  934. def _present_order_detail_all(self, payload):
  935. expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
  936. if set(payload) != expected_sections:
  937. return None
  938. overview = payload.get('overview')
  939. if not isinstance(overview, dict) or set(overview) != {
  940. 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
  941. } or not isinstance(overview['status_nodes'], list):
  942. return None
  943. overview_content = {'状态节点': []}
  944. for row in overview['status_nodes']:
  945. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  946. if translated is None:
  947. return None
  948. state = row.get('state')
  949. time_kind = row.get('time_kind')
  950. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  951. return None
  952. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  953. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  954. overview_content['状态节点'].append(translated)
  955. for raw_key, chinese_key in (
  956. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  957. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  958. ):
  959. translated = self._translate_exact(
  960. overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
  961. )
  962. if translated is None:
  963. return None
  964. overview_content[chinese_key] = translated
  965. result = {'订单概览': overview_content}
  966. for section, label in self.ORDER_DETAIL_SECTIONS.items():
  967. if section in ('overview', 'all'):
  968. continue
  969. translated = self._present_order_detail_all_section(section, payload.get(section))
  970. if translated is None:
  971. return None
  972. result[label] = translated
  973. return result
  974. def _present_order_detail_all_section(self, section, payload):
  975. if not isinstance(payload, dict) or 'pagination' not in payload:
  976. return None
  977. pagination = self._order_detail_pagination(payload.get('pagination'))
  978. if pagination is None:
  979. return None
  980. if section == 'inbound':
  981. if set(payload) != {'summary', 'records', 'pagination'}:
  982. return None
  983. summary = self._translate_exact(
  984. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  985. )
  986. records = self._translate_order_detail_rows(section, payload.get('records'))
  987. if summary is None or records is None:
  988. return None
  989. return {'入库概况': summary, '明细': records, '分页': pagination}
  990. if section == 'delivery':
  991. if set(payload) != {'summary', 'records', 'pagination'}:
  992. return None
  993. summary = self._translate_exact(
  994. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  995. )
  996. records = self._translate_order_detail_rows(section, payload.get('records'))
  997. if summary is None or records is None:
  998. return None
  999. return {'派送汇总': summary, '明细': records, '分页': pagination}
  1000. if set(payload) != {'records', 'pagination'}:
  1001. return None
  1002. records = self._translate_order_detail_rows(section, payload.get('records'))
  1003. if records is None:
  1004. return None
  1005. return {'明细': records, '分页': pagination}
  1006. def _translate_order_detail_rows(self, section, records):
  1007. if not isinstance(records, list):
  1008. return None
  1009. mapping = self.ORDER_DETAIL_FIELDS.get(section)
  1010. if not isinstance(mapping, dict):
  1011. return None
  1012. translated_rows = []
  1013. for row in records:
  1014. translated = self._translate_exact(row, mapping)
  1015. if translated is None:
  1016. return None
  1017. if section == 'inbound':
  1018. mode = row.get('weight_mode')
  1019. if mode not in ('single_box', 'total'):
  1020. return None
  1021. translated[
  1022. '单箱入库重量' if mode == 'single_box' else '总重量KG'
  1023. ] = row.get('weight', '')
  1024. translated_rows.append(translated)
  1025. return translated_rows
  1026. @staticmethod
  1027. def _translate_exact(value, mapping):
  1028. if not isinstance(value, dict) or set(value) != set(mapping):
  1029. return None
  1030. result = {}
  1031. for key, label in mapping.items():
  1032. if label is None:
  1033. continue
  1034. item = value.get(key, '')
  1035. if isinstance(item, (dict, list)):
  1036. return None
  1037. result[label] = '' if item is None else item
  1038. return result
  1039. @staticmethod
  1040. def _order_detail_pagination(raw_meta):
  1041. if not isinstance(raw_meta, dict):
  1042. return None
  1043. if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
  1044. return None
  1045. page = raw_meta.get('page')
  1046. limit = raw_meta.get('limit')
  1047. has_more = raw_meta.get('has_more')
  1048. if isinstance(page, bool) or not isinstance(page, int) or page < 1:
  1049. return None
  1050. if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
  1051. return None
  1052. if not isinstance(has_more, bool):
  1053. return None
  1054. return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
  1055. # Map local tool exceptions without exposing internal error details.
  1056. def present_exception(self, tool_name, exception):
  1057. if not self.handles(tool_name):
  1058. return self._format_error()
  1059. message = str(exception or '').strip()
  1060. if isinstance(exception, ValueError):
  1061. label = self._find_field_label(tool_name, message)
  1062. return self._error_result(
  1063. 'MCP_1401',
  1064. self._parameter_message(label),
  1065. False,
  1066. )
  1067. if message == DEVICE_INVALID_MESSAGE:
  1068. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  1069. if message.lower().startswith('tool disabled'):
  1070. return self._error_result('MCP_1202', '工具当前不可用', False)
  1071. return self._error_result(
  1072. 'MCP_9001',
  1073. '工具调用失败,请稍后重试',
  1074. True,
  1075. )
  1076. def _present_table(self, tool_name, data, raw_meta, meta):
  1077. columns = data.get('columns')
  1078. records = data.get('records')
  1079. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  1080. return self._format_error(meta)
  1081. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  1082. if not isinstance(allowed_columns, dict):
  1083. return self._format_error(meta)
  1084. if tool_name == 'query_customer_list':
  1085. expected = list(allowed_columns.keys())
  1086. actual = [
  1087. column.get('key') if isinstance(column, dict) else None
  1088. for column in columns
  1089. ]
  1090. if actual != expected or self._customer_pagination(raw_meta) is None:
  1091. return self._format_error(meta)
  1092. headers = []
  1093. keys = []
  1094. for column in columns:
  1095. if not isinstance(column, dict):
  1096. return self._format_error(meta)
  1097. key = column.get('key')
  1098. label = column.get('name')
  1099. if not isinstance(key, str) or not key.strip():
  1100. return self._format_error(meta)
  1101. if not isinstance(label, str) or not label.strip():
  1102. return self._format_error(meta)
  1103. key = key.strip()
  1104. definition = allowed_columns.get(key)
  1105. if not isinstance(definition, tuple) or not definition:
  1106. return self._format_error(meta)
  1107. keys.append(key)
  1108. header = {'label': definition[0]}
  1109. if len(definition) > 1:
  1110. header['description'] = definition[1]
  1111. headers.append(header)
  1112. rows = []
  1113. for record in records:
  1114. if not isinstance(record, dict):
  1115. return self._format_error(meta)
  1116. if tool_name == 'query_customer_list' and set(record) != set(keys):
  1117. return self._format_error(meta)
  1118. row = []
  1119. for key in keys:
  1120. value = '' if record.get(key) is None else record.get(key, '')
  1121. if tool_name == 'query_customer_list' and key == 'billing_modes':
  1122. value = self._customer_billing_modes(value)
  1123. if value is None:
  1124. return self._format_error(meta)
  1125. elif tool_name == 'query_customer_list' and isinstance(value, (dict, list)):
  1126. return self._format_error(meta)
  1127. row.append(value)
  1128. rows.append(row)
  1129. content = {
  1130. 'summary': self._safe_text(data.get('summary')),
  1131. 'headers': headers,
  1132. 'rows': rows,
  1133. }
  1134. if tool_name == 'query_customer_list':
  1135. content['display_rules'] = {
  1136. 'mode': 'complete',
  1137. 'allow_summary': False,
  1138. 'allow_omit_records': False,
  1139. 'allow_omit_empty_fields': False,
  1140. 'allow_rename_fields': False,
  1141. 'preserve_record_order': True,
  1142. 'required_field_count': len(headers),
  1143. 'returned_record_count': len(rows),
  1144. 'required_value_count': len(headers) * len(rows),
  1145. 'instruction': '最终回复必须逐条展示全部记录及全部17个字段,不得摘要、省略或改写',
  1146. }
  1147. tips = self._safe_tips(data.get('tips'))
  1148. if tips:
  1149. content['tips'] = tips
  1150. pagination = self._build_pagination(raw_meta)
  1151. if pagination:
  1152. content['pagination'] = pagination
  1153. return self._success_result(
  1154. content,
  1155. self._render_table(
  1156. content,
  1157. require_complete=tool_name == 'query_customer_list',
  1158. ),
  1159. meta,
  1160. )
  1161. def _present_customer_payment_followup(self, data, raw_meta, meta):
  1162. if set(data) != {'columns', 'records'}:
  1163. return self._format_error(meta)
  1164. columns = data.get('columns')
  1165. records = data.get('records')
  1166. pagination = self._customer_pagination(raw_meta)
  1167. expected_keys = list(self.PAYMENT_FOLLOWUP_COLUMNS)
  1168. if not isinstance(columns, list) or not isinstance(records, list):
  1169. return self._format_error(meta)
  1170. actual_keys = []
  1171. for column in columns:
  1172. if (
  1173. not isinstance(column, dict)
  1174. or set(column) != {'key', 'name'}
  1175. or not isinstance(column.get('key'), str)
  1176. or not isinstance(column.get('name'), str)
  1177. or not column.get('name').strip()
  1178. ):
  1179. return self._format_error(meta)
  1180. actual_keys.append(column['key'])
  1181. if actual_keys != expected_keys or pagination is None:
  1182. return self._format_error(meta)
  1183. amount_keys = {
  1184. 'billed_unverified_amount', 'unbilled_amount',
  1185. 'overdue_unpaid_amount', 'billed_unverified_amount_cny',
  1186. 'unbilled_amount_cny', 'overdue_unpaid_amount_cny',
  1187. 'receipt_unverified_amount', 'current_balance',
  1188. 'credit_limit', 'bad_debt_total',
  1189. }
  1190. text_keys = {'customer_name', 'settlement_currency', 'contract_status'}
  1191. rows = []
  1192. for record in records:
  1193. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1194. return self._format_error(meta)
  1195. row = []
  1196. for key in expected_keys:
  1197. value = record[key]
  1198. if key in amount_keys:
  1199. if (
  1200. isinstance(value, bool)
  1201. or not isinstance(value, (int, float))
  1202. or not math.isfinite(float(value))
  1203. ):
  1204. return self._format_error(meta)
  1205. elif key in text_keys:
  1206. if not isinstance(value, str):
  1207. return self._format_error(meta)
  1208. else:
  1209. value = self._payment_followup_monthly_summaries(value)
  1210. if value is None:
  1211. return self._format_error(meta)
  1212. row.append(value)
  1213. rows.append(row)
  1214. headers = [
  1215. {'label': self.PAYMENT_FOLLOWUP_COLUMNS[key]}
  1216. for key in expected_keys
  1217. ]
  1218. content = {
  1219. 'headers': headers,
  1220. 'rows': rows,
  1221. 'pagination': pagination,
  1222. 'display_rules': {
  1223. 'mode': 'complete',
  1224. 'allow_summary': False,
  1225. 'allow_omit_records': False,
  1226. 'allow_omit_empty_fields': False,
  1227. 'allow_rename_fields': False,
  1228. 'preserve_record_order': True,
  1229. 'required_field_count': len(headers),
  1230. 'returned_record_count': len(rows),
  1231. 'required_value_count': len(headers) * len(rows),
  1232. 'instruction': '最终回复必须逐条展示全部客户、全部字段和全部未回款月份汇总',
  1233. },
  1234. }
  1235. return self._success_result(
  1236. content,
  1237. self._render_table(content, require_complete=True),
  1238. meta,
  1239. )
  1240. def _payment_followup_monthly_summaries(self, summaries):
  1241. if not isinstance(summaries, list):
  1242. return None
  1243. expected = set(self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS)
  1244. translated = []
  1245. for summary in summaries:
  1246. if not isinstance(summary, dict) or set(summary) != expected:
  1247. return None
  1248. amount = summary.get('unverified_amount')
  1249. if (
  1250. isinstance(amount, bool)
  1251. or not isinstance(amount, (int, float))
  1252. or not math.isfinite(float(amount))
  1253. ):
  1254. return None
  1255. if (
  1256. not isinstance(summary.get('receivable_month'), str)
  1257. or not isinstance(summary.get('is_overdue'), bool)
  1258. ):
  1259. return None
  1260. item = {}
  1261. for key, label in self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS.items():
  1262. value = summary[key]
  1263. item[label] = value
  1264. translated.append(item)
  1265. return translated
  1266. def _present_customer_unverified_bill_details(self, data, raw_meta, meta):
  1267. if set(data) != {'columns', 'records'}:
  1268. return self._format_error(meta)
  1269. columns = data.get('columns')
  1270. records = data.get('records')
  1271. pagination = self._customer_pagination(raw_meta)
  1272. expected_keys = list(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1273. if not isinstance(columns, list) or not isinstance(records, list):
  1274. return self._format_error(meta)
  1275. actual_keys = []
  1276. for column in columns:
  1277. if (
  1278. not isinstance(column, dict)
  1279. or set(column) != {'key', 'name'}
  1280. or not isinstance(column.get('key'), str)
  1281. or not isinstance(column.get('name'), str)
  1282. or not column.get('name').strip()
  1283. ):
  1284. return self._format_error(meta)
  1285. actual_keys.append(column['key'])
  1286. if actual_keys != expected_keys or pagination is None:
  1287. return self._format_error(meta)
  1288. translated = self._payment_followup_details(records)
  1289. if translated is None:
  1290. return self._format_error(meta)
  1291. headers = [
  1292. {'label': self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS[key]}
  1293. for key in expected_keys
  1294. ]
  1295. rows = [[item[header['label']] for header in headers] for item in translated]
  1296. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1297. return self._success_result(content, self._render_table(content), meta)
  1298. def _payment_followup_details(self, details):
  1299. expected = set(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1300. translated = []
  1301. for detail in details:
  1302. if not isinstance(detail, dict) or set(detail) != expected:
  1303. return None
  1304. amount = detail.get('unverified_amount')
  1305. if (
  1306. isinstance(amount, bool)
  1307. or not isinstance(amount, (int, float))
  1308. or not math.isfinite(float(amount))
  1309. ):
  1310. return None
  1311. item = {}
  1312. for key, label in self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS.items():
  1313. value = detail[key]
  1314. if key != 'unverified_amount' and not isinstance(value, str):
  1315. return None
  1316. item[label] = value
  1317. translated.append(item)
  1318. return translated
  1319. def _present_customer_payment_records(self, data, raw_meta, meta):
  1320. if set(data) != {'columns', 'records'}:
  1321. return self._format_error(meta)
  1322. columns = data.get('columns')
  1323. records = data.get('records')
  1324. pagination = self._customer_pagination(raw_meta)
  1325. expected_keys = list(self.PAYMENT_RECORD_COLUMNS)
  1326. if not isinstance(columns, list) or not isinstance(records, list):
  1327. return self._format_error(meta)
  1328. actual_keys = []
  1329. for column in columns:
  1330. if (
  1331. not isinstance(column, dict)
  1332. or set(column) != {'key', 'name'}
  1333. or not isinstance(column.get('key'), str)
  1334. or not isinstance(column.get('name'), str)
  1335. or not column.get('name').strip()
  1336. ):
  1337. return self._format_error(meta)
  1338. actual_keys.append(column['key'])
  1339. if actual_keys != expected_keys or pagination is None:
  1340. return self._format_error(meta)
  1341. amount_keys = {
  1342. 'original_received_amount', 'actual_received_amount',
  1343. 'verified_amount', 'unverified_amount',
  1344. }
  1345. rows = []
  1346. for record in records:
  1347. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1348. return self._format_error(meta)
  1349. row = []
  1350. for key in expected_keys:
  1351. value = record[key]
  1352. if key in amount_keys:
  1353. if (
  1354. isinstance(value, bool)
  1355. or not isinstance(value, (int, float))
  1356. or not math.isfinite(float(value))
  1357. ):
  1358. return self._format_error(meta)
  1359. elif not isinstance(value, str):
  1360. return self._format_error(meta)
  1361. row.append(value)
  1362. rows.append(row)
  1363. headers = [
  1364. {'label': self.PAYMENT_RECORD_COLUMNS[key]}
  1365. for key in expected_keys
  1366. ]
  1367. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1368. return self._success_result(content, self._render_table(content), meta)
  1369. def _present_order_receivable_cost_details(self, data, raw_meta, meta):
  1370. if set(data) != {'summary', 'columns', 'records'}:
  1371. return self._format_error(meta)
  1372. columns = data.get('columns')
  1373. records = data.get('records')
  1374. summary = data.get('summary')
  1375. pagination = self._customer_pagination(raw_meta)
  1376. expected_keys = list(self.RECEIVABLE_COST_COLUMNS)
  1377. expected_summary = list(self.RECEIVABLE_COST_SUMMARY)
  1378. if (
  1379. not isinstance(columns, list)
  1380. or not isinstance(records, list)
  1381. or not isinstance(summary, dict)
  1382. or set(summary) != set(expected_summary)
  1383. ):
  1384. return self._format_error(meta)
  1385. actual_keys = []
  1386. for column in columns:
  1387. if (
  1388. not isinstance(column, dict)
  1389. or set(column) != {'key', 'name'}
  1390. or not isinstance(column.get('key'), str)
  1391. or not isinstance(column.get('name'), str)
  1392. or not column.get('name').strip()
  1393. ):
  1394. return self._format_error(meta)
  1395. actual_keys.append(column['key'])
  1396. if actual_keys != expected_keys or pagination is None:
  1397. return self._format_error(meta)
  1398. summary_row = []
  1399. for key in expected_summary:
  1400. value = summary[key]
  1401. if (
  1402. isinstance(value, bool)
  1403. or not isinstance(value, (int, float))
  1404. or not math.isfinite(float(value))
  1405. ):
  1406. return self._format_error(meta)
  1407. summary_row.append(value)
  1408. numeric_keys = {
  1409. 'charge_weight', 'unit_price', 'receivable_original_amount',
  1410. 'receivable_amount_cny', 'settlement_amount_cny',
  1411. }
  1412. rows = []
  1413. for record in records:
  1414. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1415. return self._format_error(meta)
  1416. row = []
  1417. for key in expected_keys:
  1418. value = record[key]
  1419. if key in numeric_keys:
  1420. if (
  1421. isinstance(value, bool)
  1422. or not isinstance(value, (int, float))
  1423. or not math.isfinite(float(value))
  1424. ):
  1425. return self._format_error(meta)
  1426. elif not isinstance(value, str):
  1427. return self._format_error(meta)
  1428. row.append(value)
  1429. rows.append(row)
  1430. headers = [
  1431. {'label': self.RECEIVABLE_COST_COLUMNS[key]}
  1432. for key in expected_keys
  1433. ]
  1434. content = {
  1435. 'summary': {
  1436. 'headers': [
  1437. {'label': self.RECEIVABLE_COST_SUMMARY[key]}
  1438. for key in expected_summary
  1439. ],
  1440. 'row': summary_row,
  1441. },
  1442. 'headers': headers,
  1443. 'rows': rows,
  1444. 'pagination': pagination,
  1445. }
  1446. return self._success_result(
  1447. content, self._render_order_receivable_cost_details(content), meta
  1448. )
  1449. @classmethod
  1450. def _render_order_receivable_cost_details(cls, content):
  1451. lines = ['订单汇总:']
  1452. summary = content['summary']
  1453. for header, value in zip(summary['headers'], summary['row']):
  1454. lines.append('- {0}: {1}'.format(header['label'], value))
  1455. lines.append('费用明细:')
  1456. lines.append(cls._render_table({
  1457. 'headers': content['headers'],
  1458. 'rows': content['rows'],
  1459. }))
  1460. return '\n'.join(lines)
  1461. def _present_receivable_cost_list(self, data, raw_meta, meta):
  1462. if set(data) != {'columns', 'records'}:
  1463. return self._format_error(meta)
  1464. columns = data.get('columns')
  1465. records = data.get('records')
  1466. pagination = self._customer_pagination(raw_meta)
  1467. expected_keys = list(self.RECEIVABLE_LIST_COLUMNS)
  1468. if (
  1469. not isinstance(columns, list)
  1470. or not isinstance(records, list)
  1471. or len(columns) != len(expected_keys)
  1472. or pagination is None
  1473. ):
  1474. return self._format_error(meta)
  1475. for column, key in zip(columns, expected_keys):
  1476. if column != {
  1477. 'key': key,
  1478. 'name': self.RECEIVABLE_LIST_COLUMNS[key],
  1479. }:
  1480. return self._format_error(meta)
  1481. amount_keys = {
  1482. 'original_amount', 'total_amount', 'billed_amount', 'unbilled_amount',
  1483. }
  1484. rows = []
  1485. for record in records:
  1486. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1487. return self._format_error(meta)
  1488. row = []
  1489. for key in expected_keys:
  1490. value = record[key]
  1491. if key in amount_keys:
  1492. if not self._valid_amount_cell(value):
  1493. return self._format_error(meta)
  1494. elif not isinstance(value, str):
  1495. return self._format_error(meta)
  1496. row.append(value)
  1497. rows.append(row)
  1498. headers = [
  1499. {'label': self.RECEIVABLE_LIST_COLUMNS[key]}
  1500. for key in expected_keys
  1501. ]
  1502. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1503. return self._success_result(content, self._render_table(content), meta)
  1504. def _present_payable_cost_list(self, data, raw_meta, meta):
  1505. if set(data) != {'business_type', 'company_currency', 'columns', 'records'}:
  1506. return self._format_error(meta)
  1507. business_type = data.get('business_type')
  1508. company_currency = data.get('company_currency')
  1509. if (
  1510. isinstance(business_type, bool)
  1511. or not isinstance(business_type, int)
  1512. or business_type not in self.PAYABLE_COST_COLUMNS
  1513. or not isinstance(company_currency, str)
  1514. or not company_currency.strip()
  1515. ):
  1516. return self._format_error(meta)
  1517. pagination = self._customer_pagination(raw_meta)
  1518. columns = data.get('columns')
  1519. records = data.get('records')
  1520. expected = list(self.PAYABLE_COST_COLUMNS[business_type])
  1521. if business_type == 2:
  1522. expected = [
  1523. (key, name.replace('%s', company_currency.strip().upper()))
  1524. for key, name in expected
  1525. ]
  1526. if (
  1527. not isinstance(columns, list)
  1528. or not isinstance(records, list)
  1529. or len(columns) != len(expected)
  1530. or pagination is None
  1531. ):
  1532. return self._format_error(meta)
  1533. for column, (key, name) in zip(columns, expected):
  1534. if column != {'key': key, 'name': name}:
  1535. return self._format_error(meta)
  1536. rows = []
  1537. expected_keys = [key for key, _ in expected]
  1538. for record in records:
  1539. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1540. return self._format_error(meta)
  1541. row = []
  1542. for key in expected_keys:
  1543. value = record[key]
  1544. if key in self.PAYABLE_AMOUNT_KEYS:
  1545. if (
  1546. isinstance(value, bool)
  1547. or not isinstance(value, (int, float))
  1548. or not math.isfinite(float(value))
  1549. ):
  1550. return self._format_error(meta)
  1551. elif not isinstance(value, str):
  1552. return self._format_error(meta)
  1553. row.append(value)
  1554. rows.append(row)
  1555. headers = [{'label': name} for _, name in expected]
  1556. content = {
  1557. 'business_type': business_type,
  1558. 'headers': headers,
  1559. 'rows': rows,
  1560. 'pagination': pagination,
  1561. }
  1562. return self._success_result(content, self._render_table(content), meta)
  1563. def _present_destination_trailer_list(self, data, raw_meta, meta):
  1564. if set(data) != {'trailer_stage', 'columns', 'records'}:
  1565. return self._format_error(meta)
  1566. trailer_stage = data.get('trailer_stage')
  1567. if trailer_stage == 'DO单制作':
  1568. expected = list(self.DESTINATION_TRAILER_COLUMNS['do'])
  1569. elif trailer_stage in self.DESTINATION_TRAILER_PROGRESS_STAGES:
  1570. expected = list(self.DESTINATION_TRAILER_COLUMNS['progress'])
  1571. else:
  1572. return self._format_error(meta)
  1573. pagination = self._customer_pagination(raw_meta)
  1574. columns = data.get('columns')
  1575. records = data.get('records')
  1576. if (
  1577. not isinstance(columns, list)
  1578. or not isinstance(records, list)
  1579. or len(columns) != len(expected)
  1580. or pagination is None
  1581. ):
  1582. return self._format_error(meta)
  1583. for column, (key, name) in zip(columns, expected):
  1584. if column != {'key': key, 'name': name}:
  1585. return self._format_error(meta)
  1586. rows = []
  1587. expected_keys = [key for key, _ in expected]
  1588. for record in records:
  1589. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1590. return self._format_error(meta)
  1591. row = []
  1592. for key in expected_keys:
  1593. value = record[key]
  1594. if key in self.DESTINATION_TRAILER_FILE_KEYS:
  1595. if value != '' and not self._valid_http_url(value):
  1596. return self._format_error(meta)
  1597. elif not isinstance(value, str):
  1598. return self._format_error(meta)
  1599. row.append(value)
  1600. rows.append(row)
  1601. headers = [{'label': name} for _, name in expected]
  1602. content = {
  1603. 'trailer_stage': trailer_stage,
  1604. 'headers': headers,
  1605. 'rows': rows,
  1606. 'pagination': pagination,
  1607. }
  1608. return self._success_result(content, self._render_table(content), meta)
  1609. def _present_order_abnormal_list(self, data, raw_meta, meta):
  1610. if set(data) != {'abnormal_status', 'columns', 'records'}:
  1611. return self._format_error(meta)
  1612. abnormal_status = data.get('abnormal_status')
  1613. if abnormal_status not in self.ORDER_ABNORMAL_STATUSES:
  1614. return self._format_error(meta)
  1615. expected = list(self.ORDER_ABNORMAL_COLUMNS)
  1616. pagination = self._customer_pagination(raw_meta)
  1617. columns = data.get('columns')
  1618. records = data.get('records')
  1619. if (
  1620. not isinstance(columns, list)
  1621. or not isinstance(records, list)
  1622. or len(columns) != len(expected)
  1623. or pagination is None
  1624. ):
  1625. return self._format_error(meta)
  1626. for column, (key, name) in zip(columns, expected):
  1627. if column != {'key': key, 'name': name}:
  1628. return self._format_error(meta)
  1629. rows = []
  1630. expected_keys = [key for key, _ in expected]
  1631. for record in records:
  1632. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1633. return self._format_error(meta)
  1634. row = []
  1635. for key in expected_keys:
  1636. value = record[key]
  1637. if not isinstance(value, str):
  1638. return self._format_error(meta)
  1639. row.append(value)
  1640. rows.append(row)
  1641. headers = [{'label': name} for _, name in expected]
  1642. content = {
  1643. 'abnormal_status': abnormal_status,
  1644. 'headers': headers,
  1645. 'rows': rows,
  1646. 'pagination': pagination,
  1647. }
  1648. return self._success_result(content, self._render_table(content), meta)
  1649. @staticmethod
  1650. def _valid_amount_cell(value):
  1651. if not isinstance(value, dict) or set(value) != {'amount', 'currency'}:
  1652. return False
  1653. amount = value.get('amount')
  1654. return (
  1655. not isinstance(amount, bool)
  1656. and isinstance(amount, (int, float))
  1657. and math.isfinite(float(amount))
  1658. and isinstance(value.get('currency'), str)
  1659. )
  1660. def _present_receivable_cost_filter_options(self, data, raw_meta, meta):
  1661. if set(data) != {'records'}:
  1662. return self._format_error(meta)
  1663. records = data.get('records')
  1664. pagination = self._customer_pagination(raw_meta)
  1665. if not isinstance(records, list) or pagination is None:
  1666. return self._format_error(meta)
  1667. rows = []
  1668. for record in records:
  1669. if not isinstance(record, dict) or set(record) != {
  1670. 'value', 'label', 'code',
  1671. }:
  1672. return self._format_error(meta)
  1673. value = record.get('value')
  1674. label = record.get('label')
  1675. code = record.get('code')
  1676. if (
  1677. isinstance(value, bool) or not isinstance(value, int)
  1678. or not isinstance(label, str) or not label.strip()
  1679. or not isinstance(code, str)
  1680. ):
  1681. return self._format_error(meta)
  1682. rows.append([value, label.strip(), code.strip()])
  1683. content = {
  1684. 'headers': [
  1685. {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
  1686. ],
  1687. 'rows': rows,
  1688. 'pagination': pagination,
  1689. }
  1690. return self._success_result(content, self._render_table(content), meta)
  1691. @staticmethod
  1692. def _customer_billing_modes(value):
  1693. if not isinstance(value, list):
  1694. return None
  1695. result = []
  1696. business_types = set()
  1697. for item in value:
  1698. if not isinstance(item, dict) or set(item) != {
  1699. 'business_type', 'settlement_mode',
  1700. }:
  1701. return None
  1702. business_type = item.get('business_type')
  1703. settlement_mode = item.get('settlement_mode')
  1704. if (
  1705. not isinstance(business_type, str) or not business_type.strip()
  1706. or not isinstance(settlement_mode, str) or not settlement_mode.strip()
  1707. or business_type in business_types
  1708. ):
  1709. return None
  1710. business_types.add(business_type)
  1711. result.append({
  1712. '业务类型': business_type.strip(),
  1713. '结算模式': settlement_mode.strip(),
  1714. })
  1715. return result
  1716. def _present_customer_options(self, data, raw_meta, meta):
  1717. if set(data) != {'records'}:
  1718. return self._format_error(meta)
  1719. records = data.get('records')
  1720. pagination = self._customer_pagination(raw_meta)
  1721. if not isinstance(records, list) or pagination is None:
  1722. return self._format_error(meta)
  1723. rows = []
  1724. for record in records:
  1725. if not isinstance(record, dict) or set(record) != {'value', 'label', 'code'}:
  1726. return self._format_error(meta)
  1727. value = record.get('value')
  1728. label = record.get('label')
  1729. code = record.get('code')
  1730. if (
  1731. isinstance(value, bool) or not isinstance(value, int) or value < 1
  1732. or not isinstance(label, str) or not label.strip()
  1733. or not isinstance(code, str)
  1734. ):
  1735. return self._format_error(meta)
  1736. rows.append([value, label.strip(), code.strip()])
  1737. content = {
  1738. 'headers': [
  1739. {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
  1740. ],
  1741. 'rows': rows,
  1742. 'pagination': pagination,
  1743. }
  1744. return self._success_result(content, self._render_table(content), meta)
  1745. @staticmethod
  1746. def _customer_pagination(raw_meta):
  1747. if not isinstance(raw_meta, dict):
  1748. return None
  1749. required = {'page', 'limit', 'has_more'}
  1750. if (
  1751. not required.issubset(raw_meta)
  1752. or not set(raw_meta).issubset(required | {'request_id'})
  1753. ):
  1754. return None
  1755. page = raw_meta.get('page')
  1756. limit = raw_meta.get('limit')
  1757. has_more = raw_meta.get('has_more')
  1758. if (
  1759. isinstance(page, bool) or not isinstance(page, int)
  1760. or page < 1 or page > 100
  1761. or isinstance(limit, bool) or not isinstance(limit, int)
  1762. or limit < 1 or limit > 100
  1763. or not isinstance(has_more, bool)
  1764. ):
  1765. return None
  1766. return {'page': page, 'limit': limit, 'has_more': has_more}
  1767. def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
  1768. summary = data.get('summary')
  1769. columns = data.get('columns')
  1770. records = data.get('records')
  1771. if not isinstance(summary, dict):
  1772. return self._format_error(meta)
  1773. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  1774. return self._format_error(meta)
  1775. if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
  1776. return self._format_error(meta)
  1777. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  1778. headers = []
  1779. keys = []
  1780. for column in columns:
  1781. if not isinstance(column, dict):
  1782. return self._format_error(meta)
  1783. key = column.get('key')
  1784. definition = allowed_columns.get(key) if isinstance(key, str) else None
  1785. if not isinstance(definition, tuple) or not definition:
  1786. return self._format_error(meta)
  1787. keys.append(key)
  1788. headers.append({'label': definition[0]})
  1789. rows = []
  1790. for record in records:
  1791. if not isinstance(record, dict):
  1792. return self._format_error(meta)
  1793. row = []
  1794. for key in keys:
  1795. value = '' if record.get(key) is None else record.get(key, '')
  1796. if key == 'customs_files':
  1797. if not isinstance(value, list):
  1798. return self._format_error(meta)
  1799. files = []
  1800. for item in value:
  1801. if not isinstance(item, dict):
  1802. return self._format_error(meta)
  1803. files.append({
  1804. '文件名称': item.get('file_name', ''),
  1805. '文件类型': item.get('file_type', ''),
  1806. '文件链接': item.get('file_url', ''),
  1807. })
  1808. value = files
  1809. row.append(value)
  1810. rows.append(row)
  1811. summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
  1812. content = {
  1813. 'summary': {
  1814. 'headers': [
  1815. {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
  1816. for key in summary_keys
  1817. ],
  1818. 'row': [summary.get(key, '') for key in summary_keys],
  1819. },
  1820. 'details': {
  1821. 'headers': headers,
  1822. 'rows': rows,
  1823. },
  1824. }
  1825. tips = self._safe_tips(data.get('tips'))
  1826. if tips:
  1827. content['details']['tips'] = tips
  1828. pagination = self._build_pagination(raw_meta)
  1829. if pagination:
  1830. content['details']['pagination'] = pagination
  1831. return self._success_result(
  1832. content,
  1833. self._render_outbound_detail(content),
  1834. meta,
  1835. )
  1836. @classmethod
  1837. def _render_outbound_detail(cls, content):
  1838. lines = ['排舱汇总:']
  1839. summary = content['summary']
  1840. for header, value in zip(summary['headers'], summary['row']):
  1841. lines.append('- {0}: {1}'.format(header['label'], value))
  1842. lines.append('订单明细:')
  1843. details = content['details']
  1844. lines.append('表头共 {0} 列:'.format(len(details['headers'])))
  1845. for index, header in enumerate(details['headers'], start=1):
  1846. lines.append('{0}. {1}'.format(index, header['label']))
  1847. for index, row in enumerate(details['rows'], start=1):
  1848. lines.append('记录 {0}:'.format(index))
  1849. for header, value in zip(details['headers'], row):
  1850. if isinstance(value, (dict, list)):
  1851. value = json.dumps(value, ensure_ascii=False)
  1852. lines.append('- {0}: {1}'.format(header['label'], value))
  1853. tips = details.get('tips') or []
  1854. if tips:
  1855. lines.append('提示:{0}'.format(';'.join(tips)))
  1856. return '\n'.join(lines)
  1857. def _present_options(self, data, raw_meta, meta):
  1858. records = data.get('records')
  1859. if not isinstance(records, list):
  1860. return self._format_error(meta)
  1861. rows = []
  1862. for record in records:
  1863. if not isinstance(record, dict):
  1864. return self._format_error(meta)
  1865. rows.append([
  1866. record.get('value', ''),
  1867. self._safe_text(record.get('label')),
  1868. self._safe_text(record.get('code')),
  1869. ])
  1870. content = {
  1871. 'headers': [
  1872. {'label': '可传值'},
  1873. {'label': '显示名称'},
  1874. {'label': '业务编码'},
  1875. ],
  1876. 'rows': rows,
  1877. }
  1878. pagination = self._build_pagination(raw_meta)
  1879. if pagination:
  1880. content['pagination'] = pagination
  1881. return self._success_result(content, self._render_table(content), meta)
  1882. def _present_export_submission(self, data, meta):
  1883. expected = {'task_ref', 'status', 'retry_after_seconds'}
  1884. if set(data) != expected:
  1885. return self._format_error(meta)
  1886. task_ref = data.get('task_ref')
  1887. retry_after = data.get('retry_after_seconds')
  1888. if (
  1889. not isinstance(task_ref, str) or not task_ref.strip()
  1890. or data.get('status') != 'queued'
  1891. or isinstance(retry_after, bool)
  1892. or not isinstance(retry_after, int)
  1893. or retry_after <= 0
  1894. ):
  1895. return self._format_error(meta)
  1896. task = {
  1897. 'task_ref': task_ref.strip(),
  1898. 'status': 'queued',
  1899. 'retry_after_seconds': retry_after,
  1900. }
  1901. content = {
  1902. 'message': '导出任务已提交',
  1903. 'task': task,
  1904. }
  1905. text = (
  1906. '导出任务已提交\n'
  1907. '- 任务引用: {0}\n'
  1908. '- 建议 {1} 秒后单独查询任务状态'
  1909. ).format(task['task_ref'], retry_after)
  1910. return self._success_result(content, text, meta)
  1911. def _present_export_task(self, data, meta):
  1912. task_ref = data.get('task_ref')
  1913. status = data.get('status')
  1914. if (
  1915. not isinstance(task_ref, str)
  1916. or not task_ref.strip()
  1917. or status not in ('queued', 'running', 'completed', 'failed')
  1918. ):
  1919. return self._format_error(meta)
  1920. task = {'task_ref': task_ref.strip(), 'status': status}
  1921. if status in ('queued', 'running'):
  1922. if set(data) != {'task_ref', 'status', 'retry_after_seconds'}:
  1923. return self._format_error(meta)
  1924. retry_after = data.get('retry_after_seconds')
  1925. if (
  1926. isinstance(retry_after, bool)
  1927. or not isinstance(retry_after, int)
  1928. or retry_after <= 0
  1929. ):
  1930. return self._format_error(meta)
  1931. task['retry_after_seconds'] = retry_after
  1932. label = '等待中' if status == 'queued' else '生成中'
  1933. content = {'message': '导出任务{0}'.format(label), 'task': task}
  1934. text = (
  1935. '导出任务{0}\n- 任务引用: {1}\n- 建议 {2} 秒后再次查询'
  1936. ).format(label, task['task_ref'], retry_after)
  1937. return self._success_result(content, text, meta)
  1938. if status == 'failed':
  1939. if set(data) != {'task_ref', 'status'}:
  1940. return self._format_error(meta)
  1941. content = {'message': '导出任务失败,请重新提交', 'task': task}
  1942. text = '导出任务失败,请重新提交'
  1943. return self._success_result(content, text, meta)
  1944. if set(data) != {'task_ref', 'status', 'files'}:
  1945. return self._format_error(meta)
  1946. files = data.get('files')
  1947. if not isinstance(files, list) or not files:
  1948. return self._format_error(meta)
  1949. safe_files = []
  1950. for item in files:
  1951. if not isinstance(item, dict) or set(item) != {'label', 'url'}:
  1952. return self._format_error(meta)
  1953. label = item.get('label')
  1954. url = item.get('url')
  1955. if (
  1956. not isinstance(label, str) or not label.strip()
  1957. or not self._valid_http_url(url)
  1958. ):
  1959. return self._format_error(meta)
  1960. safe_files.append({'label': label.strip(), 'url': url.strip()})
  1961. content = {
  1962. 'message': '文件已生成',
  1963. 'task': task,
  1964. 'files': safe_files,
  1965. }
  1966. lines = ['文件已生成']
  1967. for item in safe_files:
  1968. lines.append('- {0}: {1}'.format(item['label'], item['url']))
  1969. return self._success_result(content, '\n'.join(lines), meta)
  1970. def _valid_http_url(self, value):
  1971. if not isinstance(value, str) or not value.strip():
  1972. return False
  1973. if value != value.strip() or '\\' in value or any(
  1974. character.isspace() or ord(character) < 32 or ord(character) == 127
  1975. for character in value
  1976. ):
  1977. return False
  1978. try:
  1979. parsed = urlparse(value)
  1980. port = parsed.port
  1981. return (
  1982. parsed.scheme in ('http', 'https')
  1983. and bool(parsed.hostname)
  1984. and parsed.username is None
  1985. and parsed.password is None
  1986. and (port is None or 0 < port <= 65535)
  1987. )
  1988. except ValueError:
  1989. return False
  1990. def _business_error(self, tool_name, code, raw_message, meta):
  1991. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  1992. logger.warning(
  1993. 'Unknown MCP business error code',
  1994. extra={
  1995. 'request_id': meta.get('request_id', ''),
  1996. 'tool_code': tool_name,
  1997. 'backend_code': code,
  1998. 'response_code': 'MCP_9001',
  1999. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  2000. },
  2001. )
  2002. code = 'MCP_9001'
  2003. if code == 'MCP_1401':
  2004. label = self._find_field_label(tool_name, raw_message)
  2005. message = self._parameter_message(label)
  2006. else:
  2007. message = self.ERROR_MESSAGES[code]
  2008. retryable = code not in self.NON_RETRYABLE_CODES
  2009. return self._error_result(code, message, retryable, meta)
  2010. def _find_field_label(self, tool_name, raw_message):
  2011. message = str(raw_message or '')
  2012. fields = self.FIELD_LABELS.get(tool_name, {})
  2013. for field in sorted(fields, key=len, reverse=True):
  2014. if field in message:
  2015. return fields[field]
  2016. return ''
  2017. @staticmethod
  2018. def _parameter_message(label):
  2019. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  2020. @staticmethod
  2021. def _build_meta(raw_meta):
  2022. if not isinstance(raw_meta, dict):
  2023. return {}
  2024. request_id = raw_meta.get('request_id')
  2025. if not isinstance(request_id, str) or not request_id.strip():
  2026. return {}
  2027. return {'request_id': request_id.strip()}
  2028. @staticmethod
  2029. def _build_pagination(raw_meta):
  2030. if not isinstance(raw_meta, dict):
  2031. return {}
  2032. return {
  2033. key: raw_meta[key]
  2034. for key in ('page', 'limit', 'has_more', 'total')
  2035. if key in raw_meta
  2036. }
  2037. @staticmethod
  2038. def _safe_text(value):
  2039. if value is None:
  2040. return ''
  2041. return str(value).strip()
  2042. @classmethod
  2043. def _safe_tips(cls, value):
  2044. if not isinstance(value, list):
  2045. return []
  2046. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  2047. @classmethod
  2048. def _render_table(cls, content, require_complete=False):
  2049. headers = content.get('headers') or []
  2050. rows = content.get('rows') or []
  2051. lines = []
  2052. if require_complete:
  2053. lines.append('完整客户数据,禁止摘要、合并、隐藏字段或省略空字段。')
  2054. lines.append(
  2055. '本页记录数:{0};每条字段数:{1};应展示字段值总数:{2}。'.format(
  2056. len(rows), len(headers), len(rows) * len(headers)
  2057. )
  2058. )
  2059. summary = cls._safe_text(content.get('summary'))
  2060. if summary:
  2061. lines.append(summary)
  2062. lines.append('表头共 {0} 列:'.format(len(headers)))
  2063. for index, header in enumerate(headers, start=1):
  2064. lines.append('{0}. {1}'.format(index, header['label']))
  2065. for index, row in enumerate(rows, start=1):
  2066. lines.append('记录 {0}:'.format(index))
  2067. for header, value in zip(headers, row):
  2068. if isinstance(value, (dict, list)):
  2069. value = json.dumps(value, ensure_ascii=False)
  2070. lines.append('- {0}: {1}'.format(header['label'], value))
  2071. tips = content.get('tips') or []
  2072. if tips:
  2073. lines.append('提示:{0}'.format(';'.join(tips)))
  2074. if require_complete:
  2075. lines.append(
  2076. '展示完整性校验:已提供{0}条客户的全部{1}个字段。'.format(
  2077. len(rows), len(headers)
  2078. )
  2079. )
  2080. return '\n'.join(lines)
  2081. @staticmethod
  2082. def _success_result(content, text, meta):
  2083. return {
  2084. 'structured_content': content,
  2085. 'text': text,
  2086. 'is_error': False,
  2087. 'meta': meta,
  2088. }
  2089. @staticmethod
  2090. def _error_result(code, message, retryable, meta=None):
  2091. return {
  2092. 'structured_content': {
  2093. 'code': code,
  2094. 'message': message,
  2095. 'retryable': retryable,
  2096. },
  2097. 'text': '{0}: {1}'.format(code, message),
  2098. 'is_error': True,
  2099. 'meta': meta or {},
  2100. }
  2101. @classmethod
  2102. def _format_error(cls, meta=None):
  2103. return cls._error_result(
  2104. 'MCP_9001',
  2105. '工具返回格式异常',
  2106. True,
  2107. meta,
  2108. )