goods_ai_pre_audit_common.py 11 KB

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