From aec98de94bbd22440af22c50eab55fc29fc65d02 Mon Sep 17 00:00:00 2001 From: zakhy Date: Tue, 20 Aug 2024 10:56:45 +0700 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=BA=D0=B0=20=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=BD=D0=BE=D0=B9=20=D0=B7=D0=B0=D0=B4=D0=B0=D1=87=D0=B8?= =?UTF-8?q?=20=D0=BD=D0=B0=20=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B2=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=B8=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D1=8B=20=D1=84=D0=B0=D0=B1=D1=80=D0=B8=D0=BA=D0=B8?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Запись создается в момент начала смены, дублируя последний статус --- app/apps/main/services/base_service.py | 13 ++++++ app/apps/main/services/worktime/service.py | 26 ++++++++--- app/apps/main/tasks.py | 50 ++++++++++++---------- 3 files changed, 61 insertions(+), 28 deletions(-) diff --git a/app/apps/main/services/base_service.py b/app/apps/main/services/base_service.py index 072de96..e5e15a2 100644 --- a/app/apps/main/services/base_service.py +++ b/app/apps/main/services/base_service.py @@ -34,3 +34,16 @@ class DashboardBaseService: elif now_date.hour > 20: start_shift = now_date.replace(hour=20, minute=0, second=0, microsecond=0) return start_shift + + @staticmethod + def round_time(dt: datetime): + # Умножаем минуту на 60 и добавляем секунды для получения общего числа секунд + total_seconds = dt.hour * 3600 + dt.minute * 60 + dt.second + # Округляем до ближайшего часа + if total_seconds % 3600 >= 1800: # Если больше половины часа + total_seconds += (3600 - (total_seconds % 3600)) # Округляем вверх + else: + total_seconds -= (total_seconds % 3600) # Округляем вниз + # Получаем новые часы, минуты и секунды + new_hour = (total_seconds // 3600) % 24 # 24-часовой формат + return dt.replace(hour=new_hour, minute=0, second=0, microsecond=0) diff --git a/app/apps/main/services/worktime/service.py b/app/apps/main/services/worktime/service.py index 2a3131c..dec3aac 100644 --- a/app/apps/main/services/worktime/service.py +++ b/app/apps/main/services/worktime/service.py @@ -1,4 +1,4 @@ -from datetime import timedelta +from datetime import timedelta, datetime from dateutil.relativedelta import relativedelta @@ -29,10 +29,7 @@ class FabricWorkTimeService(DashboardBaseService): now_date = cls.get_current_time() duration = now_date - previous_time - if duration.seconds // 60 > 5: - status_durations["NW"] += duration - else: - status_durations[previous_status] += duration + status_durations[previous_status] += duration if return_duration: return status_durations status_durations_hours = { @@ -57,15 +54,34 @@ class FabricWorkTimeService(DashboardBaseService): monthly_qs = self.get_qs_by_range(start_month, now_date) monthly = self.calculate_work_time(list(monthly_qs), return_durations) + # diff_monthly = self.check_worktime_validity(monthly, start_month, now_date) + # if diff_monthly.total_seconds() // 60 > 5: + # monthly['NW'] += diff_monthly weekly_qs = self.get_qs_by_range(start_week, now_date) weekly = self.calculate_work_time(list(weekly_qs), return_durations) + # diff_weekly = self.check_worktime_validity(weekly, start_week, now_date) + # if diff_weekly.total_seconds() // 60 > 5: + # weekly['NW'] += diff_weekly shift_qs = self.get_qs_by_range(start_shift, now_date) daily = self.calculate_work_time(list(shift_qs), return_durations) + # diff_daily = self.check_worktime_validity(daily, start_shift, now_date) + # if diff_daily.total_seconds() // 60 > 5: + # daily['NW'] += diff_daily return { "monthly": monthly, "weekly": weekly, "daily": daily, } + + @classmethod + def check_worktime_validity(cls, worktime: dict, start_period: datetime, now_date: datetime) -> timedelta: + mas_worktime = [i for i in worktime.values()] + total_time = timedelta(hours=0) + for i in mas_worktime: + total_time += i + actual_worktime_duration = now_date - start_period + diff = actual_worktime_duration - total_time + return diff diff --git a/app/apps/main/tasks.py b/app/apps/main/tasks.py index e9d501e..08d6391 100644 --- a/app/apps/main/tasks.py +++ b/app/apps/main/tasks.py @@ -21,19 +21,38 @@ from sabron.util.sabronmodule import get_settings def create_worktime_data(): control_conveyor = get_settings("control_conveyor") now_date = DashboardBaseService.get_current_time() + start_shift = DashboardBaseService.get_shift_start(now_date) + with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service: value = redis_service.hget_value(control_conveyor, "Value") date_str = redis_service.hget_value(control_conveyor, "Date") date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S.%f") + obj_from_redis = {"value": value, "date": date} - latest_worktime_obj = FabricWorkTime.objects.latest('time') delta = (now_date - obj_from_redis['date']).seconds / 60 - if latest_worktime_obj.status == 'NW' and delta < 5: - obj = FabricWorkTime.objects.create(status='WO', time=obj_from_redis['date']) - return "Success. Created obj: " + str(obj) + + try: + latest_worktime_obj = FabricWorkTime.objects.latest('time') + except FabricWorkTime.DoesNotExist: + status = 'WO' if delta < 5 else 'NW' + obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date']) + return "Success. Created first obj: " + str(obj) + status = None + rounded_time = DashboardBaseService.round_time(latest_worktime_obj.time) + if (now_date.replace(minute=0, second=0, microsecond=0) == start_shift and + rounded_time != start_shift): + status = latest_worktime_obj.status + + elif latest_worktime_obj.status == 'NW' and delta < 5: + status = 'WO' + elif latest_worktime_obj.status == 'WO' and delta > 5: - obj = FabricWorkTime.objects.create(status='NW', time=obj_from_redis['date']) + status = 'NW' + + if status: + obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date']) return "Success. Created obj: " + str(obj) + return "Success. " + str(latest_worktime_obj) @@ -45,7 +64,7 @@ def create_worktime_data(): # Если с весов с Поз.4 меньше 20 - фабрика работает без нагрузки # """ # -# # TODO переписать по аналогу SQL скрипта с весами +# # try: # control_conveyor = get_settings("control_conveyor") # now_date = DashboardBaseService.get_current_time() @@ -130,6 +149,7 @@ def write_scale_control_data_to_redis(): @shared_task def thin_out_scales(): positions = Position.objects.all() + results = [] for position in positions: pos_tags = [ position.aver_smena_tag, @@ -139,7 +159,6 @@ def thin_out_scales(): position.month_tag, position.sutki_tag, ] - results = [] for tag in pos_tags: try: res = thin_out_scale(tag) @@ -149,22 +168,7 @@ def thin_out_scales(): except Exception: logging.error(f"Celery: {traceback.format_exc()} \n on tag {tag}") results.append({tag: {traceback.format_exc()}}) - return results - - -@shared_task -def thin_out_worktime(): - worktime_qs = FabricWorkTime.objects.filter( - time__lt=timezone.now() - timedelta(hours=12) - ).order_by("time") - if not worktime_qs: - return "No worktime" - prev = worktime_qs[0] - for cur_obj in worktime_qs[1:]: - if cur_obj.status == prev.status: - cur_obj.delete() - prev = cur_obj - return f"Success. Deleted: {len(worktime_qs)} rows" + return results def thin_out_scale(tag) -> bool | int: