Переработка регулярной задачи на создание объектов времени работы фабрики.

Запись создается в момент начала смены, дублируя последний статус
This commit is contained in:
zakhy 2024-08-20 10:56:45 +07:00
parent d81acdd675
commit aec98de94b
3 changed files with 61 additions and 28 deletions

View File

@ -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)

View File

@ -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

View File

@ -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: