output_presenter.py 134 KB

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