• Kunal Purohit 4
  • NEWBIE
  • 80 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 41
    Questions
  • 8
    Replies
Hi,
I am creating new Email Template(HTML). I want to include Approval Process step for Custom Object Client_Contract__c. I want to display:
1) Previous Approval Step name
2) Next  Approval Step name.
Please help.
Hi,
In my org, there are two objects Case and Project. Case object is having lookup relation with Project and Account Object. Now whenever, Case record is cretaed for particular Project, its asscoiated Account should get populated in case record. Plz help to write trigger for same.
Hello, Below is my Trigger:
public class AccountTeamTriggerHandler {
    static final String Team_Role_Value = 'Technical Support Manager';
    public static void handlerIsBeforeInsertUpdate(List<AccountTeamMember> newAccountList){
        map<Id,List<AccountTeamMember>> accIdVsTeamMemberMap = new  map<Id,List<AccountTeamMember>>();
        system.debug('newAccountList.size()=>'+newAccountList.size());
        for(AccountTeamMember accountTeamObj : newAccountList){
            if(accountTeamObj.TeamMemberRole.equalsIgnoreCase(Team_Role_Value)){
                if(accIdVsTeamMemberMap.containsKey(accountTeamObj.AccountId)) {
                    List<AccountTeamMember> accTeamList=accIdVsTeamMemberMap.get(accountTeamObj.AccountId);
                    accTeamList.add(accountTeamObj);
                    accIdVsTeamMemberMap.put(accountTeamObj.AccountId,accTeamList);
                }
                else{
                    accIdVsTeamMemberMap.put(accountTeamObj.AccountId,new List<AccountTeamMember>{accountTeamObj});
                }
            }
        }
        System.debug('accIdVsTeamMemberMap=='+accIdVsTeamMemberMap);
        List<Id> oldaccountIdSet = new List<Id>();
        List<AccountTeamMember> accountTeamList =[SELECT id,
                                                         TeamMemberRole,
                                                         AccountId 
                                                  FROM AccountTeamMember 
                                                  WHERE AccountId in: accIdVsTeamMemberMap.keyset() 
                                                  AND TeamMemberRole=:Team_Role_Value];
        for(AccountTeamMember oldaccountTeamObj : accountTeamList){
            oldaccountIdSet.add(oldaccountTeamObj.AccountId);
        }
        for(Id accId:accIdVsTeamMemberMap.keyset()){
            if(accIdVsTeamMemberMap.get(accId).size()>1){
                accIdVsTeamMemberMap.get(accId)[1].addError(Label.Account_team_member_error_message);
            }
            else{
                for(AccountTeamMember accTeamObj:accIdVsTeamMemberMap.get(accId)){
                    if(oldaccountIdSet.contains(accTeamObj.AccountId)){
                        accTeamObj.addError(Label.Account_team_member_error_message);
                    }
                }
            }
        }
    }
    
 
}


I have written below test class. Its code coverage is 80%. But I want to increase it to 85%. How to increase further:

/**
* Class       : AccountTeamMemberTriggerTest
* Description : Test Class for AccountTeamMemberTrigger  
* Created By  : Divergent
* Created On  : 030521
* */
@isTest
public class AccountTeamMemberTriggerTest {
    /**
    * Method Name : setupTestData
    * Description : Test data created for this test class.
    * Created By  : Divergent
    * Created On  : 030521
    * */
 @testSetup static void setupTestData() {
        List<Account> Accounts;
        Accounts = new List<Account>();
        Account acc = new Account();
        acc.Name = 'Acme Industries';
        Accounts.add(acc);
        insert Accounts;
     
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='testmemberuser@testorg.com');
     insert u;
     
 }
     /**
    * Method Name : testCreateMultipleAccountMember
    * Description : Create 2 account team member with role Technical support manager.
    * Created By  : Divergent
    * Created On  : 030521
    * */
     @isTest
    public static void testCreateMultipleAccountMember() {
        Account acc=[Select Id from Account];
        User u=[Select Id from User where UserName='testmemberuser@testorg.com'];
        AccountTeamMember accTeam=new AccountTeamMember();
        accTeam.AccountId=acc.id;
        accTeam.UserId=u.id;
        accteam.TeamMemberRole='Technical Support Manager';
        insert accteam;
        Try{
        AccountTeamMember accTeam2=new AccountTeamMember();
        accTeam2.AccountId=acc.id;
        accTeam2.UserId=u.id;
        accteam2.TeamMemberRole='Technical Support Manager';
        insert accteam2;
        }
        catch(Exception e){
            Boolean expectedExceptionThrown =e.getMessage().contains('Technical Support Manager')? true : false;
            System.AssertEquals(expectedExceptionThrown, true);
            System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
        }
    }
      /**
    * Method Name : testSecondMemberAsTechnical
    * Description : Create first account with other role and then next 2 with role Technical support manager.
    * Created By  : Divergent
    * Created On  : 030521
    * */
    @isTest
    public static void testSecondMemberAsTechnical() {
        Account acc=[Select Id from Account];
        User u=[Select Id from User where UserName='testmemberuser@testorg.com'];
        List<AccountTeamMember> accountTeamMembers = new List<AccountTeamMember>();
        AccountTeamMember accTeam=new AccountTeamMember();
        accTeam.AccountId=acc.id;
        accTeam.UserId=u.id;
        accteam.TeamMemberRole='Boost Overlay Rep';
        accountTeamMembers.add(accteam);
        
        
        AccountTeamMember accTeam3=new AccountTeamMember();
        accTeam3.AccountId=acc.id;
        accTeam3.UserId=u.id;
        accteam3.TeamMemberRole='Technical Support Manager';
        accountTeamMembers.add(accteam3);
        
        //insert accountTeamMembers;
        
        Try{
            AccountTeamMember accTeam2=new AccountTeamMember();
            accTeam2.AccountId=acc.id;
            accTeam2.UserId=u.id;
            accteam2.TeamMemberRole='Technical Support Manager';
            accountTeamMembers.add(accteam2);
            
            insert accountTeamMembers;
        }
        catch(Exception e){
            Boolean expectedExceptionThrown =e.getMessage().contains('Technical Support Manager')? true : false;
            System.AssertEquals(expectedExceptionThrown, true);
            System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
        }
    }
    
}

Hello, I am new to salesforce development. I want to write test class for given apex controller. Please help.

