• Silpi roy 16
  • NEWBIE
  • 30 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 16
    Questions
  • 29
    Replies
Please help me in updating the trigger code ,
Requirement is If the record is first created based on created date then set the checkbox as true.

trigger updateForecastMassUIpdateFields on ForecastSchedule__c (before insert, before update) {

for (ForecastSchedule__c fs:trigger.new)
    {
        /*List<Period> p=[SELECT Number , FiscalYearSettings.Name  FROM Period WHERE Type = 'Month' AND StartDate <=: fs.date__c AND EndDate >=: fs.date__c];   
    
        for(Period p1:p)
        {
            fs.fiscal_period__c=p1.number + '-' + p1.FiscalYearSettings.Name;
        }
        for ( Case c1 : [select id, name from case where id in (<ids>) ])

        {

        }*/
        if(fs.IsBudget__c==true || fs.SourceType__c=='4 - Budget')  
        {
            if(fs.Budget_Quantity__c==0 || fs.Budget_Quantity__c==null)
            {
                fs.Budget_Unit_Price__c=fs.UnitPrice__c;
                fs.Budget_Quantity__c=fs.Quantity__c;
                fs.Budget_Revenue__c=fs.Revenue__c;
                fs.Budget_Revenue_in_EUR__c=fs.RevenueInEUR__c;
            }
            else
            {
                fs.UnitPrice__c=fs.Budget_Unit_Price__c;
                fs.Quantity__c=fs.Budget_Quantity__c;
                //fs.Revenue__c=fs.Budget_Revenue__c;
                //fs.RevenueInEUR__c=fs.Budget_Revenue_in_EUR__c;
            }
         List<ForecastSchedule__c> FSList=[Select Id,Name,FC_quantity__c,FC_Revenue__c,FC_Unit_Price__c,ERPProductNr__c,Opportunity__c, Product2__c from ForecastSchedule__c order by CreatedDate asc LIMIT 1 ];
        if(FSList.size()>0){
        fs.isPrimary__c=True;
        }
        Update fs;
    }

}

Please help
There is custom obj and have a checkbox .
I want to sort the records based on Created date.
The checkbox should be checked for the record if created date is the oldest among the list of records.

 
Hi All,

I am trying to get the functionalty(What is the functionality for this batch class).Please someone help me understandig the below code

global class BatchCreateScheduleLineBySOItem implements Database.batchable<sObject>{

    global Database.QueryLocator start(Database.BatchableContext BC){
      List<User> users = [Select u.Id From User u where name=:ScheduleLineHelper.userIntegrationIservice];
      //return all SO Item that not yet have schedule line for all user execept user Integration i:service
      if(users.size()>0){
          String id=users.get(0).Id;
          return Database.getQueryLocator('select Id, Name, CurrencyIsoCode, Item_Qty__c, SalesOrderId__c, Confirmed_Delivery_Date__c,'+ 
            'RequestedDeliveryDate__c from SalesOrderItem__c where Id not in (select SalesItem__c from SalesItemDistribution__c) and CreatedById<>:id');
      }
      //return all SO Item that not yet have schedule line for all user
      return Database.getQueryLocator('select Id, Name, CurrencyIsoCode, Item_Qty__c, SalesOrderId__c, Confirmed_Delivery_Date__c,'+ 
            'RequestedDeliveryDate__c from SalesOrderItem__c where Id not in (select SalesItem__c from SalesItemDistribution__c)');
   }
   
   global void execute(Database.BatchableContext BC, List<sObject> scope){
        //create Schedule Line by all SO Item that not yet have Schedule Line 
        List<SalesItemDistribution__c> lstScl=new List<SalesItemDistribution__c>();
        for(Sobject so:scope){
            SalesOrderItem__c soitem=(SalesOrderItem__c)so;
            SalesItemDistribution__c sc=new SalesItemDistribution__c(Name=soitem.Name, CurrencyIsoCode=soitem.CurrencyIsoCode, 
                                        QuantityConfirmed__c=soitem.Item_Qty__c, SalesDoc__c=soitem.SalesOrderId__c, SalesItem__c=soitem.Id);
                                        
            sc.DateConfirmed__c=(soitem.Confirmed_Delivery_Date__c==null)?
                                soitem.RequestedDeliveryDate__c:soitem.Confirmed_Delivery_Date__c;
                                
            lstScl.add(sc);
            
        }
        insert lstScl;
    }

   global void finish(Database.BatchableContext BC){
   }
   
}

Thanks in Advance
 Cannot modify a collection while it is being iterated : Getting this error on this code please help and Too many SOQL Query for the below code.


trigger DeleteBillingItem on BillingItem__c (after insert) {
    set<Id> bID = new set<Id>();
    for(BillingItem__c bi:trigger.new){
       bID.add(bi.Id);
    }

    list<BillingItem__c>BItem = new list<BillingItem__c>();
    If(bID.isEmpty() == false){   
       BItem = [select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where Id IN: bID AND BillingDocumentId__c!=Null
                       and (UnitPrice__c=0 OR UnitPrice__c=null) AND  Sub_Segment__c='Undefined'];
    }

    for(BillingItem__c BI : BItem){
     System.debug('BI: '+BI);
       delete BI;
    }
Please advise
Hi All,

I am getting  error 101 for the below code(Too many SOQL query)

trigger DeleteBillingItem on BillingItem__c (after insert) {
    set<Id> bID = new set<Id>();
    for(BillingItem__c bi:trigger.new){
       bID.add(bi.Id);
    }

    list<BillingItem__c>BItem = new list<BillingItem__c>();
    If(bID.isEmpty() == false){   
       BItem = [select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where Id IN: bID AND BillingDocumentId__c!=Null
                       and (UnitPrice__c=0 OR UnitPrice__c=null) AND  Sub_Segment__c='Undefined'];
    }

    for(BillingItem__c BI : BItem){
     System.debug('BI: '+BI);
       delete BI;
    }

}

Please help!!

Thanks,
Silpi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
trigger Product_StatusChangeAlert on Product2 (after update) {
    if(Process_Exception__c.getInstance(Userinfo.getProfileId()).Run_Trigger__c){
        List<Product2> listStatusChanged = new List<Product2>();
        for (Product2 o : trigger.new) {
            if (o.Product_Status2__c != trigger.oldMap.get(o.ID).Product_Status2__c && ProductStatusChangeAlert__c.getInstance(o.Product_Status2__c) != null){
                listStatusChanged.add(o);
            }
        } 
        if (!listStatusChanged.isEmpty()) {
            ProductStatusChangeAlertController helper = new ProductStatusChangeAlertController(listStatusChanged);
            helper.sendEmailsToOpportunityOwners();
        }
    }
}
Test Class

@isTest
public class ProductStatusChangeAlertControllerTest {
 @isTest static void Product2StatusChangedTest() {
    // Insert "Process_Exception__c" related record with "System Administrator" profile
    Process_Exception__c procExcpRec = new Process_Exception__c(Name = 'Process Exception (Profile)',Run_Trigger__c = true, SetupOwnerId = '00e0Y0000015jIAQAY');
    insert procExcpRec;
    ProductStatusChangeAlert__c prodStaChaAlRec = new ProductStatusChangeAlert__c(Name = 'End of Life');
     insert prodStaChaAlRec;
    Product2 prd = new Product2(Name='Test Product', IsActive=true, MSTAV__c = '80');
    insert prd;

    Id stdPbId = Test.getStandardPricebookId();

    PricebookEntry objPBE = new PricebookEntry(Product2Id=prd.Id, Pricebook2Id=stdPbId, UnitPrice=100, IsActive=true);
    insert objPBE;
    List<Opportunity> tobeInsertedOpptyList = new List<Opportunity>();
    Opportunity objOpp = new Opportunity(Name = 'Testopp', CloseDate = date.today().addDays(100), StageName = 'Prospecting');
    tobeInsertedOpptyList.add(objOpp);
    Opportunity objOpp2 = new Opportunity(Name = 'Testopp2', CloseDate = date.today().addDays(100), StageName = 'Prospecting');
    tobeInsertedOpptyList.add(objOpp2);
    insert tobeInsertedOpptyList;
     
    OpportunityLineItem objOLI = new OpportunityLineItem(PricebookEntryID = objPBE.Id, Quantity = 1, UnitPrice = 100, OpportunityId = objOpp.Id);
    insert objOLI;
    OpportunityLineItem objOLI2 = new OpportunityLineItem(PricebookEntryID = objPBE.Id, Quantity = 1, UnitPrice = 100, OpportunityId = objOpp2.Id);
    insert objOLI2;
     
    Product2 objProduct = [select Id, Product_Status2__c,MSTAV__c from Product2 where Id = :objPBE.Product2Id];

    objProduct.MSTAV__c  = '80';
    update objProduct;
    Product2 objProduct2 = [select Id, Product_Status2__c,MSTAV__c from Product2 where Id = :objPBE.Product2Id];
    System.assertEquals('End of Life',objProduct2.Product_Status2__c );
  }
}

Please advise very urgent
I have written the below code trigger and test class but getting error in deployment as 0%test coverage.
rigger Product_StatusChangeAlert on Product2 (after update) {
    if(Process_Exception__c.getInstance(Userinfo.getProfileId()).Run_Trigger__c){
        List<Product2> listStatusChanged = new List<Product2>();
        for (Product2 o : trigger.new) {
            if (o.Product_Status2__c != trigger.oldMap.get(o.ID).Product_Status2__c && ProductStatusChangeAlert__c.getInstance(o.Product_Status2__c) != null){
                listStatusChanged.add(o);
            }
        } 
        if (!listStatusChanged.isEmpty()) {
            ProductStatusChangeAlertController helper = new ProductStatusChangeAlertController(listStatusChanged);
            helper.sendEmailsToOpportunityOwners();
        }
    }

Test Class:
@isTest
public class ProductStatusChangeAlertControllerTest {
 @isTest static void Product2StatusChangedTest() {
    // Insert "Process_Exception__c" related record with "System Administrator" profile
    Process_Exception__c procExcpRec = new Process_Exception__c(Name = 'Process Exception (Profile)',Run_Trigger__c = true, SetupOwnerId = '00e0Y0000015jIAQAY');
    insert procExcpRec;
    ProductStatusChangeAlert__c prodStaChaAlRec = new ProductStatusChangeAlert__c(Name = 'End of Life');
     insert prodStaChaAlRec;
    Product2 prd = new Product2(Name='Test Product', IsActive=true, MSTAV__c = '80');
    insert prd;

    Id stdPbId = Test.getStandardPricebookId();

    PricebookEntry objPBE = new PricebookEntry(Product2Id=prd.Id, Pricebook2Id=stdPbId, UnitPrice=100, IsActive=true);
    insert objPBE;
    List<Opportunity> tobeInsertedOpptyList = new List<Opportunity>();
    Opportunity objOpp = new Opportunity(Name = 'Testopp', CloseDate = date.today().addDays(100), StageName = 'Prospecting');
    tobeInsertedOpptyList.add(objOpp);
    Opportunity objOpp2 = new Opportunity(Name = 'Testopp2', CloseDate = date.today().addDays(100), StageName = 'Prospecting');
    tobeInsertedOpptyList.add(objOpp2);
    insert tobeInsertedOpptyList;
     
    OpportunityLineItem objOLI = new OpportunityLineItem(PricebookEntryID = objPBE.Id, Quantity = 1, UnitPrice = 100, OpportunityId = objOpp.Id);
    insert objOLI;
    OpportunityLineItem objOLI2 = new OpportunityLineItem(PricebookEntryID = objPBE.Id, Quantity = 1, UnitPrice = 100, OpportunityId = objOpp2.Id);
    insert objOLI2;
     
    Product2 objProduct = [select Id, Product_Status2__c,MSTAV__c from Product2 where Id = :objPBE.Product2Id];

    objProduct.MSTAV__c  = '80';
    update objProduct;
  }

Please advise.

Thanks,
​Silpi
I have a requirement:
When the Billing Item with Unit price=0 and Subsegment=Undefined I need to delete the data.
I have written the below code and Process Builder to handle the same but its not working as expected.
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds and BillingDocumentId__c!=Null
                       and (UnitPrice__c=0 OR UnitPrice__c=null) and  Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
       
        delete BI;
       
      
        }
}
ProcessBuilder:
If criteria meets calling the apex class.

Please suggest any other workaround
Hi All,
I want to check if Unit price has Null value or Unit price = 0 then I want to delete the Billing Item.
For that I have written the below code but getting error
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds and BillingDocumentId__c!=Null
                       and UnitPrice__c=0 || IsNull(UnitPrice__c)=True and  Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
       
        delete BI;

        }
}
Error:Missing ']' at '||' at line 8 column 43
Hi

