goods_ai_pre_audit_common.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. CONTEXT_SCHEMA = closed_object({
  78. 'country_code': {'type': 'string'},
  79. 'departure_country': {'type': 'string'},
  80. 'selected_labels': closed_object({
  81. key: {'anyOf': [
  82. {'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}},
  83. ]} for key in PAGE_FIELDS + ATTRIBUTE_FIELDS
  84. }),
  85. }, ('country_code', 'departure_country', 'selected_labels'))
  86. def field_result_schema(value_schema):
  87. return closed_object({
  88. 'value': value_schema,
  89. 'result': {'type': 'string', 'enum': list(FIELD_RESULTS)},
  90. 'suggested_value': {'anyOf': [{'type': 'null'}, value_schema]},
  91. 'reason': {'type': 'string'},
  92. }, ('value', 'result', 'suggested_value', 'reason'))
  93. FIELD_SCHEMAS = {
  94. key: field_result_schema(value) for key, value in PAGE_VALUE_SCHEMAS.items()
  95. if key not in CLEARANCE_FIELDS
  96. }
  97. FIELD_SCHEMAS.update({
  98. key: {'type': 'array', 'items': closed_object({
  99. field: field_result_schema(value) for field, value in ROW_VALUES.items()
  100. }, CLEARANCE_REQUIRED)} for key in CLEARANCE_FIELDS
  101. })
  102. CLAIM_INPUT_SCHEMA = closed_object({'goods_id': GOODS_ID})
  103. QUERY_INPUT_SCHEMA = closed_object({
  104. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE,
  105. }, ('goods_id', 'claim_ref'))
  106. SAVE_INPUT_SCHEMA = closed_object({
  107. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE,
  108. 'result': {'type': 'string', 'enum': list(OVERALL_RESULTS)},
  109. 'summary': {'type': 'string'},
  110. 'fields': dict(closed_object(FIELD_SCHEMAS), minProperties=1),
  111. }, ('goods_id', 'claim_ref', 'source_ref', 'result', 'summary', 'fields'))
  112. RESPONSE_SCHEMAS = {
  113. 'claim_goods_ai_pre_audit': {'anyOf': [
  114. closed_object({'claimed': {'type': 'boolean', 'enum': [False]}}, ('claimed',)),
  115. closed_object({
  116. 'claimed': {'type': 'boolean', 'enum': [True]},
  117. 'goods_id': GOODS_ID, 'sku': {'type': 'string'},
  118. 'claim_ref': REFERENCE, 'expires_at': TIMESTAMP,
  119. }, ('claimed', 'goods_id', 'sku', 'claim_ref', 'expires_at')),
  120. ]},
  121. 'query_goods_ai_pre_audit': closed_object({
  122. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE,
  123. 'context': CONTEXT_SCHEMA, 'page_values': PAGE_VALUES_SCHEMA,
  124. }, ('goods_id', 'claim_ref', 'source_ref', 'context', 'page_values')),
  125. 'save_goods_ai_pre_audit_result': closed_object({
  126. 'goods_id': GOODS_ID, 'saved': {'type': 'boolean', 'enum': [True]},
  127. 'ai_pre_audit_status': {'type': 'integer', 'enum': [2]},
  128. 'saved_at': TIMESTAMP,
  129. }, ('goods_id', 'saved', 'ai_pre_audit_status', 'saved_at')),
  130. }
  131. def matches_schema(value, schema):
  132. """Validate only the JSON Schema subset used by these closed contracts."""
  133. if 'anyOf' in schema:
  134. return any(matches_schema(value, option) for option in schema['anyOf'])
  135. allowed_types = schema['type']
  136. if isinstance(allowed_types, str):
  137. allowed_types = [allowed_types]
  138. value_type = {
  139. str: 'string', bool: 'boolean', int: 'integer', float: 'number',
  140. list: 'array', dict: 'object', type(None): 'null',
  141. }.get(type(value))
  142. if value_type not in allowed_types and not (
  143. value_type == 'integer' and 'number' in allowed_types
  144. ):
  145. return False
  146. if 'enum' in schema and value not in schema['enum']:
  147. return False
  148. if value_type in ('integer', 'number'):
  149. if value_type == 'number' and not math.isfinite(value):
  150. return False
  151. if 'minimum' in schema and value < schema['minimum']:
  152. return False
  153. if value_type == 'string':
  154. if 'pattern' in schema and re.fullmatch(schema['pattern'], value) is None:
  155. return False
  156. if schema.get('format') == 'uri' and value:
  157. try:
  158. url = urlsplit(value)
  159. if (url.scheme not in ('http', 'https') or not url.hostname
  160. or url.username is not None or url.password is not None
  161. or (url.port is not None and not 0 < url.port <= 65535)
  162. or any(ord(char) <= 32 for char in value)):
  163. return False
  164. except ValueError:
  165. return False
  166. if value_type == 'object':
  167. properties = schema['properties']
  168. if set(value) - set(properties) or set(schema['required']) - set(value):
  169. return False
  170. if len(value) < schema.get('minProperties', 0):
  171. return False
  172. return all(matches_schema(item, properties[key]) for key, item in value.items())
  173. if value_type == 'array':
  174. return all(matches_schema(item, schema['items']) for item in value)
  175. return True
  176. class GoodsAiPreAuditTool:
  177. def __init__(self, api_client=None):
  178. self.api_client = api_client
  179. def metadata(self):
  180. return {'name': self.name, 'description': self.description,
  181. 'input_schema': deepcopy(self.input_schema)}
  182. def build_payload(self, arguments):
  183. if not matches_schema(arguments, self.input_schema):
  184. raise ValueError('goods AI preaudit arguments are invalid')
  185. return arguments
  186. def call(self, request_id='', **arguments):
  187. if self.api_client is None:
  188. raise RuntimeError('api client is required for ' + self.name)
  189. return self.api_client.call_tool(
  190. self.name, self.route_path, self.build_payload(arguments),
  191. request_id or 'rq_' + self.name,
  192. )