"""Closed wire schemas for the Agent SKU preaudit roundtrip. These checks protect the Gateway boundary. The backend owns visibility, permissions, claims, snapshot completeness, and all business validation. """ import math import re from copy import deepcopy from urllib.parse import urlsplit GOODS_AI_PRE_AUDIT_TOOL_NAMES = frozenset(( 'claim_goods_ai_pre_audit', 'query_goods_ai_pre_audit', 'save_goods_ai_pre_audit_result', )) PAGE_FIELDS = ( 'sku', 'cn_name', 'en_name', 'material_cn', 'material_en', 'material_ratio_info', 'purpose_cn', 'purpose_en', 'image_url', 'shipping_method', 'goods_type', 'goods_category_id', 'category_ids', 'is_inspection_fee', 'is_fda_declaration', 'is_epa_declaration', 'is_act_declaration', 'is_dot_declaration', 'is_cpsc_declaration', 'product_surcharge', 'tax_surcharge', 'yf_cn_goodsname', 'yf_en_goodsname', 'ys_clearance_price', 'yf_clearance_price', 'currency', 'recommended_grade', 'recommended_keyword', 'box_value', ) ATTRIBUTE_FIELDS = ( 'is_battery', 'is_magnetic', 'is_wood', 'is_toy', 'is_sensitive', 'is_food', ) CLEARANCE_FIELDS = ('ys_clearance_data', 'yf_clearance_data') CLEARANCE_REQUIRED = ( 'clearance_hscode', 'material', 'material_ratio', 'kit_hscode', 'adjust_hscode_data', ) CLEARANCE_HINTS = ( 'tax_rate', 'extra_tax', 'is_new_hscode', 'kit_tax_rate', 'is_new_kit', 'adjust_rate_data', 'tax_tag', 'box_value', 'adjust_tax_rate', 'total_tax_rate', ) SCALAR = {'type': ['string', 'number', 'boolean', 'null']} LEAF_VALUE = {'anyOf': [SCALAR, {'type': 'array', 'items': SCALAR}]} GOODS_ID = {'type': 'integer', 'minimum': 1} REFERENCE = {'type': 'string', 'pattern': '^[0-9a-fA-F]{64}$'} TIMESTAMP = {'type': 'integer', 'minimum': 1} OVERALL_RESULTS = ('pass', 'hold', 'manual', 'reject') FIELD_RESULTS = ('pass', 'reject', 'hold', 'not_checked') # Must match PHP GoodsAiPreAuditResult::REASON_BRIEF_MAX / SUMMARY_BRIEF_MAX. REASON_BRIEF_MAX = 20 SUMMARY_BRIEF_MAX = 40 # Must match PHP GoodsAiPreAuditResult::HINT_FIELDS / HINT_ROW_FIELDS; PHP only accepts pass/not_checked on them. HINT_FIELDS = ('recommended_grade', 'recommended_keyword', 'sync_orders') HINT_ROW_FIELDS = ('tax_rate', 'extra_tax', 'is_new_hscode', 'kit_tax_rate', 'is_new_kit', 'adjust_rate_data', 'adjust_tax_rate', 'total_tax_rate', 'tax_tag', 'box_value') def brief_schema(max_length): """One non-blank line; JSON Schema maxLength counts code points, like PHP mb_strlen.""" return {'type': 'string', 'minLength': 1, 'maxLength': max_length, 'pattern': r'[^\r\n]*\S[^\r\n]*'} def closed_object(properties, required=()): return { 'type': 'object', 'properties': properties, 'required': list(required), 'additionalProperties': False, } ADJUST_RATE_ROW = closed_object({ 'adjust_hscode': {'type': 'string'}, 'adjust_rate': SCALAR, 'is_new_hscode': {'type': ['string', 'boolean', 'integer']}, }, ('adjust_hscode', 'adjust_rate', 'is_new_hscode')) SYNC_ORDER_ROW = closed_object({ 'order_id': {'type': ['string', 'integer']}, 'order_number': {'type': 'string'}, 'status_name': {'type': 'string'}, }, ('order_id', 'order_number', 'status_name')) ROW_VALUES = { key: LEAF_VALUE for key in CLEARANCE_REQUIRED + CLEARANCE_HINTS } for _key in ('clearance_hscode', 'material', 'material_ratio', 'kit_hscode'): ROW_VALUES[_key] = {'type': 'string'} for _key in ('is_new_hscode', 'is_new_kit'): ROW_VALUES[_key] = {'type': ['string', 'boolean', 'integer']} ROW_VALUES['adjust_hscode_data'] = {'type': 'array', 'items': {'type': 'string'}} ROW_VALUES['adjust_rate_data'] = {'type': 'array', 'items': ADJUST_RATE_ROW} PAGE_VALUE_SCHEMAS = {key: LEAF_VALUE for key in PAGE_FIELDS} PAGE_VALUE_SCHEMAS.update({key: {'type': 'boolean'} for key in ATTRIBUTE_FIELDS}) PAGE_VALUE_SCHEMAS['image_url'] = { 'anyOf': [{'type': 'null'}, {'type': 'string', 'format': 'uri'}], } PAGE_VALUE_SCHEMAS['sync_orders'] = {'type': 'array', 'items': SYNC_ORDER_ROW} PAGE_VALUE_SCHEMAS.update({ key: {'type': 'array', 'items': closed_object(ROW_VALUES, CLEARANCE_REQUIRED)} for key in CLEARANCE_FIELDS }) PAGE_VALUES_SCHEMA = dict(closed_object(PAGE_VALUE_SCHEMAS), minProperties=1) CERTIFICATION_FILE_GROUPS = ('battery_file', 'fda_file', 'toy_file', 'other_file') CERTIFICATION_FILE_SCHEMA = closed_object({ 'name': {'type': 'string'}, 'url': {'type': 'string', 'format': 'uri', 'pattern': r'[^\s\\\x00-\x1f\x7f]+'}, }, ('name', 'url')) CERTIFICATION_FILES_SCHEMA = closed_object({ group: {'type': 'array', 'items': CERTIFICATION_FILE_SCHEMA} for group in CERTIFICATION_FILE_GROUPS }, CERTIFICATION_FILE_GROUPS) CONTEXT_SCHEMA = closed_object({ 'country_code': {'type': 'string'}, 'departure_country': {'type': 'string'}, 'certification_files': CERTIFICATION_FILES_SCHEMA, 'selected_labels': closed_object({ key: {'anyOf': [ {'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}, ]} for key in PAGE_FIELDS + ATTRIBUTE_FIELDS }), }, ('country_code', 'departure_country', 'selected_labels')) def field_result_schema(value_schema): return closed_object({ 'value': value_schema, 'result': {'type': 'string', 'enum': list(FIELD_RESULTS)}, 'suggested_value': {'anyOf': [{'type': 'null'}, value_schema]}, 'reason': {'type': 'string'}, 'reason_brief': brief_schema(REASON_BRIEF_MAX), }, ('value', 'result', 'suggested_value', 'reason', 'reason_brief')) FIELD_SCHEMAS = { key: field_result_schema(value) for key, value in PAGE_VALUE_SCHEMAS.items() if key not in CLEARANCE_FIELDS } FIELD_SCHEMAS.update({ key: {'type': 'array', 'items': closed_object({ field: field_result_schema(value) for field, value in ROW_VALUES.items() }, CLEARANCE_REQUIRED)} for key in CLEARANCE_FIELDS }) CLAIM_INPUT_SCHEMA = closed_object({'goods_id': GOODS_ID}) QUERY_INPUT_SCHEMA = closed_object({ 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, }, ('goods_id', 'claim_ref')) SAVE_INPUT_SCHEMA = closed_object({ 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE, 'result': {'type': 'string', 'enum': list(OVERALL_RESULTS)}, 'summary': {'type': 'string'}, 'summary_brief': brief_schema(SUMMARY_BRIEF_MAX), 'fields': dict(closed_object(FIELD_SCHEMAS), minProperties=1), }, ('goods_id', 'claim_ref', 'source_ref', 'result', 'summary', 'summary_brief', 'fields')) RESPONSE_SCHEMAS = { 'claim_goods_ai_pre_audit': {'anyOf': [ closed_object({'claimed': {'type': 'boolean', 'enum': [False]}}, ('claimed',)), closed_object({ 'claimed': {'type': 'boolean', 'enum': [True]}, 'goods_id': GOODS_ID, 'sku': {'type': 'string'}, 'claim_ref': REFERENCE, 'expires_at': TIMESTAMP, }, ('claimed', 'goods_id', 'sku', 'claim_ref', 'expires_at')), ]}, 'query_goods_ai_pre_audit': closed_object({ 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE, 'context': CONTEXT_SCHEMA, 'page_values': PAGE_VALUES_SCHEMA, }, ('goods_id', 'claim_ref', 'source_ref', 'context', 'page_values')), 'save_goods_ai_pre_audit_result': closed_object({ 'goods_id': GOODS_ID, 'saved': {'type': 'boolean', 'enum': [True]}, 'ai_pre_audit_status': {'type': 'integer', 'enum': [2]}, 'saved_at': TIMESTAMP, }, ('goods_id', 'saved', 'ai_pre_audit_status', 'saved_at')), } def matches_schema(value, schema): """Validate only the JSON Schema subset used by these closed contracts.""" if 'anyOf' in schema: return any(matches_schema(value, option) for option in schema['anyOf']) allowed_types = schema['type'] if isinstance(allowed_types, str): allowed_types = [allowed_types] value_type = { str: 'string', bool: 'boolean', int: 'integer', float: 'number', list: 'array', dict: 'object', type(None): 'null', }.get(type(value)) if value_type not in allowed_types and not ( value_type == 'integer' and 'number' in allowed_types ): return False if 'enum' in schema and value not in schema['enum']: return False if value_type in ('integer', 'number'): if value_type == 'number' and not math.isfinite(value): return False if 'minimum' in schema and value < schema['minimum']: return False if value_type == 'string': if 'minLength' in schema and len(value) < schema['minLength']: return False if 'maxLength' in schema and len(value) > schema['maxLength']: return False if 'pattern' in schema and re.fullmatch(schema['pattern'], value) is None: return False if schema.get('format') == 'uri' and value: try: url = urlsplit(value) if (url.scheme not in ('http', 'https') or not url.hostname or url.username is not None or url.password is not None or (url.port is not None and not 0 < url.port <= 65535) or any(ord(char) <= 32 for char in value)): return False except ValueError: return False if value_type == 'object': properties = schema['properties'] if set(value) - set(properties) or set(schema['required']) - set(value): return False if len(value) < schema.get('minProperties', 0): return False return all(matches_schema(item, properties[key]) for key, item in value.items()) if value_type == 'array': return all(matches_schema(item, schema['items']) for item in value) return True class GoodsAiPreAuditTool: def __init__(self, api_client=None): self.api_client = api_client def metadata(self): return {'name': self.name, 'description': self.description, 'input_schema': deepcopy(self.input_schema)} def build_payload(self, arguments): if not matches_schema(arguments, self.input_schema): raise ValueError('goods AI preaudit arguments are invalid') return arguments def call(self, request_id='', **arguments): if self.api_client is None: raise RuntimeError('api client is required for ' + self.name) return self.api_client.call_tool( self.name, self.route_path, self.build_payload(arguments), request_id or 'rq_' + self.name, )