public without sharing class CreateNachaFileController {
	public String key;
	private ApexPages.StandardSetController standardController;
	public string headerImmediateDestination { get; set; }
	public string headerImmediateOrigin { get; set; }
	public string headerFileIdModifier { get; set; }
	public string headerDestinationName { get; set; }
	public string headerImmediateOriginName { get; set; }
	public string batchCompanyName { get; set; }
	public string batchCompanyId { get; set; }
	public string batchOriginatingDfiID { get; set; }
	public string batchCompanyEntryDescription { get; set; }
	public string batchCompanyDescriptiveDate { get; set; }
	public NachaFile nacha { get; set; }
	public Integer TotalCount { get; set; }
	public Decimal Total { get; set; }
	public String ServiceClass { get; set; }
	public Invoice_Header__c invoice { get; set; }
	public Customer_Payment__c NewPayment { get; set; }
	public List<SelectOption> nachaDefaultNames { get; set; }
	public String selectedNachaDefaultName { get; set; }
	public Boolean hasSplits { get; set; }
	private Map<String, CS_Nacha_Defaults__c> nachaDefaults;
	public Map<Id, InvoiceSplitWrapper> splitWrappers { get; set; }


	/////////////////////////////////////////////////////////////////
	// Outgoing (Vendor) NACHA
	/////////////////////////////////////////////////////////////////
	/**
	 * @description Constructor when called from Visualforce page as an extension, like CreateNachaFile
	 * @param standardController 
	 */
	public CreateNachaFileController(ApexPages.StandardSetController standardController) {
		if (this.standardController == null) {
			this.standardController = standardController;
			InitializeDefaults();
			headerFileIdModifier = 'A';
		}
	}

	public PageReference CreateNachaFile1() {
		return Page.CreateNachaFile;
	}

	public PageReference CreateNachaFile2() {
		TotalCount = 0;
		Decimal totalCalc = 0.0;
		Total = 0.0;
		Id[] ids = new List<Id> ();
		for (Vendor_Payment__c payment : (List<Vendor_Payment__c>) standardController.getSelected()) {
			ids.add(payment.Id);
			TotalCount++;
			if (payment.Total__c != null) { totalCalc = totalCalc + payment.Total__c; }
		}
		Total = totalCalc.setScale(2);

		nacha = new NachaFile();
		nacha.headerData.headerImmediateDestination = headerImmediateDestination.left(10);
		nacha.headerData.headerImmediateOrigin = headerImmediateOrigin.left(10);
		nacha.headerData.headerFileIdModifier = headerFileIdModifier.left(1);
		nacha.headerData.headerDestinationName = headerDestinationName.left(23);
		nacha.headerData.headerImmediateOriginName = headerImmediateOriginName.left(23);

		nacha.headerData.batchCompanyEntryDescription = batchCompanyEntryDescription == null ? '' : batchCompanyEntryDescription.left(10);
		nacha.headerData.batchCompanyName = batchCompanyName.left(16);
		nacha.headerData.batchCompanyId = batchCompanyId.left(10);
		nacha.headerData.batchOriginatingDfiID = batchOriginatingDfiID.left(8);

		nacha.headerData.serviceClass = ServiceClass;

		nacha.generateFile(ids);

		return Page.CreateNachaFile2;
	}

	public PageReference CreateNachaFile3() {
		// Create Nacha_File__c record
		NACHA_File__c nf = new NACHA_File__c();
		nf.Destination_Name__c = nacha.headerData.headerDestinationName;
		nf.File_Id_Modifier__c = nacha.headerData.headerFileIdModifier;
		nf.Generated_By__c = UserInfo.getUserId();
		nf.Immediate_Destination__c = nacha.headerData.headerImmediateDestination;
		nf.Immediate_Origin__c = nacha.headerData.headerImmediateOrigin;
		nf.Immediate_Origin_Name__c = nacha.headerData.headerImmediateOriginName;
		nf.Service_Class__c = nacha.headerData.serviceClass;
		insert nf;
		List<Vendor_Payment__c> payment = (List<Vendor_Payment__c>) standardController.getSelected();
		for (Vendor_Payment__c detail : payment) {
			detail.Status__c = 'Payment Sent';
			detail.Date_Paid__c = Date.today();
			detail.NACHA_File__c = nf.Id;
		}
		standardController.save();
		return Page.CreateNachaFile3;
	}

	public PageReference cancel() {
		Schema.DescribeSObjectResult anySObjectSchema = Vendor_Payment__c.SObjectType.getDescribe();
		String objectIdPrefix = anySObjectSchema.getKeyPrefix();
		PageReference pageReference = new PageReference('/' + objectIdPrefix + '/o');
		pageReference.setRedirect(true);
		return pageReference;
	}

	/////////////////////////////////////////////////////////////////
	// Incoming (Customer) NACHA
	/////////////////////////////////////////////////////////////////
	/**
	 * @description Constructor when called from Visualforce page as Controller - CreateIncomingNachaFile.page
	 */
	public CreateNachaFileController() {
		InitializeDefaults();
		headerFileIdModifier = 'H';
		batchCompanyEntryDescription = 'RECEIVABLE';
		batchCompanyDescriptiveDate = string.valueof(DateTime.now().month()) + string.valueof(DateTime.now().year()).substring(2, 4);

		invoice = [SELECT
		           Id, Name, Customer_Id__c, Customer_Name__c, Invoice_Total__c, Total_Balance__c, Document_Date__c, Memo__c,
		           Customer_ID__r.Bank_Account__c, Customer_ID__r.Bank_Routing__c, Customer_Id__r.Receivables_Account_Id__c, Customer_ID__r.NACHA_Vendor_NameFx__c
		           , (select Id, Name, Invoice_Split_Amount__c, Bank_Information__r.Name, Bank_Information__r.Bank_Account__c, Bank_Information__r.Bank_Routing__c, Exclude_from_NACHA_Files__c from Invoice_Splits__r)
		           FROM Invoice_Header__c
		           where Id = :key];

		hasSplits = invoice.Invoice_Splits__r.size() > 0;

		NewPayment = new Customer_Payment__c();
		NewPayment.Customer_Id__c = invoice.Customer_Id__c;
		NewPayment.Tran_Date__c = Date.today() + 1;
		NewPayment.Default_Vendor_Payment_Date__c = PaymentFromCustomerController.calculateNthWorkingDay(Date.today() + 1, 1);
		NewPayment.AR_Account_Id__c = invoice.Customer_Id__r.Receivables_Account_Id__c;
		NewPayment.Payment_Type__c = 'ACH';

		NewPayment.Amount__c = invoice.Total_Balance__c;
		System.debug(hasSplits);
		if (hasSplits) {
			NewPayment.Amount__c = 0;
			splitWrappers = new Map<Id, InvoiceSplitWrapper> ();
			for (Invoice_Split__c split : invoice.Invoice_Splits__r) {
				System.debug(split);
				System.debug(split.Exclude_from_NACHA_Files__c);
				if (split.Exclude_from_NACHA_Files__c == false) {
					System.debug('included');
					InvoiceSplitWrapper splitWrapper = new InvoiceSplitWrapper(split);
					splitWrapper.checked = true;
					splitWrappers.put(splitWrapper.invoiceSplit.Id, splitWrapper);
					NewPayment.Amount__c += split.Invoice_Split_Amount__c;
					System.debug(NewPayment.Amount__c);
				}
			}
		}
		System.debug(splitWrappers);

	}
	public PageReference CreateIncomingNachaFile1() {
		return Page.CreateIncomingNachaFile;
	}

	public PageReference CreateIncomingNachaFile2() {
		if (NewPayment.Amount__c == null || NewPayment.Tran_Date__c == null) {
			ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Amount and Payment Date are required before saving.');
			ApexPages.addMessage(myMsg);
			return null;
		}
		if (hasSplits) {
			NewPayment.Amount__c = 0;
			for (Id key : splitWrappers.keySet()) {
				InvoiceSplitWrapper sw = splitWrappers.get(key);
				if (sw.checked) {
					NewPayment.Amount__c += sw.invoiceSplit.Invoice_Split_Amount__c;
				}
			}
		}
		TotalCount = 0;
		Decimal totalCalc = 0.0;
		Total = 0.0;
		TotalCount = 1;
		totalCalc = NewPayment.Amount__c; //invoice.Total_Balance__c;
		Total = totalCalc.setScale(2);

		nacha = new NachaFile();
		nacha.headerData.headerImmediateDestination = headerImmediateDestination.left(10);
		nacha.headerData.headerImmediateOrigin = headerImmediateOrigin.left(10);
		nacha.headerData.headerFileIdModifier = headerFileIdModifier.left(1);
		nacha.headerData.headerDestinationName = headerDestinationName.left(23);
		nacha.headerData.headerImmediateOriginName = headerImmediateOriginName.left(23);

		nacha.headerData.batchCompanyName = batchCompanyName.left(16);
		nacha.headerData.batchCompanyId = batchCompanyId.left(10);
		nacha.headerData.batchOriginatingDfiID = batchOriginatingDfiID.left(8);
		nacha.headerData.batchCompanyEntryDescription = batchCompanyEntryDescription.left(10);
		nacha.headerData.batchCompanyDescriptiveDate = batchCompanyDescriptiveDate.left(6);

		nacha.headerData.serviceClass = ServiceClass;
		nacha.AmountOverride = NewPayment.Amount__c;
		nacha.PaymentDate = NewPayment.Tran_Date__c;
		System.debug(nacha);
		System.debug(splitWrappers);
		nacha.generateIncomingFile(new List<Invoice_Header__c> { invoice }, splitWrappers);

		return Page.CreateIncomingNachaFile2;
	}

	public PageReference CreateIncomingNachaFile3() {
		//Save New Payment, then save nacha file
		if (!CreateNewPayment()) return null;
		return Page.CreateIncomingNachaFile3;
	}

	// Incoming (Customer) NACHA
	public void actionSupportChangePmtDivision() {
		Id glAccount = null;
		Id pmtDivisionId = NewPayment.Payment_Division_Id__c;
		List<Payment_Division__c> pmtDivisions = [SELECT Id, Name, GL_Account_Id__c FROM Payment_Division__c WHERE Id = :pmtDivisionId];
		NewPayment.GL_Account_Id__c = null;
		if (pmtDivisions.size() != 0) {
			for (Payment_Division__c pd : pmtDivisions) {
				NewPayment.GL_Account_Id__c = pd.GL_Account_Id__c;
			}
		}
	}
	// Incoming (Customer) NACHA
	public boolean CreateNewPayment() {
		// Create Nacha_File__c record
		NACHA_File__c nf = new NACHA_File__c();
		//nacha.Name = 
		nf.Destination_Name__c = nacha.headerData.headerDestinationName;
		nf.File_Id_Modifier__c = nacha.headerData.headerFileIdModifier;
		nf.Generated_By__c = UserInfo.getUserId();
		nf.Immediate_Destination__c = nacha.headerData.headerImmediateDestination;
		nf.Immediate_Origin__c = nacha.headerData.headerImmediateOrigin;
		nf.Immediate_Origin_Name__c = nacha.headerData.headerImmediateOriginName;
		nf.Service_Class__c = nacha.headerData.serviceClass;
		insert nf;

		if (!hasSplits) {
			if (NewPayment.Amount__c == null || NewPayment.Tran_Date__c == null) {
				ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Amount and Payment Date are required before saving.');
				ApexPages.addMessage(myMsg);
				return false;
			}

			decimal totalAmountApplied = NewPayment.Amount__c;
			NewPayment.NACHA_File__c = nf.Id;
			insert NewPayment;
			Customer_Payment_Apply__c application = new Customer_Payment_Apply__c();
			application.Customer_Payment_Id__c = NewPayment.Id;
			application.Invoice_Id__c = invoice.Id;
			application.Amount__c = NewPayment.Amount__c;
			insert application;
			return true;
		} else {
			if (NewPayment.Tran_Date__c == null) {
				ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Payment Date is required before saving.');
				ApexPages.addMessage(myMsg);
				return false;
			}
			Customer_Payment__c[] paymentsToInsert = new List<Customer_Payment__c> ();
			Customer_Payment_Apply__c[] applicationsToInsert = new List<Customer_Payment_Apply__c> ();

			for (Invoice_Split__c split : invoice.Invoice_Splits__r) {
				system.debug(split);
				Customer_Payment__c splitPayment = new Customer_Payment__c();
				splitPayment.NACHA_File__c = nf.Id;
				splitPayment.Amount__c = split.Invoice_Split_Amount__c;
				splitPayment.Customer_Id__c = NewPayment.Customer_Id__c;
				splitPayment.Tran_Date__c = NewPayment.Tran_Date__c;
				splitPayment.Default_Vendor_Payment_Date__c = NewPayment.Default_Vendor_Payment_Date__c;
				splitPayment.AR_Account_Id__c = NewPayment.AR_Account_Id__c;
				splitPayment.Payment_Type__c = NewPayment.Payment_Type__c;
				splitPayment.GL_Account_Id__c = NewPayment.GL_Account_Id__c;
				splitPayment.Payment_Division_Id__c = NewPayment.Payment_Division_Id__c;
				splitPayment.Coverage_Month__c = NewPayment.Coverage_Month__c;
				splitPayment.Location__c = NewPayment.Location__c;
				splitPayment.Memo__c = NewPayment.Memo__c;
				splitPayment.Posting_Period__c = NewPayment.Posting_Period__c;
				splitPayment.Batch__c = NewPayment.Batch__c;
				splitPayment.COL_Code__c = NewPayment.COL_Code__c;
				paymentsToInsert.add(splitPayment);

			}
			insert paymentsToInsert;
			for (Customer_Payment__c pmt : paymentsToInsert) {
				Customer_Payment_Apply__c application = new Customer_Payment_Apply__c();
				application.Customer_Payment_Id__c = pmt.Id;
				application.Invoice_Id__c = invoice.Id;
				application.Amount__c = pmt.Amount__c;
				applicationsToInsert.add(application);

			}
			insert applicationsToInsert;
			return true;
		}
	}

	// Incoming NACHA
	public PageReference cancelToInvoice() {
		PageReference pageReference = new PageReference('/' + key);
		pageReference.setRedirect(true);
		return pageReference;
	}


	/////////////////////////////////////////////////////////////////
	// Both Regular NACHA and Incoming NACHA
	/////////////////////////////////////////////////////////////////
	private void InitializeDefaults() {
		key = ApexPages.currentPage().getParameters().get('invoiceid');

		nachaDefaultNames = new List<SelectOption> ();
		nachaDefaults = new Map<String, CS_Nacha_Defaults__c> ();

		// Need to order by Ordinal__c so I went with the direct SOQL route instead of the cached call (getAll)
		for (CS_Nacha_Defaults__c nd :[SELECT Name, Immediate_Origin__c, Immediate_Origin_Name__c, Immediate_Destination__c, Destination_Name__c,
		     Company_Name__c, Company_Id__c, Originating_DFI_Id__c, Company_Entry_Description__c
		     FROM CS_Nacha_Defaults__c
		     WHERE Active__c = true
		     ORDER BY Ordinal__c DESC]) {
			nachaDefaultNames.add(new SelectOption(nd.Name, nd.Name));
			nachaDefaults.put(nd.Name, nd);
		}

		selectedNachaDefaultName = nachaDefaultNames[0].getValue();
		setDefaults();

	}


	public void setDefaults() {

		CS_Nacha_Defaults__c selectedNachaDefault = nachaDefaults.get(selectedNachaDefaultName);
		//headerImmediateDestination = '011900254'; 
		//headerImmediateOrigin = '1200645984'; 
		//headerDestinationName = 'BANK OF AMERICA'; 
		//headerImmediateOriginName = 'PLANSOURCE BEN ADMIN'; 
		//batchCompanyName = 'PLANSOURCE'; 
		//batchCompanyId = '1550800751'; 
		//batchOriginatingDfiID = '011900254'; 
		headerImmediateDestination = selectedNachaDefault.Immediate_Destination__c;
		headerImmediateOrigin = selectedNachaDefault.Immediate_Origin__c;
		headerDestinationName = selectedNachaDefault.Destination_Name__c;
		headerImmediateOriginName = selectedNachaDefault.Immediate_Origin_Name__c;
		batchCompanyName = selectedNachaDefault.Company_Name__c;
		batchCompanyId = selectedNachaDefault.Company_Id__c;
		batchOriginatingDfiID = selectedNachaDefault.Originating_DFI_Id__c;
		batchCompanyEntryDescription = selectedNachaDefault.Company_Entry_Description__c;
	}

}
Hello,
While validating Dashboard, I am getting error:
Must specify sortBy attribute to one dashboard table column.

