app.py 34 KB

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