Delimiter //
/**
 * - Le type Avoir est automatiquement transformé en facture lorsque le montant est au débit
 * 
 * DOIT être placé après LOADER_ENTRIES_MAP_NEGATIVE_AMOUNTS()
 * 
 * @ticket 3756
 */
Drop Procedure If Exists LOADER_ENTRIES_MAP_NEGATIVE_AMOUNTS_CRN_TO_INV//
Create Procedure LOADER_ENTRIES_MAP_NEGATIVE_AMOUNTS_CRN_TO_INV(
    In batchnum Int
)
Begin

    Set 
        @facture        = (Select ID_DF_ENTRIES_TYPE From DF_ENTRIES_TYPE Where DF_ENTRIES_TYPE_CODE = 'INV'), 
        @avoir          = (Select ID_DF_ENTRIES_TYPE From DF_ENTRIES_TYPE Where DF_ENTRIES_TYPE_CODE = 'CRN')
    ;
    Update
        LOADER_ENTRIES E
        Inner Join
            LOADER_STATUS S
            On S.ID_LOADER_STATUS = E.LOADER_STATUS_ID_LOADER_STATUS
    Set
--         -- Type
        DF_ENTR_TYPE_ID_DF_ENTR_TYPE = @facture
    Where 
        S.LOADER_STATUS_BATCH_NUM = batchnum
        And DF_ENTR_TYPE_ID_DF_ENTR_TYPE = @avoir 
        And (   
                Coalesce(ENTRIES_DEBIT, 0) > 0
                Or Coalesce(ENTRIES_ENT_DEBIT, 0) > 0
                Or Coalesce(ENTRIES_ADMIN_DEBIT, 0) > 0
            )
    ;
End//
Delimiter ;