How to Resolve the above error. I have checked with all the reports ascociated with dashboards for which above error is coming. There is already Sort by attribute in Report. 

User-added image

Here I am getting Slash symbol along with value. Previously i was getting HTML tags along with value. That i have fixed by converting Lightning-formatted-text into Lightning-formatted-rich-text in html. Here is the code. What else i should do to remove //-// symbols?

<!-- This component displays searched results -->
<template>
    <div class="result-card slds-m-around_small">
        <article class="slds-card">
            <lightning-input class="result-selection" type="checkbox-button" name="result" checked={selected}
                onchange={handleSelectionChange}>
            </lightning-input>
            <div class="slds-card__body slds-card__body_inner" onclick={handleOpenService}>
                <div class="slds-m-bottom_small text-overflow font-emphasis">
                    <span>{result.Name}</span>
                </div>

                <div class="slds-grid slds-wrap" >
                    <div class="slds-col slds-size_1-of-2 slds-p-around_x-small">
                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Agency Name
                            </div>
                            <div class="slds-col slds-size_1-of-2 break-word">
                                {result.AgencyName}
                            </div>
                        </div>
                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Area Served is Statewide
                            </div>
                            <div class="slds-col slds-size_1-of-2 break-word">
                                {result.AreaServedisStatewide}
                            </div>
                        </div>

                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Status
                            </div>
                            <div class="slds-col slds-size_1-of-2 break-word">
                                {result.Open}
                            </div>
                        </div>

                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Area Served
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <ul>
                                    <lightning-formatted-rich-text value={result.AreaServed}></lightning-formatted-rich-text>
                                </ul>
                            </div>
                        </div>

                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Distance
                            </div>
                            <div class="slds-col slds-size_1-of-2 break-word">
                                <lightning-formatted-text value={result.Distance}></lightning-formatted-text>
                            </div>
                        </div>

                        <!-- <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Siteid
                            </div>
                            <div class="slds-col slds-size_1-of-2 break-word">
                                <lightning-formatted-text value={result.siteId}></lightning-formatted-text>
                            </div>
                        </div> -->


                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Service Hours of Operation  
                            </div>
                            <div class="slds-col slds-size_1-of-2 break-word">
                                <lightning-formatted-rich-text value={result.ServiceHoursofOperation}></lightning-formatted-rich-text>
                            </div>
                            <!-- <div class="slds-col slds-size_1-of-2">
                                <template if:true={result.hoursoperation}>
                                    <ul>
                                        <template for:each={result.hoursoperation} for:item="hour">
                                            <li class="break-word" key={hour}>{hour}</li>
                                        </template>
                                    </ul>
                                </template>
                            </div> -->
                        </div>
        
                        <div class="additionalFields">
                            <template for:each={additionalFields} for:item="field">
                                    <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section" key={field.name}>
                                        <div class="slds-col slds-size_1-of-2">
                                            {field.name}
                                        </div>
                                        <div class="slds-col slds-size_1-of-2">
                                            <div class="slds-col slds-size_1-of-2 break-word">
                                                {field.value}
                                            </div>
                                        </div>
                                    </div>
                            </template>
                        </div>
                    </div>

                    <div class="slds-col slds-size_1-of-2 slds-p-around_x-small">
                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                Preview of Description
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <ul>
                                    <lightning-formatted-rich-text value={result.DescriptionPreview}></lightning-formatted-rich-text>
                                </ul>
                            </div>
                        </div>

                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                    Additional Taxonomies Offered
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <ul>
                                    <template for:each={result.AdditionalTaxonomies} for:item="additionalTaxo">
                                        <li class="break-word" key={additionalTaxo}>{additionalTaxo}</li>
                                    </template>
                                </ul>
        
                            </div>
                        </div>

                        <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section">
                            <div class="slds-col slds-size_1-of-2">
                                    Site Address
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <div class="slds-col slds-size_1-of-2 break-word">
                                    <lightning-formatted-text value={result.siteAddress}></lightning-formatted-text>
                                </div>
        
                            </div>
                        </div>
                        
                        <div class="additionalFields">
                            <template for:each={secondColumnFields} for:item="field">
                                    <div class="slds-grid slds-wrap slds-grid_align-spread slds-has-flexi-truncate section" key={field.name}>
                                        <div class="slds-col slds-size_1-of-2">
                                            {field.name}
                                        </div>
                                        <div class="slds-col slds-size_1-of-2">
                                            <div class="break-word">
                                                <lightning-formatted-rich-text value={field.value}></lightning-formatted-rich-text>
                                            </div>
                                        </div>
                                    </div>
                            </template>
                        </div>
                    </div>
                </div>
                
            </div>
        </article>
    </div>
</template>

User-added imageHere, Service Hours is displaying HTML tags along with Value. How to remove and get only instead. Here is the VF page Code:

<apex:page controller="ResourceSearchPDFController" sideBar="false" showHeader="false" standardStylesheets="false" applyHtmlTag="false"
    applyBodyTag="false" docType="html-5.0" renderAs="pdf">

    <head>
        <style>
            @page {
                size: A4;
                margin: 35mm 5mm 35mm 5mm;

                @bottom-right {
                    content: element(info);
                }

                @top-center {
                    content: element(title);
                }

                @bottom-center {
                    content: element(footer);
                }
            }

            body {
                font-family: "Salesforce Sans";
                font-size: 14px;
            }

            .page-break {
                display: block;
                page-break-after: always;
            }

            .page-number::after {
                font-family: "Arial" "Sans-Serif";
                font-size: 10px;
                content: counter(page)
            }

            table {
                page-break-inside: avoid;
            }

            td {
                vertical-align: top;
            }

            .pages:after {
                font-family: "Arial" "Sans-Serif";
                font-size: 10px;
                content: counter(pages)
            }

            .service-table {
                width: 100%;
                border-collapse: collapse;
                table-layout: fixed;
                margin-bottom: 10px;
            }

            .service-table td {
                border: 1px solid black;
                padding: 0;
            }

            .service-table tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }

            .service-title {
                font-weight: 700;
                font-size: 20px;
                padding: 10px !important;
                text-align: center;
            }

            .service-title div,
            .service-taxonomy div {
                overflow: hidden;
            }

            .info {
                font-size: 12px;
                text-align: right;
                position: running(info);
            }

            ul {
                padding: 0px;
                margin: 0px;
                padding-left: 15px;
            }

            .title {
                text-align: center;
                font-size: 30px;
                position: running(title);
            }

            .title div {
                height:100px;
            }

            .title  img {
                margin-top: 20px;
                height: 100px; 
                position: absolute;
                right: 0;
                top: 0;
            }          

            .footer{
                text-align: center;
                position: running(footer);
            }  

            .footer img {
                height: 70px;
            }

            .grid-container {
                display: table;
                table-layout: fixed;
                border-collapse: collapse;
                width: 100%;
                height: 100%;
                padding: 5px;
            }
            

            .grid-container div {
                padding: 5px;
                display: table-row;
                page-break-inside: auto;
                page-break-after: auto;
            }

            .grid-container div div {
                display: table-cell;
                word-wrap: break-word;
                border-right: 1px solid;
                border-bottom: 1px solid;
            }

            .grid-container div div:first-child {
                width: 100px !important;
            }

            .service-field {
                font-weight: 700;
            }

            p{
                text-overflow: clip;
            }
        </style>
    </head>

    <div class="info">
        <div>Page
            <strong>
                <span class="page-number"></span>
            </strong> of
            <strong>
                <span class="pages"></span>
            </strong>
        </div>
    </div>

    <div class="footer">
        <!-- <img src="{!URLFOR($Resource.PDFAssets, 'footerMHUW.jpg')}"/> -->
    </div>

    <div class="title">
        <div>Services Referral</div>
        <img src="{!URLFOR($Resource.PDFAssets, '211-logo-2019-rgb.png')}"/>
    </div>

    <body>
        <div class="container">
            <!-- updated on 04/06/2020 -->
            <apex:repeat value="{!wrapperClassList}" var="wrap">
                <apex:repeat value="{!wrap.siteWrapper}" var="location">
                <table class="service-table" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td class="service-title" colspan="5">
                            <div>{!wrap.serviceRecord.Name + ' - ' + wrap.serviceRecord.Account__r.Name}</div>
                        </td>
                    </tr>
                    
                    <tr>
                        <td><div class="service-field">Service Description: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div><apex:outputText value="{!wrap.serviceRecord.ServiceDescription__c}" escape="false"/></div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td><div class="service-field">Service Hours of Operation: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div>
                                    <!-- <apex:repeat value="{!service.Hours_of_Operations__r}" var="hourOp"> -->
                                            <apex:outputText value="{!wrap.serviceRecord.Service_Hours_of_Operation__c}" escape="false"/>
                                    <!-- </apex:repeat> -->
                                </div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td><div class="service-field">Service Contact Phone: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div><apex:outputText value="{!wrap.serviceRecord.Service_Contact_Phone__c}"/></div>
                            </div>
                        </td>
                    </tr>

                    <!-- Contact phone? -->
                    
                    <tr>
                        <td><div class="service-field">Intake Procedure: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div><apex:outputText value="{!wrap.serviceRecord.Intake_Procedure__c}" /></div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td><div class="service-field">Intake Requirements: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div><apex:outputText value="{!wrap.serviceRecord.IntakeRequirements__c}" escape="false"/></div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td><div class="service-field">Address: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div>
                                    <!--apex:repeat value="{!service.All_Service_s_Sites__r}" var="location"-->
                                    <!-- <apex:repeat value="{!sitesList}" var="location"> -->
                                        <!-- <apex:outputText value="{!location + ';<br>'}" escape="false"/> -->
                                        <apex:outputText value="{!location.sitePhysicalAddress}" escape="false"/>
                                    <!--/apex:repeat-->
                                </div>
                            </div>
                        </td>
                    </tr>
                    
                    <tr>
                        <td><div class="service-field">Site Distance: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div>
                                    <!--apex:repeat value="{!service.All_Service_s_Sites__r}" var="location"-->
                                    <!-- <apex:repeat value="{!sitesList}" var="location"> -->
                                        <!-- <apex:outputText value="{!location + ';<br>'}" escape="false"/> -->
                                        <apex:outputText value="{!location.distance}" escape="false"/> miles
                                    <!--/apex:repeat-->
                                </div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td><div class="service-field">211colorado.org Link: </div></td>
                        <td colspan="4" style="padding: 5px;">
                            <div>
                                <div>
                                    <!--apex:repeat value="{!service.All_Service_s_Sites__r}" var="location"-->
                                    <!-- <apex:repeat value="{!sitesList}" var="location"> -->
                                        <!-- <apex:outputText value="{!location + ';<br>'}" escape="false"/> -->
                                        <apex:outputText value="{!location.friendlyURLName}" escape="false"/>
                                    <!--/apex:repeat-->
                                </div>
                            </div>
                        </td>
                    </tr>
                  
                </table>
                </apex:repeat>
            </apex:repeat>
        </div>
    </body>
