I have this apex class (coded by another developer)
@RestResource(urlMapping = '/thunder/contapj/*')
global class Thunder_SVC_ContaPJ {
public static Log_de_Integracao__c log = new Log_de_Integracao__c();
public static Wrapper_CLS_ContaPJ clientJSON = new Wrapper_CLS_ContaPJ();
public static Boolean isConverted = true;
public static Boolean isError = false;
public static Integer statusCode = 400;
public static List<String> validateFields = new List<String>();
public static RestRequest request = RestContext.request;
public static RestResponse response = RestContext.response;
@HttpPost
global static void doPost() {
initialize();
request = RestContext.request;
response = RestContext.response;
try {
log.Nome_da_Classe__c = 'ThunderWebservicePJ';
String jSONRequestBody = request.requestBody.toString();
clientJSON = Wrapper_CLS_ContaPJ.parse(jSONRequestBody);
log.Request__c = jSONRequestBody;
validateFields = clientJSON.validateRequiredFields();
// Building Response
if (validateFields.isEmpty()) {
setResponse(createClient());
setLog('createClient', isError, null);
} else {
// If there are any validation error
setResponse(validateFields);
setLog('RequiredFields', true, 'Invalid/Missing Required field');
}
} catch (JSONException j) {
setResponse('JSONException: ' + j.getMessage());
setLog('JSONException', true, 'JSONException: ' + j.getMessage());
} catch (Exception e) {
setResponse('Exception: ' + e.getMessage());
setLog('Exception', true, 'Exception: ' + e.getMessage());
} finally {
database.insert(log);
}
}
public static void initialize() {
log = new Log_de_Integracao__c();
isConverted = true;
isError = false;
statusCode = 400;
validateFields = new List<String>();
}
public static void setResponse(Object body) {
response.addHeader('Content-Type', 'application/json; charset=utf-8');
response.responseBody = Blob.ValueOf(JSON.serialize(body));
response.statuscode = statuscode;
}
public static void setNull(Object body) {
response.addHeader('Content-Type', 'application/json; charset=utf-8');
response.responseBody = Blob.ValueOf(JSON.serialize(body));
response.statuscode = statuscode;
}
public static void setLog(String method, Boolean error, String errorMessage) {
log.Metodo__c = method;
log.Codigo_de_status__c = String.valueOf(statusCode);
if (error == true) {
log.Response__c = errorMessage;
log.Mensagem_de_Erro__c = response.responseBody.toString();
log.Erro__c = error;
} else {
log.Response__c = response.responseBody.toString();
log.Erro__c = error;
}
}
public static List<String> createClient() {
List<String> erros = new List<String>();
Id recodTypeIdNacionais = Schema.SobjectType.Account.getRecordTypeInfosByName().get('Nacionais').getRecordTypeId();
Id recodTypeIdLoggiOne = Schema.SobjectType.Account.getRecordTypeInfosByName().get('LoggiOne').getRecordTypeId();
Account existingAcc = (getExistingAccount(clientJSON.cnpj, recodTypeIdNacionais) == null ? getExistingAccount(clientJSON.cnpj, recodTypeIdLoggiOne) : getExistingAccount(clientJSON.cnpj, recodTypeIdNacionais));
// If there is no Account
// Merge all similar Leads if necessary
// update Lead
if (existingAcc == null) {
Lead existingLead = getExistingLead(clientJSON.cnpj);
existingLead.idLoggi__c = Integer.valueOf(clientJSON.pk);
existingLead.Phone = clientJSON.Contact_component.telephone;
existingLead.Street = clientJSON.Address_component.address;
existingLead.City = clientJSON.Address_component.city;
existingLead.State = clientJSON.Address_component.state;
existingLead.Country = clientJSON.Address_component.country;
existingLead.PostalCode = clientJSON.Address_component.postal_code;
existingLead.Complemento__c = clientJSON.Address_component.complement;
existingLead.bairro__c = clientJSON.Address_component.neighborhood;
existingLead.CNPJ__c = clientJSON.cnpj;
existingLead.Email = clientJSON.Contact_component.email;
existingLead.blacklist__c = Boolean.valueOf(clientJSON.Bl_component.blocked);
existingLead.blacklistModificationDate__c = (clientJSON.Bl_component.blocked_at != 'None') ? Date.valueOf(clientJSON.Bl_component.blocked_at) : null;
existingLead.blacklistModifiedBy__c = clientJSON.Bl_component.blocked_by;
existingLead.blacklistReason__c = clientJSON.Bl_component.blocked_reason == 'N/A' ? clientJSON.Bl_component.blocked_reason : clientJSON.Bl_component.blocked_reason.left(255);
existingLead.boletoStatus__c = clientJSON.Financial_component.bankslip_feature;
existingLead.LastName = clientJSON.name; //clientJSON.Contact_component.email == null ? 'N/A' : clientJSON.Contact_component.email.split('@')[0];
existingLead.Company = clientJSON.name;
//existingLead.Company = clientJSON.shared_name; //clientJSON.name; PENDENTE
if(clientJSON.loggiEnvios == true){
existingLead.Status_Receita_Federal__c = 'ATIVA';
}
if (clientJSON.averageTicket != null && clientJSON.averageTicket != 'None' && existingLead.GMV_m_dio__c == null){
existingLead.GMV_m_dio__c = Decimal.valueOf(clientJSON.averageTicket);
}
if (clientJSON.favoredContactMethod != null && clientJSON.favoredContactMethod != 'None' && existingLead.Prefer_ncia_de_Contato__c == null){
existingLead.Prefer_ncia_de_Contato__c = clientJSON.favoredContactMethod;
}
if (clientJSON.segment != null && clientJSON.segment != 'None' && existingLead.Segmento__c == null){
existingLead.Segmento__c = clientJSON.segment;
}
if (
clientJSON.segment == 'Automotivo' ||
clientJSON.segment == 'Eletrônicos e Informática' ||
clientJSON.segment == 'Jogos e Brinquedos' ||
clientJSON.segment == 'Livraria' ||
clientJSON.segment == 'Máquinas e Equipamentos' ||
clientJSON.segment == 'Papelaria e Impressão Gráfica' ||
clientJSON.segment == 'Serviços Financeiros' ||
clientJSON.segment == 'Serviços Gerais' ||
clientJSON.segment == 'Serviços Logísticos' ){
existingLead.Grupo_de_Segmento__c = 'Mercado Geral';
}
if (
clientJSON.segment == 'Artigos Esportivos' ||
clientJSON.segment == 'Calçados' ||
clientJSON.segment == 'Jóias/Semi Jóias/Bijuterias' ||
clientJSON.segment == 'Óticas' ||
clientJSON.segment == 'Vestuário e Moda'){
existingLead.Grupo_de_Segmento__c = 'Moda e Esportivo';
}
if(
clientJSON.segment == 'Agronegócio' ||
clientJSON.segment == 'Alimentos' ||
clientJSON.segment == 'Cama/Mesa/Banho' ||
clientJSON.segment == 'Construção e HomeCenter' ||
clientJSON.segment == 'Cosméticos e Perfumaria' ||
clientJSON.segment == 'Eletrodomésticos' ||
clientJSON.segment == 'Farmácias' ||
clientJSON.segment == 'Hospitalar e Clínicas' ||
clientJSON.segment == 'Móveis e Decoração' ||
clientJSON.segment == 'Petshop e PetCenter' ||
clientJSON.segment == 'Sex Shop'){
existingLead.Grupo_de_Segmento__c = 'Saúde/Beleza/Casa/Pet';
}
if (clientJSON.segment == 'Top Player'){
existingLead.Grupo_de_Segmento__c = 'Top Player';
}
// casos de leads novos
if(existingLead.Id == null){
existingLead.RecordTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Queues').getRecordTypeId();
existingLead.OwnerId = [SELECT Id, Type, DeveloperName FROM Group WHERE Type = 'Queue' AND DeveloperName = 'Leads_Novos'].Id;
//existingLead.LeadSource = 'Loggi Envios';
if(clientJSON.loggiEnvios == true){
existingLead.LeadSource = 'Loggi Envios';
}
else {
existingLead.LeadSource = 'Site Loggi';
}
/*
if (clientJSON.Mkt_component.month_deliveries != 'None') {
existingLead.volumeEstimadoDeEntregasMes__c = Integer.valueOf(clientJSON.Mkt_component.month_deliveries);
} else if(existingLead.volumeEstimadoDeEntregasMes__c == null) {
existingLead.volumeEstimadoDeEntregasMes__c = 1;
}
*/
if (clientJSON.estimatedMonthlyPackages != null && existingLead.volumeEstimadoDeEntregasMes__c == null){
existingLead.volumeEstimadoDeEntregasMes__c = Decimal.valueOf(clientJSON.estimatedMonthlyPackages);
}else if (clientJSON.Mkt_component.month_deliveries != 'None' && existingLead.volumeEstimadoDeEntregasMes__c == null) {
existingLead.volumeEstimadoDeEntregasMes__c = Integer.valueOf(clientJSON.Mkt_component.month_deliveries);
}
}
try {
upsert existingLead;
log.Id_do_Registro__c = existingLead.id;
statusCode = 200;
relateContact('Lead', existingLead);
return new List<String>{'Lead criado/atualizado com sucesso! ID:' + existingLead.Id};
} catch (DMLException ed) {
isError = true;
return new List<String>{ed.getdmlMessage(0)};
} catch (Exception e) {
isError = true;
return new List<String>{e.getMessage()};
}
} else {
// existingAcc.RecordTypeId = (existingAcc.Tipo_de_Oportunidade__c != null ? (existingAcc.Tipo_de_Oportunidade__c == 'LoggiOne' ? recodTypeIDLoggiOne : recodTypeIdNacionais) : recodTypeIdNacionais);
if(existingAcc.Tipo_de_Oportunidade__c == 'LoggiOne' || existingAcc.Tipo_de_Oportunidade__c == 'Bling'){
existingAcc.RecordTypeId = recodTypeIDLoggiOne;
}
else {
existingAcc.RecordTypeId = recodTypeIdNacionais;
}
existingAcc.idLoggi__c = Integer.valueOf(clientJSON.pk);
existingAcc.Name = clientJSON.name;
existingAcc.Phone = clientJSON.Contact_component.telephone;
existingAcc.BillingStreet = clientJSON.Address_component.address;
existingAcc.BillingCity = clientJSON.Address_component.city;
existingAcc.BillingState = clientJSON.Address_component.state;
existingAcc.BillingCountry = clientJSON.Address_component.country;
existingAcc.BillingPostalCode = clientJSON.Address_component.postal_code;
existingAcc.Complemento__c = clientJSON.Address_component.complement;
existingAcc.bairro__c = clientJSON.Address_component.neighborhood;
existingAcc.CNPJ__c = clientJSON.cnpj;
existingAcc.EmailPJ__c = clientJSON.Contact_component.email;
existingAcc.pesquisa_origem__c = clientJSON.Mkt_component.signup_origin;
existingAcc.boleto_status__c = clientJSON.Financial_component.bankslip_feature;
existingAcc.Id_Externo_Unico__c = Integer.valueOf(existingAcc.idLoggi__c)+'' + existingAcc.RecordTypeId;
//existingAcc.Blacklist__c = Boolean.valueOf(clientJSON.Financial_component.is_overdue);
existingAcc.Blacklist__c = Boolean.valueOf(clientJSON.Bl_component.blocked);
existingAcc.BlackList_Modificado_Por__c = clientJSON.Bl_component.blocked_by;
existingAcc.ModificationBlacklist__c = (clientJSON.Bl_component.blocked_at != 'None') ? Date.valueOf(clientJSON.Bl_component.blocked_at) : null;
existingAcc.motivo_da_blacklist__c = clientJSON.Bl_component.blocked_reason == 'N/A' ? clientJSON.Bl_component.blocked_reason : clientJSON.Bl_component.blocked_reason.left(255);
// existingAcc.Nome_fantasia__c = clientJSON.shared_name; PENDENTE
if (clientJSON.estimatedMonthlyPackages != null && existingAcc.Volume_estimado_de_entregams__c == null){
existingAcc.Volume_estimado_de_entregams__c = Decimal.valueOf(clientJSON.estimatedMonthlyPackages);
}else if (clientJSON.Mkt_component.month_deliveries != 'None' && existingAcc.Volume_estimado_de_entregams__c == null) {
existingAcc.Volume_estimado_de_entregams__c = Integer.valueOf(clientJSON.Mkt_component.month_deliveries);
}
if (clientJSON.favoredContactMethod != null && clientJSON.favoredContactMethod != 'None' && existingAcc.Prefer_ncia_de_Contato__c == null){
existingAcc.Prefer_ncia_de_Contato__c = clientJSON.favoredContactMethod;
}
if (clientJSON.segment != null && clientJSON.segment != 'None' && existingAcc.Segmento__c == null){
existingAcc.Segmento__c = clientJSON.segment;
}
/*
if (clientJSON.Mkt_component.month_deliveries != 'None') {
existingAcc.Volume_estimado_de_entregams__c = Integer.valueOf(clientJSON.Mkt_component.month_deliveries);
} else if(existingAcc.Volume_estimado_de_entregams__c == null) {
existingAcc.Volume_estimado_de_entregams__c = 1;
}
*/
if (clientJSON.averageTicket != null && clientJSON.averageTicket != 'None' && existingAcc.GMV_m_dio__c== null ){
existingAcc.GMV_m_dio__c = Decimal.valueOf(clientJSON.averageTicket);
}
if (
clientJSON.segment == 'Automotivo' ||
clientJSON.segment == 'Eletrônicos e Informática' ||
clientJSON.segment == 'Jogos e Brinquedos' ||
clientJSON.segment == 'Livraria' ||
clientJSON.segment == 'Máquinas e Equipamentos' ||
clientJSON.segment == 'Papelaria e Impressão Gráfica' ||
clientJSON.segment == 'Serviços Financeiros' ||
clientJSON.segment == 'Serviços Gerais' ||
clientJSON.segment == 'Serviços Logísticos' ){
existingAcc.Grupo_de_Segmento__c = 'Mercado Geral';
}
if (
clientJSON.segment == 'Artigos Esportivos' ||
clientJSON.segment == 'Calçados' ||
clientJSON.segment == 'Jóias/Semi Jóias/Bijuterias' ||
clientJSON.segment == 'Óticas' ||
clientJSON.segment == 'Vestuário e Moda'){
existingAcc.Grupo_de_Segmento__c = 'Moda e Esportivo';
}
if(
clientJSON.segment == 'Agronegócio' ||
clientJSON.segment == 'Alimentos' ||
clientJSON.segment == 'Cama/Mesa/Banho' ||
clientJSON.segment == 'Construção e HomeCenter' ||
clientJSON.segment == 'Cosméticos e Perfumaria' ||
clientJSON.segment == 'Eletrodomésticos' ||
clientJSON.segment == 'Farmácias' ||
clientJSON.segment == 'Hospitalar e Clínicas' ||
clientJSON.segment == 'Móveis e Decoração' ||
clientJSON.segment == 'Petshop e PetCenter' ||
clientJSON.segment == 'Sex Shop'){
existingAcc.Grupo_de_Segmento__c = 'Saúde/Beleza/Casa/Pet';
}
if (clientJSON.segment == 'Top Player'){
existingAcc.Grupo_de_Segmento__c = 'Top Player';
}
if (isfromUra(existingAcc.ID_Externo_Unico__c, clientJSON.Mkt_component.mkt_source)) {
existingAcc.Origem__c = 'URA Inbound';
}
try {
update existingAcc;
log.Id_do_Registro__c = existingAcc.id;
statusCode = 200;
relateContact('Account', existingAcc);
return new List<String>{'Conta criada/atualizada com sucesso! ID:' + existingAcc.Id};
} catch (DMLException ed) {
isError = true;
return new List<String>{ed.getdmlMessage(0)};
} catch (Exception e) {
isError = true;
return new List<String>{e.getMessage()};
}
}
}
public static void relateContact(String type, SObject client) {
List<Contact> contactList;
switch on type {
when 'Account' {
contactList = [SELECT Id
FROM Contact
WHERE companyIdLoggi__c =: Integer.valueOf(clientJSON.pk)
AND AccountId = null LIMIT 45000];
for (Contact ctc : contactList) {
ctc.AccountId = client.id;
}
}
when 'Lead' {
contactList = [SELECT Id
FROM Contact
WHERE companyIdLoggi__c =: Integer.valueOf(clientJSON.pk)
AND LeadId__c = null LIMIT 45000];
for (Contact ctc : contactList) {
ctc.LeadId__c = client.id;
}
}
}
try {
Database.update(contactList);
} catch (Exception e) {
}
}
/*public static Account getExistingAccount(Decimal idLoggi, String recordTypeId) {
try {
return [SELECT Id, boleto_status__c, Volume_estimado_de_entregams__c
FROM Account
WHERE idLoggi__c = :idLoggi AND RecordTypeId = :recordTypeId];
} catch (System.QueryException e) {
return null;
}
}*/
public static Account getExistingAccount(String cnpj, String recordTypeId) {
try {
return [SELECT Id, boleto_status__c, Volume_estimado_de_entregams__c, Tipo_de_Oportunidade__c,Prefer_ncia_de_Contato__c, Segmento__c, GMV_m_dio__c
FROM Account
WHERE cnpj__c = :cnpj AND RecordTypeId = :recordTypeId];
} catch (System.QueryException e) {
return null;
}
}
public static Lead getExistingLead(String cnpj) {
try {
List<Lead> ldWithPK = [SELECT Id, RecordType.DeveloperName, Tipo_de_Oportunidade__c,Prefer_ncia_de_Contato__c, Segmento__c, GMV_m_dio__c,volumeEstimadoDeEntregasMes__c
FROM Lead
WHERE idloggi__c =: Integer.valueOf(clientJSON.pk)
LIMIT 1];
if (!ldWithPK.isEmpty()) return ldWithPK[0];
else {
List<Lead> ldWithCNPJ = [SELECT Id, RecordType.DeveloperName, Tipo_de_Oportunidade__c,Prefer_ncia_de_Contato__c, Segmento__c, GMV_m_dio__c,volumeEstimadoDeEntregasMes__c
FROM Lead
WHERE CNPJ__c =: cnpj
LIMIT 1];
if (!ldWithCNPJ.isEmpty()) return ldWithCNPJ[0];
else return new Lead();
}
} catch (System.QueryException e) {
return new Lead();
}
}
public static boolean isfromUra(String idExternal, String mktFont) {
List<Account> existAcc = [Select Id
from Account
where Id_Externo_Unico__c = :idExternal];
if (existAcc.isEmpty() && mktFont == 'URAS') {
return true;
} else {
return false;
}
}
}
And I have this wrapper class, also not wrote by me.
global class Wrapper_CLS_ContaPJ {
public String pk;
public String name;
public String cnpj;
public Address_component address_component;
public Contact_component contact_component;
public Financial_component financial_component;
public Mkt_component mkt_component;
public Bl_component bl_component;
public Vertical_component vertical_component;
public Enable_component enable_component;
public class Financial_component {
public String is_overdue;
public String bankslip_feature;
}
public class Bl_component {
public String blocked;
public String blocked_at;
public String blocked_by;
public String blocked_reason;
}
public class Vertical_component {
public String is_corp;
public String is_pro;
public String is_presto;
}
public class Enable_component {
public String created;
public String pro_from;
public String presto_from;
}
public class Contact_component {
public String telephone;
public String email;
}
public class Mkt_component {
public String mkt_source;
public String mkt_medium;
public String mkt_campaign;
public String signup_origin;
public String month_deliveries;
}
public class Address_component {
public String postal_code;
public String address;
public String complement;
public String neighborhood;
public String city;
public String state;
public String country;
}
//public String updated;
@AuraEnabled
public String segment;
@AuraEnabled
public Integer estimatedMonthlyPackages;
@AuraEnabled
public String averageTicket;
@AuraEnabled
public String favoredContactTime;
@AuraEnabled
public String favoredContactMethod;
@AuraEnabled
public Boolean loggiEnvios;
public static Wrapper_CLS_ContaPJ parse(String json) {
return (Wrapper_CLS_ContaPJ)System.JSON.deserialize(json, Wrapper_CLS_ContaPJ.class);
}
global List<String> validateRequiredFields() {
List<String> validate = new List<String>();
if (pk == null) {
validate.add('Parâmetro idLoggi Obrigatório');
}
if (Util.nullToEmpty(cnpj)) {
validate.add('Parâmetro CNPJ Obrigatório');
}
if (Util.nullToEmpty(name)) {
validate.add('Parâmetro nomeconta Obrigatório');
}
if (Util.nullToEmpty(Address_component.address)) {
validate.add('Parâmetro logradouro Obrigatório');
}
if (Util.nullToEmpty(Address_component.city)) {
validate.add('Parâmetro cidade Obrigatório');
}
if (Util.nullToEmpty(Address_component.state)) {
validate.add('Parâmetro estado Obrigatório');
}
if (Util.nullToEmpty(Address_component.country)) {
validate.add('Parâmetro pais Obrigatório');
}
if (Util.nullToEmpty(Address_component.postal_code)) {
validate.add('Parâmetro cep Obrigatório');
}
if (Util.nullToEmpty(Address_component.neighborhood)) {
validate.add('Parâmetro bairro Obrigatório');
}
if (Financial_component.bankslip_feature != CCConstants.NAOMODERADO && Financial_component.bankslip_feature != CCConstants.EMMODERACAO && Financial_component.bankslip_feature != CCConstants.APROVADO && Financial_component.bankslip_feature != CCConstants.RECUSADO) {
validate.add('Parâmetro Boleto Status inválido');
}
return validate;
}
}
This is the Json that I'm supposed to receive as a response of the POST Request
And this is the Json that I'm receiving
{
"pk": "576010",
"name": "TIZZIANI MOTOPECAS EIRELI",
"cnpj": "19251987000145",
"address_component": {
"postal_code": "87705190",
"address": "AV PARANA 1571",
"complement": "N/A",
"neighborhood": "JARDIM AMERICA",
"city": "PARANAVAI",
"state": "PR",
"country": "BRASIL"
},
"contact_component": {
"telephone": "0576010",
"email": "[email protected]"
},
"financial_component": {
"is_overdue": "False",
"bankslip_feature": "APROVADO"
},
"mkt_component": {
"mkt_source": "None",
"mkt_medium": "None",
"mkt_campaign": "None",
"signup_origin": "N/A",
"month_deliveries": "None"
},
"bl_component": {
"blocked": "True",
"blocked_at": "None",
"blocked_by": "N/A",
"blocked_reason": "N/A"
},
"vertical_component": {
"is_corp": "True",
"is_pro": "True",
"is_presto": "False"
},
"enable_component": {
"created": "2022-11-08 09:19:11.190067",
"pro_from": "2022-11-03 16:59:51.034103",
"presto_from": "None"
}
}
As you can see, the name of the JSON fields of the images, which should be how the data should arrive for me, and the name of the fields in the Wrapper class and in the JSON where the data is actually arriving, as a response of the POST request, are different. Example: blockedAt and blocked_at
And the fields that have the same name, for example: segment, estimatedMonthlyPackages, averageTicket, favoredContactTime, favoredContactMethod, despite having the same name, are not coming in the JSON response.
I am very new at this, so if any of you could explain to me why the name of the fields in the JSON and in the wrapper class are different and, even though, works fine for the most of the fields, but, for the last six fields in the wrapper, it does not bring the data? Please.
Thank you.