app.py 42 KB

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