Getting dupicate agent names - salesforce

Here am using map ,not abled to understand how to solve the duplicate name,i want one agent name against number of payments(child of opp)
how do I get unique names of users
public class First_Pay_ClearRates_Controller {
#AuraEnabled
public static Map<Id,User> fetchUsers() {
// List<User> userList= [SELECT Id, Name FROM User WHERE Profile.Name = 'Sales' LIMIT 20];
Map<Id,User> userMap= new Map<Id,User>([SELECT Id, Name FROM User WHERE Profile.Name = 'Sales' LIMIT 20]);
return userMap;
}
#AuraEnabled
public static List<Opportunity> getOpps(Map<Id,User> usrMap){
Map<Id,List<Opportunity>> oppMap = new Map<Id,List<Opportunity>>();
List<Opportunity> oppList = new List<Opportunity>();
List<Payments__c> payList= new List<Payments__c>();
List<Payments__c> payList1= new List<Payments__c>();
// prev key Agent_Name_User__c
// AND First_Payment_Date__c=THIS_MONTH
for(Opportunity o: [SELECT Id,First_Payment_Date__c,OwnerId,Owner.Name ,of_Payments_Made__c,PaymentsCounter__c,CollectedPaymentCount__c,First_Client_Payment_Collected_Date__c From Opportunity WHERE OwnerId IN: usrMap.keyset() AND First_Payment_Date__c!=null LIMIT 20]){
if(!oppMap.containsKey(o.OwnerId)){
oppMap.put(o.OwnerId,new List<Opportunity>());
}
o.PaymentsCounter__c=0;
o.CollectedPaymentCount__c=0;
//AND Due_Date__c=THIS_MONTH
for(Payments__c p :[Select Id,Opportunity__c,Payment_Collected__c,Due_Date__c FROM Payments__c WHERE Opportunity__c =: o.Id ]){
if(!p.Payment_Collected__c){
payList.add(p);
o.PaymentsCounter__c= payList.size();
}else if(p.Payment_Collected__c){
payList1.add(p);
o.CollectedPaymentCount__c= payList1.size();
}
}
oppList.add(o);
oppMap.put(o.OwnerId,oppList);
}
return oppList;
}

Related

Write test class for apex(salesforce)

I write code for Apex trigger, now i need to test him. Can u help me?
here is the code:
public with sharing class Sharing_Sales {
public static void SharingRelatedOrdersAndAccount(List<Sales_Rep_Assignment__c> triggerNew,
Map<Id, Sales_Rep_Assignment__c> oldMap){
List<Order> relatedOrders = new List<Order>();
List<Sales_Rep_Assignment__c> activeAssignments = new List<Sales_Rep_Assignment__c>();
Set<Id> accIds = new Set<Id>();
Set<Id> salesRepsIds = new Set<Id>();
Map<Id, List<Order>> ordersByAccountId = new Map<Id, List<Order>>();
for(Sales_Rep_Assignment__c sar: triggerNew){
if(sar.Active__c == true && (oldMap.get(sar.id).Active__c == false || oldMap == null)) {
activeAssignments.add(sar);
salesRepsIds.add(sar.Sales_Reps__c);
accIds.add(sar.Account__c);
}
for(Order ord : [SELECT Id, AccountId FROM Order WHERE AccountId IN :accIds]) {
if (!ordersByAccountId.containsKey(ord.AccountId)) {
ordersByAccountId.put(ord.AccountId, new List<Order>());
}
ordersByAccountId.get(ord.AccountId).add(ord);
}
List<OrderShare> sharingRecords = new List<OrderShare>();
for (Sales_Rep_Assignment__c srs : activeAssignments) {
for (Order ord : ordersByAccountId.get(srs.Account__c)) {
OrderShare sharingorderrecord = new OrderShare();
sharingorderrecord.OrderId = ord.Id;
sharingorderrecord.OrderAccessLevel = 'Edit';
sharingorderrecord.UserOrGroupId = 'Sales_Rep__c';
sharingorderrecord.RowCause = 'Manual';
sharingRecords.add(sharingorderrecord);
}
if(!sharingRecords.IsEmpty()){
insert sharingRecords;
}
}
}
}
public static void Sharingorderandaccountisdelete(List<Sales_Rep_Assignment__c> triggerNew,
List<Order> relatedOrders,
Map<id, Sales_Rep_Assignment__c> oldMap){
List<Sales_Rep_Assignment__c> falseAssignments = new List<Sales_Rep_Assignment__c>();
Set<Id> accIds = new Set<Id>();
Set<Id> salesRepsIds = new Set<Id>();
Map<Id, List<Order>> ordersByAccountId = new Map<Id, List<Order>>();
for(Sales_Rep_Assignment__c sar: triggerNew){
if(sar.Active__c == false && oldMap.get(sar.id).Active__c == true || triggerNew == null){
falseAssignments.add(sar);
salesRepsIds.add(sar.Sales_Reps__c);
accIds.add(sar.Account__c);
}
}
List<OrderShare> sharingDeletedOrder = new List<OrderShare>();
for(Order ord : [SELECT Id, AccountId FROM Order WHERE AccountId IN :accIds]) {
if (!ordersByAccountId.containsKey(ord.AccountId)) {
ordersByAccountId.put(ord.AccountId, new List<Order>());
}
for(OrderShare sharingRecords: [SELECT Id FROM OrderShare WHERE Id =: ord.id AND UserOrGroupId IN :salesRepsIds]){
sharingDeletedOrder.add(sharingRecords);
}
}
delete sharingDeletedOrder;
}
}`
deskp of task Use
Apex Trigger to share Account and related Orders to Sales Rep when new Sales Rep Assignment is created.
When Sales Rep Assignment record is deleted or set to Active = false Sales Rep should not have edit access to account and related orders anymore, if Active is set back to true – share records again.
You have to create a test class. Here you will find some guidance:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
After you worked it through and wrote a test class, we can help with problems.

how to fix System.NullPointerException: Attempt to de-reference a null object in apex class using Map<parentId, child>?

Getting the error in line " taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;" becasue the ownerid field is on contact.
Contact is the parent of benefit, Here I am getting all the benefits in start method. I want to add contactid only once if it has more than one child for that I used SET. I want to use maps as I need to get the contact OwnerId field from contact object which I am fetching in the query in start method. How do I Access contact.ownerId field using a map? below is the code.
global Database.QueryLocator start(Database.BatchableContext bc) {
Query='select contact__r.ownerId, contact__c, Task_creation_date__c, Status__c, task_created__c, type__c from Benefit__c Where Task_creation_date__c= TODAY AND Status__c IN (\'Active\',\'Pending\') AND Task_created__c =FALSE AND Type__c!=\'Short Term Medical\'';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc, List<Benefit__c> scope){
// process each batch of records
List<Contact> contacts = new List<Contact>();
List<Task> TaskList = new List<Task>();
set<id> conset = New set<id>();
Map<id,benefit__c> ConMap = new map<id,Benefit__c>();
for (Benefit__c b : scope) {
conset.add(b.contact__c);
ConMap.put(b.contact__c, b);
b.task_created__c = TRUE;
}
system.debug('contact and its benefit------'+ConMap);
recordsProcessed = conset.size();
//List<Contact> tempList = new List<Contact>();
// tempList = [Select Id,OwnerId, firstname from Contact where Id IN:(conset)];
if(!ConMap.isEmpty())
{
for(Benefit__c ben : ConMap.values())
{
Task taskObj = new Task();
taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;
I want to populate contact ownerid as the task ownerid but how do I access it from the map and keep the unique contact id in the map?
I see that the batch query does not have the filtering condition 'Contact__c != null'. So, it's possible that one of the benefit records is missing value in the 'Contact__c' field and you wouldn't find it in the map. You can solve this in two ways:
Add 'Contact__c != null' to the selector query if you don't care about those records.
(Or)
Check for 'null' value in the for loop as below:
if(!ConMap.isEmpty())
{
for(Benefit__c ben : ConMap.values())
{
if(String.isBlank(ben.Contact__c)){
/* continue;
or
throw exception()
*/
}
Task taskObj = new Task();
taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;
I re wrote the code to resolve this nd optimize the code as below.
public with sharing class MyBatch implements Database.Batchable<AggregateResult>{
public Iterable<AggregateResult> start(Database.BatchableContext context)
{
return [
SELECT Contact__c, Contact__r.OwnerId owner FROM Benefit__c
WHERE Contact__c != null AND ...
GROUP BY Contact__c, Contact__r.OwnerId
];
}
public void execute(Database.BatchableContext context, List<AggregateResult> scope)
{
Set<Id> contactIds = new Set<Id>();
List<Task> tasks = new List<Task>();
for (AggregateResult aggregate : scope)
{
Id ownerId = (Id)aggregate.get('owner');
Id contactId = (Id)aggregate.get('Contact__c');
contactIds.add(contactId);
tasks.add(new Task(OwnerId=ownerId, /*other fields*/));
}
insert tasks;
List<Benefit__c> benefits = [
SELECT Id FROM Benefit__c WHERE Contact__c IN :contactIds
];
for (Benefit__c benefit : benefits)
benefit.Task_Created__c = true;
update benefits;
}
public void finish(Database.BatchableContext context) { /*additional logic*/ }}

Apex code-how to get the data of campaign Members from Subquery

I am trying to display four fields on my VF page Name, Status from (Campaign Members) and Subject and Last Modified Date from (Activity History) Object.I am not able to fetch the Name and Status fields from Campaign Members.
Can anyone please tell me How to get the Name and Status fields from Campaign Members.Below is my Controller code.
public with sharing class CampaignView {
public Campaign camp {get; set; }
public List<MemberWrapper> lMemberWrappers {get; set;}
public DateTime startDate {get; set;}
public CampaignView(ApexPages.StandardController controller) {
camp = (Campaign)controller.getRecord();
lMemberWrappers = new List<MemberWrapper>();
getCampaignMembers();
startDate = null;
for (Campaign c : [Select ID, (SELECT Id, CampaignId, Status FROM CampaignMembers where CampaignId = :camp.Id) FROM campaign WHERE id = :camp.Id ]) {
for (Lead ld : CampaignMembers) {
for (ActivityHistory ah : ld.getSObjects('ActivityHistories')) {
lMemberWrappers.add(new MemberWrapper(ld.Name, ah.Subject, ah.LastModifiedDate, ld.CampaignMembers.get(0).Status));
}
}
}
}
private List<Lead> CampaignMembers;
public List<Lead> getCampaignMembers() {
CampaignMembers = [Select Id, Name, Phone, MobilePhone, Email, LastModifiedDate, (Select id, Campaign.Name, Contact.Phone, Lead.FirstName, Lead.LastName, Lead.Name, LeadID, ContactID, Lead.Phone, Lead.Email, Lastmodifieddate, Lead.LastmodifiedDate, Status, CampaignId, Campign_ID__c, Lead.MobilePhone From CampaignMembers where CampaignId = :camp.Id ),
(Select Subject, Id, lastModifiedDate From ActivityHistories order by LastModifiedDate DESC LIMIT 1 )
From Lead where Id IN(select LeadId from campaignMember where campaignId = :camp.Id ) ];
return CampaignMembers;
}
public class MemberWrapper {
public Object Status {get; set;}
public String Name {get; set;}
public String Subject {get; set;}
public Datetime LastActivityHistory {get; set;}
public MemberWrapper(String Name, String Subject, Datetime LastActivityHistory, Object Status ) {
this.Name = Name;
this.Subject = Subject;
this.LastActivityHistory = LastActivityHistory;
this.Status = Status;
}
}
}
This will take you more than one query because of the ActivityHistory requirement. There are four levels of relationships in play here: Campaign -> CampaignMember -> Lead -> ActivityHistory, so you cannot perform this using just sub-queries.
The following code should get you the info you need:
Set<Id> leadIds = new Set<Id>();
List<Campaign> campaignList = [Select ID, (SELECT Id, Status, LeadId FROM CampaignMembers) FROM campaign WHERE id = :camp.Id ];
for (Campaign c : campaignList) {
for (CampaignMember cm : c.CampaignMembers) {
leadIds.add(cm.LeadId);
}
}
Map<Id, Lead> leadMap = new Map<Id, Lead>([Select Id, Name, (Select Subject, LastModifiedDate from ActivityHistories Order By LastModifiedDate DESC limit 1) From Lead Where Id IN :leadIds]);
for (Campaign c : campaignList) {
for (CampaignMember cm : c.CampaignMembers) {
Lead ld = leadMap.get(cm.LeadId);
if (ld.ActivityHistories.size() > 0) {
ActivityHistory ah = ld.ActivityHistories[0];
lMemberWrappers.add(new MemberWrapper(ld.Name, ah.Subject, ah.LastModifiedDate, cm.Status));
}
}
}
I just skipped creating the MemberWrapper if there were no activities, but you could change it to just put blank values if you wish.

Need help in improving test coverage to 75% - Apex Class

I am not able to upload my package because test coverage is below 75%.
How to improve coverage. How to write test methods for triggers.
Please help.
I have tried this code :
This is my controller class:
public class MyController{
public List<Merchandise__c> merch{get;set;}
public Merchandise__c toDelete{get;set;}
public MyController(){
merch = [SELECT ID,Merchandise__c.name,Price__c,Description__c,Total_Inventory__c FROM Merchandise__c];
}
public pageReference del(){
string id = Apexpages.currentpage().getParameters().get('merchandiseId');
toDelete = [SELECT Id,Merchandise__c.name,Price__c,Description__c,Total_Inventory__c FROM Merchandise__c WHERE Id =: id];
delete toDelete;
return null;
}
public pageReference add(){
Merchandise__c item = new Merchandise__c(
Name = 'Enter Name',
Description__c = 'Enter Description',
Price__c = 0.00,
Total_Inventory__c = 0
);
merch.add(item);
insert item;
return null;
}
public PageReference save(){
string id = Apexpages.currentpage().getParameters().get('merchandiseId');
Merchandise__c toUpdate = [SELECT Name, Description__c, Price__c FROM Merchandise__c WHERE ID =: id];
update toUpdate;
return null;
}
}
I have craeted this Test Class :
#isTest
Public Class demoTest{
static testMethod void checkDatatableData() {
List<Merchandise__c> merch;
Test.startTest();
merch = [SELECT ID,Merchandise__c.name,Price__c,Description__c,Total_Inventory__c FROM Merchandise__c];
Test.stopTest();
}
static testMethod void checkAdd() {
Merchandise__c item = new Merchandise__c(
Name = 'Enter Name',
Description__c = 'Enter Description',
Price__c = 0.00,
Total_Inventory__c = 0
);
Test.startTest();
insert item;
System.assertNotEquals(null,item.Id);
List<Merchandise__c> merchItem = [SELECT Id FROM Merchandise__c WHERE Id =: item.Id];
System.assertEquals(1,merchItem.size());
Test.stopTest();
}
static testMethod void checkUpdateDelete() {
Merchandise__c testmerch = new Merchandise__c(
Name = 'NewProduct',
Description__c = 'this is anew product',
Price__c = 20.00,
Total_Inventory__c = 100
);
Test.startTest();
insert testmerch;
system.assertNotEquals(null,testmerch.Id);
testmerch.Price__c = 40.00;
update testmerch;
Merchandise__c updatedmerch = [SELECT Id,Price__c FROM Merchandise__c WHERE Id =: testmerch.Id];
system.assertEquals(40.00,updatedmerch.Price__c);
Merchandise__c toDelete = [SELECT ID FROM Merchandise__c WHERE Id =: testmerch.Id];
system.assertNotEquals(null,toDelete.Id);
delete toDelete;
Test.stopTest();
}
}
Can you please tell me what changes I need to do to improve coverage?
This link should tell you what you need to know.
http://wiki.developerforce.com/page/An_Introduction_to_Apex_Code_Test_Methods
Basically you need to replicate the functionality of the trigger in your test methods, so for instance if you have an after update trigger case that runs when it moves from Open to Closed you first need to create a test method for your trigger then within the test method insert a case record for testing, which may also require a contact or an account etc, then you change the value of the case to closed and then run an update method. This is very simplistic but that is the idea. So when writing test classes try to think about what your triggers and classes do and then try to automate what the user would do in your test methods, making sure to cover all your bases including where the piece of apex should fire an exception.
Try to avoid using hard-coded Id's wherever possible.
These links may also help
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_best_practices.htm
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm

How to Create a read-only group in SalesForce

I want to know how to create a read-only group + like + comment and not being able to post for members except admin and owner
* how to use triggers on the posting in this group?.
i tried but it not work:
trigger N_GroupReadOnly on FeedItem (before insert) {
ID groupId = [Select Id from CollaborationGroup where Name = 'Group_ReadOnly'].Id;
CollaborationGroup ownerId = [Select OwnerId From CollaborationGroup Where Name = 'Group_ReadOnly'];
for(FeedItem item : trigger.new){
if((item.ParentId == groupId) && (item.InsertedById != ownerId.OwnerId)){
system.debug('you can not add post in this group');
alert("you can not add post in this group");
delete item ;
return;
}
else{
insert item;
}
}
}
Thank you.
Solution:
as per this developerforce.com forum entry:
Trigger
trigger GroupReadOnly on FeedItem (before insert) {
CollaborationGroup gp = [Select OwnerId, Id From CollaborationGroup Where Name = 'Group_ReadOnly'];
List<FeedItem> feedItems = new List<FeedItem>();
for(FeedItem item : trigger.new){
if(item.ParentId == gp.Id)
{
feedItems.add(item);
}
}
if(feedItems.size() >0) GroupReadOnlyClass.FilterFeedItems(feedItems);
}
Class
public class GroupReadOnlyClass{
public static void FilterFeedItems(List<FeedItem> feedItems){
CollaborationGroup gp = [Select OwnerId, Id From CollaborationGroup Where Name = 'Group_ReadOnly'];
for(FeedItem item :feedItems){
if(item.ParentId == gp.Id)
{
if(UserInfo.getUserId()!= gp.OwnerId){
item.addError('You cannot post! Just Owner can post in this group');
}
}
}
}
}

Resources