output_presenter.py 124 KB

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