-
ChatterFeed
-
0Best Answers
-
1Likes Received
-
0Likes Given
-
11Questions
-
4Replies
compare two lists and remove records which are common in both lists from list1
I have two lists of dates list one contains 100 days dates from tomorrow and list two contains dates which come from api that contains holidays and weekends. I need to compare both the lists and remove second list values from the first list. I have tried to compare and remove but it is not giving proper result.Please help me how to do it in apex.
-
- jagadeep k
- April 04, 2022
- Like
- 0
Add check box to map array in lwc
I want to display checkbox for map array the js code is as below
import { LightningElement, api } from 'lwc';
export default class testPaginationMapArrayEnhanced extends LightningElement {
@api structureType = 3;
data = [];
globalActions = [];
// columns = [];
// keyField;
showPaginationTable = false;
connectedCallback() {
const actions = [
{ label: 'Show details', name: 'show_details' },
{ label: 'Delete', name: 'delete' },
];
/* { type: 'action',
typeAttributes: { rowActions: actions}
}*/
this.data = [
{ "name":"Test Name 1","website": {"value": "testname1.com", "type": "url"}, "phone": {"value": "09898989801", "type": "phone"}, "amount": 230.45, "closeAt": "2021-02-28"},
{ "name": "Test Name 2", "website": {"value": "testname2.com", "type": "url"}, "phone": {"value": "09898989802", "type": "phone"}, "amount": 240.5, "closeAt": "2021-01-28" },
{ "name": "Test Name 3", "website": {"value": "testname3.com", "type": "url"}, "phone": {"value": "09898989803", "type": "phone"}, "amount": 250.65, "closeAt": "2021-03-28" },
{ "name": "Test Name 4", "website": {"value": "testname4.com", "type": "url"}, "phone": {"value": "09898989804", "type": "phone"}, "amount": 260.4, "closeAt": "2021-02-28" },
{ "name": "Test Name 5", "website": {"value": "testname5.com", "type": "url"}, "phone": {"value": "09898989805", "type": "phone"}, "amount": 270, "closeAt": "2021-01-28" },
{ "name": "Test Name 6", "website": {"value": "testname6.com", "type": "url"}, "phone": {"value": "09898989806", "type": "phone"}, "amount": 280.45, "closeAt": "2021-03-28" },
{ "name": "Test Name 7", "website": {"value": "testname7.com", "type": "url"}, "phone": {"value": "09898989807", "type": "phone"}, "amount": 290.5, "closeAt": "2021-02-28" },
{ "name": "Test Name 8", "website": {"value": "testname8.com", "type": "url"}, "phone": {"value": "09898989808", "type": "phone"}, "amount": 130.65, "closeAt": "2021-01-28" },
{ "name": "Test Name 9", "website": {"value": "testname9.com", "type": "url"}, "phone": {"value": "09898989809", "type": "phone"}, "amount": 330.4, "closeAt": "2021-03-28" },
{ "name": "Test Name 10", "website": {"value": "testname10.com", "type": "url"}, "phone": {"value": "09898989810", "type": "phone"}, "amount": 430, "closeAt": "2021-02-28" },
];
this.globalActions = [
{label: "Delete", type: "delete"},
{label: "Hide", type: "hide"},
{label: "Edit", type: "edit"}
];
this.showPaginationTable = true;
}
handleRowAction(event) {
alert("Row Action Fired!\nAction Name: " + event.detail.actionName + "\nRow: " + JSON.stringify(event.detail.row));
}
handleGlobalAction(event) {
alert("Global Action Fired!\nAction Type: " + event.detail.actionType + "\nSelected Rows: " + JSON.stringify(event.detail.selectedRows));
}
handleSave(event) {
alert("Inline Edit Save Action Fired!\Draft Values: " + JSON.stringify(event.detail.draftValues));
}
}
html code is as follows
<template>
<div class="demoContainer">
<h2 class="slds-text-heading_medium slds-var-m-vertical_medium">Enhanced Pagination Datatable - With Array of Map</h2>
<template if:true={showPaginationTable}>
<c-pagination-datatable-full structure-type="3" table-data={data} rows-per-page="10" insert-numbered-column="true" show-page-numbers="true"
first-last-buttons="true" previous-next-buttons="true" numbered-buttons="true" show-filters="true"
max-number-of-index-buttons="5" dynamic-rows-per-page="true" onrowaction={handleRowAction}
global-actions={globalActions} onglobalaction={handleGlobalAction} onsave={handleSave}>
</c-pagination-datatable-full>
</template>
</div>
</template>
-
- jagadeep k
- March 03, 2022
- Like
- 0
Add checkbox to nested array in lwc
Here is my js code for the component
import { LightningElement,api } from 'lwc';
export default class testPaginationNestedArray extends LightningElement {
data = [];
globalActions = [];
columns = [];
keyField;
showPaginationTable = false;
connectedCallback() {
const actions = [
{ label: 'Show details', name: 'show_details' },
{ label: 'Delete', name: 'delete' },
];
this.columns = ["Name", "Website", "Phone", "Amount", "Close At"];
this.data = [
["Test Name 1", {"value": "testname1.com", "type": "url"}, {"value": "09898989801", "type": "phone"}, 230.45, "2021-02-28" ],
["Test Name 2", {"value": "testname2.com", "type": "url"}, {"value": "09898989802", "type": "phone"}, 240.5, "2021-01-28" ],
["Test Name 3", {"value": "testname3.com", "type": "url"}, {"value": "09898989803", "type": "phone"}, 250.65, "2021-03-28" ],
["Test Name 4", {"value": "testname4.com", "type": "url"}, {"value": "09898989804", "type": "phone"}, 260.4, "2021-02-28" ],
["Test Name 5", {"value": "testname5.com", "type": "url"}, {"value": "09898989805", "type": "phone"}, 270, "2021-01-28" ],
["Test Name 6", {"value": "testname6.com", "type": "url"}, {"value": "09898989806", "type": "phone"}, 280.45, "2021-03-28" ],
["Test Name 7", {"value": "testname7.com", "type": "url"}, {"value": "09898989807", "type": "phone"}, 290.5, "2021-02-28" ],
["Test Name 8", {"value": "testname8.com", "type": "url"}, {"value": "09898989808", "type": "phone"}, 130.65, "2021-01-28" ],
["Test Name 9", {"value": "testname9.com", "type": "url"}, {"value": "09898989809", "type": "phone"}, 330.4, "2021-03-28" ],
["Test Name 10", {"value": "testname10.com", "type": "url"}, {"value": "09898989810", "type": "phone"}, 430, "2021-02-28" ]
];
this.globalActions = [
{label: "Delete", type: "delete"},
{label: "Hide", type: "hide"},
{label: "Edit", type: "edit"}
];
this.keyField=true;
this.showPaginationTable = true;
}
handleRowAction(event) {
alert("Row Action Fired!\nAction Name: " + event.detail.actionName + "\nRow: " + JSON.stringify(event.detail.row));
}
handleGlobalAction(event) {
alert("Global Action Fired!\nAction Type: " + event.detail.actionType + "\nSelected Rows: " + JSON.stringify(event.detail.selectedRows));
}
handleSave(event) {
alert("Inline Edit Save Action Fired!\Draft Values: " + JSON.stringify(event.detail.draftValues));
}
}
Here is my html code for the component
<template>
<div class="demoContainer">
<h2 class="slds-text-heading_medium slds-var-m-bottom_medium">Pagination Datatable - With data structure type of
nested array Enhanced</h2>
<template if:true={showPaginationTable}>
<c-pagination-datatable-full structure-type="2" table-columns={columns} table-data={data} key-field={keyField}
rows-per-page="10" insert-numbered-column="true" show-page-numbers="true" first-last-buttons="true"
previous-next-buttons="true" numbered-buttons="true" show-filters="true" max-number-of-index-buttons="5"
dynamic-rows-per-page="true" onrowaction={handleRowAction} show-checkbox-column="true"
global-actions={globalActions} onglobalaction={handleGlobalAction} onsave={handleSave} >
</c-pagination-datatable-full>
</template>
</div>
</template>
-
- jagadeep k
- March 03, 2022
- Like
- 0
how to increase code coverage to more than 80% for my Apex class
public class lmiController {
//Get User's Role
public Boolean isASM{get;set;}
public Boolean isPDM{get;set;}
public Boolean isAssocPDM{get;set;}
public Boolean isASR{get;set;}
public Boolean isISR{get;set;}
public Boolean isManager{get;set;}
/*public PostalCodeWrapper[] cityList{get;set;}
public ListingWrapper[] listings{get;set;}*/
public Decimal totalPop{get;set;}
public Decimal websiteVisits{get;set;}
public Decimal avgCycles{get;set;}
public Integer accountTotal{get;set;}
public String jsonStr{get;set;}
public Transient String availableCities{get;set;}
public Transient String availableCounties{get;set;}
public String selectedCities{get;set;}
public String selectedCitiesFromCounty{get;set;}
public Transient Postal_Code__c[] fullPostalCodes{get;set;}
public Transient Set<Id> pcIds{get;set;}
public Boolean disableAddAll{get;set;}
public Boolean autoLoad{get;set;}
//Get url hacked user's first and last name
//public List<User> userFirstName{get;set;}
//public List<User> userLastName{get;set;}
//If user has employees, list here
public List<User> employeeList {set;get;}
public static Map<String, String> canadaStateMap = new Map<String, String>{
'Alberta' => 'AB',
'British Columbia' => 'BC',
'Manitoba' => 'MB',
'New Brunswick' => 'NB',
'Newfoundland and Labrodor' => 'NL',
'Nova Scotia' => 'NS',
'Northwest Territories' => 'NT',
'Nunavut' => 'NU',
'Ontario' => 'ON',
'Prince Edward Island' => 'PE',
'Quebec' => 'QC',
'Saskatchewan' => 'SK',
'Yukon' => 'YT',
'AB' => 'AB',
'BC' => 'BC',
'MB' => 'MB',
'NB' => 'NB',
'NL' => 'NL',
'NS' => 'NS',
'NT' => 'NT',
'NU' => 'NU',
'ON' => 'ON',
'PE' => 'PE',
'QC' => 'QC',
'SK' => 'SK',
'YT' => 'YT'
};
public static Map<String, String> canadaStateMapReversed = new Map<String, String>{
'AB' => 'Alberta',
'BC' => 'British Columbia',
'MB' => 'Manitoba',
'NB' => 'New Brunswick',
'NL' => 'Newfoundland and Labrodor',
'NS' => 'Nova Scotia',
'NT' => 'Northwest Territories',
'NU' => 'Nunavut',
'ON' => 'Ontario',
'PE' => 'Prince Edward Island',
'QC' => 'Quebec',
'SK' => 'Saskatchewan',
'YT' => 'Yukon'
};
//Count number of cities
public Integer cityCount{get;set;}
//public Integer pagination{get;set;}
public String toolUserId{get;set;}
public List<User> userFirstLastName{get;set;}
public Set<String> stateFilters = new Set<String>{'CO', 'WY', 'MT', 'ID', 'WA', 'OR', 'UT', 'NV', 'CA', 'AK','HI', 'TX', 'OK', 'NM', 'AZ', 'IA', 'KS', 'NE', 'SD', 'ND',
'OH', 'IN', 'MI', 'IL', 'MO', 'WI', 'MN', 'PA', 'ME', 'MA', 'RI', 'CT', 'NH', 'VT', 'DE', 'MD', 'NY', 'NJ', 'WV', 'VA',
'KY', 'TN', 'NC', 'SC', 'GA', 'MS', 'AR', 'LA', 'AL', 'FL', 'DC', 'PR'};
public Set<String> canadaStateFilters = new Set<String>{'Alberta', 'AB','British Columbia', 'BC','Manitoba', 'MB','New Brunswick', 'NB','Newfoundland and Labrodor',
'NL','Nova Scotia', 'NS','Northwest Territories', 'NT','Nunavut', 'NU','Ontario', 'ON','Prince Edward Island',
'PE','Quebec', 'QC','Saskatchewan', 'SK','Yukon', 'YT'};
//Regions:
//Northeast: ME, MA, RI, CT, NH, VT, NY, PA, NJ, DE, MD
//Southeast: WV, VA, KY, TN, NC, SC, GA, AL, MS, AR, LA, FL
//Midwest: OH, IN, MI, IL, MO, WI, MN, IA, KS, NE, SD, ND
//Southwest: TX, OK, NM, AZ
//West: CO, WY, MT, ID, WA, OR, UT, NV, CA, AK, HI
public void cityResults(){
disableAddAll = false;
selectedCities = '';
toolUserId = ApexPages.CurrentPage().getParameters().get('id');
autoLoad = ApexPages.currentPage().getParameters().get('autoLoad') == 'true';
if (toolUserId == null) {
toolUserId = UserInfo.getUserid();
}
userFirstLastName = [select FirstName, LastName from User where id = :toolUserId LIMIT 1];
employeeList = [SELECT Id,FirstName,LastName from User WHERE isActive = true AND ManagerId = :toolUserId];
if (!employeeList.isEmpty()) {
isManager = true;
}
/*cityList = new PostalCodeWrapper[]{};
listings = new ListingWrapper[]{};*/
fullPostalCodes = new Postal_Code__c[]{};
Locator_Listing__c[] fullListings;
//If user is an ASM
fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Area_Sales_Manager__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
if(!fullPostalCodes.isEmpty()) {
isASM = true;
isASR = false;
isPDM = false;
isAssocPDM = false;
isISR = false;
} else {
isASM = false;
}
//If user is an ASR
if(fullPostalCodes.isEmpty()){
fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Area_Sales_Rep__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
if(!fullPostalCodes.isEmpty()) {
isASM = false;
isASR = true;
isPDM = false;
isAssocPDM = false;
isISR = false;
} else {
isASR = false;
}
}
//If user is a PDM
if(fullPostalCodes.isEmpty()){
fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Practice_Development_Manager__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
if(!fullPostalCodes.isEmpty()) {
isASM = false;
isASR = false;
isPDM = true;
isAssocPDM = false;
isISR = false;
} else {
isPDM = false;
}
}
//If user is a PDM Associate
if(fullPostalCodes.isEmpty()){
fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Level_1_Practice_Development_Manager__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
if(!fullPostalCodes.isEmpty()) {
isASM = false;
isASR = false;
isPDM = false;
isAssocPDM = true;
isISR = false;
} else {
isAssocPDM = false;
}
}
//If user is a ISR
if(fullPostalCodes.isEmpty()){
fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Inside_Sales_Rep__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
if(!fullPostalCodes.isEmpty()) {
isASM = false;
isASR = false;
isPDM = false;
isAssocPDM = false;
isISR = true;
} else {
isISR = false;
}
}
if(fullPostalCodes.isEmpty()){
disableAddAll = true;
fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
}
pcIds = new Map<Id, Postal_Code__c>(fullPostalCodes).keySet();
Set<String> available = new Set<String>();
Set<String> availableCounts = new Set<String>();
for(Postal_Code__c pc : fullPostalCodes){
if(String.isNotBlank(pc.City__c) && String.isNotBlank(pc.State_Province__c)){
String state = pc.Country_Name__c == 'Canada' ? canadaStateMap.get(pc.State_Province__c) : pc.State_Province__c;
available.add(pc.City__c + ' ' + state);
if(String.isNotBlank(pc.County__c))
availableCounts.add(pc.County__c + ' County ' + state);
}
}
String[] av = new String[]{};
av.addAll(available);
String[] avCounties = new String[]{};
avCounties.addAll(availableCounts);
availableCities = String.join(av,',');
availableCounties = String.join(avCounties, ',');
totalPop = 0;
websiteVisits = 0;
accountTotal = 0;
if(autoLoad && av.size() < 10000){
prepAggregateData(availableCities);
}else{
autoLoad = false;
}
System.debug(disableAddAll);
}
public void prepAggregateData(){
try{
totalPop = 0;
websiteVisits = 0;
accountTotal = 0;
avgCycles = -1;
String[] cityFilterPre = selectedCities.split(',');
String[] cityFilter = new String[]{};
String[] stateFilter = new String[]{};
String[] countyFilters = new String[]{};
String[] countyStateFilters = new String[]{};
Set<String> countyCityFilters = new Set<String>();
for(String city : cityFilterPre){
if(city.toLowerCase().contains('county')){
Integer i = city.toLowerCase().indexOf('county');
String c = city.substring(0, i);
String state = city.substring(i + 6, city.length());
countyFilters.add(c.trim());
countyStateFilters.add(state.trim());
if(canadaStateMapReversed.containsKey(state.trim()))
countyStateFilters.add(canadaStateMapReversed.get(state.trim()));
}else{
Integer i = city.lastIndexOf(' ');
String c = city.substring(0, i);
String state = city.substring(i, city.length());
cityFilter.add(c.trim());
stateFilter.add(state.trim());
if(canadaStateMapReversed.containsKey(state.trim()))
stateFilter.add(canadaStateMapReversed.get(state.trim()));
}
}
if(!countyFilters.isEmpty()){
Postal_Code__c[] pcs = [SELECT Id, City__c, State_Province__c FROM Postal_Code__c WHERE County__c IN :countyFilters AND State_Province__c IN :countyStateFilters];
String[] selCitiesFromCounty = new String[]{};
for(Postal_Code__c pc : pcs){
countyCityFilters.add(pc.City__c.trim());
selCitiesFromCounty.add(pc.City__c.trim() + ' ' + pc.State_Province__c);
}
cityFilter.addAll(countyCityFilters);
stateFilter.addAll(countyStateFilters);
String[] selCities = String.isBlank(selectedCities) ? new String[]{} : selectedCities.split(',');
// selCities.addAll(selCitiesFromCounty);
selectedCities = String.join(selCities, ',');
selectedCitiesFromCounty = String.join(selCitiesFromCounty, ',');
}
System.debug(cityFilter);
System.debug(countyStateFilters);
Integer sizeBlock = cityFilter.size()/200 + (math.mod(cityFilter.size(),200)!=0?1:0);
Set<String> theseIds = new Set<String>();
String pcString = ApexPages.currentPage().getParameters().get('pcIds');
String[] pcs = new String[]{};
if(pcIds == null){
if(pcString.length() > 500000){
for(Integer i = pcString.length() / 2; i < pcString.length(); i++){
if(pcString.charAt(i) == ','.charAt(0)){
String firstHalf = pcString.substring(0, i);
String secondHalf = pcString.substring(i + 1, pcString.length() - 1);
pcs.addAll(firstHalf.split(','));
pcs.addAll(secondHalf.split(','));
break;
}
}
}else{
pcs.addAll(pcString.split(','));
}
theseIds.addAll(pcs);
}
for(Integer i = 0; i < sizeBlock; i++){
Decimal tempCycles = 0;
AggregateResult[] res = [SELECT City__c city, MAX(X2020_CS_Website_Visitors__c) siteVisits, SUM(X2010_Census_Population__c) pop, AVG(Avg_Monthly_Cycles_per_Territory__c) cycles FROM Postal_Code__c WHERE (City__c IN :cityFilter) AND State_Province__c IN :stateFilter GROUP BY City__c, State_Province__c LIMIT 200];
if(res.isEmpty())
continue;
for(AggregateResult r : res){
Integer cityInt = cityFilter.indexOf((String)r.get('city'));
if(cityInt != -1)
cityFilter.remove(cityInt);
totalPop += ((Decimal)r.get('pop') == null ? 0 : (Decimal)r.get('pop') * 0.65);
websiteVisits += ((Decimal)r.get('siteVisits') == null ? 0 : (Decimal)r.get('siteVisits'));
tempCycles += ((Decimal)r.get('cycles') == null ? 0 : (Decimal)r.get('cycles'));
}
avgCycles += tempCycles / res.size();
}
System.debug(avgCycles);
System.debug(sizeBlock);
avgCycles = Math.round(avgCycles / sizeBlock);
if(avgCycles == -1)
avgCycles = 0;
cityFilterPre = selectedCities.split(',');
cityFilter = new String[]{};
stateFilter = new String[]{};
if(!countyCityFilters.isEmpty())
cityFilter.addAll(countyCityFilters);
for(String city : cityFilterPre){
if(city.toLowerCase().contains('county')){
Integer i = city.toLowerCase().indexOf('county');
String c = city.substring(0, i);
String state = city.substring(i + 5, city.length());
cityFilter.add(c.trim());
stateFilter.add(state.trim());
if(canadaStateMapReversed.containsKey(state.trim()))
stateFilter.add(canadaStateMapReversed.get(state.trim()));
}else{
Integer i = city.lastIndexOf(' ');
String c = city.substring(0, i);
String state = city.substring(i, city.length());
cityFilter.add(c.trim());
stateFilter.add(state.trim());
if(canadaStateMapReversed.containsKey(state.trim()))
stateFilter.add(canadaStateMapReversed.get(state.trim()));
}
}
System.debug('\'' + String.join(cityFilter, '\',\'') + '\'');
Boolean pageNameCooltone = ApexPages.currentPage().getURL().toLowerCase().contains('cooltone');
String activeField = pageNameCooltone ? 'CoolTone_Active__c' : 'CoolSculpting_Active__c';
String locQuery = 'SELECT COUNT(Account__c) accCount FROM Locator_Listing__c WHERE (City__c IN :cityFilter) AND ((Country__c = \'United States of America\' AND State_ProvidenceRegion__c IN :stateFilters) OR Country__c = \'Canada\') AND Active__c = true AND ' + activeField + ' = true';
System.debug(locQuery);
AggregateResult fullListings = Database.query(locQuery);
accountTotal = (Integer)fullListings.get('accCount');
}catch(Exception e){
System.debug(e.getMessage() + ' Line: ' + e.getLineNumber());
}
}
public void prepAggregateData(String sel){
try{
totalPop = 0;
websiteVisits = 0;
accountTotal = 0;
avgCycles = -1;
String[] cityFilter = new String[]{};
for(String s : sel.split(','))
cityFilter.add(s.substring(0, s.lastIndexOf(' ')));
Integer sizeBlock = cityFilter.size()/200 + (math.mod(cityFilter.size(),200)!=0?1:0);
for(Integer i = 0; i < sizeBlock; i++){
Decimal tempCycles = 0;
AggregateResult[] res = [SELECT City__c city, MAX(X2020_CS_Website_Visitors__c) siteVisits, SUM(X2010_Census_Population__c) pop, AVG(Avg_Monthly_Cycles_per_Territory__c) cycles FROM Postal_Code__c WHERE Id IN :pcIds AND City__c IN :cityFilter GROUP BY City__c LIMIT 200];
for(AggregateResult r : res){
Integer cityInt = cityFilter.indexOf((String)r.get('city'));
if(cityInt != -1)
cityFilter.remove(cityInt);
totalPop += ((Decimal)r.get('pop') == null ? 0 : (Decimal)r.get('pop'));
websiteVisits += ((Decimal)r.get('siteVisits') == null ? 0 : (Decimal)r.get('siteVisits'));
tempCycles += ((Decimal)r.get('cycles') == null ? 0 : (Decimal)r.get('cycles'));
}
avgCycles += tempCycles / res.size();
}
avgCycles = Math.round(avgCycles / sizeBlock);
totalPop = totalPop * 0.65;
if(avgCycles == -1)
avgCycles = 0;
cityFilter = new String[]{};
for(String s : sel.split(','))
cityFilter.add(s.substring(0, s.lastIndexOf(' ')));
Boolean pageNameCooltone = ApexPages.currentPage().getURL().toLowerCase().contains('cooltone');
String activeField = pageNameCooltone ? 'CoolTone_Active__c' : 'CoolSculpting_Active__c';
String locQuery = 'SELECT COUNT(Account__c) accCount FROM Locator_Listing__c WHERE (City__c IN :cityFilter OR County__c IN :cityFilter) AND ((Country__c = \'United States of America\' AND State_ProvidenceRegion__c IN :stateFilters) OR Country__c = \'Canada\') AND Active__c = true AND ' + activeField + ' = true';
System.debug(ApexPages.currentPage().getURL().toLowerCase());
System.debug(activeField);
System.debug(locQuery);
AggregateResult fullListings = Database.query(locQuery);
accountTotal = (Integer)fullListings.get('accCount');
}catch(Exception e){
System.debug(e.getMessage() + ' Line: ' + e.getLineNumber());
}
}
@RemoteAction
public static List<Map<String, String>> searchPractices(String term){
List<Map<String, String>> results = new List<Map<String, String>>();
String preppedTerm = '%' + String.escapeSingleQuotes(term) + '%';
Account[] accs =
[SELECT Id, Name, Lifetime_Utilization__c
FROM Account
WHERE Type = 'Practice - Active'
AND
(Name LIKE :preppedTerm
OR AGN_Location_ID__c LIKE :preppedTerm
OR AGN_Account__c LIKE :preppedTerm)
LIMIT 10];
for(Account acc : accs){
results.add(new Map<String, String>{'label' => acc.Name, 'value' => acc.Name, 'cycles' => acc.Lifetime_Utilization__c != null ? String.valueOf(acc.Lifetime_Utilization__c) : null});
}
return results;
}
}
-
- jagadeep k
- July 28, 2021
- Like
- 0
how to increase code coverage for my apex test class code coverage to more than 80%
/*
01/19/18 BE@IC Created test class (00156299)
*/
@isTest
public with sharing class lmiControllerTest {
public static testMethod void testControllerASM(){
Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
'ASM' => true,
'ASR' => false,
'PDM' => false,
'PDMA' => false,
'ISR' => false
};
String roleString = 'ASM';
createSettings();
User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
User u;
List<User> employeeUsers;
// Avoid Mixed DML Operation Error
System.runAs(thisUser) {
u = createUser();
insert u;
employeeUsers = createEmployeeUsers(10,u.Id);
insert employeeUsers;
}
Account a = createAccount();
insert a;
Locator_Listing__c ll = createLocatorListing(a.Id);
insert ll;
Test.startTest();
Postal_Code__c pc = createPostalCode(u.Id,roleString);
insert pc;
LMIController ctrl = resetController(u.Id);
ctrl.cityResults();
testLocatorListings(ctrl, ll, roleString);
testRoles(ctrl,roleCheckMap, roleString);
testCityListUsers(ctrl,pc, roleString);
ctrl.selectedCities = 'TestCnty County';
ctrl.prepAggregateData();
delete pc;
Test.stopTest();
ctrl = resetController();
ctrl.cityResults();
System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
}
public static testMethod void testControllerASR(){
Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
'ASM' => false,
'ASR' => true,
'PDM' => false,
'PDMA' => false,
'ISR' => false
};
String roleString = 'ASR';
createSettings();
User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
User u;
List<User> employeeUsers;
// Avoid Mixed DML Operation Error
System.runAs(thisUser) {
u = createUser();
insert u;
employeeUsers = createEmployeeUsers(10,u.Id);
insert employeeUsers;
}
Account a = createAccount();
insert a;
Locator_Listing__c ll = createLocatorListing(a.Id);
insert ll;
Test.startTest();
Postal_Code__c pc = createPostalCode(u.Id,roleString);
insert pc;
LMIController ctrl = resetController(u.Id);
ctrl.cityResults();
testLocatorListings(ctrl, ll, roleString);
testRoles(ctrl,roleCheckMap, roleString);
testCityListUsers(ctrl,pc, roleString);
delete pc;
Test.stopTest();
ctrl = resetController();
ctrl.cityResults();
ctrl.prepAggregateData();
System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
}
public static testMethod void testControllerPDM(){
Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
'ASM' => false,
'ASR' => false,
'PDM' => true,
'PDMA' => false,
'ISR' => false
};
String roleString = 'PDM';
createSettings();
User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
User u;
List<User> employeeUsers;
// Avoid Mixed DML Operation Error
System.runAs(thisUser) {
u = createUser();
insert u;
employeeUsers = createEmployeeUsers(10,u.Id);
insert employeeUsers;
}
Account a = createAccount();
insert a;
Locator_Listing__c ll = createLocatorListing(a.Id);
insert ll;
Test.startTest();
Postal_Code__c pc = createPostalCode(u.Id,roleString);
insert pc;
LMIController ctrl = resetController(u.Id);
ctrl.cityResults();
testLocatorListings(ctrl, ll, roleString);
testRoles(ctrl,roleCheckMap, roleString);
testCityListUsers(ctrl,pc, roleString);
delete pc;
Test.stopTest();
ctrl = resetController();
ctrl.cityResults();
System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
}
public static testMethod void testControllerPDMA(){
Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
'ASM' => false,
'ASR' => false,
'PDM' => false,
'PDMA' => true,
'ISR' => false
};
String roleString = 'PDMA';
createSettings();
User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
User u;
List<User> employeeUsers;
// Avoid Mixed DML Operation Error
System.runAs(thisUser) {
u = createUser();
insert u;
employeeUsers = createEmployeeUsers(10,u.Id);
insert employeeUsers;
}
Account a = createAccount();
insert a;
Locator_Listing__c ll = createLocatorListing(a.Id);
insert ll;
Test.startTest();
Postal_Code__c pc = createPostalCode(u.Id,roleString);
insert pc;
PageReference pageRef = Page.lmiTool2;
Test.setCurrentPage(pageRef);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(pc);
ApexPages.currentPage().getParameters().put('Id',u.id);
// LMIController ctrl1 = new LMIController(sc);
LMIController ctrl = resetController(u.Id);
// String term;
ctrl.prepAggregateData();
// ctrl.searchPractices(term);
ctrl.cityResults();
testLocatorListings(ctrl, ll, roleString);
testRoles(ctrl,roleCheckMap, roleString);
testCityListUsers(ctrl,pc, roleString);
delete pc;
Test.stopTest();
ctrl = resetController();
ctrl.cityResults();
System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
}
public static testMethod void testControllerISR(){
Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
'ASM' => false,
'ASR' => false,
'PDM' => false,
'PDMA' => false,
'ISR' => true
};
String roleString = 'ISR';
createSettings();
User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
User u;
List<User> employeeUsers;
// Avoid Mixed DML Operation Error
System.runAs(thisUser) {
u = createUser();
insert u;
employeeUsers = createEmployeeUsers(10,u.Id);
insert employeeUsers;
}
Account a = createAccount();
insert a;
Locator_Listing__c ll = createLocatorListing(a.Id);
insert ll;
Test.startTest();
Postal_Code__c pc = createPostalCode(u.Id,roleString);
insert pc;
PageReference pageRef = Page.lmiTool2;
Test.setCurrentPage(pageRef);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(pc);
ApexPages.currentPage().getParameters().put('Id',u.id);
// lmiController lc = new lmiController(sc);
LMIController ctrl = resetController(u.Id);
ctrl.prepAggregateData();
ctrl.cityResults();
testLocatorListings(ctrl, ll, roleString);
testRoles(ctrl,roleCheckMap, roleString);
testCityListUsers(ctrl,pc, roleString);
delete pc;
Test.stopTest();
ctrl = resetController();
ctrl.cityResults();
System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
}
// For the case of this test class, we are only using Colorado (CO), a Western state in the US.
private static void testLocatorListings(LMIController ctrl, Locator_Listing__c ll, String currentRoleString) {
String roleString = 'Testing role: ' + currentRoleString;
String locQuery ='SELECT COUNT(Account__c) accCount FROM Locator_Listing__c WHERE (City__c=\'Test\') AND ((Country__c = \'United States of America\' AND State_ProvidenceRegion__c=\'CO\') OR Country__c = \'Canada\') AND Active__c = true AND CoolTone_Active__c = true';
ctrl.prepAggregateData();
// System.assertEquals(1,ctrl.accountTotal, roleString);
}
private static void testRoles(LMIController ctrl, Map<String,Boolean> roleCheckMap, String currentRoleString) {
String roleString = 'Testing role: ' + currentRoleString;
System.assertEquals(roleCheckMap.get('ASM'),ctrl.isASM, roleString);
System.assertEquals(roleCheckMap.get('ASR'),ctrl.isASR, roleString);
System.assertEquals(roleCheckMap.get('PDM'),ctrl.isPDM, roleString);
System.assertEquals(roleCheckMap.get('PDMA'),ctrl.isAssocPDM, roleString);
System.assertEquals(roleCheckMap.get('ISR'),ctrl.isISR,roleString);
System.assertEquals(true, ctrl.isManager, roleString);
}
// For the case of this test class, we are only using Colorado (CO), a Western state in the US.
private static void testCityListUsers(LmiController ctrl, Postal_Code__c pc, String currentRoleString) {
ctrl.prepAggregateData();
String roleString = 'Testing role: ' + currentRoleString;
System.assertEquals(1,ctrl.fullPostalCodes.size(), roleString);
// System.assertEquals(500001,ctrl.fullPostalCodes.size(), roleString);
}
private static lmiController resetController() {
PageReference p = new PageReference('Page.lmiTool2');
p.getParameters().put('autoLoad', 'true');
Test.setCurrentPageReference(p);
System.currentPageReference().getParameters().remove('id');
return new LMIController();
}
private static LMIController resetController(Id userId) {
PageReference p = new PageReference('Page.lmiTool2');
p.getParameters().put('autoLoad', 'true');
Test.setCurrentPageReference(p);
System.currentPageReference().getParameters().put('id', userId);
return new LMIController();
}
private static User createUser() {
return new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
FirstName = 'Zeltiq',
LastName = 'TestUser',
Email = 'ZeltiqTest@Test.com',
Username = 'ZeltiqTest@Test.com' + System.currentTimeMillis(),
CompanyName = 'ZeltiqTest',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US'
);
}
private static List<User> createEmployeeUsers(Integer amount, Id managerUserId) {
Id sysAdminId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id;
List<User> employees = new List<User>();
for(Integer i = 0; i < amount; i++) {
employees.add(new User(
ProfileId = sysAdminId,
FirstName = 'Zeltiq',
LastName = 'Employee ' + i,
Email = 'ZeltiqTest' + i + '@Test.com',
Username = 'ZeltiqTest' + i + '@Test.com' + System.currentTimeMillis(),
CompanyName = 'ZeltiqTest',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ManagerId = managerUserId
));
}
return employees;
}
private static Postal_Code__c createPostalCode(Id userId, String userField) {
// List<Postal_Code__c> res = [SELECT City__c city, MAX(X2020_CS_Website_Visitors__c) siteVisits, SUM(X2010_Census_Population__c) pop, AVG(Avg_Monthly_Cycles_per_Territory__c) cycles FROM Postal_Code__c WHERE City__c='Test' AND State_Province__c='CO' GROUP BY City__c, State_Province__c LIMIT 200];
Postal_Code__c pc = new Postal_Code__c(
Country_Name__c = 'United States America',
Name = '12345',
State_Province__c = 'CO',
X2020_CS_Website_Visitors__c = 10,
X2010_Census_Population__c = 10,
// Avg_Monthly_Cycles_per_Territory__c =10,
City__c = 'Test',
County__c = 'TestCnty'
);
if(userField == 'ASM') {
pc.Area_Sales_Manager__c = userId;
}
else if(userField == 'ASR') {
pc.Area_Sales_Rep__c = userId;
}
else if(userField == 'PDM') {
pc.Practice_Development_Manager__c = userId;
}
else if(userField == 'PDMA') {
pc.Level_1_Practice_Development_Manager__c = userId;
}
else if(userField == 'ISR') {
pc.Inside_Sales_Rep__c = userId;
}
return pc;
}
private static Account createAccount() {
return new Account(
Name = 'Test Account',
External_ID__c = '12345',
Type = 'Practice - Active',
Lifetime_Utilization__c=10,
AGN_Location_ID__c='TestLoc'
);
}
private static Locator_Listing__c createLocatorListing(Id accountId) {
Locator_Listing__c[] listings = new Locator_Listing__c[]{};
return new Locator_Listing__c(
Name = 'Test Locator Listing',
Account__c = accountId,
State_ProvidenceRegion__c = 'CO',
Country__c = 'United States of America',
City__c = 'Test',
Active__c = true
);
}
private static void createSettings() {
Apex_Code_Settings__c testCustomSettings = new Apex_Code_Settings__c();
testCustomSettings.GooglePrivateKey__c = 'a3--l2CjL5iGR6tOOnQrMOM5Ics=';
testCustomSettings.GoogleClientID__c = 'gme-allerganinc';
insert testCustomSettings;
}
}
-
- jagadeep k
- July 28, 2021
- Like
- 0
how to add 10 records of an aibject to 3 logged in users using apex
I am having a policy object which is having10 records and I need to assign these 10 records to logged in users for example if there are 3 users I need to distribute these 10 records among those 3 users.
-
- jagadeep k
- May 18, 2021
- Like
- 0
The 'Calculate Discount' custom button isn't properly configured. Check the instructions for how to configure the Display Type and URL.
-
- jagadeep k
- May 14, 2019
- Like
- 0
Build a welcome bot for slack
When trying to verify server on my end I'm getting the following error
C:\Users\Jagadeep\Desktop\first-slack-app\node_modules\.bin\slack-verify:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^
SyntaxError: missing ) after argument list
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:279:19)
C:\Users\Jagadeep\Desktop\first-slack-app\node_modules\.bin\slack-verify:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^
SyntaxError: missing ) after argument list
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:279:19)
-
- jagadeep k
- September 27, 2018
- Like
- 0
Create Alexa Skills and Lambda Functions with the ASK CLI
after installing node.js when i am running the command ask deploy i am getting the following error
Profile for the deployment: [default]
Skill Id: amzn1.ask.skill.f0439ae9-befa-4ece-a4c7-293f30e1669f
Skill deployment finished.
Call update-model error.
Error code: 400
{
"message": "Interaction model is not valid.",
"violations": [
{
"message": "InvalidSlotTypeName: Slot type name \"AMAZON.SearchQuery\" is invalid. The name of a custom slot type must begin with an alphabetic character and can consist only of alphabetic characters or underscores."
}
]
}
How to solve this error
Profile for the deployment: [default]
Skill Id: amzn1.ask.skill.f0439ae9-befa-4ece-a4c7-293f30e1669f
Skill deployment finished.
Call update-model error.
Error code: 400
{
"message": "Interaction model is not valid.",
"violations": [
{
"message": "InvalidSlotTypeName: Slot type name \"AMAZON.SearchQuery\" is invalid. The name of a custom slot type must begin with an alphabetic character and can consist only of alphabetic characters or underscores."
}
]
}
How to solve this error
-
- jagadeep k
- May 29, 2018
- Like
- 1
Challenge Not yet complete... here's what's wrong: Ensure that you call the correct method from orderTrigger.
In Advanced Apex Specialist Challenge 2
Challenge Not yet complete... here's what's wrong: Ensure that you call the correct method from orderTrigger.
My Trigger and helper class code I am pasting it here
trigger orderTrigger on Order (after update) {
if(Trigger.new != null){
OrderHelper.AfterUpdate(Trigger.new,Trigger.old);
}
}
OrderHelper class
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for ( Integer i=0; i<newList.size(); i++ ){
if ((newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && newList[i].ActivatedDate != null)
&& oldList[i].Status == Constants.DRAFT_ORDER_STATUS){
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity
FROM OrderItem
WHERE OrderId In :activatedOrderIds];
for(OrderItem oi : items) {
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN :productIds]);
AggregateResult[] groupedResults = [SELECT Product2Id, SUM(Quantity) activatedQuantity
FROM OrderItem
WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : groupedResults) {
productMap.get((String) ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('activatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap!=null && productMap.size()>0){
update productMap.values();
}
}
}
Challenge Not yet complete... here's what's wrong: Ensure that you call the correct method from orderTrigger.
My Trigger and helper class code I am pasting it here
trigger orderTrigger on Order (after update) {
if(Trigger.new != null){
OrderHelper.AfterUpdate(Trigger.new,Trigger.old);
}
}
OrderHelper class
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for ( Integer i=0; i<newList.size(); i++ ){
if ((newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && newList[i].ActivatedDate != null)
&& oldList[i].Status == Constants.DRAFT_ORDER_STATUS){
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity
FROM OrderItem
WHERE OrderId In :activatedOrderIds];
for(OrderItem oi : items) {
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN :productIds]);
AggregateResult[] groupedResults = [SELECT Product2Id, SUM(Quantity) activatedQuantity
FROM OrderItem
WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : groupedResults) {
productMap.get((String) ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('activatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap!=null && productMap.size()>0){
update productMap.values();
}
}
}
-
- jagadeep k
- May 22, 2018
- Like
- 0
In Map Your Workflow Actions to Process Actions I'm unable to complete the challenge as it's throwing an error
Challenge Not yet complete... here's what's wrong:
We found an opportunity that's associated with a Banking account and updated the stage to Closed Won, but a task wasn't created for the account owner to complete 7 days from today. Make sure that the Closed Won and Banking criteria node and its associated action are configured correctly.

