app.py 41 KB

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