</apex:page>
Hello All,
I have written below trigger. Now i want to write test class for same. Kindly provide your suggestion.
trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
    
    set<id> accid=new set<id>();
     if(Trigger.isInsert|| Trigger.isUpdate|| Trigger.isUndelete){
        for(Contact con:Trigger.new){
            accid.add(con.AccountId);
        }
    }

 

    if(Trigger.isDelete|| Trigger.isUpdate){
        for(Contact Con: Trigger.old){
            accid.add(Con.AccountId);
        }
    }
    
     List<Account> aclist=[SELECT Id,Open_Contact_Count__c,(SELECT Id FROM Contacts WHERE Status__c= 'Open') FROM Account WHERE Id IN: accid];
    for(Account acc: aclist){
      
       acc.Open_Contact_Count__c= acc.Contacts.size();
    }
    update aclist;
}

 
Hello All,
I am new to developmennt. 
We have Number field on Account called Open Contact Count and on Contact we have Status field picklist values as Open In Progress and Completed. Whenever any contact is created/updated with Status as Open related to Account, we need to maintain count of Open contact on related Account. I have written trigger for same but not working. Please give your valuable suggestions.
trigger ChildCount on Contact (after insert,after delete,after update,after undelete) {
     set<id> accid=new set<id>();
    if(trigger.isInsert|| trigger.IsUpdate|| trigger.isUndelete)
    {
        for(Contact con:trigger.new)
        {
            accid.add(con.AccountId);
        }
    }

    if(trigger.isDelete|| trigger.IsUpdate)
    {
        for(Contact Con: trigger.old)
        {
            accid.add(con.AccountId);
        }
    }
    
   list<Account> aclist=[select id, Open_Contact_Count__c,(Select id from Contacts) from Account where id in: accid];

 

List<Account> acupdate=new list<Account>();
   
    for(Account acc: aclist)
    {
        
       list<contact> clist= acc.Contacts;
       Account a1=new Account();
       Contact c1=new Contact();
      
               a1.Id=acc.Id;
            a1.Open_Contact_Count__c = clist.size();
       
           acupdate.add(a1);
      
    }
            update acupdate;
    }

 
Hello All,
I am trying to retrieve dashboard components in Workbench. But it shows error: Unable to find the column of summary field for !0721O000005imeP

User-added image

