output_presenter.py 146 KB

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