output_presenter.py 112 KB

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