diff --git a/src/Core/const.py b/src/Core/const.py index b180a70a..9de097ab 100644 --- a/src/Core/const.py +++ b/src/Core/const.py @@ -6,11 +6,11 @@ if not SERVER_URL: SERVER_URL = config("SERVER_URL") -PRODUCTION = os.environ.get("PRODUCTION") -if PRODUCTION is not None and PRODUCTION.lower() == "true": - PRODUCTION = True +EMULATE_DB = os.environ.get("EMULATE_DB") +if EMULATE_DB is not None and EMULATE_DB.lower() == "true": + EMULATE_DB = True else: - PRODUCTION = False + EMULATE_DB = False safety_control_ear_protection_description = """ Designed to ensure that the workers in a particular area are wearing ear protection to safeguard their hearing. diff --git a/src/Core/management/commands/startprocess.py b/src/Core/management/commands/startprocess.py index 8ec06583..2416554c 100644 --- a/src/Core/management/commands/startprocess.py +++ b/src/Core/management/commands/startprocess.py @@ -3,9 +3,11 @@ from django.core.management.base import BaseCommand +from src.Core.const import SERVER_URL from src.Core.exceptions import SenderError, InvalidResponseError from src.Inventory.models import Items +from src.CameraAlgorithms.models.camera import ZoneCameras from src.CameraAlgorithms.models import Camera, CameraAlgorithm from src.CameraAlgorithms.services.cameraalgorithm import ( camera_rtsp_link, @@ -30,23 +32,52 @@ def start_process(self) -> None: algorithm_obj: CameraAlgorithm = camera_algorithm.algorithm rtsp_link: str = camera_rtsp_link(camera_obj.id) + request: Dict[str, Any] = { + "camera_url": rtsp_link, + "algorithm": algorithm_obj.name, + "server_url": SERVER_URL, + "extra": extra_params, + } + + if camera_algorithm.algorithm.name == "machine_control": + all_zones = camera_algorithm.zones + cords = [] + for zone_id in all_zones: + zone_camera = ZoneCameras.objects.get(id=zone_id["id"], camera=camera_obj) + coords = zone_camera.coords + coords[0]["zoneId"] = zone_camera.id + coords[0]["zoneName"] = "zone " + str(zone_camera.name) + + new_object = {"coords": coords} + + cords.append(new_object) + + extra_params.append({"coords": coords}) + if camera_algorithm.algorithm.name == "min_max_control": algorithm_items = Items.objects.filter(camera=camera_obj) + areas = [] + stelag = [] for item in algorithm_items: - extra_params.append( - { - "itemId": item.id, - "coords": item.coords, - "itemName": item.name, - } + areas.append( + {"itemId": item.id, "itemName": item.name, "coords": item.coords} ) - request: Dict[str, Any] = { - "camera_url": rtsp_link, - "algorithm": algorithm_obj.name, - "extra": extra_params, - } + all_zones = camera_algorithm.zones + + for zone_id in all_zones: + zone_camera = ZoneCameras.objects.get(id=zone_id["id"], camera=camera_obj) + + stelag.append( + {"zoneId": zone_camera.id, "zoneName": zone_camera.name, "coords": zone_camera.coords} + ) + + new_data = { + "areas": areas, + "zones": stelag + } + extra_params.append(new_data) try: result = send_run_request(request) @@ -58,6 +89,5 @@ def start_process(self) -> None: ) else: new_process_id = result["pid"] - camera_algorithm.process_id = new_process_id camera_algorithm.save() diff --git a/src/Reports/serializers.py b/src/Reports/serializers.py index 89bb8e21..b04749c4 100644 --- a/src/Reports/serializers.py +++ b/src/Reports/serializers.py @@ -38,3 +38,21 @@ class OperationReportSerializer(serializers.ModelSerializer): class Meta: model = SkanyReport fields = ["id", "operationID", "camera_ip", "startTime", "endTime"] + + +class ReportByIDSerializer(serializers.ModelSerializer): + algorithm = AlgorithmSerializer() + camera = serializers.StringRelatedField() + + class Meta: + model = Report + fields = [ + "id", + "start_tracking", + "stop_tracking", + "violation_found", + "extra", + "status", + "algorithm", + "camera", + ] diff --git a/src/Reports/service.py b/src/Reports/service.py index d4754e97..c08a2a95 100644 --- a/src/Reports/service.py +++ b/src/Reports/service.py @@ -41,7 +41,7 @@ def create_skanyreport( report_data: List[Dict], violation_found: bool, start_tracking: str, - end_tracking: str + end_tracking: str, ) -> None: start_dt = datetime.strptime(start_tracking, "%Y-%m-%d %H:%M:%S.%f") start_utc = start_dt.replace(tzinfo=timezone.utc) @@ -53,12 +53,13 @@ def create_skanyreport( end_gmt = end_utc.astimezone(timezone(timedelta(hours=0))) eTime = int(end_gmt.timestamp()) - skany_indeks = report_data[0].get("skany_index") zlecenie = report_data[0].get("zlecenie") execution_date = report_data[0].get("execution_date") - logger.warning(f"Creating Skany Report start_tracking -> {start_tracking} - {sTime}, end_tracking -> {end_tracking} - {eTime}") + logger.warning( + f"Creating Skany Report start_tracking -> {start_tracking} - {sTime}, end_tracking -> {end_tracking} - {eTime}" + ) SkanyReport.objects.create( report=report, @@ -68,4 +69,4 @@ def create_skanyreport( violation_found=violation_found, start_time=sTime, end_time=eTime, - ) \ No newline at end of file + ) diff --git a/src/Reports/urls.py b/src/Reports/urls.py index 966b738d..0b6b03d7 100644 --- a/src/Reports/urls.py +++ b/src/Reports/urls.py @@ -6,6 +6,7 @@ ActionViewSet, SearchReportListView, GetOperationVideoInfo, + GetReportByID, ) @@ -15,6 +16,7 @@ urlpatterns = [ path("report-with-photos/", ActionsWithPhotos.as_view()), + path("by-id//", GetReportByID.as_view(), name="get-report-by-id"), path( "search//////", ReportListView.as_view(), diff --git a/src/Reports/views.py b/src/Reports/views.py index b41ca179..9fd68524 100644 --- a/src/Reports/views.py +++ b/src/Reports/views.py @@ -5,7 +5,7 @@ from django.db.models import Q -from rest_framework.generics import GenericAPIView, ListAPIView +from rest_framework.generics import GenericAPIView, ListAPIView, RetrieveAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.exceptions import MethodNotAllowed from rest_framework import status, viewsets @@ -13,20 +13,23 @@ from rest_framework.response import Response from src.CompanyLicense.decorators import validate_license -from src.Core.const import PRODUCTION, SERVER_URL +from src.Core.const import EMULATE_DB, SERVER_URL from src.Core.paginators import NoPagination from src.ImageReport.models import Image from src.CameraAlgorithms.models import Camera from src.CameraAlgorithms.models import Algorithm from src.Reports.models import Report, SkanyReport -from src.Reports.serializers import ReportSerializers, OperationReportSerializer +from src.Reports.serializers import ( + ReportSerializers, + OperationReportSerializer, + ReportByIDSerializer, +) from src.Inventory.service import process_item_status from src.Reports.service import edit_extra, create_skanyreport logger = logging.getLogger(__name__) - class ActionViewSet(viewsets.ModelViewSet): queryset = Report.objects.all().order_by("-id") serializer_class = ReportSerializers @@ -56,7 +59,7 @@ def post(self, request): algorithm = Algorithm.objects.get(name=algorithm_name) camera = Camera.objects.get(id=camera_ip) - + start_tracking = data.get("start_tracking") stop_tracking = data.get("stop_tracking") @@ -68,16 +71,23 @@ def post(self, request): extra = process_item_status(data.get("extra")) elif algorithm_name == "operation_control": - if not PRODUCTION: - if 'extra' in data: - for data in data['extra']: - if 'place' in data: - logger.warning(f"Operation control extra data is {data}") - requests.post(f"{SERVER_URL}:9876/skany/create/", json=data['extra'][0]) + if EMULATE_DB: + if "extra" in data: + for data in data["extra"]: + if "place" in data: + logger.warning( + f"Operation control extra data is {data}" + ) + requests.post( + f"{SERVER_URL}:9876/skany/create/", + json=data["extra"][0], + ) break else: logger.warning(f"Operation control extra data is {data}") - requests.post(f"{SERVER_URL}:9876/operation-control/", json=data) + requests.post( + f"{SERVER_URL}:9876/operation-control/", json=data + ) extra = edit_extra(data.get("extra"), camera) else: extra = data.get("extra") @@ -97,11 +107,7 @@ def post(self, request): if algorithm_name == "operation_control": create_skanyreport( - action, - extra, - not violation_found, - start_tracking, - stop_tracking + action, extra, not violation_found, start_tracking, stop_tracking ) if photos: @@ -148,7 +154,9 @@ def get(self, request, algorithm_name, camera_ip, date, start_time, end_time): if camera_ip: queryset = queryset.filter(camera__id=camera_ip) if algorithm_name: - queryset = queryset.exclude(algorithm__name='min_max_control').filter(algorithm__name=algorithm_name) + queryset = queryset.exclude(algorithm__name="min_max_control").filter( + algorithm__name=algorithm_name + ) queryset = queryset.order_by("algorithm__name", "camera__id", "id") @@ -185,7 +193,7 @@ def get_queryset(self): algorithm_filters |= Q(algorithm__name=algorithm_name) queryset = queryset.filter(algorithm_filters) - queryset = queryset.exclude(algorithm__name='min_max_control') + queryset = queryset.exclude(algorithm__name="min_max_control") queryset = queryset.order_by("-id") @@ -204,3 +212,8 @@ class GetOperationVideoInfo(ListAPIView): def get_queryset(self): return SkanyReport.objects.exclude(start_time__isnull=True) + + +class GetReportByID(RetrieveAPIView): + queryset = Report.objects.all() + serializer_class = ReportByIDSerializer diff --git a/src/newOrderView/services/__init__.py b/src/newOrderView/services/__init__.py new file mode 100644 index 00000000..6ccc451e --- /dev/null +++ b/src/newOrderView/services/__init__.py @@ -0,0 +1,2 @@ +from .operations import OperationServices +from .order import OrderServises \ No newline at end of file diff --git a/src/newOrderView/services/operations.py b/src/newOrderView/services/operations.py new file mode 100644 index 00000000..b653a6a2 --- /dev/null +++ b/src/newOrderView/services/operations.py @@ -0,0 +1,206 @@ +from typing import Iterable, List, Any, Tuple, Dict +from datetime import datetime, timedelta +import logging +import pytz + +import pyodbc + +from django.db.models import Q +from django.contrib.postgres.fields import JSONField +from django.db.models.query import QuerySet + +from src.CameraAlgorithms.models.camera import ZoneCameras +from src.MsSqlConnector.connector import connector as connector_service +from src.Reports.models import Report + +from ..utils import add_ms, convert_to_gmt0, convert_to_unix + +logger = logging.getLogger(__name__) + + +class OperationServices: + @staticmethod + def get_operations(from_date: str, to_date: str) -> List[Dict[str, Any]]: + connection: pyodbc.Connection = connector_service.get_database_connection() + + stanowiska_query: str = """ + SELECT + indeks AS id, + raport AS orderId + FROM Stanowiska + """ + + stanowiska_data: List[Tuple[Any]] = connector_service.executer( + connection=connection, query=stanowiska_query + ) + + result_list: List[Dict[str, Any]] = [] + + for row in stanowiska_data: + operation_id: int = row[0] + operation_name: str = row[1] + + operations_query: str = """ + SELECT + sk.indeks AS id, + sk.data AS startTime, + LEAD(sk.data) OVER (ORDER BY sk.data) AS endTime, + z.zlecenie AS orderId + FROM Skany sk + JOIN Skany_vs_Zlecenia sz ON sk.indeks = sz.indeksskanu + JOIN zlecenia z ON sz.indekszlecenia = z.indeks + WHERE sk.stanowisko = ? + """ + + params: List[Any] = [operation_id] + + if from_date and to_date: + operations_query += " AND sk.data >= ? AND sk.data <= ?" + + from_date_dt: datetime = datetime.strptime(from_date, "%Y-%m-%d") + from_date_dt: datetime = from_date_dt + timedelta(microseconds=1) + + to_date_dt: datetime = datetime.strptime(to_date, "%Y-%m-%d") + to_date_dt: datetime = to_date_dt + timedelta(days=1) - timedelta(microseconds=1) + + params.extend([from_date_dt, to_date_dt]) + + operations_query += " ORDER BY sk.data" + + operations_data: List[Tuple[Any]] = connector_service.executer( + connection=connection, query=operations_query, params=params + ) + + operations_list: List[Dict[str, Any]] = [] + + if not operations_data: + continue + + for i in range(len(operations_data)): + operation_row: Tuple[Any] = operations_data[i] + + id: int = operation_row[0] + orderId: str = operation_row[3].strip() + startTime: str = str(operation_row[1]) + endTime: str = ( + str(operation_row[2]) if i < len(operations_data) - 1 else None + ) + + operation: Dict[str, Any] = { + "id": id, + "orId": orderId, + "sTime": startTime, + "eTime": endTime, + } + + startTime_dt: datetime = add_ms(startTime) + startTime_dt: datetime = convert_to_gmt0(startTime_dt) + startTime_unix: int = convert_to_unix(startTime_dt) + + operation["sTime"] = startTime_unix + + if endTime is not None: + endTime_dt: datetime = add_ms(endTime) + endTime_dt = endTime_dt.astimezone(pytz.utc) + + if endTime_dt.date() > startTime_dt.date(): + endTime_dt = startTime_dt + timedelta(hours=1) + else: + endTime_dt = endTime_dt or startTime_dt + timedelta(hours=1) + + endTime_dt: datetime = convert_to_gmt0(endTime_dt) + endTime_unix: int = convert_to_unix(endTime_dt) + + operation["eTime"] = endTime_unix + else: + endTime_dt = startTime_dt + timedelta(hours=1) + + endTime_dt: datetime = convert_to_gmt0(endTime_dt) + endTime_unix: int = convert_to_unix(endTime_dt) + + operation["eTime"] = endTime_unix + + operations_list.append(operation) + + # Machine Control + + zone_cameras_ids: Iterable[int] = ZoneCameras.objects.filter(index_workplace=operation_id).values_list('id', flat=True) + zone_cameras_ids: List[int] = [JSONField().to_python(id) for id in zone_cameras_ids] + + reports_with_matching_zona_id: Iterable[QuerySet] = Report.objects.filter( + Q(algorithm=3) & Q(extra__has_key="zoneId") & Q(extra__zoneId__in=zone_cameras_ids) + ) + + machine_reports: List[Dict[str, Any]] = [] + + logger.warning(f"reports_with_matching_zona_id - {reports_with_matching_zona_id}") + + for report in reports_with_matching_zona_id: + zone_data: Dict[int, str] = report.extra + zone_id: int = zone_data["zoneId"] + zone_name: str = zone_data["zoneName"] + + machine_control_report_id: int = report.id + start_tracking: str = report.start_tracking + stop_tracking: str = report.stop_tracking + + sTime: int = int( + datetime.strptime( + start_tracking, "%Y-%m-%d %H:%M:%S.%f" + ).timestamp() + ) + eTime: int = int( + datetime.strptime(stop_tracking, "%Y-%m-%d %H:%M:%S.%f").timestamp() + ) + + report_data: Dict[str, Any] = { + "zoneId": machine_control_report_id, + "orId": zone_name, + "sTime": sTime * 1000, + "eTime": eTime * 1000, + } + + machine_reports.append(report_data) + + machine_result = { + "oprTypeID": zone_id, + "oprName": zone_name, + "oprs": machine_reports + } + + result_list.append(machine_result) + + operation_result = { + "oprTypeID": operation_id, + "oprName": operation_name, + "oprs": operations_list, + } + + result_list.append(operation_result) + return result_list + + @staticmethod + def get_whnet_operation() -> List[Dict[str, Any]]: + connection: pyodbc.Connection = connector_service.get_database_connection() + + query: str = """ + SELECT + indeks AS id, + raport AS operationName + FROM Stanowiska + """ + + data: List[Tuple[Any]] = connector_service.executer( + connection=connection, query=query + ) + result_list: List[Dict[str, Any]] = [] + + for order_row in data: + order: Dict[str, Any] = { + "id": int(order_row[0]), + "operationName": str(order_row[1]).strip(), + } + + result_list.append(order) + + return result_list diff --git a/src/newOrderView/services/order.py b/src/newOrderView/services/order.py new file mode 100644 index 00000000..d9eada5c --- /dev/null +++ b/src/newOrderView/services/order.py @@ -0,0 +1,163 @@ +from typing import List, Any, Tuple, Dict, Optional +from datetime import datetime, timedelta +import logging + +import pyodbc + +from src.MsSqlConnector.connector import connector as connector_service +from src.OrderView.models import IndexOperations +from src.OrderView.utils import get_skany_video_info +from src.CameraAlgorithms.models import Camera +from src.Reports.models import SkanyReport + +logger = logging.getLogger(__name__) + + +class OrderServises: + @staticmethod + def get_order(from_date: str, to_date: str) -> List[Dict[str, Any]]: + connection: pyodbc.Connection = connector_service.get_database_connection() + + order_query: str = """ + SELECT + DISTINCT z.zlecenie AS orderId + FROM Skany sk + JOIN Skany_vs_Zlecenia sz ON sk.indeks = sz.indeksskanu + JOIN zlecenia z ON sz.indekszlecenia = z.indeks + WHERE sk.data >= ? AND sk.data <= ? + """ + + if from_date and to_date: + from_date_dt = datetime.strptime(from_date, "%Y-%m-%d") + from_date_dt = from_date_dt + timedelta(microseconds=1) + + to_date_dt = datetime.strptime(to_date, "%Y-%m-%d") + to_date_dt = to_date_dt + timedelta(days=1) - timedelta(microseconds=1) + + params: List[Any] = [from_date_dt, to_date_dt] + + order_data: List[Tuple[Any]] = connector_service.executer( + connection=connection, query=order_query, params=params + ) + + result_list: List[Dict[str, Any]] = [] + + for order_row in order_data: + order: Dict[str, Any] = { + "orId": order_row[0].strip(), + } + + result_list.append(order) + + return result_list + + @staticmethod + def get_order_by_details(operation_id: int) -> Dict[str, Any]: + connection: pyodbc.Connection = connector_service.get_database_connection() + + order_query = """ + WITH Operation AS ( + SELECT + sk.data AS operationTime + FROM Skany sk + JOIN Stanowiska st ON sk.stanowisko = st.indeks + WHERE sk.indeks = ? + ) + SELECT + z.indeks AS id, + z.zlecenie AS orderId, + st.raport AS operationName, + u.imie AS firstName, + u.nazwisko AS lastName, + CONVERT(VARCHAR(23), op.operationTime, 121) AS startTime, + CASE + WHEN DATEPART(year, sk_next.data) > DATEPART(year, op.operationTime) + OR DATEPART(month, sk_next.data) > DATEPART(month, op.operationTime) + OR DATEPART(day, sk_next.data) > DATEPART(day, op.operationTime) + THEN DATEADD(hour, 1, op.operationTime) + ELSE CONVERT(VARCHAR(23), sk_next.data, 121) + END AS endTime, + st.indeks AS workplaceID, + sk.indeks AS operationID, + z.typ AS type + FROM Zlecenia z + JOIN Skany_vs_Zlecenia sz ON z.indeks = sz.indekszlecenia + JOIN Skany sk ON sz.indeksskanu = sk.indeks + JOIN Stanowiska st ON sk.stanowisko = st.indeks + JOIN Uzytkownicy u ON sk.uzytkownik = u.indeks + JOIN Operation op ON op.operationTime = sk.data + LEFT JOIN Skany sk_next ON sk_next.data > op.operationTime + AND sk_next.stanowisko = st.indeks + WHERE sk.indeks = ? + """ + + params: List[Any] = [operation_id, operation_id] + + order_data: List[Tuple[Any]] = connector_service.executer( + connection=connection, query=order_query, params=params + ) + + if order_data: + id: int = order_data[0][8] + orderId: str = order_data[0][1].strip() + operationName: str = order_data[0][2] + firstName: str = order_data[0][3] + lastName: str = order_data[0][4] + startTime: datetime = datetime.strptime( + str(order_data[0][5]), "%Y-%m-%d %H:%M:%S.%f" + ) + endTime_str = str(order_data[0][6]) if order_data[0][6] else None + + if endTime_str: + if "." not in endTime_str: + endTime_str += ".000" + endTime = datetime.strptime(endTime_str, "%Y-%m-%d %H:%M:%S.%f") + else: + endTime = startTime + timedelta(hours=1) + + workplaceID: int = order_data[0][7] + elementType = order_data[0][9] + video_data: Optional[Dict[str, Any]] = None + + if startTime is not None: + camera_obj: Optional[Camera] = None + operation_status: Optional[bool] = None + video_data: Dict[str, bool] = {} + + skany_report: Optional[SkanyReport] = SkanyReport.objects.filter( + skany_index=id + ).first() + camera_obj: Optional[Camera] = IndexOperations.objects.filter( + type_operation=workplaceID + ).first() + + if skany_report: + operation_status: Optional[bool] = skany_report.violation_found + video_time: Optional[bool] = skany_report.start_time + logger.warning(f"Skany report was founded. Data -> {operation_status}, {video_data}",) + if camera_obj and video_time: + logger.warning(video_time*1000) + video_data: Dict[str, Any] = get_skany_video_info( + time=(video_time * 1000), camera_ip=camera_obj.camera.id + ) + + startTime_unix: int = int(startTime.timestamp()) * 1000 + endTime_unix: int = int(endTime.timestamp()) * 1000 + logger.warning(f"GET START TIME {startTime}") + logger.warning(f"MAKE UNIX {startTime_unix}") + result: Dict[str, Any] = { + "id": id, + "orId": orderId, + "oprName": operationName, + "elType": elementType, + "sTime": startTime_unix, + "eTime": endTime_unix, + "frsName": firstName, + "lstName": lastName, + "status": operation_status, + "video": video_data, + } + + return result + else: + return {} diff --git a/src/newOrderView/services/order_services.py b/src/newOrderView/services/order_services.py deleted file mode 100644 index a1ac5623..00000000 --- a/src/newOrderView/services/order_services.py +++ /dev/null @@ -1,348 +0,0 @@ -from typing import Iterable, List, Any, Tuple, Dict, Optional -from datetime import datetime, timedelta -import logging -import pytz - -import pyodbc - -from django.db.models import Q -from django.contrib.postgres.fields import JSONField -from django.db.models.query import QuerySet - -from src.CameraAlgorithms.models.camera import ZoneCameras -from src.MsSqlConnector.connector import connector as connector_service -from src.OrderView.models import IndexOperations -from src.OrderView.utils import get_skany_video_info -from src.CameraAlgorithms.models import Camera -from src.Reports.models import Report, SkanyReport - -from ..utils import add_ms, convert_to_gmt0, convert_to_unix - -logger = logging.getLogger(__name__) - - -class OrderServices: - @staticmethod - def get_operations(from_date: str, to_date: str) -> List[Dict[str, Any]]: - connection: pyodbc.Connection = connector_service.get_database_connection() - - stanowiska_query: str = """ - SELECT - indeks AS id, - raport AS orderId - FROM Stanowiska - """ - - stanowiska_data: List[Tuple[Any]] = connector_service.executer( - connection=connection, query=stanowiska_query - ) - - result_list: List[Dict[str, Any]] = [] - - for row in stanowiska_data: - operation_id: int = row[0] - operation_name: str = row[1] - - operations_query: str = """ - SELECT - sk.indeks AS id, - sk.data AS startTime, - LEAD(sk.data) OVER (ORDER BY sk.data) AS endTime, - z.zlecenie AS orderId - FROM Skany sk - JOIN Skany_vs_Zlecenia sz ON sk.indeks = sz.indeksskanu - JOIN zlecenia z ON sz.indekszlecenia = z.indeks - WHERE sk.stanowisko = ? - """ - - params: List[Any] = [operation_id] - - if from_date and to_date: - operations_query += " AND sk.data >= ? AND sk.data <= ?" - - from_date_dt = datetime.strptime(from_date, "%Y-%m-%d") - from_date_dt = from_date_dt + timedelta(microseconds=1) - - to_date_dt = datetime.strptime(to_date, "%Y-%m-%d") - to_date_dt = to_date_dt + timedelta(days=1) - timedelta(microseconds=1) - - params.extend([from_date_dt, to_date_dt]) - - operations_query += " ORDER BY sk.data" - - operations_data: List[Tuple[Any]] = connector_service.executer( - connection=connection, query=operations_query, params=params - ) - - operations_list: List[Dict[str, Any]] = [] - - if not operations_data: - continue - - for i in range(len(operations_data)): - operation_row: Tuple[Any] = operations_data[i] - - id: int = operation_row[0] - orderId: str = operation_row[3].strip() - startTime: str = str(operation_row[1]) - endTime: str = ( - str(operation_row[2]) if i < len(operations_data) - 1 else None - ) - - operation: Dict[str, Any] = { - "id": id, - "orId": orderId, - "sTime": startTime, - "eTime": endTime, - } - - startTime_dt: datetime = add_ms(startTime) - startTime_dt: datetime = convert_to_gmt0(startTime_dt) - startTime_unix: int = convert_to_unix(startTime_dt) - - - operation["sTime"] = startTime_unix - - if endTime is not None: - endTime_dt: datetime = add_ms(endTime) - endTime_dt = endTime_dt.astimezone(pytz.utc) - - if endTime_dt.date() > startTime_dt.date(): - endTime_dt = startTime_dt + timedelta(hours=1) - else: - endTime_dt = endTime_dt or startTime_dt + timedelta(hours=1) - - endTime_dt: datetime = convert_to_gmt0(endTime_dt) - endTime_unix: int = convert_to_unix(endTime_dt) - - operation["eTime"] = endTime_unix - else: - endTime_dt = startTime_dt + timedelta(hours=1) - - endTime_dt: datetime = convert_to_gmt0(endTime_dt) - endTime_unix: int = convert_to_unix(endTime_dt) - - operation["eTime"] = endTime_unix - - operations_list.append(operation) - - zone_cameras_ids: Iterable[int] = ZoneCameras.objects.filter(index_workplace=operation_id).values_list('id', flat=True) - zone_cameras_ids: List[int] = [JSONField().to_python(id) for id in zone_cameras_ids] - zone_cameras_names: Dict[int, str] = dict( - ZoneCameras.objects.filter(index_workplace=operation_id).values_list('id', 'name') - ) - - reports_with_matching_zona_id: Iterable[QuerySet] = Report.objects.filter( - Q(algorithm=3) & Q(extra__has_key="zonaID") & Q(extra__zonaID__in=zone_cameras_ids) - ) - - reports: List[Dict[str, Any]] = [] - - logger.warning(f"zone_cameras_names - {zone_cameras_names}, reports_with_matching_zona_id - {reports_with_matching_zona_id}") - - for report in reports_with_matching_zona_id: - zona_data: Dict[int, str] = report.extra - id: int = report.id - orId: str = zone_cameras_names[zona_data["zonaID"]] - start_tracking: str = report.start_tracking - stop_tracking: str = report.stop_tracking - sTime: int = int( - datetime.strptime( - start_tracking, "%Y-%m-%d %H:%M:%S.%f" - ).timestamp() - ) - eTime: int = int( - datetime.strptime(stop_tracking, "%Y-%m-%d %H:%M:%S.%f").timestamp() - ) - report_data: Dict[str, Any] = { - "id": id, - "orId": orId, - "sTime": sTime * 1000, - "eTime": eTime * 1000, - } - - reports.append(report_data) - - result = { - "oprTypeID": operation_id, - "oprName": operation_name, - "oprs": operations_list, - "reports": reports, - } - - result_list.append(result) - return result_list - - @staticmethod - def get_order(from_date: str, to_date: str) -> List[Dict[str, Any]]: - connection: pyodbc.Connection = connector_service.get_database_connection() - - order_query: str = """ - SELECT - DISTINCT z.zlecenie AS orderId - FROM Skany sk - JOIN Skany_vs_Zlecenia sz ON sk.indeks = sz.indeksskanu - JOIN zlecenia z ON sz.indekszlecenia = z.indeks - WHERE sk.data >= ? AND sk.data <= ? - """ - - if from_date and to_date: - from_date_dt = datetime.strptime(from_date, "%Y-%m-%d") - from_date_dt = from_date_dt + timedelta(microseconds=1) - - to_date_dt = datetime.strptime(to_date, "%Y-%m-%d") - to_date_dt = to_date_dt + timedelta(days=1) - timedelta(microseconds=1) - - params: List[Any] = [from_date_dt, to_date_dt] - - order_data: List[Tuple[Any]] = connector_service.executer( - connection=connection, query=order_query, params=params - ) - - result_list: List[Dict[str, Any]] = [] - - for order_row in order_data: - order: Dict[str, Any] = { - "orId": order_row[0].strip(), - } - - result_list.append(order) - - return result_list - - @staticmethod - def get_order_by_details(operation_id: int) -> Dict[str, Any]: - connection: pyodbc.Connection = connector_service.get_database_connection() - - order_query = """ - WITH Operation AS ( - SELECT - sk.data AS operationTime - FROM Skany sk - JOIN Stanowiska st ON sk.stanowisko = st.indeks - WHERE sk.indeks = ? - ) - SELECT - z.indeks AS id, - z.zlecenie AS orderId, - st.raport AS operationName, - u.imie AS firstName, - u.nazwisko AS lastName, - CONVERT(VARCHAR(23), op.operationTime, 121) AS startTime, - CASE - WHEN DATEPART(year, sk_next.data) > DATEPART(year, op.operationTime) - OR DATEPART(month, sk_next.data) > DATEPART(month, op.operationTime) - OR DATEPART(day, sk_next.data) > DATEPART(day, op.operationTime) - THEN DATEADD(hour, 1, op.operationTime) - ELSE CONVERT(VARCHAR(23), sk_next.data, 121) - END AS endTime, - st.indeks AS workplaceID, - sk.indeks AS operationID, - z.typ AS type - FROM Zlecenia z - JOIN Skany_vs_Zlecenia sz ON z.indeks = sz.indekszlecenia - JOIN Skany sk ON sz.indeksskanu = sk.indeks - JOIN Stanowiska st ON sk.stanowisko = st.indeks - JOIN Uzytkownicy u ON sk.uzytkownik = u.indeks - JOIN Operation op ON op.operationTime = sk.data - LEFT JOIN Skany sk_next ON sk_next.data > op.operationTime - AND sk_next.stanowisko = st.indeks - WHERE sk.indeks = ? - """ - - params: List[Any] = [operation_id, operation_id] - - order_data: List[Tuple[Any]] = connector_service.executer( - connection=connection, query=order_query, params=params - ) - - if order_data: - id: int = order_data[0][8] - orderId: str = order_data[0][1].strip() - operationName: str = order_data[0][2] - firstName: str = order_data[0][3] - lastName: str = order_data[0][4] - startTime: datetime = datetime.strptime( - str(order_data[0][5]), "%Y-%m-%d %H:%M:%S.%f" - ) - endTime_str = str(order_data[0][6]) if order_data[0][6] else None - - if endTime_str: - if "." not in endTime_str: - endTime_str += ".000" - endTime = datetime.strptime(endTime_str, "%Y-%m-%d %H:%M:%S.%f") - else: - endTime = startTime + timedelta(hours=1) - - workplaceID: int = order_data[0][7] - elementType = order_data[0][9] - video_data: Optional[Dict[str, Any]] = None - - if startTime is not None: - camera_obj: Optional[Camera] = None - operation_status: Optional[bool] = None - video_data: Dict[str, bool] = {} - - skany_report: Optional[SkanyReport] = SkanyReport.objects.filter( - skany_index=id - ).first() - camera_obj: Optional[Camera] = IndexOperations.objects.filter( - type_operation=workplaceID - ).first() - - if skany_report: - operation_status: Optional[bool] = skany_report.violation_found - video_time: Optional[bool] = skany_report.start_time - logger.warning(f"Skany report was founded. Data -> {operation_status}, {video_data}",) - if camera_obj and video_time: - logger.warning(video_time*1000) - video_data: Dict[str, Any] = get_skany_video_info( - time=(video_time * 1000), camera_ip=camera_obj.camera.id - ) - - startTime_unix: int = int(startTime.timestamp()) * 1000 - endTime_unix: int = int(endTime.timestamp()) * 1000 - logger.warning(f"GET START TIME {startTime}") - logger.warning(f"MAKE UNIX {startTime_unix}") - result: Dict[str, Any] = { - "id": id, - "orId": orderId, - "oprName": operationName, - "elType": elementType, - "sTime": startTime_unix, - "eTime": endTime_unix, - "frsName": firstName, - "lstName": lastName, - "status": operation_status, - "video": video_data, - } - - return result - else: - return {} - - @staticmethod - def get_whnet_operation() -> List[Dict[str, Any]]: - connection: pyodbc.Connection = connector_service.get_database_connection() - - query: str = """ - SELECT - indeks AS id, - raport AS operationName - FROM Stanowiska - """ - - data: List[Tuple[Any]] = connector_service.executer( - connection=connection, query=query - ) - result_list: List[Dict[str, Any]] = [] - - for order_row in data: - order: Dict[str, Any] = { - "id": int(order_row[0]), - "operationName": str(order_row[1]).strip(), - } - - result_list.append(order) - - return result_list diff --git a/src/newOrderView/views.py b/src/newOrderView/views.py index cc97f2e7..d22723c9 100644 --- a/src/newOrderView/views.py +++ b/src/newOrderView/views.py @@ -10,7 +10,7 @@ from src.Core.paginators import OrderViewPaginnator, NoPagination from src.MsSqlConnector.connector import connector as connector_service -from .services.order_services import OrderServices +from .services import OperationServices, OrderServises from .utils import generate_hash @@ -24,7 +24,7 @@ def get(self, request): response = cache.get(key) if response is None: - response: List[Dict[str, Any]] = OrderServices.get_operations( + response: List[Dict[str, Any]] = OperationServices.get_operations( from_date, to_date ) cache.set(key, response, timeout=120) @@ -44,7 +44,7 @@ def get(self, request): response = cache.get("get_order_" + key) if response is None: - response: List[Dict[str, str]] = OrderServices.get_order(from_date, to_date) + response: List[Dict[str, str]] = OrderServises.get_order(from_date, to_date) cache.set(key, response, timeout=120) return JsonResponse(response, status=status.HTTP_200_OK, safe=False) @@ -56,7 +56,7 @@ class GetOrderByDetail(generics.GenericAPIView): @connector_service.check_database_connection def get(self, request): operation_id: int = request.GET.get("operation") - response: Dict[str, Any] = OrderServices.get_order_by_details(operation_id) + response: Dict[str, Any] = OrderServises.get_order_by_details(operation_id) return JsonResponse(data=response, status=status.HTTP_200_OK) @@ -66,6 +66,6 @@ class GetWhnetOperation(generics.GenericAPIView): @method_decorator(cache_page(30)) @connector_service.check_database_connection def get(self, request): - response: Dict[str, Any] = OrderServices.get_whnet_operation() + response: Dict[str, Any] = OperationServices.get_whnet_operation() return JsonResponse(data=response, status=status.HTTP_200_OK, safe=False)