diff --git a/apps/main/admin.py b/apps/main/admin.py index 611c0c7..f24dd87 100644 --- a/apps/main/admin.py +++ b/apps/main/admin.py @@ -1,6 +1,8 @@ from django.contrib import admin -from apps.main.models.dashboard_models import FabricWorkTime, ScalesControl, AccidentStop, Position +from apps.main.api.accident_stops.models import AccidentStop +from apps.main.api.scales_control.models import ScalesControl, Position +from apps.main.api.worktime.models import FabricWorkTime @admin.register(FabricWorkTime) diff --git a/apps/main/api/accident_stops/models.py b/apps/main/api/accident_stops/models.py new file mode 100644 index 0000000..6b336ca --- /dev/null +++ b/apps/main/api/accident_stops/models.py @@ -0,0 +1,16 @@ +from django.db import models +from django.utils.timezone import now + + +class AccidentStop(models.Model): + """ + Модель для хранения времени аварийных остановок + """ + time = models.DateTimeField(default=now) + + class Meta: + verbose_name = 'Аварийная остановка' + verbose_name_plural = 'Аварийные остановки' + + def __str__(self): + return f'Авайрийная остановка: {self.time}' diff --git a/apps/main/api/accident_stops/service.py b/apps/main/api/accident_stops/service.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/main/api/accident_stops/views.py b/apps/main/api/accident_stops/views.py new file mode 100644 index 0000000..e5a7044 --- /dev/null +++ b/apps/main/api/accident_stops/views.py @@ -0,0 +1,23 @@ +from dateutil.relativedelta import relativedelta +from django.http import JsonResponse +from django.utils import timezone + +from apps.main.api.accident_stops.models import AccidentStop +from apps.main.api.common.base_view import base_view, get_qs_by_range + + +@base_view +def get_accident_stops(request): + now_date = timezone.now() + start_month = now_date - relativedelta(hours=730) + start_week = now_date - relativedelta(hours=168) + start_day = now_date - relativedelta(hours=24) + + stops_by_month = get_qs_by_range(AccidentStop, start_month, now_date) + stops_by_week = get_qs_by_range(AccidentStop, start_week, now_date) + stops_by_day = get_qs_by_range(AccidentStop, start_day, now_date) + return JsonResponse({ + 'stops_by_month': stops_by_month.count(), + 'stops_by_week': stops_by_week.count(), + 'stops_by_day': stops_by_day.count() + }) diff --git a/apps/main/views/views_core.py b/apps/main/api/common/base_view.py similarity index 71% rename from apps/main/views/views_core.py rename to apps/main/api/common/base_view.py index 459a434..8bc2bf3 100644 --- a/apps/main/views/views_core.py +++ b/apps/main/api/common/base_view.py @@ -1,7 +1,8 @@ import functools import traceback - +from datetime import datetime from django.conf import settings +from django.db.models import QuerySet from django.http import JsonResponse from sabron.util import logging @@ -10,8 +11,7 @@ from sabron.util import logging def ret(json_object, status=200): return JsonResponse(json_object, status=status, - safe=not isinstance(json_object, list), - ) + safe=not isinstance(json_object, list)) def error_response(exception): @@ -28,5 +28,8 @@ def base_view(fn): return fn(request, *args, **kwargs) except Exception as e: return error_response(e) - return inner + + +def get_qs_by_range(model, start: datetime, end: datetime) -> QuerySet: + return model.objects.only('time').filter(time__range=(start, end)).values() diff --git a/apps/main/api/common/qs_functions.py b/apps/main/api/common/qs_functions.py new file mode 100644 index 0000000..fa1997f --- /dev/null +++ b/apps/main/api/common/qs_functions.py @@ -0,0 +1,7 @@ +from datetime import datetime + +from django.db.models import QuerySet + + +def get_qs_by_range(model, start: datetime, end: datetime) -> QuerySet: + return model.objects.only('time').filter(time__range=(start, end)).values() diff --git a/apps/main/models/dashboard_models.py b/apps/main/api/scales_control/models.py similarity index 51% rename from apps/main/models/dashboard_models.py rename to apps/main/api/scales_control/models.py index cf22ebc..e6a42d5 100644 --- a/apps/main/models/dashboard_models.py +++ b/apps/main/api/scales_control/models.py @@ -1,30 +1,4 @@ from django.db import models -from django.utils.timezone import now - - -class FabricWorkTime(models.Model): - """ - Модель для хранения времени работы фабрики - Поле time хранит время записи - Поле status хранит состояние фабрики - Имеет три статуса: - WO - Работает под нагрузкой - WA - Работает без нагрузки - NW - Не работает - """ - time = models.DateTimeField(default=now) - status = models.CharField( - choices=( - ('WO', 'Работает под нагрузкой'), ('WA', 'Работает без нагрузки'), ('NW', 'Не работает')), - max_length=10 - ) - - class Meta: - verbose_name = 'Время работы фабрики' - verbose_name_plural = 'Отрезки времени работы фабрики' - - def __str__(self): - return f'{self.time}: {self.status}' class ScalesControl(models.Model): @@ -48,20 +22,6 @@ class ScalesControl(models.Model): } -class AccidentStop(models.Model): - """ - Модель для хранения времени аварийных остановок - """ - time = models.DateTimeField(default=now) - - class Meta: - verbose_name = 'Аварийная остановка' - verbose_name_plural = 'Аварийные остановки' - - def __str__(self): - return f'Авайрийная остановка: {self.time}' - - class Position(models.Model): """ Модель для хранения позиций, по которым работают весы diff --git a/apps/main/dashboard.py b/apps/main/api/scales_control/service.py similarity index 72% rename from apps/main/dashboard.py rename to apps/main/api/scales_control/service.py index bab3268..b1c4bb1 100644 --- a/apps/main/dashboard.py +++ b/apps/main/api/scales_control/service.py @@ -1,75 +1,7 @@ -import traceback - import pytz -from datetime import datetime, timedelta - from django.db.models import QuerySet -from django.db.models.functions import TruncMinute -from django.utils import timezone -from dateutil.relativedelta import relativedelta -import decimal - -from apps.main.models.dashboard_models import ScalesControl, FabricWorkTime - - -def get_qs_by_range(model, start: datetime, end: datetime) -> QuerySet: - return model.objects.only('time').filter(time__range=(start, end)).values() - - -def create_worktime_data(): - """ - Создает объекты FabricWorkTime для анализа времени работы фабрики - """ - try: - now_date = timezone.now() - start_day = now_date - relativedelta(hours=24) - - latest_records = ScalesControl.objects.filter( - name='SIEMENSPLC.AZG01.ReportProdDB.Pos4AverSmena', - date__range=(start_day, now_date) - ).annotate( - date_minute=TruncMinute('date') - ).order_by('date_minute', '-date').distinct('date_minute') - - for record in latest_records: - status = 'WO' if record.value > decimal.Decimal(20.0) else 'WA' - FabricWorkTime.objects.get_or_create(time=record.date, status=status) - except Exception as e: - with open('error.txt', 'w') as f: - f.write(e) - - -def calculate_work_time(qs: list): - status_durations = { - 'WO': timedelta(0), - 'WA': timedelta(0), - 'NW': timedelta(0) - } - - if not qs: - return status_durations - - previous_time = qs[0]['time'] - previous_status = qs[0]['status'] - - for work in qs[1:]: - current_time = work['time'] - current_status = work['status'] - - duration = current_time - previous_time - status_durations[previous_status] += duration - - previous_time = current_time - previous_status = current_status - - now_date = timezone.now() - duration = now_date - previous_time - status_durations[previous_status] += duration - - status_durations_hours = {k: round(v.total_seconds() / 3600) for k, v in status_durations.items()} - - return status_durations_hours +from apps.main.api.scales_control.models import ScalesControl def get_scales_value(positions: QuerySet, interval: str) -> dict: diff --git a/apps/main/api/scales_control/views.py b/apps/main/api/scales_control/views.py new file mode 100644 index 0000000..6016665 --- /dev/null +++ b/apps/main/api/scales_control/views.py @@ -0,0 +1,20 @@ +from django.http import JsonResponse + +from apps.main.api.common.base_view import base_view +from apps.main.api.scales_control.models import Position +from apps.main.api.scales_control.service import get_scales_value, get_scales_value_by_shifts + + +@base_view +def get_scales_data(request): + positions = Position.objects.order_by('id') + monthly = get_scales_value(positions, 'Month') + average = get_scales_value_by_shifts(positions, 'Aver') + daily = get_scales_value_by_shifts(positions, 'Smena') + return JsonResponse({'daily': daily, 'average': average, 'monthly': monthly}) + + +@base_view +def get_positions(request): + positions = Position.objects.values_list('title', flat=True).order_by('id') + return JsonResponse(list(positions), safe=False) diff --git a/apps/main/api/workstatus/models.py b/apps/main/api/workstatus/models.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/main/api/workstatus/service.py b/apps/main/api/workstatus/service.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/main/api/workstatus/views.py b/apps/main/api/workstatus/views.py new file mode 100644 index 0000000..f744d42 --- /dev/null +++ b/apps/main/api/workstatus/views.py @@ -0,0 +1,28 @@ +from datetime import timedelta + +from dateutil.relativedelta import relativedelta +from django.http import JsonResponse +from django.utils import timezone + +from apps.main.api.common.base_view import base_view, get_qs_by_range +from apps.main.api.worktime.models import FabricWorkTime + + +@base_view +def get_current_status(request): + now_date = timezone.now() + start_month = now_date - relativedelta(hours=730) + status_list = list(get_qs_by_range(FabricWorkTime, start_month, now_date)) + if not status_list: + return JsonResponse({'last_status': 'WO', 'worktime': timedelta(0)}) + if len(status_list) < 2: + return JsonResponse( + {'last_status': status_list[0]['status'], 'worktime': timezone.now() - status_list[0]['time']}) + last_status = status_list[-1] + start_status = status_list[-2] + while start_status['status'] == last_status['status'] and len(status_list) >= 1: + start_status = status_list.pop() + now_date = timezone.now() + duration = now_date - last_status['time'] + status_worktime = last_status['time'] - start_status['time'] + duration + return JsonResponse({'last_status': last_status['status'], 'worktime': status_worktime}) \ No newline at end of file diff --git a/apps/main/api/worktime/models.py b/apps/main/api/worktime/models.py new file mode 100644 index 0000000..aa4281f --- /dev/null +++ b/apps/main/api/worktime/models.py @@ -0,0 +1,27 @@ +from django.db import models +from django.utils.timezone import now + + +class FabricWorkTime(models.Model): + """ + Модель для хранения времени работы фабрики + Поле time хранит время записи + Поле status хранит состояние фабрики + Имеет три статуса: + WO - Работает под нагрузкой + WA - Работает без нагрузки + NW - Не работает + """ + time = models.DateTimeField(default=now) + status = models.CharField( + choices=( + ('WO', 'Работает под нагрузкой'), ('WA', 'Работает без нагрузки'), ('NW', 'Не работает')), + max_length=10 + ) + + class Meta: + verbose_name = 'Время работы фабрики' + verbose_name_plural = 'Отрезки времени работы фабрики' + + def __str__(self): + return f'{self.time}: {self.status}' diff --git a/apps/main/api/worktime/service.py b/apps/main/api/worktime/service.py new file mode 100644 index 0000000..f8eb1ee --- /dev/null +++ b/apps/main/api/worktime/service.py @@ -0,0 +1,39 @@ +from datetime import timedelta + +from django.utils import timezone + + +def calculate_work_time(qs: list) -> dict: + status_durations = { + 'WO': timedelta(0), + 'WA': timedelta(0), + 'NW': timedelta(0) + } + + if not qs: + return { + 'WO': 0, + 'WA': 0, + 'NW': 0 + } + + previous_time = qs[0]['time'] + previous_status = qs[0]['status'] + + for work in qs[1:]: + current_time = work['time'] + current_status = work['status'] + + duration = current_time - previous_time + status_durations[previous_status] += duration + + previous_time = current_time + previous_status = current_status + + now_date = timezone.now() + duration = now_date - previous_time + status_durations[previous_status] += duration + + status_durations_hours = {k: round(v.total_seconds() / 3600) for k, v in status_durations.items()} + + return status_durations_hours diff --git a/apps/main/api/worktime/views.py b/apps/main/api/worktime/views.py new file mode 100644 index 0000000..e1f0b08 --- /dev/null +++ b/apps/main/api/worktime/views.py @@ -0,0 +1,32 @@ +from dateutil.relativedelta import relativedelta +from django.http import JsonResponse +from django.utils import timezone + +from apps.main.api.common.base_view import base_view, get_qs_by_range +from apps.main.api.worktime.models import FabricWorkTime +from apps.main.api.worktime.service import calculate_work_time +from apps.main.tasks import create_worktime_data + + +@base_view +def factory_work_time(request): + create_worktime_data() + now_date = timezone.now() + start_month = now_date - relativedelta(hours=730) + start_week = now_date - relativedelta(hours=168) + start_day = now_date - relativedelta(hours=24) + + monthly_qs = get_qs_by_range(FabricWorkTime, start_month, now_date) + monthly = calculate_work_time(list(monthly_qs)) + + weekly_qs = get_qs_by_range(FabricWorkTime, start_week, now_date) + weekly = calculate_work_time(list(weekly_qs)) + + daily_qs = get_qs_by_range(FabricWorkTime, start_day, now_date) + daily = calculate_work_time(list(daily_qs)) + + return JsonResponse({ + 'monthly': monthly, + 'weekly': weekly, + 'daily': daily, + }) diff --git a/apps/main/tasks.py b/apps/main/tasks.py new file mode 100644 index 0000000..a6cd790 --- /dev/null +++ b/apps/main/tasks.py @@ -0,0 +1,34 @@ +import decimal +import traceback + +from dateutil.relativedelta import relativedelta +from django.db.models.functions import TruncMinute +from django.utils import timezone + +from apps.main.api.scales_control.models import ScalesControl +from apps.main.api.worktime.models import FabricWorkTime +from sabron.util import logging + + +def create_worktime_data() -> None: + """ + Создает объекты FabricWorkTime для анализа времени работы фабрики. + Если с весов нет ответа - фабрика не работает - конвейер стоит + Если с весов с Поз.4 меньше 20 - фабрика работает без нагрузки + """ + # TODO переписать под ситуации, создать модуль настроек для упр. конвейера + try: + now_date = timezone.now() + start_day = now_date - relativedelta(hours=24) + + latest_records = ScalesControl.objects.filter( + name='SIEMENSPLC.AZG01.ReportProdDB.Pos4AverSmena', + date__range=(start_day, now_date) + ).annotate( + date_minute=TruncMinute('date') + ).order_by('date_minute', '-date').distinct('date_minute') + for record in latest_records: + status = 'WO' if record.value > decimal.Decimal(20.0) else 'WA' + FabricWorkTime.objects.get_or_create(time=record.date, status=status) + except Exception: + logging.error(traceback.format_exc()) diff --git a/apps/main/tests.py b/apps/main/tests.py index 304e446..d1565d4 100644 --- a/apps/main/tests.py +++ b/apps/main/tests.py @@ -5,8 +5,10 @@ from django.urls import reverse from django.utils import timezone from freezegun import freeze_time -from apps.main.dashboard import calculate_work_time, get_scales_value_by_shifts, get_scales_value -from apps.main.models.dashboard_models import AccidentStop, FabricWorkTime, Position, ScalesControl +from apps.main.api.accident_stops.models import AccidentStop +from apps.main.api.scales_control.models import ScalesControl, Position +from apps.main.api.worktime.models import FabricWorkTime +from apps.main.api.worktime.service import calculate_work_time class AccidentStopViewTests(TestCase): @@ -165,4 +167,4 @@ class GetScalesDataViewTests(TestCase): # TODO тесты для весов # TODO проверить остальные тесты -# TODO написать unit тесты для функций в файле dashboard.py \ No newline at end of file +# TODO написать unit тесты для функций в файле dashboard.py diff --git a/apps/main/urls.py b/apps/main/urls.py index 8ffc4f9..2673f85 100644 --- a/apps/main/urls.py +++ b/apps/main/urls.py @@ -1,19 +1,20 @@ -# -*- coding: utf-8 -*- from django.conf.urls import url -from django.contrib.auth.decorators import login_required -from django.conf.urls import include # Используйте include() чтобы добавлять URL из каталога приложения from django.urls import path -from apps.main.views import views_main, ajax_views +from apps.main import views_main +from apps.main.api.accident_stops.views import get_accident_stops +from apps.main.api.scales_control.views import get_scales_data, get_positions +from apps.main.api.workstatus.views import get_current_status +from apps.main.api.worktime.views import factory_work_time urlpatterns = [ url(r'^$', views_main.mainindex, name='mainindex'), url(r'^scada/$', views_main.scada_index, name='scada_index'), url(r'scada/ajax/$', views_main.get_ajax, name='get_ajax'), - path('accident_stops/', ajax_views.get_accident_stops, name='accident_stops'), - path('worktime/', ajax_views.factory_work_time, name='factory_time'), - path('status/', ajax_views.get_current_status, name='current_status'), - path('scales/', ajax_views.get_scales_data, name='scales'), - path('positions/', ajax_views.get_positions, name='get_positions') + path('accident_stops/', get_accident_stops, name='accident_stops'), + path('worktime/', factory_work_time, name='factory_time'), + path('status/', get_current_status, name='current_status'), + path('scales/', get_scales_data, name='scales'), + path('positions/', get_positions, name='get_positions') ] diff --git a/apps/main/views/ajax_views.py b/apps/main/views/ajax_views.py deleted file mode 100644 index aec55c5..0000000 --- a/apps/main/views/ajax_views.py +++ /dev/null @@ -1,87 +0,0 @@ -from datetime import timedelta - -from dateutil.relativedelta import relativedelta - -from django.http import JsonResponse -from django.utils import timezone - -from apps.main.dashboard import get_qs_by_range, calculate_work_time, get_scales_value_by_shifts, get_scales_value, \ - create_worktime_data -from apps.main.models.dashboard_models import FabricWorkTime, AccidentStop, Position, ScalesControl -from apps.main.views.views_core import base_view - - -@base_view -def get_accident_stops(request): - now_date = timezone.now() - start_month = now_date - relativedelta(hours=730) - start_week = now_date - relativedelta(hours=168) - start_day = now_date - relativedelta(hours=24) - - stops_by_month = get_qs_by_range(AccidentStop, start_month, now_date) - stops_by_week = get_qs_by_range(AccidentStop, start_week, now_date) - stops_by_day = get_qs_by_range(AccidentStop, start_day, now_date) - return JsonResponse({ - 'stops_by_month': stops_by_month.count(), - 'stops_by_week': stops_by_week.count(), - 'stops_by_day': stops_by_day.count() - }) - - -@base_view -def factory_work_time(request): - create_worktime_data() - now_date = timezone.now() - start_month = now_date - relativedelta(hours=730) - start_week = now_date - relativedelta(hours=168) - start_day = now_date - relativedelta(hours=24) - - monthly_qs = get_qs_by_range(FabricWorkTime, start_month, now_date) - monthly = calculate_work_time(list(monthly_qs)) - - weekly_qs = get_qs_by_range(FabricWorkTime, start_week, now_date) - weekly = calculate_work_time(list(weekly_qs)) - - daily_qs = get_qs_by_range(FabricWorkTime, start_day, now_date) - daily = calculate_work_time(list(daily_qs)) - - return JsonResponse({ - 'monthly': monthly, - 'weekly': weekly, - 'daily': daily, - }) - - -@base_view -def get_current_status(request): - now_date = timezone.now() - start_month = now_date - relativedelta(hours=730) - status_list = list(get_qs_by_range(FabricWorkTime, start_month, now_date)) - if not status_list: - return JsonResponse({'last_status': 'WO', 'worktime': timedelta(0)}) - if len(status_list) < 2: - return JsonResponse( - {'last_status': status_list[0]['status'], 'worktime': timezone.now() - status_list[0]['time']}) - last_status = status_list[-1] - start_status = status_list[-2] - while start_status['status'] == last_status['status'] and len(status_list) >= 1: - start_status = status_list.pop() - now_date = timezone.now() - duration = now_date - last_status['time'] - status_worktime = last_status['time'] - start_status['time'] + duration - return JsonResponse({'last_status': last_status['status'], 'worktime': status_worktime}) - - -@base_view -def get_scales_data(request): - positions = Position.objects.order_by('id') - monthly = get_scales_value(positions, 'Month') - average = get_scales_value_by_shifts(positions, 'Aver') - daily = get_scales_value_by_shifts(positions, 'Smena') - return JsonResponse({'daily': daily, 'average': average, 'monthly': monthly}) - - -@base_view -def get_positions(request): - positions = Position.objects.values_list('title', flat=True).order_by('id') - return JsonResponse(list(positions), safe=False) diff --git a/apps/main/views/views_main.py b/apps/main/views_main.py similarity index 100% rename from apps/main/views/views_main.py rename to apps/main/views_main.py diff --git a/repcofkk/settings.py b/repcofkk/settings.py index 853048a..a74c9a5 100644 --- a/repcofkk/settings.py +++ b/repcofkk/settings.py @@ -13,7 +13,7 @@ LANGUAGE_CODE = 'ru' TIME_ZONE = 'Asia/Krasnoyarsk' USE_I18N = True USE_L10N = True -USE_TZ = True +USE_TZ = False DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' MIDDLEWARE = [