Once Case is created with updated fields, The updated fields should be updated in Account - apex

trigger Ecare_Trg_UpdateContCoreData on Case (after update) {
List<AccountContactRelation> arcList = New List<AccountContactRelation>();
for(Case c: Trigger.New)
{
if(c.Status =='Closed' && c.Type == 'Commercial' && c.vlocity_cmt__Reason__c =='Change Request' && c.Description == 'Haupaddressdurang')
{
AccountContactRelation ct = [SELECT ContactId,AccountId From AccountContactRelation Where AccountId =: c.AccountId];
ct.Contact.FirstName = c.First_Name__c;
ct.Contact.LastName = c.Last_Name__c;
ct.Contact.Salutation = c.Salutation__c;
ct.Account.BillingCity = c.City__c;
ct.Account.BillingPostalCode = String.ValueOf(c.Postal_Code__c);
ct.Account.BillingStreet = c.Street__c;
arcList.add(ct);
System.debug(c.AccountId);
}
}
if(arcList.size()>0){
upsert arcList;
}
}
I need to update the update case details in Account By this trigger i am not able update how we can do it?

Related

start_time__c field of custom object is not working in trigger i don't no what to do?

I have to do this:-
If an attendee has registered to parallel sessions (Sessions happening at the same time/overlapping sessions), then a checkbox (Registered_To_Parallel_Sessions__c) on the Attendee(Lead) object must be checked automatically.
This is my trigger:-
trigger RegisteredToParallelSession on Session_Attendee__c (after insert,before insert) {
list<session_attendee__C> sa2 = [select attendee__c, session__c, session__r.id,session__r.name, session__r.Start_Time__c from Session_attendee__c];
list<lead> l = [select id, Registered_To_Parallel_Session__c from lead];
list<session__c> s = [select id, start_time__c from session__c];
for(session_attendee__c sa4 : trigger.new){
for(session__c s2 : s){
for(lead l1 : l){
if(l1.Id == sa4.Attendee__c && s2.id == sa4.session__c && s2.Start_Time__c == sa4.session__r.Start_Time__c ) // this condition is not working
{
l1.Registered_To_Parallel_Session__c = true;
update l1;
}
}
}
}
}
This if(sa4.session__c && s2.Start_Time__c == sa4.session__r.Start_Time__c ) condition in above code is not working
please help & Thanks!

Create a cycle in T-SQL from the list

