app.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. import argparse
  2. import json
  3. import sys
  4. import uuid
  5. from config import GatewayConfig
  6. from constants import DEVICE_INVALID_MESSAGE
  7. from mcp_protocol import McpProtocolHandler
  8. from public_gateway import PublicGatewayApp
  9. from public_server import serve_public
  10. from services.api_client import ApiClient
  11. from services.auth_client import AuthClient
  12. from services.gateway_session_store import GatewaySessionStore
  13. from services.diagnostic_reporter import (
  14. NullDiagnosticReporter,
  15. diagnostic_reporter_from_config,
  16. )
  17. from services.scoped_api_client import ScopedApiClient
  18. from services.token_store import FileTokenStore, RedisSocketClient, RedisTokenStore
  19. from tools.list_order_filter_options import ListOrderFilterOptionsTool
  20. from tools.list_customer_filter_options import ListCustomerFilterOptionsTool
  21. from tools.list_receivable_cost_filter_options import (
  22. ListReceivableCostFilterOptionsTool,
  23. )
  24. from tools.list_outbound_filter_options import ListOutboundFilterOptionsTool
  25. from tools.export_pending_outbound_orders import ExportPendingOutboundOrdersTool
  26. from tools.export_out_of_province_port_data import (
  27. ExportOutOfProvincePortDataTool,
  28. )
  29. from tools.export_receivable_cost_list import ExportReceivableCostListTool
  30. from tools.list_pending_outbound_export_filter_options import (
  31. ListPendingOutboundExportFilterOptionsTool,
  32. )
  33. from tools.query_order import QueryOrderTool
  34. from tools.query_customs_declaration_files import (
  35. QueryCustomsDeclarationFilesTool,
  36. )
  37. from tools.query_order_exact import QueryOrderExactTool
  38. from tools.query_order_detail import QueryOrderDetailTool
  39. from tools.query_export_task import QueryExportTaskTool
  40. from tools.query_outbound_detail import QueryOutboundDetailTool
  41. from tools.query_outbound_list import QueryOutboundListTool
  42. from tools.query_track import QueryTrackTool
  43. from tools.query_customer_list import QueryCustomerListTool
  44. from tools.query_customer_payment_followup import QueryCustomerPaymentFollowupTool
  45. from tools.query_customer_unverified_bill_details import QueryCustomerUnverifiedBillDetailsTool
  46. from tools.query_customer_payment_records import QueryCustomerPaymentRecordsTool
  47. from tools.query_order_receivable_cost_details import (
  48. QueryOrderReceivableCostDetailsTool,
  49. )
  50. from tools.query_receivable_cost_list import QueryReceivableCostListTool
  51. from tools.query_payable_cost_list import QueryPayableCostListTool
  52. from tools.list_payable_cost_filter_options import ListPayableCostFilterOptionsTool
  53. from tools.export_payable_cost_list import ExportPayableCostListTool
  54. from tools.export_pallet_data import ExportPalletDataTool
  55. from tools.query_destination_trailer_list import QueryDestinationTrailerListTool
  56. from tools.list_destination_trailer_filter_options import (
  57. ListDestinationTrailerFilterOptionsTool,
  58. )
  59. from tools.query_order_abnormal_list import QueryOrderAbnormalListTool
  60. from tools.list_order_abnormal_filter_options import (
  61. ListOrderAbnormalFilterOptionsTool,
  62. )
  63. from tools.query_receive_volume_list import QueryReceiveVolumeListTool
  64. from tools.list_receive_volume_filter_options import (
  65. ListReceiveVolumeFilterOptionsTool,
  66. )
  67. from tools.query_goods_info import QueryGoodsInfoTool
  68. from tools.trial_goods_tax import TrialGoodsTaxTool
  69. from tools.query_container_timeliness_list import QueryContainerTimelinessListTool
  70. from tools.export_container_timeliness_report import (
  71. ExportContainerTimelinessReportTool,
  72. )
  73. def parse_int_list(value):
  74. if not value:
  75. return []
  76. return [int(item.strip()) for item in value.split(',') if item.strip()]
  77. def parse_string_list(value):
  78. result = []
  79. for item in (value or '').split(','):
  80. item = item.strip()
  81. if item and item not in result:
  82. result.append(item)
  83. return result
  84. class GatewayApp:
  85. def __init__(
  86. self,
  87. auth_client=None,
  88. api_client=None,
  89. token_store=None,
  90. reporter=None,
  91. ):
  92. self.auth_client = auth_client
  93. self.api_client = api_client
  94. self.token_store = token_store
  95. self.reporter = reporter or NullDiagnosticReporter()
  96. self._tools = {
  97. 'query_order': QueryOrderTool(api_client=api_client),
  98. 'query_track': QueryTrackTool(api_client=api_client),
  99. 'query_order_exact': QueryOrderExactTool(api_client=api_client),
  100. 'query_order_detail': QueryOrderDetailTool(api_client=api_client),
  101. 'query_customs_declaration_files':
  102. QueryCustomsDeclarationFilesTool(api_client=api_client),
  103. 'query_outbound_list': QueryOutboundListTool(api_client=api_client),
  104. 'query_outbound_detail': QueryOutboundDetailTool(api_client=api_client),
  105. 'query_customer_list': QueryCustomerListTool(api_client=api_client),
  106. 'query_customer_payment_followup': QueryCustomerPaymentFollowupTool(
  107. api_client=api_client
  108. ),
  109. 'query_customer_unverified_bill_details':
  110. QueryCustomerUnverifiedBillDetailsTool(api_client=api_client),
  111. 'query_customer_payment_records': QueryCustomerPaymentRecordsTool(
  112. api_client=api_client
  113. ),
  114. 'query_order_receivable_cost_details':
  115. QueryOrderReceivableCostDetailsTool(api_client=api_client),
  116. 'query_receivable_cost_list':
  117. QueryReceivableCostListTool(api_client=api_client),
  118. 'query_payable_cost_list':
  119. QueryPayableCostListTool(api_client=api_client),
  120. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  121. api_client=api_client
  122. ),
  123. 'list_order_filter_options': ListOrderFilterOptionsTool(
  124. api_client=api_client
  125. ),
  126. 'list_customer_filter_options': ListCustomerFilterOptionsTool(
  127. api_client=api_client
  128. ),
  129. 'list_receivable_cost_filter_options':
  130. ListReceivableCostFilterOptionsTool(api_client=api_client),
  131. 'list_payable_cost_filter_options':
  132. ListPayableCostFilterOptionsTool(api_client=api_client),
  133. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  134. api_client=api_client
  135. ),
  136. 'export_out_of_province_port_data':
  137. ExportOutOfProvincePortDataTool(api_client=api_client),
  138. 'export_receivable_cost_list': ExportReceivableCostListTool(
  139. api_client=api_client
  140. ),
  141. 'export_payable_cost_list': ExportPayableCostListTool(
  142. api_client=api_client
  143. ),
  144. 'export_pallet_data': ExportPalletDataTool(
  145. api_client=api_client
  146. ),
  147. 'query_export_task': QueryExportTaskTool(api_client=api_client),
  148. 'list_pending_outbound_export_filter_options':
  149. ListPendingOutboundExportFilterOptionsTool(api_client=api_client),
  150. 'query_destination_trailer_list': QueryDestinationTrailerListTool(
  151. api_client=api_client
  152. ),
  153. 'list_destination_trailer_filter_options':
  154. ListDestinationTrailerFilterOptionsTool(api_client=api_client),
  155. 'query_order_abnormal_list': QueryOrderAbnormalListTool(
  156. api_client=api_client
  157. ),
  158. 'list_order_abnormal_filter_options':
  159. ListOrderAbnormalFilterOptionsTool(api_client=api_client),
  160. 'query_receive_volume_list': QueryReceiveVolumeListTool(
  161. api_client=api_client
  162. ),
  163. 'query_goods_info': QueryGoodsInfoTool(api_client=api_client),
  164. 'trial_goods_tax': TrialGoodsTaxTool(api_client=api_client),
  165. 'list_receive_volume_filter_options':
  166. ListReceiveVolumeFilterOptionsTool(api_client=api_client),
  167. 'query_container_timeliness_list': QueryContainerTimelinessListTool(
  168. api_client=api_client
  169. ),
  170. 'export_container_timeliness_report':
  171. ExportContainerTimelinessReportTool(api_client=api_client),
  172. }
  173. @classmethod
  174. def from_config(cls, config, redis_client=None):
  175. if config.token_store_type == 'redis':
  176. redis = redis_client or RedisSocketClient(
  177. host=config.redis_host,
  178. port=config.redis_port,
  179. db=config.redis_db,
  180. password=config.redis_password,
  181. timeout=config.timeout_seconds,
  182. )
  183. token_store = RedisTokenStore(
  184. redis,
  185. prefix=config.redis_prefix,
  186. session_key=config.session_key,
  187. refresh_skew_seconds=config.refresh_skew_seconds,
  188. )
  189. elif config.token_store_type == 'file':
  190. token_store = FileTokenStore(
  191. config.token_store_path,
  192. refresh_skew_seconds=config.refresh_skew_seconds,
  193. )
  194. else:
  195. raise ValueError('unsupported token store type: {0}'.format(config.token_store_type))
  196. auth_client = AuthClient(
  197. base_url=config.auth_base_url,
  198. client_type=config.client_type,
  199. token_store=token_store,
  200. timeout=config.timeout_seconds,
  201. session_key=config.session_key,
  202. )
  203. api_client = ApiClient(
  204. base_url=config.tools_base_url,
  205. token_store=token_store,
  206. timeout=config.timeout_seconds,
  207. )
  208. return cls(
  209. auth_client=auth_client,
  210. api_client=api_client,
  211. token_store=token_store,
  212. reporter=diagnostic_reporter_from_config(config),
  213. )
  214. def registered_tool_names(self):
  215. return tuple(self._tools.keys())
  216. def _enabled_tool_names(self, response):
  217. if not isinstance(response, dict):
  218. raise RuntimeError('invalid enabled tool response')
  219. if response.get('code') != 'MCP_0000':
  220. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  221. data = response.get('data')
  222. codes = data.get('tool_codes') if isinstance(data, dict) else None
  223. if not isinstance(codes, list):
  224. raise RuntimeError('invalid enabled tool response')
  225. return {
  226. code.strip().lower()
  227. for code in codes
  228. if isinstance(code, str) and code.strip()
  229. }
  230. def _load_enabled_tool_names(self, request_id=''):
  231. if self.api_client is None or not hasattr(self.api_client, 'list_enabled_tools'):
  232. raise RuntimeError('enabled tool client unavailable')
  233. return self._enabled_tool_names(
  234. self.api_client.list_enabled_tools(request_id=request_id)
  235. )
  236. def list_tools(self, request_id=''):
  237. request_id = self.build_request_id(request_id)
  238. enabled = self._load_enabled_tool_names(request_id)
  239. return [
  240. tool.metadata()
  241. for name, tool in self._tools.items()
  242. if name in enabled
  243. ]
  244. def build_request_id(self, request_id=''):
  245. request_id = str(request_id or '').strip()
  246. if request_id:
  247. return request_id
  248. return 'rq_{0}'.format(uuid.uuid4().hex[:16])
  249. def ensure_session(self):
  250. if self.token_store is None:
  251. return
  252. session = self.token_store.get()
  253. if not session or not session.get('token'):
  254. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  255. if self.token_store.is_expiring():
  256. if self.auth_client is None:
  257. raise RuntimeError('mcp token expiring but auth client missing')
  258. self.auth_client.refresh(session['token'])
  259. def call_tool(self, name, arguments=None, request_id=''):
  260. if name not in self._tools:
  261. raise KeyError('tool not registered: {0}'.format(name))
  262. tool = self._tools[name]
  263. if getattr(tool, 'requires_session', True):
  264. self.ensure_session()
  265. request_id = self.build_request_id(request_id)
  266. if name not in self._load_enabled_tool_names(request_id):
  267. raise RuntimeError('tool disabled: {0}'.format(name))
  268. arguments = arguments or {}
  269. return tool.call(request_id=request_id, **arguments)
  270. def create_protocol_handler(self):
  271. return McpProtocolHandler(self, reporter=self.reporter)
  272. def run_cli(self, argv=None, stdin=None, stdout=None):
  273. stdin = stdin or sys.stdin
  274. stdout = stdout or sys.stdout
  275. parser = argparse.ArgumentParser(prog='mcp-gateway')
  276. subparsers = parser.add_subparsers(dest='command', required=True)
  277. subparsers.add_parser('list-tools')
  278. subparsers.add_parser('serve-stdio')
  279. public_parser = subparsers.add_parser('serve-public')
  280. public_parser.add_argument('--host', default='0.0.0.0')
  281. public_parser.add_argument('--port', type=int, default=8765)
  282. call_parser = subparsers.add_parser('call')
  283. call_parser.add_argument('--tool', required=True)
  284. call_parser.add_argument('--keyword', default='')
  285. call_parser.add_argument('--sku', default='')
  286. call_parser.add_argument('--cn-name', default='')
  287. call_parser.add_argument('--departure-country', default='')
  288. call_parser.add_argument('--destination-country', default='')
  289. call_parser.add_argument('--price', type=float, default=0)
  290. call_parser.add_argument('--qty', type=float, default=0)
  291. call_parser.add_argument('--gross-weight', type=float, default=0)
  292. call_parser.add_argument('--box', type=float, default=0)
  293. call_parser.add_argument('--order-id', type=int, default=0)
  294. call_parser.add_argument('--order-number', default='')
  295. call_parser.add_argument('--business-type', type=int, default=0)
  296. call_parser.add_argument('--section', default='全部')
  297. call_parser.add_argument('--order-numbers', default='')
  298. call_parser.add_argument('--tracking-number', default='')
  299. call_parser.add_argument('--tracking-numbers', default='')
  300. call_parser.add_argument('--reference-number', default='')
  301. call_parser.add_argument('--reference-numbers', default='')
  302. call_parser.add_argument('--outbound-number', default='')
  303. call_parser.add_argument('--outbound-numbers', default='')
  304. call_parser.add_argument('--bl-numbers', default='')
  305. call_parser.add_argument('--container-code', default='')
  306. call_parser.add_argument('--container-codes', default='')
  307. call_parser.add_argument('--so-number', default='')
  308. call_parser.add_argument('--so-numbers', default='')
  309. call_parser.add_argument('--shipment-id', default='')
  310. call_parser.add_argument('--receiver-country', default='')
  311. call_parser.add_argument('--product-ids', default='')
  312. call_parser.add_argument('--customer-ids', default='')
  313. call_parser.add_argument('--customer-id', type=int, default=0)
  314. call_parser.add_argument('--sub-customer-id', type=int, default=0)
  315. call_parser.add_argument('--bill-numbers', default='')
  316. call_parser.add_argument('--business-date-start', default='')
  317. call_parser.add_argument('--business-date-end', default='')
  318. call_parser.add_argument('--cost-date-start', default='')
  319. call_parser.add_argument('--cost-date-end', default='')
  320. call_parser.add_argument('--operation-date-start', default='')
  321. call_parser.add_argument('--operation-date-end', default='')
  322. call_parser.add_argument('--business-node-id', type=int, default=0)
  323. call_parser.add_argument('--provider-id', type=int, default=0)
  324. call_parser.add_argument('--cost-type-ids', default='')
  325. call_parser.add_argument('--billing-status', type=int, default=None)
  326. call_parser.add_argument('--payment-status', type=int, default=None)
  327. call_parser.add_argument('--verification-status', type=int, default=None)
  328. call_parser.add_argument('--document-type', type=int, default=None)
  329. call_parser.add_argument('--cost-type-id', type=int, default=0)
  330. call_parser.add_argument('--receive-date-start', default='')
  331. call_parser.add_argument('--receive-date-end', default='')
  332. call_parser.add_argument('--sales-id', type=int, default=0)
  333. call_parser.add_argument('--merchandiser-id', type=int, default=0)
  334. call_parser.add_argument(
  335. '--has-unverified-receivable-only',
  336. choices=('true', 'false'),
  337. default='true',
  338. )
  339. call_parser.add_argument('--warehouse-ids', default='')
  340. call_parser.add_argument('--warehouse-id', type=int, default=0)
  341. call_parser.add_argument('--department-id', type=int, default=0)
  342. call_parser.add_argument('--outbound-status', type=int, default=0)
  343. call_parser.add_argument('--shipping-method', type=int, default=0)
  344. call_parser.add_argument('--is-direct-send', type=int, default=None)
  345. call_parser.add_argument('--trailer-types', default='')
  346. call_parser.add_argument('--declaration-types', default='')
  347. call_parser.add_argument('--clearance-types', default='')
  348. call_parser.add_argument('--closing-time-start', default='')
  349. call_parser.add_argument('--closing-time-end', default='')
  350. call_parser.add_argument('--est-loading-time-start', default='')
  351. call_parser.add_argument('--est-loading-time-end', default='')
  352. call_parser.add_argument('--create-date-start', default='')
  353. call_parser.add_argument('--create-date-end', default='')
  354. call_parser.add_argument('--loading-time-start', default='')
  355. call_parser.add_argument('--loading-time-end', default='')
  356. call_parser.add_argument('--inbound-date-start', default='')
  357. call_parser.add_argument('--inbound-date-end', default='')
  358. call_parser.add_argument('--inbound-time-start', default='')
  359. call_parser.add_argument('--inbound-time-end', default='')
  360. call_parser.add_argument('--departure-time-start', default='')
  361. call_parser.add_argument('--departure-time-end', default='')
  362. call_parser.add_argument('--outbound-date-start', default='')
  363. call_parser.add_argument('--outbound-date-end', default='')
  364. call_parser.add_argument('--filter-type', default='')
  365. call_parser.add_argument('--trailer-stage', default='')
  366. call_parser.add_argument('--abnormal-status', default='')
  367. call_parser.add_argument('--sales-ids', default='')
  368. call_parser.add_argument('--merchandiser-ids', default='')
  369. call_parser.add_argument('--packing-types', default='')
  370. call_parser.add_argument('--providers-id', type=int, default=0)
  371. call_parser.add_argument('--bill-status', type=int, default=None)
  372. call_parser.add_argument('--cabinet-type', type=int, default=0)
  373. call_parser.add_argument('--eta-start', default='')
  374. call_parser.add_argument('--eta-end', default='')
  375. call_parser.add_argument('--pickup-time-start', default='')
  376. call_parser.add_argument('--pickup-time-end', default='')
  377. call_parser.add_argument('--container-return-time-start', default='')
  378. call_parser.add_argument('--container-return-time-end', default='')
  379. call_parser.add_argument('--task-ref', default='')
  380. call_parser.add_argument('--page', type=int, default=1)
  381. call_parser.add_argument('--limit', type=int, default=20)
  382. call_parser.add_argument('--request-id', default='')
  383. args = parser.parse_args(argv or [])
  384. if args.command == 'list-tools':
  385. payload = self.list_tools()
  386. elif args.command == 'serve-stdio':
  387. try:
  388. return self.create_protocol_handler().run_stdio(
  389. stdin=stdin,
  390. stdout=stdout,
  391. )
  392. finally:
  393. self.reporter.close()
  394. elif args.command == 'serve-public':
  395. config = GatewayConfig.from_env()
  396. reporter = self.reporter
  397. if isinstance(reporter, NullDiagnosticReporter):
  398. reporter = diagnostic_reporter_from_config(config)
  399. redis = RedisSocketClient(
  400. host=config.redis_host,
  401. port=config.redis_port,
  402. db=config.redis_db,
  403. password=config.redis_password,
  404. timeout=config.timeout_seconds,
  405. )
  406. session_store = GatewaySessionStore(
  407. redis,
  408. prefix=config.redis_prefix,
  409. ttl_seconds=config.gateway_session_ttl_seconds,
  410. )
  411. public_app = PublicGatewayApp(
  412. session_store=session_store,
  413. api_client=ScopedApiClient(config.tools_base_url, timeout=config.timeout_seconds),
  414. )
  415. try:
  416. return serve_public(
  417. public_app,
  418. host=args.host,
  419. port=args.port,
  420. enable_rate_limit=config.rate_limit_enabled,
  421. rate_limit_max_requests=config.rate_limit_max_requests,
  422. rate_limit_window_seconds=config.rate_limit_window_seconds,
  423. max_in_flight_per_tool=config.max_in_flight_per_tool,
  424. reporter=reporter,
  425. )
  426. finally:
  427. reporter.close()
  428. elif args.command == 'call':
  429. tool_args = {
  430. 'page': args.page,
  431. 'limit': args.limit,
  432. }
  433. if args.tool == 'query_order':
  434. if not args.keyword:
  435. raise ValueError('--keyword is required for query_order')
  436. tool_args['keyword'] = args.keyword
  437. elif args.tool == 'query_track':
  438. if args.order_id > 0:
  439. tool_args['order_id'] = args.order_id
  440. if args.order_number:
  441. tool_args['order_number'] = args.order_number
  442. if args.tracking_number:
  443. tool_args['tracking_number'] = args.tracking_number
  444. if args.order_id <= 0 and not args.order_number and not args.tracking_number:
  445. raise ValueError('--order-id, --order-number or --tracking-number is required for query_track')
  446. elif args.tool == 'query_order_exact':
  447. exact_strings = {
  448. 'order_number': args.order_number,
  449. 'reference_number': args.reference_number,
  450. 'tracking_number': args.tracking_number,
  451. 'outbound_number': args.outbound_number,
  452. 'container_code': args.container_code,
  453. 'so_number': args.so_number,
  454. 'shipment_id': args.shipment_id,
  455. 'receiver_country': args.receiver_country,
  456. 'inbound_date_start': args.inbound_date_start,
  457. 'inbound_date_end': args.inbound_date_end,
  458. 'outbound_date_start': args.outbound_date_start,
  459. 'outbound_date_end': args.outbound_date_end,
  460. }
  461. for field, value in exact_strings.items():
  462. if value:
  463. tool_args[field] = value
  464. exact_number_lists = {
  465. 'order_numbers': args.order_numbers,
  466. 'reference_numbers': args.reference_numbers,
  467. 'tracking_numbers': args.tracking_numbers,
  468. 'outbound_numbers': args.outbound_numbers,
  469. 'container_codes': args.container_codes,
  470. 'so_numbers': args.so_numbers,
  471. }
  472. for field, value in exact_number_lists.items():
  473. if value:
  474. tool_args[field] = parse_string_list(value)
  475. exact_lists = {
  476. 'product_ids': args.product_ids,
  477. 'customer_ids': args.customer_ids,
  478. 'warehouse_ids': args.warehouse_ids,
  479. }
  480. for field, value in exact_lists.items():
  481. if value:
  482. tool_args[field] = parse_int_list(value)
  483. if args.sales_id > 0:
  484. tool_args['sales_id'] = args.sales_id
  485. if args.department_id > 0:
  486. tool_args['department_id'] = args.department_id
  487. elif args.tool == 'query_order_detail':
  488. if not args.order_number:
  489. raise ValueError('--order-number is required for query_order_detail')
  490. tool_args['order_number'] = args.order_number
  491. tool_args['section'] = args.section
  492. elif args.tool == 'query_customer_list':
  493. for field, value in (
  494. ('customer_id', args.customer_id),
  495. ('department_id', args.department_id),
  496. ('sales_id', args.sales_id),
  497. ('merchandiser_id', args.merchandiser_id),
  498. ):
  499. if value > 0:
  500. tool_args[field] = value
  501. elif args.tool == 'query_customer_payment_followup':
  502. for field, value in (
  503. ('customer_id', args.customer_id),
  504. ('department_id', args.department_id),
  505. ('sales_id', args.sales_id),
  506. ('merchandiser_id', args.merchandiser_id),
  507. ):
  508. if value > 0:
  509. tool_args[field] = value
  510. tool_args['has_unverified_receivable_only'] = (
  511. args.has_unverified_receivable_only == 'true'
  512. )
  513. elif args.tool == 'query_customer_unverified_bill_details':
  514. if args.customer_id <= 0:
  515. raise ValueError(
  516. '--customer-id is required for query_customer_unverified_bill_details'
  517. )
  518. tool_args['customer_id'] = args.customer_id
  519. elif args.tool == 'query_customer_payment_records':
  520. if args.customer_id <= 0:
  521. raise ValueError(
  522. '--customer-id is required for query_customer_payment_records'
  523. )
  524. tool_args['customer_id'] = args.customer_id
  525. if args.receive_date_start:
  526. tool_args['receive_date_start'] = args.receive_date_start
  527. if args.receive_date_end:
  528. tool_args['receive_date_end'] = args.receive_date_end
  529. elif args.tool == 'query_order_receivable_cost_details':
  530. if not args.order_number:
  531. raise ValueError(
  532. '--order-number is required for query_order_receivable_cost_details'
  533. )
  534. tool_args['order_number'] = args.order_number
  535. elif args.tool in (
  536. 'query_payable_cost_list', 'export_payable_cost_list'
  537. ):
  538. if args.business_type <= 0:
  539. raise ValueError(
  540. '--business-type is required for ' + args.tool
  541. )
  542. tool_args['business_type'] = args.business_type
  543. payable_number_lists = {
  544. 'order_numbers': args.order_numbers,
  545. 'tracking_numbers': args.tracking_numbers,
  546. 'container_codes': args.container_codes,
  547. 'bl_numbers': args.bl_numbers,
  548. 'so_numbers': args.so_numbers,
  549. }
  550. for field, value in payable_number_lists.items():
  551. if value:
  552. tool_args[field] = parse_string_list(value)
  553. payable_dates = {
  554. 'business_date_start': args.business_date_start,
  555. 'business_date_end': args.business_date_end,
  556. 'cost_date_start': args.cost_date_start,
  557. 'cost_date_end': args.cost_date_end,
  558. 'operation_date_start': args.operation_date_start,
  559. 'operation_date_end': args.operation_date_end,
  560. }
  561. for field, value in payable_dates.items():
  562. if value:
  563. tool_args[field] = value
  564. for field, value in (
  565. ('business_node_id', args.business_node_id),
  566. ('provider_id', args.provider_id),
  567. ):
  568. if value > 0:
  569. tool_args[field] = value
  570. if args.cost_type_ids:
  571. tool_args['cost_type_ids'] = parse_int_list(
  572. args.cost_type_ids
  573. )
  574. for field, value in (
  575. ('billing_status', args.billing_status),
  576. ('payment_status', args.payment_status),
  577. ('verification_status', args.verification_status),
  578. ('document_type', args.document_type),
  579. ):
  580. if value is not None:
  581. tool_args[field] = value
  582. if args.tool == 'export_payable_cost_list':
  583. tool_args.pop('page', None)
  584. tool_args.pop('limit', None)
  585. elif args.tool == 'query_receivable_cost_list':
  586. for field, value in (
  587. ('reference_numbers', args.reference_numbers),
  588. ('tracking_numbers', args.tracking_numbers),
  589. ('order_numbers', args.order_numbers),
  590. ('bill_numbers', args.bill_numbers),
  591. ):
  592. if value:
  593. tool_args[field] = parse_string_list(value)
  594. for field, value in (
  595. ('business_date_start', args.business_date_start),
  596. ('business_date_end', args.business_date_end),
  597. ):
  598. if value:
  599. tool_args[field] = value
  600. for field, value in (
  601. ('customer_id', args.customer_id),
  602. ('sub_customer_id', args.sub_customer_id),
  603. ('cost_type_id', args.cost_type_id),
  604. ):
  605. if value > 0:
  606. tool_args[field] = value
  607. for field, value in (
  608. ('billing_status', args.billing_status),
  609. ('verification_status', args.verification_status),
  610. ('document_type', args.document_type),
  611. ):
  612. if value is not None:
  613. tool_args[field] = value
  614. elif args.tool == 'export_receivable_cost_list':
  615. for field, value in (
  616. ('reference_numbers', args.reference_numbers),
  617. ('tracking_numbers', args.tracking_numbers),
  618. ('order_numbers', args.order_numbers),
  619. ('bill_numbers', args.bill_numbers),
  620. ):
  621. if value:
  622. tool_args[field] = parse_string_list(value)
  623. for field, value in (
  624. ('business_date_start', args.business_date_start),
  625. ('business_date_end', args.business_date_end),
  626. ):
  627. if value:
  628. tool_args[field] = value
  629. for field, value in (
  630. ('customer_id', args.customer_id),
  631. ('sub_customer_id', args.sub_customer_id),
  632. ('cost_type_id', args.cost_type_id),
  633. ):
  634. if value > 0:
  635. tool_args[field] = value
  636. for field, value in (
  637. ('billing_status', args.billing_status),
  638. ('verification_status', args.verification_status),
  639. ('document_type', args.document_type),
  640. ):
  641. if value is not None:
  642. tool_args[field] = value
  643. tool_args.pop('page', None)
  644. tool_args.pop('limit', None)
  645. elif args.tool == 'query_customs_declaration_files':
  646. if args.outbound_numbers:
  647. tool_args['outbound_numbers'] = parse_string_list(
  648. args.outbound_numbers
  649. )
  650. if args.order_numbers:
  651. tool_args['order_numbers'] = parse_string_list(
  652. args.order_numbers
  653. )
  654. elif args.tool == 'query_outbound_list':
  655. outbound_number_lists = {
  656. 'outbound_numbers': args.outbound_numbers,
  657. 'order_numbers': args.order_numbers,
  658. 'container_codes': args.container_codes,
  659. 'so_numbers': args.so_numbers,
  660. 'bl_numbers': args.bl_numbers,
  661. }
  662. for field, value in outbound_number_lists.items():
  663. if value:
  664. tool_args[field] = parse_string_list(value)
  665. outbound_mode_lists = {
  666. 'trailer_types': args.trailer_types,
  667. 'declaration_types': args.declaration_types,
  668. 'clearance_types': args.clearance_types,
  669. }
  670. for field, value in outbound_mode_lists.items():
  671. if value:
  672. tool_args[field] = parse_int_list(value)
  673. outbound_dates = {
  674. 'closing_time_start': args.closing_time_start,
  675. 'closing_time_end': args.closing_time_end,
  676. 'est_loading_time_start': args.est_loading_time_start,
  677. 'est_loading_time_end': args.est_loading_time_end,
  678. 'create_date_start': args.create_date_start,
  679. 'create_date_end': args.create_date_end,
  680. 'loading_time_start': args.loading_time_start,
  681. 'loading_time_end': args.loading_time_end,
  682. }
  683. for field, value in outbound_dates.items():
  684. if value:
  685. tool_args[field] = value
  686. if args.outbound_status > 0:
  687. tool_args['outbound_status'] = args.outbound_status
  688. if args.shipping_method > 0:
  689. tool_args['shipping_method'] = args.shipping_method
  690. if args.warehouse_id == -1 or args.warehouse_id > 0:
  691. tool_args['warehouse_id'] = args.warehouse_id
  692. if args.is_direct_send is not None:
  693. tool_args['is_direct_send'] = args.is_direct_send
  694. elif args.tool == 'query_outbound_detail':
  695. if not args.outbound_number:
  696. raise ValueError(
  697. '--outbound-number is required for '
  698. 'query_outbound_detail'
  699. )
  700. tool_args['outbound_number'] = args.outbound_number
  701. elif args.tool == 'export_pallet_data':
  702. if args.container_codes:
  703. tool_args['container_codes'] = parse_string_list(
  704. args.container_codes
  705. )
  706. if args.bl_numbers:
  707. tool_args['bl_numbers'] = parse_string_list(
  708. args.bl_numbers
  709. )
  710. if args.inbound_time_start:
  711. tool_args['inbound_time_start'] = args.inbound_time_start
  712. if args.inbound_time_end:
  713. tool_args['inbound_time_end'] = args.inbound_time_end
  714. tool_args.pop('page', None)
  715. tool_args.pop('limit', None)
  716. elif args.tool == 'query_export_task':
  717. if not args.task_ref:
  718. raise ValueError(
  719. '--task-ref is required for query_export_task'
  720. )
  721. tool_args = {'task_ref': args.task_ref}
  722. elif args.tool == 'list_payable_cost_filter_options':
  723. if not args.filter_type:
  724. raise ValueError(
  725. '--filter-type is required for '
  726. 'list_payable_cost_filter_options'
  727. )
  728. tool_args['filter_type'] = args.filter_type
  729. tool_args['keyword'] = args.keyword
  730. if args.business_type > 0:
  731. tool_args['business_type'] = args.business_type
  732. elif args.tool == 'list_receivable_cost_filter_options':
  733. if not args.filter_type:
  734. raise ValueError(
  735. '--filter-type is required for '
  736. 'list_receivable_cost_filter_options'
  737. )
  738. tool_args['filter_type'] = args.filter_type
  739. tool_args['keyword'] = args.keyword
  740. if args.customer_id > 0:
  741. tool_args['customer_id'] = args.customer_id
  742. elif args.tool == 'query_destination_trailer_list':
  743. if not args.trailer_stage:
  744. raise ValueError(
  745. '--trailer-stage is required for '
  746. 'query_destination_trailer_list'
  747. )
  748. tool_args['trailer_stage'] = args.trailer_stage
  749. if args.bl_numbers:
  750. tool_args['bl_numbers'] = parse_string_list(args.bl_numbers)
  751. if args.container_codes:
  752. tool_args['container_codes'] = parse_string_list(
  753. args.container_codes
  754. )
  755. if args.providers_id > 0:
  756. tool_args['providers_id'] = args.providers_id
  757. if args.warehouse_id > 0:
  758. tool_args['warehouse_id'] = args.warehouse_id
  759. if args.is_direct_send is not None:
  760. tool_args['is_direct_send'] = args.is_direct_send
  761. if args.bill_status is not None:
  762. tool_args['bill_status'] = args.bill_status
  763. if args.cabinet_type > 0:
  764. tool_args['cabinet_type'] = args.cabinet_type
  765. if args.shipping_method > 0:
  766. tool_args['shipping_method'] = args.shipping_method
  767. trailer_dates = {
  768. 'eta_start': args.eta_start,
  769. 'eta_end': args.eta_end,
  770. 'pickup_time_start': args.pickup_time_start,
  771. 'pickup_time_end': args.pickup_time_end,
  772. 'container_return_time_start':
  773. args.container_return_time_start,
  774. 'container_return_time_end':
  775. args.container_return_time_end,
  776. }
  777. for field, value in trailer_dates.items():
  778. if value:
  779. tool_args[field] = value
  780. elif args.tool == 'query_order_abnormal_list':
  781. if not args.abnormal_status:
  782. raise ValueError(
  783. '--abnormal-status is required for '
  784. 'query_order_abnormal_list'
  785. )
  786. tool_args['abnormal_status'] = args.abnormal_status
  787. if args.order_numbers:
  788. tool_args['order_numbers'] = parse_string_list(
  789. args.order_numbers
  790. )
  791. elif args.tool == 'trial_goods_tax':
  792. tool_args['sku'] = args.sku
  793. tool_args['departure_country'] = args.departure_country
  794. tool_args['destination_country'] = args.destination_country
  795. tool_args['price'] = args.price
  796. tool_args['qty'] = args.qty
  797. tool_args['gross_weight'] = args.gross_weight
  798. tool_args['box'] = args.box
  799. elif args.tool == 'query_goods_info':
  800. if args.sku:
  801. tool_args['sku'] = args.sku
  802. if args.cn_name:
  803. tool_args['cn_name'] = args.cn_name
  804. if not args.sku and not args.cn_name:
  805. raise ValueError(
  806. '--sku or --cn-name is required for query_goods_info'
  807. )
  808. elif args.tool == 'query_receive_volume_list':
  809. if not args.inbound_date_start or not args.inbound_date_end:
  810. raise ValueError(
  811. '--inbound-date-start and --inbound-date-end are '
  812. 'required for query_receive_volume_list'
  813. )
  814. tool_args['inbound_date_start'] = args.inbound_date_start
  815. tool_args['inbound_date_end'] = args.inbound_date_end
  816. if args.customer_ids:
  817. tool_args['customer_ids'] = parse_int_list(args.customer_ids)
  818. if args.sales_ids:
  819. tool_args['sales_ids'] = parse_int_list(args.sales_ids)
  820. if args.merchandiser_ids:
  821. tool_args['merchandiser_ids'] = parse_int_list(
  822. args.merchandiser_ids
  823. )
  824. if args.packing_types:
  825. tool_args['packing_types'] = parse_string_list(
  826. args.packing_types
  827. )
  828. if args.product_ids:
  829. tool_args['product_ids'] = parse_int_list(args.product_ids)
  830. elif args.tool in (
  831. 'query_container_timeliness_list',
  832. 'export_container_timeliness_report',
  833. ):
  834. if args.container_codes:
  835. tool_args['container_codes'] = parse_string_list(
  836. args.container_codes
  837. )
  838. if args.bl_numbers:
  839. tool_args['bl_numbers'] = parse_string_list(args.bl_numbers)
  840. if args.departure_time_start:
  841. tool_args['departure_time_start'] = args.departure_time_start
  842. if args.departure_time_end:
  843. tool_args['departure_time_end'] = args.departure_time_end
  844. if args.tool == 'export_container_timeliness_report':
  845. tool_args.pop('page', None)
  846. tool_args.pop('limit', None)
  847. elif args.tool in (
  848. 'list_order_filter_options', 'list_outbound_filter_options',
  849. 'list_customer_filter_options',
  850. 'list_destination_trailer_filter_options',
  851. 'list_order_abnormal_filter_options',
  852. 'list_receive_volume_filter_options',
  853. ):
  854. if not args.filter_type:
  855. raise ValueError(
  856. '--filter-type is required for '
  857. + args.tool
  858. )
  859. tool_args['filter_type'] = args.filter_type
  860. tool_args['keyword'] = args.keyword
  861. else:
  862. if args.keyword:
  863. tool_args['keyword'] = args.keyword
  864. payload = self.call_tool(
  865. args.tool,
  866. tool_args,
  867. request_id=args.request_id,
  868. )
  869. else:
  870. raise RuntimeError('unsupported command')
  871. stdout.write(json.dumps(payload, ensure_ascii=False))
  872. return 0
  873. def main(argv=None):
  874. config = GatewayConfig.from_env()
  875. app = GatewayApp.from_config(config)
  876. return app.run_cli(argv=argv)
  877. if __name__ == '__main__':
  878. raise SystemExit(main(sys.argv[1:]))