Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some new Apex code #1

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ on:
branches:
- main # or the name of your main branch
- release**
- feature**
pull_request:
types: [opened, synchronize, reopened]
workflow_dispatch:
jobs:
sonarqube:
name: SonarQubeAnalysis
Expand All @@ -22,9 +24,9 @@ jobs:
env:
PMD_JAVA_OPTS: -Xmx2g
- name: updatePmd
run: awk '{gsub("/home/.*salesforce-apex-example/", "/github/workspace/");print}' $GITHUB_WORKSPACE/pmd.xml > $GITHUB_WORKSPACE/pmdnew.xml
run: awk '{gsub("/home/.*salesforce-apex-example/", "/github/workspace/");print}' $GITHUB_WORKSPACE/pmd.xml > $GITHUB_WORKSPACE/pmdfixedpaths.xml
- name: check-pmd-new
run: cat $GITHUB_WORKSPACE/pmdnew.xml
run: cat $GITHUB_WORKSPACE/pmdfixedpaths.xml
- uses: sonarsource/sonarqube-scan-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
Expand All @@ -34,4 +36,5 @@ jobs:
-Dsonar.projectName=Salesforce-Apex-Example
-Dsonar.projectKey=SonarSource-Demos_salesforce-apex-example
-Dsonar.verbose=true
-Dsonar.apex.pmd.reportPaths=pmdnew.xml
-Dsonar.apex.pmd.reportPaths=pmdfixedpaths.xml
-Dsonar.exclusions=pmd*.xml
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ This project is a copy of the [Milestones-PM](https://github.com/SalesforceLabs/

Please don't use this code, or any bytecode hosted here, for anything. Please refer to the original Force.com LAB repository for any use of the library.

[![Quality Gate Status](https://nautilus.sonarqube.org/api/project_badges/measure?project=SonarSource-Demos_salesforce-apex-example&metric=alert_status&token=01f5a714d878252a848df0651cea66135a0f2837)](https://nautilus.sonarqube.org/dashboard?id=SonarSource-Demos_salesforce-apex-example)
Main branch SonarQube status
==============
[![Quality Gate Status](https://nautilus.sonarqube.org/api/project_badges/measure?project=SonarSource-Demos_salesforce-apex-example&metric=alert_status&token=01f5a714d878252a848df0651cea66135a0f2837)](https://nautilus.sonarqube.org/dashboard?id=SonarSource-Demos_salesforce-apex-example)[![Security Rating](https://nautilus.sonarqube.org/api/project_badges/measure?project=SonarSource-Demos_salesforce-apex-example&metric=security_rating&token=01f5a714d878252a848df0651cea66135a0f2837)](https://nautilus.sonarqube.org/dashboard?id=SonarSource-Demos_salesforce-apex-example)[![Reliability Rating](https://nautilus.sonarqube.org/api/project_badges/measure?project=SonarSource-Demos_salesforce-apex-example&metric=reliability_rating&token=01f5a714d878252a848df0651cea66135a0f2837)](https://nautilus.sonarqube.org/dashboard?id=SonarSource-Demos_salesforce-apex-example)

[![Security Rating](https://nautilus.sonarqube.org/api/project_badges/measure?project=SonarSource-Demos_salesforce-apex-example&metric=security_rating&token=01f5a714d878252a848df0651cea66135a0f2837)](https://nautilus.sonarqube.org/dashboard?id=SonarSource-Demos_salesforce-apex-example)

[![Reliability Rating](https://nautilus.sonarqube.org/api/project_badges/measure?project=SonarSource-Demos_salesforce-apex-example&metric=reliability_rating&token=01f5a714d878252a848df0651cea66135a0f2837)](https://nautilus.sonarqube.org/dashboard?id=SonarSource-Demos_salesforce-apex-example)


205 changes: 205 additions & 0 deletions src/force-app/AddressService.cls
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/*
Copyright (c) 2021 Salesforce.org
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Salesforce.org nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Salesforce.org
* @date 2021
* @description Address Service class in NPSP.
*/
public inherited sharing class AddressService {

@TestVisible
private OrgConfig orgConfig {
get {
if (orgConfig == null) {
orgConfig = new OrgConfig();
}
return orgConfig;
}
set;
}

/*******************************************************************************************************
* Doesn't do anything special when State and Country picklists are enabled (the
* platform will fill out State and Country Code values using the values from the
* picklist fields), and multiline street addresses.
* @param sobjSrc the source Contact or Account
* @param strFieldPrefixSrc the address fields to copy from, ie., Mailing, Other, Shipping, Billing
* @param sobjDst the destination Contact or Account
* @param strFieldPrefixDst the address fields to copy to, ie., Mailing, Other, Shipping, Billing
*/
public void copyAddressStdSObj(SObject sobjSrc, String strFieldPrefixSrc, SObject sobjDst, String strFieldPrefixDst) {
sobjDst.put(strFieldPrefixDst + 'Street', sobjSrc.get(strFieldPrefixSrc + 'Street'));
sobjDst.put(strFieldPrefixDst + 'City', sobjSrc.get(strFieldPrefixSrc + 'City'));
sobjDst.put(strFieldPrefixDst + 'PostalCode', sobjSrc.get(strFieldPrefixSrc + 'PostalCode'));
sobjDst.put(strFieldPrefixDst + 'State', sobjSrc.get(strFieldPrefixSrc + 'State'));
sobjDst.put(strFieldPrefixDst + 'Country', sobjSrc.get(strFieldPrefixSrc + 'Country'));
sobjDst.put(strFieldPrefixDst + 'Latitude', sobjSrc.get(strFieldPrefixSrc + 'Latitude'));
sobjDst.put(strFieldPrefixDst + 'Longitude', sobjSrc.get(strFieldPrefixSrc + 'Longitude'));
if (orgConfig.isStateCountryPicklistsEnabled()) {
sobjDst.put(strFieldPrefixDst + 'StateCode', sobjSrc.get(strFieldPrefixSrc + 'StateCode'));
sobjDst.put(strFieldPrefixDst + 'CountryCode', sobjSrc.get(strFieldPrefixSrc + 'CountryCode'));
}
}

/*******************************************************************************************************
* @description utility to compare a Contact or Account address to the Address record
* @param sObj Account or Contact
* @param addr Address
* @return boolean. true if any of the Address fields on the Contact are different from this Address record
*/
public Boolean isSObjectAddressDifferent(SObject sObj, IAddress other) {
Address__c addr = (Address__c) other.getRecord();
if (sObj == null || addr == null) {
return false;
}
String prefix = ((sObj.getSObjectType() == Contact.SObjectType) ? 'Mailing' : 'Billing');

Boolean isDifferent = isDifferentIncludingLatLong(sObj, prefix, other);
return isDifferent;
}

private Boolean isDifferentIncludingLatLong(SObject sObj, String prefix, IAddress other) {
return (
!equalsCaseSensitive((String) sObj.get(prefix + 'Street'), other.multilineStreet()) ||
!equalsCaseSensitive((String) sObj.get(prefix + 'City'), other.city()) ||
!equalsCaseSensitive((String) sObj.get(prefix + 'State'), other.state()) ||
!equalsCaseSensitive((String) sObj.get(prefix + 'PostalCode'), other.postalCode()) ||
!equalsCaseSensitive((String) sObj.get(prefix + 'Country'), other.country()) ||
(Decimal) sObj.get(prefix + 'Latitude') != other.latitude() ||
(Decimal) sObj.get(prefix + 'Longitude') != other.longitude()
);
}

public static Boolean isAddressManagementEnabled() {
if (!UTIL_CustomSettingsFacade.getContactsSettings().Household_Account_Addresses_Disabled__c) {
return true;
}
return false;
}

public static Boolean isOrgAccountAddressesEnabled() {
if (UTIL_CustomSettingsFacade.getContactsSettings().Organizational_Account_Addresses_Enabled__c) {
return true;
}
return false;
}

/*******************************************************************************************************
* @description Returns whether two strings are equal, using a case sensitve comparison
* @param str1 The first string
* @param str2 The second string
* @return boolean
********************************************************************************************************/
public Boolean equalsCaseSensitive(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
if (str2 == null) {
return false;
}
return str1.equals(str2);
}

/*******************************************************************************************************
* @description Utility to copy Address fields from an Address object to a Contact or Account.
* Handles instances where State and Country picklists are enabled, and multiline street addresses.
* @param anAddress the Address object to copy from
* @param sobjDst the destination Contact or Account
* @param strFieldPrefix the address fields to copy to, ie., Mailing, Other, Shipping, Billing
* @param strFieldAddrType an optional Address Type field on sobjDst to copy to
*/
public void copyOntoSObject(IAddress anAddress, SObject sobjDst,
String strFieldPrefix, String strFieldAddrType) {
Address__c addr = (Address__c) anAddress.getRecord();

String undeliverableField = UTIL_Namespace.StrAllNSPrefix('Undeliverable__c');
Set<String> populatedFieldsAsMapKeySet =
anAddress.getRecord().getPopulatedFieldsAsMap().keySet();
if (populatedFieldsAsMapKeySet.contains(undeliverableField)) {
String undeliverableAddressField =
UTIL_Namespace.StrAllNSPrefix('Undeliverable_Address__c');
sobjDst.put(undeliverableAddressField, anAddress.isUndeliverable());
}

sobjDst.put(strFieldPrefix + 'Street', anAddress.multilineStreet());
sobjDst.put(strFieldPrefix + 'City', addr.MailingCity__c);
sobjDst.put(strFieldPrefix + 'PostalCode', addr.MailingPostalCode__c);
sobjDst.put(strFieldPrefix + 'Latitude', addr.Geolocation__Latitude__s);
sobjDst.put(strFieldPrefix + 'Longitude', addr.Geolocation__Longitude__s);

if (!orgConfig.isStateCountryPicklistsEnabled()) {
sobjDst.put(strFieldPrefix + 'State', addr.MailingState__c);
sobjDst.put(strFieldPrefix + 'Country', addr.MailingCountry__c);
} else {
if (addr.MailingCountry__c != null) {
if (orgConfig.validCountriesByLabel().containsKey(addr.MailingCountry__c
.toUpperCase()
)) {
sobjDst.put(strFieldPrefix + 'Country', addr.MailingCountry__c);
sobjDst.put(strFieldPrefix + 'CountryCode',
orgConfig.validCountriesByLabel().get(
addr.MailingCountry__c.toUpperCase()));
} else if (orgConfig.validCountriesByCode().containsKey(addr.MailingCountry__c
.toUpperCase())) {
sobjDst.put(strFieldPrefix + 'CountryCode', addr.MailingCountry__c.toUpperCase());
sobjDst.put(strFieldPrefix + 'Country',
orgConfig.validCountriesByCode().get(
addr.MailingCountry__c.toUpperCase()));
} else {
// allow the invalid country to be placed in the country field, so Salesforce will generate the error.
sobjDst.put(strFieldPrefix + 'Country', addr.MailingCountry__c);
}
} else { // MailingCountry = null
sobjDst.put(strFieldPrefix + 'CountryCode', null);
sobjDst.put(strFieldPrefix + 'Country', null);
}
if (addr.MailingState__c != null) {
if (orgConfig.validStatesByLabel().containsKey(addr.MailingState__c
.toUpperCase())) {
sobjDst.put(strFieldPrefix + 'State', addr.MailingState__c);
sobjDst.put(strFieldPrefix + 'StateCode', orgConfig.validStatesByLabel()
.get(addr
.MailingState__c.toUpperCase()));
} else {
// too expensive for us to create the map of CountryCode|StateCode to StateLabel
// so we will just try to save any state that isn't a label as a code.
sobjDst.put(strFieldPrefix + 'StateCode', addr.MailingState__c.toUpperCase());
}
} else { // MailingState = null
sobjDst.put(strFieldPrefix + 'StateCode', null);
sobjDst.put(strFieldPrefix + 'State', null);
}
}

if (strFieldAddrType != null) {
sobjDst.put(strFieldAddrType, addr.Address_Type__c);
}
}
}
5 changes: 5 additions & 0 deletions src/force-app/AddressService.cls-meta.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>53.0</apiVersion>
<status>Active</status>
</ApexClass>
101 changes: 101 additions & 0 deletions src/force-app/AddressServiceTests_TEST.cls
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
Copyright (c) 2022 Salesforce.org
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Salesforce.org nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Salesforce.org
* @date 2022
* @description Tests for the Address Service class in NPSP.
*/
@IsTest
private class AddressServiceTests_TEST {

private static OrgConfig orgConfig = new OrgConfig();

/**
* @description in order to be effective this test must be run in an Org that has State
* & Country picklists enabled.
* NPSP's in-memory map, validStatesByLabel(), has no way of knowing which State is
* applicable for which Country. The platform does and will automatically populate the
* state code depending on the value in the Country (or CountryCode) value.
*/
@IsTest
static void shouldDirectlySetStateCodeValue() {
if (!orgConfig.isStateCountryPicklistsEnabled()) {
return;
}

// Arrange
String stateName = 'Minnesota';
String stateCode = 'MN';
Contact aContact = new Contact();
IAddress anAddress = new NPSP_Address(
new Address__c(
MailingState__c = stateName,
MailingCountry__c = 'United States'
)
);
AddressService addressService = new AddressService();

// Act
addressService.copyOntoSObject(
anAddress,
aContact,
'Mailing',
null
);

// Assert
System.assertEquals(stateCode, aContact.get('MailingStateCode'),
'The copyOntoSObject method should be setting State Code values.');
}

@IsTest
static void shouldCopyUndeliverableStatus(){
// Arrange
Contact aContact = new Contact();
IAddress anUndeliverableAddress = new NPSP_Address(
new Address__c(
Undeliverable__c = true
)
);
AddressService addressService = new AddressService();

// Act
addressService.copyOntoSObject(
anUndeliverableAddress,
aContact,
'Mailing',
null
);

// Assert
System.assertEquals(true, aContact.Undeliverable_Address__c,
'The copyOntoSObject method should map the Addresses undeliverable status.');
}
}
5 changes: 5 additions & 0 deletions src/force-app/AddressServiceTests_TEST.cls-meta.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>53.0</apiVersion>
<status>Active</status>
</ApexClass>
Loading
Loading