from patch.include import *
from tqdm import tqdm
from collections import defaultdict


@app_context(commit=True)
def fix_resource_assignments():
    """
    Для тестирования патча: ( cd /opt/eva-app; python3 -m patch.202502281718_fix_resource_assignments )
    BCRM ~ 1.5 минута
    """
    print('Запуск патча fix_resource_assignments')
    _filter = [['cmf_created_at', '>', 'now() - 1y 6m'],
               ['OR', ['responsible', '!=', None],
                      ['executors', 'EXISTS', '']]]

    to_be_fixed_ids = []

    for t in models.CmfTask.slist(filter=_filter, fields=['executors', 'responsible', 'parent']):
        executors_count = len([e for e in t.executors if e.class_name == 'CmfPerson']) if t.executors else 0

        if t.responsible and t.responsible.class_name == 'CmfPerson':
            executors_count += 1

        assignments = models.CmfTaskResAssign.slist(filter=['parent_id', '==', t.id])

        if len(assignments) > 0 and executors_count != len(assignments):
            to_be_fixed_ids.append(t.id)

    i = 0
    step = 100
    while True:
        batch =  models.CmfTask.list(filter=['id', 'IN', to_be_fixed_ids], slice=[i, i + step])

        if not batch:
            break

        for task in batch:
            models.CmfTaskResAssign.sync_task_resources(task)

        i += step

        cmf_commit()

if __name__ == "__main__":
    fix_resource_assignments()