My scenario is :
Billing Document:Parent
Billing Item:Child
I need a detion trigger to delete Billing Item with Unit Price=0/Blank and Subsegment=Undefined.

Note:Billing document can also be created from SAP.So if any Billing Item with above mentioed criteria is there it should also get deleted
Thanks!!
Could anyone give me some idea on scheduling the CLI dataloader
I have written the following code in sandbox which is showing 100% test coverage .
But during deployment it is showing the following error:
System.AssertException: Assertion Failed: Expected: false, Actual: true 
Stack Trace: Class.DeleteBillingItemsTest.DeleteBillingItemsTest: line 37, column 1.
Code is as follows:
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds and BillingDocumentId__c!=Null
                       and UnitPrice__c=0 and Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
        delete BI;
        }
}

@isTest
Public class DeleteBillingItemsTest{
Static testMethod void DeleteBillingItemsTest(){
Account acc=new Account();
acc.Name='Test';
insert acc;

 Product2 Pd1=new Product2();
   Pd1.Name='Pd01';
   Pd1.Production_Location__c='SMT-TH';
   Pd1.SAP_Product_Nr__c='123';
  Pd1.Module_Source__c='bought';
   insert pd1;
        
 BillingDoc__c BD1=new BillingDoc__c();
            BD1.DocumentType__c='Test01';
            BD1.Name='001';
            BD1.Production_Location__c='SMT-TH';
            BD1.DocumentTypeCode__c='ZOR';
            BD1.DocumentDate__c=System.Today();
            BD1.FacturaDate__c=System.Today();
        insert BD1;

BillingItem__c BI= new BillingItem__c();
BI.Name='Test';
BI.Quantity__c=100;
BI.Units__c='PCE';
BI.UnitPrice__c= 500;
BI.Product2__c=PD1.id;
BI.BillingDocumentId__c=BD1.ID;


insert BI;
BI.UnitPrice__c= 0;
Update BI; 
BillingItem__c deletedBI = [SELECT Id, IsDeleted FROM BillingItem__c WHERE Id = :BI.Id ALL ROWS];
System.assertEquals(deletedBI.IsDeleted, true);



}

}
Hi All I am trying to use the below code to delete the Billing Item.
Billing item is having a Master-detail with BillDoc.and also a rollup is there in Billing Doc.
I have written the following code.It is working where we have single Billing Item.but when there are Billing Item with valuesand 
Subsegment!=Undefined .It is not working .
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds
                       and UnitPrice__c=0 and Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
        delete BI;
        }
}

