Delimiter //
/**
 * If the account ref exists, give its id to the entries
 * Else, notify an error
 * 
 * @author Jean-François
 * @ticket #3926
 */ 
Drop Procedure If Exists LOADER_ENTRIES_NORMALIZE_MAP_ACCOUNT_REF_PROVIDED//
Create Procedure LOADER_ENTRIES_NORMALIZE_MAP_ACCOUNT_REF_PROVIDED(
    In batch_num Int
)
Begin

    Set @idEntities = GET_LOADER_INFO('ID_ENTITIES', batch_num);

--     Update
--         LOADER_ENTRIES E
--         Inner Join LOADER_STATUS S
--             On S.ID_LOADER_STATUS = E.LOADER_STATUS_ID_LOADER_STATUS
--         Left Join ACCOUNTS A
--             On A.ACCOUNTS_REF = E.ACCOUNTS_REF
--             And A.ENTITIES_ID_ENTITIES = @idEntities
--     Set
--         E.ACCOUNTS_ID_ACCOUNTS = A.ID_ACCOUNTS
--         , S.LOADER_STATUS_ERRCOUNT = 
--             (CASE WHEN A.ID_ACCOUNTS IS NULL
--                 THEN S.LOADER_STATUS_ERRCOUNT + 1
--                 ELSE S.LOADER_STATUS_ERRCOUNT
--             END)
--         , S.LOADER_STATUS_ERRMSGS = 
--             (CASE WHEN A.ID_ACCOUNTS IS NULL
--                 THEN LOADER_CONCAT_ERR(S.LOADER_STATUS_ERRMSGS, Concat('Référence de compte inexistante :', E.ACCOUNTS_REF ) )
--                 ELSE S.LOADER_STATUS_ERRMSGS
--             END)
--     Where S.LOADER_STATUS_BATCH_NUM = batch_num
--         And Coalesce(E.ACCOUNTS_REF, '') != ''
--     ;

--     -- initilitialisation si on doit rejouer le batch
-- 
--     Update
--         LOADER_ENTRIES E
--         Inner Join LOADER_STATUS S
--             On S.ID_LOADER_STATUS = E.LOADER_STATUS_ID_LOADER_STATUS
--         
--     Set
--         E.ACCOUNTS_ID_ACCOUNTS = null
--     Where 
--         S.LOADER_STATUS_BATCH_NUM = batch_num
--         And Coalesce(E.ACCOUNTS_REF, '') != ''
--     ;

    -- maj ID ACCOUNT

    Update
        LOADER_ENTRIES E
        Inner Join LOADER_STATUS S
            On S.ID_LOADER_STATUS = E.LOADER_STATUS_ID_LOADER_STATUS
        Inner Join ACCOUNTS A
            On A.ACCOUNTS_REF = E.ACCOUNTS_REF
            And A.ENTITIES_ID_ENTITIES = @idEntities
    Set
        E.ACCOUNTS_ID_ACCOUNTS = A.ID_ACCOUNTS
        
    Where S.LOADER_STATUS_BATCH_NUM = batch_num
        And Coalesce(E.ACCOUNTS_REF, '') != ''
    ;

    -- maj des erreur

    Update
        LOADER_ENTRIES E
        Inner Join LOADER_STATUS S
            On S.ID_LOADER_STATUS = E.LOADER_STATUS_ID_LOADER_STATUS
    Set
        S.LOADER_STATUS_ERRCOUNT = S.LOADER_STATUS_ERRCOUNT + 1
        , S.LOADER_STATUS_ERRMSGS = LOADER_CONCAT_ERR(S.LOADER_STATUS_ERRMSGS, Concat('Référence de compte inexistante :', E.ACCOUNTS_REF ) )
    Where 
        S.LOADER_STATUS_BATCH_NUM = batch_num
        And Coalesce(E.ACCOUNTS_REF, '') != ''
        And E.ACCOUNTS_ID_ACCOUNTS Is Null
    ;

End//
Delimiter ;