from patch.include import *
from tqdm import tqdm


def calc_cache_path(role):
    path = []
    def get_org_unit(org_unit_id):
        org_unit = models.CmfOrgUnit.get(id=org_unit_id, fields=['tree_parent_id'])
        if org_unit is not None:
            path.insert(0, {'id': org_unit.id.value, 'code': org_unit.code.value, 'name': org_unit.name.value})
            org_unit_parent = org_unit.tree_parent_id.value if org_unit.tree_parent_id else None
            if org_unit_parent:
                get_org_unit(org_unit_parent)

    if role.tree_parent_id:
        get_org_unit(role.tree_parent_id.value)

    role.cache_path = path
    role.save(only_data=True)

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

    for role in models.CmfRole.list(fields=['tree_parent_id']):
        calc_cache_path(role)

if __name__ == "__main__":
    patch()