Please suggest.

Thanks
Hi All ,
Getting assertion Failure for the below test class.
@isTest
Private class updateQtyTest{
    Static testMethod void UpdateQty(){
    
     Product2 Pd1=new Product2();
        Pd1.Name='Pd01';
        Pd1.Production_Location__c='SMT-TH';
        Pd1.SAP_Product_Nr__c='123';
        Pd1.Module_Source__c='bought';
        insert pd1;
        
        BillingDoc__c BD1=new BillingDoc__c();
            BD1.DocumentType__c='Test01';
            BD1.Name='001';
            BD1.Production_Location__c='SMT-TH';
            BD1.DocumentTypeCode__c='ZOR';
            BD1.DocumentDate__c=System.Today();
            BD1.FacturaDate__c=System.Today();
        insert BD1;

        
        BillingItem__c BI1= new BillingItem__c();
            BI1.Name='Sales Strategy Manager';
            BI1.ItemNo__c= '001';
            BI1.Quantity__c=23456;
            BI1.Units__c='PCE';
            BI1.UnitPrice__c=1000;
            BI1.PriceUnit__c=1;
            BI1.BillingDocumentId__c=BD1.ID;
            BI1.Product2__c=Pd1.ID;
            insert BI1;
       Test.startTest();
      BD1.DocumentTypeCode__c = 'ZR2';
      update BD1;
      
      test.stopTest();
      // Now check if it is giving desired results using system.assert
      // Total Quantity in Billing Document should be 0.
      List<BillingItem__c> BIList=[Select Name,Quantity__c,BillingDocumentId__c from BillingItem__c where id=:BI1.Id];
      System.assertEquals(0, BI1.Quantity__c);
      

}
}