I have code written in C#, but I want to create a T-SQL script to run on the server. This is part of my C# code that I want to convert to T-SQL:
var enumerator = distinctlist.GetEnumerator();
while (enumerator.MoveNext())
{
mtbn dtb = enumerator.Current as mtbn;
var user = users.Where(x => x.Name == dtb.UserNameTb).FirstOrDefault();
var action = actions.Where(x => x.Name == dtb.ActionTb.Value.ToString()).FirstOrDefault();
var project = projects.Where(x => x.Name == dtb.ProjectNameTb).FirstOrDefault();
var transaction = transactions.Where(x => x.Name == dtb.TransactioNameTb).FirstOrDefault();
TransactBoard transactBoard = dbContext.TransactBoard.Add(new TransactBoard
{
User = user != null ? user : new EF.User { Name = dtb.UserNameTb },
Action = action != null ? action : new EF.Action { Name = dtb.ActionTb.Value.ToString() },
Project = project != null ? project : new Project { Name = dtb.ProjectNameTb, Path = #"S:\\xxxx\\" + dtb.ProjectNameTb },
Transaction = transaction != null ? transaction : new Transaction { Name = dtb.TransactioNameTb },
DateTime = dtb.WriteDateTimeTb.Value
});
dbContext.MonitorControl.Add(
new MonitorControl
{
ElementId = dtb.ElementIdTb.Value,
Category = category.Where(x => x.Id == dtb.CategoryIdTb).FirstOrDefault(),
TransactBoard = transactBoard
});
}
This is what I did on T-SQL:
begin tran
insert dbo.TransactionBoard(TrancationId, UserId, ActionId, ProjectId, [DateTime] )
select t.Id as TrancationId, u.Id as UserId, s.ActionTb, p.Id as ProjectId, s.WriteDateTimeTb
from monitorControlDb.dbo.MonitorlControlTable s
left join dbo.[Transaction] t
on t.[Name] = s.TransactioNameTb
left join dbo.[User] u
on u.[Name] = s.UserNameTb
left join dbo.Project p
on p.[Name] = s.ProjectNameTb
insert dbo.MonitorControl(ElementId, CategoryId)
select s.ElementIdTb, s.CategoryIdTb
from monitorControlDb.dbo.MonitorlControlTable s
commit

Test coverage for test class of trigger is showing 53 constantly

I am new to salesforce development.I have written test class for following trigger, which is having coverage as 53 only. I tried several times by adding and changing code lines into test class but it is still showing 53. Could you please help me to resolve this?
Thanks in advance. any help would be appreciated.
trigger CaseTrigger on Case (before insert,before update, after update)
{
if((Trigger.isBefore && Trigger.isUpdate)||(Trigger.isBefore && Trigger.isInsert))
{
List<Id> contactIds = new List<Id>();
List<Id> acctIds = new List<Id>();
for (Case c: Trigger.new){
if (c.EntitlementId == null && c.ContactId!= null && c.AccountId!= null){
contactIds.add(c.ContactId);
acctIds.add(c.AccountId);
}
}
if(contactIds.isEmpty()==false || acctIds.isEmpty()==false){
/* Added check for active entitlement */
List <EntitlementContact> entlContacts = [Select e.EntitlementId,e.ContactId,e.Entitlement.AssetId From EntitlementContact e
Where e.ContactId in:contactIds
And e.Entitlement.EndDate >= Today And e.Entitlement.StartDate <= Today];
if(entlContacts.isEmpty()==false){
for(Case c: Trigger.new){
if(c.EntitlementId == null && c.ContactId!= null){
for(EntitlementContact ec:entlContacts){
if(ec.ContactId==c.ContactId){
c.EntitlementId = ec.EntitlementId;
if(c.AssetId==null && ec.Entitlement.AssetId!=null)
c.AssetId=ec.Entitlement.AssetId;
break;
}
} // end for entitlement
}
} // end for case
} else{
List <Entitlement> entls = [Select e.StartDate, e.Id, e.EndDate, e.AccountId, e.AssetId
From Entitlement e
Where e.AccountId in:acctIds And e.EndDate >= Today And e.StartDate <= Today];
if(entls.isEmpty()==false){
for(Case c: Trigger.new){
if(c.EntitlementId == null && c.AccountId!= null){
for(Entitlement e:entls){
if(e.AccountId==c.AccountId){
c.EntitlementId = e.Id;
if(c.AssetId==null && e.AssetId!=null)
c.AssetId=e.AssetId;
break;
}
} // end for
}
} // end for
}
}
} // end if(contactIds.isEmpty()==false)
}
if(Trigger.isBefore && Trigger.isUpdate)
{
System.debug('entered if condition');
for(Case c : Trigger.new)
{
if (c.Assignment_Group__c != trigger.oldMap.get(c.Id).Assignment_Group__c){
System.debug('Updating logic');
List<Group> qid = [select Id from Group where Name = : c.Assignment_Group__c and Type = 'Queue'];
for(Group g : qid)
{
c.OwnerId = g.id;
System.debug('updated');
}
}}
}
if(Trigger.isBefore && Trigger.isUpdate)
{
for(Case c : Trigger.new)
{
if(c.Assignment_Group__c=='Tech Support'||c.Assignment_Group__c=='GD-IT'||c.Assignment_Group__c=='App-Support'||c.Assignment_Group__c=='GD-RM'||c.Assignment_Group__c=='GD-DB'||c.Assignment_Group__c=='Dev-Ops'||c.Assignment_Group__c=='App-Management'||c.Assignment_Group__c=='PDT-DS-Engg'||c.Assignment_Group__c=='PDT-US-Engg')
{
c.Group_Manager_Email__c = 'sargware#gmail.com'; c.Escalation_Level_2_Email__c ='sargware#gmail.com'; c.Escalation_Level_3_Email__c='sargware#gmail.com';
}
}
}
if(Trigger.isBefore && Trigger.isUpdate)
{
for(Case c : Trigger.new)
{
if(c.Internal_Impact__c == 'Low' && c.Internal_Urgency__c=='Low')
{
c.Priority='Planning';
}
if(c.Internal_Impact__c == 'High' && c.Internal_Urgency__c=='High')
{
c.Priority='Critical';
}
if(c.Status=='Pending User' || c.Status=='Pending Vendor')
{
c.IsStopped = True;
}
}
}
if((Trigger.isAfter && Trigger.isUpdate))
{
Set<Id> Ids = new Set<Id>();
Set<Id> IdR = new Set<Id>();
Set<Id> IdC = new Set<Id>();
List<SC_Problem_Case_Link__c> scprblm = new List<SC_Problem_Case_Link__c>();
List<SC_Problem_Case_Link__c> scprblmo = new List<SC_Problem_Case_Link__c>();
List<SC_Problem_Case_Link__c> scprblmc = new List<SC_Problem_Case_Link__c>();
for (Case cs: Trigger.new)
{
Case oldLead = Trigger.oldMap.get(cs.Id);
if (cs.Status == 'Tested' && Trigger.oldMap.get(oldLead .Id).Status=='Ready for Testing')
{
Ids.add(cs.Id);
}
if (cs.Status == 'ReOpen')
{
IdR.add(cs.Id);
}
if (cs.Status == 'Closed')
{
IdC.add(cs.Id);
}
}
for (SC_Problem_Case_Link__c rateSheet: [select Id,Status__c from SC_Problem_Case_Link__c where Status__c = 'Ready for Testing' AND Case__c in :Ids])
{
if (rateSheet.Status__c != 'Tested') {
rateSheet.Status__c = 'Tested';
//rateSheet.Case__c.Status= 'Awaiting Deployment';
scprblm.add(rateSheet);
}
}
if (!scprblm.isEmpty()) {
update scprblm;
}
for (SC_Problem_Case_Link__c rateSheet: [select Id,Status__c from SC_Problem_Case_Link__c where Status__c = 'Resolved' AND Case__c in :IdR])
{
// List<SC_Problem_Case_Link__c> accts = [Select Id, Status__c from SC_Problem_Case_Link__c where Id in : Trigger.old];
if (rateSheet.Status__c != 'Open') {
rateSheet.Status__c = 'Open';
scprblmo.add(rateSheet);
}
}
if (!scprblmo.isEmpty()) {
update scprblmo;
}
for (SC_Problem_Case_Link__c rateSheet: [select Id,Status__c from SC_Problem_Case_Link__c where Status__c = 'Resolved' AND Case__c in :IdC])
{
if (rateSheet.Status__c != 'Closed') {
rateSheet.Status__c = 'Closed';
scprblmc.add(rateSheet);
}
}
if (!scprblmc.isEmpty()) {
update scprblmc;
}
}
}
Hi SAdmin and welcome to the community.
You can use Developer Console in order to check which part of your code is not covered on your test class. Every time you run your test class you are able to see which lines of code is covered by clicking on Code Coverage dropdown on your main apex class.
This way you can see that the lines of code that are covered by tests are blue. Lines of code that aren’t covered are red. Lines of code that don’t require coverage (for example, curly brackets, comments, and System.debug calls) are left white.
Please check this guide out to find some more info.

Salesforce Trigger Test Class

below is my Apex Trigger. I am a beginner and trying to write its test class but continuously getting error "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Error: You can't select products until you've chosen a price book for this opportunity on the products related list.: []".
trigger TrgrOptyHighestCustmorePrice on Opportunity (before insert, before update)
{
public Id oid;
public String bidType;
public String BUCode;
for(Opportunity o : trigger.new)
{
oid = o.Id;
bidType = o.BidType__c;
BUCode = o.Business_Line_BU__c;
}
List<OpportunityLineItem> oliList = new list<OpportunityLineItem>([SELECT id, Customer_Price__c, ReCat_Product_Line__c
FROM OpportunityLineItem
WHERE OpportunityId =: oid ORDER BY
Customer_Price__c DESC LIMIT 1]);
for(OpportunityLineItem oli : oliList)
{
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.619';
}
if(bidType == 'Competitive' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.620';
}
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.622';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.624';
}
if(bidType == 'Sole Sourced' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.621';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.623';
}
}
for(Opportunity opt : trigger.new)
{
opt.Business_Line_BU__c = BUCode;
}
}
Test Class
#isTest(seeAllData=true)
public class Test_TrgrOptyHighestCustmorePrice {
private static testmethod void TrgrOptyHighestCustmorePriceTest(){
Test.startTest();
//Insert a test product.
Product2 p1 = new Product2(Name='Product Monthly 1111', isActive=true, CurrencyIsoCode='USD', ReCat_Product_Line__c = 'DMS');
insert p1;
// Get standard price book ID.
Id pricebookId = Test.getStandardPricebookId();
// Insert a price book entry for the standard price book.
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = p1.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(
Pricebook2Id = customPB.Id, Product2Id = p1.Id,
UnitPrice = 12000, IsActive = true);
insert customPrice;
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619',
PriceBook2 = customPB);
insert opt;
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id);
insert optLI;
update opt;
Test.stopTest();
}
}
I am unable to understand how can I test my simple trigger.
Its because u do not fill all required fields for the Opportunity Line Item. See: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_opportunitylineitem.htm for required fields.
This as an example will work:
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id, TotalPrice = 100, PricebookEntryId=customPrice.Id, Quantity =3);
First Insert the opportunity.
Then update the opportunity with the pricebookid.
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619'
);
insert opt;
opt.PriceBook2 = customPB;
update opt;

