feat: implement backend API clients for multi-marketplace integration and frontend service layer

This commit is contained in:
2026-05-12 13:16:14 +03:00
parent 6974af486a
commit ee39a3d83b
65 changed files with 2501 additions and 33 deletions

View File

@@ -0,0 +1,15 @@
from .client import MMClient
from .services.orders import OrdersService
from .services.shipments import ShipmentsService
class MagnitMarketAPI:
"""
Main entry point for Magnit Market SDK.
Instantiates all services with a shared client.
"""
def __init__(self, api_key: str = None):
self.client = MMClient(api_key)
# Initialize services
self.orders = OrdersService(self.client)
self.shipments = ShipmentsService(self.client)

67
backend/mm_api/client.py Normal file
View File

@@ -0,0 +1,67 @@
import os
import requests
import time
from typing import Dict, Any, Optional
from .exceptions import MMAPIError, MMAuthError, MMRateLimitError, MMBadRequestError, MMNotFoundError
class MMClient:
"""Base client for interacting with Magnit Market API."""
BASE_URL = "https://b2b-api.magnit.ru"
def __init__(self, api_key: Optional[str] = None):
# Fetch from env if not provided
self.api_key = api_key or os.getenv('MM_API_KEY')
if not self.api_key:
raise ValueError("MM_API_KEY must be provided")
self.session = requests.Session()
self.session.headers.update({
"X-Api-Key": self.api_key,
"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 MM 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 MMRateLimitError("Rate limit exceeded")
if response.status_code in (401, 403):
raise MMAuthError(f"Authentication failed: {response.text}")
if response.status_code == 400:
raise MMBadRequestError(f"Bad Request: {response.text}")
if response.status_code == 404:
raise MMNotFoundError(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 MMAPIError(f"Request failed: {str(e)}")
raise MMAPIError("Request failed after max retries")
def post(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("POST", path, data=data)
def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("GET", path, params=params)

View File

@@ -0,0 +1,19 @@
class MMAPIError(Exception):
"""Base exception for all Magnit Market API errors."""
pass
class MMAuthError(MMAPIError):
"""Raised when authentication fails (HTTP 401 or 403)."""
pass
class MMRateLimitError(MMAPIError):
"""Raised when API rate limits are exceeded (HTTP 429)."""
pass
class MMBadRequestError(MMAPIError):
"""Raised when API returns HTTP 400 (Bad Request)."""
pass
class MMNotFoundError(MMAPIError):
"""Raised when API returns HTTP 404 (Not Found)."""
pass

View File

@@ -0,0 +1,52 @@
from typing import Dict, Any, List
from ..client import MMClient
class OrdersService:
"""Service to handle Magnit Market Orders (FBS)."""
def __init__(self, client: MMClient):
self.client = client
def get_unprocessed_list(self, dir: str = "ASC", page_size: int = 100, page_token: str = None, **filters) -> Dict[str, Any]:
"""
Get list of unprocessed assembly tasks.
Endpoint: /api/seller/v1/orders/list/unprocessed
"""
payload = {
"dir": dir,
"page_size": page_size
}
if page_token:
payload["page_token"] = page_token
# Add any extra filters like created_at, cutoff_time, etc.
payload.update(filters)
return self.client.post("/api/seller/v1/orders/list/unprocessed", data=payload)
def get_list(self, dir: str = "ASC", page_size: int = 100, page_token: str = None, **filters) -> Dict[str, Any]:
"""
Get list of orders by parameters.
Endpoint: /api/seller/v1/orders/list
"""
payload = {
"dir": dir,
"page_size": page_size
}
if page_token:
payload["page_token"] = page_token
payload.update(filters)
return self.client.post("/api/seller/v1/orders/list", data=payload)
def cancel_items(self, order_id: str, items: List[Dict[str, int]]) -> Dict[str, Any]:
"""
Cancel specific items in an order.
Endpoint: /api/seller/v1/orders/cancel-items
"""
payload = {
"order_id": order_id,
"items": items
}
return self.client.post("/api/seller/v1/orders/cancel-items", data=payload)

View File

@@ -0,0 +1,30 @@
from typing import Dict, Any
from ..client import MMClient
class ShipmentsService:
"""Service to handle Magnit Market Shipments."""
def __init__(self, client: MMClient):
self.client = client
def get_list(self, dir: str = "ASC", page_size: int = 100, page_token: str = None, **filters) -> Dict[str, Any]:
"""
Get list of shipments.
Endpoint: /api/seller/v1/shipments/list
"""
payload = {
"dir": dir,
"page_size": page_size
}
if page_token:
payload["page_token"] = page_token
payload.update(filters)
return self.client.post("/api/seller/v1/shipments/list", data=payload)
def confirm(self, shipment_id: str) -> Dict[str, Any]:
"""
Confirm a shipment.
Endpoint: /api/seller/v1/shipments/confirm
"""
return self.client.post("/api/seller/v1/shipments/confirm", data={"shipment_id": shipment_id})