Please Advise.

Thanks,
Silpi
Hi All,

With thebelow code i am trying to update Billing Item Qty=0 ,Based on Document Type in Billing document in salsforce .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
trigger UpdateQty on BillingDoc__c (after insert,after update) {
Set<id> setOfParentId = new Set<Id>();
for(BillingDoc__c BD:trigger.new){
List<BillingItem__c> listBI=new List<BillingItem__c>([Select Id,BillingDocumentId__c,Quantity__c from BillingItem__c where BillingDocumentId__c in: setOfParentId]);

if ( listBI.size() > 0 )
  for(BillingItem__c BI : listBI){
   if(BD.DocumentTypeCode__c=='ZG2')
   {
   BI.Quantity__c = 0;
   }
   listBI.add(BI);
  }
 }
 

}

But it is not updating the Quatity=0.

please suggest me if it need some updation.

Thanks,
Silpi
Hi All!

Hope everyone is doing well.
Please help me denugging the following code.
public class ForecaseScheduleDuplicateController {
    
    public static void beforeFSController(list<ForecastSchedule__c> vlstFS)
    {
        set<string> vsetAccs = new set<string>();
        set<string> vsetOpps = new set<string>();
        set<string> vsetProds = new set<string>();
        set<string> vsetStype = new set<string>();
        set<string> vsetSegment = new set<string>();
        set<string> vsetSubSegment = new set<string>();
        set<string> vsetSalesLocation = new set<string>();
        set<date> vsetDate = new set<date>();
        for(ForecastSchedule__c fdn : vlstFS)
        {
            vsetaccs.add(fdn.Account__c);
            vsetOpps.add(fdn.Opportunity__c);
            vsetProds.add(fdn.Product2__c);
            vsetStype.add(fdn.SourceType__c);
            vsetDate.add(fdn.Date__c);
            vsetSegment.add(fdn.Segment__c);
            vsetSubSegment.add(fdn.SubSegment__c);
            vsetSalesLocation.add(fdn.SalesLocation__c);
        }
        list<ForecastSchedule__c> vlstFSinsert = new list<ForecastSchedule__c>();
        map<string,ForecastSchedule__c> vmapunikeys = new  map<string,ForecastSchedule__c>();
        for(ForecastSchedule__c fsnew : [select id,name,Opportunity__c,OpportunityOwnerFormula__c,Product2__c,Account__c,Date__c,SourceType__c,Segment__c,SalesLocation__c,SubSegment__c from ForecastSchedule__c 
                                         where 
                                         Opportunity__c IN :vsetOpps 
                                         and Product2__c IN : vsetProds
                                         and Account__c IN : vsetaccs
                                         and Date__c IN : vsetDate
                                         and SourceType__c IN : vsetStype
                                         and SubSegment__c IN :vsetSubSegment
                                         and Segment__c IN : vsetSegment
                                         and SalesLocation__c IN :vsetSalesLocation ])
        {
            system.debug('forecastschedule========'+fsnew);
            if(fsnew.SourceType__c == '4 - Budget' || fsnew.SourceType__c == '1 - Forecast')
            {
                string uniqrec = string.valueof(fsnew.Opportunity__c) + string.valueof(fsnew.Product2__c) + string.valueof(fsnew.Account__c) + string.valueof(fsnew.Date__c) + string.valueof(fsnew.SourceType__c) + string.valueof(fsnew.SalesLocation__c) + string.valueof(fsnew.Segment__c) + string.valueof(fsnew.SubSegment__c);
                
                vmapunikeys.put(uniqrec, fsnew);
            }
        }
        system.debug('keys========'+vmapunikeys.keyset());
        system.debug('values========'+vmapunikeys.values());
        for(ForecastSchedule__c fs : vlstFS)
        {
            if(fs.SourceType__c == '4 - Budget' || fs.SourceType__c == '1 - Forecast')
            {
                string uniqrec = string.valueof(fs.Opportunity__c) + string.valueof(fs.Product2__c) + string.valueof(fs.Account__c) + string.valueof(fs.Date__c) + string.valueof(fs.SourceType__c + string.valueof(fs.SalesLocation__c) + string.valueof(fs.Segment__c) + string.valueof(fs.SubSegment__c));
                
                ForecastSchedule__c fsold = vmapunikeys.get(uniqrec);
               
                 string duplicrec;
                if(fsold != null)
                 duplicrec = string.valueof(fsold.Opportunity__c) + string.valueof(fsold.Product2__c) + string.valueof(fsold.Account__c) + string.valueof(fsold.Date__c) + string.valueof(fsold.SourceType__c) + string.valueof(fsold.SalesLocation__c) + string.valueof(fsold.Segment__c) + string.valueof(fsold.SubSegment__c);
                
                system.debug('uniqrec ========'+uniqrec);
                if(uniqrec != duplicrec)
                {
                    vlstFSinsert.add(fs);
                    system.debug('vlstFSinsert========'+vlstFSinsert);
                }
                else
                {
                    
                    system.debug('entering else condition========');
                    //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Duplicate record found');
                    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                    opportunity opp = [select id,ownerid,owner.email from opportunity where id=:fsold.Opportunity__c limit 1];
                    
                     SendEmail(opp.id);
                     fs.adderror('Duplicate record found record' +  + fsold.Name + +'already having the same values');
                  }
            }
            
            
        }
        
        
    }
    @future
    public static void SendEmail(id oppid)
    {
      
               
                    system.debug('entering else condition========');
                    //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Duplicate record found');
                    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                    opportunity opp = [select id,ownerid,owner.email , owner.name from opportunity where id=:oppid limit 1];
                    Messaging.SingleEmailMessage mail = 
                        new Messaging.SingleEmailMessage();
                    list<string> tomails = new list<string>();
                    tomails.add(opp.owner.email);
                     tomails.add('chandraiah.cherukuru@atos.net');
                    system.debug('tomails====='+tomails);
                     mail.setToAddresses(tomails);
                    string body = 'Hi '+ opp.owner.name;
                    body += 'There is a record already exist with the above information';
                    body += 'we are not processing your request.<br/>';
                    body += 'Thanks,<br/>';
                    body += 'Support Team';
                    mail.setSubject('Duplicate Record');
                   
                    mail.setTargetObjectId(opp.ownerid); 
                    mail.setSaveAsActivity(false);
                    mail.setHtmlBody(body); 
                    mails.add(mail);
                    system.debug('before sending===='+mails);
                    try
                    {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                     system.debug('After sending===='+ Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }));
                    }
                    catch(DMLexception e)
                    {
                       system.debug('error======'+e.getStackTraceString()); 
                    }
                
            
    }
    public static void beforeFSControllerUpdate(list<ForecastSchedule__c> vlstFS,Map<id,ForecastSchedule__c> vmapold)
    {
        set<string> vsetAccs = new set<string>();
        set<string> vsetOpps = new set<string>();
        set<string> vsetProds = new set<string>();
         set<string> vsetStype = new set<string>();
        set<date> vsetDate = new set<date>();
          set<string> vsetSegment = new set<string>();
        set<string> vsetSubSegment = new set<string>();
        set<string> vsetSalesLocation = new set<string>();
        
        for(ForecastSchedule__c fdn : vlstFS /*vmapold.values()*/)
        {
            vsetaccs.add(fdn.Account__c);
            vsetOpps.add(fdn.Opportunity__c);
            vsetProds.add(fdn.Product2__c);
            vsetStype.add(fdn.SourceType__c);
            vsetDate.add(fdn.Date__c);
            vsetSegment.add(fdn.Segment__c);
            vsetSubSegment.add(fdn.SubSegment__c);
            vsetSalesLocation.add(fdn.SalesLocation__c);
            
        }
       
        list<ForecastSchedule__c> vlstFSinsert = new list<ForecastSchedule__c>();
        map<string,ForecastSchedule__c> vmapunikeys = new  map<string,ForecastSchedule__c>();
        for(ForecastSchedule__c fsnew : [select id,name,Opportunity__c,OpportunityOwnerFormula__c,Product2__c,Account__c,SalesLocation__c,Segment__c,Date__c,SubSegment__c,SourceType__c from ForecastSchedule__c 
                                          where Opportunity__c IN :vsetOpps 
                                         and Product2__c IN : vsetProds
                                         and Account__c IN : vsetaccs
                                         and Date__c IN : vsetDate
                                         and SourceType__c IN : vsetStype
                                         and SubSegment__c IN :vsetSubSegment
                                         and Segment__c IN : vsetSegment
                                         and SalesLocation__c IN :vsetSalesLocation ])
        {
            system.debug('forecastschedule========'+fsnew);
            if(fsnew.SourceType__c == '4 - Budget' || fsnew.SourceType__c == '1 - Forecast')
            {
                string uniqrec = string.valueof(fsnew.Opportunity__c) + string.valueof(fsnew.Product2__c) + string.valueof(fsnew.Account__c) + string.valueof(fsnew.Date__c) + string.valueof(fsnew.SourceType__c) + string.valueof(fsnew.SalesLocation__c) + string.valueof(fsnew.Segment__c) + string.valueof(fsnew.SubSegment__c);

                vmapunikeys.put(uniqrec, fsnew);
            }
        }
        system.debug('keys========'+vmapunikeys.keyset());
        system.debug('values========'+vmapunikeys.values());
        for(ForecastSchedule__c fs : vlstFS)
        {
            if(fs.SourceType__c == '4 - Budget' || fs.SourceType__c == '1 - Forecast')
            {
               // string uniqrec = string.valueof(fs.Opportunity__c) + string.valueof(fs.Product2__c) + string.valueof(fs.Account__c) + string.valueof(fs.Date__c) + string.valueof(fs.SourceType__c);
                string uniqrec = string.valueof(fs.Opportunity__c) + string.valueof(fs.Product2__c) + string.valueof(fs.Account__c) + string.valueof(fs.Date__c) + string.valueof(fs.SourceType__c) + string.valueof(fs.SalesLocation__c) + string.valueof(fs.Segment__c) + string.valueof(fs.SubSegment__c);

                
                system.debug('uniqrec========'+uniqrec);
               ForecastSchedule__c fsold = vmapold.get(fs.id);
                 string duplicrec;
                string duplicrec1;
              //  
                  ForecastSchedule__c fsold1 = vmapunikeys.get(uniqrec);
                if(fsold1 != null)
                
                   duplicrec1 = string.valueof(fsold1.Opportunity__c) + string.valueof(fsold1.Product2__c) + string.valueof(fsold1.Account__c) + String.valueof(fsold1.Date__c) +string.valueof(fsold1.SourceType__c) + string.valueof(fsold.SalesLocation__c) + string.valueof(fsold.Segment__c) + string.valueof(fsold.SubSegment__c);

                if(fsold != null)
                 duplicrec = string.valueof(fsold.Opportunity__c) + string.valueof(fsold.Product2__c) + string.valueof(fsold.Account__c) + String.valueof(fsold.Date__c) +string.valueof(fsold.SourceType__c) + string.valueof(fsold.SalesLocation__c) + string.valueof(fsold.Segment__c) + string.valueof(fsold.SubSegment__c);
                system.debug('duplicrec========'+duplicrec);
                system.debug('duplicrec1 ========'+duplicrec1);
                if((uniqrec == duplicrec &&  uniqrec != duplicrec1) || (uniqrec != duplicrec &&  uniqrec == duplicrec1))
                {
                       fs.adderror('Duplicate record found record' +  + fsold.Name + +'already having the same values');  
                    
                   
                }
            }
            
            
        }
        
        
    }
   }

