output_presenter.py 117 KB

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