output_presenter.py 88 KB

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