Skip to content

Instantly share code, notes, and snippets.

@julianperezpesce
Last active January 18, 2023 15:33
Show Gist options
  • Save julianperezpesce/a85e50fb765bdbf3f8845339eb7fd4de to your computer and use it in GitHub Desktop.
Save julianperezpesce/a85e50fb765bdbf3f8845339eb7fd4de to your computer and use it in GitHub Desktop.
Ejemplos
public with sharing class AccountManager {
// createAccount: Creates an account by receiving the name, number of employees, document
// type and document number. Returns the id of the new account
// Este esta bien, había que resolver try and catch, pero es mejor opción Database Save Result
public static Id createAccount(String name, Integer numberOfEmployees, String documentType, String documentNumber) {
Account anAccount = new Account(
Name = name,
NumberOfEmployees = numberOfEmployees,
Identification_Type__c = documentType,
Document_number__c = documentNumber
);
Database.SaveResult result = Database.insert(anAccount, false);
return result.getId();
}
// UpdateAccount: Updates an account by receiving the name, number of employees, document
// type and document number. Returns true if the account was updated or false if it was not
//updated.
// Lo comentado esta todo mal
public static Boolean updateAccount(String name, Integer numberOfEmployees, String documentType, String documentNumber) {
// List<Account> accounts = [SELECT Id, Name, NumberOfEmployees, Identification_Type__c, Document_number__c FROM Account];
// if (accounts.size() > 0) {
// for (Account account : accounts) {
// if (account.Name == name) {
// account.NumberOfEmployees = numberOfEmployees;
// account.Identification_Type__c = documentType;
// account.Document_number__c = documentNumber;
// return true;
// }
// }
// }
// return false;
Account anAccount = [
SELECT Id
FROM Account
WHERE Document_number__c = :documentNumber
AND Identification_Type__c = :documentType
LIMIT 1
];
anAccount.Name = name;
anAccount.NumberOfEmployees = numberOfEmployees;
Database.SaveResult result = Database.update(anAccount, false);
return result.isSuccess();
}
// DeleteAccount: Removes an account receiving the document type and number. Returns true if
// deleted or false if not deleted
public static Boolean deleteAccount(String documentType, String documentNumber) {
// List<Account> accounts = [SELECT Id, Identification_Type__c, Document_number__c FROM Account WHERE Identification_Type__c = :documentType AND Document_number__c = :documentNumber];
// for (Account account : accounts) {
// delete account;
// return true;
// }
// return false;
Account anAccount = [
SELECT Id
FROM Account
WHERE Document_number__c = :documentNumber
AND Identification_Type__c = :documentType
LIMIT 1
];
Database.DeleteResult result = Database.delete(anAccount, false);
return result.isSuccess();
}
// ConsultAccount: Consult an account by receiving the document type and number. Return the
// account found or null if it does not exist.
public static Account consultAccount(String documentType, String documentNumber) {
List<Account> accounts = [
SELECT Id
FROM Account
WHERE Document_number__c = :documentNumber
AND Identification_Type__c = :documentType
LIMIT 1
];
if(accounts.size() > 0) {
return accounts[0];
} else {
return null;
}
}
}
trigger AccountTrigger on Account (before insert, before update) {
//trigger.new la lista de lo que esta pasando por el trigger en la instancia correspondiente
//trigger.newMap el mapa id,SObject de lo que esta pasando por el trigger en la instancia correspondiente
//trigger.old la lista de lo que esta pasando por el trigger en la instancia correspondiente pero sin la nueva actualizacion
//trigger.oldMap el mapa de id,SObject esta pasando por el trigger en la instancia correspondiente pero sin la nueva actualizacion
if (Trigger.isBefore) {
if (Trigger.isInsert) {
List<Account> accountsToValidate = new List<Account>();
for (Account anAccount : Trigger.new) {
if (
!String.isBlank(anAccount.Document_number__c)
&& !String.isBlank(anAccount.Identification_type__c)
) {
accountsToValidate.add(anAccount);
}
}
if (!accountsToValidate.isEmpty()) {
AccountTriggerHandler.validateAccount(accountsToValidate);
}
} else if (Trigger.isUpdate) {
List<Account> accountsToValidate = new List<Account>();
for (Account anAccount : Trigger.new) {
Account oldAccount = trigger.oldMap.get(anAccount.Id);
if (
(anAccount.Document_number__c != oldAccount.Document_number__c
|| anAccount.Identification_type__c != oldAccount.Identification_type__c)
&& (!String.isBlank(anAccount.Document_number__c)
&& !String.isBlank(anAccount.Identification_type__c))
) {
accountsToValidate.add(anAccount);
}
}
if (!accountsToValidate.isEmpty()) {
AccountTriggerHandler.validateAccount(accountsToValidate);
}
}
}
}
public with sharing class AccountTriggerHandler {
public static void validateAccount(List<Account> accounts) {
List<String> documentNumbers = new List<String>();
List<String> identificationTypes = new List<String>();
Map<String, Account> accountsByDocumentNumerAndIdentificationType = new Map<String, Account>();
for (Account anAccount : accounts) {
documentNumbers.add(anAccount.Document_number__c);
identificationTypes.add(anAccount.Identification_type__c);
accountsByDocumentNumerAndIdentificationType.put(
anAccount.Document_number__c+anAccount.Identification_type__c, anAccount
);
}
List<Account> accountsFromDataBase = [
SELECT Document_number__c, Identification_type__c
FROM Account
WHERE Document_number__c IN :documentNumbers
AND Identification_type__c IN :identificationTypes
];
/*for (Account anAccount : accountsFromDataBase) {
for(Account newAccount : accounts){
if (
anAccount.Document_number__c == newAccount.Document_number__c
&& anAccount.Identification_type__c == newAccount.Identification_type__c
) {
newAccount.addError('this document number is duplicated');
}
}
}*/
if (!accounts.isEmpty()) {
for (Account anAccount : accountsFromDataBase) {
if (
accountsByDocumentNumerAndIdentificationType.containsKey(
anAccount.Document_number__c+anAccount.Identification_type__c
)
) {
Account newAccount = accountsByDocumentNumerAndIdentificationType.get(
anAccount.Document_number__c+anAccount.Identification_type__c
);
newAccount.addError('this document number is duplicated');
}
}
}
}
}
@isTest
public with sharing class AccountTriggerTest {
//test setup genera base de datos interna para todos los test
@TestSetup
static void makeData(){
List<Account> accounts = new List<Account>();
Account anAccount = new Account(
Name = 'Globant',
Identification_type__c = 'PP',
Document_number__c = '33333333'
);
accounts.add(anAccount);
Account anOtherAccount = new Account(
Name = 'Globant2',
Identification_type__c = 'PP',
Document_number__c = '33333334'
);
accounts.add(anOtherAccount);
insert accounts;
}
@IsTest
static void whenTryToInsertAnAccountWithTheSameDocumentNumerAndIdentificationTypeAsAnotherAccountExistentIntoDataBaseRecivedAnErrror(){
//dentro del test puedo llamarla para usarla
/*Account anAccount = [
SELECT Id
FROM Account
WHERE Name = 'Globant'
LIMIT 1
];*/
Account anAccount = new Account(
Name = 'Globant',
Identification_type__c = 'PP',
Document_number__c = '33333333'
);
Test.startTest();
/*String error = '';
try {
instert anAccount;
} catch (Exception e) {
error = e.getMessage();
}*/
Database.SaveResult result = Database.insert(anAccount, false);
Test.stopTest();
System.assertEquals(false, result.isSuccess(), 'the duplicated account was inserted into the data base');
System.assertEquals(
'this document number is duplicated',
result.getErrors()[0].getMessage(),
'the error message is not the expected message'
);
}
@IsTest
static void methodName(){
List<Account> accounts = [
SELECT Document_number__c, Identification_type__c
FROM Account
];
Account accountToUpdate = accounts[0];
accountToUpdate.Document_number__c = accounts[1].Document_number__c;
Test.startTest();
Database.SaveResult result = Database.update(accountToUpdate, false);
Test.stopTest();
System.assertEquals(false, result.isSuccess(), 'the duplicated account was inserted into the data base');
System.assertEquals(
'this document number is duplicated',
result.getErrors()[0].getMessage(),
'the error message is not the expected message'
);
}
}
public with sharing class CaseTriggerHandler {
public static void vinculateTaskToCase (List<Case> cases) {
//List<String> contactsIds = new List <String>();
Map <String,Case> mapContactsIdsIdCase = new Map <String, Case>();
for (Case aCase : cases) {
// contactsIds.add(aCase.ContactId);
//mapContactsIdsIdCase.put(aCase.ContactId, aCase.Id);
mapContactsIdsIdCase.put(aCase.ContactId, aCase);
}
if (!mapContactsIdsIdCase.isEmpty()) {
Task tasksFromDatabase;
String subjectType = 'Call';
Datetime dt = Datetime.now().addMinutes(-2);
//Si DATECREATED <= dt ==> actualizar Si las Task se creó 2 minutos antes que el caso se asigna
List <Task> tasks =[SELECT WhoId
FROM Task WHERE WhoId In: mapContactsIdsIdCase.keySet()
AND WhatId = null AND Subject = :subjectType AND CreatedTime < :dt];
for (Task aTask : tasks ) {
Case aCase = mapContactsIdsIdCase.get(aTask.WhoId);
aTask.WhatId = aCase.Id;
}
update tasks;
}
}
}
Tenemos que enviar una info a un endpoint cuando un registro tiene un cambio.
Lo quisimos hacer por Flow y nos daba un error. Lo queremos hacer por Trigger,
nos dá error Callout from triggers are currently not supported...
Luego dice en help : You can invoke callouts from triggers by encapsulating
the callouts in @future methods.
Peeeeeero, cuando lo agrego, no me deja deployar porque:
"Future methods do not support return type of System.HttpResponse"
¿Que hacer ?
maximiliano vargas: Un encolable
Para y con el dato del response que quieren hacer?
El endpoint al que envian es de a uno o recibe una lista?
Llego a la oficina y les pasp un ejemplo
Andrea Wigand
Estamos con Rodri y ya lo resolvimos....
pero aceptamos ejemplos para la próxima
maximiliano vargas
Como lo resolvieron?
public without sharing class Opportunity_Product {
@future (callout=true)
public static void calloutFuture(String body, String endpoint,String method){
callout(body, endpoint, method);
}
public static HttpResponse callout(String body, String endpoint,String method){
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:SantanderApi' + endpoint);
System.debug(endpoint);
request.setTimeout(120000);
request.setMethod(method);
if(String.isNotBlank(body)){
request.setBody(body);
}
System.debug(request + 'Linia 105');
return http.send(request);
}
public static String getLegajo(){
return
[
SELECT id, File__c
FROM User
WHERE id = :System.UserInfo.getUserId()
LIMIT 1
]?.File__c;
}
Aceptamos buenas prácticas para recomendar
Este es el método que selecciona la info
public static void envioDatosProductoNoInteresado(List<OpportunityLineItem> lista){
Endpoint__mdt intentionEndpoint =[
SELECT BS_URL__c
FROM Endpoint__mdt
WHERE DeveloperName = 'Intenciones_IN_POST'
LIMIT 1
];
OpportunityLineItem oppProduct = lista[0];
Map<String, String> reqBody= new Map<String,String> ();
reqBody.put('nup', oppProduct.Opportunity.Account.NUP__c);
reqBody.put('legajo', getLegajo());
reqBody.put('status', oppProduct.Stage__c);
reqBody.put('externalId', oppProduct.ExternalId__c);
String reqBodyJSON = JSON.serialize(reqBody);
calloutFuture(reqBodyJSON, intentionEndpoint.BS_URL__c, 'POST');
System.debug(reqBodyJSON);
}
The Easiest Way to Get Record Type Name in Apex
To get the RecordTypeId by Name, developers usually use .
Id clinicRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get(‘Clinic’).getRecordTypeId();
And there is a query we can run on RecordType object if we want it the other way around.
[Select Name from RecordType where ID = 'Id of the record type'];
What if I want to get the Record Type Name by Record Id? It seems easy, but most of the developers are doing it in a very complex way, and I have seen the following code, or something similar on countless projects.
Id recordId = ‘aed323000000sssUEYDs’;
//get the object API name
String sObjectAPINAme = String.valueOf(recordId.getSObjectType());
// build a dynamic query, here is the problem we can actually get the name from here
String queryString = ‘SELECT Name, RecordTypeId FROM ‘+sObjectAPINAme+’ WHERE Id =: recordId’;
SObject recordTypeInfo = Database.query(queryString);
// get all record types under the object
List<RecordType> recordTypes = [SELECT Id,DeveloperName FROM RecordType WHERE SobjectType=:sObjectTypeFromId];
//loop to find the matching record type
Id recordTypeId = (Id)recordTypeInfo.get(‘RecordTypeId’);
for(RecordType rt :recordTypes ) {
if(rt.Id == recordTypeId) {
System.debug(r.DeveloperName);
}
}
Instead of making it so complex and inefficient, just query the RecordType under sObject.
SELECT Name, RecordType.DeveloperName FROM Contact
Think twice before we start coding. There’s got to be an easier way. Happy coding!
https://yutian-zheng1.medium.com/the-easiest-way-to-get-record-type-name-in-apex-38b3d054df29
@TestSetup
static void makeData(){
// Estos datos son una "BBDD Interna", porque los tests estan aislados de
// la BBDD
Contact contacto = new Contact(
LastName = 'Andy Young'
);
insert contacto;
Task tarea = new Task(
Subject = 'Call',
WhoId = contacto.Id,
Status = 'In Progress'
);
insert tarea;
}
@isTest
static void assignTaskTest(){
Contact contacto = [SELECT Id FROM Contact WHERE LastName='Andy Young'];
Case caso = new Case(
ContactId = contacto.Id
);
Test.startTest();
insert caso;
Test.stopTest();
Task tarea = [SELECT WhatId FROM Task WHERE WhoId=:contacto.Id];
System.assertEquals(caso.Id, tarea.WhatId, 'El caso no se relaciono correctamente con la tarea');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment