app.py 29 KB

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