app.py 45 KB

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