output_presenter.py 146 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472
  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. 'fields': '逐字段预审结果',
  1026. },
  1027. 'query_export_task': {
  1028. 'task_ref': '导出任务引用',
  1029. },
  1030. 'query_freightower_track': {
  1031. 'bl_number': '提单号',
  1032. 'container_code': '柜号',
  1033. },
  1034. }
  1035. ERROR_MESSAGES = {
  1036. 'MCP_1101': '设备配置已失效,请重新生成配置',
  1037. 'MCP_1102': '设备会话已过期,请重新连接',
  1038. 'MCP_1103': '员工账号不可用,请联系管理员',
  1039. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  1040. 'MCP_1201': '工具当前不可用',
  1041. 'MCP_1202': '工具当前不可用',
  1042. 'MCP_1301': '没有权限使用此工具',
  1043. 'MCP_1501': '目标数据不可用',
  1044. 'MCP_1502': '结果过多,请缩小查询范围',
  1045. 'MCP_1601': '没有可导出的数据',
  1046. 'MCP_9001': '工具调用失败,请稍后重试',
  1047. }
  1048. TAX_TRIAL_MESSAGES = frozenset((
  1049. '未找到已审核商品',
  1050. '匹配到多条商品,请核对起运国和目的国',
  1051. '该商品没有应收清关编码,无法试算',
  1052. '关税试算失败,请稍后重试',
  1053. ))
  1054. NON_RETRYABLE_CODES = frozenset((
  1055. 'MCP_1101',
  1056. 'MCP_1102',
  1057. 'MCP_1103',
  1058. 'MCP_1104',
  1059. 'MCP_1201',
  1060. 'MCP_1202',
  1061. 'MCP_1301',
  1062. 'MCP_1401',
  1063. 'MCP_1501',
  1064. 'MCP_1502',
  1065. 'MCP_1601',
  1066. ))
  1067. def handles(self, tool_name):
  1068. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  1069. # Convert a backend envelope into text and structured display data.
  1070. def present(self, tool_name, tool_result):
  1071. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  1072. return self._format_error()
  1073. code = str(tool_result.get('code') or '').strip()
  1074. meta = self._build_meta(tool_result.get('meta'))
  1075. if code not in ('MCP_0000', '0'):
  1076. return self._business_error(
  1077. tool_name,
  1078. code or 'MCP_9001',
  1079. tool_result.get('msg'),
  1080. meta,
  1081. )
  1082. data = tool_result.get('data')
  1083. if not isinstance(data, dict):
  1084. return self._format_error(meta)
  1085. if tool_name in self.GOODS_AI_PRE_AUDIT_TOOLS:
  1086. if not matches_schema(data, RESPONSE_SCHEMAS[tool_name]):
  1087. return self._format_error(meta)
  1088. return self._success_result(
  1089. data, json.dumps(data, ensure_ascii=False, allow_nan=False), meta,
  1090. )
  1091. if tool_name in self.DETAIL_TOOLS:
  1092. return self._present_outbound_detail(
  1093. tool_name,
  1094. data,
  1095. tool_result.get('meta'),
  1096. meta,
  1097. )
  1098. if tool_name in self.ORDER_DETAIL_TOOLS:
  1099. return self._present_order_detail(data, tool_result.get('meta'), meta)
  1100. if tool_name in self.PAYMENT_FOLLOWUP_TOOLS:
  1101. return self._present_customer_payment_followup(
  1102. data, tool_result.get('meta'), meta
  1103. )
  1104. if tool_name in self.PAYMENT_DETAIL_TOOLS:
  1105. return self._present_customer_unverified_bill_details(
  1106. data, tool_result.get('meta'), meta
  1107. )
  1108. if tool_name in self.PAYMENT_RECORD_TOOLS:
  1109. return self._present_customer_payment_records(
  1110. data, tool_result.get('meta'), meta
  1111. )
  1112. if tool_name in self.RECEIVABLE_COST_TOOLS:
  1113. return self._present_order_receivable_cost_details(
  1114. data, tool_result.get('meta'), meta
  1115. )
  1116. if tool_name in self.RECEIVABLE_LIST_TOOLS:
  1117. return self._present_receivable_cost_list(
  1118. data, tool_result.get('meta'), meta
  1119. )
  1120. if tool_name in self.RECEIVABLE_FILTER_TOOLS:
  1121. return self._present_receivable_cost_filter_options(
  1122. data, tool_result.get('meta'), meta
  1123. )
  1124. if tool_name in self.PAYABLE_COST_TOOLS:
  1125. return self._present_payable_cost_list(
  1126. data, tool_result.get('meta'), meta
  1127. )
  1128. if tool_name in self.PAYABLE_FILTER_TOOLS:
  1129. return self._present_receivable_cost_filter_options(
  1130. data, tool_result.get('meta'), meta
  1131. )
  1132. if tool_name in self.DESTINATION_TRAILER_TOOLS:
  1133. return self._present_destination_trailer_list(
  1134. data, tool_result.get('meta'), meta
  1135. )
  1136. if tool_name in self.ARRANGE_TRAILER_TOOLS:
  1137. return self._present_arrange_destination_trailer(data, meta)
  1138. if tool_name in self.ORDER_ABNORMAL_TOOLS:
  1139. return self._present_order_abnormal_list(
  1140. data, tool_result.get('meta'), meta
  1141. )
  1142. if tool_name in self.RECEIVE_VOLUME_TOOLS:
  1143. return self._present_receive_volume_list(
  1144. data, tool_result.get('meta'), meta
  1145. )
  1146. if tool_name in self.PENDING_GOODS_TOOLS:
  1147. return self._present_pending_goods_list(
  1148. data, tool_result.get('meta'), meta
  1149. )
  1150. if tool_name in self.GOODS_AUDIT_OPEN_TOOLS:
  1151. return self._present_open_goods_audit(data, meta)
  1152. if tool_name in self.GOODS_AUDIT_SUBMIT_TOOLS:
  1153. return self._present_submit_goods_audit(data, meta)
  1154. if tool_name in self.GOODS_INFO_TOOLS:
  1155. return self._present_goods_info(
  1156. data, tool_result.get('meta'), meta
  1157. )
  1158. if tool_name in self.GOODS_TAX_TOOLS:
  1159. return self._present_goods_tax(data, meta)
  1160. if tool_name in self.CONTAINER_TIMELINESS_TOOLS:
  1161. return self._present_container_timeliness_list(
  1162. data, tool_result.get('meta'), meta
  1163. )
  1164. if tool_name in self.HEADHAUL_DOCUMENT_TOOLS:
  1165. return self._present_headhaul_document_list(
  1166. data, tool_result.get('meta'), meta
  1167. )
  1168. if tool_name in self.HEADHAUL_PREPARE_TOOLS:
  1169. return self._present_headhaul_prepare(data, meta)
  1170. if tool_name in self.HEADHAUL_SAVE_TOOLS:
  1171. return self._present_headhaul_save(data, meta)
  1172. if tool_name in self.HEADHAUL_DELETE_TOOLS:
  1173. return self._present_headhaul_delete(data, meta)
  1174. if tool_name in self.INBOUND_RECEIPT_TOOLS:
  1175. return self._present_inbound_receipt_templates(data, meta)
  1176. if tool_name in self.FREIGHTOWER_TRACK_TOOLS:
  1177. return self._present_freightower_track(data, meta)
  1178. if tool_name in self.REMOTE_ADDRESS_MAINTAIN_TOOLS:
  1179. return self._present_remote_address_maintain(
  1180. data, tool_result.get('meta'), meta
  1181. )
  1182. if tool_name in self.REMOTE_ADDRESS_SAVE_TOOLS:
  1183. return self._present_remote_address_save(data, meta)
  1184. if tool_name in self.TABLE_TOOLS:
  1185. return self._present_table(
  1186. tool_name,
  1187. data,
  1188. tool_result.get('meta'),
  1189. meta,
  1190. )
  1191. if tool_name in self.OPTION_TOOLS:
  1192. if tool_name == 'list_customer_filter_options':
  1193. return self._present_customer_options(
  1194. data, tool_result.get('meta'), meta
  1195. )
  1196. return self._present_options(data, tool_result.get('meta'), meta)
  1197. if tool_name in self.EXPORT_TOOLS:
  1198. return self._present_export_submission(data, meta)
  1199. if tool_name in self.PAYABLE_EXPORT_TOOLS:
  1200. return self._present_export_submission(data, meta)
  1201. return self._present_export_task(data, meta)
  1202. def _present_order_detail(self, data, raw_meta, meta):
  1203. if set(data) != {'section', 'order_number', 'payload'}:
  1204. return self._format_error(meta)
  1205. section = data.get('section')
  1206. order_number = data.get('order_number')
  1207. payload = data.get('payload')
  1208. if (
  1209. section not in self.ORDER_DETAIL_SECTIONS
  1210. or not isinstance(order_number, str) or not order_number.strip()
  1211. or not isinstance(payload, dict)
  1212. ):
  1213. return self._format_error(meta)
  1214. content = {
  1215. '订单号': order_number.strip(),
  1216. '详情模块': self.ORDER_DETAIL_SECTIONS[section],
  1217. }
  1218. if section == 'all':
  1219. all_content = self._present_order_detail_all(payload)
  1220. if all_content is None:
  1221. return self._format_error(meta)
  1222. content.update(all_content)
  1223. elif section == 'overview':
  1224. expected = {
  1225. 'status_nodes', 'order_info', 'freight_info',
  1226. 'package_summary', 'trader_info',
  1227. }
  1228. if set(payload) != expected or not isinstance(payload['status_nodes'], list):
  1229. return self._format_error(meta)
  1230. nodes = []
  1231. for row in payload['status_nodes']:
  1232. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  1233. if translated is None:
  1234. return self._format_error(meta)
  1235. state = row.get('state')
  1236. time_kind = row.get('time_kind')
  1237. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  1238. return self._format_error(meta)
  1239. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  1240. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  1241. nodes.append(translated)
  1242. content['状态节点'] = nodes
  1243. for raw_key, chinese_key in (
  1244. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  1245. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  1246. ):
  1247. translated = self._translate_exact(
  1248. payload.get(raw_key),
  1249. self.ORDER_DETAIL_FIELDS['overview'][raw_key],
  1250. )
  1251. if translated is None:
  1252. return self._format_error(meta)
  1253. content[chinese_key] = translated
  1254. elif section == 'inbound':
  1255. if set(payload) != {'summary', 'records'}:
  1256. return self._format_error(meta)
  1257. summary = self._translate_exact(
  1258. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  1259. )
  1260. records = self._translate_order_detail_rows(section, payload.get('records'))
  1261. if summary is None or records is None:
  1262. return self._format_error(meta)
  1263. content['入库概况'] = summary
  1264. content['明细'] = records
  1265. pagination = self._order_detail_pagination(raw_meta)
  1266. if pagination is None:
  1267. return self._format_error(meta)
  1268. content['分页'] = pagination
  1269. elif section == 'delivery':
  1270. if set(payload) != {'summary', 'records'}:
  1271. return self._format_error(meta)
  1272. summary = self._translate_exact(
  1273. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  1274. )
  1275. records = self._translate_order_detail_rows(section, payload.get('records'))
  1276. if summary is None or records is None:
  1277. return self._format_error(meta)
  1278. content['派送汇总'] = summary
  1279. content['明细'] = records
  1280. pagination = self._order_detail_pagination(raw_meta)
  1281. if pagination is None:
  1282. return self._format_error(meta)
  1283. content['分页'] = pagination
  1284. else:
  1285. if set(payload) != {'records'}:
  1286. return self._format_error(meta)
  1287. records = self._translate_order_detail_rows(section, payload.get('records'))
  1288. pagination = self._order_detail_pagination(raw_meta)
  1289. if records is None or pagination is None:
  1290. return self._format_error(meta)
  1291. content['明细'] = records
  1292. content['分页'] = pagination
  1293. text = json.dumps(content, ensure_ascii=False, indent=2)
  1294. return self._success_result(content, text, meta)
  1295. def _present_order_detail_all(self, payload):
  1296. expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
  1297. if set(payload) != expected_sections:
  1298. return None
  1299. overview = payload.get('overview')
  1300. if not isinstance(overview, dict) or set(overview) != {
  1301. 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
  1302. } or not isinstance(overview['status_nodes'], list):
  1303. return None
  1304. overview_content = {'状态节点': []}
  1305. for row in overview['status_nodes']:
  1306. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  1307. if translated is None:
  1308. return None
  1309. state = row.get('state')
  1310. time_kind = row.get('time_kind')
  1311. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  1312. return None
  1313. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  1314. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  1315. overview_content['状态节点'].append(translated)
  1316. for raw_key, chinese_key in (
  1317. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  1318. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  1319. ):
  1320. translated = self._translate_exact(
  1321. overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
  1322. )
  1323. if translated is None:
  1324. return None
  1325. overview_content[chinese_key] = translated
  1326. result = {'订单概览': overview_content}
  1327. for section, label in self.ORDER_DETAIL_SECTIONS.items():
  1328. if section in ('overview', 'all'):
  1329. continue
  1330. translated = self._present_order_detail_all_section(section, payload.get(section))
  1331. if translated is None:
  1332. return None
  1333. result[label] = translated
  1334. return result
  1335. def _present_order_detail_all_section(self, section, payload):
  1336. if not isinstance(payload, dict) or 'pagination' not in payload:
  1337. return None
  1338. pagination = self._order_detail_pagination(payload.get('pagination'))
  1339. if pagination is None:
  1340. return None
  1341. if section == 'inbound':
  1342. if set(payload) != {'summary', 'records', 'pagination'}:
  1343. return None
  1344. summary = self._translate_exact(
  1345. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  1346. )
  1347. records = self._translate_order_detail_rows(section, payload.get('records'))
  1348. if summary is None or records is None:
  1349. return None
  1350. return {'入库概况': summary, '明细': records, '分页': pagination}
  1351. if section == 'delivery':
  1352. if set(payload) != {'summary', 'records', 'pagination'}:
  1353. return None
  1354. summary = self._translate_exact(
  1355. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  1356. )
  1357. records = self._translate_order_detail_rows(section, payload.get('records'))
  1358. if summary is None or records is None:
  1359. return None
  1360. return {'派送汇总': summary, '明细': records, '分页': pagination}
  1361. if set(payload) != {'records', 'pagination'}:
  1362. return None
  1363. records = self._translate_order_detail_rows(section, payload.get('records'))
  1364. if records is None:
  1365. return None
  1366. return {'明细': records, '分页': pagination}
  1367. def _translate_order_detail_rows(self, section, records):
  1368. if not isinstance(records, list):
  1369. return None
  1370. mapping = self.ORDER_DETAIL_FIELDS.get(section)
  1371. if not isinstance(mapping, dict):
  1372. return None
  1373. translated_rows = []
  1374. for row in records:
  1375. translated = self._translate_exact(row, mapping)
  1376. if translated is None:
  1377. return None
  1378. if section == 'inbound':
  1379. mode = row.get('weight_mode')
  1380. if mode not in ('single_box', 'total'):
  1381. return None
  1382. translated[
  1383. '单箱入库重量' if mode == 'single_box' else '总重量KG'
  1384. ] = row.get('weight', '')
  1385. translated_rows.append(translated)
  1386. return translated_rows
  1387. @staticmethod
  1388. def _translate_exact(value, mapping):
  1389. if not isinstance(value, dict) or set(value) != set(mapping):
  1390. return None
  1391. result = {}
  1392. for key, label in mapping.items():
  1393. if label is None:
  1394. continue
  1395. item = value.get(key, '')
  1396. if isinstance(item, (dict, list)):
  1397. return None
  1398. result[label] = '' if item is None else item
  1399. return result
  1400. @staticmethod
  1401. def _order_detail_pagination(raw_meta):
  1402. if not isinstance(raw_meta, dict):
  1403. return None
  1404. if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
  1405. return None
  1406. page = raw_meta.get('page')
  1407. limit = raw_meta.get('limit')
  1408. has_more = raw_meta.get('has_more')
  1409. if isinstance(page, bool) or not isinstance(page, int) or page < 1:
  1410. return None
  1411. if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
  1412. return None
  1413. if not isinstance(has_more, bool):
  1414. return None
  1415. return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
  1416. # Map local tool exceptions without exposing internal error details.
  1417. def present_exception(self, tool_name, exception):
  1418. if not self.handles(tool_name):
  1419. return self._format_error()
  1420. message = str(exception or '').strip()
  1421. if isinstance(exception, ValueError):
  1422. label = self._find_field_label(tool_name, message)
  1423. return self._error_result(
  1424. 'MCP_1401',
  1425. self._parameter_message(label),
  1426. False,
  1427. )
  1428. if message == DEVICE_INVALID_MESSAGE:
  1429. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  1430. if message.lower().startswith('tool disabled'):
  1431. return self._error_result('MCP_1202', '工具当前不可用', False)
  1432. return self._error_result(
  1433. 'MCP_9001',
  1434. '工具调用失败,请稍后重试',
  1435. True,
  1436. )
  1437. def _present_table(self, tool_name, data, raw_meta, meta):
  1438. columns = data.get('columns')
  1439. records = data.get('records')
  1440. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  1441. return self._format_error(meta)
  1442. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  1443. if not isinstance(allowed_columns, dict):
  1444. return self._format_error(meta)
  1445. if tool_name == 'query_customer_list':
  1446. expected = list(allowed_columns.keys())
  1447. actual = [
  1448. column.get('key') if isinstance(column, dict) else None
  1449. for column in columns
  1450. ]
  1451. if actual != expected or self._customer_pagination(raw_meta) is None:
  1452. return self._format_error(meta)
  1453. headers = []
  1454. keys = []
  1455. for column in columns:
  1456. if not isinstance(column, dict):
  1457. return self._format_error(meta)
  1458. key = column.get('key')
  1459. label = column.get('name')
  1460. if not isinstance(key, str) or not key.strip():
  1461. return self._format_error(meta)
  1462. if not isinstance(label, str) or not label.strip():
  1463. return self._format_error(meta)
  1464. key = key.strip()
  1465. definition = allowed_columns.get(key)
  1466. if not isinstance(definition, tuple) or not definition:
  1467. return self._format_error(meta)
  1468. keys.append(key)
  1469. header = {'label': definition[0]}
  1470. if len(definition) > 1:
  1471. header['description'] = definition[1]
  1472. headers.append(header)
  1473. rows = []
  1474. for record in records:
  1475. if not isinstance(record, dict):
  1476. return self._format_error(meta)
  1477. if tool_name == 'query_customer_list' and set(record) != set(keys):
  1478. return self._format_error(meta)
  1479. row = []
  1480. for key in keys:
  1481. value = '' if record.get(key) is None else record.get(key, '')
  1482. if tool_name == 'query_customer_list' and key == 'billing_modes':
  1483. value = self._customer_billing_modes(value)
  1484. if value is None:
  1485. return self._format_error(meta)
  1486. elif tool_name == 'query_customer_list' and isinstance(value, (dict, list)):
  1487. return self._format_error(meta)
  1488. row.append(value)
  1489. rows.append(row)
  1490. content = {
  1491. 'summary': self._safe_text(data.get('summary')),
  1492. 'headers': headers,
  1493. 'rows': rows,
  1494. }
  1495. if tool_name == 'query_customer_list':
  1496. content['display_rules'] = {
  1497. 'mode': 'complete',
  1498. 'allow_summary': False,
  1499. 'allow_omit_records': False,
  1500. 'allow_omit_empty_fields': False,
  1501. 'allow_rename_fields': False,
  1502. 'preserve_record_order': True,
  1503. 'required_field_count': len(headers),
  1504. 'returned_record_count': len(rows),
  1505. 'required_value_count': len(headers) * len(rows),
  1506. 'instruction': '最终回复必须逐条展示全部记录及全部17个字段,不得摘要、省略或改写',
  1507. }
  1508. tips = self._safe_tips(data.get('tips'))
  1509. if tips:
  1510. content['tips'] = tips
  1511. pagination = self._build_pagination(raw_meta)
  1512. if pagination:
  1513. content['pagination'] = pagination
  1514. return self._success_result(
  1515. content,
  1516. self._render_table(
  1517. content,
  1518. require_complete=tool_name == 'query_customer_list',
  1519. ),
  1520. meta,
  1521. )
  1522. def _present_remote_address_maintain(self, data, raw_meta, meta):
  1523. required = {
  1524. 'summary', 'mode_text', 'address_no', 'remote_name',
  1525. 'status_text', 'temp_key', 'columns', 'records',
  1526. }
  1527. if not isinstance(data, dict) or not required.issubset(set(data)):
  1528. return self._format_error(meta)
  1529. if set(data) - required - {'tips'}:
  1530. return self._format_error(meta)
  1531. if data.get('mode_text') not in ('新增', '编辑'):
  1532. return self._format_error(meta)
  1533. for key in ('summary', 'address_no', 'remote_name', 'status_text', 'temp_key'):
  1534. if not isinstance(data.get(key), str):
  1535. return self._format_error(meta)
  1536. columns = data.get('columns')
  1537. records = data.get('records')
  1538. expected = list(self.REMOTE_ADDRESS_DETAIL_COLUMNS)
  1539. if not isinstance(columns, list) or len(columns) != len(expected):
  1540. return self._format_error(meta)
  1541. if not isinstance(records, list):
  1542. return self._format_error(meta)
  1543. for index, column in enumerate(columns):
  1544. key, label = expected[index]
  1545. if (
  1546. not isinstance(column, dict)
  1547. or column.get('key') != key
  1548. or column.get('name') != label
  1549. ):
  1550. return self._format_error(meta)
  1551. keys = [item[0] for item in expected]
  1552. rows = []
  1553. for record in records:
  1554. if not isinstance(record, dict) or set(record) != set(keys):
  1555. return self._format_error(meta)
  1556. rows.append(['' if record.get(key) is None else record.get(key) for key in keys])
  1557. headers = [{'label': label} for _, label in expected]
  1558. table = {
  1559. 'summary': self._safe_text(data.get('summary')),
  1560. 'headers': headers,
  1561. 'rows': rows,
  1562. }
  1563. tips = self._safe_tips(data.get('tips'))
  1564. if tips:
  1565. table['tips'] = tips
  1566. content = {
  1567. 'summary': table['summary'],
  1568. 'mode_text': data['mode_text'],
  1569. 'address_no': data['address_no'],
  1570. 'remote_name': data['remote_name'],
  1571. 'status_text': data['status_text'],
  1572. 'headers': headers,
  1573. 'rows': rows,
  1574. }
  1575. if tips:
  1576. content['tips'] = tips
  1577. pagination = self._build_pagination(raw_meta)
  1578. if pagination:
  1579. content['pagination'] = pagination
  1580. return self._success_result(content, self._render_table(table), meta)
  1581. def _present_remote_address_save(self, data, meta):
  1582. required = {'summary', 'mode_text', 'address_no', 'remote_name', 'status_text'}
  1583. if not isinstance(data, dict) or set(data) != required:
  1584. return self._format_error(meta)
  1585. if data.get('mode_text') not in ('新增', '编辑'):
  1586. return self._format_error(meta)
  1587. if data.get('status_text') not in ('启用', '禁用'):
  1588. return self._format_error(meta)
  1589. address_no = data.get('address_no')
  1590. remote_name = data.get('remote_name')
  1591. summary = data.get('summary')
  1592. if (
  1593. not isinstance(address_no, str)
  1594. or not address_no.startswith('PY')
  1595. or not address_no[2:].isdigit()
  1596. or not isinstance(remote_name, str)
  1597. or not remote_name.strip()
  1598. or not isinstance(summary, str)
  1599. or not summary.strip()
  1600. ):
  1601. return self._format_error(meta)
  1602. content = {
  1603. '结果': summary.strip(),
  1604. '操作': data['mode_text'],
  1605. '地址库编号': address_no,
  1606. '地址库名称': remote_name.strip(),
  1607. '状态': data['status_text'],
  1608. }
  1609. return self._success_result(content, summary.strip(), meta)
  1610. @staticmethod
  1611. def _remote_address_save_message(message):
  1612. if message in (
  1613. '地址库名称不能为空',
  1614. '地址库名称过长',
  1615. '状态只能是启用或禁用',
  1616. '地址库编号不正确',
  1617. '地址明细格式不正确',
  1618. '地址库没有详情,请导入',
  1619. '编辑只修改名称和状态,不能同时提交地址明细',
  1620. ):
  1621. return True
  1622. if message.startswith('一次最多保存') and message.endswith('条地址明细'):
  1623. return True
  1624. if (
  1625. message.startswith('第')
  1626. and '条' in message
  1627. and len(message) <= 80
  1628. ):
  1629. return True
  1630. return False
  1631. @staticmethod
  1632. def _fuel_rate_message(message):
  1633. if not message or len(message) > 400:
  1634. return False
  1635. lowered = message.lower()
  1636. if 'sql' in lowered or 'exception' in lowered or '\\' in message:
  1637. return False
  1638. markers = (
  1639. '不正确', '不存在', '不能为空', '只能', '请添加', '请完善',
  1640. '对应多条', '不能大于', '不能同时', '重复', '过多', '未启用',
  1641. '草稿', '失败', '只适用于', '日期', '只新增', '最多新增', '不能修改', '不支持',
  1642. '已启用', '最多启用', '请选择',
  1643. )
  1644. return any(marker in message for marker in markers)
  1645. def _present_customer_payment_followup(self, data, raw_meta, meta):
  1646. if set(data) != {'columns', 'records'}:
  1647. return self._format_error(meta)
  1648. columns = data.get('columns')
  1649. records = data.get('records')
  1650. pagination = self._customer_pagination(raw_meta)
  1651. expected_keys = list(self.PAYMENT_FOLLOWUP_COLUMNS)
  1652. if not isinstance(columns, list) or not isinstance(records, list):
  1653. return self._format_error(meta)
  1654. actual_keys = []
  1655. for column in columns:
  1656. if (
  1657. not isinstance(column, dict)
  1658. or set(column) != {'key', 'name'}
  1659. or not isinstance(column.get('key'), str)
  1660. or not isinstance(column.get('name'), str)
  1661. or not column.get('name').strip()
  1662. ):
  1663. return self._format_error(meta)
  1664. actual_keys.append(column['key'])
  1665. if actual_keys != expected_keys or pagination is None:
  1666. return self._format_error(meta)
  1667. amount_keys = {
  1668. 'billed_unverified_amount', 'unbilled_amount',
  1669. 'overdue_unpaid_amount', 'billed_unverified_amount_cny',
  1670. 'unbilled_amount_cny', 'overdue_unpaid_amount_cny',
  1671. 'receipt_unverified_amount', 'current_balance',
  1672. 'credit_limit', 'bad_debt_total',
  1673. }
  1674. text_keys = {'customer_name', 'settlement_currency', 'contract_status'}
  1675. rows = []
  1676. for record in records:
  1677. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1678. return self._format_error(meta)
  1679. row = []
  1680. for key in expected_keys:
  1681. value = record[key]
  1682. if key in amount_keys:
  1683. if (
  1684. isinstance(value, bool)
  1685. or not isinstance(value, (int, float))
  1686. or not math.isfinite(float(value))
  1687. ):
  1688. return self._format_error(meta)
  1689. elif key in text_keys:
  1690. if not isinstance(value, str):
  1691. return self._format_error(meta)
  1692. else:
  1693. value = self._payment_followup_monthly_summaries(value)
  1694. if value is None:
  1695. return self._format_error(meta)
  1696. row.append(value)
  1697. rows.append(row)
  1698. headers = [
  1699. {'label': self.PAYMENT_FOLLOWUP_COLUMNS[key]}
  1700. for key in expected_keys
  1701. ]
  1702. content = {
  1703. 'headers': headers,
  1704. 'rows': rows,
  1705. 'pagination': pagination,
  1706. 'display_rules': {
  1707. 'mode': 'complete',
  1708. 'allow_summary': False,
  1709. 'allow_omit_records': False,
  1710. 'allow_omit_empty_fields': False,
  1711. 'allow_rename_fields': False,
  1712. 'preserve_record_order': True,
  1713. 'required_field_count': len(headers),
  1714. 'returned_record_count': len(rows),
  1715. 'required_value_count': len(headers) * len(rows),
  1716. 'instruction': '最终回复必须逐条展示全部客户、全部字段和全部未回款月份汇总',
  1717. },
  1718. }
  1719. return self._success_result(
  1720. content,
  1721. self._render_table(content, require_complete=True),
  1722. meta,
  1723. )
  1724. def _payment_followup_monthly_summaries(self, summaries):
  1725. if not isinstance(summaries, list):
  1726. return None
  1727. expected = set(self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS)
  1728. translated = []
  1729. for summary in summaries:
  1730. if not isinstance(summary, dict) or set(summary) != expected:
  1731. return None
  1732. amount = summary.get('unverified_amount')
  1733. if (
  1734. isinstance(amount, bool)
  1735. or not isinstance(amount, (int, float))
  1736. or not math.isfinite(float(amount))
  1737. ):
  1738. return None
  1739. if (
  1740. not isinstance(summary.get('receivable_month'), str)
  1741. or not isinstance(summary.get('is_overdue'), bool)
  1742. ):
  1743. return None
  1744. item = {}
  1745. for key, label in self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS.items():
  1746. value = summary[key]
  1747. item[label] = value
  1748. translated.append(item)
  1749. return translated
  1750. def _present_customer_unverified_bill_details(self, data, raw_meta, meta):
  1751. if set(data) != {'columns', 'records'}:
  1752. return self._format_error(meta)
  1753. columns = data.get('columns')
  1754. records = data.get('records')
  1755. pagination = self._customer_pagination(raw_meta)
  1756. expected_keys = list(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1757. if not isinstance(columns, list) or not isinstance(records, list):
  1758. return self._format_error(meta)
  1759. actual_keys = []
  1760. for column in columns:
  1761. if (
  1762. not isinstance(column, dict)
  1763. or set(column) != {'key', 'name'}
  1764. or not isinstance(column.get('key'), str)
  1765. or not isinstance(column.get('name'), str)
  1766. or not column.get('name').strip()
  1767. ):
  1768. return self._format_error(meta)
  1769. actual_keys.append(column['key'])
  1770. if actual_keys != expected_keys or pagination is None:
  1771. return self._format_error(meta)
  1772. translated = self._payment_followup_details(records)
  1773. if translated is None:
  1774. return self._format_error(meta)
  1775. headers = [
  1776. {'label': self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS[key]}
  1777. for key in expected_keys
  1778. ]
  1779. rows = [[item[header['label']] for header in headers] for item in translated]
  1780. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1781. return self._success_result(content, self._render_table(content), meta)
  1782. def _payment_followup_details(self, details):
  1783. expected = set(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
  1784. translated = []
  1785. for detail in details:
  1786. if not isinstance(detail, dict) or set(detail) != expected:
  1787. return None
  1788. amount = detail.get('unverified_amount')
  1789. if (
  1790. isinstance(amount, bool)
  1791. or not isinstance(amount, (int, float))
  1792. or not math.isfinite(float(amount))
  1793. ):
  1794. return None
  1795. item = {}
  1796. for key, label in self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS.items():
  1797. value = detail[key]
  1798. if key != 'unverified_amount' and not isinstance(value, str):
  1799. return None
  1800. item[label] = value
  1801. translated.append(item)
  1802. return translated
  1803. def _present_customer_payment_records(self, data, raw_meta, meta):
  1804. if set(data) != {'columns', 'records'}:
  1805. return self._format_error(meta)
  1806. columns = data.get('columns')
  1807. records = data.get('records')
  1808. pagination = self._customer_pagination(raw_meta)
  1809. expected_keys = list(self.PAYMENT_RECORD_COLUMNS)
  1810. if not isinstance(columns, list) or not isinstance(records, list):
  1811. return self._format_error(meta)
  1812. actual_keys = []
  1813. for column in columns:
  1814. if (
  1815. not isinstance(column, dict)
  1816. or set(column) != {'key', 'name'}
  1817. or not isinstance(column.get('key'), str)
  1818. or not isinstance(column.get('name'), str)
  1819. or not column.get('name').strip()
  1820. ):
  1821. return self._format_error(meta)
  1822. actual_keys.append(column['key'])
  1823. if actual_keys != expected_keys or pagination is None:
  1824. return self._format_error(meta)
  1825. amount_keys = {
  1826. 'original_received_amount', 'actual_received_amount',
  1827. 'verified_amount', 'unverified_amount',
  1828. }
  1829. rows = []
  1830. for record in records:
  1831. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1832. return self._format_error(meta)
  1833. row = []
  1834. for key in expected_keys:
  1835. value = record[key]
  1836. if key in amount_keys:
  1837. if (
  1838. isinstance(value, bool)
  1839. or not isinstance(value, (int, float))
  1840. or not math.isfinite(float(value))
  1841. ):
  1842. return self._format_error(meta)
  1843. elif not isinstance(value, str):
  1844. return self._format_error(meta)
  1845. row.append(value)
  1846. rows.append(row)
  1847. headers = [
  1848. {'label': self.PAYMENT_RECORD_COLUMNS[key]}
  1849. for key in expected_keys
  1850. ]
  1851. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1852. return self._success_result(content, self._render_table(content), meta)
  1853. def _present_order_receivable_cost_details(self, data, raw_meta, meta):
  1854. if set(data) != {'summary', 'columns', 'records'}:
  1855. return self._format_error(meta)
  1856. columns = data.get('columns')
  1857. records = data.get('records')
  1858. summary = data.get('summary')
  1859. pagination = self._customer_pagination(raw_meta)
  1860. expected_keys = list(self.RECEIVABLE_COST_COLUMNS)
  1861. expected_summary = list(self.RECEIVABLE_COST_SUMMARY)
  1862. if (
  1863. not isinstance(columns, list)
  1864. or not isinstance(records, list)
  1865. or not isinstance(summary, dict)
  1866. or set(summary) != set(expected_summary)
  1867. ):
  1868. return self._format_error(meta)
  1869. actual_keys = []
  1870. for column in columns:
  1871. if (
  1872. not isinstance(column, dict)
  1873. or set(column) != {'key', 'name'}
  1874. or not isinstance(column.get('key'), str)
  1875. or not isinstance(column.get('name'), str)
  1876. or not column.get('name').strip()
  1877. ):
  1878. return self._format_error(meta)
  1879. actual_keys.append(column['key'])
  1880. if actual_keys != expected_keys or pagination is None:
  1881. return self._format_error(meta)
  1882. summary_row = []
  1883. for key in expected_summary:
  1884. value = summary[key]
  1885. if (
  1886. isinstance(value, bool)
  1887. or not isinstance(value, (int, float))
  1888. or not math.isfinite(float(value))
  1889. ):
  1890. return self._format_error(meta)
  1891. summary_row.append(value)
  1892. numeric_keys = {
  1893. 'charge_weight', 'unit_price', 'receivable_original_amount',
  1894. 'receivable_amount_cny', 'settlement_amount_cny',
  1895. }
  1896. rows = []
  1897. for record in records:
  1898. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1899. return self._format_error(meta)
  1900. row = []
  1901. for key in expected_keys:
  1902. value = record[key]
  1903. if key in numeric_keys:
  1904. if (
  1905. isinstance(value, bool)
  1906. or not isinstance(value, (int, float))
  1907. or not math.isfinite(float(value))
  1908. ):
  1909. return self._format_error(meta)
  1910. elif not isinstance(value, str):
  1911. return self._format_error(meta)
  1912. row.append(value)
  1913. rows.append(row)
  1914. headers = [
  1915. {'label': self.RECEIVABLE_COST_COLUMNS[key]}
  1916. for key in expected_keys
  1917. ]
  1918. content = {
  1919. 'summary': {
  1920. 'headers': [
  1921. {'label': self.RECEIVABLE_COST_SUMMARY[key]}
  1922. for key in expected_summary
  1923. ],
  1924. 'row': summary_row,
  1925. },
  1926. 'headers': headers,
  1927. 'rows': rows,
  1928. 'pagination': pagination,
  1929. }
  1930. return self._success_result(
  1931. content, self._render_order_receivable_cost_details(content), meta
  1932. )
  1933. @classmethod
  1934. def _render_order_receivable_cost_details(cls, content):
  1935. lines = ['订单汇总:']
  1936. summary = content['summary']
  1937. for header, value in zip(summary['headers'], summary['row']):
  1938. lines.append('- {0}: {1}'.format(header['label'], value))
  1939. lines.append('费用明细:')
  1940. lines.append(cls._render_table({
  1941. 'headers': content['headers'],
  1942. 'rows': content['rows'],
  1943. }))
  1944. return '\n'.join(lines)
  1945. def _present_receivable_cost_list(self, data, raw_meta, meta):
  1946. if set(data) != {'columns', 'records'}:
  1947. return self._format_error(meta)
  1948. columns = data.get('columns')
  1949. records = data.get('records')
  1950. pagination = self._customer_pagination(raw_meta)
  1951. expected_keys = list(self.RECEIVABLE_LIST_COLUMNS)
  1952. if (
  1953. not isinstance(columns, list)
  1954. or not isinstance(records, list)
  1955. or len(columns) != len(expected_keys)
  1956. or pagination is None
  1957. ):
  1958. return self._format_error(meta)
  1959. for column, key in zip(columns, expected_keys):
  1960. if column != {
  1961. 'key': key,
  1962. 'name': self.RECEIVABLE_LIST_COLUMNS[key],
  1963. }:
  1964. return self._format_error(meta)
  1965. amount_keys = {
  1966. 'original_amount', 'total_amount', 'billed_amount', 'unbilled_amount',
  1967. }
  1968. rows = []
  1969. for record in records:
  1970. if not isinstance(record, dict) or set(record) != set(expected_keys):
  1971. return self._format_error(meta)
  1972. row = []
  1973. for key in expected_keys:
  1974. value = record[key]
  1975. if key in amount_keys:
  1976. if not self._valid_amount_cell(value):
  1977. return self._format_error(meta)
  1978. elif not isinstance(value, str):
  1979. return self._format_error(meta)
  1980. row.append(value)
  1981. rows.append(row)
  1982. headers = [
  1983. {'label': self.RECEIVABLE_LIST_COLUMNS[key]}
  1984. for key in expected_keys
  1985. ]
  1986. content = {'headers': headers, 'rows': rows, 'pagination': pagination}
  1987. return self._success_result(content, self._render_table(content), meta)
  1988. def _present_payable_cost_list(self, data, raw_meta, meta):
  1989. if set(data) != {'business_type', 'company_currency', 'columns', 'records'}:
  1990. return self._format_error(meta)
  1991. business_type = data.get('business_type')
  1992. company_currency = data.get('company_currency')
  1993. if (
  1994. isinstance(business_type, bool)
  1995. or not isinstance(business_type, int)
  1996. or business_type not in self.PAYABLE_COST_COLUMNS
  1997. or not isinstance(company_currency, str)
  1998. or not company_currency.strip()
  1999. ):
  2000. return self._format_error(meta)
  2001. pagination = self._customer_pagination(raw_meta)
  2002. columns = data.get('columns')
  2003. records = data.get('records')
  2004. expected = list(self.PAYABLE_COST_COLUMNS[business_type])
  2005. if business_type == 2:
  2006. expected = [
  2007. (key, name.replace('%s', company_currency.strip().upper()))
  2008. for key, name in expected
  2009. ]
  2010. if (
  2011. not isinstance(columns, list)
  2012. or not isinstance(records, list)
  2013. or len(columns) != len(expected)
  2014. or pagination is None
  2015. ):
  2016. return self._format_error(meta)
  2017. for column, (key, name) in zip(columns, expected):
  2018. if column != {'key': key, 'name': name}:
  2019. return self._format_error(meta)
  2020. rows = []
  2021. expected_keys = [key for key, _ in expected]
  2022. for record in records:
  2023. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2024. return self._format_error(meta)
  2025. row = []
  2026. for key in expected_keys:
  2027. value = record[key]
  2028. if key in self.PAYABLE_AMOUNT_KEYS:
  2029. if (
  2030. isinstance(value, bool)
  2031. or not isinstance(value, (int, float))
  2032. or not math.isfinite(float(value))
  2033. ):
  2034. return self._format_error(meta)
  2035. elif not isinstance(value, str):
  2036. return self._format_error(meta)
  2037. row.append(value)
  2038. rows.append(row)
  2039. headers = [{'label': name} for _, name in expected]
  2040. content = {
  2041. 'business_type': business_type,
  2042. 'headers': headers,
  2043. 'rows': rows,
  2044. 'pagination': pagination,
  2045. }
  2046. return self._success_result(content, self._render_table(content), meta)
  2047. def _present_arrange_destination_trailer(self, data, meta):
  2048. expected = ('trailer_number', 'bl_number', 'container_code')
  2049. if set(data) != set(expected):
  2050. return self._format_error(meta)
  2051. for key in expected:
  2052. if not isinstance(data.get(key), str):
  2053. return self._format_error(meta)
  2054. content = {
  2055. '拖车单号': data['trailer_number'],
  2056. '提单号': data['bl_number'],
  2057. '柜号': data['container_code'],
  2058. }
  2059. text = '拖车单号:{0};提单号:{1};柜号:{2}'.format(
  2060. data['trailer_number'], data['bl_number'], data['container_code']
  2061. )
  2062. return self._success_result(content, text, meta)
  2063. def _present_destination_trailer_list(self, data, raw_meta, meta):
  2064. if set(data) != {'trailer_stage', 'columns', 'records'}:
  2065. return self._format_error(meta)
  2066. trailer_stage = data.get('trailer_stage')
  2067. if trailer_stage == 'DO单制作':
  2068. expected = list(self.DESTINATION_TRAILER_COLUMNS['do'])
  2069. elif trailer_stage in self.DESTINATION_TRAILER_PROGRESS_STAGES:
  2070. expected = list(self.DESTINATION_TRAILER_COLUMNS['progress'])
  2071. else:
  2072. return self._format_error(meta)
  2073. pagination = self._customer_pagination(raw_meta)
  2074. columns = data.get('columns')
  2075. records = data.get('records')
  2076. if (
  2077. not isinstance(columns, list)
  2078. or not isinstance(records, list)
  2079. or len(columns) != len(expected)
  2080. or pagination is None
  2081. ):
  2082. return self._format_error(meta)
  2083. for column, (key, name) in zip(columns, expected):
  2084. if column != {'key': key, 'name': name}:
  2085. return self._format_error(meta)
  2086. rows = []
  2087. expected_keys = [key for key, _ in expected]
  2088. for record in records:
  2089. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2090. return self._format_error(meta)
  2091. row = []
  2092. for key in expected_keys:
  2093. value = record[key]
  2094. if key in self.DESTINATION_TRAILER_FILE_KEYS:
  2095. if value != '' and not self._valid_http_url(value):
  2096. return self._format_error(meta)
  2097. elif not isinstance(value, str):
  2098. return self._format_error(meta)
  2099. row.append(value)
  2100. rows.append(row)
  2101. headers = [{'label': name} for _, name in expected]
  2102. content = {
  2103. 'trailer_stage': trailer_stage,
  2104. 'headers': headers,
  2105. 'rows': rows,
  2106. 'pagination': pagination,
  2107. }
  2108. return self._success_result(content, self._render_table(content), meta)
  2109. def _present_order_abnormal_list(self, data, raw_meta, meta):
  2110. if set(data) != {'abnormal_status', 'columns', 'records'}:
  2111. return self._format_error(meta)
  2112. abnormal_status = data.get('abnormal_status')
  2113. if abnormal_status not in self.ORDER_ABNORMAL_STATUSES:
  2114. return self._format_error(meta)
  2115. expected = list(self.ORDER_ABNORMAL_COLUMNS)
  2116. pagination = self._customer_pagination(raw_meta)
  2117. columns = data.get('columns')
  2118. records = data.get('records')
  2119. if (
  2120. not isinstance(columns, list)
  2121. or not isinstance(records, list)
  2122. or len(columns) != len(expected)
  2123. or pagination is None
  2124. ):
  2125. return self._format_error(meta)
  2126. for column, (key, name) in zip(columns, expected):
  2127. if column != {'key': key, 'name': name}:
  2128. return self._format_error(meta)
  2129. rows = []
  2130. expected_keys = [key for key, _ in expected]
  2131. for record in records:
  2132. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2133. return self._format_error(meta)
  2134. row = []
  2135. for key in expected_keys:
  2136. value = record[key]
  2137. if not isinstance(value, str):
  2138. return self._format_error(meta)
  2139. row.append(value)
  2140. rows.append(row)
  2141. headers = [{'label': name} for _, name in expected]
  2142. content = {
  2143. 'abnormal_status': abnormal_status,
  2144. 'headers': headers,
  2145. 'rows': rows,
  2146. 'pagination': pagination,
  2147. }
  2148. return self._success_result(content, self._render_table(content), meta)
  2149. def _present_goods_tax(self, data, meta):
  2150. expected = {
  2151. 'estimated_tax', 'sku', 'departure_country', 'destination_country',
  2152. }
  2153. if set(data) != expected:
  2154. return self._format_error(meta)
  2155. amount = data.get('estimated_tax')
  2156. sku = data.get('sku')
  2157. departure = data.get('departure_country')
  2158. destination = data.get('destination_country')
  2159. if (
  2160. isinstance(amount, bool) or not isinstance(amount, (int, float))
  2161. or not math.isfinite(float(amount))
  2162. or not isinstance(sku, str) or not sku.strip()
  2163. or not self._country_code(departure)
  2164. or not self._country_code(destination)
  2165. ):
  2166. return self._format_error(meta)
  2167. content = {
  2168. 'estimated_tax': amount,
  2169. 'sku': sku,
  2170. 'departure_country': departure,
  2171. 'destination_country': destination,
  2172. }
  2173. text = '预计关税金额: {0}'.format(amount)
  2174. return self._success_result(content, text, meta)
  2175. @staticmethod
  2176. def _country_code(value):
  2177. return (
  2178. isinstance(value, str)
  2179. and value.isalpha()
  2180. and value.isupper()
  2181. and 2 <= len(value) <= 3
  2182. )
  2183. def _present_goods_info(self, data, raw_meta, meta):
  2184. if set(data) != {'columns', 'records'}:
  2185. return self._format_error(meta)
  2186. expected = list(self.GOODS_INFO_COLUMNS)
  2187. pagination = self._customer_pagination(raw_meta)
  2188. columns = data.get('columns')
  2189. records = data.get('records')
  2190. if (
  2191. not isinstance(columns, list)
  2192. or not isinstance(records, list)
  2193. or len(columns) != len(expected)
  2194. or pagination is None
  2195. ):
  2196. return self._format_error(meta)
  2197. for column, (key, name) in zip(columns, expected):
  2198. if column != {'key': key, 'name': name}:
  2199. return self._format_error(meta)
  2200. rows = []
  2201. expected_keys = [key for key, _ in expected]
  2202. for record in records:
  2203. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2204. return self._format_error(meta)
  2205. row = []
  2206. for key in expected_keys:
  2207. value = record[key]
  2208. if not isinstance(value, str):
  2209. return self._format_error(meta)
  2210. row.append(value)
  2211. rows.append(row)
  2212. headers = [{'label': name} for _, name in expected]
  2213. content = {
  2214. 'headers': headers,
  2215. 'rows': rows,
  2216. 'pagination': pagination,
  2217. }
  2218. return self._success_result(content, self._render_table(content), meta)
  2219. def _present_receive_volume_list(self, data, raw_meta, meta):
  2220. if set(data) != {'columns', 'records'}:
  2221. return self._format_error(meta)
  2222. expected = list(self.RECEIVE_VOLUME_COLUMNS)
  2223. pagination = self._customer_pagination(raw_meta)
  2224. columns = data.get('columns')
  2225. records = data.get('records')
  2226. if (
  2227. not isinstance(columns, list)
  2228. or not isinstance(records, list)
  2229. or len(columns) != len(expected)
  2230. or pagination is None
  2231. ):
  2232. return self._format_error(meta)
  2233. for column, (key, name) in zip(columns, expected):
  2234. if column != {'key': key, 'name': name}:
  2235. return self._format_error(meta)
  2236. rows = []
  2237. expected_keys = [key for key, _ in expected]
  2238. for record in records:
  2239. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2240. return self._format_error(meta)
  2241. row = []
  2242. for key in expected_keys:
  2243. value = record[key]
  2244. if key == 'inbound_volume':
  2245. if not self._valid_volume_cell(value):
  2246. return self._format_error(meta)
  2247. row.append(value)
  2248. continue
  2249. if not isinstance(value, str):
  2250. return self._format_error(meta)
  2251. row.append(value)
  2252. rows.append(row)
  2253. headers = [{'label': name} for _, name in expected]
  2254. content = {
  2255. 'headers': headers,
  2256. 'rows': rows,
  2257. 'pagination': pagination,
  2258. }
  2259. return self._success_result(content, self._render_table(content), meta)
  2260. def _present_open_goods_audit(self, data, meta):
  2261. if set(data) != {'audit_sheet', 'options', 'reference'}:
  2262. return self._format_error(meta)
  2263. if not self._valid_goods_audit_sheet(data['audit_sheet']):
  2264. return self._format_error(meta)
  2265. if not self._valid_goods_audit_options(data['options']):
  2266. return self._format_error(meta)
  2267. if not self._valid_goods_audit_reference(data['reference']):
  2268. return self._format_error(meta)
  2269. sheet = data['audit_sheet']
  2270. text = '商品编号:{0}。请按审核单字段提交,不要提交参考和可选项名单。'.format(
  2271. sheet['goods_id']
  2272. )
  2273. return self._success_result(data, text, meta)
  2274. def _present_submit_goods_audit(self, data, meta):
  2275. expected = ('goods_id', 'status', 'status_name')
  2276. if set(data) != set(expected):
  2277. return self._format_error(meta)
  2278. for key in expected:
  2279. if not isinstance(data.get(key), str) or data[key] == '':
  2280. return self._format_error(meta)
  2281. if data['status'] not in ('30', '-10', '25'):
  2282. return self._format_error(meta)
  2283. if data['status_name'] not in ('审核通过', '审核驳回', '预审通过'):
  2284. return self._format_error(meta)
  2285. text = '商品编号:{0},{1}'.format(data['goods_id'], data['status_name'])
  2286. return self._success_result({
  2287. '商品编号': data['goods_id'],
  2288. '审核结果': data['status_name'],
  2289. }, text, meta)
  2290. def _valid_goods_audit_sheet(self, sheet):
  2291. expected = {
  2292. 'goods_id', 'goods_clearance_id', 'shipping_method', 'goods_type',
  2293. 'goods_category_id', 'category_ids', 'goods_attr',
  2294. 'is_inspection_fee', 'product_surcharge', 'tax_surcharge',
  2295. 'yf_cn_goodsname', 'yf_en_goodsname',
  2296. 'yf_clearance_price', 'ys_clearance_price',
  2297. 'yf_clearance_data', 'ys_clearance_data',
  2298. 'is_fda_declaration', 'is_epa_declaration', 'is_act_declaration',
  2299. 'is_dot_declaration', 'is_cpsc_declaration',
  2300. }
  2301. if not isinstance(sheet, dict) or set(sheet) != expected:
  2302. return False
  2303. for key, value in sheet.items():
  2304. if key == 'goods_attr':
  2305. if not self._valid_goods_attr(value):
  2306. return False
  2307. elif key in ('yf_clearance_data', 'ys_clearance_data'):
  2308. if not self._valid_clearance_rows(value):
  2309. return False
  2310. elif not isinstance(value, str):
  2311. return False
  2312. return True
  2313. def _valid_goods_attr(self, attr):
  2314. keys = {
  2315. 'is_battery', 'is_magnetic', 'is_wood', 'is_other', 'is_fda',
  2316. 'is_toy', 'is_ultra_limit', 'is_sensitive', 'is_food',
  2317. }
  2318. if not isinstance(attr, dict) or set(attr) != keys:
  2319. return False
  2320. return all(isinstance(value, bool) for value in attr.values())
  2321. def _valid_clearance_rows(self, rows):
  2322. keys = {
  2323. 'clearance_hscode', 'material', 'material_ratio', 'kit_hscode',
  2324. 'adjust_hscode_data', 'tax_rate', 'extra_tax',
  2325. 'is_new_hscode', 'kit_tax_rate',
  2326. }
  2327. if not isinstance(rows, list):
  2328. return False
  2329. for row in rows:
  2330. if not isinstance(row, dict) or set(row) != keys:
  2331. return False
  2332. codes = row['adjust_hscode_data']
  2333. if not isinstance(codes, list) or any(
  2334. not isinstance(code, str) for code in codes
  2335. ):
  2336. return False
  2337. if row['is_new_hscode'] not in ('是', '否'):
  2338. return False
  2339. for key, value in row.items():
  2340. if key == 'adjust_hscode_data':
  2341. continue
  2342. if not isinstance(value, str):
  2343. return False
  2344. return True
  2345. def _valid_goods_audit_options(self, options):
  2346. expected = {
  2347. 'results', 'reject_types', 'product_surcharges', 'goods_categories',
  2348. 'goods_marks', 'cpsc_marks', 'shipping_methods', 'goods_types',
  2349. 'tax_surcharges', 'sync_orders',
  2350. }
  2351. if not isinstance(options, dict) or set(options) != expected:
  2352. return False
  2353. if not self._valid_choice_rows(options['results'], False):
  2354. return False
  2355. if not self._valid_choice_rows(options['reject_types'], True):
  2356. return False
  2357. for key in (
  2358. 'product_surcharges', 'goods_categories', 'goods_marks',
  2359. 'shipping_methods', 'goods_types', 'tax_surcharges',
  2360. ):
  2361. if not self._valid_choice_rows(options[key], False):
  2362. return False
  2363. marks = options['cpsc_marks']
  2364. if not isinstance(marks, dict) or set(marks) - {'Y', 'B'}:
  2365. return False
  2366. if any(not isinstance(value, str) or value == '' for value in marks.values()):
  2367. return False
  2368. for order in options['sync_orders']:
  2369. if not isinstance(order, dict) or set(order) != {
  2370. 'order_id', 'order_number', 'status_name',
  2371. }:
  2372. return False
  2373. if any(not isinstance(value, str) for value in order.values()):
  2374. return False
  2375. return True
  2376. def _valid_choice_rows(self, rows, with_content):
  2377. if not isinstance(rows, list):
  2378. return False
  2379. keys = {'value', 'label', 'content'} if with_content else {'value', 'label'}
  2380. for row in rows:
  2381. if not isinstance(row, dict) or set(row) != keys:
  2382. return False
  2383. if any(not isinstance(value, str) for value in row.values()):
  2384. return False
  2385. return True
  2386. def _valid_goods_audit_reference(self, reference):
  2387. if not isinstance(reference, dict) or set(reference) != {
  2388. 'image_url', 'files', 'recommended_grade', 'recommended_keyword',
  2389. }:
  2390. return False
  2391. for key in ('image_url', 'recommended_grade', 'recommended_keyword'):
  2392. if not isinstance(reference[key], str):
  2393. return False
  2394. files = reference['files']
  2395. names = {'battery_file', 'fda_file', 'toy_file', 'other_file'}
  2396. if not isinstance(files, dict) or set(files) != names:
  2397. return False
  2398. for group in files.values():
  2399. if not isinstance(group, list):
  2400. return False
  2401. for item in group:
  2402. if not isinstance(item, dict) or set(item) != {'name', 'url'}:
  2403. return False
  2404. if not isinstance(item['name'], str) or not isinstance(item['url'], str):
  2405. return False
  2406. return True
  2407. def _present_pending_goods_list(self, data, raw_meta, meta):
  2408. if set(data) != {'columns', 'records'}:
  2409. return self._format_error(meta)
  2410. expected = list(self.PENDING_GOODS_COLUMNS)
  2411. pagination = self._customer_pagination(raw_meta)
  2412. columns = data.get('columns')
  2413. records = data.get('records')
  2414. if (
  2415. not isinstance(columns, list)
  2416. or not isinstance(records, list)
  2417. or len(columns) != len(expected)
  2418. or pagination is None
  2419. ):
  2420. return self._format_error(meta)
  2421. for column, (key, name) in zip(columns, expected):
  2422. if column != {'key': key, 'name': name}:
  2423. return self._format_error(meta)
  2424. rows = []
  2425. expected_keys = [key for key, _ in expected]
  2426. for record in records:
  2427. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2428. return self._format_error(meta)
  2429. row = []
  2430. for key in expected_keys:
  2431. value = record[key]
  2432. if not isinstance(value, str):
  2433. return self._format_error(meta)
  2434. row.append(value)
  2435. rows.append(row)
  2436. content = {
  2437. 'headers': [{'label': name} for _, name in expected],
  2438. 'rows': rows,
  2439. 'pagination': pagination,
  2440. }
  2441. return self._success_result(content, self._render_table(content), meta)
  2442. def _present_container_timeliness_list(self, data, raw_meta, meta):
  2443. if set(data) != {'columns', 'records'}:
  2444. return self._format_error(meta)
  2445. expected = list(self.CONTAINER_TIMELINESS_COLUMNS)
  2446. pagination = self._customer_pagination(raw_meta)
  2447. columns = data.get('columns')
  2448. records = data.get('records')
  2449. if (
  2450. not isinstance(columns, list)
  2451. or not isinstance(records, list)
  2452. or len(columns) != len(expected)
  2453. or pagination is None
  2454. ):
  2455. return self._format_error(meta)
  2456. for column, (key, name) in zip(columns, expected):
  2457. if column != {'key': key, 'name': name}:
  2458. return self._format_error(meta)
  2459. rows = []
  2460. expected_keys = [key for key, _ in expected]
  2461. for record in records:
  2462. if not isinstance(record, dict) or set(record) != set(expected_keys):
  2463. return self._format_error(meta)
  2464. row = []
  2465. for key in expected_keys:
  2466. value = record[key]
  2467. if not isinstance(value, str):
  2468. return self._format_error(meta)
  2469. row.append(value)
  2470. rows.append(row)
  2471. headers = [{'label': name} for _, name in expected]
  2472. content = {
  2473. 'headers': headers,
  2474. 'rows': rows,
  2475. 'pagination': pagination,
  2476. }
  2477. return self._success_result(content, self._render_table(content), meta)
  2478. def _present_headhaul_document_list(self, data, raw_meta, meta):
  2479. if set(data) != {'columns', 'records'}:
  2480. return self._format_error(meta)
  2481. expected = list(self.HEADHAUL_DOCUMENT_COLUMNS)
  2482. pagination = self._customer_pagination(raw_meta)
  2483. columns = data.get('columns')
  2484. records = data.get('records')
  2485. if (
  2486. not isinstance(columns, list)
  2487. or not isinstance(records, list)
  2488. or len(columns) != len(expected)
  2489. or pagination is None
  2490. ):
  2491. return self._format_error(meta)
  2492. for column, (key, name) in zip(columns, expected):
  2493. if column != {'key': key, 'name': name}:
  2494. return self._format_error(meta)
  2495. rows = []
  2496. expected_keys = [key for key, _ in expected]
  2497. for record in records:
  2498. if not isinstance(record, dict):
  2499. return self._format_error(meta)
  2500. if set(record) != set(expected_keys + ['document_ref']):
  2501. return self._format_error(meta)
  2502. document_ref = record.get('document_ref')
  2503. if not isinstance(document_ref, str) or not document_ref.strip():
  2504. return self._format_error(meta)
  2505. if not document_ref.startswith('mhdd_'):
  2506. return self._format_error(meta)
  2507. row = []
  2508. for key in expected_keys:
  2509. value = record[key]
  2510. if key == 'safe_url':
  2511. if value != '' and not self._valid_http_url(value):
  2512. return self._format_error(meta)
  2513. row.append(value)
  2514. continue
  2515. if not isinstance(value, str):
  2516. return self._format_error(meta)
  2517. row.append(value)
  2518. row.append(document_ref.strip())
  2519. rows.append(row)
  2520. headers = [{'label': name} for _, name in expected]
  2521. headers.append({'label': '文档身份'})
  2522. content = {
  2523. 'headers': headers,
  2524. 'rows': rows,
  2525. 'pagination': pagination,
  2526. }
  2527. return self._success_result(content, self._render_table(content), meta)
  2528. def _present_headhaul_prepare(self, data, meta):
  2529. expected = {
  2530. 'upload_token', 'upload_url', 'expires_in',
  2531. }
  2532. if set(data) != expected:
  2533. return self._format_error(meta)
  2534. upload_token = data.get('upload_token')
  2535. upload_url = data.get('upload_url')
  2536. expires_in = data.get('expires_in')
  2537. if (
  2538. not isinstance(upload_token, str) or not upload_token.strip()
  2539. or not isinstance(upload_url, str)
  2540. or upload_url != '/mcp/upload-headhaul-document'
  2541. or isinstance(expires_in, bool)
  2542. or not isinstance(expires_in, int)
  2543. or expires_in <= 0
  2544. ):
  2545. return self._format_error(meta)
  2546. from services.headhaul_document_app import public_upload_url
  2547. posted_url = public_upload_url()
  2548. content = {
  2549. 'upload_token': upload_token.strip(),
  2550. 'upload_url': posted_url,
  2551. 'expires_in': expires_in,
  2552. }
  2553. result_meta = dict(meta)
  2554. result_meta['upload_token'] = upload_token.strip()
  2555. text = (
  2556. '请把对话窗口里已添加的文件 POST 到上传地址,并带上上传令牌。'
  2557. '不要使用选文件框,也不要把文件放进工具参数。'
  2558. '上传地址:{0}'
  2559. ).format(posted_url)
  2560. return self._success_result(content, text, result_meta)
  2561. def _present_headhaul_save(self, data, meta):
  2562. if set(data) != {'document_ref'}:
  2563. return self._format_error(meta)
  2564. document_ref = data.get('document_ref')
  2565. if (
  2566. not isinstance(document_ref, str)
  2567. or not document_ref.strip()
  2568. or not document_ref.startswith('mhdd_')
  2569. ):
  2570. return self._format_error(meta)
  2571. content = {'文档身份': document_ref.strip(), '结果': '已保存'}
  2572. return self._success_result(content, '头程文档已保存', meta)
  2573. def _present_headhaul_delete(self, data, meta):
  2574. if set(data) != {'result'}:
  2575. return self._format_error(meta)
  2576. result = data.get('result')
  2577. if result != '已删除':
  2578. return self._format_error(meta)
  2579. content = {'结果': '已删除'}
  2580. return self._success_result(content, '头程文档已删除', meta)
  2581. @staticmethod
  2582. def _valid_volume_cell(value):
  2583. return (
  2584. not isinstance(value, bool)
  2585. and isinstance(value, (int, float))
  2586. and math.isfinite(float(value))
  2587. )
  2588. @staticmethod
  2589. def _valid_amount_cell(value):
  2590. if not isinstance(value, dict) or set(value) != {'amount', 'currency'}:
  2591. return False
  2592. amount = value.get('amount')
  2593. return (
  2594. not isinstance(amount, bool)
  2595. and isinstance(amount, (int, float))
  2596. and math.isfinite(float(amount))
  2597. and isinstance(value.get('currency'), str)
  2598. )
  2599. def _present_receivable_cost_filter_options(self, data, raw_meta, meta):
  2600. if set(data) != {'records'}:
  2601. return self._format_error(meta)
  2602. records = data.get('records')
  2603. pagination = self._customer_pagination(raw_meta)
  2604. if not isinstance(records, list) or pagination is None:
  2605. return self._format_error(meta)
  2606. rows = []
  2607. for record in records:
  2608. if not isinstance(record, dict) or set(record) != {
  2609. 'value', 'label', 'code',
  2610. }:
  2611. return self._format_error(meta)
  2612. value = record.get('value')
  2613. label = record.get('label')
  2614. code = record.get('code')
  2615. if (
  2616. isinstance(value, bool) or not isinstance(value, int)
  2617. or not isinstance(label, str) or not label.strip()
  2618. or not isinstance(code, str)
  2619. ):
  2620. return self._format_error(meta)
  2621. rows.append([value, label.strip(), code.strip()])
  2622. content = {
  2623. 'headers': [
  2624. {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
  2625. ],
  2626. 'rows': rows,
  2627. 'pagination': pagination,
  2628. }
  2629. return self._success_result(content, self._render_table(content), meta)
  2630. @staticmethod
  2631. def _customer_billing_modes(value):
  2632. if not isinstance(value, list):
  2633. return None
  2634. result = []
  2635. business_types = set()
  2636. for item in value:
  2637. if not isinstance(item, dict) or set(item) != {
  2638. 'business_type', 'settlement_mode',
  2639. }:
  2640. return None
  2641. business_type = item.get('business_type')
  2642. settlement_mode = item.get('settlement_mode')
  2643. if (
  2644. not isinstance(business_type, str) or not business_type.strip()
  2645. or not isinstance(settlement_mode, str) or not settlement_mode.strip()
  2646. or business_type in business_types
  2647. ):
  2648. return None
  2649. business_types.add(business_type)
  2650. result.append({
  2651. '业务类型': business_type.strip(),
  2652. '结算模式': settlement_mode.strip(),
  2653. })
  2654. return result
  2655. def _present_customer_options(self, data, raw_meta, meta):
  2656. if set(data) != {'records'}:
  2657. return self._format_error(meta)
  2658. records = data.get('records')
  2659. pagination = self._customer_pagination(raw_meta)
  2660. if not isinstance(records, list) or pagination is None:
  2661. return self._format_error(meta)
  2662. rows = []
  2663. for record in records:
  2664. if not isinstance(record, dict) or set(record) != {'value', 'label', 'code'}:
  2665. return self._format_error(meta)
  2666. value = record.get('value')
  2667. label = record.get('label')
  2668. code = record.get('code')
  2669. if (
  2670. isinstance(value, bool) or not isinstance(value, int) or value < 1
  2671. or not isinstance(label, str) or not label.strip()
  2672. or not isinstance(code, str)
  2673. ):
  2674. return self._format_error(meta)
  2675. rows.append([value, label.strip(), code.strip()])
  2676. content = {
  2677. 'headers': [
  2678. {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
  2679. ],
  2680. 'rows': rows,
  2681. 'pagination': pagination,
  2682. }
  2683. return self._success_result(content, self._render_table(content), meta)
  2684. @staticmethod
  2685. def _customer_pagination(raw_meta):
  2686. if not isinstance(raw_meta, dict):
  2687. return None
  2688. required = {'page', 'limit', 'has_more'}
  2689. if (
  2690. not required.issubset(raw_meta)
  2691. or not set(raw_meta).issubset(required | {'request_id'})
  2692. ):
  2693. return None
  2694. page = raw_meta.get('page')
  2695. limit = raw_meta.get('limit')
  2696. has_more = raw_meta.get('has_more')
  2697. if (
  2698. isinstance(page, bool) or not isinstance(page, int)
  2699. or page < 1 or page > 100
  2700. or isinstance(limit, bool) or not isinstance(limit, int)
  2701. or limit < 1 or limit > 100
  2702. or not isinstance(has_more, bool)
  2703. ):
  2704. return None
  2705. return {'page': page, 'limit': limit, 'has_more': has_more}
  2706. def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
  2707. summary = data.get('summary')
  2708. columns = data.get('columns')
  2709. records = data.get('records')
  2710. if not isinstance(summary, dict):
  2711. return self._format_error(meta)
  2712. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  2713. return self._format_error(meta)
  2714. if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
  2715. return self._format_error(meta)
  2716. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  2717. headers = []
  2718. keys = []
  2719. for column in columns:
  2720. if not isinstance(column, dict):
  2721. return self._format_error(meta)
  2722. key = column.get('key')
  2723. definition = allowed_columns.get(key) if isinstance(key, str) else None
  2724. if not isinstance(definition, tuple) or not definition:
  2725. return self._format_error(meta)
  2726. keys.append(key)
  2727. headers.append({'label': definition[0]})
  2728. rows = []
  2729. for record in records:
  2730. if not isinstance(record, dict):
  2731. return self._format_error(meta)
  2732. row = []
  2733. for key in keys:
  2734. value = '' if record.get(key) is None else record.get(key, '')
  2735. if key == 'customs_files':
  2736. if not isinstance(value, list):
  2737. return self._format_error(meta)
  2738. files = []
  2739. for item in value:
  2740. if not isinstance(item, dict):
  2741. return self._format_error(meta)
  2742. files.append({
  2743. '文件名称': item.get('file_name', ''),
  2744. '文件类型': item.get('file_type', ''),
  2745. '文件链接': item.get('file_url', ''),
  2746. })
  2747. value = files
  2748. row.append(value)
  2749. rows.append(row)
  2750. summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
  2751. content = {
  2752. 'summary': {
  2753. 'headers': [
  2754. {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
  2755. for key in summary_keys
  2756. ],
  2757. 'row': [summary.get(key, '') for key in summary_keys],
  2758. },
  2759. 'details': {
  2760. 'headers': headers,
  2761. 'rows': rows,
  2762. },
  2763. }
  2764. tips = self._safe_tips(data.get('tips'))
  2765. if tips:
  2766. content['details']['tips'] = tips
  2767. pagination = self._build_pagination(raw_meta)
  2768. if pagination:
  2769. content['details']['pagination'] = pagination
  2770. return self._success_result(
  2771. content,
  2772. self._render_outbound_detail(content),
  2773. meta,
  2774. )
  2775. @classmethod
  2776. def _render_outbound_detail(cls, content):
  2777. lines = ['排舱汇总:']
  2778. summary = content['summary']
  2779. for header, value in zip(summary['headers'], summary['row']):
  2780. lines.append('- {0}: {1}'.format(header['label'], value))
  2781. lines.append('订单明细:')
  2782. details = content['details']
  2783. lines.append('表头共 {0} 列:'.format(len(details['headers'])))
  2784. for index, header in enumerate(details['headers'], start=1):
  2785. lines.append('{0}. {1}'.format(index, header['label']))
  2786. for index, row in enumerate(details['rows'], start=1):
  2787. lines.append('记录 {0}:'.format(index))
  2788. for header, value in zip(details['headers'], row):
  2789. if isinstance(value, (dict, list)):
  2790. value = json.dumps(value, ensure_ascii=False)
  2791. lines.append('- {0}: {1}'.format(header['label'], value))
  2792. tips = details.get('tips') or []
  2793. if tips:
  2794. lines.append('提示:{0}'.format(';'.join(tips)))
  2795. return '\n'.join(lines)
  2796. def _present_options(self, data, raw_meta, meta):
  2797. records = data.get('records')
  2798. if not isinstance(records, list):
  2799. return self._format_error(meta)
  2800. rows = []
  2801. for record in records:
  2802. if not isinstance(record, dict):
  2803. return self._format_error(meta)
  2804. rows.append([
  2805. record.get('value', ''),
  2806. self._safe_text(record.get('label')),
  2807. self._safe_text(record.get('code')),
  2808. ])
  2809. content = {
  2810. 'headers': [
  2811. {'label': '可传值'},
  2812. {'label': '显示名称'},
  2813. {'label': '业务编码'},
  2814. ],
  2815. 'rows': rows,
  2816. }
  2817. pagination = self._build_pagination(raw_meta)
  2818. if pagination:
  2819. content['pagination'] = pagination
  2820. return self._success_result(content, self._render_table(content), meta)
  2821. def _present_inbound_receipt_templates(self, data, meta):
  2822. if set(data) != {'receipt_kind', 'templates'}:
  2823. return self._format_error(meta)
  2824. kind = data.get('receipt_kind')
  2825. templates = data.get('templates')
  2826. if kind not in ('直送入仓单', '非直送入仓单') or not isinstance(templates, list):
  2827. return self._format_error(meta)
  2828. if not templates:
  2829. return self._format_error(meta)
  2830. rows = []
  2831. for item in templates:
  2832. if not isinstance(item, dict) or set(item) != {'name', 'template_code'}:
  2833. return self._format_error(meta)
  2834. name = item.get('name')
  2835. code = item.get('template_code')
  2836. if (
  2837. not isinstance(name, str) or not name.strip()
  2838. or not isinstance(code, str) or not code.strip()
  2839. ):
  2840. return self._format_error(meta)
  2841. rows.append([name.strip(), code.strip()])
  2842. content = {
  2843. 'receipt_kind': kind,
  2844. 'summary': kind,
  2845. 'headers': [
  2846. {'label': '模板名称'},
  2847. {'label': '模板编码'},
  2848. ],
  2849. 'rows': rows,
  2850. }
  2851. return self._success_result(content, self._render_table(content), meta)
  2852. def _present_export_submission(self, data, meta):
  2853. expected = {'task_ref', 'status', 'retry_after_seconds'}
  2854. if set(data) != expected:
  2855. return self._format_error(meta)
  2856. task_ref = data.get('task_ref')
  2857. retry_after = data.get('retry_after_seconds')
  2858. if (
  2859. not isinstance(task_ref, str) or not task_ref.strip()
  2860. or data.get('status') != 'queued'
  2861. or isinstance(retry_after, bool)
  2862. or not isinstance(retry_after, int)
  2863. or retry_after <= 0
  2864. ):
  2865. return self._format_error(meta)
  2866. task = {
  2867. 'task_ref': task_ref.strip(),
  2868. 'status': 'queued',
  2869. 'retry_after_seconds': retry_after,
  2870. }
  2871. content = {
  2872. 'message': '导出任务已提交',
  2873. 'task': task,
  2874. }
  2875. text = (
  2876. '导出任务已提交\n'
  2877. '- 任务引用: {0}\n'
  2878. '- 建议 {1} 秒后单独查询任务状态'
  2879. ).format(task['task_ref'], retry_after)
  2880. return self._success_result(content, text, meta)
  2881. def _present_export_task(self, data, meta):
  2882. task_ref = data.get('task_ref')
  2883. status = data.get('status')
  2884. if (
  2885. not isinstance(task_ref, str)
  2886. or not task_ref.strip()
  2887. or status not in ('queued', 'running', 'completed', 'failed')
  2888. ):
  2889. return self._format_error(meta)
  2890. task = {'task_ref': task_ref.strip(), 'status': status}
  2891. if status in ('queued', 'running'):
  2892. if set(data) != {'task_ref', 'status', 'retry_after_seconds'}:
  2893. return self._format_error(meta)
  2894. retry_after = data.get('retry_after_seconds')
  2895. if (
  2896. isinstance(retry_after, bool)
  2897. or not isinstance(retry_after, int)
  2898. or retry_after <= 0
  2899. ):
  2900. return self._format_error(meta)
  2901. task['retry_after_seconds'] = retry_after
  2902. label = '等待中' if status == 'queued' else '生成中'
  2903. content = {'message': '导出任务{0}'.format(label), 'task': task}
  2904. text = (
  2905. '导出任务{0}\n- 任务引用: {1}\n- 建议 {2} 秒后再次查询'
  2906. ).format(label, task['task_ref'], retry_after)
  2907. return self._success_result(content, text, meta)
  2908. if status == 'failed':
  2909. if set(data) != {'task_ref', 'status'}:
  2910. return self._format_error(meta)
  2911. content = {'message': '导出任务失败,请重新提交', 'task': task}
  2912. text = '导出任务失败,请重新提交'
  2913. return self._success_result(content, text, meta)
  2914. if set(data) != {'task_ref', 'status', 'files'}:
  2915. return self._format_error(meta)
  2916. files = data.get('files')
  2917. if not isinstance(files, list) or not files:
  2918. return self._format_error(meta)
  2919. safe_files = []
  2920. for item in files:
  2921. if not isinstance(item, dict) or set(item) != {'label', 'url'}:
  2922. return self._format_error(meta)
  2923. label = item.get('label')
  2924. url = item.get('url')
  2925. if (
  2926. not isinstance(label, str) or not label.strip()
  2927. or not self._valid_http_url(url)
  2928. ):
  2929. return self._format_error(meta)
  2930. safe_files.append({'label': label.strip(), 'url': url.strip()})
  2931. content = {
  2932. 'message': '文件已生成',
  2933. 'task': task,
  2934. 'files': safe_files,
  2935. }
  2936. lines = ['文件已生成']
  2937. for item in safe_files:
  2938. lines.append('- {0}: {1}'.format(item['label'], item['url']))
  2939. return self._success_result(content, '\n'.join(lines), meta)
  2940. def _valid_http_url(self, value):
  2941. if not isinstance(value, str) or not value.strip():
  2942. return False
  2943. if value != value.strip() or '\\' in value or any(
  2944. character.isspace() or ord(character) < 32 or ord(character) == 127
  2945. for character in value
  2946. ):
  2947. return False
  2948. try:
  2949. parsed = urlparse(value)
  2950. port = parsed.port
  2951. return (
  2952. parsed.scheme in ('http', 'https')
  2953. and bool(parsed.hostname)
  2954. and parsed.username is None
  2955. and parsed.password is None
  2956. and (port is None or 0 < port <= 65535)
  2957. )
  2958. except ValueError:
  2959. return False
  2960. def _business_error(self, tool_name, code, raw_message, meta):
  2961. message = str(raw_message or '').strip()
  2962. if tool_name == 'trial_goods_tax' and message in self.TAX_TRIAL_MESSAGES:
  2963. safe_code = code if code in self.ERROR_MESSAGES else 'MCP_9001'
  2964. retryable = safe_code not in self.NON_RETRYABLE_CODES
  2965. return self._error_result(safe_code, message, retryable, meta)
  2966. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  2967. logger.warning(
  2968. 'Unknown MCP business error code',
  2969. extra={
  2970. 'request_id': meta.get('request_id', ''),
  2971. 'tool_code': tool_name,
  2972. 'backend_code': code,
  2973. 'response_code': 'MCP_9001',
  2974. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  2975. },
  2976. )
  2977. code = 'MCP_9001'
  2978. if code == 'MCP_1401' and tool_name in self.ARRANGE_TRAILER_TOOLS:
  2979. if not self._arrange_trailer_message(message):
  2980. message = self._parameter_message('')
  2981. return self._error_result(code, message, False, meta)
  2982. elif code == 'MCP_1401' and tool_name in self.REMOTE_ADDRESS_SAVE_TOOLS:
  2983. if not self._remote_address_save_message(message):
  2984. message = self._parameter_message('')
  2985. return self._error_result(code, message, False, meta)
  2986. elif code == 'MCP_1401' and tool_name in self.FUEL_RATE_TOOLS:
  2987. if not self._fuel_rate_message(message):
  2988. message = self._parameter_message('')
  2989. return self._error_result(code, message, False, meta)
  2990. elif code == 'MCP_1401' and tool_name in (
  2991. self.GOODS_AUDIT_OPEN_TOOLS | self.GOODS_AUDIT_SUBMIT_TOOLS
  2992. ):
  2993. if self._goods_audit_message(message):
  2994. return self._error_result(code, message, False, meta)
  2995. message = self._parameter_message('')
  2996. return self._error_result(code, message, False, meta)
  2997. elif code == 'MCP_1501' and tool_name in (
  2998. self.GOODS_AUDIT_OPEN_TOOLS | self.GOODS_AUDIT_SUBMIT_TOOLS
  2999. ):
  3000. if message == '商品不存在':
  3001. return self._error_result(code, message, False, meta)
  3002. message = self.ERROR_MESSAGES['MCP_1501']
  3003. return self._error_result(code, message, False, meta)
  3004. elif code == 'MCP_1401':
  3005. label = self._find_field_label(tool_name, raw_message)
  3006. message = self._parameter_message(label)
  3007. elif tool_name in self.INBOUND_RECEIPT_TOOLS | self.EXPORT_TOOLS and (
  3008. tool_name in (
  3009. 'list_inbound_receipt_templates',
  3010. 'export_inbound_receipt',
  3011. )
  3012. ):
  3013. allowed = self._inbound_receipt_message(message)
  3014. message = allowed or self.ERROR_MESSAGES.get(
  3015. code, self.ERROR_MESSAGES['MCP_9001']
  3016. )
  3017. elif tool_name in self.FREIGHTOWER_TRACK_TOOLS:
  3018. allowed = str(raw_message or '').strip()
  3019. if allowed not in (
  3020. '暂时没有飞驼轨迹',
  3021. '未找到本公司排舱单',
  3022. '匹配到多票排舱单,请同时提供提单号和柜号',
  3023. '未找到飞驼轨迹订单',
  3024. '飞驼查询超时',
  3025. '飞驼查询失败',
  3026. ):
  3027. message = self.ERROR_MESSAGES.get(code, self.ERROR_MESSAGES['MCP_9001'])
  3028. else:
  3029. message = allowed
  3030. elif tool_name in self.REMOTE_ADDRESS_MAINTAIN_TOOLS and message == '地址库不存在':
  3031. message = '地址库不存在'
  3032. elif tool_name in self.REMOTE_ADDRESS_SAVE_TOOLS and message == '地址库不存在':
  3033. message = '地址库不存在'
  3034. else:
  3035. message = self.ERROR_MESSAGES[code]
  3036. retryable = code not in self.NON_RETRYABLE_CODES
  3037. return self._error_result(code, message, retryable, meta)
  3038. @staticmethod
  3039. def _arrange_trailer_message(message):
  3040. if message in (
  3041. '请提供提单号或柜号',
  3042. '存在不能填写的内容',
  3043. '号码不正确',
  3044. '请填写拖车行',
  3045. '找不到可安排的柜子',
  3046. '匹配到不止一柜,请改说另一个号码',
  3047. '当前柜子不能安排拖车行',
  3048. '当前不需要填写海外仓',
  3049. '当前不需要填写直送改拆',
  3050. '当前不需要填写改拆原因',
  3051. '直送柜只能选择是或否',
  3052. '拖车行请说完整的名称-代码',
  3053. '拖车行不能填',
  3054. '港后跟进人不能填',
  3055. '预计提柜时间不正确',
  3056. '请选择直送改拆',
  3057. '直送改拆只能选择是或否',
  3058. '改拆原因不正确',
  3059. '请填写海外仓',
  3060. '海外仓不能填',
  3061. '请填写仓库联系人',
  3062. '请填写仓库联系电话',
  3063. '当前不需要填写重量体积',
  3064. '该柜子需要在页面上传BOL后再安排',
  3065. '重量体积不正确',
  3066. '订单不在这一柜',
  3067. '请填写重量体积',
  3068. '干线未出发不可安排拖车',
  3069. '当前柜子已安排拖车行',
  3070. '仓库不存在',
  3071. '仓库联系人不能为空',
  3072. '仓库联系电话不能为空',
  3073. '拖车行不存在',
  3074. '拖车行类型不是海外拖车',
  3075. '排舱单不存在',
  3076. '安排拖车行失败',
  3077. ):
  3078. return True
  3079. return message.startswith('请填写订单') and message.endswith('的重量和体积')
  3080. def _goods_audit_message(self, message):
  3081. if message in (
  3082. '请填写商品编号',
  3083. '只能是待审核或预审通过状态的商品才能审核',
  3084. '这条商品不能预审通过',
  3085. '不能把这次审核记成系统审核或改写操作日志',
  3086. '清关记录编号不是这条商品的',
  3087. '这条商品不能同步订单',
  3088. '驳回原因不能为空',
  3089. '驳回类型不能为空',
  3090. '驳回类型不正确',
  3091. '请选择商品标记',
  3092. '商品标记不在可选项里',
  3093. '加拿大商品这几项申报只能为否',
  3094. ):
  3095. return True
  3096. return message.startswith('这个商品编号有多条,请补充起运国和目的国')
  3097. def _find_field_label(self, tool_name, raw_message):
  3098. message = str(raw_message or '')
  3099. fields = self.FIELD_LABELS.get(tool_name, {})
  3100. for field in sorted(fields, key=len, reverse=True):
  3101. if field in message:
  3102. return fields[field]
  3103. return ''
  3104. @staticmethod
  3105. def _parameter_message(label):
  3106. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  3107. @classmethod
  3108. def _inbound_receipt_message(cls, message):
  3109. text = str(message or '').strip()
  3110. if text in (
  3111. '当前没有可用的入仓单模板',
  3112. '所选模板不属于这次柜号对应的入仓单',
  3113. ):
  3114. return text
  3115. missing_prefix = '这些柜号没有对应的排舱单:'
  3116. if text.startswith(missing_prefix) and cls._container_code_list(
  3117. text[len(missing_prefix):]
  3118. ):
  3119. return text
  3120. direct_prefix = '这些柜号是直送柜:'
  3121. indirect_mark = '。这些柜号是非直送柜:'
  3122. if text.startswith(direct_prefix) and text.endswith('。') and indirect_mark in text:
  3123. body = text[len(direct_prefix):-1]
  3124. direct, indirect = body.split(indirect_mark, 1)
  3125. if cls._container_code_list(direct) and cls._container_code_list(indirect):
  3126. return text
  3127. return ''
  3128. @staticmethod
  3129. def _container_code_list(text):
  3130. if not text or len(text) > 200 * 101:
  3131. return False
  3132. parts = text.split('、')
  3133. for part in parts:
  3134. if (
  3135. not part
  3136. or part != part.strip()
  3137. or len(part) > 100
  3138. or any(ord(char) < 32 for char in part)
  3139. ):
  3140. return False
  3141. return True
  3142. @staticmethod
  3143. def _build_meta(raw_meta):
  3144. if not isinstance(raw_meta, dict):
  3145. return {}
  3146. request_id = raw_meta.get('request_id')
  3147. if not isinstance(request_id, str) or not request_id.strip():
  3148. return {}
  3149. return {'request_id': request_id.strip()}
  3150. @staticmethod
  3151. def _build_pagination(raw_meta):
  3152. if not isinstance(raw_meta, dict):
  3153. return {}
  3154. return {
  3155. key: raw_meta[key]
  3156. for key in ('page', 'limit', 'has_more', 'total')
  3157. if key in raw_meta
  3158. }
  3159. @staticmethod
  3160. def _safe_text(value):
  3161. if value is None:
  3162. return ''
  3163. return str(value).strip()
  3164. @classmethod
  3165. def _safe_tips(cls, value):
  3166. if not isinstance(value, list):
  3167. return []
  3168. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  3169. @classmethod
  3170. def _render_table(cls, content, require_complete=False):
  3171. headers = content.get('headers') or []
  3172. rows = content.get('rows') or []
  3173. lines = []
  3174. if require_complete:
  3175. lines.append('完整客户数据,禁止摘要、合并、隐藏字段或省略空字段。')
  3176. lines.append(
  3177. '本页记录数:{0};每条字段数:{1};应展示字段值总数:{2}。'.format(
  3178. len(rows), len(headers), len(rows) * len(headers)
  3179. )
  3180. )
  3181. summary = cls._safe_text(content.get('summary'))
  3182. if summary:
  3183. lines.append(summary)
  3184. lines.append('表头共 {0} 列:'.format(len(headers)))
  3185. for index, header in enumerate(headers, start=1):
  3186. lines.append('{0}. {1}'.format(index, header['label']))
  3187. for index, row in enumerate(rows, start=1):
  3188. lines.append('记录 {0}:'.format(index))
  3189. for header, value in zip(headers, row):
  3190. if isinstance(value, (dict, list)):
  3191. value = json.dumps(value, ensure_ascii=False)
  3192. lines.append('- {0}: {1}'.format(header['label'], value))
  3193. tips = content.get('tips') or []
  3194. if tips:
  3195. lines.append('提示:{0}'.format(';'.join(tips)))
  3196. if require_complete:
  3197. lines.append(
  3198. '展示完整性校验:已提供{0}条客户的全部{1}个字段。'.format(
  3199. len(rows), len(headers)
  3200. )
  3201. )
  3202. return '\n'.join(lines)
  3203. def _present_freightower_track(self, data, meta):
  3204. expected = {'schedule', 'ports', 'containers', 'tracks', 'terminal_plan'}
  3205. if set(data) != expected:
  3206. return self._format_error(meta)
  3207. schedule = self._freightower_object(data.get('schedule'), (
  3208. ('bl_number', '提单号'),
  3209. ('container_code', '柜号'),
  3210. ('carrier_name', '船公司'),
  3211. ('vessel', '船名'),
  3212. ('voyage', '航次'),
  3213. ('route_code', '航线'),
  3214. ('current_status', '当前状态'),
  3215. ('current_status_time', '当前状态时间'),
  3216. ('current_status_place', '当前状态地点'),
  3217. ('update_time', '数据更新时间'),
  3218. ('etd', '预计离港'),
  3219. ('atd', '实际离港'),
  3220. ('eta', '预计到达'),
  3221. ))
  3222. if schedule is None:
  3223. return self._format_error(meta)
  3224. ports = self._freightower_rows(data.get('ports'), (
  3225. ('place_type', '地点类型'),
  3226. ('port_name', '港口'),
  3227. ('terminal_name', '码头'),
  3228. ('etd', '预计离港'),
  3229. ('atd', '实际离港'),
  3230. ('eta', '预计到达'),
  3231. ('ata', '实际到达'),
  3232. ), {'place_type': ('起运港', '中转港', '目的港', '交货地')})
  3233. containers = self._freightower_rows(data.get('containers'), (
  3234. ('container_no', '箱号'),
  3235. ('container_type', '箱型'),
  3236. ('seal_no', '铅封号'),
  3237. ('current_status', '当前状态'),
  3238. ('off_load', '是否甩柜'),
  3239. ), {'off_load': ('', '是', '否')})
  3240. tracks = self._freightower_rows(data.get('tracks'), (
  3241. ('time', '时间'),
  3242. ('location', '地点'),
  3243. ('content', '内容'),
  3244. ('event_code', '状态代码'),
  3245. ('estimate_flag', '实际/预计'),
  3246. ('vessel_voyage', '船名航次'),
  3247. ('terminal_name', '码头'),
  3248. ), {'estimate_flag': ('实际', '预计')})
  3249. terminal_plan = self._freightower_object(data.get('terminal_plan'), (
  3250. ('port_name', '港口'),
  3251. ('terminal_name', '码头'),
  3252. ('open_time', '开港'),
  3253. ('close_time', '截港'),
  3254. ('etd', '预计离港'),
  3255. ('atd', '实际离港'),
  3256. ('shipping_agent', '船代'),
  3257. ))
  3258. if None in (ports, containers, tracks, terminal_plan):
  3259. return self._format_error(meta)
  3260. content = {
  3261. '船期': schedule,
  3262. '港口': ports,
  3263. '箱子': containers,
  3264. '轨迹': tracks,
  3265. '港区计划': terminal_plan,
  3266. }
  3267. lines = ['飞驼船期']
  3268. for label, value in schedule.items():
  3269. lines.append('- {0}: {1}'.format(label, value))
  3270. lines.extend(self._freightower_section('港口', ports, (
  3271. '地点类型', '港口', '码头', '预计离港', '实际离港', '预计到达', '实际到达',
  3272. )))
  3273. lines.extend(self._freightower_section('箱子', containers, (
  3274. '箱号', '箱型', '铅封号', '当前状态', '是否甩柜',
  3275. )))
  3276. lines.extend(self._freightower_section('轨迹', tracks, (
  3277. '时间', '地点', '内容', '状态代码', '实际/预计', '船名航次', '码头',
  3278. )))
  3279. if any(terminal_plan.values()):
  3280. lines.append('港区计划')
  3281. for label, value in terminal_plan.items():
  3282. lines.append('- {0}: {1}'.format(label, value))
  3283. else:
  3284. lines.append('港区计划')
  3285. lines.append('- 无')
  3286. return self._success_result(content, '\n'.join(lines), meta)
  3287. def _freightower_object(self, value, fields):
  3288. if not isinstance(value, dict) or set(value) != {key for key, _label in fields}:
  3289. return None
  3290. result = {}
  3291. for key, label in fields:
  3292. item = value.get(key)
  3293. if not isinstance(item, str):
  3294. return None
  3295. result[label] = item
  3296. return result
  3297. def _freightower_rows(self, rows, fields, choices):
  3298. if not isinstance(rows, list):
  3299. return None
  3300. keys = {key for key, _label in fields}
  3301. result = []
  3302. for row in rows:
  3303. if not isinstance(row, dict) or set(row) != keys:
  3304. return None
  3305. item = {}
  3306. for key, label in fields:
  3307. cell = row.get(key)
  3308. if not isinstance(cell, str):
  3309. return None
  3310. allowed = choices.get(key)
  3311. if allowed is not None and cell not in allowed:
  3312. return None
  3313. item[label] = cell
  3314. result.append(item)
  3315. return result
  3316. @staticmethod
  3317. def _freightower_section(title, rows, labels):
  3318. lines = [title]
  3319. if not rows:
  3320. lines.append('- 无')
  3321. return lines
  3322. for row in rows:
  3323. lines.append('- ' + ' '.join(row[label] for label in labels))
  3324. return lines
  3325. @staticmethod
  3326. def _success_result(content, text, meta):
  3327. return {
  3328. 'structured_content': content,
  3329. 'text': text,
  3330. 'is_error': False,
  3331. 'meta': meta,
  3332. }
  3333. @staticmethod
  3334. def _error_result(code, message, retryable, meta=None):
  3335. return {
  3336. 'structured_content': {
  3337. 'code': code,
  3338. 'message': message,
  3339. 'retryable': retryable,
  3340. },
  3341. 'text': '{0}: {1}'.format(code, message),
  3342. 'is_error': True,
  3343. 'meta': meta or {},
  3344. }
  3345. @classmethod
  3346. def _format_error(cls, meta=None):
  3347. return cls._error_result(
  3348. 'MCP_9001',
  3349. '工具返回格式异常',
  3350. True,
  3351. meta,
  3352. )