from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def gantt_project_recalc_actual():
    """
    Для тестирования патча: ( cd /opt/eva-app; python3 -m patch.202408161254_gantt_project_recalc_actual )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    print('Запуск патча gantt_project_recalc_actual')

    preload_fields = [
        '*',
        'parent',
        'task',
        'gantt_project',
        'gantt_project.op_gantt_task',
        'parent_task',
        'parent_task.gantt_project',
        'parent_task.op_gantt_task',
        'task.logic_prefix',
        'task.parent_task.logic_prefix',
        'task.has_child_tasks',
        'task.plan_start_date',
        'task.plan_end_date',
        'task.responsible',
        'task.executors',
    ]

    for gantt_project in models.CmfGanttTask.list(filter=['task.logic_prefix', '==', 'task.gantt_project'], fields=preload_fields):

        child_task_filter=[['gantt_project', '==', gantt_project.task],
                           ['parent_task', '==', None],
                           ['actual_work', '!=', None],
                           ['actual_work', '!=', 0]]
        child_tasks = models.CmfGanttTask.list(filter=child_task_filter, fields=['actual_work'])
        child_tasks_actual_work = 0
        for child_task in child_tasks:
            child_tasks_actual_work += child_task.actual_work.value

        gantt_project.actual_work = child_tasks_actual_work
        gantt_project._calc_actual_complete()
        gantt_project.save(only_data=True)

if __name__ == "__main__":
    gantt_project_recalc_actual()