Salesforce Trigger to populate a lookup field

I am trying to create salesforce trigger on Lead that auto-populates a look up field which links the current Lead to an existing Account if there exist an Account with the same name as the Lead's Company custom field.
This is my code:
trigger Link_Lead_To_Account on Lead (before insert ) {
Set<String> whatIDs = new Set<String>();
MAP<id,String> accountMap= new MAP<id,String>();
// save the leads that have been triggered
for (Lead l : Trigger.new) {
whatIDs.add(l.id);
}
List<Lead> leads = [SELECT Id,Company FROM Lead where ID=:whatIDs ];
// loop through the triggered leads, if the account.name == to lead.company then link the found account to the lead
for (Integer i = 0; i <Trigger.new.size(); i++)
{
// System.Debug('++++++++++++++'+Trigger.new[i].company+Trigger.new[i].id);
if(accountMap.get(Trigger.new[i].company)!=null)
{
for(Account ac :[Select name,id from Account])
{
if(Trigger.new[i].Company==ac.Name)
{
Trigger.new[i].Account__c= ac.id;
break;
}
}
}
// System.Debug('Trigger.new[i].Account__c::::'+Trigger.new[i].Account__c);
// System.Debug('Trigger.new[i].company:::::'+Trigger.new[i].company);
// System.Debug('Trigger.new[i].ID:::::'+Trigger.new[i].ID);
}
update leads;
}
But it doesn't work at all. It throws the following error:
Review all error messages below to correct your data.
Apex trigger Link_Lead_To_Account caused an unexpected exception, contact your administrator: Link_Lead_To_Account: execution of AfterInsert caused by: System.StringException: Invalid id: TestAccount2: External entry point
As it requires the Company field to be an ID, but when I write an ID it does't perform any changes.
I managed to fix it.
This is the working class where newLeads.Values() is being populated in the constructor with to the Trigger.new() values on the before insert event:
public void LinkLeadToAccount() {
Set<String> companies = new Set<String>();
for (Lead l: newLeads.values()) {
if (l.Company != null) companies.add(l.Company);
}
if (companies.size() > 0) {
// Pick most recent Account where more than one with same name
Map<String, Id> accountNameToId = new Map<String, Id>();
for (Account a : [
select Name, Id
from Account
where Name in :companies
order by CreatedDate
]) {
accountNameToId.put(a.Name, a.Id);
}
if (accountNameToId.size() > 0) {
Lead[] updates = new Lead[] {};
for (Lead l: newLeads.values()) {
if (l.Company != null) {
Id accountId = accountNameToId.get(l.Company);
if (accountId != null) {
updates.add(new Lead(Id = l.Id, Account__c = accountId));
}
}
}
System.debug(' leads_to_update : ' + updates.size() + ' leads_to_update : ' + updates);
update updates;
}
}
}