Please Suggest.
Hello All,
I have written below code to parse values of excel sheet. It works fine if no of records is upto 4. But if i insert records beyond 4, i.e either 5 or 6 records, parse button didnt works. Below is the code.
public with sharing class InvoiceImportController {

	public InvoiceImportController() {
	}

	@RemoteAction
	public static Map<String, List<String>> getValidationData(string invoices, string invoiceDetails, string vendorBills, string vendorBillDetails) {

		Map<String, List<String>> outputMap = new Map<String, List<String>> ();

		// Parse the raw data
		List<invoiceStruct> invoiceList = parseInvoiceHeaders(invoices);
		List<invoiceDetailStruct> detailList = parseInvoiceDetails(invoiceDetails);
		List<vendorBillStruct> billList = parseVendorBills(vendorBills);
		List<vendorBillDetailStruct> billDetailList = parseVendorBillDetails(vendorBillDetails);

		// Capture the data points to validate
		Set<String> customerIds = new Set<String> ();
		Set<String> glAccountIds = new Set<String> ();
		Set<String> itemIds = new Set<String> ();
		Set<String> vendorIds = new Set<String> ();

		for (invoiceStruct inv : invoiceList) {
			customerIds.add(inv.record.Customer_ID__c);
			glAccountIds.add(inv.record.GL_Account_Id__c);
		}
		for (invoiceDetailStruct invDetail : detailList) {
			itemIds.add(invDetail.record.Item_Id__c);
		}
		for (vendorBillStruct vb : billList) {
			customerIds.add(vb.record.Customer__c);
			glAccountIds.add(vb.record.GL_Account_Id__c);
			vendorIds.add(vb.record.Vendor_Id__c);
		}
		for (vendorBillDetailStruct vbd : billDetailList) {
			itemIds.add(vbd.record.Item_Id__c);
		}

		Map<Id, Account> customerIdMap = new Map<Id, Account> ([select id from account where id in :customerIds]);
		Map<Id, GL_Account__c> glAccountIdMap = new Map<Id, GL_Account__c> ([select id from gl_account__c where id in :glAccountIds]);
		Map<Id, Netsuite_Item__c> itemIdMap = new Map<Id, Netsuite_Item__c> ([Select id from Netsuite_Item__c where id in :itemIds]);
		Map<Id, Account> vendorIdMap = new Map<Id, Account> ([Select id from Account where id in :vendorIds]);

		List<String> picklistInvoiceLocations = getPickListValuesIntoList('Invoice_Header__c', 'Location__c');
		List<String> picklistInvoiceStatuses = getPickListValuesIntoList('Invoice_Header__c', 'Invoicing_Status__c');
		List<String> picklistInvoiceRemitTos = getPickListValuesIntoList('Invoice_Header__c', 'Remit_to_Bank__c');
		List<String> picklistInvoiceDetailLocations = getPickListValuesIntoList('Invoice_Detail__c', 'Location__c');
		List<String> picklistVendorBillLocations = getPickListValuesIntoList('Vendor_Bill__c', 'Location__c');
		//List<String> picklistVendorBillTerms = getPickListValuesIntoList('Vendor_Bill__c', 'Terms__c');
		List<String> picklistVendorBillDetailLocations = getPickListValuesIntoList('Vendor_Bill_Detail__c', 'Location__c');

		outputMap.put('CustomerIds', new List<Id> (customerIdMap.keySet()));
		outputMap.put('GLAccountIds', new List<Id> (glAccountIdMap.keySet()));
		outputMap.put('ItemIds', new List<Id> (itemIdMap.keySet()));
		outputMap.put('VendorIds', new List<Id> (vendorIdMap.keySet()));
		outputMap.put('InvoiceLocations', picklistInvoiceLocations);
		outputMap.put('InvoiceStatuses', picklistInvoiceStatuses);
		outputMap.put('InvoiceRemitTos', picklistInvoiceRemitTos);
		outputMap.put('InvoiceDetailLocations', picklistInvoiceDetailLocations);
		outputMap.put('VendorBillLocations', picklistVendorBillLocations);
		//outputMap.put('VendorBillTerms', picklistVendorBillTerms);
		outputMap.put('VendorBillDetailLocations', picklistVendorBillDetailLocations);


		System.debug(outputMap);
		System.debug(glAccountIdMap);
		return outputMap;
	}

	public static List<String> getPickListValuesIntoList(String sobjectname, String fieldapiName) {
		List<String> pickListValuesList = new List<String> ();
		List<Schema.PicklistEntry> ple = Schema.getGlobalDescribe().get(sobjectname).getDescribe().fields.getMap().get(fieldApiName).getDescribe().getPicklistValues();
		for (Schema.PicklistEntry pickListVal : ple) {
			pickListValuesList.add(pickListVal.getLabel());
		}
		return pickListValuesList;
	}

	@RemoteAction
	public static Map<String, Object> loadData(string invoices, string invoiceDetails, string vendorBills, string vendorBillDetails) {
		System.debug('remoting loadData');
		Map<String, Object> retMap = new Map<String, Object> ();
		retMap.put('errors', new Map<String, Object> ());
		retMap.put('records', new Map<String, List<recordStruct>> ());
		List<recordStruct> retInvoices = new List<recordStruct> ();
		List<recordStruct> retInvoiceDetails = new List<recordStruct> ();
		List<recordStruct> retVendorBills = new List<recordStruct> ();
		List<recordStruct> retVendorBillDetails = new List<recordStruct> ();



		List<invoiceStruct> invoiceList;
		List<invoiceDetailStruct> detailList;
		List<vendorBillStruct> billList;
		List<vendorBillDetailStruct> billDetailList;
		try {
			invoiceList = parseInvoiceHeaders(invoices);
			detailList = parseInvoiceDetails(invoiceDetails);
			billList = parseVendorBills(vendorBills);
			billDetailList = parseVendorBillDetails(vendorBillDetails);
		} catch(Exception e) {
			((Map<String, Object>) retMap.get('errors')).put('Parse', e.getMessage());
			return retMap;
		}

		Set<String> accountIds = new Set<String> ();
		for (invoiceStruct inv : invoiceList) {
			accountIds.add(inv.record.Customer_ID__c);
		}

		Map<Id, Account> accountAddresses =
		new Map<Id, Account> ([select Id, Name,
		                      ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry,
		                      BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry,
		                      Phone, Phone__c, Phone_2__c, Email__c, Fax
		                      from Account where id in :accountIds]);

		Savepoint sp = Database.setSavepoint();
		try {
			// Invoices
			List<Invoice_Header__c> newInvoices = new List<Invoice_Header__c> ();
			for (invoiceStruct inv : invoiceList) {
				Invoice_Header__c record = inv.record;
				Account acct = accountAddresses.get(record.Customer_ID__c);
				record.Billing_Addressee__c = acct.Name;
				record.Billing_Line_1__c = acct.BillingStreet;
				record.Billing_City__c = acct.BillingCity;
				record.Billing_State__c = acct.BillingState;
				record.Billing_Zip__c = acct.BillingPostalCode;
				record.Billing_Country__c = acct.BillingCountry;
				record.Shipping_Addressee__c = acct.Name;
				record.Shipping_Line_1__c = acct.ShippingStreet;
				record.Shipping_City__c = acct.ShippingCity;
				record.Shipping_State__c = acct.ShippingState;
				record.Shipping_Zip__c = acct.ShippingPostalCode;
				record.Shipping_Country__c = acct.ShippingCountry;
				record.Fax__c = acct.Fax;
				record.Billing_Phone__c = acct.Phone__c;
				record.Shipping_Phone__c = acct.Phone_2__c;
				record.Email__c = acct.Email__c;
				newInvoices.add(inv.record);
			}
			insert newInvoices;
			Map<String, Invoice_Header__c> invoiceMap = new Map<String, Invoice_Header__c> ();
			for (invoiceStruct inv : invoiceList) {
				invoiceMap.put(inv.tmpId, inv.record);
				recordStruct r = new recordStruct();
				r.tmpId = inv.tmpId;
				r.Id = inv.record.Id;
				retInvoices.add(r);
			}

			// Vendor Bills
			List<Vendor_Bill__c> newVendorBills = new List<Vendor_Bill__c> ();
			for (vendorBillStruct bill : billList) {
				newVendorBills.add(bill.record);
			}
			insert newVendorBills;
			Map<String, Vendor_Bill__c> vendorBillMap = new Map<String, Vendor_Bill__c> ();
            List<Vendor_Payment__c> vendorPayments = new List<Vendor_Payment__c>();
			for (vendorBillStruct bill : billList) {
				vendorBillMap.put(bill.tmpId, bill.record);
                if(bill.paymentRecord.Payment_Date__c != null){
                    bill.paymentRecord.Vendor_Bill_Id__c = bill.record.Id;    
                    vendorPayments.add(bill.paymentRecord);
                }
				recordStruct r = new recordStruct();
				r.tmpId = bill.tmpId;
				r.Id = bill.record.Id;
				retVendorBills.add(r);
			}
            if(vendorPayments.size() > 0)
                insert vendorPayments;
			List<Vendor_Bill_Detail__c> newVendorBillDetails = new List<Vendor_Bill_Detail__c> ();
			for (vendorBillDetailStruct billDetail : billDetailList) {
				billDetail.record.Vendor_Bill_Id__c = vendorBillMap.get(billDetail.tmpIdVendorBill).Id;
				billDetail.record.Customer_Id__c = vendorBillMap.get(billDetail.tmpIdVendorBill).Customer__c;
				newVendorBillDetails.add(billDetail.record);
			}
			insert newVendorBillDetails;
			for (vendorBillDetailStruct billDetail : billDetailList) {
				recordStruct r = new recordStruct();
				r.tmpId = billDetail.tmpId;
				r.Id = billDetail.record.Id;
				retVendorBillDetails.add(r);
			}

			List<Invoice_Detail__c> newInvoiceDetails = new List<Invoice_Detail__c> ();
			for (invoiceDetailStruct invDetail : detailList) {
				invDetail.record.Vendor_Bill_Id__c = vendorBillMap.get(invDetail.tmpIdVendorBill).Id;
				invDetail.record.Invoice_Header__c = invoiceMap.get(invDetail.tmpIdInvoice).Id;
				newInvoiceDetails.add(invDetail.record);
			}
			insert newInvoiceDetails;
			for (invoiceDetailStruct invDetail : detailList) {
				recordStruct r = new recordStruct();
				r.tmpId = invDetail.tmpId;
				r.Id = invDetail.record.Id;
				retInvoiceDetails.add(r);
			}
		} catch(Exception e) {
			database.rollback(sp);
			((Map<String, Object>) retMap.get('errors')).put('Insert: ', e.getMessage());
			return retMap;
		}

		((Map<String, Object>) retMap.get('records')).put('Invoices', retInvoices);
		((Map<String, Object>) retMap.get('records')).put('Invoice Details', retInvoiceDetails);
		((Map<String, Object>) retMap.get('records')).put('Vendor Bills', retVendorBills);
		((Map<String, Object>) retMap.get('records')).put('Vendor Bill Details', retVendorBillDetails);

		return retMap;
	}


	public static List<invoiceStruct> parseInvoiceHeaders(string invoices) {
		List<invoiceStruct> invoiceList = new List<invoiceStruct> ();
		List<Object> invoiceJSON = (List<Object>) JSON.deserializeUntyped(invoices);
		Id rt = Schema.SObjectType.Invoice_Header__c.RecordTypeInfosByName.get('Treasury').RecordTypeId;
		for (Object obj : invoiceJSON) {
			Invoice_Header__c row = new Invoice_Header__c();
			row.RecordTypeId = rt;
			Map<String, Object> raw = (Map<String, Object>) obj;
			string tmpId = (string) ((Map<String, Object>) raw.get('tmpId')).get('value');

			// Lookups
			row.Customer_ID__c = stringId(raw, 'Customer_ID__c');
			row.GL_Account_Id__c = stringId(raw, 'GL_Account_Id__c');

			row.Location__c = (string) ((Map<String, Object>) raw.get('Location__c')).get('value');
			row.Terms__c = (string) ((Map<String, Object>) raw.get('Terms__c')).get('value');
			row.Invoicing_Status__c = (string) ((Map<String, Object>) raw.get('Invoicing_Status__c')).get('value');
			row.Remit_to_Bank__c = (string) ((Map<String, Object>) raw.get('Remit_to_Bank__c')).get('value');

			row.Customer_PO__c = (string) ((Map<String, Object>) raw.get('Customer_PO__c')).get('value');
			row.Invoice_Period__c = (string) ((Map<String, Object>) raw.get('Invoice_Period__c')).get('value');
			row.Memo__c = (string) ((Map<String, Object>) raw.get('Memo__c')).get('value');

			//string dueDate = (string) ((Map<String, Object>) raw.get('Due_Date__c')).get('value');
			string coverageDate = (string) ((Map<String, Object>) raw.get('Coverage_Month__c')).get('value');
			string documentDate = (string) ((Map<String, Object>) raw.get('Document_Date__c')).get('value');

			//row.Due_Date__c = dueDate == '' ? null : Date.parse(dueDate);
			row.Coverage_Month__c = coverageDate == '' ? null : Date.parse(coverageDate);
			row.Document_Date__c = documentDate == '' ? null : Date.parse(documentDate);

			invoiceStruct struct = new invoiceStruct();
			struct.tmpId = tmpId;
			struct.record = row;
			invoiceList.add(struct);
		}
		return invoiceList;
	}

	public static List<invoiceDetailStruct> parseInvoiceDetails(string invoiceDetails) {
		List<invoiceDetailStruct> invoiceDetailList = new List<invoiceDetailStruct> ();

		List<Object> detailJSON = (List<Object>) JSON.deserializeUntyped(invoiceDetails);
		Id rt = Schema.SObjectType.Invoice_Detail__c.RecordTypeInfosByName.get('Treasury').RecordTypeId;
		for (Object obj : detailJSON) {
			Invoice_Detail__c row = new Invoice_Detail__c();
			row.RecordTypeId = rt;
			Map<String, Object> raw = (Map<String, Object>) obj;
			string tmpId = (string) ((Map<String, Object>) raw.get('tmpId')).get('value');
			string invoiceId = (string) ((Map<String, Object>) raw.get('Invoice_Header__c')).get('value');
			string vendorBillId = (string) ((Map<String, Object>) raw.get('Vendor_Bill_Id__c')).get('value');

			// Lookups
			row.Item_Id__c = stringId(raw, 'Item_Id__c');

			row.Location__c = (string) ((Map<String, Object>) raw.get('Location__c')).get('value');
			row.Item_Description__c = (string) ((Map<String, Object>) raw.get('Item_Description__c')).get('value');
			row.Policy_Number__c = (string) ((Map<String, Object>) raw.get('Policy_Number__c')).get('value');
			row.Memo__c = (string) ((Map<String, Object>) raw.get('Memo__c')).get('value');
			row.Ordinal__c = Decimal.valueOf((string) ((Map<String, Object>) raw.get('Ordinal__c')).get('value'));
			row.Unit_Price__c = Decimal.valueOf((string) ((Map<String, Object>) raw.get('Unit_Price__c')).get('value'));
			//row.Quantity__c = Decimal.valueOf((String) ((Map<String, Object>) raw.get('Quantity__c')).get('value'));
			//row.Vendor_Bill_Total__c = Decimal.valueOf((String) ((Map<String, Object>) raw.get('Vendor_Bill_Total__c')).get('value'));
			//row.Doc_Number__c = (string) ((Map<String, Object>) raw.get('Doc_Number__c')).get('value');
			row.Ignore_Vendor_Bill_Amount__c = boolean.valueOf((string) ((Map<String, Object>) raw.get('Ignore_Vendor_Bill_Amount__c')).get('value'));
			row.Is_Applied__c = boolean.valueOf((string) ((Map<String, Object>) raw.get('Is_Applied__c')).get('value'));

			invoiceDetailStruct struct = new invoiceDetailStruct();
			struct.tmpId = tmpId;
			struct.tmpIdInvoice = invoiceId;
			struct.tmpIdVendorBill = vendorBillId;
			struct.record = row;
			invoiceDetailList.add(struct);
		}

		return invoiceDetailList;
	}

	public static List<vendorBillStruct> parseVendorBills(string vendorBills) {
		List<vendorBillStruct> vendorBillList = new List<vendorBillStruct> ();
		List<Object> vendorBillJSON = (List<Object>) JSON.deserializeUntyped(vendorBills);
		//Id rt = Schema.SObjectType.Vendor_Bill__c.RecordTypeInfosByName.get('Treasury').RecordTypeId;

		for (Object obj : vendorBillJSON) {
			Vendor_Bill__c row = new Vendor_Bill__c();

			Map<String, Object> raw = (Map<String, Object>) obj;
			string tmpId = (string) ((Map<String, Object>) raw.get('tmpId')).get('value');
			// Lookups
			row.Customer__c = stringId(raw, 'Customer__c');
			row.GL_Account_Id__c = stringId(raw, 'GL_Account_Id__c');
			row.Vendor_Id__c = stringId(raw, 'Vendor_Id__c');

			row.Location__c = (string) ((Map<String, Object>) raw.get('Location__c')).get('value');
			//row.Terms__c = (string) ((Map<String, Object>) raw.get('Terms__c')).get('value');
			row.Memo__c = (string) ((Map<String, Object>) raw.get('Memo__c')).get('value');
			row.Vendor_Description__c = (string) ((Map<String, Object>) raw.get('Vendor_Description__c')).get('value');
			row.Ordinal__c = Decimal.valueOf((string) ((Map<String, Object>) raw.get('Ordinal__c')).get('value'));
			//row.Tran_Id__c = (string) ((Map<String, Object>) raw.get('Tran_Id__c')).get('value');
			row.Pay_By_ACH__c = Boolean.valueOf((string) ((Map<String, Object>) raw.get('Pay_By_ACH__c')).get('value'));

			//string dueDate = (string) ((Map<String, Object>) raw.get('Due_Date__c')).get('value');
			//string transDate = (string) ((Map<String, Object>) raw.get('Trans_Date__c')).get('value');
			string coverageFromDate = (string) ((Map<String, Object>) raw.get('Coverage_From__c')).get('value');
			string coverageToDate = (string) ((Map<String, Object>) raw.get('Coverage_To__c')).get('value');
			//row.Due_Date__c = dueDate == '' ? null : Date.parse(dueDate);
			//row.Trans_Date__c = transDate == '' ? null : Date.parse(transDate);
			row.Coverage_From__c = coverageFromDate == '' ? null : Date.parse(coverageFromDate);
			row.Coverage_To__c = coverageToDate == '' ? null : Date.parse(coverageToDate);
            string paymentDate = (string) ((Map<String, Object>) raw.get('Payment_Date__c')).get('value');
            
			vendorBillStruct struct = new vendorBillStruct();
			struct.tmpId = tmpId;
			struct.record = row;
            struct.paymentRecord =  new Vendor_Payment__c();
			struct.paymentRecord.Payment_Date__c = paymentDate == '' ? null : Date.parse(paymentDate);
			vendorBillList.add(struct);
		}
		return vendorBillList;
	}

	public static List<vendorBillDetailStruct> parseVendorBillDetails(string vendorBillDetails) {
		List<vendorBillDetailStruct> vendorBillDetailList = new List<vendorBillDetailStruct> ();
		List<Object> vendorBillDetailJSON = (List<Object>) JSON.deserializeUntyped(vendorBillDetails);
		for (Object obj : vendorBillDetailJSON) {
			Vendor_Bill_Detail__c row = new Vendor_Bill_Detail__c();
			Map<String, Object> raw = (Map<String, Object>) obj;
			string tmpId = (string) ((Map<String, Object>) raw.get('tmpId')).get('value');
			string vendorBillId = (string) ((Map<String, Object>) raw.get('Vendor_Bill_Id__c')).get('value');

			// Lookups
			row.Item_Id__c = stringId(raw, 'Item_Id__c');

			row.Location__c = (string) ((Map<String, Object>) raw.get('Location__c')).get('value');
			row.Is_Billable__c = Boolean.valueOf((string) ((Map<String, Object>) raw.get('Is_Billable__c')).get('value'));
			row.Description__c = (string) ((Map<String, Object>) raw.get('Description__c')).get('value');
			row.Policy_Number__c = (string) ((Map<String, Object>) raw.get('Policy_Number__c')).get('value');
			row.Cost_Center__c = (string) ((Map<String, Object>) raw.get('Cost_Center__c')).get('value');
			row.Invoice_Number__c = (string) ((Map<String, Object>) raw.get('Invoice_Number__c')).get('value');
			row.Rate__c = Decimal.valueOf((string) ((Map<String, Object>) raw.get('Rate__c')).get('value'));
			row.Quantity__c = Decimal.valueOf((string) ((Map<String, Object>) raw.get('Quantity__c')).get('value'));
			//if (!vendorBillDetailMap.keySet().contains(tmpId)) { vendorBillDetailMap.add(tmpId, new List<Vendor_Bill_Detail__c> ()); }
			//vendorBillDetailMap.get(vendorBillId).add(row);

			vendorBillDetailStruct struct = new vendorBillDetailStruct();
			struct.tmpId = tmpId;
			struct.tmpIdVendorBill = vendorBillId;
			struct.record = row;
			vendorBillDetailList.add(struct);

		}
		return vendorBillDetailList;
	}
	public static string stringId(Map<String, Object> raw, string fieldName) {
		string itemId = (string) ((Map<String, Object>) raw.get(fieldName)).get('value');
		if (itemId.length() == 15 || itemId.length() == 18) {
			return itemId;
		}
		return null;
	}

	class invoiceStruct {
		public Invoice_Header__c record;
		public string tmpId;
	}
	class invoiceDetailStruct {
		public Invoice_Detail__c record;
		public string tmpId;
		public string tmpIdInvoice;
		public string tmpIdVendorBill;
	}
	class vendorBillStruct {
		public Vendor_Bill__c record;
        public Vendor_Payment__c paymentRecord;
		public string tmpId;
	}
	class vendorBillDetailStruct {
		public Vendor_Bill_Detail__c record;
		public string tmpId;
		public string tmpIdVendorBill;
	}
	class recordStruct {
		public string tmpId;
		public Id Id;
	}
}

 
Hello All, Below is my Apex class
@RestResource(urlMapping='/Tasks/*')
global class GetTasksFromTeamWork {
    @HttpPost
    global static void handleTWTaskRequest() {
        RestRequest req = RestContext.request;
        String jsonresponse = req.requestBody.toString();
        system.debug('jsonresponse'+jsonresponse);
        TeamworkIntegarionUtility.TasksWrapper tasksObj = (TeamworkIntegarionUtility.TasksWrapper)JSON.deserialize(jsonresponse, TeamworkIntegarionUtility.TasksWrapper.class);
        try
        {
            TW_Task_List__c taskListRefference = new TW_Task_List__c(TaskListId__c = tasksObj.task.taskListId);
            // Contact contactRefference = new Contact(UserId__c = tasksObj.task.taskListId);
            
            TW_Task__c twTasksobj = new TW_Task__c();
            twTasksobj.Name = tasksObj.task.name;
            twTasksobj.TW_Description__c = tasksObj.task.description;
            twTasksobj.TW_Due_Date__c =  Date.valueOf(tasksObj.task.dueDate);
            twTasksobj.TW_Progress__c = Decimal.valueOf(tasksObj.task.progress);
            twTasksobj.TW_Priority__c = tasksObj.task.priority;
            twTasksobj.TW_Start_Date__c =  Date.valueOf(tasksObj.task.startDate);
            twTasksobj.TW_Estimated_Total_Time__c = Decimal.valueOf(tasksObj.task.estimatedMinutes);
            twTasksobj.TaskId__c = tasksObj.task.id;
            twTasksobj.TW_Task_List_Name__r = taskListRefference;
            if(tasksObj.task.parentId != null && tasksObj.task.parentId != '0'){
                TW_Task__c parentTaskRefference = new TW_Task__c(TaskId__c = tasksObj.task.parentId);
                twTasksobj.TW_Parent_Task__r = parentTaskRefference;
            }
            system.debug('twTasksobj =>'+twTasksobj);
            upsert twTasksobj TaskId__c;
            
            If(!tasksObj.task.assignedUserIds.isEmpty()){
                List<TW_Milestone_Task_User__c> milestoneTaskUserObjList = new  List<TW_Milestone_Task_User__c>();
                for(String userId : tasksObj.task.assignedUserIds) {
                    TW_Milestone_Task_User__c milestoneTaskUserObj = new TW_Milestone_Task_User__c();
                    milestoneTaskUserObj.TW_User_ID__r = new Contact(UserId__c = userId);
                    milestoneTaskUserObj.TW_Task_ID__c = twTasksobj.Id;
                    milestoneTaskUserObjList.add(milestoneTaskUserObj);
                }
                upsert milestoneTaskUserObjList;
           }
        }
        catch(Exception ex)
        {
            string sfId = TeamworkIntegarionUtility.getSaleforceIDByExtenalID('TW_Task__c','TaskId__c',tasksObj.task.id);
            if(!string.isBlank(sfId))
            {
                TW_Task__c task = new TW_Task__c(ID = sfId);
                task.TW_Sync_status__c = 'Failed';
                update task;
            }
            TeamworkIntegarionUtility.logError(tasksObj.task.id,ex.getMessage(),'','TW_Task__c', sfId);
        }
    }
}
I have Test class for it. But i am getting code coverage of 74%. Can somebody plz help me to achieve 75% for below Test class
@isTest
public class GetTasksFromTeamWorkTest {
    
