app.py 47 KB

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