We found an opportunity that's associated with a Banking account and updated the stage to Closed Won, but a task wasn't created for the account owner to complete 7 days from today. Make sure that the Closed Won and Banking criteria node and its associated action are configured correctly.
-
- jagadeep k
- January 12, 2018
- Like
- 0
Create Alexa Skills and Lambda Functions with the ASK CLI
after installing node.js when i am running the command ask deploy i am getting the following error
Profile for the deployment: [default]
Skill Id: amzn1.ask.skill.f0439ae9-befa-4ece-a4c7-293f30e1669f
Skill deployment finished.
Call update-model error.
Error code: 400
{
"message": "Interaction model is not valid.",
"violations": [
{
"message": "InvalidSlotTypeName: Slot type name \"AMAZON.SearchQuery\" is invalid. The name of a custom slot type must begin with an alphabetic character and can consist only of alphabetic characters or underscores."
}
]
}
How to solve this error
Profile for the deployment: [default]
Skill Id: amzn1.ask.skill.f0439ae9-befa-4ece-a4c7-293f30e1669f
Skill deployment finished.
Call update-model error.
Error code: 400
{
"message": "Interaction model is not valid.",
"violations": [
{
"message": "InvalidSlotTypeName: Slot type name \"AMAZON.SearchQuery\" is invalid. The name of a custom slot type must begin with an alphabetic character and can consist only of alphabetic characters or underscores."
}
]
}
How to solve this error
-
- jagadeep k
- May 29, 2018
- Like
- 1
how to add 10 records of an aibject to 3 logged in users using apex
I am having a policy object which is having10 records and I need to assign these 10 records to logged in users for example if there are 3 users I need to distribute these 10 records among those 3 users.

