output_presenter.py 83 KB

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