app.py 45 KB

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