Thanks,
Silpi
Please help me in updating the trigger code ,
Requirement is If the record is first created based on created date then set the checkbox as true.

trigger updateForecastMassUIpdateFields on ForecastSchedule__c (before insert, before update) {

for (ForecastSchedule__c fs:trigger.new)
    {
        /*List<Period> p=[SELECT Number , FiscalYearSettings.Name  FROM Period WHERE Type = 'Month' AND StartDate <=: fs.date__c AND EndDate >=: fs.date__c];   
    
        for(Period p1:p)
        {
            fs.fiscal_period__c=p1.number + '-' + p1.FiscalYearSettings.Name;
        }
        for ( Case c1 : [select id, name from case where id in (<ids>) ])

        {

        }*/
        if(fs.IsBudget__c==true || fs.SourceType__c=='4 - Budget')  
        {
            if(fs.Budget_Quantity__c==0 || fs.Budget_Quantity__c==null)
            {
                fs.Budget_Unit_Price__c=fs.UnitPrice__c;
                fs.Budget_Quantity__c=fs.Quantity__c;
                fs.Budget_Revenue__c=fs.Revenue__c;
                fs.Budget_Revenue_in_EUR__c=fs.RevenueInEUR__c;
            }
            else
            {
                fs.UnitPrice__c=fs.Budget_Unit_Price__c;
                fs.Quantity__c=fs.Budget_Quantity__c;
                //fs.Revenue__c=fs.Budget_Revenue__c;
                //fs.RevenueInEUR__c=fs.Budget_Revenue_in_EUR__c;
            }
         List<ForecastSchedule__c> FSList=[Select Id,Name,FC_quantity__c,FC_Revenue__c,FC_Unit_Price__c,ERPProductNr__c,Opportunity__c, Product2__c from ForecastSchedule__c order by CreatedDate asc LIMIT 1 ];
        if(FSList.size()>0){
        fs.isPrimary__c=True;
        }
        Update fs;
    }

}

Please help
Hi,

I am getting below error when updating accounts
"
axgen`20181102210502.798`4LCdyAGRZvCkt7nRp0uvX-`77456`0`0`0`````36ac5e486dafb48b`0```P-`216.11.2```00DE0000000PVJs`00544000008qVwX`684882`175186``````27.0`ApexLimitExceeded:00DE0000000PVJs:ACTIVE(db=ACTIVE,api=Active):System.LimitException: Too many SOQL queries: 101 "

Could you please anyone suggest me.

Thank you,
Prasad
 Cannot modify a collection while it is being iterated : Getting this error on this code please help and Too many SOQL Query for the below code.


trigger DeleteBillingItem on BillingItem__c (after insert) {
    set<Id> bID = new set<Id>();
    for(BillingItem__c bi:trigger.new){
       bID.add(bi.Id);
    }

    list<BillingItem__c>BItem = new list<BillingItem__c>();
    If(bID.isEmpty() == false){   
       BItem = [select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where Id IN: bID AND BillingDocumentId__c!=Null
                       and (UnitPrice__c=0 OR UnitPrice__c=null) AND  Sub_Segment__c='Undefined'];
    }

    for(BillingItem__c BI : BItem){
     System.debug('BI: '+BI);
       delete BI;
    }
Please advise
Hi All,

I am getting  error 101 for the below code(Too many SOQL query)

trigger DeleteBillingItem on BillingItem__c (after insert) {
    set<Id> bID = new set<Id>();
    for(BillingItem__c bi:trigger.new){
       bID.add(bi.Id);
    }

    list<BillingItem__c>BItem = new list<BillingItem__c>();
    If(bID.isEmpty() == false){   
       BItem = [select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where Id IN: bID AND BillingDocumentId__c!=Null
                       and (UnitPrice__c=0 OR UnitPrice__c=null) AND  Sub_Segment__c='Undefined'];
    }

    for(BillingItem__c BI : BItem){
     System.debug('BI: '+BI);
       delete BI;
    }

}

Please help!!

Thanks,
Silpi
I have a requirement:
When the Billing Item with Unit price=0 and Subsegment=Undefined I need to delete the data.
I have written the below code and Process Builder to handle the same but its not working as expected.
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds and BillingDocumentId__c!=Null
                       and (UnitPrice__c=0 OR UnitPrice__c=null) and  Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
       
        delete BI;
       
      
        }
}
ProcessBuilder:
If criteria meets calling the apex class.

Please suggest any other workaround
Hi All,
I want to check if Unit price has Null value or Unit price = 0 then I want to delete the Billing Item.
For that I have written the below code but getting error
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds and BillingDocumentId__c!=Null
                       and UnitPrice__c=0 || IsNull(UnitPrice__c)=True and  Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
       
        delete BI;

        }
}
Error:Missing ']' at '||' at line 8 column 43
Hi

My scenario is :
Billing Document:Parent
Billing Item:Child
I need a detion trigger to delete Billing Item with Unit Price=0/Blank and Subsegment=Undefined.

Note:Billing document can also be created from SAP.So if any Billing Item with above mentioed criteria is there it should also get deleted
Thanks!!
Could anyone give me some idea on scheduling the CLI dataloader
I have written the following code in sandbox which is showing 100% test coverage .
But during deployment it is showing the following error:
System.AssertException: Assertion Failed: Expected: false, Actual: true 
Stack Trace: Class.DeleteBillingItemsTest.DeleteBillingItemsTest: line 37, column 1.
Code is as follows:
public class DeleteBillingItems
{
    @InvocableMethod
    public static void BIDelete(List<Id> BIIds)
    {
        List<BillingItem__c> BI =[select id,BillingDocumentId__c,UnitPrice__c,Sub_Segment__c,Gross__c,NettoAmount2__c from BillingItem__c
                          where BillingItem__c.id in :BIIds and BillingDocumentId__c!=Null
                       and UnitPrice__c=0 and Sub_Segment__c='Undefined' and Gross__c=0 and NettoAmount2__c =0 ];
        delete BI;
        }
}

@isTest
Public class DeleteBillingItemsTest{
Static testMethod void DeleteBillingItemsTest(){
Account acc=new Account();
acc.Name='Test';
insert acc;

 Product2 Pd1=new Product2();
   Pd1.Name='Pd01';
   Pd1.Production_Location__c='SMT-TH';
   Pd1.SAP_Product_Nr__c='123';
  Pd1.Module_Source__c='bought';
   insert pd1;
        
 BillingDoc__c BD1=new BillingDoc__c();
            BD1.DocumentType__c='Test01';
            BD1.Name='001';
            BD1.Production_Location__c='SMT-TH';
            BD1.DocumentTypeCode__c='ZOR';
            BD1.DocumentDate__c=System.Today();
            BD1.FacturaDate__c=System.Today();
        insert BD1;

BillingItem__c BI= new BillingItem__c();
BI.Name='Test';
BI.Quantity__c=100;
BI.Units__c='PCE';
BI.UnitPrice__c= 500;
BI.Product2__c=PD1.id;
BI.BillingDocumentId__c=BD1.ID;


insert BI;
BI.UnitPrice__c= 0;
Update BI; 
BillingItem__c deletedBI = [SELECT Id, IsDeleted FROM BillingItem__c WHERE Id = :BI.Id ALL ROWS];
System.assertEquals(deletedBI.IsDeleted, true);



}

}