output_presenter.py 88 KB

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