194 lines
7.9 KiB
Python
194 lines
7.9 KiB
Python
|
|
import requests
|
|||
|
|
from django.http import JsonResponse
|
|||
|
|
from django.views import View
|
|||
|
|
from django.conf import settings
|
|||
|
|
import asyncio
|
|||
|
|
import aiohttp
|
|||
|
|
import json
|
|||
|
|
from django.utils.decorators import method_decorator
|
|||
|
|
from django.views.decorators.csrf import csrf_exempt
|
|||
|
|
|
|||
|
|
|
|||
|
|
# http://192.168.254.2/szkm/api/batch/load/eb7bb39a-fd68-47c7-aec8-0041a4fe5faf/
|
|||
|
|
|
|||
|
|
# Настройки API
|
|||
|
|
API_BASE_URL = "http://192.168.254.2:8280/api"
|
|||
|
|
API_REPORTS_URL = f"{API_BASE_URL}/productlinereport/list"
|
|||
|
|
LOGIN_URL = f"{API_BASE_URL}/login"
|
|||
|
|
BATCH_LIST_URL = f"{API_BASE_URL}/Batch/list"
|
|||
|
|
|
|||
|
|
|
|||
|
|
# Данные для входа
|
|||
|
|
USERNAME = "user"
|
|||
|
|
PASSWORD = "user"
|
|||
|
|
|
|||
|
|
def get_auth_token():
|
|||
|
|
"""Авторизуется и получает Bearer токен"""
|
|||
|
|
response = requests.post(LOGIN_URL, json={"username": USERNAME, "password": PASSWORD})
|
|||
|
|
if response.status_code == 200:
|
|||
|
|
data = response.json()
|
|||
|
|
token = data.get("Value", {}).get("Token") # Исправленный способ получения токена
|
|||
|
|
if token:
|
|||
|
|
return token
|
|||
|
|
return None
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
class BatchListView(View):
|
|||
|
|
"""Получает список партий с фильтрацией по CreatedOn"""
|
|||
|
|
def get(self, request):
|
|||
|
|
token = get_auth_token()
|
|||
|
|
if not token:
|
|||
|
|
return JsonResponse({"error": "Не удалось получить токен"}, status=401)
|
|||
|
|
|
|||
|
|
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|||
|
|
payload = {
|
|||
|
|
"Filter": {
|
|||
|
|
"Filters": [
|
|||
|
|
{"Value": "2024-01-1 00:00:00", "Operator": "gte", "Field": "CreatedOn"},
|
|||
|
|
{"Value": "2025.11.22", "Operator": "lte", "Field": "CreatedOn"}
|
|||
|
|
],
|
|||
|
|
"Logic": "and"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
response = requests.post(BATCH_LIST_URL, json=payload, headers=headers)
|
|||
|
|
if response.status_code == 200:
|
|||
|
|
return JsonResponse(response.json(), safe=False)
|
|||
|
|
return JsonResponse({"error": "Ошибка при запросе данных"}, status=response.status_code)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class BatchListGTIN(View):
|
|||
|
|
"""Получает список партий с фильтрацией по CreatedOn"""
|
|||
|
|
def get(self, request):
|
|||
|
|
token = get_auth_token()
|
|||
|
|
if not token:
|
|||
|
|
return JsonResponse({"error": "Не удалось получить токен"}, status=401)
|
|||
|
|
|
|||
|
|
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|||
|
|
payload = {
|
|||
|
|
"Filter": {
|
|||
|
|
"Filters": [
|
|||
|
|
{
|
|||
|
|
"Filters": [
|
|||
|
|
{
|
|||
|
|
"Value": "04607017161371",
|
|||
|
|
"Operator": "eq",
|
|||
|
|
"Field": "ProductType.GTIN"
|
|||
|
|
},
|
|||
|
|
{
|
|||
|
|
"Value": "04607017161371",
|
|||
|
|
"Operator": "linq",
|
|||
|
|
"Field": "CodesForProductLines.Any( a=> a.ProductType.GTIN=='{0}' )"
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
"Logic": "or"
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
"Logic": "and"
|
|||
|
|
},
|
|||
|
|
"Includes": [
|
|||
|
|
"ProductType",
|
|||
|
|
"CodesForProductLines.ProductType"
|
|||
|
|
]
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
response = requests.post(BATCH_LIST_URL, json=payload, headers=headers)
|
|||
|
|
if response.status_code == 200:
|
|||
|
|
return JsonResponse(response.json(), safe=False)
|
|||
|
|
return JsonResponse({"error": "Ошибка при запросе данных"}, status=response.status_code)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@method_decorator(csrf_exempt, name='dispatch')
|
|||
|
|
class BatchListReport(View):
|
|||
|
|
"""Получает список партий с фильтрацией по CreatedOn и BatchId из тела запроса"""
|
|||
|
|
|
|||
|
|
def post(self, request):
|
|||
|
|
token = get_auth_token()
|
|||
|
|
if not token:
|
|||
|
|
return JsonResponse({"error": "Не удалось получить токен"}, status=401)
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
body = json.loads(request.body)
|
|||
|
|
batch_id = body.get("id")
|
|||
|
|
except json.JSONDecodeError:
|
|||
|
|
return JsonResponse({"error": "Неверный формат JSON"}, status=400)
|
|||
|
|
|
|||
|
|
if not batch_id:
|
|||
|
|
return JsonResponse({"error": "Отсутствует параметр 'id'"}, status=400)
|
|||
|
|
|
|||
|
|
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|||
|
|
payload = {"skip":0,"take":10,"includes":["ProductLineBatch","ProductLineBatch.ProductType","ProductLine"],"sort":[{"field":"CreatedOn","dir":"desc"}],"filter":{"filters":[{"operator":"eq","field":"ProductLineBatchId","value":batch_id}],"logic":"and"}}
|
|||
|
|
|
|||
|
|
response = requests.post(API_REPORTS_URL, json=payload, headers=headers)
|
|||
|
|
if response.status_code == 200:
|
|||
|
|
return JsonResponse(response.json(), safe=False)
|
|||
|
|
return JsonResponse({"error": "Ошибка при запросе данных"}, status=response.status_code)
|
|||
|
|
class BatchReportView(View):
|
|||
|
|
"""Получает список партий и прикрепляет к ним отчёты асинхронно."""
|
|||
|
|
|
|||
|
|
async def fetch_reports(self, session, headers, batch_id):
|
|||
|
|
"""Асинхронно получает список отчётов для заданной партии."""
|
|||
|
|
if not batch_id:
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
report_payload = {
|
|||
|
|
"Skip": 0,
|
|||
|
|
"Take": 100000,
|
|||
|
|
"Filter": {
|
|||
|
|
"Field": "BatchId",
|
|||
|
|
"Operator": "eq",
|
|||
|
|
"Value": batch_id
|
|||
|
|
},
|
|||
|
|
"TotalCount": 0,
|
|||
|
|
"Sort": [{"Field": "CreatedOn", "Dir": "desc"}]
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async with session.post(API_REPORTS_URL, json=report_payload, headers=headers) as response:
|
|||
|
|
if response.status == 200:
|
|||
|
|
data = await response.json()
|
|||
|
|
return data.get("Value", {}).get("Items", [])
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
async def fetch_all_reports(self, batches, headers):
|
|||
|
|
"""Запрашивает отчёты для всех партий параллельно."""
|
|||
|
|
async with aiohttp.ClientSession() as session:
|
|||
|
|
tasks = [self.fetch_reports(session, headers, batch.get("ProductTypeId")) for batch in batches]
|
|||
|
|
reports = await asyncio.gather(*tasks)
|
|||
|
|
|
|||
|
|
# Присваиваем отчёты соответствующим партиям
|
|||
|
|
for batch, report in zip(batches, reports):
|
|||
|
|
batch["Reports"] = report
|
|||
|
|
|
|||
|
|
def get(self, request):
|
|||
|
|
"""Основной метод обработки GET-запроса."""
|
|||
|
|
token = get_auth_token()
|
|||
|
|
if not token:
|
|||
|
|
return JsonResponse({"error": "Не удалось получить токен"}, status=401)
|
|||
|
|
|
|||
|
|
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|||
|
|
|
|||
|
|
# Запрос списка партий
|
|||
|
|
batch_payload = {
|
|||
|
|
"Filter": {
|
|||
|
|
"Filters": [
|
|||
|
|
{"Value": "2025-01-1 00:00:00", "Operator": "gte", "Field": "CreatedOn"},
|
|||
|
|
{"Value": "2025.11.22", "Operator": "lte", "Field": "CreatedOn"}
|
|||
|
|
],
|
|||
|
|
"Logic": "and"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
batch_response = requests.post(BATCH_LIST_URL, json=batch_payload, headers=headers)
|
|||
|
|
|
|||
|
|
if batch_response.status_code != 200:
|
|||
|
|
return JsonResponse({"error": "Ошибка при запросе списка партий"}, status=batch_response.status_code)
|
|||
|
|
|
|||
|
|
batch_data = batch_response.json()
|
|||
|
|
batches = batch_data.get("Value", {}).get("Items", [])
|
|||
|
|
print(batches)
|
|||
|
|
# Асинхронно получаем отчёты для всех партий
|
|||
|
|
asyncio.run(self.fetch_all_reports(batches, headers))
|
|||
|
|
print(fetch_all_reports)
|
|||
|
|
return JsonResponse({"Batches": batches}, safe=False)
|
|||
|
|
|