app.py 44 KB

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