    static testMethod void testPostTask() {
        
        //Insert Records
        Account acc = new Account(Name = 'Testing');
        insert acc;
        
        String Uid = UserInfo.getUserId();
        
        Contact con = new Contact(LastName = 'TestCon',Title = 'Testing ', Phone = '1223456789', Email = 'test123@gmail.com', UserId__c = Uid);
        insert con;
        
        Opportunity OppObj = new Opportunity (Name = 'Opp Test', AccountId = acc.Id, StageName= 'Qualification', CloseDate = system.today()+2);
        insert OppObj;
        
        TW_Project__c projObj = new TW_Project__c(Name = 'Test Project', TW_Opportunity__c = OppObj.Id , ProjectId__c = '438022');
        insert projObj;
        
        TW_Milestone__c milestoneObj = new TW_Milestone__c(Name = 'Test Milestone', MilestoneId__c = '2233', TW_Project__c = projObj.Id);
        insert milestoneObj;
        
        TW_Task_List__c taskListObj = new TW_Task_List__c(Name = 'Test TaskList', TW_Project__c = projObj.Id, TW_Milestone__c = milestoneObj.Id , TaskListId__c = '2336');
        insert taskListObj;
        
        TW_Task__c taskObj = new TW_Task__c(Name = 'Test Task', TaskId__c = '1234', TW_Task_List_Name__c = taskListObj.Id);
        insert taskObj;
        
        TeamworkIntegarionUtility.eventCreator eveCreaObj = new TeamworkIntegarionUtility.eventCreator();
        //eveCreaObj.id;
        eveCreaObj.firstName = 'eventCreator';
        eveCreaObj.lastName = 'Test';
        
        TeamworkIntegarionUtility.Project project = new TeamworkIntegarionUtility.Project();
        project.Id=projObj.Id;
        Project.name='Ptest';
        Project.description='testing1';
        Project.status='complete';
        Project.ownerId='001';
        Project.companyId='00121';
        Project.categoryId='121';
        
        TeamworkIntegarionUtility.Task task = new TeamworkIntegarionUtility.Task();
        task.Id=taskObj.Id;
        task.name='test';
        task.description='testing';
        task.priority='low';
        task.status='open';
        task.progress=1;
        task.estimatedMinutes=10;
        task.hasCustomFields=true;
        task.projectId=projObj.ProjectId__c;
        task.dueDate=String.valueOf(Date.today().addMonths(1));
        task.startDate=String.valueOf(Date.today());
        
        TeamworkIntegarionUtility.TaskList taskList = new TeamworkIntegarionUtility.TaskList();
        Tasklist.Id=taskListObj.TaskListId__c;
        Tasklist.name='Sample test';
        Tasklist.description='Testing sample';
        Tasklist.milestoneId='001';
        Tasklist.projectId=projObj.ProjectId__c;
        
        task.taskListId = Tasklist.Id;
        TeamworkIntegarionUtility.TasksWrapper wrapTask = new TeamworkIntegarionUtility.TasksWrapper();
        wrapTask.eventCreator = eveCreaObj;
        wrapTask.project = project;
        wrapTask.task = task;
        wrapTask.taskList = taskList;
        String myJSON = JSON.serialize(wrapTask);
        
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/GetTasksFromTeamWork/';
        req.httpMethod = 'POST';
        req.requestBody = Blob.valueof(myJSON);
        RestContext.request = req;
        RestContext.response= res;
        GetTasksFromTeamWork.handleTWTaskRequest();
    }
    
