Delimiter $$
/**
 * Author:  armen
 * Created: 22 juin 2023
 */
Drop Procedure if Exists BUSINESS_FI_ANA_COMPUTE_LAST_MONTH_HISTO $$
Create Procedure BUSINESS_FI_ANA_COMPUTE_LAST_MONTH_HISTO(In idaccounts Int unsigned)
Begin
    bfaclmh_Main: Begin

        Set @bfaclmh_idaccounts = idaccounts;
        if @bfaclmh_idaccounts Is null Then
--             Set @bfaclmh_accMinVal = 0;
            Set @bfaclmh_accMinVal = (Select ID_ACCOUNTS FROM ACCOUNTS Order By ID_ACCOUNTS Limit 1);
--             Set @bfaclmh_accMaxVal = 40000000;
            Set @bfaclmh_accMaxVal = (Select ID_ACCOUNTS FROM ACCOUNTS Order By ID_ACCOUNTS Desc Limit 1);
        Else
            Set @bfaclmh_accMinVal = @bfaclmh_idaccounts;
            Set @bfaclmh_accMaxVal = @bfaclmh_idaccounts;
        End if;

--         Set FIANAHISTO_OPT_EXCLUDE_DSORB =  Cast(X'8000' As Unsigned);
--         Set FIANAHISTO_OPT_MAX_DSO_MASQ = Cast(X'7FFF' As Unsigned);

        call BUSINESS_FI_ANA_INSERT_NEW_ACCOUNTS(@bfaclmh_idaccounts, null);
        call BUSINESS_FI_ANA_INSERT_NEW_MEMBERS(Null);

        Set @bfaclmh_today = CURDATE(); 
        Set @bfaclmh_previusMonth = DATE_ADD(@bfaclmh_today, INTERVAL -DAY(@bfaclmh_today) day);

--         Set @bfaclmh_oldestCalculatedMonth = DATE_SUB(@bfaclmh_previusMonth, INTERVAL 1 MONTH);
--         Set @bfaclmh_oldestCalculatedMonth = LAST_DAY(@bfaclmh_previusMonth);
        Set @bfaclmh_oldestCalculatedMonth = LAST_DAY(@bfaclmh_previusMonth);

        Set @bfaclmh_computedMonth =  @bfaclmh_oldestCalculatedMonth;
        Set @bfaclmh_loopCount = 0;

        
        -- Repeat
        -- util xxxx end repeat
        bfaclmh_minloop: While @bfaclmh_loopCount < 2 Do
            select @bfaclmh_loopCount;
            Set @AMO_BAL_DATE_DEFAULT = @bfaclmh_computedMonth; 


            Start transaction;
                --
--                 call BUSINESS_CALCULATE_MATCHING_CODE_STATE(@bfaclmh_idaccounts, null, null); -- pas util car pas de delettrage

				call BUSINESS_UPDATE_FIANA(@bfaclmh_idaccounts, null);
                call BUSINESS_UPDATE_FIANA_MEMBERS(Null);
				-- le dso RB est bassé les valeurs de FI_ANA_HISTO
				-- on dois populer FI_ANA_HISTO avec le DSO RB
				call BUSINESS_BACKUP_FIANA(@bfaclmh_idaccounts, 0);                
                call BUSINESS_BACKUP_FIANA_MEMBERS(Null, 0);

--                 if (FIANAHISTO_OPT_EXCLUDE_DSORB & @bifah_optionsmask) <> FIANAHISTO_OPT_EXCLUDE_DSORB Then
-- 					-- on ne dois pas exclure le calcul du DSO RB
-- 					Call BUSINESS_DSO_ROLLBACK(idaccounts, null, 1, @FIANAHISTO_OPT_MAX_DSO_VALUE);
-- 				End if;
            commit;


            Set @bfaclmh_loopCount = @bfaclmh_loopCount +1;
            Set @bfaclmh_computedMonth =  @bfaclmh_today;
-- 
        End While bfaclmh_minloop;

    end;





End $$
Delimiter ;
