function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lise-Marie DECLOUXLise-Marie DECLOUX 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TOKD_T13_Case_Before_Insert: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object

hi

i try to upload a package but get an error message. My developpeur is not here so i need help from anybody who could help me

This is the apex class:
global class TOKD_MessagingDevis implements Messaging.InboundEmailHandler {
    
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        
        Id idProcess=null;
        Boolean codeProjetChange;
        
        Case demandeLocale=null;
        Date dateFinProgrammee = null;
        
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        
        String myPlainText= '';
        
        /* Le mail envoyé par BaaN est renseigné sur htmlBody */        
        if(email.htmlBody!=null)
            myPlainText = email.htmlBody;
        else if(email.plainTextBody!=null)
            myPlainText = email.plainTextBody;
        
        List<String> infoMail = myPlainText.split(':');
        String caseNumber='';
        String nameFile=null;
        String dateFinProg = null;
        String codeProjetStr='';
        TOKD_Projet__c projet = new TOKD_Projet__c();
        
        if (infoMail!=null){
            if(infoMail[0]!=null){
                caseNumber=infoMail[0];
                caseNumber=caseNumber.trim();
            }
            if(infoMail[1]!=null){
                nameFile=infoMail[1];
                nameFile=nameFile.trim();
            }
            if(infoMail[2]!=null){
                if (!infoMail[2].equals('')) {
                    dateFinProg=infoMail[2].trim();
                    System.debug('-------dateFinProg : '+dateFinProg);
                    Integer day = Integer.valueOf(dateFinProg.substring(0,2));
                    Integer month = Integer.valueOf(dateFinProg.substring(3,5));
                    Integer year = Integer.valueOf(dateFinProg.substring(6,10));
                    dateFinProgrammee= date.newInstance(year, month, day);
                }
            }
            // Superieur à 4 car on compte 3 éléments + le postscriptum de la poste en 4ème
            if(infoMail[3]!=null){
                System.debug('@@@@@ CODE PROJET : ' + infoMail[3]);
                codeProjetStr=infoMail[3];
                codeProjetStr=codeProjetStr.trim();
                
                List<TOKD_Projet__c> listeprojet = [SELECT Id,Direction__c FROM TOKD_Projet__c WHERE Name = :codeProjetStr];
                
                if (listeprojet.size() != 0 ) {
                    projet = listeprojet.get(0);
                    result.success = true;   
                } else {
                    System.debug('-------Code Projet [' + codeProjetStr + '] Inconnu en base');
                    result.success = false;   
                }
            }
        }
        
        System.debug('-------caseNumber : '+caseNumber);
        System.debug('-------nameFile : '+nameFile);
        System.debug('-------dateFinProgrammee : '+dateFinProgrammee);
        System.debug('-------codeProjet : '+codeProjetStr);
        
        //récupération des informations sur la demande locale
        List<Case> listDemandeLocale=[Select Id,Status,CaseNumber,TOKD_Realisation__c,TOKD_Approbation_automatique__c,
                                      TOKD_Utilisateur_approbateur_demande__c,TOKD_DernierDevisId__c,
                                      TOKD_SLA_TypeDemande__c, TOKD_Code_projet_baan__c, TOKD_Date_Fin_Programmee__c, TOKD_Date_realisation_souhaitee__c,Preacceptation_du_devis__c,TOKD_LIN__c,ContactId,TOKD_ATM__c,TOKD_Direction__c,TOKD_ATM__r.Territoire__r.Directeur_territorial__c
                                      from Case where CaseNumber=:caseNumber];
        
        System.debug('@@@@@12' + listDemandeLocale.get(0));             
        if (listDemandeLocale.size()!=0){
            System.debug('Etape 0A');
            demandeLocale=listDemandeLocale.get(0);
            System.debug('Etape 0B : ' + result.success + ' ' + demandeLocale.CaseNumber);
        }
        System.debug('Etape 1');
        if(demandeLocale!=null && result.success == true){
            System.debug('Etape 2');
            System.debug('####################email = '+email);
            //pièce jointe           
            if (email.binaryAttachments != 
                null && email.binaryAttachments.size() > 0){
                    System.debug('####################PJ = ');
                    for (integer i = 0 ; i < email.binaryAttachments.size() ; i++){
                        //si le nom dans le texte du mail est vide on prend le nom du fichier du mail
                        if (nameFile==null || nameFile==''){
                            nameFile=email.binaryAttachments[i].filename;
                        }
                        
                        Attachment a = new Attachment(ParentId = demandeLocale.Id,
                                                      Name = '#'+nameFile,
                                                      Body = email.binaryAttachments[i].body);
                        insert a;
                        demandeLocale.TOKD_DernierDevisId__c=a.Id;
                    }
                }
            
            //pièce jointe ajoutée
            result.success = true;
            
            System.debug('-------demandeLocale.TOKD_Approbation_automatique__c:'+demandeLocale.TOKD_Approbation_automatique__c);
            
            //avenant 2 suppression de la gestion de la demande automatique, toute les demandes pass par la validation du client           
            
            
            //mise à jour last commentaire
            demandeLocale.TOKD_LastCaseCommentBody__c='Aucun commentaire';
            demandeLocale.TOKD_Date_Fin_Programmee__c = dateFinProgrammee;
            
            //Mantis 30871 : calcul de la date d'engagement 
            if (demandeLocale.Preacceptation_du_devis__c == true) {
                // Mantis 49384: empêcher le passage à Accepté Client suite réception d'un devis sur une demande en cours
                if (demandelocale.status !='En Cours') {
                    demandeLocale.status='Accepté Client';
                }
                demandeLocale.TOKD_DateValidation__c =system.now();          
                
            } else {
                // Mantis 49384: empêcher le passage à Validé DSEM suite réception d'un devis sur une demande en cours
                if (demandelocale.status !='En Cours') 
                {
                    demandeLocale.status='Validé DSEM';
                }
                
                // ## CGU - 2016/07/04 : Mise à jour de la date de validation à l'arrvée du devis pour les demandes en approbation automatique et devis manuel
                if (demandeLocale.TOKD_Approbation_automatique__c != 'Manuel'){
                    demandeLocale.TOKD_DateValidation__c = system.now();
                }
            }
            
            // ## CGU - 2016/12/26 : Calcul de la date d'engagement à réception du devis pour les demandes Territoire
            if(demandeLocale.TOKD_Realisation__c=='Territoire'){
                Case estime = TOKD_Case_Utils.calcule_DateEngagement(demandeLocale, demandeLocale.TOKD_DateValidation__c);
                demandeLocale.TOKD_Date_engagement_estimee__c = estime.TOKD_Date_engagement__c;
                demandeLocale.TOKD_Date_engagement__c = demandeLocale.TOKD_Date_engagement_estimee__c;
            }
            
            
            //Mantis 11144 : Changement du code Projet
            if (demandeLocale.TOKD_Code_projet_baan__c != projet.Id) {
                codeProjetChange = true;
                // Sauvegarde de l'ancien Code Projet
                demandeLocale.TOKD_Ancien_Code_Projet__c = demandeLocale.TOKD_Code_projet_baan__c;
                
                //Affectation du nouveau Code Projet
                demandeLocale.TOKD_Code_projet_baan__c = projet.Id;
                
                // Mise à jour de la direction
                demandeLocale.TOKD_Direction__c=projet.Direction__c;
                
            }
            
            update demandeLocale;
            
            // MANTIS 32622- ELE - 30/01/2014 - 
            //Gestion des partages sur la demande locale si le code projet à changé
            if (codeProjetChange == true) {
                //Gestion des partages sur la demande locale
                TOKD_Case_Utils.partagerDemandeLocale(demandeLocale, demandeLocale.TOKD_LIN__c == 'true');
            }
            
            if (demandeLocale.status=='Validé DSEM') {
                //soumission de la demande locale pour validation devis en utilisant le processus d'approbation Demande_locale_Valide_Dsem
                Approval.ProcessSubmitRequest validationDevis = new Approval.ProcessSubmitRequest();
                validationDevis.setComments('Demande d\'approbation sur le devis');
                validationDevis.setProcessDefinitionNameOrId('Demande_locale_Valide_Dsem');
                validationDevis.setObjectId(demandeLocale.id);
                try{
                Approval.ProcessResult validationDevisResult = Approval.process(validationDevis);
                }
                catch(DmlException e){
                    
                }
            }
            
        }else{
            //pièce jointe non ajoutée
            result.success = false;        
        }
        
        //pour ne pas envoyer de mail d'erreur 
        result.success = true;
        
        
        return result;
        
    }
    
    static testMethod void testTOKD_MessagingDevis() {
        
        
        
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        Messaging.InboundEmail.BinaryAttachment inAtt = new Messaging.InboundEmail.BinaryAttachment();
        
        Case sollicitation =new Case();
        sollicitation.Subject ='testsollicitation';
        sollicitation.Status ='Créé';
        insert sollicitation;
        System.debug('###########sollicitation='+sollicitation);
        Case demandeLocale= [select Id, CaseNumber from Case where Id=:sollicitation.Id LIMIT 1];
        
        email.subject = sollicitation.Id;
        email.plainTextBody=demandeLocale.CaseNumber+':NomFichier.pdf:28/04/2011:NIL000133:';
        System.debug('###########email.plainTextBody='+email.plainTextBody);
        env.fromAddress = 'user@acme.com';
        
        // set the body of the attachment
        inAtt.body = blob.valueOf('test2');
        inAtt.fileName = 'my attachment name';
        inAtt.mimeTypeSubType = 'plain/txt';
        
        email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] {inAtt }; 
            
            TOKD_MessagingDevis messagingDevis=new TOKD_MessagingDevis();
        messagingDevis.handleInboundEmail(email, env);
        
    }
    
    
    
}

 
Lise-Marie DECLOUXLise-Marie DECLOUX
This is the trigger:


