goods_ai_pre_audit_common.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. """Closed wire schemas for the Agent SKU preaudit roundtrip.
  2. These checks protect the Gateway boundary. The backend owns visibility,
  3. permissions, claims, snapshot completeness, and all business validation.
  4. """
  5. import math
  6. import re
  7. from copy import deepcopy
  8. from urllib.parse import urlsplit
  9. GOODS_AI_PRE_AUDIT_TOOL_NAMES = frozenset((
  10. 'claim_goods_ai_pre_audit', 'query_goods_ai_pre_audit',
  11. 'save_goods_ai_pre_audit_result',
  12. ))
  13. PAGE_FIELDS = (
  14. 'sku', 'cn_name', 'en_name', 'material_cn', 'material_en',
  15. 'material_ratio_info', 'purpose_cn', 'purpose_en', 'image_url',
  16. 'shipping_method', 'goods_type', 'goods_category_id', 'category_ids',
  17. 'is_inspection_fee', 'is_fda_declaration', 'is_epa_declaration',
  18. 'is_act_declaration', 'is_dot_declaration', 'is_cpsc_declaration',
  19. 'product_surcharge', 'tax_surcharge', 'yf_cn_goodsname', 'yf_en_goodsname',
  20. 'ys_clearance_price', 'yf_clearance_price', 'currency',
  21. 'recommended_grade', 'recommended_keyword', 'box_value',
  22. )
  23. ATTRIBUTE_FIELDS = (
  24. 'is_battery', 'is_magnetic', 'is_wood', 'is_toy', 'is_sensitive', 'is_food',
  25. )
  26. CLEARANCE_FIELDS = ('ys_clearance_data', 'yf_clearance_data')
  27. CLEARANCE_REQUIRED = (
  28. 'clearance_hscode', 'material', 'material_ratio', 'kit_hscode',
  29. 'adjust_hscode_data',
  30. )
  31. CLEARANCE_HINTS = (
  32. 'tax_rate', 'extra_tax', 'is_new_hscode', 'kit_tax_rate', 'is_new_kit',
  33. 'adjust_rate_data', 'tax_tag', 'box_value', 'adjust_tax_rate', 'total_tax_rate',
  34. )
  35. SCALAR = {'type': ['string', 'number', 'boolean', 'null']}
  36. LEAF_VALUE = {'anyOf': [SCALAR, {'type': 'array', 'items': SCALAR}]}
  37. GOODS_ID = {'type': 'integer', 'minimum': 1}
  38. REFERENCE = {'type': 'string', 'pattern': '^[0-9a-fA-F]{64}$'}
  39. TIMESTAMP = {'type': 'integer', 'minimum': 1}
  40. OVERALL_RESULTS = ('pass', 'hold', 'manual', 'reject')
  41. FIELD_RESULTS = ('pass', 'reject', 'hold', 'not_checked')
  42. def closed_object(properties, required=()):
  43. return {
  44. 'type': 'object', 'properties': properties,
  45. 'required': list(required), 'additionalProperties': False,
  46. }
  47. ADJUST_RATE_ROW = closed_object({
  48. 'adjust_hscode': {'type': 'string'},
  49. 'adjust_rate': SCALAR,
  50. 'is_new_hscode': {'type': ['string', 'boolean', 'integer']},
  51. }, ('adjust_hscode', 'adjust_rate', 'is_new_hscode'))
  52. SYNC_ORDER_ROW = closed_object({
  53. 'order_id': {'type': ['string', 'integer']},
  54. 'order_number': {'type': 'string'},
  55. 'status_name': {'type': 'string'},
  56. }, ('order_id', 'order_number', 'status_name'))
  57. ROW_VALUES = {
  58. key: LEAF_VALUE for key in CLEARANCE_REQUIRED + CLEARANCE_HINTS
  59. }
  60. for _key in ('clearance_hscode', 'material', 'material_ratio', 'kit_hscode'):
  61. ROW_VALUES[_key] = {'type': 'string'}
  62. for _key in ('is_new_hscode', 'is_new_kit'):
  63. ROW_VALUES[_key] = {'type': ['string', 'boolean', 'integer']}
  64. ROW_VALUES['adjust_hscode_data'] = {'type': 'array', 'items': {'type': 'string'}}
  65. ROW_VALUES['adjust_rate_data'] = {'type': 'array', 'items': ADJUST_RATE_ROW}
  66. PAGE_VALUE_SCHEMAS = {key: LEAF_VALUE for key in PAGE_FIELDS}
  67. PAGE_VALUE_SCHEMAS.update({key: {'type': 'boolean'} for key in ATTRIBUTE_FIELDS})
  68. PAGE_VALUE_SCHEMAS['image_url'] = {
  69. 'anyOf': [{'type': 'null'}, {'type': 'string', 'format': 'uri'}],
  70. }
  71. PAGE_VALUE_SCHEMAS['sync_orders'] = {'type': 'array', 'items': SYNC_ORDER_ROW}
  72. PAGE_VALUE_SCHEMAS.update({
  73. key: {'type': 'array', 'items': closed_object(ROW_VALUES, CLEARANCE_REQUIRED)}
  74. for key in CLEARANCE_FIELDS
  75. })
  76. PAGE_VALUES_SCHEMA = dict(closed_object(PAGE_VALUE_SCHEMAS), minProperties=1)
  77. CERTIFICATION_FILE_GROUPS = ('battery_file', 'fda_file', 'toy_file', 'other_file')
  78. CERTIFICATION_FILE_SCHEMA = closed_object({
  79. 'name': {'type': 'string'},
  80. 'url': {'type': 'string', 'format': 'uri', 'pattern': r'[^\s\\\x00-\x1f\x7f]+'},
  81. }, ('name', 'url'))
  82. CERTIFICATION_FILES_SCHEMA = closed_object({
  83. group: {'type': 'array', 'items': CERTIFICATION_FILE_SCHEMA}
  84. for group in CERTIFICATION_FILE_GROUPS
  85. }, CERTIFICATION_FILE_GROUPS)
  86. CONTEXT_SCHEMA = closed_object({
  87. 'country_code': {'type': 'string'},
  88. 'departure_country': {'type': 'string'},
  89. 'certification_files': CERTIFICATION_FILES_SCHEMA,
  90. 'selected_labels': closed_object({
  91. key: {'anyOf': [
  92. {'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}},
  93. ]} for key in PAGE_FIELDS + ATTRIBUTE_FIELDS
  94. }),
  95. }, ('country_code', 'departure_country', 'selected_labels'))
  96. def field_result_schema(value_schema):
  97. return closed_object({
  98. 'value': value_schema,
  99. 'result': {'type': 'string', 'enum': list(FIELD_RESULTS)},
  100. 'suggested_value': {'anyOf': [{'type': 'null'}, value_schema]},
  101. 'reason': {'type': 'string'},
  102. }, ('value', 'result', 'suggested_value', 'reason'))
  103. FIELD_SCHEMAS = {
  104. key: field_result_schema(value) for key, value in PAGE_VALUE_SCHEMAS.items()
  105. if key not in CLEARANCE_FIELDS
  106. }
  107. FIELD_SCHEMAS.update({
  108. key: {'type': 'array', 'items': closed_object({
  109. field: field_result_schema(value) for field, value in ROW_VALUES.items()
  110. }, CLEARANCE_REQUIRED)} for key in CLEARANCE_FIELDS
  111. })
  112. CLAIM_INPUT_SCHEMA = closed_object({'goods_id': GOODS_ID})
  113. QUERY_INPUT_SCHEMA = closed_object({
  114. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE,
  115. }, ('goods_id', 'claim_ref'))
  116. SAVE_INPUT_SCHEMA = closed_object({
  117. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE,
  118. 'result': {'type': 'string', 'enum': list(OVERALL_RESULTS)},
  119. 'summary': {'type': 'string'},
  120. 'fields': dict(closed_object(FIELD_SCHEMAS), minProperties=1),
  121. }, ('goods_id', 'claim_ref', 'source_ref', 'result', 'summary', 'fields'))
  122. RESPONSE_SCHEMAS = {
  123. 'claim_goods_ai_pre_audit': {'anyOf': [
  124. closed_object({'claimed': {'type': 'boolean', 'enum': [False]}}, ('claimed',)),
  125. closed_object({
  126. 'claimed': {'type': 'boolean', 'enum': [True]},
  127. 'goods_id': GOODS_ID, 'sku': {'type': 'string'},
  128. 'claim_ref': REFERENCE, 'expires_at': TIMESTAMP,
  129. }, ('claimed', 'goods_id', 'sku', 'claim_ref', 'expires_at')),
  130. ]},
  131. 'query_goods_ai_pre_audit': closed_object({
  132. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE,
  133. 'context': CONTEXT_SCHEMA, 'page_values': PAGE_VALUES_SCHEMA,
  134. }, ('goods_id', 'claim_ref', 'source_ref', 'context', 'page_values')),
  135. 'save_goods_ai_pre_audit_result': closed_object({
  136. 'goods_id': GOODS_ID, 'saved': {'type': 'boolean', 'enum': [True]},
  137. 'ai_pre_audit_status': {'type': 'integer', 'enum': [2]},
  138. 'saved_at': TIMESTAMP,
  139. }, ('goods_id', 'saved', 'ai_pre_audit_status', 'saved_at')),
  140. }
  141. def matches_schema(value, schema):
  142. """Validate only the JSON Schema subset used by these closed contracts."""
  143. if 'anyOf' in schema:
  144. return any(matches_schema(value, option) for option in schema['anyOf'])
  145. allowed_types = schema['type']
  146. if isinstance(allowed_types, str):
  147. allowed_types = [allowed_types]
  148. value_type = {
  149. str: 'string', bool: 'boolean', int: 'integer', float: 'number',
  150. list: 'array', dict: 'object', type(None): 'null',
  151. }.get(type(value))
  152. if value_type not in allowed_types and not (
  153. value_type == 'integer' and 'number' in allowed_types
  154. ):
  155. return False
  156. if 'enum' in schema and value not in schema['enum']:
  157. return False
  158. if value_type in ('integer', 'number'):
  159. if value_type == 'number' and not math.isfinite(value):
  160. return False
  161. if 'minimum' in schema and value < schema['minimum']:
  162. return False
  163. if value_type == 'string':
  164. if 'pattern' in schema and re.fullmatch(schema['pattern'], value) is None:
  165. return False
  166. if schema.get('format') == 'uri' and value:
  167. try:
  168. url = urlsplit(value)
  169. if (url.scheme not in ('http', 'https') or not url.hostname
  170. or url.username is not None or url.password is not None
  171. or (url.port is not None and not 0 < url.port <= 65535)
  172. or any(ord(char) <= 32 for char in value)):
  173. return False
  174. except ValueError:
  175. return False
  176. if value_type == 'object':
  177. properties = schema['properties']
  178. if set(value) - set(properties) or set(schema['required']) - set(value):
  179. return False
  180. if len(value) < schema.get('minProperties', 0):
  181. return False
  182. return all(matches_schema(item, properties[key]) for key, item in value.items())
  183. if value_type == 'array':
  184. return all(matches_schema(item, schema['items']) for item in value)
  185. return True
  186. class GoodsAiPreAuditTool:
  187. def __init__(self, api_client=None):
  188. self.api_client = api_client
  189. def metadata(self):
  190. return {'name': self.name, 'description': self.description,
  191. 'input_schema': deepcopy(self.input_schema)}
  192. def build_payload(self, arguments):
  193. if not matches_schema(arguments, self.input_schema):
  194. raise ValueError('goods AI preaudit arguments are invalid')
  195. return arguments
  196. def call(self, request_id='', **arguments):
  197. if self.api_client is None:
  198. raise RuntimeError('api client is required for ' + self.name)
  199. return self.api_client.call_tool(
  200. self.name, self.route_path, self.build_payload(arguments),
  201. request_id or 'rq_' + self.name,
  202. )