| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982 |
- import json
- import logging
- import math
- from urllib.parse import urlparse
- from constants import DEVICE_INVALID_MESSAGE
- logger = logging.getLogger(__name__)
- # Builds AI-safe MCP results for the explicitly supported tool set.
- class OutputPresenter:
- TABLE_TOOLS = frozenset((
- 'query_order_exact',
- 'query_track',
- 'query_customs_declaration_files',
- 'query_outbound_list',
- 'query_customer_list',
- ))
- PAYMENT_FOLLOWUP_TOOLS = frozenset(('query_customer_payment_followup',))
- PAYMENT_DETAIL_TOOLS = frozenset((
- 'query_customer_unverified_bill_details',
- ))
- PAYMENT_RECORD_TOOLS = frozenset(('query_customer_payment_records',))
- RECEIVABLE_COST_TOOLS = frozenset((
- 'query_order_receivable_cost_details',
- ))
- RECEIVABLE_LIST_TOOLS = frozenset(('query_receivable_cost_list',))
- RECEIVABLE_FILTER_TOOLS = frozenset((
- 'list_receivable_cost_filter_options',
- ))
- PAYABLE_COST_TOOLS = frozenset(('query_payable_cost_list',))
- PAYABLE_FILTER_TOOLS = frozenset(('list_payable_cost_filter_options',))
- PAYABLE_EXPORT_TOOLS = frozenset(('export_payable_cost_list',))
- DETAIL_TOOLS = frozenset(('query_outbound_detail',))
- ORDER_DETAIL_TOOLS = frozenset(('query_order_detail',))
- OPTION_TOOLS = frozenset((
- 'list_order_filter_options',
- 'list_outbound_filter_options',
- 'list_pending_outbound_export_filter_options',
- 'list_customer_filter_options',
- ))
- EXPORT_TOOLS = frozenset((
- 'export_pending_outbound_orders',
- 'export_out_of_province_port_data',
- 'export_receivable_cost_list',
- ))
- TASK_TOOLS = frozenset(('query_export_task',))
- SAFE_TOOLS = (
- TABLE_TOOLS | DETAIL_TOOLS | ORDER_DETAIL_TOOLS | PAYMENT_FOLLOWUP_TOOLS
- | PAYMENT_DETAIL_TOOLS | PAYMENT_RECORD_TOOLS | RECEIVABLE_COST_TOOLS
- | RECEIVABLE_LIST_TOOLS | RECEIVABLE_FILTER_TOOLS
- | PAYABLE_COST_TOOLS | PAYABLE_FILTER_TOOLS | PAYABLE_EXPORT_TOOLS
- | OPTION_TOOLS | EXPORT_TOOLS | TASK_TOOLS
- )
- ORDER_DETAIL_SECTIONS = {
- 'overview': '订单概览',
- 'packages': '箱单信息',
- 'package_items': '箱单商品',
- 'dw_auth': 'DW授权信息',
- 'attachments': '附件信息',
- 'inbound': '入库信息',
- 'checks': '查验信息',
- 'tracks': '订单轨迹',
- 'operation_logs': '操作日志',
- 'cost_logs': '应收与结算日志',
- 'delivery': '派送信息',
- 'all': '全部',
- }
- ORDER_DETAIL_FIELDS = {
- 'overview': {
- 'order_info': {
- 'order_number': '订单号', 'reference_number': '客户参考号',
- 'customer_name': '客户名称', 'departure_country': '起运国',
- 'destination_country': '目的国', 'package_method': '包装类型',
- 'product_name': '物流产品', 'forecast_pwv': '预报件重体',
- 'inbound_pwv': '入库件重体',
- 'receivable_charge_weight': '应收计费重/体积',
- 'settlement_charge_weight': '结算计费重/体积',
- 'declaration_type': '报关类型', 'pre_recording': '是否需要预录单',
- 'idcard_name': '企业/个人姓名',
- 'idcard_number': '社会信用代码/身份证号',
- 'outbound_number': '排舱单号', 'container_mode': '直送柜/拼柜',
- 'track_map_available': '是否可查看轨迹地图', 'insurance': '购买保险',
- 'delivery_way': '派送方式', 'return_shipping_surcharge': '退运附加',
- 'work_order_count': '工单数量', 'bill_remark': '账单备注',
- 'remark': '订单备注',
- },
- 'freight_info': {
- 'estimated_inbound_time': '预计入库时间', 'cargo_type': '货物类型',
- 'pickup_way': '交货方式', 'warehouse': '交货仓库',
- 'pickup_address': '提货地址', 'pickup_contact': '提货联系人',
- 'pickup_phone': '提货联系电话', 'delivery_type': '派送类型',
- 'delivery_address': '派送地址', 'delivery_remark': '派送备注',
- 'oversea_warehouse': '海外仓',
- },
- 'package_summary': {
- 'box_count': '箱数', 'total_weight': '重量', 'weight_unit': '重量单位',
- 'total_volume': '体积', 'sku_count': 'SKU数量',
- 'clearance_total_price': '清关总价', 'clearance_currency': '清关币种',
- 'purchase_total_price': '采购总价', 'purchase_currency': '采购币种',
- },
- 'trader_info': {
- 'exporter': '出口商', 'importer': '进口商',
- 'coo_required': '是否做产地证',
- },
- },
- 'packages': {
- 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
- 'sku_summary': 'SKU', 'product_name_summary': '商品名',
- 'box_quantity': '箱数', 'box_length_cm': '单箱长(CM)',
- 'box_width_cm': '单箱宽(CM)', 'box_height_cm': '单箱高(CM)',
- 'gross_weight_kg': '单箱毛重量(KG)', 'net_weight_kg': '单箱净重量(KG)',
- 'is_over_length': '长度是否超限', 'is_over_width': '宽度是否超限',
- 'is_over_height': '高度是否超限', 'is_over_weight': '重量是否超限',
- },
- 'package_items': {
- 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
- 'box_specification': '箱规', 'box_specification_unit': '箱规单位',
- 'package_gross_weight_kg': '箱单单箱毛重(KG)',
- 'package_net_weight_kg': '箱单单箱净重(KG)',
- 'inspection_result': '查验结果', 'exception_reason': '异常原因',
- 'inspection_photo_count': '查验图片数量', 'sku': 'SKU',
- 'units_per_box': '单箱个数', 'declaration_type': '报关类型',
- 'box_number': '箱号', 'item_gross_weight_kg': '商品单箱毛重量(KG)',
- 'item_net_weight_kg': '商品单箱净重量(KG)', 'chinese_name': '中文品名',
- 'english_name': '英文名称', 'brand_type': '品牌类型', 'brand': '品牌',
- 'model': '型号', 'material_cn': '材质(CN)', 'material_en': '材质(EN)',
- 'purpose_cn': '用途', 'goods_attributes': '商品属性',
- 'declaration_hs_code': '报关编码', 'clearance_hs_code': '清关编码',
- 'material_ratio': '材质占比', 'clearance_unit_price': '清关单价',
- 'clearance_currency': '清关币种', 'purchase_unit_price': '采购单价',
- 'purchase_currency': '采购币种', 'product_image_count': '商品图片数量',
- 'remark': '备注',
- },
- 'dw_auth': {
- 'fba_id': 'FBAID', 'dw_start': 'DW开始时间', 'dw_end': 'DW结束时间',
- 'dw_display': 'DW', 'authorization_status': '客户授权状态',
- },
- 'attachments': {
- 'category': '附件分类', 'file_name': '文件名称',
- 'file_extension': '文件类型', 'is_image': '是否图片',
- 'preview_url': '预览链接', 'download_url': '下载链接',
- 'cost_name': '收费项目',
- },
- 'inbound_summary': {
- 'inbound_status': '入库状态', 'inbound_time': '入库时间',
- 'inbound_operator': '操作人', 'warehouse': '仓库',
- 'abnormal_reason': '异常原因', 'inbound_photo_count': '入库图片数量',
- 'forecast_pwv_summary': '预报件重体', 'inbound_pwv_summary': '入库件重体',
- },
- 'inbound': {
- 'has_label': '是否贴标', 'shipment_id': 'SHIPMENT ID',
- 'inbound_quantity': '入库件数',
- 'measurement_photo_count': '测量图片数量',
- 'box_specification': '入库箱规', 'weight_mode': None, 'weight': None,
- 'weight_unit': '重量单位', 'is_over_length': '长度是否超限',
- 'is_over_width': '宽度是否超限', 'is_over_height': '高度是否超限',
- 'is_over_weight': '重量是否超限', 'operated_at': '操作时间',
- },
- 'checks': {
- 'shipment_id': '货件编号', 'sku': 'SKU', 'box_number': '箱号',
- 'box_quantity': '箱数', 'box_specification': '箱规',
- 'inspection_result': '查验结果',
- 'inspection_photo_count': '查验图片数量', 'remark': '备注',
- 'inspector': '查验人', 'inspected_at': '查验时间',
- },
- 'tracks': {
- 'track_type': '轨迹类型', 'status': '轨迹节点', 'location': '轨迹地点',
- 'occurred_at': '时间', 'tracking_number': '跟踪号',
- 'shipment_id': 'SHIPMENT ID', 'content': '轨迹内容',
- },
- 'operation_logs': {
- 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
- },
- 'cost_logs': {
- 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
- },
- 'delivery_summary': {
- 'master_tracking_number': '主跟踪号', 'sub_order_count': '子单数量',
- },
- 'delivery': {'sub_tracking_number': '子跟踪号'},
- }
- ORDER_DETAIL_STATUS_FIELDS = {
- 'stage': '阶段', 'label': '节点', 'state': '状态',
- 'occurred_at': '时间', 'time_kind': '时间类型',
- }
- ORDER_DETAIL_STATES = {
- 'completed': '已完成', 'in_progress': '进行中',
- 'pending': '待完成', 'hidden': '不展示',
- }
- ORDER_DETAIL_TIME_KINDS = {
- 'actual': '实际', 'estimated': '预计', 'empty': '暂无',
- }
- TABLE_COLUMNS = {
- 'query_order_exact': {
- 'order_number': ('订单号',),
- 'reference_number': ('客户参考号',),
- 'status_txt_name': ('状态',),
- 'check_status_txt_name': ('是否已查验',),
- 'customer_name': ('客户名称',),
- 'customer_account_type_name': ('客户属性',),
- 'inbound_date': ('入库时间',),
- 'wo_num': ('未完成工单',),
- 'product_name': ('物流产品',),
- 'inbound_pieces': ('件数',),
- 'inbound_volume': ('体积(CBM)',),
- 'inbound_weight': ('重量(KG)',),
- 'pro_cn_name': ('品名',),
- 'export_declaration_type': ('报关方式',),
- 'merge_declare_number': ('合并报关单号',),
- 'delivery_address': ('派送地址',),
- 'container_code': ('柜号',),
- 'out_status_txt': ('排舱单状态',),
- 'hinge_of_destination': ('目的港',),
- 'etd': ('ETD',),
- 'atd': ('ATD',),
- 'eta': ('ETA',),
- 'ata': ('ATA',),
- 'release_time': ('清关放行时间',),
- 'oversea_inbound_date': ('海外入库时间',),
- 'appt_time': ('APPT时间',),
- 'est_loading_time': ('预计装柜时间',),
- 'pickup_time': ('海外提柜时间',),
- 'delivery_way_title': ('派送方式',),
- 'tracking_number': ('快递单号', '承运商跟踪号码'),
- 'shipment_id': ('Shipment ID',),
- 'goods_attribute': ('商品属性',),
- 'sku': ('SKU',),
- 'sales_user': ('商务经理',),
- 'service_user': ('客户经理',),
- 'department_name': ('事业部',),
- 'remark': ('订单备注',),
- 'importer_name': ('进口商',),
- 'warehouse_name': ('交货仓库',),
- 'paid_status_name': ('付款状态',),
- },
- 'query_track': {
- 'status': ('轨迹节点', '轨迹状态,如:开始集港、离港放行、清关、配送等'),
- 'location': ('轨迹地点', '发生地点'),
- 'time': ('时间', '轨迹发生时间(已转换为用户时区)'),
- 'content': ('轨迹内容', '详细描述'),
- 'tracking_number': ('跟踪号', '快递单号'),
- 'shipment_id': ('Shipment ID', '包裹ID'),
- },
- 'query_customs_declaration_files': {
- 'outbound_number': ('排舱单号',),
- 'order_number': ('订单号',),
- 'file_name': ('文件名',),
- 'file_type': ('文件类型',),
- 'file_url': ('文件链接',),
- },
- 'query_outbound_list': {
- 'outbound_number': ('排舱单号',),
- 'direct_send': ('直送柜',),
- 'remark': ('备注',),
- 'cargo_type': ('超长超重',),
- 'warehouse_name': ('集货仓库',),
- 'status': ('状态',),
- 'so_number': ('SO号',),
- 'container_code': ('柜号',),
- 'seal_number': ('封条号',),
- 'container_type': ('柜型',),
- 'shipping_method': ('运输方式',),
- 'total_volume': ('体积(CBM)',),
- 'total_weight': ('重量(KG)',),
- 'ship_schedule': ('船期',),
- 'closing_time': ('截关时间',),
- 'est_loading_time': ('预计装柜时间',),
- 'operator': ('操作人',),
- 'operation_modes': ('拖报清方式',),
- 'operation_time': ('操作时间',),
- 'ship_company': ('船司',),
- 'vessel_name': ('船名航次',),
- 'cutoff_time_si': ('截SI时间',),
- 'clearance_port': ('清关口岸',),
- 'loading_port': ('起运港',),
- 'destination_port': ('目的港',),
- 'transit_port': ('中转港',),
- 'etd': ('ETD',),
- 'eta': ('ETA',),
- 'has_fda': ('是否含FDA认证商品',),
- 'has_cpsc': ('是否含CPSC商品',),
- 'has_food': ('是否含食品',),
- },
- 'query_outbound_detail': {
- 'order_number': ('订单号',),
- 'cargo_type': ('超长超重',),
- 'customs_files': ('报关资料',),
- 'reference_number': ('客户参考号',),
- 'customer_name': ('客户名称',),
- 'declaration_type': ('报关方式',),
- 'merge_declare_number': ('合并报关单号',),
- 'order_remark': ('订单备注',),
- 'bl_number': ('提单号',),
- 'container_code': ('柜号',),
- 'customer_service': ('客户经理',),
- 'est_inbound_date': ('预计入库时间',),
- 'inbound_date': ('实际入库时间',),
- 'status': ('状态',),
- 'pieces': ('预报件数 / 入库件数',),
- 'weight': ('预报实重(KG) / 入库实重(KG)',),
- 'volume': ('预报体积(m³) / 入库体积(m³)',),
- 'pickup_place': ('交货地',),
- 'product_name': ('物流产品',),
- 'goods_name': ('品名',),
- 'closing_time': ('截关时间',),
- 'clearance_remark': ('报关备注',),
- 'import_clearance_remark': ('清关备注',),
- 'delivery_address': ('派送地址',),
- 'delivery_type': ('派送类型',),
- 'delivery_way': ('派送方式',),
- 'channel': ('派送渠道',),
- 'country_name': ('目的国',),
- 'importer_name': ('进口商',),
- 'vat_type': ('清关税号',),
- 'packing_type': ('货物类型',),
- 'is_abnormal': ('是否问题件',),
- 'package_method': ('包装类型',),
- 'order_reply': ('到货回复',),
- 'is_must_load': ('订单是否必装',),
- 'has_fda': ('是否含FDA认证商品',),
- 'has_cpsc': ('是否含CPSC商品',),
- 'has_food': ('是否含食品',),
- },
- 'query_customer_list': {
- 'customer_name': ('客户名称',),
- 'customer_code': ('客户代码',),
- 'create_time': ('开户时间',),
- 'business_type': ('业务类型',),
- 'customer_attribute': ('客户属性',),
- 'customer_source': ('客户来源',),
- 'first_inbound_date': ('首次成交时间',),
- 'last_inbound_date': ('最后一次走货时间',),
- 'active_status': ('活跃状态',),
- 'contract_status': ('合同状态',),
- 'contract_validity': ('合同有效期',),
- 'credit_limit': ('信用额度',),
- 'currency_code': ('结算币种',),
- 'billing_modes': ('结算模式(分业务类型)',),
- 'sales_name': ('商务经理',),
- 'merchandiser_name': ('客户经理',),
- 'department_name': ('事业部',),
- },
- }
- PAYMENT_FOLLOWUP_COLUMNS = {
- 'customer_name': '客户名称',
- 'settlement_currency': '结算币种',
- 'billed_unverified_amount': '已出账未核销金额',
- 'unbilled_amount': '未出账金额',
- 'overdue_unpaid_amount': '逾期未回款金额',
- 'billed_unverified_amount_cny': '已出账未核销金额(人民币)',
- 'unbilled_amount_cny': '未出账金额(人民币)',
- 'overdue_unpaid_amount_cny': '逾期未回款金额(人民币)',
- 'unverified_receivable_monthly_summary': '未回款月份汇总',
- 'receipt_unverified_amount': '收款单未核销金额',
- 'current_balance': '当前余额',
- 'credit_limit': '信用额度',
- 'bad_debt_total': '坏账合计',
- 'contract_status': '合同状态',
- }
- PAYMENT_FOLLOWUP_DETAIL_COLUMNS = {
- 'bill_month': '账单月份',
- 'bill_no': '账单号',
- 'business_type': '业务类型',
- 'settlement_mode': '结算模式',
- 'unverified_amount': '未核销金额',
- 'customer_receivable_date': '客户应收款日期',
- }
- PAYMENT_RECORD_COLUMNS = {
- 'customer_name': '客户名称',
- 'payment_reference': '收款水单号',
- 'original_received_amount': '原币到账金额',
- 'actual_received_amount': '实际收款金额',
- 'receive_date': '收款日期',
- 'verified_amount': '已核销金额',
- 'unverified_amount': '未核销金额',
- 'payment_approval_status': '收款审核状态',
- }
- RECEIVABLE_COST_COLUMNS = {
- 'order_number': '订单号',
- 'customer_name': '客户名称',
- 'cost_name': '费用项',
- 'cost_customer_name': '费用客户',
- 'charge_weight': '计费重',
- 'unit_price': '计费单价',
- 'quote_currency': '原币币种',
- 'receivable_original_amount': '应收原币',
- 'receivable_amount_cny': '应收金额(CNY)',
- 'settlement_amount_cny': '结算金额(CNY)',
- 'cost_confirmation_status': '费用确认状态',
- 'closing_status': '关账状态',
- 'verification_status': '核销状态',
- }
- RECEIVABLE_LIST_COLUMNS = {
- 'main_customer_name': '主客户',
- 'sub_customer_name': '子客户',
- 'customer_attribute': '客户属性',
- 'department_name': '事业部',
- 'document_type': '单据类型',
- 'warehouse_name': '仓库',
- 'business_number': '业务单号',
- 'reference_number': '参考号',
- 'cost_name': '费用项',
- 'original_amount': '原币金额',
- 'total_amount': '总金额',
- 'billed_amount': '已出账金额',
- 'unbilled_amount': '未出账金额',
- 'bill_number': '账单编号',
- 'verification_status': '核销状态',
- 'receipt_number': '收款水单号',
- 'receipt_date': '收款日期',
- 'sales_name': '商务经理',
- 'merchandiser_name': '客户经理',
- 'drainage_user_name': '引流人',
- 'first_leg_order_status': '头程订单状态',
- 'settlement_mode': '结算模式',
- 'cost_occurred_at': '费用发生时间',
- 'business_occurred_at': '业务发生时间',
- }
- PAYABLE_COST_COLUMNS = {
- 1: (
- ('number', '单号'), ('so_number', 'SO号'), ('container_code', '柜号'),
- ('bl_number', '提单号'), ('sub_number', '订单号'),
- ('business_node_name', '业务节点'), ('providers_name', '物流商'),
- ('cost_name', '费用名称'), ('payable_cost_q', '金额'), ('currency', '币种'),
- ('company_money_q', '本位币金额'), ('yf_lock', '应付锁定'),
- ('trade_date', '费用发生时间'), ('verify_status_text', '核销状态'),
- ('remark', '备注'), ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
- ),
- 2: (
- ('number', '单号'), ('sub_number', '跟踪单号'), ('workorder_number', '工单号'),
- ('order_type_name', '单据类型'), ('providers_name', '物流商'),
- ('cost_name', '费用名称'), ('payable_cost_q', '应付原币金额'),
- ('currency', '应付原币币种'), ('company_money_q', '本位币金额%s'),
- ('yf_lock', '应付锁定'), ('business_date', '业务发生时间'),
- ('trade_date', '费用发生时间'), ('create_date', '操作时间'),
- ('verify_status_text', '核销状态'), ('remark', '备注'),
- ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
- ),
- 3: (
- ('number', '单号'), ('order_status_text', '包裹状态'),
- ('providers_name', '物流商'), ('business_node_name', '费用业务节点'),
- ('cost_name', '费用名称'), ('detail_price', '计费单价'),
- ('charge_weight', '计费重'), ('quote_cost', '计费金额'),
- ('payable_cost_q', '实际应付金额'), ('quote_currency', '原币币种'),
- ('company_money_q', '计费本位币金额'), ('yf_lock', '应付锁定'),
- ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
- ('trade_date', '费用发生时间'), ('verify_status_text', '核销状态'),
- ('remark', '财务备注'), ('create_user_name', '操作人'), ('create_date', '录入时间'),
- ),
- 4: (
- ('number', '订单号'), ('business_bill_no', '货代账单号'),
- ('providers_name', '物流商'), ('cost_name', '费用名称'),
- ('payable_cost_q', '金额'), ('currency', '币种'),
- ('company_money_q', '本位币金额'), ('department_name', '事业部'),
- ('yf_lock', '应付锁定'), ('trade_date', '费用发生时间'),
- ('verify_status_text', '核销状态'), ('business_node_name', '业务节点'),
- ('remark', '备注'), ('bill_no', '应付账单编号'),
- ('payment_order_number', '付款单号'),
- ),
- 5: (
- ('order_type_name', '单据类型'), ('number', '订单号'), ('warehouse_name', '仓库'),
- ('business_node_name', '业务节点'), ('providers_name', '物流商'),
- ('cost_name', '费用名称'), ('payable_cost_q', '金额'), ('currency', '币种'),
- ('company_money_q', '本位币金额'), ('yf_lock', '应付锁定'),
- ('trade_date', '费用发生时间'), ('verify_status_text', '核销状态'),
- ('remark', '备注'), ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
- ),
- 7: (
- ('number', '订单号'), ('ep_order_status_text', '订单状态'),
- ('business_node_name', '业务节点'), ('providers_name', '物流商'),
- ('cost_name', '费用名称'), ('detail_price', '计费单价'),
- ('charge_weight', '计费重'), ('quote_cost', '计费金额'),
- ('payable_cost_q', '实际应付金额'), ('quote_currency', '原币币种'),
- ('company_money_q', '本位币金额'), ('trade_date', '费用发生时间'),
- ('remark', '备注'), ('verify_status_text', '核销状态'),
- ('bill_no', '账单编号'), ('payment_order_number', '付款单号'),
- ('create_user_name', '操作人'), ('create_date', '录入时间'),
- ),
- }
- PAYABLE_AMOUNT_KEYS = frozenset((
- 'detail_price', 'charge_weight', 'quote_cost', 'payable_cost_q', 'company_money_q',
- ))
- PAYMENT_FOLLOWUP_MONTHLY_COLUMNS = {
- 'receivable_month': '应收月份',
- 'unverified_amount': '未核销金额',
- 'is_overdue': '是否逾期',
- }
- OUTBOUND_DETAIL_SUMMARY = {
- 'bl_number': '提单号',
- 'container_code': '柜号',
- 'container_type': '柜型',
- 'total_volume': '总体积',
- 'total_weight': '总重量',
- 'total_pieces': '总件数',
- 'sku': 'SKU',
- 'buy_declaration_count': '买单报关数量',
- 'general_declaration_count': '一般贸易报关数量',
- 'must_load': '必装单量/体积',
- 'backup_load': '备装单量/体积',
- }
- FIELD_LABELS = {
- 'query_order_exact': {
- 'order_number': '订单号',
- 'order_numbers': '订单号',
- 'reference_number': '客户参考号',
- 'reference_numbers': '客户参考号',
- 'tracking_number': '快递单号',
- 'tracking_numbers': '快递单号',
- 'outbound_number': '排舱单号',
- 'outbound_numbers': '排舱单号',
- 'container_code': '柜号',
- 'container_codes': '柜号',
- 'so_number': 'SO号',
- 'so_numbers': 'SO号',
- 'shipment_id': 'Shipment ID',
- 'receiver_country': '收货国家',
- 'product_ids': '物流产品',
- 'customer_ids': '客户',
- 'sales_id': '销售人员',
- 'warehouse_ids': '仓库',
- 'department_id': '事业部',
- 'inbound_date_start': '入库开始日期',
- 'inbound_date_end': '入库结束日期',
- 'outbound_date_start': '出库开始日期',
- 'outbound_date_end': '出库结束日期',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_track': {
- 'order_id': '订单ID',
- 'order_number': '订单号',
- 'tracking_number': '快递单号',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_customs_declaration_files': {
- 'outbound_numbers': '排舱单号',
- 'order_numbers': '订单号',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_outbound_list': {
- 'outbound_numbers': '排舱单号',
- 'order_numbers': '订单号',
- 'container_codes': '柜号',
- 'so_numbers': 'SO号',
- 'bl_numbers': '提单号',
- 'outbound_status': '排舱状态',
- 'shipping_method': '运输方式',
- 'warehouse_id': '集货仓库',
- 'is_direct_send': '是否直送柜',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_outbound_detail': {
- 'outbound_number': '排舱单号',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_order_detail': {
- 'order_number': '订单号', 'section': '详情模块',
- 'page': '页码', 'limit': '每页数量',
- },
- 'list_order_filter_options': {
- 'filter_type': '筛选项类型',
- 'keyword': '关键词',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'list_outbound_filter_options': {
- 'filter_type': '筛选类别',
- 'keyword': '显示名称',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'list_pending_outbound_export_filter_options': {
- 'filter_type': '筛选项类型',
- 'product_type_id': '产品分类',
- 'keyword': '关键词',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_customer_list': {
- 'customer_id': '客户名称',
- 'department_id': '事业部',
- 'sales_id': '商务经理',
- 'merchandiser_id': '客户经理',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_customer_payment_followup': {
- 'customer_id': '客户名称',
- 'department_id': '事业部',
- 'sales_id': '商务经理',
- 'merchandiser_id': '客户经理',
- 'has_unverified_receivable_only': '只看有应收未核销费用的客户',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'query_customer_unverified_bill_details': {
- 'customer_id': '客户名称',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'list_customer_filter_options': {
- 'filter_type': '筛选项类型',
- 'keyword': '关键词',
- 'page': '页码',
- 'limit': '每页数量',
- },
- 'export_pending_outbound_orders': {
- 'number': '单号',
- 'product_type_id': '产品分类',
- 'product_id': '物流产品',
- 'order_warehouse_id': '集货仓库',
- 'receiver_country': '目的国',
- 'is_remove': '是否装柜剔除',
- 'address': '派送地址',
- 'inbound_date': '入库时间',
- 'status': '订单状态',
- 'merge_declare_number': '合并报关单号',
- 'importer_id': '进口商',
- 'packing_type': '货物类型',
- 'is_battery': '带电属性',
- 'is_magnetic': '带磁属性',
- 'is_wood': '带木属性',
- 'is_other': '其他商品属性',
- 'is_fda': 'FDA产品属性',
- 'is_toy': '玩具属性',
- 'is_ultra_limit': '超长超重属性',
- 'is_sensitive': '敏感货属性',
- 'is_food': '食品属性',
- 'no_property': '无属性',
- },
- 'export_out_of_province_port_data': {
- 'outbound_numbers': '排舱单号',
- 'container_codes': '柜号',
- 'bl_numbers': '提单号',
- 'so_numbers': 'SO号',
- 'file_type': '资料类型',
- },
- 'export_receivable_cost_list': {
- 'reference_numbers': '参考号',
- 'tracking_numbers': '跟踪号',
- 'order_numbers': '订单号',
- 'bill_numbers': '账单编号',
- 'business_date_start': '业务发生开始日期',
- 'business_date_end': '业务发生结束日期',
- 'customer_id': '主客户',
- 'sub_customer_id': '子客户',
- 'billing_status': '出账状态',
- 'verification_status': '核销状态',
- 'document_type': '单据类型',
- 'cost_type_id': '费用项',
- },
- 'query_export_task': {
- 'task_ref': '导出任务引用',
- },
- }
- ERROR_MESSAGES = {
- 'MCP_1101': '设备配置已失效,请重新生成配置',
- 'MCP_1102': '设备会话已过期,请重新连接',
- 'MCP_1103': '员工账号不可用,请联系管理员',
- 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
- 'MCP_1201': '工具当前不可用',
- 'MCP_1202': '工具当前不可用',
- 'MCP_1301': '没有权限使用此工具',
- 'MCP_1501': '目标数据不可用',
- 'MCP_1502': '结果过多,请缩小查询范围',
- 'MCP_1601': '没有可导出的数据',
- 'MCP_9001': '工具调用失败,请稍后重试',
- }
- NON_RETRYABLE_CODES = frozenset((
- 'MCP_1101',
- 'MCP_1102',
- 'MCP_1103',
- 'MCP_1104',
- 'MCP_1201',
- 'MCP_1202',
- 'MCP_1301',
- 'MCP_1401',
- 'MCP_1501',
- 'MCP_1502',
- 'MCP_1601',
- ))
- def handles(self, tool_name):
- return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
- # Convert a backend envelope into text and structured display data.
- def present(self, tool_name, tool_result):
- if not self.handles(tool_name) or not isinstance(tool_result, dict):
- return self._format_error()
- code = str(tool_result.get('code') or '').strip()
- meta = self._build_meta(tool_result.get('meta'))
- if code not in ('MCP_0000', '0'):
- return self._business_error(
- tool_name,
- code or 'MCP_9001',
- tool_result.get('msg'),
- meta,
- )
- data = tool_result.get('data')
- if not isinstance(data, dict):
- return self._format_error(meta)
- if tool_name in self.DETAIL_TOOLS:
- return self._present_outbound_detail(
- tool_name,
- data,
- tool_result.get('meta'),
- meta,
- )
- if tool_name in self.ORDER_DETAIL_TOOLS:
- return self._present_order_detail(data, tool_result.get('meta'), meta)
- if tool_name in self.PAYMENT_FOLLOWUP_TOOLS:
- return self._present_customer_payment_followup(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.PAYMENT_DETAIL_TOOLS:
- return self._present_customer_unverified_bill_details(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.PAYMENT_RECORD_TOOLS:
- return self._present_customer_payment_records(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.RECEIVABLE_COST_TOOLS:
- return self._present_order_receivable_cost_details(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.RECEIVABLE_LIST_TOOLS:
- return self._present_receivable_cost_list(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.RECEIVABLE_FILTER_TOOLS:
- return self._present_receivable_cost_filter_options(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.PAYABLE_COST_TOOLS:
- return self._present_payable_cost_list(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.PAYABLE_FILTER_TOOLS:
- return self._present_receivable_cost_filter_options(
- data, tool_result.get('meta'), meta
- )
- if tool_name in self.TABLE_TOOLS:
- return self._present_table(
- tool_name,
- data,
- tool_result.get('meta'),
- meta,
- )
- if tool_name in self.OPTION_TOOLS:
- if tool_name == 'list_customer_filter_options':
- return self._present_customer_options(
- data, tool_result.get('meta'), meta
- )
- return self._present_options(data, tool_result.get('meta'), meta)
- if tool_name in self.EXPORT_TOOLS:
- return self._present_export_submission(data, meta)
- if tool_name in self.PAYABLE_EXPORT_TOOLS:
- return self._present_export_submission(data, meta)
- return self._present_export_task(data, meta)
- def _present_order_detail(self, data, raw_meta, meta):
- if set(data) != {'section', 'order_number', 'payload'}:
- return self._format_error(meta)
- section = data.get('section')
- order_number = data.get('order_number')
- payload = data.get('payload')
- if (
- section not in self.ORDER_DETAIL_SECTIONS
- or not isinstance(order_number, str) or not order_number.strip()
- or not isinstance(payload, dict)
- ):
- return self._format_error(meta)
- content = {
- '订单号': order_number.strip(),
- '详情模块': self.ORDER_DETAIL_SECTIONS[section],
- }
- if section == 'all':
- all_content = self._present_order_detail_all(payload)
- if all_content is None:
- return self._format_error(meta)
- content.update(all_content)
- elif section == 'overview':
- expected = {
- 'status_nodes', 'order_info', 'freight_info',
- 'package_summary', 'trader_info',
- }
- if set(payload) != expected or not isinstance(payload['status_nodes'], list):
- return self._format_error(meta)
- nodes = []
- for row in payload['status_nodes']:
- translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
- if translated is None:
- return self._format_error(meta)
- state = row.get('state')
- time_kind = row.get('time_kind')
- if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
- return self._format_error(meta)
- translated['状态'] = self.ORDER_DETAIL_STATES[state]
- translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
- nodes.append(translated)
- content['状态节点'] = nodes
- for raw_key, chinese_key in (
- ('order_info', '订单信息'), ('freight_info', '货运信息'),
- ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
- ):
- translated = self._translate_exact(
- payload.get(raw_key),
- self.ORDER_DETAIL_FIELDS['overview'][raw_key],
- )
- if translated is None:
- return self._format_error(meta)
- content[chinese_key] = translated
- elif section == 'inbound':
- if set(payload) != {'summary', 'records'}:
- return self._format_error(meta)
- summary = self._translate_exact(
- payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
- )
- records = self._translate_order_detail_rows(section, payload.get('records'))
- if summary is None or records is None:
- return self._format_error(meta)
- content['入库概况'] = summary
- content['明细'] = records
- pagination = self._order_detail_pagination(raw_meta)
- if pagination is None:
- return self._format_error(meta)
- content['分页'] = pagination
- elif section == 'delivery':
- if set(payload) != {'summary', 'records'}:
- return self._format_error(meta)
- summary = self._translate_exact(
- payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
- )
- records = self._translate_order_detail_rows(section, payload.get('records'))
- if summary is None or records is None:
- return self._format_error(meta)
- content['派送汇总'] = summary
- content['明细'] = records
- pagination = self._order_detail_pagination(raw_meta)
- if pagination is None:
- return self._format_error(meta)
- content['分页'] = pagination
- else:
- if set(payload) != {'records'}:
- return self._format_error(meta)
- records = self._translate_order_detail_rows(section, payload.get('records'))
- pagination = self._order_detail_pagination(raw_meta)
- if records is None or pagination is None:
- return self._format_error(meta)
- content['明细'] = records
- content['分页'] = pagination
- text = json.dumps(content, ensure_ascii=False, indent=2)
- return self._success_result(content, text, meta)
- def _present_order_detail_all(self, payload):
- expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
- if set(payload) != expected_sections:
- return None
- overview = payload.get('overview')
- if not isinstance(overview, dict) or set(overview) != {
- 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
- } or not isinstance(overview['status_nodes'], list):
- return None
- overview_content = {'状态节点': []}
- for row in overview['status_nodes']:
- translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
- if translated is None:
- return None
- state = row.get('state')
- time_kind = row.get('time_kind')
- if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
- return None
- translated['状态'] = self.ORDER_DETAIL_STATES[state]
- translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
- overview_content['状态节点'].append(translated)
- for raw_key, chinese_key in (
- ('order_info', '订单信息'), ('freight_info', '货运信息'),
- ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
- ):
- translated = self._translate_exact(
- overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
- )
- if translated is None:
- return None
- overview_content[chinese_key] = translated
- result = {'订单概览': overview_content}
- for section, label in self.ORDER_DETAIL_SECTIONS.items():
- if section in ('overview', 'all'):
- continue
- translated = self._present_order_detail_all_section(section, payload.get(section))
- if translated is None:
- return None
- result[label] = translated
- return result
- def _present_order_detail_all_section(self, section, payload):
- if not isinstance(payload, dict) or 'pagination' not in payload:
- return None
- pagination = self._order_detail_pagination(payload.get('pagination'))
- if pagination is None:
- return None
- if section == 'inbound':
- if set(payload) != {'summary', 'records', 'pagination'}:
- return None
- summary = self._translate_exact(
- payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
- )
- records = self._translate_order_detail_rows(section, payload.get('records'))
- if summary is None or records is None:
- return None
- return {'入库概况': summary, '明细': records, '分页': pagination}
- if section == 'delivery':
- if set(payload) != {'summary', 'records', 'pagination'}:
- return None
- summary = self._translate_exact(
- payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
- )
- records = self._translate_order_detail_rows(section, payload.get('records'))
- if summary is None or records is None:
- return None
- return {'派送汇总': summary, '明细': records, '分页': pagination}
- if set(payload) != {'records', 'pagination'}:
- return None
- records = self._translate_order_detail_rows(section, payload.get('records'))
- if records is None:
- return None
- return {'明细': records, '分页': pagination}
- def _translate_order_detail_rows(self, section, records):
- if not isinstance(records, list):
- return None
- mapping = self.ORDER_DETAIL_FIELDS.get(section)
- if not isinstance(mapping, dict):
- return None
- translated_rows = []
- for row in records:
- translated = self._translate_exact(row, mapping)
- if translated is None:
- return None
- if section == 'inbound':
- mode = row.get('weight_mode')
- if mode not in ('single_box', 'total'):
- return None
- translated[
- '单箱入库重量' if mode == 'single_box' else '总重量KG'
- ] = row.get('weight', '')
- translated_rows.append(translated)
- return translated_rows
- @staticmethod
- def _translate_exact(value, mapping):
- if not isinstance(value, dict) or set(value) != set(mapping):
- return None
- result = {}
- for key, label in mapping.items():
- if label is None:
- continue
- item = value.get(key, '')
- if isinstance(item, (dict, list)):
- return None
- result[label] = '' if item is None else item
- return result
- @staticmethod
- def _order_detail_pagination(raw_meta):
- if not isinstance(raw_meta, dict):
- return None
- if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
- return None
- page = raw_meta.get('page')
- limit = raw_meta.get('limit')
- has_more = raw_meta.get('has_more')
- if isinstance(page, bool) or not isinstance(page, int) or page < 1:
- return None
- if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
- return None
- if not isinstance(has_more, bool):
- return None
- return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
- # Map local tool exceptions without exposing internal error details.
- def present_exception(self, tool_name, exception):
- if not self.handles(tool_name):
- return self._format_error()
- message = str(exception or '').strip()
- if isinstance(exception, ValueError):
- label = self._find_field_label(tool_name, message)
- return self._error_result(
- 'MCP_1401',
- self._parameter_message(label),
- False,
- )
- if message == DEVICE_INVALID_MESSAGE:
- return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
- if message.lower().startswith('tool disabled'):
- return self._error_result('MCP_1202', '工具当前不可用', False)
- return self._error_result(
- 'MCP_9001',
- '工具调用失败,请稍后重试',
- True,
- )
- def _present_table(self, tool_name, data, raw_meta, meta):
- columns = data.get('columns')
- records = data.get('records')
- if not isinstance(columns, list) or not columns or not isinstance(records, list):
- return self._format_error(meta)
- allowed_columns = self.TABLE_COLUMNS.get(tool_name)
- if not isinstance(allowed_columns, dict):
- return self._format_error(meta)
- if tool_name == 'query_customer_list':
- expected = list(allowed_columns.keys())
- actual = [
- column.get('key') if isinstance(column, dict) else None
- for column in columns
- ]
- if actual != expected or self._customer_pagination(raw_meta) is None:
- return self._format_error(meta)
- headers = []
- keys = []
- for column in columns:
- if not isinstance(column, dict):
- return self._format_error(meta)
- key = column.get('key')
- label = column.get('name')
- if not isinstance(key, str) or not key.strip():
- return self._format_error(meta)
- if not isinstance(label, str) or not label.strip():
- return self._format_error(meta)
- key = key.strip()
- definition = allowed_columns.get(key)
- if not isinstance(definition, tuple) or not definition:
- return self._format_error(meta)
- keys.append(key)
- header = {'label': definition[0]}
- if len(definition) > 1:
- header['description'] = definition[1]
- headers.append(header)
- rows = []
- for record in records:
- if not isinstance(record, dict):
- return self._format_error(meta)
- if tool_name == 'query_customer_list' and set(record) != set(keys):
- return self._format_error(meta)
- row = []
- for key in keys:
- value = '' if record.get(key) is None else record.get(key, '')
- if tool_name == 'query_customer_list' and key == 'billing_modes':
- value = self._customer_billing_modes(value)
- if value is None:
- return self._format_error(meta)
- elif tool_name == 'query_customer_list' and isinstance(value, (dict, list)):
- return self._format_error(meta)
- row.append(value)
- rows.append(row)
- content = {
- 'summary': self._safe_text(data.get('summary')),
- 'headers': headers,
- 'rows': rows,
- }
- if tool_name == 'query_customer_list':
- content['display_rules'] = {
- 'mode': 'complete',
- 'allow_summary': False,
- 'allow_omit_records': False,
- 'allow_omit_empty_fields': False,
- 'allow_rename_fields': False,
- 'preserve_record_order': True,
- 'required_field_count': len(headers),
- 'returned_record_count': len(rows),
- 'required_value_count': len(headers) * len(rows),
- 'instruction': '最终回复必须逐条展示全部记录及全部17个字段,不得摘要、省略或改写',
- }
- tips = self._safe_tips(data.get('tips'))
- if tips:
- content['tips'] = tips
- pagination = self._build_pagination(raw_meta)
- if pagination:
- content['pagination'] = pagination
- return self._success_result(
- content,
- self._render_table(
- content,
- require_complete=tool_name == 'query_customer_list',
- ),
- meta,
- )
- def _present_customer_payment_followup(self, data, raw_meta, meta):
- if set(data) != {'columns', 'records'}:
- return self._format_error(meta)
- columns = data.get('columns')
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- expected_keys = list(self.PAYMENT_FOLLOWUP_COLUMNS)
- if not isinstance(columns, list) or not isinstance(records, list):
- return self._format_error(meta)
- actual_keys = []
- for column in columns:
- if (
- not isinstance(column, dict)
- or set(column) != {'key', 'name'}
- or not isinstance(column.get('key'), str)
- or not isinstance(column.get('name'), str)
- or not column.get('name').strip()
- ):
- return self._format_error(meta)
- actual_keys.append(column['key'])
- if actual_keys != expected_keys or pagination is None:
- return self._format_error(meta)
- amount_keys = {
- 'billed_unverified_amount', 'unbilled_amount',
- 'overdue_unpaid_amount', 'billed_unverified_amount_cny',
- 'unbilled_amount_cny', 'overdue_unpaid_amount_cny',
- 'receipt_unverified_amount', 'current_balance',
- 'credit_limit', 'bad_debt_total',
- }
- text_keys = {'customer_name', 'settlement_currency', 'contract_status'}
- rows = []
- for record in records:
- if not isinstance(record, dict) or set(record) != set(expected_keys):
- return self._format_error(meta)
- row = []
- for key in expected_keys:
- value = record[key]
- if key in amount_keys:
- if (
- isinstance(value, bool)
- or not isinstance(value, (int, float))
- or not math.isfinite(float(value))
- ):
- return self._format_error(meta)
- elif key in text_keys:
- if not isinstance(value, str):
- return self._format_error(meta)
- else:
- value = self._payment_followup_monthly_summaries(value)
- if value is None:
- return self._format_error(meta)
- row.append(value)
- rows.append(row)
- headers = [
- {'label': self.PAYMENT_FOLLOWUP_COLUMNS[key]}
- for key in expected_keys
- ]
- content = {
- 'headers': headers,
- 'rows': rows,
- 'pagination': pagination,
- 'display_rules': {
- 'mode': 'complete',
- 'allow_summary': False,
- 'allow_omit_records': False,
- 'allow_omit_empty_fields': False,
- 'allow_rename_fields': False,
- 'preserve_record_order': True,
- 'required_field_count': len(headers),
- 'returned_record_count': len(rows),
- 'required_value_count': len(headers) * len(rows),
- 'instruction': '最终回复必须逐条展示全部客户、全部字段和全部未回款月份汇总',
- },
- }
- return self._success_result(
- content,
- self._render_table(content, require_complete=True),
- meta,
- )
- def _payment_followup_monthly_summaries(self, summaries):
- if not isinstance(summaries, list):
- return None
- expected = set(self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS)
- translated = []
- for summary in summaries:
- if not isinstance(summary, dict) or set(summary) != expected:
- return None
- amount = summary.get('unverified_amount')
- if (
- isinstance(amount, bool)
- or not isinstance(amount, (int, float))
- or not math.isfinite(float(amount))
- ):
- return None
- if (
- not isinstance(summary.get('receivable_month'), str)
- or not isinstance(summary.get('is_overdue'), bool)
- ):
- return None
- item = {}
- for key, label in self.PAYMENT_FOLLOWUP_MONTHLY_COLUMNS.items():
- value = summary[key]
- item[label] = value
- translated.append(item)
- return translated
- def _present_customer_unverified_bill_details(self, data, raw_meta, meta):
- if set(data) != {'columns', 'records'}:
- return self._format_error(meta)
- columns = data.get('columns')
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- expected_keys = list(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
- if not isinstance(columns, list) or not isinstance(records, list):
- return self._format_error(meta)
- actual_keys = []
- for column in columns:
- if (
- not isinstance(column, dict)
- or set(column) != {'key', 'name'}
- or not isinstance(column.get('key'), str)
- or not isinstance(column.get('name'), str)
- or not column.get('name').strip()
- ):
- return self._format_error(meta)
- actual_keys.append(column['key'])
- if actual_keys != expected_keys or pagination is None:
- return self._format_error(meta)
- translated = self._payment_followup_details(records)
- if translated is None:
- return self._format_error(meta)
- headers = [
- {'label': self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS[key]}
- for key in expected_keys
- ]
- rows = [[item[header['label']] for header in headers] for item in translated]
- content = {'headers': headers, 'rows': rows, 'pagination': pagination}
- return self._success_result(content, self._render_table(content), meta)
- def _payment_followup_details(self, details):
- expected = set(self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS)
- translated = []
- for detail in details:
- if not isinstance(detail, dict) or set(detail) != expected:
- return None
- amount = detail.get('unverified_amount')
- if (
- isinstance(amount, bool)
- or not isinstance(amount, (int, float))
- or not math.isfinite(float(amount))
- ):
- return None
- item = {}
- for key, label in self.PAYMENT_FOLLOWUP_DETAIL_COLUMNS.items():
- value = detail[key]
- if key != 'unverified_amount' and not isinstance(value, str):
- return None
- item[label] = value
- translated.append(item)
- return translated
- def _present_customer_payment_records(self, data, raw_meta, meta):
- if set(data) != {'columns', 'records'}:
- return self._format_error(meta)
- columns = data.get('columns')
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- expected_keys = list(self.PAYMENT_RECORD_COLUMNS)
- if not isinstance(columns, list) or not isinstance(records, list):
- return self._format_error(meta)
- actual_keys = []
- for column in columns:
- if (
- not isinstance(column, dict)
- or set(column) != {'key', 'name'}
- or not isinstance(column.get('key'), str)
- or not isinstance(column.get('name'), str)
- or not column.get('name').strip()
- ):
- return self._format_error(meta)
- actual_keys.append(column['key'])
- if actual_keys != expected_keys or pagination is None:
- return self._format_error(meta)
- amount_keys = {
- 'original_received_amount', 'actual_received_amount',
- 'verified_amount', 'unverified_amount',
- }
- rows = []
- for record in records:
- if not isinstance(record, dict) or set(record) != set(expected_keys):
- return self._format_error(meta)
- row = []
- for key in expected_keys:
- value = record[key]
- if key in amount_keys:
- if (
- isinstance(value, bool)
- or not isinstance(value, (int, float))
- or not math.isfinite(float(value))
- ):
- return self._format_error(meta)
- elif not isinstance(value, str):
- return self._format_error(meta)
- row.append(value)
- rows.append(row)
- headers = [
- {'label': self.PAYMENT_RECORD_COLUMNS[key]}
- for key in expected_keys
- ]
- content = {'headers': headers, 'rows': rows, 'pagination': pagination}
- return self._success_result(content, self._render_table(content), meta)
- def _present_order_receivable_cost_details(self, data, raw_meta, meta):
- if set(data) != {'columns', 'records'}:
- return self._format_error(meta)
- columns = data.get('columns')
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- expected_keys = list(self.RECEIVABLE_COST_COLUMNS)
- if not isinstance(columns, list) or not isinstance(records, list):
- return self._format_error(meta)
- actual_keys = []
- for column in columns:
- if (
- not isinstance(column, dict)
- or set(column) != {'key', 'name'}
- or not isinstance(column.get('key'), str)
- or not isinstance(column.get('name'), str)
- or not column.get('name').strip()
- ):
- return self._format_error(meta)
- actual_keys.append(column['key'])
- if actual_keys != expected_keys or pagination is None:
- return self._format_error(meta)
- numeric_keys = {
- 'charge_weight', 'unit_price', 'receivable_original_amount',
- 'receivable_amount_cny', 'settlement_amount_cny',
- }
- rows = []
- for record in records:
- if not isinstance(record, dict) or set(record) != set(expected_keys):
- return self._format_error(meta)
- row = []
- for key in expected_keys:
- value = record[key]
- if key in numeric_keys:
- if (
- isinstance(value, bool)
- or not isinstance(value, (int, float))
- or not math.isfinite(float(value))
- ):
- return self._format_error(meta)
- elif not isinstance(value, str):
- return self._format_error(meta)
- row.append(value)
- rows.append(row)
- headers = [
- {'label': self.RECEIVABLE_COST_COLUMNS[key]}
- for key in expected_keys
- ]
- content = {'headers': headers, 'rows': rows, 'pagination': pagination}
- return self._success_result(content, self._render_table(content), meta)
- def _present_receivable_cost_list(self, data, raw_meta, meta):
- if set(data) != {'columns', 'records'}:
- return self._format_error(meta)
- columns = data.get('columns')
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- expected_keys = list(self.RECEIVABLE_LIST_COLUMNS)
- if (
- not isinstance(columns, list)
- or not isinstance(records, list)
- or len(columns) != len(expected_keys)
- or pagination is None
- ):
- return self._format_error(meta)
- for column, key in zip(columns, expected_keys):
- if column != {
- 'key': key,
- 'name': self.RECEIVABLE_LIST_COLUMNS[key],
- }:
- return self._format_error(meta)
- amount_keys = {
- 'original_amount', 'total_amount', 'billed_amount', 'unbilled_amount',
- }
- rows = []
- for record in records:
- if not isinstance(record, dict) or set(record) != set(expected_keys):
- return self._format_error(meta)
- row = []
- for key in expected_keys:
- value = record[key]
- if key in amount_keys:
- if not self._valid_amount_cell(value):
- return self._format_error(meta)
- elif not isinstance(value, str):
- return self._format_error(meta)
- row.append(value)
- rows.append(row)
- headers = [
- {'label': self.RECEIVABLE_LIST_COLUMNS[key]}
- for key in expected_keys
- ]
- content = {'headers': headers, 'rows': rows, 'pagination': pagination}
- return self._success_result(content, self._render_table(content), meta)
- def _present_payable_cost_list(self, data, raw_meta, meta):
- if set(data) != {'business_type', 'company_currency', 'columns', 'records'}:
- return self._format_error(meta)
- business_type = data.get('business_type')
- company_currency = data.get('company_currency')
- if (
- isinstance(business_type, bool)
- or not isinstance(business_type, int)
- or business_type not in self.PAYABLE_COST_COLUMNS
- or not isinstance(company_currency, str)
- or not company_currency.strip()
- ):
- return self._format_error(meta)
- pagination = self._customer_pagination(raw_meta)
- columns = data.get('columns')
- records = data.get('records')
- expected = list(self.PAYABLE_COST_COLUMNS[business_type])
- if business_type == 2:
- expected = [
- (key, name.replace('%s', company_currency.strip().upper()))
- for key, name in expected
- ]
- if (
- not isinstance(columns, list)
- or not isinstance(records, list)
- or len(columns) != len(expected)
- or pagination is None
- ):
- return self._format_error(meta)
- for column, (key, name) in zip(columns, expected):
- if column != {'key': key, 'name': name}:
- return self._format_error(meta)
- rows = []
- expected_keys = [key for key, _ in expected]
- for record in records:
- if not isinstance(record, dict) or set(record) != set(expected_keys):
- return self._format_error(meta)
- row = []
- for key in expected_keys:
- value = record[key]
- if key in self.PAYABLE_AMOUNT_KEYS:
- if (
- isinstance(value, bool)
- or not isinstance(value, (int, float))
- or not math.isfinite(float(value))
- ):
- return self._format_error(meta)
- elif not isinstance(value, str):
- return self._format_error(meta)
- row.append(value)
- rows.append(row)
- headers = [{'label': name} for _, name in expected]
- content = {
- 'business_type': business_type,
- 'headers': headers,
- 'rows': rows,
- 'pagination': pagination,
- }
- return self._success_result(content, self._render_table(content), meta)
- @staticmethod
- def _valid_amount_cell(value):
- if not isinstance(value, dict) or set(value) != {'amount', 'currency'}:
- return False
- amount = value.get('amount')
- return (
- not isinstance(amount, bool)
- and isinstance(amount, (int, float))
- and math.isfinite(float(amount))
- and isinstance(value.get('currency'), str)
- )
- def _present_receivable_cost_filter_options(self, data, raw_meta, meta):
- if set(data) != {'records'}:
- return self._format_error(meta)
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- if not isinstance(records, list) or pagination is None:
- return self._format_error(meta)
- rows = []
- for record in records:
- if not isinstance(record, dict) or set(record) != {
- 'value', 'label', 'code',
- }:
- return self._format_error(meta)
- value = record.get('value')
- label = record.get('label')
- code = record.get('code')
- if (
- isinstance(value, bool) or not isinstance(value, int)
- or not isinstance(label, str) or not label.strip()
- or not isinstance(code, str)
- ):
- return self._format_error(meta)
- rows.append([value, label.strip(), code.strip()])
- content = {
- 'headers': [
- {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
- ],
- 'rows': rows,
- 'pagination': pagination,
- }
- return self._success_result(content, self._render_table(content), meta)
- @staticmethod
- def _customer_billing_modes(value):
- if not isinstance(value, list):
- return None
- result = []
- business_types = set()
- for item in value:
- if not isinstance(item, dict) or set(item) != {
- 'business_type', 'settlement_mode',
- }:
- return None
- business_type = item.get('business_type')
- settlement_mode = item.get('settlement_mode')
- if (
- not isinstance(business_type, str) or not business_type.strip()
- or not isinstance(settlement_mode, str) or not settlement_mode.strip()
- or business_type in business_types
- ):
- return None
- business_types.add(business_type)
- result.append({
- '业务类型': business_type.strip(),
- '结算模式': settlement_mode.strip(),
- })
- return result
- def _present_customer_options(self, data, raw_meta, meta):
- if set(data) != {'records'}:
- return self._format_error(meta)
- records = data.get('records')
- pagination = self._customer_pagination(raw_meta)
- if not isinstance(records, list) or pagination is None:
- return self._format_error(meta)
- rows = []
- for record in records:
- if not isinstance(record, dict) or set(record) != {'value', 'label', 'code'}:
- return self._format_error(meta)
- value = record.get('value')
- label = record.get('label')
- code = record.get('code')
- if (
- isinstance(value, bool) or not isinstance(value, int) or value < 1
- or not isinstance(label, str) or not label.strip()
- or not isinstance(code, str)
- ):
- return self._format_error(meta)
- rows.append([value, label.strip(), code.strip()])
- content = {
- 'headers': [
- {'label': '可传值'}, {'label': '显示名称'}, {'label': '业务编码'},
- ],
- 'rows': rows,
- 'pagination': pagination,
- }
- return self._success_result(content, self._render_table(content), meta)
- @staticmethod
- def _customer_pagination(raw_meta):
- if not isinstance(raw_meta, dict):
- return None
- required = {'page', 'limit', 'has_more'}
- if (
- not required.issubset(raw_meta)
- or not set(raw_meta).issubset(required | {'request_id'})
- ):
- return None
- page = raw_meta.get('page')
- limit = raw_meta.get('limit')
- has_more = raw_meta.get('has_more')
- if (
- isinstance(page, bool) or not isinstance(page, int)
- or page < 1 or page > 100
- or isinstance(limit, bool) or not isinstance(limit, int)
- or limit < 1 or limit > 100
- or not isinstance(has_more, bool)
- ):
- return None
- return {'page': page, 'limit': limit, 'has_more': has_more}
- def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
- summary = data.get('summary')
- columns = data.get('columns')
- records = data.get('records')
- if not isinstance(summary, dict):
- return self._format_error(meta)
- if not isinstance(columns, list) or not columns or not isinstance(records, list):
- return self._format_error(meta)
- if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
- return self._format_error(meta)
- allowed_columns = self.TABLE_COLUMNS.get(tool_name)
- headers = []
- keys = []
- for column in columns:
- if not isinstance(column, dict):
- return self._format_error(meta)
- key = column.get('key')
- definition = allowed_columns.get(key) if isinstance(key, str) else None
- if not isinstance(definition, tuple) or not definition:
- return self._format_error(meta)
- keys.append(key)
- headers.append({'label': definition[0]})
- rows = []
- for record in records:
- if not isinstance(record, dict):
- return self._format_error(meta)
- row = []
- for key in keys:
- value = '' if record.get(key) is None else record.get(key, '')
- if key == 'customs_files':
- if not isinstance(value, list):
- return self._format_error(meta)
- files = []
- for item in value:
- if not isinstance(item, dict):
- return self._format_error(meta)
- files.append({
- '文件名称': item.get('file_name', ''),
- '文件类型': item.get('file_type', ''),
- '文件链接': item.get('file_url', ''),
- })
- value = files
- row.append(value)
- rows.append(row)
- summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
- content = {
- 'summary': {
- 'headers': [
- {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
- for key in summary_keys
- ],
- 'row': [summary.get(key, '') for key in summary_keys],
- },
- 'details': {
- 'headers': headers,
- 'rows': rows,
- },
- }
- tips = self._safe_tips(data.get('tips'))
- if tips:
- content['details']['tips'] = tips
- pagination = self._build_pagination(raw_meta)
- if pagination:
- content['details']['pagination'] = pagination
- return self._success_result(
- content,
- self._render_outbound_detail(content),
- meta,
- )
- @classmethod
- def _render_outbound_detail(cls, content):
- lines = ['排舱汇总:']
- summary = content['summary']
- for header, value in zip(summary['headers'], summary['row']):
- lines.append('- {0}: {1}'.format(header['label'], value))
- lines.append('订单明细:')
- details = content['details']
- lines.append('表头共 {0} 列:'.format(len(details['headers'])))
- for index, header in enumerate(details['headers'], start=1):
- lines.append('{0}. {1}'.format(index, header['label']))
- for index, row in enumerate(details['rows'], start=1):
- lines.append('记录 {0}:'.format(index))
- for header, value in zip(details['headers'], row):
- if isinstance(value, (dict, list)):
- value = json.dumps(value, ensure_ascii=False)
- lines.append('- {0}: {1}'.format(header['label'], value))
- tips = details.get('tips') or []
- if tips:
- lines.append('提示:{0}'.format(';'.join(tips)))
- return '\n'.join(lines)
- def _present_options(self, data, raw_meta, meta):
- records = data.get('records')
- if not isinstance(records, list):
- return self._format_error(meta)
- rows = []
- for record in records:
- if not isinstance(record, dict):
- return self._format_error(meta)
- rows.append([
- record.get('value', ''),
- self._safe_text(record.get('label')),
- self._safe_text(record.get('code')),
- ])
- content = {
- 'headers': [
- {'label': '可传值'},
- {'label': '显示名称'},
- {'label': '业务编码'},
- ],
- 'rows': rows,
- }
- pagination = self._build_pagination(raw_meta)
- if pagination:
- content['pagination'] = pagination
- return self._success_result(content, self._render_table(content), meta)
- def _present_export_submission(self, data, meta):
- expected = {'task_ref', 'status', 'retry_after_seconds'}
- if set(data) != expected:
- return self._format_error(meta)
- task_ref = data.get('task_ref')
- retry_after = data.get('retry_after_seconds')
- if (
- not isinstance(task_ref, str) or not task_ref.strip()
- or data.get('status') != 'queued'
- or isinstance(retry_after, bool)
- or not isinstance(retry_after, int)
- or retry_after <= 0
- ):
- return self._format_error(meta)
- task = {
- 'task_ref': task_ref.strip(),
- 'status': 'queued',
- 'retry_after_seconds': retry_after,
- }
- content = {
- 'message': '导出任务已提交',
- 'task': task,
- }
- text = (
- '导出任务已提交\n'
- '- 任务引用: {0}\n'
- '- 建议 {1} 秒后单独查询任务状态'
- ).format(task['task_ref'], retry_after)
- return self._success_result(content, text, meta)
- def _present_export_task(self, data, meta):
- task_ref = data.get('task_ref')
- status = data.get('status')
- if (
- not isinstance(task_ref, str)
- or not task_ref.strip()
- or status not in ('queued', 'running', 'completed', 'failed')
- ):
- return self._format_error(meta)
- task = {'task_ref': task_ref.strip(), 'status': status}
- if status in ('queued', 'running'):
- if set(data) != {'task_ref', 'status', 'retry_after_seconds'}:
- return self._format_error(meta)
- retry_after = data.get('retry_after_seconds')
- if (
- isinstance(retry_after, bool)
- or not isinstance(retry_after, int)
- or retry_after <= 0
- ):
- return self._format_error(meta)
- task['retry_after_seconds'] = retry_after
- label = '等待中' if status == 'queued' else '生成中'
- content = {'message': '导出任务{0}'.format(label), 'task': task}
- text = (
- '导出任务{0}\n- 任务引用: {1}\n- 建议 {2} 秒后再次查询'
- ).format(label, task['task_ref'], retry_after)
- return self._success_result(content, text, meta)
- if status == 'failed':
- if set(data) != {'task_ref', 'status'}:
- return self._format_error(meta)
- content = {'message': '导出任务失败,请重新提交', 'task': task}
- text = '导出任务失败,请重新提交'
- return self._success_result(content, text, meta)
- if set(data) != {'task_ref', 'status', 'files'}:
- return self._format_error(meta)
- files = data.get('files')
- if not isinstance(files, list) or not files:
- return self._format_error(meta)
- safe_files = []
- for item in files:
- if not isinstance(item, dict) or set(item) != {'label', 'url'}:
- return self._format_error(meta)
- label = item.get('label')
- url = item.get('url')
- if (
- not isinstance(label, str) or not label.strip()
- or not self._valid_http_url(url)
- ):
- return self._format_error(meta)
- safe_files.append({'label': label.strip(), 'url': url.strip()})
- content = {
- 'message': '文件已生成',
- 'task': task,
- 'files': safe_files,
- }
- lines = ['文件已生成']
- for item in safe_files:
- lines.append('- {0}: {1}'.format(item['label'], item['url']))
- return self._success_result(content, '\n'.join(lines), meta)
- def _valid_http_url(self, value):
- if not isinstance(value, str) or not value.strip():
- return False
- if value != value.strip() or '\\' in value or any(
- character.isspace() or ord(character) < 32 or ord(character) == 127
- for character in value
- ):
- return False
- try:
- parsed = urlparse(value)
- port = parsed.port
- return (
- parsed.scheme in ('http', 'https')
- and bool(parsed.hostname)
- and parsed.username is None
- and parsed.password is None
- and (port is None or 0 < port <= 65535)
- )
- except ValueError:
- return False
- def _business_error(self, tool_name, code, raw_message, meta):
- if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
- logger.warning(
- 'Unknown MCP business error code',
- extra={
- 'request_id': meta.get('request_id', ''),
- 'tool_code': tool_name,
- 'backend_code': code,
- 'response_code': 'MCP_9001',
- 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
- },
- )
- code = 'MCP_9001'
- if code == 'MCP_1401':
- label = self._find_field_label(tool_name, raw_message)
- message = self._parameter_message(label)
- else:
- message = self.ERROR_MESSAGES[code]
- retryable = code not in self.NON_RETRYABLE_CODES
- return self._error_result(code, message, retryable, meta)
- def _find_field_label(self, tool_name, raw_message):
- message = str(raw_message or '')
- fields = self.FIELD_LABELS.get(tool_name, {})
- for field in sorted(fields, key=len, reverse=True):
- if field in message:
- return fields[field]
- return ''
- @staticmethod
- def _parameter_message(label):
- return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
- @staticmethod
- def _build_meta(raw_meta):
- if not isinstance(raw_meta, dict):
- return {}
- request_id = raw_meta.get('request_id')
- if not isinstance(request_id, str) or not request_id.strip():
- return {}
- return {'request_id': request_id.strip()}
- @staticmethod
- def _build_pagination(raw_meta):
- if not isinstance(raw_meta, dict):
- return {}
- return {
- key: raw_meta[key]
- for key in ('page', 'limit', 'has_more', 'total')
- if key in raw_meta
- }
- @staticmethod
- def _safe_text(value):
- if value is None:
- return ''
- return str(value).strip()
- @classmethod
- def _safe_tips(cls, value):
- if not isinstance(value, list):
- return []
- return [cls._safe_text(item) for item in value if cls._safe_text(item)]
- @classmethod
- def _render_table(cls, content, require_complete=False):
- headers = content.get('headers') or []
- rows = content.get('rows') or []
- lines = []
- if require_complete:
- lines.append('完整客户数据,禁止摘要、合并、隐藏字段或省略空字段。')
- lines.append(
- '本页记录数:{0};每条字段数:{1};应展示字段值总数:{2}。'.format(
- len(rows), len(headers), len(rows) * len(headers)
- )
- )
- summary = cls._safe_text(content.get('summary'))
- if summary:
- lines.append(summary)
- lines.append('表头共 {0} 列:'.format(len(headers)))
- for index, header in enumerate(headers, start=1):
- lines.append('{0}. {1}'.format(index, header['label']))
- for index, row in enumerate(rows, start=1):
- lines.append('记录 {0}:'.format(index))
- for header, value in zip(headers, row):
- if isinstance(value, (dict, list)):
- value = json.dumps(value, ensure_ascii=False)
- lines.append('- {0}: {1}'.format(header['label'], value))
- tips = content.get('tips') or []
- if tips:
- lines.append('提示:{0}'.format(';'.join(tips)))
- if require_complete:
- lines.append(
- '展示完整性校验:已提供{0}条客户的全部{1}个字段。'.format(
- len(rows), len(headers)
- )
- )
- return '\n'.join(lines)
- @staticmethod
- def _success_result(content, text, meta):
- return {
- 'structured_content': content,
- 'text': text,
- 'is_error': False,
- 'meta': meta,
- }
- @staticmethod
- def _error_result(code, message, retryable, meta=None):
- return {
- 'structured_content': {
- 'code': code,
- 'message': message,
- 'retryable': retryable,
- },
- 'text': '{0}: {1}'.format(code, message),
- 'is_error': True,
- 'meta': meta or {},
- }
- @classmethod
- def _format_error(cls, meta=None):
- return cls._error_result(
- 'MCP_9001',
- '工具返回格式异常',
- True,
- meta,
- )
|