trigger TOKD_T13_Case_Before_Insert on Case (before insert) {     system.debug('Start Trigger insert Case before : '+trigger.new);     List<TOKD_Type_de_demande__c> listTypeDemande = [select Id, SLA_Unite__c, SLA__c from TOKD_Type_de_demande__c];     Map<Id, TOKD_Type_de_demande__c> mapTypeDemande = new Map<Id, TOKD_Type_de_demande__c>();          for (TOKD_Type_de_demande__c typeDemande : listTypeDemande){         mapTypeDemande.put(typeDemande.Id, typeDemande);     }          for (Case caseTraitement : trigger.new)  {                  integer delai = 0;         double boucle = 1;         if (caseTraitement != null){             system.debug('idTypeDemande : '+caseTraitement.TOKD_Type_de_demande__c);                                      system.debug('UniteTypeDemande : '+mapTypeDemande.get(caseTraitement.TOKD_Type_de_demande__c).SLA_Unite__c);             try{                 if (mapTypeDemande.get(caseTraitement.TOKD_Type_de_demande__c).SLA_Unite__c == 'J'){                     boucle = mapTypeDemande.get(caseTraitement.TOKD_Type_de_demande__c).SLA__c+1;                 }                 else if (mapTypeDemande.get(caseTraitement.TOKD_Type_de_demande__c).SLA_Unite__c == 'H'){                     delai = Integer.valueOf(mapTypeDemande.get(caseTraitement.TOKD_Type_de_demande__c).SLA__c);                     boucle = 1;                 }             }             catch(Exception e){                 boucle = 1;                 delai = 0;             }         }          datetime date_realisation_souhaitee = System.now().date();         for (double i = 0; i < boucle; i++){             date_realisation_souhaitee = date_realisation_souhaitee.addHours(24);             if(date_realisation_souhaitee.format('u') == '6' || date_realisation_souhaitee.format('u') == '7'){                 boucle++;             }           }                      datetime date_debut_souhaitee = System.now().date();         for (double i = 0; i < 1; i++){             date_debut_souhaitee = date_debut_souhaitee.addHours(24);             if(date_debut_souhaitee.format('u') == '6' || date_debut_souhaitee.format('u') == '7'){                 i--;             }         }                  date_realisation_souhaitee = date_realisation_souhaitee.addHours(delai);         if(date_realisation_souhaitee.format('u') == '7'){             date_realisation_souhaitee = date_realisation_souhaitee.addHours(24);         }                      else if (date_realisation_souhaitee.format('u') == '6'){             date_realisation_souhaitee = date_realisation_souhaitee.addHours(48);         }                  system.debug('date_debut_souhaitee : '+date_debut_souhaitee);         system.debug('date_realisation_souhaitee : '+date_realisation_souhaitee);         caseTraitement.TOKD_Date_debut_souhaitee__c = date.valueOf(date_debut_souhaitee);         caseTraitement.TOKD_Date_realisation_souhaitee__c = date.valueOf(date_realisation_souhaitee);              } }

and the error i have:

Class Name: TOKD_MessagingDevis
Method Name: testTOKD_MessagingDevis
Error Message: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TOKD_T13_Case_Before_Insert: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.TOKD_T13_Case_Before_Insert: line 18, column 1: [] 
Stack Trace: Class.TOKD_MessagingDevis.testTOKD_MessagingDevis: line 207, column 1