app.py 45 KB

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