app.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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. def parse_int_list(value):
  55. if not value:
  56. return []
  57. return [int(item.strip()) for item in value.split(',') if item.strip()]
  58. def parse_string_list(value):
  59. result = []
  60. for item in (value or '').split(','):
  61. item = item.strip()
  62. if item and item not in result:
  63. result.append(item)
  64. return result
  65. class GatewayApp:
  66. def __init__(
  67. self,
  68. auth_client=None,
  69. api_client=None,
  70. token_store=None,
  71. reporter=None,
  72. ):
  73. self.auth_client = auth_client
  74. self.api_client = api_client
  75. self.token_store = token_store
  76. self.reporter = reporter or NullDiagnosticReporter()
  77. self._tools = {
  78. 'query_order': QueryOrderTool(api_client=api_client),
  79. 'query_track': QueryTrackTool(api_client=api_client),
  80. 'query_order_exact': QueryOrderExactTool(api_client=api_client),
  81. 'query_order_detail': QueryOrderDetailTool(api_client=api_client),
  82. 'query_customs_declaration_files':
  83. QueryCustomsDeclarationFilesTool(api_client=api_client),
  84. 'query_outbound_list': QueryOutboundListTool(api_client=api_client),
  85. 'query_outbound_detail': QueryOutboundDetailTool(api_client=api_client),
  86. 'query_customer_list': QueryCustomerListTool(api_client=api_client),
  87. 'query_customer_payment_followup': QueryCustomerPaymentFollowupTool(
  88. api_client=api_client
  89. ),
  90. 'query_customer_unverified_bill_details':
  91. QueryCustomerUnverifiedBillDetailsTool(api_client=api_client),
  92. 'query_customer_payment_records': QueryCustomerPaymentRecordsTool(
  93. api_client=api_client
  94. ),
  95. 'query_order_receivable_cost_details':
  96. QueryOrderReceivableCostDetailsTool(api_client=api_client),
  97. 'query_receivable_cost_list':
  98. QueryReceivableCostListTool(api_client=api_client),
  99. 'query_payable_cost_list':
  100. QueryPayableCostListTool(api_client=api_client),
  101. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  102. api_client=api_client
  103. ),
  104. 'list_order_filter_options': ListOrderFilterOptionsTool(
  105. api_client=api_client
  106. ),
  107. 'list_customer_filter_options': ListCustomerFilterOptionsTool(
  108. api_client=api_client
  109. ),
  110. 'list_receivable_cost_filter_options':
  111. ListReceivableCostFilterOptionsTool(api_client=api_client),
  112. 'list_payable_cost_filter_options':
  113. ListPayableCostFilterOptionsTool(api_client=api_client),
  114. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  115. api_client=api_client
  116. ),
  117. 'export_out_of_province_port_data':
  118. ExportOutOfProvincePortDataTool(api_client=api_client),
  119. 'export_receivable_cost_list': ExportReceivableCostListTool(
  120. api_client=api_client
  121. ),
  122. 'export_payable_cost_list': ExportPayableCostListTool(
  123. api_client=api_client
  124. ),
  125. 'query_export_task': QueryExportTaskTool(api_client=api_client),
  126. 'list_pending_outbound_export_filter_options':
  127. ListPendingOutboundExportFilterOptionsTool(api_client=api_client),
  128. }
  129. @classmethod
  130. def from_config(cls, config, redis_client=None):
  131. if config.token_store_type == 'redis':
  132. redis = redis_client or RedisSocketClient(
  133. host=config.redis_host,
  134. port=config.redis_port,
  135. db=config.redis_db,
  136. password=config.redis_password,
  137. timeout=config.timeout_seconds,
  138. )
  139. token_store = RedisTokenStore(
  140. redis,
  141. prefix=config.redis_prefix,
  142. session_key=config.session_key,
  143. refresh_skew_seconds=config.refresh_skew_seconds,
  144. )
  145. elif config.token_store_type == 'file':
  146. token_store = FileTokenStore(
  147. config.token_store_path,
  148. refresh_skew_seconds=config.refresh_skew_seconds,
  149. )
  150. else:
  151. raise ValueError('unsupported token store type: {0}'.format(config.token_store_type))
  152. auth_client = AuthClient(
  153. base_url=config.auth_base_url,
  154. client_type=config.client_type,
  155. token_store=token_store,
  156. timeout=config.timeout_seconds,
  157. session_key=config.session_key,
  158. )
  159. api_client = ApiClient(
  160. base_url=config.tools_base_url,
  161. token_store=token_store,
  162. timeout=config.timeout_seconds,
  163. )
  164. return cls(
  165. auth_client=auth_client,
  166. api_client=api_client,
  167. token_store=token_store,
  168. reporter=diagnostic_reporter_from_config(config),
  169. )
  170. def registered_tool_names(self):
  171. return tuple(self._tools.keys())
  172. def _enabled_tool_names(self, response):
  173. if not isinstance(response, dict):
  174. raise RuntimeError('invalid enabled tool response')
  175. if response.get('code') != 'MCP_0000':
  176. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  177. data = response.get('data')
  178. codes = data.get('tool_codes') if isinstance(data, dict) else None
  179. if not isinstance(codes, list):
  180. raise RuntimeError('invalid enabled tool response')
  181. return {
  182. code.strip().lower()
  183. for code in codes
  184. if isinstance(code, str) and code.strip()
  185. }
  186. def _load_enabled_tool_names(self, request_id=''):
  187. if self.api_client is None or not hasattr(self.api_client, 'list_enabled_tools'):
  188. raise RuntimeError('enabled tool client unavailable')
  189. return self._enabled_tool_names(
  190. self.api_client.list_enabled_tools(request_id=request_id)
  191. )
  192. def list_tools(self, request_id=''):
  193. request_id = self.build_request_id(request_id)
  194. enabled = self._load_enabled_tool_names(request_id)
  195. return [
  196. tool.metadata()
  197. for name, tool in self._tools.items()
  198. if name in enabled
  199. ]
  200. def build_request_id(self, request_id=''):
  201. request_id = str(request_id or '').strip()
  202. if request_id:
  203. return request_id
  204. return 'rq_{0}'.format(uuid.uuid4().hex[:16])
  205. def ensure_session(self):
  206. if self.token_store is None:
  207. return
  208. session = self.token_store.get()
  209. if not session or not session.get('token'):
  210. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  211. if self.token_store.is_expiring():
  212. if self.auth_client is None:
  213. raise RuntimeError('mcp token expiring but auth client missing')
  214. self.auth_client.refresh(session['token'])
  215. def call_tool(self, name, arguments=None, request_id=''):
  216. if name not in self._tools:
  217. raise KeyError('tool not registered: {0}'.format(name))
  218. tool = self._tools[name]
  219. if getattr(tool, 'requires_session', True):
  220. self.ensure_session()
  221. request_id = self.build_request_id(request_id)
  222. if name not in self._load_enabled_tool_names(request_id):
  223. raise RuntimeError('tool disabled: {0}'.format(name))
  224. arguments = arguments or {}
  225. return tool.call(request_id=request_id, **arguments)
  226. def create_protocol_handler(self):
  227. return McpProtocolHandler(self, reporter=self.reporter)
  228. def run_cli(self, argv=None, stdin=None, stdout=None):
  229. stdin = stdin or sys.stdin
  230. stdout = stdout or sys.stdout
  231. parser = argparse.ArgumentParser(prog='mcp-gateway')
  232. subparsers = parser.add_subparsers(dest='command', required=True)
  233. subparsers.add_parser('list-tools')
  234. subparsers.add_parser('serve-stdio')
  235. public_parser = subparsers.add_parser('serve-public')
  236. public_parser.add_argument('--host', default='0.0.0.0')
  237. public_parser.add_argument('--port', type=int, default=8765)
  238. call_parser = subparsers.add_parser('call')
  239. call_parser.add_argument('--tool', required=True)
  240. call_parser.add_argument('--keyword', default='')
  241. call_parser.add_argument('--order-id', type=int, default=0)
  242. call_parser.add_argument('--order-number', default='')
  243. call_parser.add_argument('--business-type', type=int, default=0)
  244. call_parser.add_argument('--section', default='全部')
  245. call_parser.add_argument('--order-numbers', default='')
  246. call_parser.add_argument('--tracking-number', default='')
  247. call_parser.add_argument('--tracking-numbers', default='')
  248. call_parser.add_argument('--reference-number', default='')
  249. call_parser.add_argument('--reference-numbers', default='')
  250. call_parser.add_argument('--outbound-number', default='')
  251. call_parser.add_argument('--outbound-numbers', default='')
  252. call_parser.add_argument('--bl-numbers', default='')
  253. call_parser.add_argument('--container-code', default='')
  254. call_parser.add_argument('--container-codes', default='')
  255. call_parser.add_argument('--so-number', default='')
  256. call_parser.add_argument('--so-numbers', default='')
  257. call_parser.add_argument('--shipment-id', default='')
  258. call_parser.add_argument('--receiver-country', default='')
  259. call_parser.add_argument('--product-ids', default='')
  260. call_parser.add_argument('--customer-ids', default='')
  261. call_parser.add_argument('--customer-id', type=int, default=0)
  262. call_parser.add_argument('--sub-customer-id', type=int, default=0)
  263. call_parser.add_argument('--bill-numbers', default='')
  264. call_parser.add_argument('--business-date-start', default='')
  265. call_parser.add_argument('--business-date-end', default='')
  266. call_parser.add_argument('--cost-date-start', default='')
  267. call_parser.add_argument('--cost-date-end', default='')
  268. call_parser.add_argument('--operation-date-start', default='')
  269. call_parser.add_argument('--operation-date-end', default='')
  270. call_parser.add_argument('--business-node-id', type=int, default=0)
  271. call_parser.add_argument('--provider-id', type=int, default=0)
  272. call_parser.add_argument('--cost-type-ids', default='')
  273. call_parser.add_argument('--billing-status', type=int, default=None)
  274. call_parser.add_argument('--payment-status', type=int, default=None)
  275. call_parser.add_argument('--verification-status', type=int, default=None)
  276. call_parser.add_argument('--document-type', type=int, default=None)
  277. call_parser.add_argument('--cost-type-id', type=int, default=0)
  278. call_parser.add_argument('--receive-date-start', default='')
  279. call_parser.add_argument('--receive-date-end', default='')
  280. call_parser.add_argument('--sales-id', type=int, default=0)
  281. call_parser.add_argument('--merchandiser-id', type=int, default=0)
  282. call_parser.add_argument(
  283. '--has-unverified-receivable-only',
  284. choices=('true', 'false'),
  285. default='true',
  286. )
  287. call_parser.add_argument('--warehouse-ids', default='')
  288. call_parser.add_argument('--warehouse-id', type=int, default=0)
  289. call_parser.add_argument('--department-id', type=int, default=0)
  290. call_parser.add_argument('--outbound-status', type=int, default=0)
  291. call_parser.add_argument('--shipping-method', type=int, default=0)
  292. call_parser.add_argument('--is-direct-send', type=int, default=None)
  293. call_parser.add_argument('--trailer-types', default='')
  294. call_parser.add_argument('--declaration-types', default='')
  295. call_parser.add_argument('--clearance-types', default='')
  296. call_parser.add_argument('--closing-time-start', default='')
  297. call_parser.add_argument('--closing-time-end', default='')
  298. call_parser.add_argument('--est-loading-time-start', default='')
  299. call_parser.add_argument('--est-loading-time-end', default='')
  300. call_parser.add_argument('--create-date-start', default='')
  301. call_parser.add_argument('--create-date-end', default='')
  302. call_parser.add_argument('--loading-time-start', default='')
  303. call_parser.add_argument('--loading-time-end', default='')
  304. call_parser.add_argument('--inbound-date-start', default='')
  305. call_parser.add_argument('--inbound-date-end', default='')
  306. call_parser.add_argument('--outbound-date-start', default='')
  307. call_parser.add_argument('--outbound-date-end', default='')
  308. call_parser.add_argument('--filter-type', default='')
  309. call_parser.add_argument('--task-ref', default='')
  310. call_parser.add_argument('--page', type=int, default=1)
  311. call_parser.add_argument('--limit', type=int, default=20)
  312. call_parser.add_argument('--request-id', default='')
  313. args = parser.parse_args(argv or [])
  314. if args.command == 'list-tools':
  315. payload = self.list_tools()
  316. elif args.command == 'serve-stdio':
  317. try:
  318. return self.create_protocol_handler().run_stdio(
  319. stdin=stdin,
  320. stdout=stdout,
  321. )
  322. finally:
  323. self.reporter.close()
  324. elif args.command == 'serve-public':
  325. config = GatewayConfig.from_env()
  326. reporter = self.reporter
  327. if isinstance(reporter, NullDiagnosticReporter):
  328. reporter = diagnostic_reporter_from_config(config)
  329. redis = RedisSocketClient(
  330. host=config.redis_host,
  331. port=config.redis_port,
  332. db=config.redis_db,
  333. password=config.redis_password,
  334. timeout=config.timeout_seconds,
  335. )
  336. session_store = GatewaySessionStore(
  337. redis,
  338. prefix=config.redis_prefix,
  339. ttl_seconds=config.gateway_session_ttl_seconds,
  340. )
  341. public_app = PublicGatewayApp(
  342. session_store=session_store,
  343. api_client=ScopedApiClient(config.tools_base_url, timeout=config.timeout_seconds),
  344. )
  345. try:
  346. return serve_public(
  347. public_app,
  348. host=args.host,
  349. port=args.port,
  350. enable_rate_limit=config.rate_limit_enabled,
  351. rate_limit_max_requests=config.rate_limit_max_requests,
  352. rate_limit_window_seconds=config.rate_limit_window_seconds,
  353. max_in_flight_per_tool=config.max_in_flight_per_tool,
  354. reporter=reporter,
  355. )
  356. finally:
  357. reporter.close()
  358. elif args.command == 'call':
  359. tool_args = {
  360. 'page': args.page,
  361. 'limit': args.limit,
  362. }
  363. if args.tool == 'query_order':
  364. if not args.keyword:
  365. raise ValueError('--keyword is required for query_order')
  366. tool_args['keyword'] = args.keyword
  367. elif args.tool == 'query_track':
  368. if args.order_id > 0:
  369. tool_args['order_id'] = args.order_id
  370. if args.order_number:
  371. tool_args['order_number'] = args.order_number
  372. if args.tracking_number:
  373. tool_args['tracking_number'] = args.tracking_number
  374. if args.order_id <= 0 and not args.order_number and not args.tracking_number:
  375. raise ValueError('--order-id, --order-number or --tracking-number is required for query_track')
  376. elif args.tool == 'query_order_exact':
  377. exact_strings = {
  378. 'order_number': args.order_number,
  379. 'reference_number': args.reference_number,
  380. 'tracking_number': args.tracking_number,
  381. 'outbound_number': args.outbound_number,
  382. 'container_code': args.container_code,
  383. 'so_number': args.so_number,
  384. 'shipment_id': args.shipment_id,
  385. 'receiver_country': args.receiver_country,
  386. 'inbound_date_start': args.inbound_date_start,
  387. 'inbound_date_end': args.inbound_date_end,
  388. 'outbound_date_start': args.outbound_date_start,
  389. 'outbound_date_end': args.outbound_date_end,
  390. }
  391. for field, value in exact_strings.items():
  392. if value:
  393. tool_args[field] = value
  394. exact_number_lists = {
  395. 'order_numbers': args.order_numbers,
  396. 'reference_numbers': args.reference_numbers,
  397. 'tracking_numbers': args.tracking_numbers,
  398. 'outbound_numbers': args.outbound_numbers,
  399. 'container_codes': args.container_codes,
  400. 'so_numbers': args.so_numbers,
  401. }
  402. for field, value in exact_number_lists.items():
  403. if value:
  404. tool_args[field] = parse_string_list(value)
  405. exact_lists = {
  406. 'product_ids': args.product_ids,
  407. 'customer_ids': args.customer_ids,
  408. 'warehouse_ids': args.warehouse_ids,
  409. }
  410. for field, value in exact_lists.items():
  411. if value:
  412. tool_args[field] = parse_int_list(value)
  413. if args.sales_id > 0:
  414. tool_args['sales_id'] = args.sales_id
  415. if args.department_id > 0:
  416. tool_args['department_id'] = args.department_id
  417. elif args.tool == 'query_order_detail':
  418. if not args.order_number:
  419. raise ValueError('--order-number is required for query_order_detail')
  420. tool_args['order_number'] = args.order_number
  421. tool_args['section'] = args.section
  422. elif args.tool == 'query_customer_list':
  423. for field, value in (
  424. ('customer_id', args.customer_id),
  425. ('department_id', args.department_id),
  426. ('sales_id', args.sales_id),
  427. ('merchandiser_id', args.merchandiser_id),
  428. ):
  429. if value > 0:
  430. tool_args[field] = value
  431. elif args.tool == 'query_customer_payment_followup':
  432. for field, value in (
  433. ('customer_id', args.customer_id),
  434. ('department_id', args.department_id),
  435. ('sales_id', args.sales_id),
  436. ('merchandiser_id', args.merchandiser_id),
  437. ):
  438. if value > 0:
  439. tool_args[field] = value
  440. tool_args['has_unverified_receivable_only'] = (
  441. args.has_unverified_receivable_only == 'true'
  442. )
  443. elif args.tool == 'query_customer_unverified_bill_details':
  444. if args.customer_id <= 0:
  445. raise ValueError(
  446. '--customer-id is required for query_customer_unverified_bill_details'
  447. )
  448. tool_args['customer_id'] = args.customer_id
  449. elif args.tool == 'query_customer_payment_records':
  450. if args.customer_id <= 0:
  451. raise ValueError(
  452. '--customer-id is required for query_customer_payment_records'
  453. )
  454. tool_args['customer_id'] = args.customer_id
  455. if args.receive_date_start:
  456. tool_args['receive_date_start'] = args.receive_date_start
  457. if args.receive_date_end:
  458. tool_args['receive_date_end'] = args.receive_date_end
  459. elif args.tool == 'query_order_receivable_cost_details':
  460. if not args.order_number:
  461. raise ValueError(
  462. '--order-number is required for query_order_receivable_cost_details'
  463. )
  464. tool_args['order_number'] = args.order_number
  465. elif args.tool in (
  466. 'query_payable_cost_list', 'export_payable_cost_list'
  467. ):
  468. if args.business_type <= 0:
  469. raise ValueError(
  470. '--business-type is required for ' + args.tool
  471. )
  472. tool_args['business_type'] = args.business_type
  473. payable_number_lists = {
  474. 'order_numbers': args.order_numbers,
  475. 'tracking_numbers': args.tracking_numbers,
  476. 'container_codes': args.container_codes,
  477. 'bl_numbers': args.bl_numbers,
  478. 'so_numbers': args.so_numbers,
  479. }
  480. for field, value in payable_number_lists.items():
  481. if value:
  482. tool_args[field] = parse_string_list(value)
  483. payable_dates = {
  484. 'business_date_start': args.business_date_start,
  485. 'business_date_end': args.business_date_end,
  486. 'cost_date_start': args.cost_date_start,
  487. 'cost_date_end': args.cost_date_end,
  488. 'operation_date_start': args.operation_date_start,
  489. 'operation_date_end': args.operation_date_end,
  490. }
  491. for field, value in payable_dates.items():
  492. if value:
  493. tool_args[field] = value
  494. for field, value in (
  495. ('business_node_id', args.business_node_id),
  496. ('provider_id', args.provider_id),
  497. ):
  498. if value > 0:
  499. tool_args[field] = value
  500. if args.cost_type_ids:
  501. tool_args['cost_type_ids'] = parse_int_list(
  502. args.cost_type_ids
  503. )
  504. for field, value in (
  505. ('billing_status', args.billing_status),
  506. ('payment_status', args.payment_status),
  507. ('verification_status', args.verification_status),
  508. ('document_type', args.document_type),
  509. ):
  510. if value is not None:
  511. tool_args[field] = value
  512. if args.tool == 'export_payable_cost_list':
  513. tool_args.pop('page', None)
  514. tool_args.pop('limit', None)
  515. elif args.tool == 'query_receivable_cost_list':
  516. for field, value in (
  517. ('reference_numbers', args.reference_numbers),
  518. ('tracking_numbers', args.tracking_numbers),
  519. ('order_numbers', args.order_numbers),
  520. ('bill_numbers', args.bill_numbers),
  521. ):
  522. if value:
  523. tool_args[field] = parse_string_list(value)
  524. for field, value in (
  525. ('business_date_start', args.business_date_start),
  526. ('business_date_end', args.business_date_end),
  527. ):
  528. if value:
  529. tool_args[field] = value
  530. for field, value in (
  531. ('customer_id', args.customer_id),
  532. ('sub_customer_id', args.sub_customer_id),
  533. ('cost_type_id', args.cost_type_id),
  534. ):
  535. if value > 0:
  536. tool_args[field] = value
  537. for field, value in (
  538. ('billing_status', args.billing_status),
  539. ('verification_status', args.verification_status),
  540. ('document_type', args.document_type),
  541. ):
  542. if value is not None:
  543. tool_args[field] = value
  544. elif args.tool == 'export_receivable_cost_list':
  545. for field, value in (
  546. ('reference_numbers', args.reference_numbers),
  547. ('tracking_numbers', args.tracking_numbers),
  548. ('order_numbers', args.order_numbers),
  549. ('bill_numbers', args.bill_numbers),
  550. ):
  551. if value:
  552. tool_args[field] = parse_string_list(value)
  553. for field, value in (
  554. ('business_date_start', args.business_date_start),
  555. ('business_date_end', args.business_date_end),
  556. ):
  557. if value:
  558. tool_args[field] = value
  559. for field, value in (
  560. ('customer_id', args.customer_id),
  561. ('sub_customer_id', args.sub_customer_id),
  562. ('cost_type_id', args.cost_type_id),
  563. ):
  564. if value > 0:
  565. tool_args[field] = value
  566. for field, value in (
  567. ('billing_status', args.billing_status),
  568. ('verification_status', args.verification_status),
  569. ('document_type', args.document_type),
  570. ):
  571. if value is not None:
  572. tool_args[field] = value
  573. tool_args.pop('page', None)
  574. tool_args.pop('limit', None)
  575. elif args.tool == 'query_customs_declaration_files':
  576. if args.outbound_numbers:
  577. tool_args['outbound_numbers'] = parse_string_list(
  578. args.outbound_numbers
  579. )
  580. if args.order_numbers:
  581. tool_args['order_numbers'] = parse_string_list(
  582. args.order_numbers
  583. )
  584. elif args.tool == 'query_outbound_list':
  585. outbound_number_lists = {
  586. 'outbound_numbers': args.outbound_numbers,
  587. 'order_numbers': args.order_numbers,
  588. 'container_codes': args.container_codes,
  589. 'so_numbers': args.so_numbers,
  590. 'bl_numbers': args.bl_numbers,
  591. }
  592. for field, value in outbound_number_lists.items():
  593. if value:
  594. tool_args[field] = parse_string_list(value)
  595. outbound_mode_lists = {
  596. 'trailer_types': args.trailer_types,
  597. 'declaration_types': args.declaration_types,
  598. 'clearance_types': args.clearance_types,
  599. }
  600. for field, value in outbound_mode_lists.items():
  601. if value:
  602. tool_args[field] = parse_int_list(value)
  603. outbound_dates = {
  604. 'closing_time_start': args.closing_time_start,
  605. 'closing_time_end': args.closing_time_end,
  606. 'est_loading_time_start': args.est_loading_time_start,
  607. 'est_loading_time_end': args.est_loading_time_end,
  608. 'create_date_start': args.create_date_start,
  609. 'create_date_end': args.create_date_end,
  610. 'loading_time_start': args.loading_time_start,
  611. 'loading_time_end': args.loading_time_end,
  612. }
  613. for field, value in outbound_dates.items():
  614. if value:
  615. tool_args[field] = value
  616. if args.outbound_status > 0:
  617. tool_args['outbound_status'] = args.outbound_status
  618. if args.shipping_method > 0:
  619. tool_args['shipping_method'] = args.shipping_method
  620. if args.warehouse_id == -1 or args.warehouse_id > 0:
  621. tool_args['warehouse_id'] = args.warehouse_id
  622. if args.is_direct_send is not None:
  623. tool_args['is_direct_send'] = args.is_direct_send
  624. elif args.tool == 'query_outbound_detail':
  625. if not args.outbound_number:
  626. raise ValueError(
  627. '--outbound-number is required for '
  628. 'query_outbound_detail'
  629. )
  630. tool_args['outbound_number'] = args.outbound_number
  631. elif args.tool == 'query_export_task':
  632. if not args.task_ref:
  633. raise ValueError(
  634. '--task-ref is required for query_export_task'
  635. )
  636. tool_args = {'task_ref': args.task_ref}
  637. elif args.tool == 'list_payable_cost_filter_options':
  638. if not args.filter_type:
  639. raise ValueError(
  640. '--filter-type is required for '
  641. 'list_payable_cost_filter_options'
  642. )
  643. tool_args['filter_type'] = args.filter_type
  644. tool_args['keyword'] = args.keyword
  645. if args.business_type > 0:
  646. tool_args['business_type'] = args.business_type
  647. elif args.tool == 'list_receivable_cost_filter_options':
  648. if not args.filter_type:
  649. raise ValueError(
  650. '--filter-type is required for '
  651. 'list_receivable_cost_filter_options'
  652. )
  653. tool_args['filter_type'] = args.filter_type
  654. tool_args['keyword'] = args.keyword
  655. if args.customer_id > 0:
  656. tool_args['customer_id'] = args.customer_id
  657. elif args.tool in (
  658. 'list_order_filter_options', 'list_outbound_filter_options',
  659. 'list_customer_filter_options'
  660. ):
  661. if not args.filter_type:
  662. raise ValueError(
  663. '--filter-type is required for '
  664. + args.tool
  665. )
  666. tool_args['filter_type'] = args.filter_type
  667. tool_args['keyword'] = args.keyword
  668. else:
  669. if args.keyword:
  670. tool_args['keyword'] = args.keyword
  671. payload = self.call_tool(
  672. args.tool,
  673. tool_args,
  674. request_id=args.request_id,
  675. )
  676. else:
  677. raise RuntimeError('unsupported command')
  678. stdout.write(json.dumps(payload, ensure_ascii=False))
  679. return 0
  680. def main(argv=None):
  681. config = GatewayConfig.from_env()
  682. app = GatewayApp.from_config(config)
  683. return app.run_cli(argv=argv)
  684. if __name__ == '__main__':
  685. raise SystemExit(main(sys.argv[1:]))