I cannot resolve this error.
Closing a Maintenance Request of type 'Routine Maintenance' or 'Repair' did not create of a new Maintenance Request with the correct due date. The challenge is expecting the due date to be calculated using the maintenance cycle defined on the related equipment records. If multiple equipments are used in the maintenance request, choose the shortest maintenance cycle to define the service date.
I'm having a really hard time finishing this challenge. I want to know that which part of my code is wrong, not just answer.
// TriggerHandler
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(Map<Id, Case> oldCases) {
// TODO: Complete the method to update workorders
Map<Id, Integer> toGetDueDateMap = new Map<Id, Integer>();
AggregateResult[] results = [SELECT Id, MIN(Maintenance_Cycle__c) minMC FROM Product2 GROUP BY Id];
for (AggregateResult ar : results) {
if (ar != null) {
toGetDueDateMap.put(ar.Id, Integer.valueOf(ar.get('minMC')));
}
}
List<Case> newCases = new List<Case>();
for (Case c : oldCases.values()) {
Case newCase = new Case();
newCase.Status = 'New';
newCase.Origin = 'web';
newCase.Vehicle__c = c.Vehicle__c;
newCase.ProductId = c.ProductId;
newCase.Type = 'Routine Maintenance';
newCase.Subject = 'Routine Maintenance';
newCase.Date_Reported__c = Date.today();
newCase.Date_Due__c = (toGetDueDateMap.get(c.Id) != null) ? Date.today().addDays(toGetDueDateMap.get(c.Id)) : Date.today();
newCases.add(newCase);
}
insert newCases;
}
}
// Trigger
trigger MaintenanceRequest on Case (after update) {
// ToDo: Call MaintenanceRequestHelper.updateWorkOrders
Map<Id, Case> caseToEvaluate = new Map<Id, Case>();
if(Trigger.isAfter && Trigger.isUpdate) {
for(Case c : Trigger.New) {
if(c.Status == 'Closed' && (c.Type == 'Repair' || c.Type == 'Routine Maintenance')) {
caseToEvaluate.put(c.Id, c);
}
}
}
MaintenanceRequestHelper.updateWorkOrders(caseToEvaluate);
}
I create correct algoritm to find less maintenance cycle days.
Try it.
newCase.Date_Due__c = Date.today() + suchEarlyDay(newMaintenanceRequest).get(cases.Id);
newCases.add(newCase);
}
}
if (newCases.size() > 0) {
insert newCases;
}
}
private static Map<Id, Integer> suchEarlyDay(List<Case> cases) {
Map<Id, Case> caseMap = new Map<Id, Case>(cases);
Map<Id, Integer> lessDate = new Map<Id, Integer>();
List<Equipment_Maintenance_Item__c> relatedList = [
SELECT Maintenance_Request__c,
Equipment__r.Maintenance_Cycle__c
FROM Equipment_Maintenance_Item__c
WHERE Maintenance_Request__c = :caseMap.keySet()
];
for (Id caseId : caseMap.keySet()) {
for (Equipment_Maintenance_Item__c equip : relatedList) {
if (!lessDate.containsKey(caseId) && caseId == equip.Maintenance_Request__c) {
lessDate.put(caseId, (Integer) equip.Equipment__r.Maintenance_Cycle__c);
} else if (lessDate.containsKey(caseId) && lessDate.get(caseId) > (Integer) equip.Equipment__r.Maintenance_Cycle__c) {
lessDate.put(caseId, (Integer) equip.Equipment__r.Maintenance_Cycle__c);
}
}
}
return lessDate;
}
This link helped me, so I modified the code like this:
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<Case> updWorkOrders, Map<Id,Case> nonUpdCaseMap) {
Set<Id> validIds = new Set<Id>();
For (Case c : updWorkOrders){
if (nonUpdCaseMap.get(c.Id).Status != 'Closed' && c.Status == 'Closed'){
if (c.Type == 'Repair' || c.Type == 'Routine Maintenance'){
validIds.add(c.Id);
}
}
}
if (!validIds.isEmpty()){
List<Case> newCases = new List<Case>();
Map<Id,Case> closedCasesM = new Map<Id,Case>([SELECT Id, Vehicle__c, ProductId, Product.Maintenance_Cycle__c,(SELECT Id,Equipment__c,Quantity__c FROM Equipment_Maintenance_Items__r)
FROM Case WHERE Id IN :validIds]);
Map<Id,Decimal> maintenanceCycles = new Map<ID,Decimal>();
AggregateResult[] results = [SELECT Maintenance_Request__c, MIN(Equipment__r.Maintenance_Cycle__c)cycle FROM Equipment_Maintenance_Item__c WHERE Maintenance_Request__c IN :ValidIds GROUP BY Maintenance_Request__c];
for (AggregateResult ar : results){
maintenanceCycles.put((Id) ar.get('Maintenance_Request__c'), (Decimal) ar.get('cycle'));
}
for(Case cc : closedCasesM.values()){
Case nc = new Case (
ParentId = cc.Id,
Status = 'New',
Subject = 'Routine Maintenance',
Type = 'Routine Maintenance',
Vehicle__c = cc.Vehicle__c,
ProductId =cc.ProductId,
Origin = 'Web',
Date_Reported__c = Date.Today()
);
If (maintenanceCycles.containskey(cc.Id)){
nc.Date_Due__c = Date.today().addDays((Integer) maintenanceCycles.get(cc.Id));
} else {
nc.Date_Due__c = Date.today().addDays((Integer) cc.Product.maintenance_Cycle__c);
}
newCases.add(nc);
}
insert newCases;
List<Equipment_Maintenance_Item__c> clonedWPs = new List<Equipment_Maintenance_Item__c>();
for (Case nc : newCases){
for (Equipment_Maintenance_Item__c wp : closedCasesM.get(nc.ParentId).Equipment_Maintenance_Items__r){
Equipment_Maintenance_Item__c wpClone = wp.clone();
wpClone.Maintenance_Request__c = nc.Id;
ClonedWPs.add(wpClone);
}
}
insert ClonedWPs;
}
}
}
And the trigger:
trigger MaintenanceRequest on Case (before update, after update) {
if(Trigger.isUpdate && Trigger.isAfter){
MaintenanceRequestHelper.updateWorkOrders(Trigger.New, Trigger.OldMap);
} }
Apex Trigger :
trigger MaintenanceRequest on Case (before update, after update) {
// ToDo: Call MaintenanceRequestHelper.updateWorkOrders
if(Trigger.isAfter && Trigger.isUpdate){
MaintenanceRequestHelper.updateWorkOrders(Trigger.new);
}
}
Apex Handler:
public with sharing class MaintenanceRequestHelper {
public static void updateWorkOrders(List<Case> existingMainReq) {
// TODO: Complete the method to update workorders
Integer count = 0;
Map<Id, Integer> toGetDueDateMap = new Map<Id, Integer>();
Map<Id,Case> newCasesToIdsMap = new Map<Id,Case>();
List<Case> createNewMainReq = new List<Case>();
List<Case> caseIdsList = new List<Case>();
Map<Equipment_Maintenance_Item__c,Id> EquipMainItemsToProdIds = new Map<Equipment_Maintenance_Item__c,Id>();
if(!existingMainReq.isEmpty()){
for(Case cc : existingMainReq){
if((cc.Type == 'Repair' || cc.Type == 'Routine Maintenance') && cc.Status == 'Closed'){
caseIdsList.add(cc);
}
}
}
List<Equipment_Maintenance_Item__c> equipMainList = [Select id,Equipment__c,Maintenance_Request__c from Equipment_Maintenance_Item__c where Maintenance_Request__c IN : caseIdsList];
if(!equipMainList.isEmpty()){
for(Equipment_Maintenance_Item__c equipMainn : equipMainList){
EquipMainItemsToProdIds.put(equipMainn,equipMainn.Equipment__c);
system.debug(EquipMainItemsToProdIds.size());
if(EquipMainItemsToProdIds.size() > 1){
count = EquipMainItemsToProdIds.size();
}
}
}
List<Equipment_Maintenance_Item__c> EMIList = [Select Equipment__r.Maintenance_Cycle__c,Equipment__c from Equipment_Maintenance_Item__c where Equipment__r.Id IN :EquipMainItemsToProdIds.values() AND Maintenance_Request__c IN:caseIdsList order By Equipment__r.Maintenance_Cycle__c ASC limit 1];
for(Equipment_Maintenance_Item__c equip : EMIList){
toGetDueDateMap.put(equip.Id,Integer.valueOf(equip.Equipment__r.Maintenance_Cycle__c));
for(Case c : caseIdsList){
Case mainRe = new Case();
mainRe.Vehicle__c = c.Vehicle__c;
mainRe.status = 'New';
mainRe.Type = 'Routine Maintenance';
mainRe.Subject = 'New Main Request For Vehicle for Apex Specialist';
mainRe.Date_Reported__c = date.today();
if(count > 1){
mainRe.Date_Due__c = Date.today().addDays(toGetDueDateMap.get(equip.Id));
}
else{
mainRe.Date_Due__c = Date.today();
}
createNewMainReq.add(mainRe);
newCasesToIdsMap.put(c.Id,mainRe);
}
insert createNewMainReq;
if(caseIdsList.size()>0 && newCasesToIdsMap.size()>0){
cloneEquipItems(caseIdsList,newCasesToIdsMap);
}
}
}
public static void cloneEquipItems(List<case> closedCaseRecords, Map<Id,case> newCreatedCasesMapp){
List<Equipment_Maintenance_Item__c> newEquipItems = new List<Equipment_Maintenance_Item__c>();
try{
if(!closedCaseRecords.isEmpty() && newCreatedCasesMapp.size()>0){
List<Equipment_Maintenance_Item__c> oldEquipItems = [SELECT Equipment__c, Maintenance_Request__c, Quantity__c,Maintenance_Request__r.Id
FROM Equipment_Maintenance_Item__c
WHERE Maintenance_Request__c IN :closedCaseRecords];
for(Equipment_Maintenance_Item__c equipItem : oldEquipItems) {
Equipment_Maintenance_Item__c newItem = equipItem.clone(false, true, false, false);
newItem.Maintenance_Request__c = newCreatedCasesMapp.get(equipItem.Maintenance_Request__c).id;
newEquipItems.add(newItem);
}
insert newEquipItems;
}
}
catch(Exception e){
System.debug('Exception is'+ e);
}
}
}
Related
**When I run the below test class it return empty list in query method. I there any different way to write test class for aggregate batch apex **
global class Batch_Agent implements Database.Batchable {
global Iterable<AggregateResult> start(Database.BatchableContext BC){
string query='SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, SUM(Monthly_Premium__c) Sum_of_Monthly_Permium ,Sales_Agent__c FROM InsurancePolicy WHERE Is_Agency_commission_Paid__c=False and Effectuated__c=true and Submitted_Date__c >= 2021-02-02 and Submitted_Date__c <= 2021-05-01 and Sales_Agent__r.Sales_Agent_User__r.IsActive = true and Expected_Agency_Commission__c!= 0 and Expected_Agency_Commission__c!= null Group by Sales_Agent__c, Is_Agency_commission_Paid__c ';
return new AggregateResultIterable(query);
}
global void execute(Database.BatchableContext BC, List<Sobject> scope){
List<Sobject> policyLists = scope;
List<contact> agentContactList = new List<contact>();
List<Contact> conlist = [SELECT Id, Name, Seat_Cost__c, Tier__c FROM Contact WHERE Sales_Agent_User__r.IsActive = true and RecordType.name ='Sales Agent'];
List<Bonus_Amount__c> bonusList = [SELECT Id , Name, Commission_Amount__c,Commission_End_Amount__c,Bonus_Percentage__c FROM Bonus_Amount__c ];
List<Agent_Commission__c> agentComList = new List<Agent_Commission__c>();
list<Id> salesAgentIds = new List<Id>();
for(Sobject policy:policyLists){
if(policy.Get('Sales_Agent__c')!=null){
Id conIds;
Decimal seatCost;
String agentTier;
Decimal comissionAmount;
Decimal bonusPercentage;
Agent_Commission__c agentComm = new Agent_Commission__c();
agentComm.Sum_of_Expected_Agency_Commission__c = (Decimal)policy.Get('Sum_of_Agency_Commission');
agentComm.Sum_of_Monthly_Permium__c = (Decimal)policy.Get('Sum_of_Monthly_Permium');
conIds = (Id)policy.Get('Sales_Agent__c');
for(contact con:conlist ){
if(con.Id==conIds){
seatCost=con.Seat_Cost__c;
agentTier=con.Tier__c;
}
}
agentComm.Commisionable_Amount__c = ((Decimal)policy.Get('Sum_of_Agency_Commission')-seatCost);
comissionAmount = agentComm.Commisionable_Amount__c ;
for(Bonus_Amount__c bnus:bonusList){
if(bnus.Name == agentTier){
if (comissionAmount < 0 ){
bonusPercentage = 0;
}
else if( comissionAmount >= bnus.Commission_Amount__c && comissionAmount < bnus.Commission_End_Amount__c){
bonusPercentage = bnus.Bonus_Percentage__c;
}
}
}
agentComm.Bonus_Percentage__c = bonusPercentage;
agentComm.Bonus_Amount__c = comissionAmount*bonusPercentage;
agentComm.Sales_Agent__c = (String)policy.Get('Sales_Agent__c');
salesAgentIds.add(agentComm.Sales_Agent__c);
agentComm.Name = String.valueOf(System.now());
agentComList.add(agentComm);
}
}
Insert agentComList;
List<InsurancePolicy> policyUpdates = [SELECT ID, Name, test_Is_Agency_commission_Paid__c, Is_Agency_commission_Paid__c, Sales_Agent__c FROM InsurancePolicy
WHERE Is_Agency_commission_Paid__c= false and Sales_Agent__r.Sales_Agent_User__r.IsActive = true and
Expected_Agency_Commission__c!= 0 and Expected_Agency_Commission__c!= null and Effectuated__c=true and
Submitted_Date__c > 2021-01-01 and Sales_Agent__c in :salesAgentIDs ];
for(InsurancePolicy polupdate :policyUpdates ){
polupdate.Is_Agency_commission_Paid__c = false;
}
Update policyUpdates;
}
global void finish(Database.BatchableContext BC){
}
}
==================================================
#isTest(SeeAllData = FALSE)
public class lig_AgentCommissionTrigerHandlerTest {
private static Contact createContact(String lastName, Boolean withInsert ){
Contact newContact = new Contact(
LastName = lastName,
recordTypeId = Schema.getGlobalDescribe().get('Contact').getDescribe().getRecordTypeInfosByName().get('Sales Agent').getRecordTypeId(),
Seat_Cost__c = 22000,
Tier__c = 'T1'
);
if(withInsert){
insert newContact;
}
return newContact;
}
private static Bonus_Amount__c createBonusList(Boolean withInsert){
Bonus_Amount__c newBonusAmount = new Bonus_Amount__c(
Name = 'T1',
Commission_Amount__c = 2100,
Commission_End_Amount__c = 3500,
Bonus_Percentage__c = 0.03
);
if(withInsert){
insert newBonusAmount ;
}
return newBonusAmount ;
}
private static InsurancePolicy createInsurancePolicy(String name, Id nameInsuredId, Id saleAgentID,Integer agencycom, Integer mnthlyper, Boolean withInsert){
InsurancePolicy newPolicy = new InsurancePolicy(
NameInsuredId = nameInsuredId,
Name = name,
Sales_Agent__c = saleAgentID,
Expected_Agency_Commission__c = 12345,
Monthly_Premium__c = 231,
Is_Agency_commission_Paid__c = False
//Effectuated__c = True
);
if(withInsert){
insert newPolicy;
}
return newPolicy;
}
#TestSetup
private static void createTestData() {
//create test account
//create test account
Account policyHolder = lig_TestDataFactory.createPersonAccount('Test',
'Account',
'test#account.com',
'1234567890',
'1234567980',
TRUE);
Contact agentContact = lig_AgentCommissionTrigerHandlerTest.createContact('Test',
TRUE);
Bonus_Amount__c bonusAmount = lig_AgentCommissionTrigerHandlerTest.createBonusList(TRUE);
List<InsurancePolicy> testPolicies = new List<InsurancePolicy>();
testPolicies.add(lig_AgentCommissionTrigerHandlerTest.createInsurancePolicy('Test Policy 1',
policyHolder.Id,
agentContact.Id,
1234,
212,
FALSE));
testPolicies.add(lig_AgentCommissionTrigerHandlerTest.createInsurancePolicy('Test Policy 2',
policyHolder.Id,
agentContact.Id,
2311,
123,
FALSE));
insert testPolicies;
}
#isTest static void testCreateRenewalOppty()
{
List<Sobject> policies = [SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission, SUM(Monthly_Premium__c) Sum_of_Monthly_Permium ,Sales_Agent__c FROM InsurancePolicy
WHERE Is_Agency_commission_Paid__c=False Group by Sales_Agent__c];
List<Bonus_Amount__c> bonusList = [SELECT Id , Name, Commission_Amount__c,Commission_End_Amount__c,Bonus_Percentage__c FROM Bonus_Amount__c ];
list<Id> salesAgentIds = new List<Id>();
Test.startTest();
Batch_Agent baAgent = new Batch_Agent();
ID jobID = database.executebatch(baAgent,5);
Test.stopTest();
}
}
It returns an empty list because the test data you are creating does not match the query filters:
SELECT SUM(Expected_Agency_Commission__c) Sum_of_Agency_Commission,
SUM(Monthly_Premium__c) Sum_of_Monthly_Permium,
Sales_Agent__c
FROM InsurancePolicy
WHERE Is_Agency_commission_Paid__c=False
and Effectuated__c=true
and Submitted_Date__c >= 2021-02-02
and Submitted_Date__c <= 2021-05-01
and Sales_Agent__r.Sales_Agent_User__r.IsActive = true
and Expected_Agency_Commission__c!= 0
and Expected_Agency_Commission__c!= null
Group by Sales_Agent__c, Is_Agency_commission_Paid__c
Your test-context InsurancePolicy records must match all of the WHERE filters. Note as one example that your test data factory doesn't populate the Submitted_Date__c field. (It's unclear why you have hard-coded these values in your query).
I want to any pass date value from Datepicker input of lightning web component to PostingDate variable in LWCcontroller.cls
import { LightningElement,api ,track} from 'lwc';
import getInvoiceData from '#salesforce/apex/CustomerRefundLwcController.getInvoiceData';
import getBankAccounts from '#salesforce/apex/CustomerRefundLwcController.getBankAccounts';
import processCustomerRefund from '#salesforce/apex/CustomerRefundLwcController.processCustomerRefund';
export default class CustomerRefund extends LightningElement {
#api recordId; /*Sales Credit Id*/
#track invoiceData;
#track invoiceLinesData;
#api headerText;
#api recordProcessing;
#api bankAccounts = new Array();
#track selectedBankId;
#track allocateToSalesCredit;
#track referenceDetail;
#track bShowModal = false;
#track PostingDate;
/*Toast Event Variables*/
#api isError = false;
#api iswarning = false;
#api issuccess = false;
#api ToastMessage;
PostingDateChange(event)
{
this.PostingDate = event.target.value;
this.invoiceData.PostingDate = this.PostingDate;
}
processRefundHandler() {
this.recordProcessing = true;
//console.log('this.formData----'+JSON.stringify(this.invoiceLinesData));
console.log('this.formData----'+JSON.stringify(this.invoiceData));
processCustomerRefund({ lstInvoiceLines : this.invoiceLinesData, bankId : this.selectedBankId, allocateToSalesCredit : this.allocateToSalesCredit, reference : this.referenceDetail, postingdate : this.PostingDate })
.then(result => {
var responseMessage = result;
this.recordProcessing = false;
this.ToastMessage = responseMessage;
if(responseMessage == "Success"){
//this.issuccess = true;
this.isError = false;
this.ToastMessage = "Your Bank Customer Refund has been created";
this.bShowModal = true;
}else{
this.isError = true;
}
})
.catch(error => {
this.isError = true;
this.ToastMessage = error ;
console.log(error);
});
}
<div class="slds-col">
<label class="slds-form-element__label slds-no-flex">Posting Date</label>
<lightning-input type="date"
name="Postingdate"
value={PostingDate}
onchange={PostingDateChange}
>
</lightning-input>
</div>
CRLWC.cls
#AuraEnabled
public static string processCustomerRefund(List lstInvoiceLines,string bankId,boolean allocateToSalesCredit,string reference){
system.debug('start update');
string successMessage = 'Success';
string responseMessage = 'Success';
Savepoint spTran = database.setSavePoint();
try{
List<Sales_Invoice_Line_Item__c> lstLinesToUpdate = new List<Sales_Invoice_Line_Item__c>();
decimal amount=0;
Id taxRate;
Id salesinvoiceid;
boolean isValid = true;
boolean allocateToInvoice = allocateToSalesCredit;
map<id,Sales_Invoice_Line_Item__c> mapOfSelectedLines = new map<id,Sales_Invoice_Line_Item__c>();
for(ScLineWrapper lineWrapper : lstInvoiceLines){
system.debug('isselect>> ' + lineWrapper.isSelected);
if(lineWrapper.isSelected){
salesinvoiceid = lineWrapper.InvoiceLine.Sales_Invoice__c;
decimal lineAmount = lineWrapper.InvoiceLine.Foreign_Gross__c;
if(lineAmount != null && lineAmount > 0){
amount += lineAmount;
mapOfSelectedLines.put(lineWrapper.InvoiceLine.id,lineWrapper.InvoiceLine);
}
if(lineWrapper.InvoiceLine.Tax_Rate__c != null){
taxRate = lineWrapper.InvoiceLine.Tax_Rate__c;
}
}
}
if(salesinvoiceid == null){
isValid = false;
responseMessage = 'Please select at least one sales invoice line';
}else if(bankId == null){
isValid = false;
responseMessage = 'Please select bank account';
}else if(amount <= 0){
isValid = false;
responseMessage = 'Refund amount should be greater than zero';
}
system.debug('updatelst>> ' + lstLinesToUpdate);
//update lstLinesToUpdate;
if(isValid){
Sales_Invoice__c siInfo = [select id,Status__c,Account__c,Name from Sales_Invoice__c where id=: salesinvoiceid];
BankCustomerRefundService objCustomerRefundService = new BankCustomerRefundService();
BankCustomerRefundService.BankCustomerRefundWrapper objRefundWrapper = new BankCustomerRefundService.BankCustomerRefundWrapper();
Id accountId = siInfo.Account__c;
objRefundWrapper.AccountId = accountId;
objRefundWrapper.PostingDate = Date.Today()+(-216);
objRefundWrapper.BankAccountId = bankId;
objRefundWrapper.TaxRate = taxRate;
objRefundWrapper.Amount = amount;
objRefundWrapper.Reference = reference;
BankCustomerRefundService.Response objResponse = objCustomerRefundService.CreateBankCustomerRefund(objRefundWrapper);
responseMessage = objResponse.ResponseMessage;
if(allocateToInvoice && responseMessage == successMessage){
Bank_Payment__c objBankPayment = objResponse.BankPayments.get(accountId);
List<Ledger__c> listofLedgers = [Select id,name,Foreign_Gross_Total__c,Type__c
FROM Ledger__c
Where Customer_Supplier_Account_Name__c =: accountId AND Show_On_Transaction__c=1
AND Paid__c = 'N' AND Is_Deleted__c = false
AND (Sales_Invoice_Line_Item__c IN: mapOfSelectedLines.keyset() OR Bank_Payment__c =: objBankPayment.id) ];
if(!listofLedgers.isEmpty()){
BankAllocateCreditsAndPaymentsService objAllocateCreditsAndPaymentService = new BankAllocateCreditsAndPaymentsService();
BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsWrapper objAllocateCreditWrapper = new BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsWrapper();
objAllocateCreditWrapper.AccountId = accountId;
objAllocateCreditWrapper.PostingDate = Date.Today()+(-216);
List<BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper> BankAllocateCreditsAndPaymentsLines = new List<BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper>();
for(Ledger__c ledger : listofLedgers){
BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper objPaymentLine = new BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper();
objPaymentLine.LedgerName = ledger.Name;
objPaymentLine.Amount = ledger.Foreign_Gross_Total__c;
BankAllocateCreditsAndPaymentsLines.add(objPaymentLine);
}
objAllocateCreditWrapper.BankAllocateLines = BankAllocateCreditsAndPaymentsLines;
BankAllocateCreditsAndPaymentsService.Response objAllocateResponse = objAllocateCreditsAndPaymentService.BankAllocateCustomerBalance(objAllocateCreditWrapper);
responseMessage = objAllocateResponse.ResponseMessage;
system.debug('Response>>' + objAllocateResponse.ResponseMessage);
}
}
}
}catch(Exception ex){
responseMessage = ex.getStackTraceString();
}
if(responseMessage != successMessage){
Database.rollback(spTran);
}
system.debug('Response>>' + responseMessage);
return responseMessage;
}
You need to add the new parameter postingdate to the Apex Method
#AuraEnabled
public static string processCustomerRefund (
List lstInvoiceLines,
String bankId,
Boolean allocateToSalesCredit,
String reference,
Long postingdate
) {
I'm not sure long is the correct type thought, maybe DateTime or Date, I don't remember how Salesforce handle this. If it's long, it would be a timestamp.
Lightning input (type="date") returns a string in YYYY-MM-DD format.
Here's what I did:
public static Date convertDate(String datestr){
List<String> dateSplit = datestr.split('-');
return Date.newInstance(Integer.valueOf(dateSplit[0]), Integer.valueOf(dateSplit[1]), Integer.valueOf(dateSplit[2]));
}
You could also simply use Date as a parameter type in the apex method and that should work as well.
This is the case, for example, if a user now creates a page. So the next day I need Azure Logic apps to send an email after 1 day.
The problem is: right now, it is by no means sending any email to me if I sign up yesterday. But it sends me an email that now it has gone through with succe.
I would like to know what goes wrong since it by no means email me as I set up yesterday.
My Logic app (From Azure) - Images
However, be aware that the code can be made short but I just need to find out if Logic apps are making mistakes or if thus my code previously works without problems.
[Route("/api/cronjob")]
[HttpGet]
public async Task<IActionResult> NewSletterUserEmail()
{
await Newsletter();
return Ok("Godkendt!");
}
public async Task<IActionResult> Newsletter()
{
var m = new Settings.ArdklarMail();
var dtt = DateTime.Now;
var days = _dbContext.OfferUser.Max(i => i.Days);
var MaxDays = DateTime.Now.AddDays(-days);
var userlist = _dbContext.Users.Where(i => i.Opretdate >= MaxDays && i.TilmeldtNyhedsbrev == true).ToList();
if (userlist != null)
{
foreach (var item in userlist)
{
string mail = item.Brugernavn;
string fullname = item.Navn;
var memberData = _dbContext.MemberShipValue.FirstOrDefault(r => r.UserId == item.UserId);
if (memberData == null)
{
//alm bruger
var result = _dbContext.OfferUser.Where(x => x.Value == 1).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
else
{
var result = _dbContext.OfferUser.Where(x => x.Value == 2).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
}
}
//Det er til dem fra nyhedsbrevet som få tilsendt nyhedsbrev omkring div ting.
var newsletterlist = _dbContext.NewsletterList.Where(i => i.Tilmeldtdato >= MaxDays).ToList();
if (newsletterlist != null)
{
foreach (var item in newsletterlist)
{
string mail = item.Email;
string fullname = item.Email;
//til de nyhedsbrevet område
var result = _dbContext.OfferUser.Where(x => x.Value == 3).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Tilmeldtdato.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(mail);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(3500);
}
}
}
}
}
return Ok("Godkendt!");
}
No, I don't see mistake in Azure Logic Apps. Since the Logic App uses a recurrence trigger, it triggers the Logic App at the defined interval of time.
As there was send email action both side on the parallel branch, it will somehow send you an email by no means.
I have a trigger on a master-detail object where Doctor is master and Patient is child. Doctor has a field called TotalAmount and Patient has a field called Amount. Now, when a patient is filling in the amount field, the TotalAmount field in Doctor should give the sum of Amount in all the patient records.
I have written the code below, but it shows an error:
Invalid identifier: Amount__c
How can I fix this?
trigger tgPatient on Patient__c (after insert,after update) {
Set<Id>SetDoctor = new Set<Id>();
for (Patient__c p : trigger.new) {
if( p.Amount__c != Null ) {
SetDoctor.add(p.Doctor__c);
}
}
List<Doctor> lstDoctor = new List<Doctor>();
for( Doctor__c d : [SELECT Id, (SELECT Id,Amount__c FROM Patients__r) FROM Doctor__c WHERE Id IN:SetDoctor]){
Integer Amount__c = 0;
for (Patient__c p : d.Patient__r) {
int Amount__c += p.Amount__c;
}
d.Total_Amount__c = int Amount__c;
lstDoctor.add(d);
}
update lstDoctor;
}
Try the below one:
trigger tgPatient on Patient__c (after insert,after update) {
Set<Id>SetDoctor = new Set<Id>();
for (Patient__c p : trigger.new){
if( p.Amount__c != Null ){
SetDoctor.add(p.Doctor__c);
}
}
List<Doctor> lstDoctor = new List<Doctor>();
for( Doctor__c d : [SELECT Id, (SELECT Id,Amount__c FROM Patients__r) FROM Doctor__c WHERE Id IN:SetDoctor]){
Integer amountVAR = 0;
for (Patient__c p : d.Patient__r){
amountVAR += p.Amount__c;
}
d.Total_Amount__c = amountVAR ;
lstDoctor.add(d);
}
update lstDoctor;
regards
ajay
Try below:
trigger tgPatient on Patient__c(after insert, after update) {
Set < Id > SetDoctor = new Set < Id > ();
for (Patient__c p: trigger.new) {
if (p.Amount__c != Null) {
SetDoctor.add(p.Doctor__c);
}
}
List < Doctor > lstDoctor = new List < Doctor > ();
for (Doctor__c d: [SELECT Id, (SELECT Id, Amount__c FROM Patients__r) FROM Doctor__c WHERE Id IN: SetDoctor]) {
d.Total_Amount__c = 0;
for (Patient__c p: d.Patient__r) {
d.Total_Amount__c += p.Amount__c;
}
lstDoctor.add(d);
}
update lstDoctor;
}
But why do you want to use a Trigger? Why not create a roll-up summary field on Doctor?
Creating Roll Up Summary fields
I am very new to Apex.. a day into it so sorry for my ingornace. What I am trying to do is return a list of my accounts and then review the contract dates of the account(Contract_Expiration__c). Depending on that date it should update a custome field (
update_active_status_text__c) with null, Active, or Void.
I am not getting any error but I am not getting any code coverage. Any help will go a long way.
Thanks in advance
Apex Class
public class update_active_status {
public static VOID update_active_statustest(){
list<Account> myaccount = [SELECT Id, Contract_Expiration__c, update_active_status_text__c FROM Account WHERE CMS_Customer_Type__c = 'Enterprise' or CMS_Customer_Type__c = 'cloud'];
for(Account a: myaccount){
if (a.Contract_Expiration__c == null ){
a.update_active_status_text__c = null;
update a;
} else if (a.Contract_Expiration__c >= Date.today().addDays(-60)) {
a.update_active_status_text__c = 'Active';
update a;
} else if (a.Contract_Expiration__c < Date.today().addDays(-60)) {
a.update_active_status_text__c = 'Void';
update a;
} else {
a.update_active_status_text__c = 'Void';
update a;
}
}
}
}
Test Class
#isTest
public class testupdate_active_status {
static testMethod void myupdate_active_statusTest() {
Account acc = new Account(Name = 'Test Account');
insert(acc);
Date d = Date.today();
acc.Contract_Expiration__c = d;
update(acc);
acc.update_active_status_text__c = 'Active';
update(acc);
acc = [Select update_active_status_text__c From Account Where Id = : acc.Id];
System.assertEquals('Active', acc.update_active_status_text__c);
}
static testMethod void setToNull() {
Account acc = new Account(Name = 'Test Account');
insert(acc);
Date d = Date.today();
acc.Contract_Expiration__c = d;
update(acc);
acc.Contract_Expiration__c = null;
update(acc);
acc = [Select update_active_status_text__c From Account Where Id = : acc.Id];
System.assertEquals(null, acc.update_active_status_text__c);
}
static testMethod void createWithDate() {
Date d = Date.today().addDays(-70);
Account acc = new Account(Name = 'Test Account', Contract_Expiration__c = d);
insert(acc);
acc.update_active_status_text__c = 'Void';
update(acc);
acc = [Select update_active_status_text__c From Account Where Id = : acc.Id];
System.assertEquals('Void', acc.update_active_status_text__c);
}
}
Your test isn't actually using any of the methods in the class you wrote. Perhaps:
#isTest
public class testupdate_active_status {
static testMethod void myupdate_active_statusTest() {
Account acc = new Account(Name = 'Test Account');
insert(acc);
Date d = Date.today();
acc.Contract_Expiration__c = d;
update(acc);
testupdate_active_status.update_active_statustest(); // Call your new method!
acc = [Select update_active_status_text__c From Account Where Id = : acc.Id];
System.assertEquals('Active', acc.update_active_status_text__c);
}
static testMethod void setToNull() {
Account acc = new Account(Name = 'Test Account');
insert(acc);
Date d = Date.today();
acc.Contract_Expiration__c = d;
update(acc);
testupdate_active_status.update_active_statustest(); // Call your new method!
acc = [Select update_active_status_text__c From Account Where Id = : acc.Id];
System.assertEquals(null, acc.update_active_status_text__c);
}
static testMethod void createWithDate() {
Date d = Date.today().addDays(-70);
Account acc = new Account(Name = 'Test Account', Contract_Expiration__c = d);
insert(acc);
testupdate_active_status.update_active_statustest(); // Call your new method!
acc = [Select update_active_status_text__c From Account Where Id = : acc.Id];
System.assertEquals('Void', acc.update_active_status_text__c);
}
}
Your new class's job is to update the update_active_status_text__c...you're bypassing that job when you manually/explicitly update that field yourself (acc.update_active_status_text__c = 'Active'; update(acc);).