Delimiter //
/**
 * Account categ is not provided : we search the default "DOVALID" category for 
 * the current entity. If it not exists, we throw an error. Else, if 
 * it exists, we assign it to the line
 * because do valid was not populated by defaut, search either "CHECK' category
 * @param int batchnum
 * @author Benoit
 * @ticket #4142
 */ 
Drop Procedure If Exists LOADER_ACCOUNTS_NORMALIZE_MAP_CATEG_NOT_PROVIDED//
Create Procedure LOADER_ACCOUNTS_NORMALIZE_MAP_CATEG_NOT_PROVIDED(
    In batchnum Int
)
Begin

    Set @id_entity = GET_LOADER_INFO('ID_ENTITIES', batchnum);

    -- // Get the Id of "DOVALID" category for the current entity
    Set @id_categ = ( 
        Select Min(AC.ID_DF_ACCOUNTS_CATEGORIES)
        From DF_ACC_CATEG AC
        Where 
			AC.DF_ACC_CATEG_CODE In ('DOVALID', 'CHECK')
            And AC.ENTITIES_ID_ENTITIES = @id_entity
    );

    -- // Apply to new accounts without category
    Update 
        LOADER_ACCOUNTS LA
        Inner Join 
            LOADER_STATUS LS
            On LS.ID_LOADER_STATUS = LA.LOADER_STATUS_ID_LOADER_STATUS
    Set 
        LA.DF_ACC_CATEG_ID_DF_ACC_CATEG = @id_categ
        , LS.LOADER_STATUS_ERRCOUNT = 
            (CASE WHEN @id_categ IS NULL
                THEN LS.LOADER_STATUS_ERRCOUNT + 1
                ELSE LS.LOADER_STATUS_ERRCOUNT
            END)
        , LS.LOADER_STATUS_ERRMSGS = 
            (CASE WHEN @id_categ IS NULL
                THEN LOADER_CONCAT_ERR(LS.LOADER_STATUS_ERRMSGS, Concat('Catégorie "DOVALID" ou "CHECK" par défaut introuvable pour l''entité "', Coalesce(@id_entity, '?'), '"' ))
                ELSE LS.LOADER_STATUS_ERRMSGS
            END)
    Where
        LS.LOADER_STATUS_BATCH_NUM = batchnum 
        And LA.ID_ACCOUNTS_NEW Is Not Null
        And Coalesce(LA.ACCOUNTS_CATEG,'') = ''
    ;
            
End//