Visualforce Apex Trigger updating wrong records - triggers

I cant figure out why this trigger is sometimes updating records that dont match the criteria. The idea is that when an account goes from 'on-hold' to an active service, any cancelled assignments are returned to pending. I cant figure out whats triggering it, but it seems everyone in a while, assignments are un-cancelled for accounts that have no change in service. Heres the code:
trigger cancelAssignments on Account (before update) {
List<Assignment__c> masterListA = [select Id, Status__c, Practice__c from Assignment__c where Practice__c IN :Trigger.newMap.keySet() and type_of_work__c != 'a0Qa000000G1WmVEAV' AND (status__c = 'Feedback Needed' OR status__c = 'Pending Review' OR status__c = 'Accepted')];
List<Assignment__c> masterListB = [select Id, Status__c, Practice__c from Assignment__c where Practice__c IN :Trigger.newMap.keySet() and type_of_work__c != 'a0Qa000000G1WmVEAV' AND (status__c = 'Canceled')];
for (Account oAccount : trigger.new) {
if (oAccount.current_services__c == null || oAccount.current_services__c == 'Hold'){
for (Account oAcct : trigger.old){
if (oAcct.current_services__c != null && oAcct.current_services__c != 'Hold'){
List<Assignment__c> assignmentsToUpdate = new List<Assignment__c>();
for (Assignment__c rd : masterListA){
if (rd.practice__c == oAccount.id){
rd.Status__c = 'Canceled';
assignmentsToUpdate.add(rd);
}
}update assignmentsToUpdate;
}
}
}
else if (oAccount.current_services__c != 'Hold' && oAccount.current_services__c != null ){
for (Account oAcctB : trigger.old){
if (oAcctB.current_services__c == 'Hold'){
List<Assignment__c> assignmentsToUpdateB = new List<Assignment__c>();
for (Assignment__c rdB : masterListB){
if (rdB.practice__c == oAccount.id){
rdB.Status__c = 'Pending Review';
assignmentsToUpdateB.add(rdB);
}
}update assignmentsToUpdateB;
}
}
}
}
}

