SyncMadeEasy/force-app/main/default/classes/UpdateCustomerFromShopify.cls

865 lines
58 KiB
OpenEdge ABL
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* ─────────────────────────────────────────────────────────────────────────────────────────────────┐
* This web service class is use for handle Shopify's Customer webhook response.
* Trigger on customer update and create.
* Shopify API Documentation: https://shopify.dev/docs/admin-api/rest/reference
* Create Shopify Store: https://www.shopify.com/signup?itcat=identity&itterm=create-new-store
* Shopify API Release 2020: https://www.shopify.in/partners/blog/shopify-api-release-january-2020
* What is Person Account in Salesforce ? https://help.salesforce.com/articleView?id=account_person.htm&type=5
* ──────────────────────────────────────────────────────────────────────────────────────────────────
* @author Sumit <sumit@hicShopify.com>
* ──────────────────────────────────────────────────────────────────────────────────────────────────
*/
@RestResource(urlMapping='/UpdateCustomerFromShopify/*')
global with sharing class UpdateCustomerFromShopify {
@HttpPost
global static String updateCustomer() {
List<Account> listOfAccountToUpdate = new List<Account>();
RestRequest request = RestContext.request;
RestResponse response = RestContext.response;
// Default store name
String store = 'Default';
Map<String, String> params = request.params;
if (!params.isEmpty() && params.containsKey('store') && params.get('store') != null)
store = params.get('store');
System.debug('🛍️ Debug Store Name -- ' + store);
String customerResponse = request.requestBody.toString().trim();
// Deserialize JSON
Map<String, Object> MapofCustomer =
(Map<String, Object>) JSON.deserializeUntyped(customerResponse);
// Normalize email to lowercase
if (MapofCustomer.containsKey('email') && MapofCustomer.get('email') != null) {
MapofCustomer.put(
'email',
String.valueOf(MapofCustomer.get('email')).toLowerCase()
);
}
// Serialize back and overwrite the SAME variable
customerResponse = JSON.serialize(MapofCustomer);
System.debug('MapofCustomer: ' + JSON.serializePretty(MapofCustomer));
String shopifyId = String.valueOf(MapofCustomer.get('id'));
System.debug('Shopify Customer ID: ' + shopifyId);
// Get configuration for this store
List<HIC_ShopifySync__HIC_Configuration__c> listofConfiguration = [
SELECT Id, Name, HIC_ShopifySync__Enable_Lead__c,
HIC_ShopifySync__Shopify_URL__c,
HIC_ShopifySync__Private_Key_Password__c
FROM HIC_ShopifySync__HIC_Configuration__c
WHERE Name = :store
LIMIT 1
];
// Check if configuration and Lead feature are enabled
if (!listofConfiguration.isEmpty() &&
listofConfiguration[0].HIC_ShopifySync__Enable_Lead__c) {
// Check if webhook payload includes orders_count
if (MapofCustomer.containsKey('orders_count')) {
Integer ordersCount = Integer.valueOf(String.valueOf(MapofCustomer.get('orders_count')));
System.debug('Orders Count (from webhook): ' + ordersCount);
if (ordersCount < 1) {
createLead(customerResponse, store);
} else {
createAccountContact(customerResponse, store);
}
} else {
System.enqueueJob(new HIC_ShopifyUtility.FetchCustomerJob(
listofConfiguration[0].Id,
shopifyId,
store,
customerResponse
));
}
} else if (!listofConfiguration.isEmpty()) {
// Only run this if we actually have a configuration
System.enqueueJob(new HIC_ShopifyUtility.FetchCustomerJob(
listofConfiguration[0].Id,
shopifyId,
store,
customerResponse
));
} else {
// No configuration for this store. Returning 200 here silently DISCARDED the customer —
// the relay treats 2xx as success and Shopify never re-delivers. Signal a retryable
// failure instead so the record survives until the store is configured.
System.debug(LoggingLevel.ERROR, 'SME_SYNC No configuration found for store: ' + store
+ ' — rejecting as retryable so the record is not lost');
response.statusCode = 503;
return 'NO_CONFIG_FOR_STORE';
}
response.statusCode = 200;
return 'OK';
}
global static string updateCustomer(String requestBody, Map <String, String> params){
/* list<Account> listOfAccountToUpdate = new list<Account>();
String generic_value1 = '';
//RestRequest request = RestContext.request;
String store = 'Default';
//Map <String, String> params = request.params;
if(!params.isEmpty() && params.containsKey('store') && params.get('store') != null)
store = params.get('store');
System.debug('Debug Store Name--'+store);
//RestResponse response = RestContext.response;
String customerResponse = requestBody.trim();
list<HIC_ShopifySync__HIC_Configuration__c> listofConfiguration = new list<HIC_ShopifySync__HIC_Configuration__c>();
String query = 'Select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Specify_Close_Date__c, HIC_ShopifySync__Account_Contact__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Default_Account__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' LIMIT 49999';
listofConfiguration = database.query(query);
String companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey;
//Business Account is Enabled
if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Account_Contact__c == true && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == false && listofConfiguration[0].HIC_ShopifySync__Default_Account__c == false )
{
Map<String, Object> MapofCustomer = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
System.debug('MapofCustomer=='+MapofCustomer);
list<HIC_ShopifySync__HIC_Field_Mapping__c> accountFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c ','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Account\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
accountFieldsList = database.query(query);
list<HIC_ShopifySync__HIC_Field_Mapping__c> updatedAccountFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
if(!MapofCustomer.isEmpty() && MapofCustomer.containskey('default_address')){
Map<String,Object> accMap = (Map<String,Object>)MapofCustomer.get('default_address');
/* if(!accMap.isEmpty() && accMap.containsKey('company') && (accMap.get('company') == null || accMap.get('company') == '' || accMap.get('company') == 'null')){
accMap.put('company', MapofCustomer.get('first_name')+' '+ MapofCustomer.get('last_name'));
MapofCustomer.put('default_address', accMap);*/
//Update On 18/102023
// --------------------------------------------------------- Start
/* if (!accMap.isEmpty() && accMap.containsKey('company') &&
(String.isBlank((String)accMap.get('company')) || accMap.get('company') == 'null')) {
accMap.put('company',
(String.isBlank((String)MapofCustomer.get('first_name')) ? '' : (String)MapofCustomer.get('first_name')) +
(String.isBlank((String)MapofCustomer.get('last_name')) ? '' : ' ' + (String)MapofCustomer.get('last_name'))
);
MapofCustomer.put('default_address', accMap);
// --------------------------------------------------------- End
}
} else if ((MapofCustomer.containsKey('first_name') && MapofCustomer.get('first_name') != null) || (MapofCustomer.containsKey('last_name') && MapofCustomer.get('last_name') != null)){
MapofCustomer.put('default_address', new Map<String, Object>{'company' => (String)MapofCustomer.get('first_name') + MapofCustomer.get('last_name')});
}
String listType = 'List<' + 'Account' + '>';
list<sobject> accountListToupsert = (List<SObject>)Type.forName(listType).newInstance();
if(updatedAccountFieldsList.isEmpty()){
accountListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(accountFieldsList,'Account',MapofCustomer,listofConfiguration,companyTimeZone));
}else{
accountListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(updatedAccountFieldsList,'Account',MapofCustomer,listofConfiguration,companyTimeZone));
}
Map<String, Object> MapofCustomer1 = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
list<HIC_ShopifySync__HIC_Field_Mapping__c> ContactFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c ,HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
ContactFieldsList = database.query(query);
MapofCustomer1.put('Accountid',String.valueof(MapofCustomer1.get('id')));
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(MapofCustomer1.containsKey('Accountid') && !(String.valueOf(MapofCustomer1.get('Accountid'))).contains('Person ')){
MapofCustomer1.put('Accountid','Person '+String.valueof(MapofCustomer1.get('id')));
}else if(!MapofCustomer1.containsKey('Accountid')){
MapofCustomer1.put('Accountid','Person '+String.valueof(MapofCustomer1.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(MapofCustomer1.containsKey('Accountid') && !(String.valueOf(MapofCustomer1.get('Accountid'))).contains('Business ')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}else if(!MapofCustomer1.containsKey('Accountid')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}
}
}else{
if(MapofCustomer1.containsKey('Accountid') && !(String.valueOf(MapofCustomer1.get('Accountid'))).contains('Business ')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}else if(!MapofCustomer1.containsKey('Accountid')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}
}
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer1.get('id'))).contains('Person ')){
MapofCustomer1.put('id','Person '+String.valueof(MapofCustomer1.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer1.get('id'))).contains('Business ')){
MapofCustomer1.put('id','Business '+String.valueof(MapofCustomer1.get('id')));
}
}
}else{
if(!(String.valueOf(MapofCustomer1.get('id'))).contains('Business '))
MapofCustomer1.put('id','Business '+String.valueof(MapofCustomer1.get('id')));
}
String listType1 = 'List<' + 'Contact' + '>';
list<sobject> ContactListToupsert = (List<SObject>)Type.forName(listType1).newInstance();
ContactListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(ContactFieldsList,'Contact',MapofCustomer1,listofConfiguration,companyTimeZone));
if(accountListToupsert.Isempty()) return null;
Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account');
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
try{
if(!Test.isRunningTest()){
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Account',accountListToupsert,theField,true,store);
}
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
if(ContactListToupsert.Isempty()) return null;
Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact');
Map<String, SObjectField> fieldMap1 = objectType1.getDescribe().fields.getMap();
Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c');
try{
if(!Test.isRunningTest()){
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Contact',ContactListToupsert,theField1,true,store);
return null;
}
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
//Business Account & Contact is Enabled amd Default Account
}else if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Account_Contact__c == true && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == false && listofConfiguration[0].HIC_ShopifySync__Default_Account__c == true ){
Map<String, Object> MapofCustomer2 = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
list<HIC_ShopifySync__HIC_Field_Mapping__c> ContactFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
ContactFieldsList = database.query(query);
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer2.get('id'))).contains('Person ')){
MapofCustomer2.put('id','Person '+String.valueof(MapofCustomer2.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer2.get('id'))).contains('Business ')){
MapofCustomer2.put('id','Business '+String.valueof(MapofCustomer2.get('id')));
}
}
}else{
if(!(String.valueOf(MapofCustomer2.get('id'))).contains('Business '))
MapofCustomer2.put('id','Business '+String.valueof(MapofCustomer2.get('id')));
}
String listType = 'List<' + 'Contact' + '>';
list<sobject> ContactListToupsert = (List<SObject>)Type.forName(listType).newInstance();
ContactListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(ContactFieldsList,'Contact',MapofCustomer2,listofConfiguration,companyTimeZone));
if(ContactListToupsert.Isempty()) return null;
Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact');
Map<String, SObjectField> fieldMap1 = objectType1.getDescribe().fields.getMap();
Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c');
if(!Test.isRunningTest()){
try{
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Contact',ContactListToupsert,theField1,true,store);
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
}return null;
//Person Account is Enabled
}else if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == true && listofConfiguration[0].HIC_ShopifySync__Default_Account__c == false ){
Map<String, Object> MapofCustomer = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
list<HIC_ShopifySync__HIC_Field_Mapping__c> PersonaccountFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>([Select HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Object_name__c from HIC_ShopifySync__HIC_Field_Mapping__c Where (HIC_ShopifySync__Object_Name__c = 'Account' OR HIC_ShopifySync__Object_Name__c = 'PersonAccount' ) And HIC_ShopifySync__SF_Field__c != 'name' And name !='Account-RecordTypeId' AND HIC_ShopifySync__Store__c =: store]);
String listType = 'List<' + 'Account' + '>';
list<sobject> PersonaccountListToupsert = (List<SObject>)Type.forName(listType).newInstance();
PersonaccountListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(PersonaccountFieldsList,'Account',MapofCustomer,listofConfiguration,companyTimeZone));
try{
if(PersonaccountListToupsert.Isempty()) return null;
Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account');
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Account',PersonaccountListToupsert,theField,true,store);
}catch(Exception e){
System.debug('DML Error');
}
}
} */
return null;
}
public static void createLead(String customerResponse, String store){
list<HIC_ShopifySync__HIC_Configuration__c> listofConfiguration = new list<HIC_ShopifySync__HIC_Configuration__c>();
String companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey;
String querys = 'Select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__DNCDAMissingAccounts__c,HIC_ShopifySync__Number_of_pages_for_Account__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Specify_Close_Date__c, HIC_ShopifySync__Account_Contact__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Default_Account__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c,HIC_ShopifySync__Enable_Lead__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' LIMIT 49999';
listofConfiguration = database.query(querys);
list<HIC_ShopifySync__HIC_Field_Mapping__c> LeadFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
string query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c ','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Lead\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
LeadFieldsList = database.query(query);
Map<String, Object> MapofCustomer = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
if(!MapofCustomer.isEmpty()){
if(!MapofCustomer.isEmpty() && MapofCustomer.containskey('default_address')){
Map<String,Object> accMap = (Map<String,Object>)MapofCustomer.get('default_address');
if(!accMap.isEmpty() && accMap.containsKey('company') && (accMap.get('company') == null || accMap.get('company') == '' || accMap.get('company') == 'null')){
if (!String.isBlank((String)accMap.get('first_name')) || !String.isBlank((String)accMap.get('last_name'))) {
accMap.put('company',
(String.isBlank((String)accMap.get('first_name')) ? '' : (String)accMap.get('first_name')) +
(String.isBlank((String)accMap.get('last_name')) ? '' : ' ' + (String)accMap.get('last_name'))
);
} else {
accMap.put('company',
(String.isBlank((String)MapofCustomer.get('first_name')) ? '' : (String)MapofCustomer.get('first_name')) +
(String.isBlank((String)MapofCustomer.get('last_name')) ? '' : ' ' + (String)MapofCustomer.get('last_name'))
);
}
MapofCustomer.put('default_address', accMap);
// --------------------------------------------------------- End
}
}else if((MapofCustomer.containsKey('first_name') && MapofCustomer.get('first_name') != null) || (MapofCustomer.containsKey('last_name') && MapofCustomer.get('last_name') != null)){
MapofCustomer.put('default_address', new Map<String, Object>{'company' => (String)MapofCustomer.get('first_name') + MapofCustomer.get('last_name')});
}
}
String updatedCustomerResponse = JSON.serialize(MapofCustomer);
String listType1 = 'List<' + 'Lead' + '>';
list<sobject> LeadListToupsert = (List<SObject>)Type.forName(listType1).newInstance();
list<HIC_ShopifySync__HIC_Field_Mapping__c> updatedLeadFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
if(updatedLeadFieldsList.isEmpty()){
System.debug('LeadFieldsList-->'+LeadFieldsList);
System.debug('updatedLeadFieldsList-->'+updatedLeadFieldsList);
LeadListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(LeadFieldsList,'Lead',MapofCustomer,listofConfiguration,companyTimeZone));
System.debug('LeadListToupsertif-->'+LeadListToupsert);
}else{
System.debug('updatedLeadFieldsList-->'+updatedLeadFieldsList);
LeadListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(updatedLeadFieldsList,'Lead',MapofCustomer,listofConfiguration,companyTimeZone));
System.debug('LeadListToupsertelse-->'+LeadListToupsert);
}
Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Lead');
Map<String, SObjectField> fieldMap1 = objectType1.getDescribe().fields.getMap();
Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c');
if(!Test.isRunningTest()){
try{
EmailErrorCSV.makeCsvAndSendInEmail(updatedCustomerResponse,'Lead',LeadListToupsert,theField1,true,store);
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
}
}
public static void createAccountContact(String customerResponse, String store){
String companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey;
list<HIC_ShopifySync__HIC_Configuration__c> listofConfiguration = new list<HIC_ShopifySync__HIC_Configuration__c>();
String querys = 'Select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__DNCDAMissingAccounts__c,HIC_ShopifySync__Number_of_pages_for_Account__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Specify_Close_Date__c, HIC_ShopifySync__Account_Contact__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Default_Account__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c,HIC_ShopifySync__Enable_Lead__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Customer_Email_Domain__c','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' LIMIT 49999';
listofConfiguration = database.query(querys);
// ====== B2B Store Path ======
if (!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Customer_Email_Domain__c == true) {
Map<String, Object> MapofCustomer = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
String email = '';
if (MapofCustomer.containsKey('email') && MapofCustomer.get('email') != null) {
email = String.valueOf(MapofCustomer.get('email')).trim();
}
if (String.isNotBlank(email) && email.contains('@')) {
String domain = email.substringAfter('@').substringBefore('.');
// Find or create Account by domain name
Id b2bAccountId;
List<Account> existingAccounts = [SELECT Id, Name FROM Account WHERE Name = :domain LIMIT 1];
if (!existingAccounts.isEmpty()) {
b2bAccountId = existingAccounts[0].Id;
} else {
Account acc = new Account(Name = domain);
insert acc;
b2bAccountId = acc.Id;
}
// Build Contact via field mapping
list<HIC_ShopifySync__HIC_Field_Mapping__c> ContactFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
string query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c ,HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Is_Override__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
ContactFieldsList = database.query(query);
Map<String, Object> MapofCustomer1 = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
if (!(String.valueOf(MapofCustomer1.get('id'))).contains('Business ')) {
MapofCustomer1.put('id', 'Business ' + String.valueof(MapofCustomer1.get('id')));
}
MapofCustomer1.put('Accountid', MapofCustomer1.get('id'));
String listType1 = 'List<' + 'Contact' + '>';
list<sobject> ContactListToupsert = (List<SObject>)Type.forName(listType1).newInstance();
ContactListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(ContactFieldsList, 'Contact', MapofCustomer1, listofConfiguration, companyTimeZone));
// Override: clear external ID ref and set direct AccountId
if (!ContactListToupsert.isEmpty()) {
SObject con = ContactListToupsert[0];
con.putSObject('Account', null);
con.put('AccountId', b2bAccountId);
}
Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact');
Map<String, SObjectField> fieldMap1 = objectType1.getDescribe().fields.getMap();
Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c');
try {
if (!Test.isRunningTest()) {
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse, 'Contact', ContactListToupsert, theField1, true, store);
}
} catch(Exception e) {
System.debug('Exception ' + e.getMessage() + ' at ' + e.getLineNumber());
}
}
return;
}
//Business Account is Enabled
if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Account_Contact__c == true && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == false && listofConfiguration[0].HIC_ShopifySync__Default_Account__c == false )
{
list<HIC_ShopifySync__HIC_Field_Mapping__c> accountFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
string query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Is_Override__c ','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Account\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
accountFieldsList = database.query(query);
list<HIC_ShopifySync__HIC_Field_Mapping__c> updatedAccountFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
Map<String, Object> MapofCustomer = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
if(!MapofCustomer.isEmpty() && MapofCustomer.containskey('default_address')){
Map<String,Object> accMap = (Map<String,Object>)MapofCustomer.get('default_address');
if(!accMap.isEmpty() && accMap.containsKey('company') && (accMap.get('company') == null || accMap.get('company') == '' || accMap.get('company') == 'null')&& !listofConfiguration[0].HIC_ShopifySync__DNCDAMissingAccounts__c){
if (!String.isBlank((String)accMap.get('first_name')) || !String.isBlank((String)accMap.get('last_name'))) {
accMap.put('company',
(String.isBlank((String)accMap.get('first_name')) ? '' : (String)accMap.get('first_name')) +
(String.isBlank((String)accMap.get('last_name')) ? '' : ' ' + (String)accMap.get('last_name'))
);
} else {
accMap.put('company',
(String.isBlank((String)MapofCustomer.get('first_name')) ? '' : (String)MapofCustomer.get('first_name')) +
(String.isBlank((String)MapofCustomer.get('last_name')) ? '' : ' ' + (String)MapofCustomer.get('last_name'))
);
}
MapofCustomer.put('default_address', accMap);
// --------------------------------------------------------- End
}
}else if((MapofCustomer.containsKey('first_name') && MapofCustomer.get('first_name') != null) || (MapofCustomer.containsKey('last_name') && MapofCustomer.get('last_name') != null)){
if(listofConfiguration[0].HIC_ShopifySync__DNCDAMissingAccounts__c) return;
MapofCustomer.put('default_address', new Map<String, Object>{'company' => (String)MapofCustomer.get('first_name') + MapofCustomer.get('last_name')});
}
String updatedCustomerResponse = JSON.serialize(MapofCustomer);
String listType = 'List<' + 'Account' + '>';
list<sobject> accountListToupsert = (List<SObject>)Type.forName(listType).newInstance();
if(updatedAccountFieldsList.isEmpty()){
accountListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(accountFieldsList,'Account',MapofCustomer,listofConfiguration,companyTimeZone));
}else{
accountListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(updatedAccountFieldsList,'Account',MapofCustomer,listofConfiguration,companyTimeZone));
}
Map<String, Object> MapofCustomer1 = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
list<HIC_ShopifySync__HIC_Field_Mapping__c> ContactFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c ,HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Is_Override__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
ContactFieldsList = database.query(query);
MapofCustomer1.put('Accountid',String.valueof(MapofCustomer1.get('id')));
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(MapofCustomer1.containsKey('Accountid') && !(String.valueOf(MapofCustomer1.get('Accountid'))).contains('Person ')){
MapofCustomer1.put('Accountid','Person '+String.valueof(MapofCustomer1.get('id')));
}else if(!MapofCustomer1.containsKey('Accountid')){
MapofCustomer1.put('Accountid','Person '+String.valueof(MapofCustomer1.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(MapofCustomer1.containsKey('Accountid') && !(String.valueOf(MapofCustomer1.get('Accountid'))).contains('Business ')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}else if(!MapofCustomer1.containsKey('Accountid')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}
}
}else{
if(MapofCustomer1.containsKey('Accountid') && !(String.valueOf(MapofCustomer1.get('Accountid'))).contains('Business ')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}else if(!MapofCustomer1.containsKey('Accountid')){
MapofCustomer1.put('Accountid','Business '+String.valueof(MapofCustomer1.get('id')));
}
}
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer1.get('id'))).contains('Person ')){
MapofCustomer1.put('id','Person '+String.valueof(MapofCustomer1.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer1.get('id'))).contains('Business ')){
MapofCustomer1.put('id','Business '+String.valueof(MapofCustomer1.get('id')));
}
}
}else{
if(!(String.valueOf(MapofCustomer1.get('id'))).contains('Business '))
MapofCustomer1.put('id','Business '+String.valueof(MapofCustomer1.get('id')));
}
String listType1 = 'List<' + 'Contact' + '>';
list<sobject> ContactListToupsert = (List<SObject>)Type.forName(listType1).newInstance();
ContactListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(ContactFieldsList,'Contact',MapofCustomer1,listofConfiguration,companyTimeZone));
//if(accountListToupsert.Isempty()) return null;
Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account');
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
try{
if(!Test.isRunningTest()){
EmailErrorCSV.makeCsvAndSendInEmail(updatedCustomerResponse,'Account',accountListToupsert,theField,true,store);
}
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
// if(ContactListToupsert.Isempty()) return null;
Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact');
Map<String, SObjectField> fieldMap1 = objectType1.getDescribe().fields.getMap();
Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c');
try{
if(!Test.isRunningTest()){
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Contact',ContactListToupsert,theField1,true,store);
// return null;
}
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
//Business Account & Contact is Enabled amd Default Account
}else if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Account_Contact__c == true && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == false && listofConfiguration[0].HIC_ShopifySync__Default_Account__c == true ){
Map<String, Object> MapofCustomer2 = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
list<HIC_ShopifySync__HIC_Field_Mapping__c> ContactFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>();
string query = '';
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Is_Override__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
ContactFieldsList = database.query(query);
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer2.get('id'))).contains('Person ')){
MapofCustomer2.put('id','Person '+String.valueof(MapofCustomer2.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(MapofCustomer2.get('id'))).contains('Business ')){
MapofCustomer2.put('id','Business '+String.valueof(MapofCustomer2.get('id')));
}
}
}else{
if(!(String.valueOf(MapofCustomer2.get('id'))).contains('Business '))
MapofCustomer2.put('id','Business '+String.valueof(MapofCustomer2.get('id')));
}
String listType = 'List<' + 'Contact' + '>';
list<sobject> ContactListToupsert = (List<SObject>)Type.forName(listType).newInstance();
ContactListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(ContactFieldsList,'Contact',MapofCustomer2,listofConfiguration,companyTimeZone));
// if(ContactListToupsert.Isempty()) return null;
Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact');
Map<String, SObjectField> fieldMap1 = objectType1.getDescribe().fields.getMap();
Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c');
if(!Test.isRunningTest()){
try{
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Contact',ContactListToupsert,theField1,true,store);
}catch(Exception e){
System.debug('Exception '+ e.getMessage() + ' at' +e.getLineNumber());
}
}//return null;
//Person Account is Enabled
}else if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == true && listofConfiguration[0].HIC_ShopifySync__Default_Account__c == false ){
Map<String, Object> MapofCustomer = (Map<String, Object>) JSON.deserializeUntyped(customerResponse);
list<HIC_ShopifySync__HIC_Field_Mapping__c> PersonaccountFieldsList = new list<HIC_ShopifySync__HIC_Field_Mapping__c>([Select HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Object_name__c, HIC_ShopifySync__Is_Override__c from HIC_ShopifySync__HIC_Field_Mapping__c Where (HIC_ShopifySync__Object_Name__c = 'Account' OR HIC_ShopifySync__Object_Name__c = 'PersonAccount' ) And HIC_ShopifySync__SF_Field__c != 'name' And name !='Account-RecordTypeId' AND HIC_ShopifySync__Store__c =: store]);
String listType = 'List<' + 'Account' + '>';
list<sobject> PersonaccountListToupsert = (List<SObject>)Type.forName(listType).newInstance();
PersonaccountListToupsert.add(HIC_ShopifyUtility.processFieldTypeAndMapping(PersonaccountFieldsList,'Account',MapofCustomer,listofConfiguration,companyTimeZone));
try{
// if(PersonaccountListToupsert.Isempty()) return null;
Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account');
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'Account',PersonaccountListToupsert,theField,true,store);
}catch(Exception e){
System.debug('DML Error');
}
}
}
public static void convertLead(String payload, String store){
System.debug('payload==>' + payload);
System.debug('store-->>'+store);
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(payload);
Map<String, Object> defaultAddress = (Map<String, Object>) parsed.get('default_address');
if (defaultAddress != null) {
// safe config lookup (no exception if not found)
List<HIC_ShopifySync__HIC_Configuration__c> cfgList = [
SELECT Name, HIC_ShopifySync__Account_Contact__c, HIC_ShopifySync__Person_Account__c,
HIC_ShopifySync__Customer_Email_Domain__c
FROM HIC_ShopifySync__HIC_Configuration__c
WHERE HIC_ShopifySync__Store__c = :store
LIMIT 1
];
HIC_ShopifySync__HIC_Configuration__c config = (cfgList.isEmpty() ? null : cfgList[0]);
String customerId = String.valueOf(defaultAddress.get('customer_id'));
String shopifyId = '%' + customerId; // kept exactly as you wrote
// Fetch Lead (unchanged)
List<Lead> leadList = [
SELECT Id, Email, HIC_ShopifySync__Shopify_Id__c
FROM Lead
WHERE HIC_ShopifySync__Shopify_Id__c = :customerId
AND IsConverted = FALSE
LIMIT 1
];
if (!leadList.isEmpty()) {
Lead salesforceLead = leadList[0];
// Determine behavior: if config absent, fallback to Account+Contact (your old behaviour)
Boolean useAccountContact = (config != null && config.HIC_ShopifySync__Account_Contact__c == true);
Boolean usePersonAccount = (config != null && config.HIC_ShopifySync__Person_Account__c == true);
// ====== B2B: Customer Email Domain path ======
Boolean isB2B = (config != null && config.HIC_ShopifySync__Customer_Email_Domain__c == true);
if (isB2B) {
// Resolve Account by email domain
String leadEmail = salesforceLead.Email;
Id domainAccountId;
if (String.isNotBlank(leadEmail) && leadEmail.contains('@')) {
String domain = leadEmail.substringAfter('@').substringBefore('.');
List<Account> domainAccounts = [SELECT Id FROM Account WHERE Name = :domain LIMIT 1];
if (!domainAccounts.isEmpty()) {
domainAccountId = domainAccounts[0].Id;
} else {
Account domainAcc = new Account(Name = domain);
insert domainAcc;
domainAccountId = domainAcc.Id;
}
}
// Find existing Contact by Shopify ID
List<Contact> existingContact = [
SELECT Id FROM Contact
WHERE HIC_ShopifySync__Shopify_Id__c LIKE :shopifyId
LIMIT 1
];
Id existingContactId = !existingContact.isEmpty() ? existingContact[0].Id : null;
// Convert Lead under domain Account
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(salesforceLead.Id);
if (domainAccountId != null) {
lc.setAccountId(domainAccountId);
}
if (existingContactId != null) {
lc.setContactId(existingContactId);
}
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Closed - Converted');
Database.LeadConvertResult result = Database.convertLead(lc);
if (result.isSuccess()) {
Id contactId = result.getContactId();
Contact con = new Contact(
Id = contactId,
HIC_ShopifySync__Shopify_Id__c = 'Business ' + salesforceLead.HIC_ShopifySync__Shopify_Id__c,
Email = salesforceLead.Email
);
update con;
}
}
else if (useAccountContact || config == null) {
// ACCOUNT + CONTACT path (same queries you had)
List<Account> existingAccount = [
SELECT Id, HIC_ShopifySync__Shopify_Id__c
FROM Account
WHERE HIC_ShopifySync__Shopify_Id__c LIKE :shopifyId
LIMIT 1
];
List<Contact> existingContact = [
SELECT Id, AccountId, HIC_ShopifySync__Shopify_Id__c
FROM Contact
WHERE HIC_ShopifySync__Shopify_Id__c LIKE :shopifyId
LIMIT 1
];
if (!existingAccount.isEmpty()) {
Id accId = existingAccount[0].Id;
Id existingContactId = !existingContact.isEmpty() ? existingContact[0].Id : null;
System.debug('existingAccount==>' + existingAccount);
System.debug('existingContact==>' + existingContact);
convertLeadIfAccountExist(salesforceLead, accId, existingContactId);
}
else {
convertLeadIfAccountDoesNotExist(salesforceLead);
}
}
else if (usePersonAccount) {
// PERSON ACCOUNT path - dynamic SOQL to avoid compile errors in orgs without Person Accounts
String shopifyEsc = String.escapeSingleQuotes(shopifyId);
String personQuery =
'SELECT Id FROM Account ' +
'WHERE IsPersonAccount = TRUE ' +
'AND HIC_ShopifySync__Shopify_Id__c LIKE \'' + shopifyEsc + '\' ' +
'LIMIT 1';
List<Account> existingPersonAcc = Database.query(personQuery);
if (!existingPersonAcc.isEmpty()) {
convertLeadIfPersonAccountExist(salesforceLead, existingPersonAcc[0].Id);
} else {
convertLeadIfPersonAccountDoesNotExist(salesforceLead);
}
}
}
else {
createAccountContact(payload, store);
}
}
}
// Business Account: existing Account
public static void convertLeadIfAccountExist(Lead sLead, Id accId, Id existingContactId){
Id leadId = sLead.Id;
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadId);
lc.setAccountId(accId);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Closed - Converted');
// If a Contact already exists (created by createAccountContact), reuse it
// instead of letting Salesforce create a new one — prevents duplicate Contacts
if (existingContactId != null) {
lc.setContactId(existingContactId);
System.debug('Reusing existing Contact during lead convert: ' + existingContactId);
}
Database.LeadConvertResult result = Database.convertLead(lc);
System.debug('Converted Lead ID: ' + result.getLeadId());
System.debug('coverted-AccountId==>' + result.getAccountId());
System.debug('converted-ContactId==>' + result.getContactId());
if (result.isSuccess()) {
Id contactId = result.getContactId();
List<Contact> conList = new List<Contact>();
Contact con = new Contact(
Id = contactId,
HIC_ShopifySync__Shopify_Id__c = 'Business ' + sLead.HIC_ShopifySync__Shopify_Id__c,
Email = sLead.Email
);
conList.add(con);
if (!conList.isEmpty()) {
update conList;
}
}
}
// Business Account: no existing Account (Salesforce will create one on convert)
public static void convertLeadIfAccountDoesNotExist(Lead sLead){
Id leadId = sLead.Id;
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadId);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Closed - Converted');
Database.LeadConvertResult result = Database.convertLead(lc);
if (result.isSuccess()) {
Id accountId = result.getAccountId();
List<Account> accList = new List<Account>();
Account acct = new Account(
Id = accountId,
AccountSource = 'Shopify',
HIC_ShopifySync__Shopify_Id__c = 'Business ' + sLead.HIC_ShopifySync__Shopify_Id__c
);
accList.add(acct);
Id contactId = result.getContactId();
List<Contact> conList = new List<Contact>();
Contact con = new Contact(
Id = contactId,
HIC_ShopifySync__Shopify_Id__c = 'Business ' + sLead.HIC_ShopifySync__Shopify_Id__c,
Email = sLead.Email
);
conList.add(con);
if (!accList.isEmpty()) update accList;
if (!conList.isEmpty()) update conList;
}
}
// Person Account: existing Person Account found -> attach and update with Person prefix
public static void convertLeadIfPersonAccountExist(Lead sLead, Id personAccId){
Id leadId = sLead.Id;
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadId);
lc.setAccountId(personAccId);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Closed - Converted');
Database.LeadConvertResult result = Database.convertLead(lc);
if (result.isSuccess()) {
Account pa = new Account(
Id = personAccId,
HIC_ShopifySync__Shopify_Id__c = 'Person ' + sLead.HIC_ShopifySync__Shopify_Id__c
);
update pa;
}
}
// Person Account: no existing Person Account -> let convert create it then update
public static void convertLeadIfPersonAccountDoesNotExist(Lead sLead){
Id leadId = sLead.Id;
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadId);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Closed - Converted');
Database.LeadConvertResult result = Database.convertLead(lc);
if (result.isSuccess()) {
Account pa = new Account(
Id = result.getAccountId(),
AccountSource = 'Shopify',
HIC_ShopifySync__Shopify_Id__c = 'Person ' + sLead.HIC_ShopifySync__Shopify_Id__c
);
update pa;
}
}
}