from patch.include import *
from tqdm import tqdm


def rec_recalc(task):
    print(task)
    if task.parent_task and task.parent_task.cmf_deleted:
        # фиксим таски с удаленным parent
        task.parent_task = None
    task._calc_cache_branch_gantt_path()
    task.save(only_data=True, emit=False, notify=False)
    for sub_task in models.CmfTask.list(
            cache_branch_gantt_path=None, has_child_tasks=True, parent_task=task, fields=['has_child_tasks', 'parent_task.cmf_deleted'],
        ):
        rec_recalc(sub_task)

@app_context(commit=True)
def patch():
    with cmfutil.disable_acl(), cmfutil.disable_notify():
        for task in models.CmfTask.list(
            cache_branch_gantt_path=None, has_child_tasks=True, parent_task=None, fields=['has_child_tasks', 'parent_task.cmf_deleted'],
        ):
            # Проходим рекурсивно вниз, т.к. для рассчета требуется последовательность
            rec_recalc(task)

if __name__ == "__main__":
    patch()
