from patch.include import *
from tqdm import tqdm


@app_context(commit=True)
def patch():
    """
    Для тестирования патча: ( cd /opt/crm; python3 -m patch.20220XXXXXXX_PATCHNAME )
    Здесь можно работать с моделями через models.CmfTask и т.д.
    Для прогрессбара используйте:
    for task in tqdm(models.CmfTask.list()):
        ...
    """
    for model in cmfutil.iter_models():
        count = 0
        if 'orderno' in model.fields:
            for obj in model.list(filter=['orderno', '=', None], include_templates=True, fields=['orderno']):
                count += 1
                obj.orderno = 0
                obj.save(only_data=True, emit=False)
                if count % 10000 == 0:
                    commit_all_ds()
        if count:
            print(f'{model.class_name}.orderno: {count} fixed')
            commit_all_ds()

        count = 0
        if 'is_template' in model.fields:
            for obj in model.list(filter=['is_template', '=', None], include_templates=True, fields=['is_template']):
                count += 1
                obj.is_template = False
                obj.save(only_data=True, emit=False)
                if count % 10000 == 0:
                    commit_all_ds()
        if count:
            print(f'{model.class_name}.is_template: {count} fixed')
            commit_all_ds()


if __name__ == "__main__":
    patch()
