feat: implement backend API clients for multi-marketplace integration and frontend service layer
This commit is contained in:
15
backend/mega_api/__init__.py
Normal file
15
backend/mega_api/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from .client import MegaClient
|
||||
from .services.orders import OrdersService
|
||||
from .services.assortment import AssortmentService
|
||||
|
||||
class MegaMarketAPI:
|
||||
"""
|
||||
Main entry point for MegaMarket SDK.
|
||||
Instantiates all services with a shared client.
|
||||
"""
|
||||
def __init__(self, api_token: str = None):
|
||||
self.client = MegaClient(api_token)
|
||||
|
||||
# Initialize services
|
||||
self.orders = OrdersService(self.client)
|
||||
self.assortment = AssortmentService(self.client)
|
||||
79
backend/mega_api/client.py
Normal file
79
backend/mega_api/client.py
Normal file
@@ -0,0 +1,79 @@
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Dict, Any, Optional
|
||||
from .exceptions import MegaAPIError, MegaAuthError, MegaRateLimitError, MegaBadRequestError, MegaNotFoundError
|
||||
|
||||
class MegaClient:
|
||||
"""Base client for interacting with MegaMarket API."""
|
||||
|
||||
BASE_URL = "https://partner.goodsteam.tech/api/market/v1"
|
||||
|
||||
def __init__(self, api_token: Optional[str] = None):
|
||||
# Fetch from env if not provided
|
||||
self.api_token = api_token or os.getenv('MEGA_API_TOKEN')
|
||||
|
||||
if not self.api_token:
|
||||
raise ValueError("MEGA_API_TOKEN must be provided")
|
||||
|
||||
self.session = requests.Session()
|
||||
# Мегамаркет может требовать токен как Bearer, либо внутри тела JSON в "meta".
|
||||
# Будем использовать Bearer, как наиболее распространенный стандарт для V1.
|
||||
self.session.headers.update({
|
||||
"Authorization": f"Bearer {self.api_token}",
|
||||
"Content-Type": "application/json"
|
||||
})
|
||||
|
||||
def request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, retries: int = 3) -> Dict[str, Any]:
|
||||
"""Perform HTTP request to MegaMarket API with automatic retries."""
|
||||
url = f"{self.BASE_URL}{path}"
|
||||
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
response = self.session.request(method, url, json=data, params=params)
|
||||
|
||||
# Check rate limiting
|
||||
if response.status_code == 429:
|
||||
if attempt < retries - 1:
|
||||
time.sleep(2 ** attempt) # Exponential backoff
|
||||
continue
|
||||
raise MegaRateLimitError("Rate limit exceeded")
|
||||
|
||||
if response.status_code in (401, 403):
|
||||
raise MegaAuthError(f"Authentication failed: {response.text}")
|
||||
|
||||
if response.status_code == 400:
|
||||
raise MegaBadRequestError(f"Bad Request: {response.text}")
|
||||
|
||||
if response.status_code == 404:
|
||||
raise MegaNotFoundError(f"Not Found: {response.text}")
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
if response.content:
|
||||
return response.json()
|
||||
return {}
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if attempt < retries - 1:
|
||||
time.sleep(2 ** attempt)
|
||||
continue
|
||||
raise MegaAPIError(f"Request failed: {str(e)}")
|
||||
|
||||
raise MegaAPIError("Request failed after max retries")
|
||||
|
||||
def post(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
# Мегамаркет во многих методах требует структуру {"meta": {}, "data": {}}
|
||||
# Если data не обернута, обернем ее
|
||||
if data and "data" not in data and "meta" not in data:
|
||||
payload = {
|
||||
"meta": {},
|
||||
"data": data
|
||||
}
|
||||
else:
|
||||
payload = data
|
||||
|
||||
return self.request("POST", path, data=payload)
|
||||
|
||||
def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
return self.request("GET", path, params=params)
|
||||
19
backend/mega_api/exceptions.py
Normal file
19
backend/mega_api/exceptions.py
Normal file
@@ -0,0 +1,19 @@
|
||||
class MegaAPIError(Exception):
|
||||
"""Base exception for all MegaMarket API errors."""
|
||||
pass
|
||||
|
||||
class MegaAuthError(MegaAPIError):
|
||||
"""Raised when authentication fails (HTTP 401 or 403)."""
|
||||
pass
|
||||
|
||||
class MegaRateLimitError(MegaAPIError):
|
||||
"""Raised when API rate limits are exceeded (HTTP 429)."""
|
||||
pass
|
||||
|
||||
class MegaBadRequestError(MegaAPIError):
|
||||
"""Raised when API returns HTTP 400 (Bad Request)."""
|
||||
pass
|
||||
|
||||
class MegaNotFoundError(MegaAPIError):
|
||||
"""Raised when API returns HTTP 404 (Not Found)."""
|
||||
pass
|
||||
32
backend/mega_api/services/assortment.py
Normal file
32
backend/mega_api/services/assortment.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from typing import Dict, Any, List
|
||||
from ..client import MegaClient
|
||||
|
||||
class AssortmentService:
|
||||
"""Service to handle MegaMarket Assortment/Prices/Stocks."""
|
||||
|
||||
def __init__(self, client: MegaClient):
|
||||
self.client = client
|
||||
|
||||
def update_stocks(self, stocks: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Обновить остатки.
|
||||
Endpoint: /stockService/stock/update
|
||||
"""
|
||||
payload = {
|
||||
"data": {
|
||||
"stocks": stocks
|
||||
}
|
||||
}
|
||||
return self.client.post("/stockService/stock/update", data=payload)
|
||||
|
||||
def update_prices(self, prices: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Обновить цены.
|
||||
Endpoint: /priceService/price/update
|
||||
"""
|
||||
payload = {
|
||||
"data": {
|
||||
"prices": prices
|
||||
}
|
||||
}
|
||||
return self.client.post("/priceService/price/update", data=payload)
|
||||
55
backend/mega_api/services/orders.py
Normal file
55
backend/mega_api/services/orders.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from typing import Dict, Any, List
|
||||
from ..client import MegaClient
|
||||
|
||||
class OrdersService:
|
||||
"""Service to handle MegaMarket Orders (FBS)."""
|
||||
|
||||
def __init__(self, client: MegaClient):
|
||||
self.client = client
|
||||
|
||||
def get_new_orders(self, limit: int = 100) -> Dict[str, Any]:
|
||||
"""
|
||||
Мегамаркет обычно отправляет заказы webhook-ами, но также имеет методы пулинга или запроса списков.
|
||||
Endpoint: /orderService/order/search (условно)
|
||||
"""
|
||||
payload = {
|
||||
"data": {
|
||||
"statuses": ["NEW"],
|
||||
"limit": limit
|
||||
}
|
||||
}
|
||||
return self.client.post("/orderService/order/search", data=payload)
|
||||
|
||||
def confirm_order(self, order_id: str, items: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Подтвердить заказ (отправить информацию о том, что он принят в работу).
|
||||
Endpoint: /orderService/order/confirm
|
||||
"""
|
||||
payload = {
|
||||
"data": {
|
||||
"shipments": [
|
||||
{
|
||||
"shipmentId": order_id,
|
||||
"items": items
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
return self.client.post("/orderService/order/confirm", data=payload)
|
||||
|
||||
def reject_order(self, order_id: str, reason: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Отменить заказ.
|
||||
Endpoint: /orderService/order/reject
|
||||
"""
|
||||
payload = {
|
||||
"data": {
|
||||
"shipments": [
|
||||
{
|
||||
"shipmentId": order_id,
|
||||
"reason": {"type": reason}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
return self.client.post("/orderService/order/reject", data=payload)
|
||||
Reference in New Issue
Block a user