output_presenter.py 110 KB

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