backend/scan/viewss1/management_views.py

89 lines
3.0 KiB
Python
Raw Normal View History

# views/management_views.py
from rest_framework.views import APIView
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
from ..api_client import APIClient
from ..constants import API_URLS
logger = logging.getLogger(__name__)
class ManagementDataView(APIView):
"""Получение управленческих данных"""
client = APIClient()
response_handler = APIClient.create_response
MAX_WORKERS = 5
REQUEST_TIMEOUT = 5
def get(self, request):
token = self.client.get_token(API_URLS["LOGIN_ASPU"])
if not token:
return self.response_handler(
"Error",
"Failed to get token",
status_code=500
)
all_data = {}
with ThreadPoolExecutor(max_workers=self.MAX_WORKERS) as executor:
futures = {
executor.submit(
self.client.make_request,
url,
token,
timeout=self.REQUEST_TIMEOUT
): name
for name, url in API_URLS["MANAGEMENT_ENDPOINTS"].items()
}
for future in as_completed(futures):
name = futures[future]
try:
self.process_response(
name,
future.result(),
all_data
)
except Exception as e:
logger.error(f"Error processing {name}: {str(e)}")
return self.response_handler(
"OK" if all_data else "Error",
data=all_data or None,
status_code=200 if all_data else 404
)
def process_response(self, source_name, response, data_store):
"""Обработка полученных данных"""
if not response or not response.get("Value"):
return
value_data = response["Value"]
batch_name = value_data.get("BatchName")
for product in value_data.get("ProductTypes", []):
product_id = product.get("Id")
if not product_id:
continue
if product_id not in data_store:
data_store[product_id] = {
"Name": product.get("Name"),
"ShortName": product.get("ShortName"),
"BatchName": batch_name,
"Stats": [],
"Sources": [],
"Gtin": product.get("Gtin"),
"GroupType": product.get("GroupType", ""),
"Quantity": 0
}
data_store[product_id]["Stats"].extend(product.get("Stats", []))
data_store[product_id]["Sources"].append(source_name)
if product.get("GroupType") == "Pallet":
data_store[product_id]["Quantity"] = sum(
stat["Value"]
for stat in product.get("Stats", [])
if stat["Type"] == "Validated"
)