- jagadeep k
- May 18, 2021
- Like
- 0
Create Alexa Skills and Lambda Functions with the ASK CLI
after installing node.js when i am running the command ask deploy i am getting the following error
Profile for the deployment: [default]
Skill Id: amzn1.ask.skill.f0439ae9-befa-4ece-a4c7-293f30e1669f
Skill deployment finished.
Call update-model error.
Error code: 400
{
"message": "Interaction model is not valid.",
"violations": [
{
"message": "InvalidSlotTypeName: Slot type name \"AMAZON.SearchQuery\" is invalid. The name of a custom slot type must begin with an alphabetic character and can consist only of alphabetic characters or underscores."
}
]
}
How to solve this error
Profile for the deployment: [default]
Skill Id: amzn1.ask.skill.f0439ae9-befa-4ece-a4c7-293f30e1669f
Skill deployment finished.
Call update-model error.
Error code: 400
{
"message": "Interaction model is not valid.",
"violations": [
{
"message": "InvalidSlotTypeName: Slot type name \"AMAZON.SearchQuery\" is invalid. The name of a custom slot type must begin with an alphabetic character and can consist only of alphabetic characters or underscores."
}
]
}
How to solve this error

- jagadeep k
- May 29, 2018
- Like
- 1
Challenge Not yet complete... here's what's wrong: Ensure that you call the correct method from orderTrigger.
In Advanced Apex Specialist Challenge 2
Challenge Not yet complete... here's what's wrong: Ensure that you call the correct method from orderTrigger.
My Trigger and helper class code I am pasting it here
trigger orderTrigger on Order (after update) {
if(Trigger.new != null){
OrderHelper.AfterUpdate(Trigger.new,Trigger.old);
}
}
OrderHelper class
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for ( Integer i=0; i<newList.size(); i++ ){
if ((newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && newList[i].ActivatedDate != null)
&& oldList[i].Status == Constants.DRAFT_ORDER_STATUS){
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity
FROM OrderItem
WHERE OrderId In :activatedOrderIds];
for(OrderItem oi : items) {
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN :productIds]);
AggregateResult[] groupedResults = [SELECT Product2Id, SUM(Quantity) activatedQuantity
FROM OrderItem
WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : groupedResults) {
productMap.get((String) ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('activatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap!=null && productMap.size()>0){
update productMap.values();
}
}
}
Challenge Not yet complete... here's what's wrong: Ensure that you call the correct method from orderTrigger.
My Trigger and helper class code I am pasting it here
trigger orderTrigger on Order (after update) {
if(Trigger.new != null){
OrderHelper.AfterUpdate(Trigger.new,Trigger.old);
}
}
OrderHelper class
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for ( Integer i=0; i<newList.size(); i++ ){
if ((newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && newList[i].ActivatedDate != null)
&& oldList[i].Status == Constants.DRAFT_ORDER_STATUS){
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity
FROM OrderItem
WHERE OrderId In :activatedOrderIds];
for(OrderItem oi : items) {
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN :productIds]);
AggregateResult[] groupedResults = [SELECT Product2Id, SUM(Quantity) activatedQuantity
FROM OrderItem
WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : groupedResults) {
productMap.get((String) ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('activatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap!=null && productMap.size()>0){
update productMap.values();
}
}
}

- jagadeep k
- May 22, 2018
- Like
- 0