Delimiter //
/**
 * Author:  armen
 * Created: 20 sept. 2017
 * purge et rempli la table LOADER_MATCHINGCODES_MATCHINGCODES_TOREMOVE
 * contentant la liste des lettrage à supprimer
 */
Drop Procedure if Exists LOADER_MATCHINGCODE_NORMALIZE_MAP_MATCHING_CODE_TO_REMOVE//
Create Procedure LOADER_MATCHINGCODE_NORMALIZE_MAP_MATCHING_CODE_TO_REMOVE (
    In batchnum int
	, In stdLetteringMode Int 
)
Begin
	lmcnmmctr_Main: Begin	
		Set @stdLetteringMode = Coalesce(stdLetteringMode, 0); 

-- 		Delete LOADER_MATCHINGCODES_MATCHINGCODES_TOREMOVE From  LOADER_MATCHINGCODES_MATCHINGCODES_TOREMOVE  ;

		if @stdLetteringMode = 0 then
			-- lettrage mode NON stadard (d'un point de vu comptable)
            -- mode de lettre historique et privilegié dans l'application
			-- pour retro-compataibilité
			-- on ne réutilise pas un code lettrage
			-- on le recréé systématiqueemnt
			Insert Into LOADER_MATCHINGCODES_MATCHINGCODES_TOREMOVE  (
					ID_MATCHCOD
			)
			Select distinct
				EhM.MATCHCOD_ID_MATCHCOD
			From
				LOADER_MATCHINGCODES LMC
				Inner Join LOADER_STATUS S
					On S.ID_LOADER_STATUS = LMC.LOADER_STATUS_ID_LOADER_STATUS
				Inner Join ENTRIES_MATCHCOD EhM
					On EhM.ENTRIES_ID_ENTRIES = LMC.ID_ENTRIES
                    And EhM.ENTRIES_MATCHCOD_CURRENT = 1
			Where 
				S.LOADER_STATUS_ERRCOUNT = 0
				And S.LOADER_STATUS_BATCH_NUM = batchnum
			;
-- 		Else
-- -- dans ce mode on ne doit jammias supprimer des lettrage car car le code lettrage est perssitance
-- -- , seul les ecriture sont ajouter ou supprimer du lettrage
-- 			-- lettrage STANDARD (d'un point de vu comptable)
-- 			-- si un code lettrage est re-fournis, on ajouté les ecritures aux lettrage existant
-- 			Insert Into LOADER_MATCHINGCODES_MATCHINGCODES_TOREMOVE  (
-- 					ID_MATCHCOD
-- 			)
-- 			Select distinct
-- 				EhM.MATCHCOD_ID_MATCHCOD
-- 			From
-- 				LOADER_MATCHINGCODES LMC
-- 				Inner Join LOADER_STATUS S
-- 					On S.ID_LOADER_STATUS = LMC.LOADER_STATUS_ID_LOADER_STATUS
-- 				Inner Join ENTRIES_MATCHCOD EhM
-- 					On EhM.ENTRIES_ID_ENTRIES = LMC.ID_ENTRIES
-- 			Where 
-- 				S.LOADER_STATUS_ERRCOUNT = 0
-- 				And (
-- 					LMC.MATCHINGCODES_ID_MATCHINGCODES Is Null
-- 					Or LMC.MATCHINGCODES_UNMATCH_FORCED = 1 
-- 				)
-- 				And S.LOADER_STATUS_BATCH_NUM = batchnum
-- 			;
		End if;
	End ;

End //
Delimiter ;

