app.py 37 KB

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