output_presenter.py 90 KB

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