from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def fix_attach_ver():
    """
    Для тестирования патча: ( cd /opt/eva-app; python3 -m patch.202309070934_fix_attach_ver )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    print('Создадим версии файлам у которых их нет')
    step = 1000
    _filter = [['parent_id', 'LIKE', 'CmfDocument:%'], ['cmf_import', '!=', None]]
    cnt = models.CmfAttachment.count(filter=_filter)
    i = 0
    while i*step < cnt:
        for attach in tqdm(models.CmfAttachment.list(slice=[i*step, i*step + step], filter=_filter, order_by=['cmf_created_at'])):
            try:
                rfile = attach.get_rfile()
                if not rfile or rfile.get_version() is not None:
                    continue
                for f in attach.get_content():
                    attach.upload_stream_file(stream=f, make_preview=False)
            except Exception as e:
                print(f'Не удалось исправить вложение: {attach.id}')
                print(e)
        i += 1


if __name__ == "__main__":
    fix_attach_ver()
