output_presenter.py 76 KB

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