Delimiter //
/**
    In batchnum Int : num du lot, si 0 ou null traitement de l'ensembles des lignes
*/
Drop Procedure if exists LOADER_ACCOUNTS_COPY//
Create Procedure LOADER_ACCOUNTS_COPY (
    In batchnum int
)
Begin

    set @lac_batchnum = batchnum;

    lac_preTreatement: Begin

        if @lac_batchnum <> 1 Then
            leave lac_preTreatement;
        End if;

        --  test si des scores sont mise à jour
        --  => historisation FIANA
        
        Set @scoreUpdated = Coalesce(
                    (
                        Select ID_ACCOUNTS 
                        From LOADER_ACCOUNTS tar
                            Inner Join LOADER_STATUS sts
                                On tar.LOADER_STATUS_ID_LOADER_STATUS = sts.ID_LOADER_STATUS
                        Where ID_ACCOUNTS Is Not Null
                            And sts.LOADER_STATUS_ERRCOUNT = 0
                            And Coalesce(FI_ANA_CASH_ASSESSMENT, FI_ANA_INTERNAL_SCORE_RATING, FI_ANA_EXTERNAL_SCORE_RATING) IS Not Null
                        Limit 1 
                    )
                    , 0 
                )
            ;
        if @scoreUpdated = 0 Then
            leave lac_preTreatement;
        End if;

        -- des score vont être mise à jour
        -- il faut historiser fi_ana
--         call BUSINESS_BACKUP_FIANA(null, 0);
        call LOADER_ACCOUNTS_COPY_FIANA_BACKUP();
        call BUSINESS_KEEP_ONE_ACCOUNT_FIANA_PER_MONTH();
    End;

    updateQuerys: Begin
        call LOADER_ACCOUNTS_UPDATE(batchnum);
        call LOADER_ACCOUNTS_COPY_ACCOUNTSSTATUS_UPDATE(batchnum);
        call LOADER_ACCOUNTS_PENALTIES_DELETE(batchnum);
        call LOADER_ACCOUNTS_COPY_FIANA_UPDATE(batchnum);
    end ;
    insertQuerys: Begin

        call CASH_AUTOINCREMENT_VALUE('ACCOUNTS', @lac_lastid);
        set @entitie = GET_LOADER_INFO('ID_ENTITIES', batchnum);

        call LOADER_ACCOUNTS_INSERT(batchnum, @lac_lastid, @entitie);
        call LOADER_ACCOUNTS_COPY_ACCOUNTSSTATUS_INSERT(batchnum, @lac_lastid);
        call LOADER_ACCOUNTS_PENALTIES_INSERT(batchnum, @lac_lastid);
        call LOADER_ACCOUNTS_COPY_CONTACTS_ACCOUNTS_UPDATE(batchnum, @lac_lastid);
        call LOADER_ACCOUNTS_COPY_FIANA_INSERT(batchnum, @lac_lastid);

    end ;
    

End //

Delimiter ;