The problem may be as follows:
masterListB grabs assignments for more than one account
The code in the for (Account oAcctB : trigger.old) loop never checks to see whether old account that's in "Hold" status is the same account
One solution may be to make the edit below:
/* Old condition replaced:
if (oAcctB.current_services__c == 'Hold') { */
if (oAcctB.current_services__c == 'Hold' and oAcctB.Id == oAccount.Id) {
To prove whether this is the right solution, I suggest creating a unit test that works like this:
Create two Accounts, "Alpha Corp" and "Beta Corp"
Set Alpha Corp's Current Services to "Hold"
Set Beta Corp's Current Services to "Active"
Add a related Assignment to Alpha Corp with Status "Canceled"
Add a related Assignment to Beta Corp with Status "Canceled"
Update both accounts in a single DML operation, doing something trivial like changing the Billing Country from "US" to "United States"
Assert that the related Assignment for Alpha Corp remains "Canceled"
I suspect that the code you shared will not pass the unit test, in which case you'll be able to zero in on the problem and fix it.

While Marty's code answered the question I asked, I also ran into some 'Too Many Code Statements' errors. Here is the final code that seems to resolve that:
trigger cancelAssignments on Account (before update) {
List<account> quitingAccounts = new List<account>();
List<account> returningAccounts = new List<account>();
List<Assignment__c> assignmentsToCancel;
List<Assignment__c> assignmentsToReturn;
for (Account oAccount : trigger.new)
{
if (oAccount.current_services__c == null || oAccount.current_services__c == 'Hold')
{
for (Account oAcct : trigger.old)
{
if (oAcct.current_services__c != null && oAcct.current_services__c != 'Hold' && oAcct.Id == oAccount.Id)
{
quitingAccounts.add(oAcct);
}
}
}
else if (oAccount.current_services__c != 'Hold' && oAccount.current_services__c != null )
{
for (Account oAcctB : trigger.old)
{
if (oAcctB.current_services__c == 'Hold' && oAcctB.Id == oAccount.Id)
{
returningAccounts.add(oAcctB);
}
}
}
}
assignmentsToCancel = [select Id, Status__c, Practice__c from Assignment__c where Practice__c IN :quitingAccounts and type_of_work__c != 'a0Qa000000G1WmVEAV' AND (status__c = 'Feedback Needed' OR status__c = 'Pending Review' OR status__c = 'Accepted')];
assignmentsToReturn = [select Id, Status__c, Practice__c from Assignment__c where Practice__c IN :returningAccounts and type_of_work__c != 'a0Qa000000G1WmVEAV' AND status__c = 'Canceled'];
for (Assignment__c rd : assignmentsToCancel)
{
rd.Status__c = 'Canceled';
}
for (Assignment__c rd : assignmentsToReturn)
{
rd.Status__c = 'Pending Review';
}
update assignmentsToCancel;
update assignmentsToReturn;
}

Related

salesforce compare standard obj and custom object and assign value

I have custom obj "A" and Standard obj Case. Case standard obj has lookup to custom obj "A". there is a field between the two objects called Customer_ID__c. I wrote a Trigger (before Insert, Before Update) to associated the case record to the correct existing custom obj "A" record if "Case.Custom_Id__c" match the one in the Custom obj "A". Unfortunate it is not happening and I'm not sure where to look.
trigger IAACaseRelateASAP on Case (before insert, before update) {
Id recordtypes = [Select Id, name
From RecordType
Where SobjectType = 'Case'
AND Name = 'I Buy'
LIMIT 1].Id;
Set<String> casId = new Set<String>();
for(Case cs : Trigger.new)
{
if(cs.RecordtypeId == recordtypes && cs.Type == 'Contact Me')
{
if(cs.custm_Obj_A_Name__lookupfield__c == null && (cs.Customer_ID__c != null || cs.Customer_ID__c !='0'))
{
casId.add(cs.Customer_ID__c);
}
}
}
system.debug('Case Set Ids' + casId);
List<A__c> aList = [Select Customer_ID__c, Id
From A__c
Where Customer_ID__c IN: casId
AND
A__c != 'Provider'];
System.Debug('equals' + aList);
Map<String, A__c> aMapId = new Map<String, A__c>();
for(A__c aAcct : aList)
{
aMapId.put(aAcct.Customer_ID__c, aAcct);
}
for(Case cas : Trigger.new)
{
if(cas.RecordtypeId == recordtypes && cas.Type == 'Contact Me')
{
if(cas.custm_Obj_A_Name__lookupfield__c == null && (cas.Customer_ID__c != null || cas.Customer_ID__c !='0'))
{
if(aMapId.containsKey(cas.Customer_ID__c))
{
A__c aAcct = aMapId.get(cas.Customer_ID__c);
System.Debug('Case IAA ASAP Account value: ' + asapAcct);
}
}
}
}
}
It might be best when looping through your cases to build your set of Customer_ID__c ids to also build a List of cases with customer ids so that you don't have to loop through the entire new list a second time. There are a couple other issues with the trigger in general but I'll ignore those and just focus on what you asked. Think your issue is that you don't actually set the case field in this area:
if(aMapId.containsKey(cas.Customer_ID__c))
{
A__c aAcct = aMapId.get(cas.Customer_ID__c);
System.Debug('Case IAA ASAP Account value: ' + asapAcct);
}
It should be :
if(aMapId.containsKey(cas.Customer_ID__c))
{
cas.custm_Obj_A_Name__lookupfield__c = aMapId.get(cas.Customer_ID__c).Id;
}

Amount change on Opportunity Apex Trigger

I'm trying to create trigger if record type is Revenue Risk then amount should be saved in negative value, Here's my code in which I'm having error, I tried it two ways, second is in comments.. none of them is working
public with sharing class amountValidator {
//pull data of Opportunity in list
public static void validateAmount (list<Opportunity> oppList){
oppList = [Select amount FROM Opportunity WHERE RecordType.Name IN ('Revenue Risk')];
for(Opportunity opportunities : oppList){
if(oppList.amount >= '0'){
oppList.amount = oppList.amount * '-1';
}
}
/*Map<String,Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();
Schema.RecordTypeInfo rtByName = rtMapByName.get('Revenue Risk');
for(Opportunity each : oppList){
if(rtByName.size == 0){
}
else{
if(oppList.Amount >= 0){
oppList.Amount = oppList.Amount*-1;
}
}
}*/
The error is very clear:
if(oppList.amount >= '0'){ // THIS LINE WILL THROW AN ERROR: 'Comparison arguments must be compatible types: Integer (or Double), String
oppList.amount = oppList.amount * '-1'; // THIS ONE TOO: 'Arithmetic expressions must use numeric arguments'
}
Your second code snippet is also wrong (same for first one).
if(oppList.Amount >= 0){
oppList.Amount = oppList.Amount*-1;
// MUST BE each.Amount = each.Amount * - 1; Please try not to use reserved words as variable names
}
You may want to take a look at a previous post describing strongly typed programming languages: Strongly Typed
Since we can't add comments just yet, we're going to add a new answer:
You're not updating/inserting the updated amount for your opportunity.
The correct way of doing this is to create a separate List of Opportunities (i.e. List oppsToUpdate) and add the updated opportunities to this list.
public static void validateAmount (list<Opportunity> oppList){
oppList = [Select amount FROM Opportunity WHERE RecordType.Name IN ('Revenue Risk')]; // Why are you requerying the Opportunity if you already have it??
List<Opportunity> oppsToUpdate = new List<Opportunity>();
for(Opportunity opportunities : oppList){
if(opportunities.amount > 0){
opportunities.amount = opportunities.amount * -1;
oppsToUpdate.add(opportunities);
}
}
upsert opportunities;
}
Remember to enclose your function with try-catch statements with system debugs to see what's going on with your code.
And this is the link to the input parameter modifications and why this is bad practice: Input Parameters
Working Code:
trigger Risk_NegativeQuantity on OpportunityLineItem (before insert) {
set<id> oppid = new set<id>();
for (OpportunityLineItem oli : trigger.new)
{
oppid.add(oli.opportunityid);
}
Id RevenueRisk= Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Revenue Risk').getRecordTypeId();
list<opportunity> opplist = [select id, recordtype.name,recordtypeid from opportunity where id in : oppid ];
for (OpportunityLineItem oli : trigger.new)
{
for (opportunity opp: opplist)
{
if (oli.opportunityid == opp.id)
{
if(opp.recordtype.name == 'Revenue Risk')
{
if(oli.Quantity > 0)
{
oli.Quantity = oli.Quantity * -1;
}
}
}
}
}
}

Test Coverage fails on before insert / before update Apex trigger

I have this very simple before insert / update trigger on Opportunity that auto-selects the Price Book based on a dropdown value containing Sales Office (State) location info.
Here's my Trigger:
trigger SelectPriceBook on Opportunity ( before insert, before update ) {
for( Opportunity opp : Trigger.new ) {
// Change Price Book
// New York
if( opp.Campus__c == 'NYC' )
opp.Pricebook2Id = PB_NYC; // contains a Pricebook's ID
// Atlanta
if( opp.Campus__c == 'ATL' )
opp.Pricebook2Id = PB_ATL; // contains another Pricebook's ID
}
}
Here's my Test Class:
#isTest (SeeAllData = true)
public class SelectPriceBookTestClass {
static testMethod void validateSelectPriceBook() {
// Pricebook IDs
ID PB_NYC = 'xxxx';
ID PB_ATL = 'xxxx';
// New Opp
Opportunity opp = new Opportunity();
opp.Name = 'Test Opp';
opp.Office__c = 'NYC';
opp.StageName = 'Quote';
// Insert
insert opp;
// Retrive inserted opportunity
opp = [SELECT Pricebook2id FROM Opportunity WHERE Id =:opp.Id];
System.debug( 'Retrieved Pricebook Id: ' + opp.Pricebook2Id );
// Change Campus
opp.Office__c = 'ATL';
// Update Opportunity
update opp;
// Retrive updated opportunity
opp = [SELECT Pricebook2id FROM Opportunity WHERE Id =:opp.Id];
System.debug( 'Retrieved Updated Pricebook Id: ' + opp.Pricebook2Id );
// Test
System.assertEquals( PB_ATL, opp.Pricebook2Id );
}
}
The test runs report 0% test coverage.
Also, on similar lines I have another before insert trigger that sets the Owner of an Event same as the Owner of the parent Lead. Here's the code:
trigger AutoCampusTourOwner on Event( before insert ) {
for( Event evt : Trigger.new ) {
// Abort if other kind of Event
if( evt.Subject != 'Visit' )
return;
// Set Owner Id
Lead parentLead = [SELECT OwnerId FROM Lead WHERE Id = :evt.WhoId];
evt.OwnerId = parentLead.OwnerId;
}
}
This, too, is causing 0% coverage - my guess is that it's got something to do with the for loops in both. I know I'm seriously flouting DML rules by invoking SOQL query inside a for loop, but for my purposes it should be fine as these Events are created manually and only one at a time - so there are no scopes of governor limits kicking in due to bulk inserts.
The code in both cases work 100%. Please suggest a fix for the test cases.
Have you tried trigger.old ?? My thinking is, when you update the office in your test class from NYC to ATL, the value 'NYC' will be in trigger.old, and that's what you want to check in your trigger.
I could be wrong since i'm new to apex too, but try it and let me know what happens.
For the first trigger don't do anything rather just create opportunity and execute like this.
Test class for SelectPriceBook
#isTest
private class TriggerTestClass {
static testmethod void selectPriceTest(){
Opportunity opps = new Opportunity(
Name= 'Test Opps',
CloseDate = System.today().addDays(30),
StageName = 'Prospecting',
ForecastCategoryName = 'Pipeline',
Office__c = 'NYC');
insert opps;
Opportunity opps2 = new Opportunity(
Name= 'Test Opps 2',
CloseDate = System.today().addDays(28),
StageName = 'Prospecting',
ForecastCategoryName = 'Pipeline',
Office__c = 'ATL');
insert opps2;
}
}
It will give you good test coverage and I don't know what are you trying to do in AutoCampusTourOwner!
i have test class for these
trigger ClientEmailTrigger on inflooens__Client_Email__c (after insert, after update, before insert, before update) {
ApexTriggerSettings__c setting = ApexTriggerSettings__c.getValues('Inflooens Trigger Settings');
if(setting != NULL && setting.ClientEmailTrigger__c == TRUE){
AuditTrailController objAdt = new AuditTrailController();
if(Trigger.isAfter){
if(Trigger.isUpdate){
System.debug('In Update Client Email Record');
objAdt.insertAuditRecord(Trigger.newMap, 'inflooens__Client_Email__c', Trigger.new.get(0).Id, Trigger.oldMap);
}
if(Trigger.isInsert){
objAdt.insertAuditRecord(Trigger.newMap, 'inflooens__Client_Email__c', null , null);
}
}
}
}

how to debug EF 5 null reference exception?

I am getting a null refrence exception when im filtering EF but I am absolultely clueless.
public IEnumerable<TonalityBatchModel> GetTonalityBatch(int briefID)
{
try
{
var brief = NeptuneUnitOfWork.Briefs.FindWhere(b => b.ID == briefID).FirstOrDefault();
if (brief != null && brief.TonalityCriteria != null)
{
return brief.TonalityCriteria.TonalityBatches
.Select(b => new TonalityBatchModel()
{
BriefID = b.BriefID,
Status = b.TonalityCriteria.IsActive == true ?"Active":"Ended",
BatchID = b.ID,
CompetitorID = b.BriefCompetitorID,
Competitor = brief.BriefCompetitors.Where(i=>i.ID == b.BriefCompetitorID).Select(c=>c.Organisation.Name).First(),
Size = b.BatchSize,
StartDate = b.StartDate,
EndDate = b.EndDate,
IsPublished = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Published?"Yes":"No",
IsCompleted = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Completed ? "Yes" : "No",
IsAssigned = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Allocated ? "Yes" : "No",
ImportantCount = b.TonalityItems.Count(i=> i.IsImportant),
ArticlesCount = b.TonalityItems.Count,
FavourableCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Favourable),
UnfavourableCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Unfavourable),
NeutralCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Neutral)
}).ToList();
}
return new List<TonalityBatchModel>();
}
catch (Exception ex)
{
Logger.Error(ex);
throw;
}
}
You'll need to reduce your query to a simpler query, and then start building it back up again until the NullReferenceException occurs. Looking at your code, here are some likely places (I'm making some assumptions since I don't know everything about your model):
Competitor = brief.BriefCompetitors.Where(i=>i.ID == b.BriefCompetitorID).Select(c=>c.Organisation.Name).First()
BriefCompetitors could be null. c.Organisation could be null.
IsPublished = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Published?"Yes":"No",
(and other similar lines) b.Lookup_TonalityBatchStatus might be null.
ImportantCount = b.TonalityItems.Count(i=> i.IsImportant),
(and other similar lines) b.TonalityItems might be null.
I believe this is because your count is returning null records. I could be wrong but the SQL that's being produced here is something like:
INNER JOIN TonalityItems i on i.Lookup_TonalityScoreTypes == x
Where x is the value of (int)TonalitySourceType.Favourable. Because this join has no matching results there is nothing to do a count on. You could try adding ?? 0 to the end of the query:
FavourableCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Favourable) ?? 0,

Display error message after using isAllowed

For example I have this implementation of the assert method in the class derived from Zend_Acl_Assert_Interface.
function assert(
Zend_Acl $acl,
Zend_Acl_Role_Interface $user = null,
Zend_Acl_Resource_Interface $item = null,
$privilege = null
) {
if (!$user instanceof User) throw new Exception("…");
if (!$item instanceof Item) throw new Exception("…");
return
$user->money >= $item->price &&
$user->rating >= $item->requiredRating;
}
It checks two conditions: user has enought money and user has enought rating. How to display error message to make user know which condition is failed when isAllowed method returns only bool?
simply check them one by one
$error = array();
if(!($user->money >= $item->price))
$error[] = "user money is less then price";
if(!($user->rating >= $item->requiredRating))
$error[] = "user rating less then required rating ";
Zend_Registery::set('acl_error',$error);
if(count($error) == 2) return false;
return true;
you can retrieve acl errors anywhere in your applicating by Zend_Registry::get('acl_error') ; and show it to user as you like.