    static testMethod void testPostTask_Error() {
        
        //Insert Records
        Account acc = new Account(Name = 'Testing');
        insert acc;
        
        String Uid = UserInfo.getUserId();
        
        Contact con = new Contact(LastName = 'TestCon',Title = 'Testing ', Phone = '1223456789', Email = 'test123@gmail.com', UserId__c = Uid);
        insert con;
        
        Opportunity OppObj = new Opportunity (Name = 'Opp Test', AccountId = acc.Id, StageName= 'Qualification', CloseDate = system.today()+2);
        insert OppObj;
        
        TW_Project__c projObj = new TW_Project__c(Name = 'Test Project', TW_Opportunity__c = OppObj.Id , ProjectId__c = '438022');
        insert projObj;
        
        TW_Milestone__c milestoneObj = new TW_Milestone__c(Name = 'Test Milestone', MilestoneId__c = '2233', TW_Project__c = projObj.Id);
        insert milestoneObj;
        
        TW_Task_List__c taskListObj = new TW_Task_List__c(Name = 'Test TaskList', TW_Project__c = projObj.Id, TW_Milestone__c = milestoneObj.Id , TaskListId__c = '2336');
        insert taskListObj;
        
        TW_Task__c taskObj = new TW_Task__c(Name = 'Test Task', TaskId__c = '1234', TW_Task_List_Name__c = taskListObj.Id);
        insert taskObj;
        
        TeamworkIntegarionUtility.eventCreator eveCreaObj = new TeamworkIntegarionUtility.eventCreator();
        //eveCreaObj.id;
        eveCreaObj.firstName = 'eventCreator';
        eveCreaObj.lastName = 'Test';
        
        TeamworkIntegarionUtility.Project project = new TeamworkIntegarionUtility.Project();
        project.Id=projObj.Id;
        Project.name='Ptest';
        Project.description='testing1';
        Project.status='complete';
        Project.ownerId='001';
        Project.companyId='00121';
        Project.categoryId='121';
        
        TeamworkIntegarionUtility.Task task = new TeamworkIntegarionUtility.Task();
        task.Id=taskObj.Id;
        task.name='test';
        task.description='testing';
        task.priority='low';
        task.status='open';
        task.progress=1;
        task.estimatedMinutes=10;
        task.hasCustomFields=true;
        task.dueDate=String.valueOf(Date.today().addMonths(1));
        task.startDate=String.valueOf(Date.today());
        
        TeamworkIntegarionUtility.TasksWrapper wrapTask = new TeamworkIntegarionUtility.TasksWrapper();
        wrapTask.eventCreator = eveCreaObj;
        wrapTask.project = project;
        wrapTask.task = task;
        //wrapTask.taskList = taskList;
        String myJSON = JSON.serialize(wrapTask);
        
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/GetTasksFromTeamWork/';
        req.httpMethod = 'POST';
        req.requestBody = Blob.valueof(myJSON);
        RestContext.request = req;
        RestContext.response= res;
        GetTasksFromTeamWork.handleTWTaskRequest();
    }
}


 
Hello All,
I have cretaed scratch org from production org. But now production org features such as installed packages are not getting displayed in scratch org. Could anybody help me to achieve the same? 
Hello Team, I want to create a scratch org. But it is giving error
Socket timeout occurred while listening for results.
DevHub is also enabled. Please help to resolve issue.

 
Hello All, I have written below Apex Class and its Test Class... Can somebody help me to achieve 100% code coverage?

Apex Class
@RestResource(urlMapping='/Tasks/*')
global class GetTasksFromTeamWork {
	@HttpPost
    global static void handleTWTaskRequest() {
        RestRequest req = RestContext.request;
        String jsonresponse = req.requestBody.toString();
        system.debug('jsonresponse'+jsonresponse);
        TasksWrapper tasksObj = (TasksWrapper)JSON.deserialize(jsonresponse, TasksWrapper.class);
        
        TW_Task_List__c taskListRefference = new TW_Task_List__c(TaskListId__c = tasksObj.task.taskListId);
        // Contact contactRefference = new Contact(UserId__c = tasksObj.task.taskListId);
        
        TW_Task__c twTasksobj = new TW_Task__c();
        twTasksobj.Name = tasksObj.task.name;
        twTasksobj.TW_Description__c = tasksObj.task.description;
        twTasksobj.TW_Due_Date__c =  Date.valueOf(tasksObj.task.dueDate);
        twTasksobj.TW_Progress__c = Decimal.valueOf(tasksObj.task.progress);
        twTasksobj.TW_Priority__c = tasksObj.task.priority;
        twTasksobj.TW_Start_Date__c =  Date.valueOf(tasksObj.task.startDate);
        twTasksobj.TW_Estimated_Total_Time__c = Decimal.valueOf(tasksObj.task.estimatedMinutes);
        twTasksobj.TaskId__c = tasksObj.task.id;
        twTasksobj.TW_Task_List_Name__r = taskListRefference;
        if(tasksObj.task.parentId != '0'){
            TW_Task__c parentTaskRefference = new TW_Task__c(TaskId__c = tasksObj.task.parentId);
            twTasksobj.TW_Parent_Task__r = parentTaskRefference;
        }
        system.debug('twTasksobj =>'+twTasksobj);
        upsert twTasksobj TaskId__c;
    }
    
    public class TasksWrapper{
        public EventCreator eventCreator;
        public Project project;
        public Task  task;
        public TaskList taskList;
        public List<Tags> users;
     }
    
    public class Project {
		public String id;
		public String name;
		public String description;
		public String status;
		public Object startDate;
		public Object endDate;
		public List<Tags> tags;
		public Integer ownerId;
		public Integer companyId;
		public Integer categoryId;
		public String dateCreated;
	}

	public class Task {
		public String id;
		public String name;
		public String description;
		public String priority;
		public String status;
		public List<Tags> assignedUserIds;
		public String parentId;
		public String taskListId;
		public String startDate;
		public String dueDate;
		public Integer progress;
		public Integer estimatedMinutes;
		public List<Tags> tags;
		public Integer projectId;
		public String dateCreated;
		public String dateUpdated;
		public Boolean hasCustomFields;
	}

	
	

	public class TaskList {
		public Integer id;
		public String name;
		public String description;
		public String status;
		public Integer milestoneId;
		public Integer projectId;
		public Object templateId;
		public List<Tags> tags;
	}

	public class EventCreator {
		public Integer id;
		public String firstName;
		public String lastName;
		public String avatar;
	}

	public class Tags {
	}

}
Test Class
@isTest
public class GetTasksFromTeamWorkTest {
    
