app.py 43 KB

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