output_presenter.py 83 KB

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