app.py 38 KB

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