    static testMethod void testPost() {
        
        //Insert Records
        Account acc = new Account(Name = 'Testing');
        insert acc;
        
        String Uid = UserInfo.getUserId();
        
        Contact con = new Contact(LastName = 'TestCon',Title = 'Testing ', Phone = '1223456789', Email = 'test123@gmail.com', UserId__c = Uid);
        insert con;
        
        Opportunity OppObj = new Opportunity (Name = 'Opp Test', AccountId = acc.Id, StageName= 'Qualification', CloseDate = system.today()+2);
        insert OppObj;
        
        TW_Project__c projObj = new TW_Project__c(Name = 'Test Project', TW_Opportunity__c = OppObj.Id , ProjectId__c = '438022');
        insert projObj;
        
        TW_Milestone__c milestoneObj = new TW_Milestone__c(Name = 'Test Milestone', MilestoneId__c = '2233', TW_Project__c = projObj.Id);
        insert milestoneObj;
        
        TW_Task_List__c taskListObj = new TW_Task_List__c(Name = 'Test TaskList', TW_Project__c = projObj.Id, TW_Milestone__c = milestoneObj.Id , TaskListId__c = '2336');
        insert taskListObj;
        
        TW_Task__c taskObj = new TW_Task__c(Name = 'Test Task', TaskId__c = '1234', TW_Task_List_Name__c = taskListObj.Id);
        insert taskObj;
        
        TW_Time__c timeObj = new TW_Time__c(TW_Project__c = projObj.Id,TW_Who__c = con.Id, TimeId__c = '2336', TW_Task__c = taskObj.Id);
        insert timeObj;
        
        GetTasksFromTeamWork.eventCreator eveCreaObj = new GetTasksFromTeamWork.eventCreator();
        //eveCreaObj.id;
		eveCreaObj.firstName = 'eventCreator';
		eveCreaObj.lastName = 'Test';
        
        GetTasksFromTeamWork.Project project = new GetTasksFromTeamWork.Project();
        GetTasksFromTeamWork.Task task = new GetTasksFromTeamWork.Task();
        GetTasksFromTeamWork.TaskList taskList = new GetTasksFromTeamWork.TaskList();
        
        GetTasksFromTeamWork.TasksWrapper wrapTask = new GetTasksFromTeamWork.TasksWrapper();
        wrapTask.eventCreator = eveCreaObj;
        wrapTask.project = project;
        wrapTask.task = task;
        wrapTask.taskList = taskList;
        String myJSON = JSON.serialize(wrapTask);
        
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/GetTasksFromTeamWork/';
        req.httpMethod = 'POST';
        req.requestBody = Blob.valueof(myJSON);
        RestContext.request = req;
        RestContext.response= res;
        GetTasksFromTeamWork.handleTWTaskRequest();
    }

}


 
@RestResource(urlMapping='/Projects/*')
global class GetProjectsFromTeamWork {
    @HttpPost
    global static void doPost() {
        RestRequest req = RestContext.request;
        String jsonresponse = req.requestBody.toString();
        system.debug('jsonresponse=='+jsonresponse);
        
        wrapperOfProject proj = (wrapperOfProject)JSON.deserialize(jsonresponse, wrapperOfProject.class);
        Contact contactRefference = new Contact(UserId__c = proj.Project.ownerId);
        List<Account> accList = [Select id From Account Where CompanyId__c = :proj.Project.companyId];
        system.debug('accList==='+accList);
        List<Opportunity> oppList = [Select id from Opportunity Where AccountId = :accList[0].id];
        System.debug('oppList==='+oppList);
        TW_Project__c projectObj = new TW_Project__c();
        projectObj.Name = proj.Project.name;
        projectObj.TW_Description__c = proj.Project.description;
        projectObj.TW_Opportunity__c = oppList[0].id;
        projectObj.ProjectId__c = proj.Project.id;
        projectObj.TW_Project_Manager__c = contactRefference.id;
        insert projectObj;
    }
    
    public class wrapperOfProject{
        public eventCreator eventCreator;
        public Project project;
    }
    
   	public class EventCreator {
		public Integer id;
		public String firstName;
		public String lastName;
		public String avatar;
	}
    
    public class Project {
		public String id;
		public String name;
		public String description;
		public String status;
		public Object startDate;
		public Object endDate;
		public List<Tags> tags;
		public String ownerId;
		public String companyId;
		public String categoryId;
		public String dateCreated;
	}
    
    public class Tags {
	}
}

 
Hello team, Plz help me for writing test class for code given below.
@RestResource(urlMapping='/Projects/*')
global class GetProjectsFromTeamWork {
    @HttpPost
    global static void doPost() {
        RestRequest req = RestContext.request;
        String jsonresponse = req.requestBody.toString();
        system.debug('jsonresponse=='+jsonresponse);
        
        wrapperOfProject proj = (wrapperOfProject)JSON.deserialize(jsonresponse, wrapperOfProject.class);
        Contact contactRefference = new Contact(UserId__c = proj.Project.ownerId);
        List<Account> accList = [Select id From Account Where CompanyId__c = :proj.Project.companyId];
        system.debug('accList==='+accList);
        List<Opportunity> oppList = [Select id from Opportunity Where AccountId = :accList[0].id];
        System.debug('oppList==='+oppList);
        TW_Project__c projectObj = new TW_Project__c();
        projectObj.Name = proj.Project.name;
        projectObj.TW_Description__c = proj.Project.description;
        projectObj.TW_Opportunity__c = oppList[0].id;
        projectObj.ProjectId__c = proj.Project.id;
        projectObj.TW_Project_Manager__c = contactRefference.id;
        insert projectObj;
    }
    
    public class wrapperOfProject{
        public eventCreator eventCreator;
        public Project project;
    }
    
   	public class EventCreator {
		public Integer id;
		public String firstName;
		public String lastName;
		public String avatar;
	}
    
    public class Project {
		public String id;
		public String name;
		public String description;
		public String status;
		public Object startDate;
		public Object endDate;
		public List<Tags> tags;
		public String ownerId;
		public String companyId;
		public String categoryId;
		public String dateCreated;
	}
    
    public class Tags {
	}
}
Hello Team,
i am writing Webservice and want to map json.But in debug log shows status ""For input string: "" at [line:1, column:218]..

Here is Json Response:
invoice":{"id":2651,"number":"In-151","poNumber":""}

Here is the code:
@RestResource(urlMapping='/Invoice/*')
global class GetInvoiceFromTeamWork {
	@HttpPost
    global static void doPost() {
        RestRequest req = RestContext.request;
        String jsonresponse = req.requestBody.toString();
        system.debug('jsonresponse'+jsonresponse);
        
        
        wrapperofInvoice wrapinvoice=(wrapperofInvoice)JSON.deserialize(jsonresponse, wrapperofInvoice.class);
        TW_Invoice__c inv =new TW_Invoice__c();
        inv.TW_Invoice_ID__c=wrapinvoice.invoice.id;
        
        //inv.TW_PO_Number__c=wrapinvoice.invoice.poNumber;
        insert inv;   
    }
    
    public class wrapperofInvoice{
        public eventCreator eventCreator;
        public Invoice invoice;
    }
    
    public class eventCreator {
        public String wholeJson;
    }
    
    public class invoice{
        Public integer id;
        public integer number;
        public decimal poNumber;
        public String description;
       public String Status;
        public String currencyCode;
	public String dateCreated;        
    }
}

 
Hello Team,
My requirement is that whenever record is created/edited in external application,it should get displayed in salesforce...How to perform this task? Please suggest..
Hi, i have written below code to retreive project information from Teamwork into Salesforce. But it is not reteriving projects. Instead its showing Not Authorised...
Public class RestApp1 {
public void basicAuthCallout(){
HttpRequest request=new HttpRequest();
request.setEndpoint('https://blueflamelab1.teamwork.com/projects.json');
request.setMethod('GET');
request.setHeader('Authorization','Bearer tkn.v1_OGZhNWRhNjYtZjVhOS00ZDBhLWJhODEtODVhZTA2MTgzYTE5LTcxMjQ3Ny40MTE3NTAuVVM=');
 Http http = new Http();
 HTTPResponse res = http.send(request);
 System.debug(res.getBody());   
}
}

 
Hi,
In my org, there are two objects Case and Project. Case object is having lookup relation with Project and Account Object. Now whenever, Case record is cretaed for particular Project, its asscoiated Account should get populated in case record. Plz help to write trigger for same.
public class StatusPublished implements database.Batchable<sobject>,Schedulable{

    public void execute(Schedulablecontext sc)
    {
         string cron='0 2 * * * ?*';
        StatusPublished sp =new StatusPublished();
        system.schedule('updatepaper', cron, sp);
      //database.executeBatch(sp);
    }
        public database.QueryLocator start(database.BatchableContext bc)
    {
        string query='select id,Name,Status__c from Research_Paper__c';
        return database.getQueryLocator(query);
    }
        public void execute(database.BatchableContext bc,list<Account> acc)
    {
        List<Research_Paper__c> rlist=new list<Research_Paper__c>();
        for(Research_Paper__c rp: rlist)
        {
            if(rp.Status__c=='Paper registration Complete')
            {
                rp.Status__c='Published';
                rlist.add(rp);
            }
        }
        update rlist;
    }
    
     public void finish(database.BatchableContext bc)
    {
 
    }

 
I am writing this trigger to prevent duplicate entry. But this trigger runs even at time of creating new record..How to resolve?
trigger TriggerOpp on Opportunity (before insert,before update) {
   set<id> setid=new set<id>();
    for(Opportunity opp:trigger.new)
    {
       setid.add(opp.AccountId);
    }
    
    Map<id,Account> acmap=new map<id,Account>();
    
    for(account acc:[select id,Name,(select id,Name,StageName from Opportunities) from Account where id in:setid])
    {
        acmap.put(acc.id,acc);
    }
    
    for(Opportunity opp:trigger.new)
    {
        if(acmap.containsKey(opp.AccountId) && acmap.get(opp.AccountId).Opportunities!=null)
        {
        
           {
               if(opp.StageName=='Prospecting')
               {
                     (opp.AccountId).addError('Duplicate value');
               }
           }
        }
    }
}
Scenario for trigger is that, if Opportunity Object having record with field stageName=='Prospecting ' and Parent Account name with,lets say XYZ.,so another record with same field value and same parent should not get duplicated.. I have written below trigger but it is showing error.

 
trigger TriggerOpp on Opportunity (before insert,before update) {
   set<id> setid=new set<id>();
    for(Opportunity opp:trigger.new)
    {
       setid.add(opp.AccountId);
    }
    
    Map<id,Account> acmap=new map<id,Account>();
    
    for(account acc:[select id,Name,(select id,Name,StageName from Opportunities) from Account where id in:setid])
    {
        acmap.put(acc.id,acc);
    }
    
    for(Opportunity opp:trigger.new)
    {
        if(acmap.containsKey(opp.AccountId))
        {
           if(acmap.get(opp.AccountId).StageName=='Prospecting')
           {
               (opp.AccountId).addError('Duplicate value');
           }
        }
    }
}
I want to remove prefix 'Mr.' from my Account object. I have tried through the BatchApex class. But still its not working.
public class BatchApex1 implements database.Batchable<Sobject> {
    public database.QueryLocator start(database.BatchableContext Bc)
    {
        string query='select id,name from Account';
        return database.getQueryLocator(query);
    }
    
    public void execute(database.BatchableContext Bc, list<Account> alist)
    {
        for(account a:alist)
        {
           a.name= a.Name.removeStart('Mr.');
        }
        
        update alist;
        system.debug(alist);
    }
     public void finish(database.BatchableContext Bc)
    {
        
    }

}
 
I have junction object "Author-Research Paper". This object has two master detail relationship with objects "Authors" and "Research Paper".
Now,there must not be more than 5 Authors for single research paper. How to write validtion rule for it?