diff --git a/app/apps/main/services/base_service.py b/app/apps/main/services/base_service.py index e5e15a2..50bb820 100644 --- a/app/apps/main/services/base_service.py +++ b/app/apps/main/services/base_service.py @@ -1,7 +1,6 @@ -from datetime import timedelta, datetime +from datetime import datetime from dateutil.relativedelta import relativedelta -from django.db.models import Model from django.utils import timezone @@ -11,14 +10,14 @@ class DashboardBaseService: def get_qs_by_range(self, start, end): return ( - self.model.objects.only("time") + self.model.objects.only('time') .filter(time__range=(start, end)) - .order_by("time") + .order_by('time') .values() ) def get_latest_value(self): - self.model.objects.latest("time") + self.model.objects.latest('time') @staticmethod def get_current_time(): @@ -31,7 +30,7 @@ class DashboardBaseService: start_shift = now_date.replace( hour=20, minute=0, second=0, microsecond=0 ) - relativedelta(days=1) - elif now_date.hour > 20: + elif now_date.hour >= 20: start_shift = now_date.replace(hour=20, minute=0, second=0, microsecond=0) return start_shift diff --git a/app/apps/main/services/urls.py b/app/apps/main/services/urls.py index c7ab711..36d9ead 100644 --- a/app/apps/main/services/urls.py +++ b/app/apps/main/services/urls.py @@ -8,6 +8,7 @@ from apps.main.services.scales_control.views import ( ) from apps.main.services.workstatus.views import get_current_status from apps.main.services.worktime.views import ( + create_worktime, factory_work_time, factory_work_time_durations, ) @@ -21,6 +22,7 @@ urlpatterns = [ factory_work_time_durations, name='factory_time_durations', ), + path('worktime/create/', create_worktime, name='create_worktime'), path('status/', get_current_status, name='current_status'), path('positions/', get_positions, name='get_positions'), path('density_sensors/', get_sensors_list, name='get_sensors_list'), diff --git a/app/apps/main/services/worktime/create_worktime_data.py b/app/apps/main/services/worktime/create_worktime_data.py new file mode 100644 index 0000000..6e0ba69 --- /dev/null +++ b/app/apps/main/services/worktime/create_worktime_data.py @@ -0,0 +1,47 @@ +from datetime import timedelta + +from apps.main.models.scales_control import ScalesControl +from apps.main.models.worktime import FabricWorkTime +from apps.main.services.base_service import DashboardBaseService +from django.db.models.functions import TruncMinute +from sabron.util.sabronmodule import get_settings + + +def create_worktime_data() -> bool: + """ + Description: Создает объекты времени работы фабрики, собирая данные с весов. + Returns: 1 | 0 + """ + # получение входных данных + now_date = DashboardBaseService.get_current_time() + start_period = now_date - timedelta(hours=0) + control_conveyor = get_settings('control_conveyor') + + # получение данных с весов поминутно + latest_records_scales = ScalesControl.objects.filter( + name=control_conveyor, + time__lte=start_period + ).annotate( + time_minute=TruncMinute('time') + ).order_by('time_minute').distinct('time_minute') + + # если нет записей с весов - выход из функции + if not latest_records_scales: + return 0 + + # получение указателя на первую запись в qs + current_record = latest_records_scales[0] + # создание первой записи + FabricWorkTime.objects.get_or_create(time=current_record.time, status='WO') + # цикл по qs с двумя указателями - на текущую и следующую запись + for record in latest_records_scales[1:]: + # вычисление разницы (в минутах) между временем текущей и следующей записи + delta = (record.time - current_record.time).total_seconds() / 60 + # если разница больше 5 минут - фабрика не работает в промежутке между текущей и следующей записью + if delta > 5: + # текущая запись - начало остановки + FabricWorkTime.objects.get_or_create(status='NW', time=current_record.time) + # следующая запись - начало работы + FabricWorkTime.objects.get_or_create(status='WO', time=record.time) + current_record = record + return 1 diff --git a/app/apps/main/services/worktime/views.py b/app/apps/main/services/worktime/views.py index 70ae79c..97ebca2 100644 --- a/app/apps/main/services/worktime/views.py +++ b/app/apps/main/services/worktime/views.py @@ -1,10 +1,8 @@ -from django.http import JsonResponse - from apps.main.models.worktime import FabricWorkTime from apps.main.services.worktime.service import FabricWorkTimeService from apps.main.tasks import create_worktime_data - from apps.util.base_view import base_view +from django.http import JsonResponse @base_view @@ -17,3 +15,9 @@ def factory_work_time(request): def factory_work_time_durations(request): service = FabricWorkTimeService(FabricWorkTime) return JsonResponse(service.return_worktime(return_durations=True)) + + +@base_view +def create_worktime(request): + res = create_worktime_data() + return JsonResponse({'success': bool(res)}, safe=False) diff --git a/app/apps/main/tasks.py b/app/apps/main/tasks.py index 4c741e8..e4dfa9b 100644 --- a/app/apps/main/tasks.py +++ b/app/apps/main/tasks.py @@ -40,7 +40,7 @@ def create_start_shift_worktime(): """ Description: Создает копию FabricWorkTime под время начала смены. - Вызывается в 8:01 и 20:01 + Вызывается в 8:00 и 20:00 Returns: """ @@ -65,35 +65,37 @@ def create_start_shift_worktime(): def create_worktime_data(): """ Description: - Создает объекты времени работы фабрики. Получает данные с Redis по весам конвейера. Если разница времени записи с + Создает объекты времени работы фабрики. Получает данные с Redis по весам конвейера. Если разница текущего времени записи с Redis больше чем 5 минут с текущим временем - фабрика не работает Запись будет создаваться только в случае если статус изменился. - + Вызывается каждые 30 секунд Returns: строку со статусом задачи """ now_date = DashboardBaseService.get_current_time() obj_from_redis = get_scales_data_from_redis(get_settings('control_conveyor')) - delta = (now_date - obj_from_redis['date']).total_seconds() / 60 + + delta_now_and_redis = (now_date - obj_from_redis['date']).total_seconds() / 60 try: latest_worktime_obj = FabricWorkTime.objects.latest('time') except FabricWorkTime.DoesNotExist: - obj = FabricWorkTime.objects.create(status='WO' if delta < 5 else 'NW', time=obj_from_redis['date']) + obj = FabricWorkTime.objects.create(status='WO' if delta_now_and_redis < 5 else 'NW', + time=obj_from_redis['date']) return 'Success. Created first obj: ' + str(obj) status = None - if latest_worktime_obj.status == 'NW' and delta < 5: + if latest_worktime_obj.status == 'NW' and delta_now_and_redis < 5: status = 'WO' - elif latest_worktime_obj.status == 'WO' and delta > 5: + elif latest_worktime_obj.status == 'WO' and delta_now_and_redis > 5: status = 'NW' if status: obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date']) - return 'Success. Created obj: ' + str(obj) + return f'Success. Created obj: {str(obj)} (latest {str(latest_worktime_obj)}' return 'Success. ' + str(latest_worktime_obj) @@ -214,7 +216,8 @@ def create_shift_report(): daily = service.get_scales_value_by_shifts(positions, 'Smena') concentrate = service.get_concentrate_value() if not concentrate: - concentrate = {} + concentrate = {'concentrate': 0, + 'dropout': 0} scales_data = json.dumps({'daily': daily, 'average': average}, sort_keys=True, indent=1, diff --git a/app/apps/util/redis_api.py b/app/apps/util/redis_api.py index 4306ade..4dc7220 100644 --- a/app/apps/util/redis_api.py +++ b/app/apps/util/redis_api.py @@ -164,5 +164,13 @@ class RedisHashService(RedisBaseService): return None -class RedisService(RedisHashService, RedisSimpleService): +class RedisExpireService(RedisBaseService): + def set_expire(self, key: str, expire: int): + try: + self.connection.expire(key, expire) + except redis.RedisError as e: + print(f'Error getting setting expiring values: {e}') + + +class RedisService(RedisHashService, RedisSimpleService, RedisExpireService): pass diff --git a/app/apps/util/redis_cache.py b/app/apps/util/redis_cache.py index 38cc46b..c0beeba 100644 --- a/app/apps/util/redis_cache.py +++ b/app/apps/util/redis_cache.py @@ -9,6 +9,7 @@ class RedisCache: def set_cache_value(self, key: str, value: str) -> str: with RedisService(host=self.redis_host, port=self.redis_port, db=2) as redis_service: value = redis_service.set_value('cache_tasks/' + key, value) + redis_service.set_expire('cache_tasks/' + key, 60) return value def get_cache_value(self, key: str) -> bool: diff --git a/app/repcofkk/celery.py b/app/repcofkk/celery.py index b6ccb64..0245dd9 100644 --- a/app/repcofkk/celery.py +++ b/app/repcofkk/celery.py @@ -33,6 +33,6 @@ app.conf.beat_schedule = { }, 'shift_start_worktime': { 'task': 'apps.main.tasks.create_start_shift_worktime', - 'schedule': crontab(hour='8,20', minute=1) + 'schedule': crontab(hour='8,20', minute=0) } }