from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def project_copy_fix():
    """
    Исправляет проблемы в скопированных проектах:
    1. Неверный main_gantt_project в скопированном проекте
    2. В скопированном проекте права наследуются от оригинального проекта
    """
    print('Запуск патча ')
    for project in models.CmfProject.list(fields=['main_gantt_project.op_gantt_task.project']):
        if project.main_gantt_project and project.main_gantt_project.op_gantt_task.project != project:
            print(f'Обрабатываю проект:{project.id} - {project.code} - {project.name}')
            project.main_gantt_project.op_gantt_task = None
            project.main_gantt_project._calc_gantt_task()
            project.main_gantt_project.save(notify=False)

            project.tree_parent.is_changed = True
            project.perm_acl = None
            project._calc_perm_parent()
            project._calc_perm_inherit_acl_id()
            project._calc_perm_has_acl()
            project._calc_perm_acl()
            project.perm_has_acl.is_changed = True
            project._calc_perm_effective_acl()
            project.save(notify=False)

            for child_model in cmf.models.CmfEntity.iter_subclasses():
                if child_model.class_name =="CmfAccessList":
                    continue
                children = child_model.list(parent=project)
                for child in children:
                    print(f'Обрабатываю объект:{child.id} - {child.code} - {child.name}')
                    child.tree_parent.is_changed = True
                    child.perm_acl = None
                    child._calc_perm_parent()
                    child._calc_perm_inherit_acl_id()
                    child._calc_perm_has_acl()
                    child._calc_perm_acl()
                    child._calc_perm_effective_acl()
                    child.save(notify=False, only_data=True)

            project.cmf_owner.is_changed = True
            project.perm_effective_acl_id.is_changed = True
            project._acl_spread_inheritance()
            project.perm_policy.is_changed = True
            project._calc_perm_acl()
            project.save(notify=False, only_data=True)
            commit_all_ds()

if __name__ == "__main__":
    project_copy_fix()
