from patch.include import *
from tqdm import tqdm
import datetime

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

    def update_custom_fields():
        models.CmfTask.custom_fields_gen_meta(
            {
                'meta_version': datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
                'model_name': 'CmfTask',
                'force': False,
            }
        )
        models.CmfTask.custom_field_sync_update_models({'cmf_model_name': 'CmfTask'})

    need_update_custom_fields = True
    for cust_field in tqdm(models.CmfCustField.list(filter=['field_type', '==', 'CmfBool'])):
        field_name = cust_field.name.value
        # Иногда меты кастомных полей может и не быть, например у dev сервера
        if not hasattr(models.CmfTask, field_name) and need_update_custom_fields:
            update_custom_fields()
            need_update_custom_fields = False
        models.CmfTask.bulk_update(values={field_name: False}, filter=[field_name, '==', None])
        commit_all_ds()


if __name__ == "__main__":
    custom_field_bool_fix()
