goods_ai_pre_audit_common.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. # Must match PHP GoodsAiPreAuditResult::REASON_BRIEF_MAX / SUMMARY_BRIEF_MAX.
  43. REASON_BRIEF_MAX = 20
  44. SUMMARY_BRIEF_MAX = 40
  45. # Must match PHP GoodsAiPreAuditResult::HINT_FIELDS / HINT_ROW_FIELDS; PHP only accepts pass/not_checked on them.
  46. HINT_FIELDS = ('recommended_grade', 'recommended_keyword', 'sync_orders')
  47. HINT_ROW_FIELDS = ('tax_rate', 'extra_tax', 'is_new_hscode', 'kit_tax_rate', 'is_new_kit',
  48. 'adjust_rate_data', 'adjust_tax_rate', 'total_tax_rate', 'tax_tag', 'box_value')
  49. def brief_schema(max_length):
  50. """One non-blank line; JSON Schema maxLength counts code points, like PHP mb_strlen."""
  51. return {'type': 'string', 'minLength': 1, 'maxLength': max_length,
  52. 'pattern': r'[^\r\n]*\S[^\r\n]*'}
  53. def closed_object(properties, required=()):
  54. return {
  55. 'type': 'object', 'properties': properties,
  56. 'required': list(required), 'additionalProperties': False,
  57. }
  58. ADJUST_RATE_ROW = closed_object({
  59. 'adjust_hscode': {'type': 'string'},
  60. 'adjust_rate': SCALAR,
  61. 'is_new_hscode': {'type': ['string', 'boolean', 'integer']},
  62. }, ('adjust_hscode', 'adjust_rate', 'is_new_hscode'))
  63. SYNC_ORDER_ROW = closed_object({
  64. 'order_id': {'type': ['string', 'integer']},
  65. 'order_number': {'type': 'string'},
  66. 'status_name': {'type': 'string'},
  67. }, ('order_id', 'order_number', 'status_name'))
  68. ROW_VALUES = {
  69. key: LEAF_VALUE for key in CLEARANCE_REQUIRED + CLEARANCE_HINTS
  70. }
  71. for _key in ('clearance_hscode', 'material', 'material_ratio', 'kit_hscode'):
  72. ROW_VALUES[_key] = {'type': 'string'}
  73. for _key in ('is_new_hscode', 'is_new_kit'):
  74. ROW_VALUES[_key] = {'type': ['string', 'boolean', 'integer']}
  75. ROW_VALUES['adjust_hscode_data'] = {'type': 'array', 'items': {'type': 'string'}}
  76. ROW_VALUES['adjust_rate_data'] = {'type': 'array', 'items': ADJUST_RATE_ROW}
  77. PAGE_VALUE_SCHEMAS = {key: LEAF_VALUE for key in PAGE_FIELDS}
  78. PAGE_VALUE_SCHEMAS.update({key: {'type': 'boolean'} for key in ATTRIBUTE_FIELDS})
  79. PAGE_VALUE_SCHEMAS['image_url'] = {
  80. 'anyOf': [{'type': 'null'}, {'type': 'string', 'format': 'uri'}],
  81. }
  82. PAGE_VALUE_SCHEMAS['sync_orders'] = {'type': 'array', 'items': SYNC_ORDER_ROW}
  83. PAGE_VALUE_SCHEMAS.update({
  84. key: {'type': 'array', 'items': closed_object(ROW_VALUES, CLEARANCE_REQUIRED)}
  85. for key in CLEARANCE_FIELDS
  86. })
  87. PAGE_VALUES_SCHEMA = dict(closed_object(PAGE_VALUE_SCHEMAS), minProperties=1)
  88. CERTIFICATION_FILE_GROUPS = ('battery_file', 'fda_file', 'toy_file', 'other_file')
  89. CERTIFICATION_FILE_SCHEMA = closed_object({
  90. 'name': {'type': 'string'},
  91. 'url': {'type': 'string', 'format': 'uri', 'pattern': r'[^\s\\\x00-\x1f\x7f]+'},
  92. }, ('name', 'url'))
  93. CERTIFICATION_FILES_SCHEMA = closed_object({
  94. group: {'type': 'array', 'items': CERTIFICATION_FILE_SCHEMA}
  95. for group in CERTIFICATION_FILE_GROUPS
  96. }, CERTIFICATION_FILE_GROUPS)
  97. CONTEXT_SCHEMA = closed_object({
  98. 'country_code': {'type': 'string'},
  99. 'departure_country': {'type': 'string'},
  100. 'certification_files': CERTIFICATION_FILES_SCHEMA,
  101. 'selected_labels': closed_object({
  102. key: {'anyOf': [
  103. {'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}},
  104. ]} for key in PAGE_FIELDS + ATTRIBUTE_FIELDS
  105. }),
  106. }, ('country_code', 'departure_country', 'selected_labels'))
  107. def field_result_schema(value_schema):
  108. return closed_object({
  109. 'value': value_schema,
  110. 'result': {'type': 'string', 'enum': list(FIELD_RESULTS)},
  111. 'suggested_value': {'anyOf': [{'type': 'null'}, value_schema]},
  112. 'reason': {'type': 'string'},
  113. 'reason_brief': brief_schema(REASON_BRIEF_MAX),
  114. }, ('value', 'result', 'suggested_value', 'reason', 'reason_brief'))
  115. FIELD_SCHEMAS = {
  116. key: field_result_schema(value) for key, value in PAGE_VALUE_SCHEMAS.items()
  117. if key not in CLEARANCE_FIELDS
  118. }
  119. FIELD_SCHEMAS.update({
  120. key: {'type': 'array', 'items': closed_object({
  121. field: field_result_schema(value) for field, value in ROW_VALUES.items()
  122. }, CLEARANCE_REQUIRED)} for key in CLEARANCE_FIELDS
  123. })
  124. CLAIM_INPUT_SCHEMA = closed_object({'goods_id': GOODS_ID})
  125. QUERY_INPUT_SCHEMA = closed_object({
  126. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE,
  127. }, ('goods_id', 'claim_ref'))
  128. SAVE_INPUT_SCHEMA = closed_object({
  129. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE,
  130. 'result': {'type': 'string', 'enum': list(OVERALL_RESULTS)},
  131. 'summary': {'type': 'string'},
  132. 'summary_brief': brief_schema(SUMMARY_BRIEF_MAX),
  133. 'fields': dict(closed_object(FIELD_SCHEMAS), minProperties=1),
  134. }, ('goods_id', 'claim_ref', 'source_ref', 'result', 'summary', 'summary_brief', 'fields'))
  135. RESPONSE_SCHEMAS = {
  136. 'claim_goods_ai_pre_audit': {'anyOf': [
  137. closed_object({'claimed': {'type': 'boolean', 'enum': [False]}}, ('claimed',)),
  138. closed_object({
  139. 'claimed': {'type': 'boolean', 'enum': [True]},
  140. 'goods_id': GOODS_ID, 'sku': {'type': 'string'},
  141. 'claim_ref': REFERENCE, 'expires_at': TIMESTAMP,
  142. }, ('claimed', 'goods_id', 'sku', 'claim_ref', 'expires_at')),
  143. ]},
  144. 'query_goods_ai_pre_audit': closed_object({
  145. 'goods_id': GOODS_ID, 'claim_ref': REFERENCE, 'source_ref': REFERENCE,
  146. 'context': CONTEXT_SCHEMA, 'page_values': PAGE_VALUES_SCHEMA,
  147. }, ('goods_id', 'claim_ref', 'source_ref', 'context', 'page_values')),
  148. 'save_goods_ai_pre_audit_result': closed_object({
  149. 'goods_id': GOODS_ID, 'saved': {'type': 'boolean', 'enum': [True]},
  150. 'ai_pre_audit_status': {'type': 'integer', 'enum': [2]},
  151. 'saved_at': TIMESTAMP,
  152. }, ('goods_id', 'saved', 'ai_pre_audit_status', 'saved_at')),
  153. }
  154. def matches_schema(value, schema):
  155. """Validate only the JSON Schema subset used by these closed contracts."""
  156. if 'anyOf' in schema:
  157. return any(matches_schema(value, option) for option in schema['anyOf'])
  158. allowed_types = schema['type']
  159. if isinstance(allowed_types, str):
  160. allowed_types = [allowed_types]
  161. value_type = {
  162. str: 'string', bool: 'boolean', int: 'integer', float: 'number',
  163. list: 'array', dict: 'object', type(None): 'null',
  164. }.get(type(value))
  165. if value_type not in allowed_types and not (
  166. value_type == 'integer' and 'number' in allowed_types
  167. ):
  168. return False
  169. if 'enum' in schema and value not in schema['enum']:
  170. return False
  171. if value_type in ('integer', 'number'):
  172. if value_type == 'number' and not math.isfinite(value):
  173. return False
  174. if 'minimum' in schema and value < schema['minimum']:
  175. return False
  176. if value_type == 'string':
  177. if 'minLength' in schema and len(value) < schema['minLength']:
  178. return False
  179. if 'maxLength' in schema and len(value) > schema['maxLength']:
  180. return False
  181. if 'pattern' in schema and re.fullmatch(schema['pattern'], value) is None:
  182. return False
  183. if schema.get('format') == 'uri' and value:
  184. try:
  185. url = urlsplit(value)
  186. if (url.scheme not in ('http', 'https') or not url.hostname
  187. or url.username is not None or url.password is not None
  188. or (url.port is not None and not 0 < url.port <= 65535)
  189. or any(ord(char) <= 32 for char in value)):
  190. return False
  191. except ValueError:
  192. return False
  193. if value_type == 'object':
  194. properties = schema['properties']
  195. if set(value) - set(properties) or set(schema['required']) - set(value):
  196. return False
  197. if len(value) < schema.get('minProperties', 0):
  198. return False
  199. return all(matches_schema(item, properties[key]) for key, item in value.items())
  200. if value_type == 'array':
  201. return all(matches_schema(item, schema['items']) for item in value)
  202. return True
  203. class GoodsAiPreAuditTool:
  204. def __init__(self, api_client=None):
  205. self.api_client = api_client
  206. def metadata(self):
  207. return {'name': self.name, 'description': self.description,
  208. 'input_schema': deepcopy(self.input_schema)}
  209. def build_payload(self, arguments):
  210. if not matches_schema(arguments, self.input_schema):
  211. raise ValueError('goods AI preaudit arguments are invalid')
  212. return arguments
  213. def call(self, request_id='', **arguments):
  214. if self.api_client is None:
  215. raise RuntimeError('api client is required for ' + self.name)
  216. return self.api_client.call_tool(
  217. self.name, self.route_path, self.build_payload(arguments),
  218. request_id or 'rq_' + self.name,
  219. )