app.py 40 KB

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