/** * ─────────────────────────────────────────────────────────────────────────────────────────────────┐ * This Batch class is use for upsert Shopify's customer into the Salesfroce * 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 * ────────────────────────────────────────────────────────────────────────────────────────────────── */ global with sharing class FetchAccounts implements Database.Batchable, Database.allowscallouts, Database.Stateful{ integer count = 0; List listOfConfiguration; Boolean checkException; String linkForNextPage = ''; Boolean isEnd = false; String store = 'Default'; String updated_at_min = ''; String updated_at_max = ''; global FetchAccounts(String linkForNextPage,Boolean isEnd, String store){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; checkException = false; this.store = store; } global FetchAccounts(String linkForNextPage,Boolean isEnd, String store, String updated_at_min, String updated_at_max){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; checkException = false; this.store = store; this.updated_at_min = updated_at_min; this.updated_at_max = updated_at_max; } //Depreceated global FetchAccounts(String linkForNextPage,Boolean isEnd){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; checkException = false; this.store = '123'; } global Iterable start(Database.BatchableContext bc){ String customerResponse = ''; String JSONResponse = ''; String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Chunk_Size__c,HIC_ShopifySync__Enable_Lead__c,HIC_ShopifySync__Upsert_Customer_basis_on_Email__c, HIC_ShopifySync__Draft_Order_Sync__c, id,HIC_ShopifySync__AccountContactBatchCompleted__c, name,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__ProductVariantBatchCompleted__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__Collection__c, HIC_ShopifySync__Number_of_pages_for_Account__c,HIC_ShopifySync__OrderBatchCompleted__c, HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c, HIC_ShopifySync__Default_Account__c,HIC_ShopifySync__InventoryBatchCompleted__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__Person_Account__c, HIC_ShopifySync__Account_Contact__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 1' ; listOfConfiguration = new list(); listOfConfiguration = Database.query(query); system.debug('query ==> '+query); System.debug('query 11 ---'+database.query(query)); system.debug('listOfConfiguration ==> '+listOfConfiguration); Map main = new Map(); try{ // Get Shopif's Customer JSON Response if(!Test.isRunningTest()){ if(String.isNotBlank(linkForNextPage) && !isEnd){ JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('customers.json?limit='+listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c+'&page_info='+linkForNextPage, listOfConfiguration); }else{ JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('customers.json?limit='+listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c+(updated_at_min!=''?'&updated_at_min='+updated_at_min:'')+(updated_at_max!=''?'&updated_at_max='+updated_at_max:''), listOfConfiguration); } } else{ JSONResponse = 'not blank'; } if(String.isNotBlank(JSONResponse)){ if(!Test.isRunningTest()){ main = (Map) JSON.deserializeUntyped(JSONResponse); }else{ main.put('link',null); main.put('response','{ "customers": [ { "id": 1073387929664, "email": "", "accepts_marketing": false, "created_at": "2019-01-10T00:12:13-12:00", "updated_at": "2019-01-10T00:12:13-12:00", "first_name": "", "last_name": "", "orders_count": 0, "state": "disabled", "total_spent": "0.00", "last_order_id": null, "note": "", "verified_email": true, "multipass_identifier": null, "tax_exempt": false, "phone": "9717626066", "tags": "", "last_order_name": null, "currency": "INR", "addresses": [ { "id": 1197969899584, "customer_id": 1073387929664, "first_name": "firstnameu", "last_name": "lastnamev", "company": "test", "address1": "address", "address2": "", "city": "", "province": "", "country": "India", "zip": "", "phone": "9717626066", "name": "firstnameu lastnamev", "province_code": null, "country_code": "IN", "country_name": "India", "default": true } ], "admin_graphql_api_id": "gid://shopify/Customer/1073387929664", "default_address": { "id": 1197969899584, "customer_id": 1073387929664, "first_name": "firstnameu", "last_name": "lastnamev", "company": "test", "address1": "address", "address2": "", "city": "", "province": "", "country": "India", "zip": "", "phone": "9717626066", "name": "firstnameu lastnamev", "province_code": null, "country_code": "IN", "country_name": "India", "default": true } } ] }'); } if(!main.isEmpty() && main.containskey('response') && main.containskey('link') ){ if( main.get('response') != null) customerResponse = String.valueof(main.get('response')); if(main.get('link') != null && String.isNotBlank(customerResponse)){ linkForNextPage = String.valueof(main.get('link')); }else{ isEnd = true; } } } if(!String.isNotBlank(customerResponse)){ checkException = true; } }catch(Exception e){ checkException = true; } if(!checkException){ Map meta = (Map) JSON.deserializeUntyped(customerResponse); List objectList = (List) meta.get('customers'); for(Object obj : objectList){ Map metaForObj = (Map) obj; Map objectListForObj; if(!Test.isRunningTest()){ objectListForObj = (Map) metaForObj.get('default_address'); } String name = (metaForObj.get('first_name')==null?'':String.valueOf(metaForObj.get('first_name')).trim()) + ' ' + (metaForObj.get('last_name')==null?'':String.valueOf(metaForObj.get('last_name')).trim()); String email = (metaForObj.get('email')==null?'':String.valueOf(metaForObj.get('email')).trim()); String phone = (metaForObj.get('phone')==null?'':String.valueOf(metaForObj.get('phone')).trim()); } return objectList; }else{ List objectList = new List(); return objectList; } } global void execute(Database.BatchableContext bc, List scope){ count = count + 1; /* ---------- pre-load e-mails when flag is on ---------- */ Set scopeEmails = new Set(); Boolean needEmailCheck = !listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Enable_Lead__c && listofConfiguration[0].HIC_ShopifySync__Upsert_Customer_basis_on_Email__c; if (needEmailCheck) { for (Object o : scope) { if (o == null) continue; Map c = (Map) o; if (c == null) continue; Object emailVal = c.containsKey('email') ? c.get('email') : null; String em = (emailVal == null) ? '' : String.valueOf(emailVal).trim(); if (String.isNotBlank(em)) { scopeEmails.add(em.toLowerCase()); } } } Map emailToContact = new Map(); if (!scopeEmails.isEmpty()) { for (Contact con : [SELECT Id, AccountId, Email FROM Contact WHERE Email IN :scopeEmails LIMIT 1]) { emailToContact.put(con.Email.toLowerCase(), con); } } /* ---------- NEW: map e-mail → open Lead (Shopify_ID__c != null) ---------- */ Map emailToLead = new Map(); if (needEmailCheck && !scopeEmails.isEmpty()) { for (Lead ld : [SELECT Id, Email, HIC_ShopifySync__Shopify_ID__c FROM Lead WHERE Email IN :scopeEmails AND IsConverted = false AND HIC_ShopifySync__Shopify_ID__c != null]) { emailToLead.put(ld.Email.toLowerCase(), ld); } } /* --------------------------------------------------------------------------- */ for (Object obj : scope) { String JSONsingleobj = JSON.serialize(obj); Map customerMap = (Map) obj; system.debug('customerMap--->' + customerMap); Boolean createLead = false; Boolean leadJustConverted = false; if (!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Enable_Lead__c) { Integer ordersCount = customerMap.containsKey('orders_count') ? Integer.valueOf(customerMap.get('orders_count')) : 0; System.debug('[BATCH-DISPATCH] Customer ID: ' + customerMap.get('id') + ' | orders_count raw: ' + customerMap.get('orders_count') + ' | parsed: ' + ordersCount); /* ----- original "create Lead" path (ordersCount < 1) ----- */ if (ordersCount < 1) { if (needEmailCheck) { String em = ''; if (customerMap.containsKey('email')) { Object emailVal = customerMap.get('email'); if (emailVal != null) { em = String.valueOf(emailVal).trim(); } } if (String.isNotBlank(em) && emailToContact.containsKey(em.toLowerCase())) { createLead = false; // Contact already exists } else { createLead = true; } } else { createLead = true; } } else { /* ----- NEW: ordersCount > 0 – convert Lead if one exists ----- */ String em = ''; if (customerMap.containsKey('email')) { Object emailVal = customerMap.get('email'); if (emailVal != null) { em = String.valueOf(emailVal).trim(); } } if (String.isNotBlank(em)) { Lead openLead = emailToLead.get(em.toLowerCase()); if (openLead != null) { convertLeadAndStampIds(openLead); // helper below leadJustConverted = true; } } } } System.debug('[BATCH-DISPATCH] createLead=' + createLead + ' | leadJustConverted=' + leadJustConverted); /* ---------- dispatch ---------- */ if (createLead) { createLead(JSONsingleobj, store); } else if (leadJustConverted) { /* Lead was converted – nothing else to do for this row */ continue; } else { createAccountContact(JSONsingleobj, store); } } } /* ---------- helper: convert Lead and reuse existing Account/Contact ---------- */ private void convertLeadAndStampIds(Lead l) { if (l == null || listOfConfiguration.isEmpty()) { return; } // ====== B2B: Customer Email Domain path ====== Boolean isB2B = listOfConfiguration[0].HIC_ShopifySync__Customer_Email_Domain__c == true; if (isB2B) { // Resolve Account by email domain String leadEmail = l.Email; Id domainAccountId; if (String.isNotBlank(leadEmail) && leadEmail.contains('@')) { String domain = leadEmail.substringAfter('@').substringBefore('.'); List 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 String shopifyIdToSearch = 'Business ' + l.HIC_ShopifySync__Shopify_ID__c; List existingCon = [ SELECT Id FROM Contact WHERE HIC_ShopifySync__Shopify_Id__c = :shopifyIdToSearch LIMIT 1 ]; Database.LeadConvert lc = new Database.LeadConvert(); lc.setLeadId(l.Id); lc.setConvertedStatus('Closed - Converted'); lc.setDoNotCreateOpportunity(true); if (domainAccountId != null) { lc.setAccountId(domainAccountId); } if (!existingCon.isEmpty()) { lc.setContactId(existingCon[0].Id); } Database.LeadConvertResult r = Database.convertLead(lc, true); // Stamp Shopify ID on Contact if (r.isSuccess() && r.getContactId() != null) { Contact con = new Contact( Id = r.getContactId(), HIC_ShopifySync__Shopify_Id__c = shopifyIdToSearch, Email = l.Email ); update con; } return; } // ====== End B2B path ====== String prefix = listOfConfiguration[0].HIC_ShopifySync__Person_Account__c ? 'Person ' : 'Business '; String shopifyIdWithPrefix = prefix + l.HIC_ShopifySync__Shopify_ID__c; // Find existing Account by Shopify ID Account existingAcc; List accList = [ SELECT Id FROM Account WHERE HIC_ShopifySync__Shopify_ID__c = :shopifyIdWithPrefix LIMIT 1 ]; if (!accList.isEmpty()) { existingAcc = accList[0]; } // Find existing Contact by Shopify ID Contact existingCon2; List conList = [ SELECT Id FROM Contact WHERE HIC_ShopifySync__Shopify_ID__c = :shopifyIdWithPrefix LIMIT 1 ]; if (!conList.isEmpty()) { existingCon2 = conList[0]; } Database.LeadConvert lc = new Database.LeadConvert(); lc.setLeadId(l.Id); lc.setConvertedStatus('Closed - Converted'); lc.setDoNotCreateOpportunity(true); // Reuse existing Account if found if (existingAcc != null) { lc.setAccountId(existingAcc.Id); } // ⭐ CRITICAL FIX: Reuse existing Contact to avoid duplicate rule error if (existingCon2 != null) { lc.setContactId(existingCon2.Id); } Database.LeadConvertResult r = Database.convertLead(lc, true); List recordsToUpdate = new List(); // Stamp Shopify ID on Account if newly created if (existingAcc == null && r.getAccountId() != null) { recordsToUpdate.add(new Account( Id = r.getAccountId(), HIC_ShopifySync__Shopify_ID__c = shopifyIdWithPrefix )); } // Stamp Shopify ID on Contact if newly created if (existingCon2 == null && r.getContactId() != null) { recordsToUpdate.add(new Contact( Id = r.getContactId(), HIC_ShopifySync__Shopify_ID__c = shopifyIdWithPrefix )); } if (!recordsToUpdate.isEmpty()) { update recordsToUpdate; } } global void finish(Database.BatchableContext bc){ if(!checkException && !isEnd && !test.isRunningTest()){ //Call batch again if got any exception on page FetchAccounts callBatchAgain = new FetchAccounts(linkForNextPage,false,store,updated_at_min,updated_at_max); Database.executeBatch(callBatchAgain,1); }else if(checkException && !test.isRunningTest()){ if(String.isNotBlank(linkForNextPage)){ //Call batch again for next page of record pagination FetchAccounts callBatchAgain = new FetchAccounts(linkForNextPage,false,store,updated_at_min,updated_at_max); Database.executeBatch(callBatchAgain,1); } }else{ // Call next batch For Order and Opportunity if(listofConfiguration[0].HIC_ShopifySync__Order__c || listofConfiguration[0].HIC_ShopifySync__Opportunity__c){ if(!test.isRunningTest()) { HIC_ShopifyUtility.fetchOrderAndOpportunity(listOfConfiguration,store,updated_at_min,updated_at_max); } if(CheckAccessibility.isUpsertable('HIC_ShopifySync__AccountContactBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){ if(!listofConfiguration.isEmpty()){ listofConfiguration[0].HIC_ShopifySync__AccountContactBatchCompleted__c = true; } } if(!listofConfiguration.isempty() && listofConfiguration != null ){ try{ update listofConfiguration; }catch(exception e){ } } }else // Call next batch For collection and collects if(listofConfiguration[0].HIC_ShopifySync__Collection__c){ if(!test.isRunningTest()) { HIC_ShopifyUtility.processCollections(listofConfiguration,store,updated_at_min,updated_at_max); } if(CheckAccessibility.isUpsertable('HIC_ShopifySync__AccountContactBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){ if(!listofConfiguration.isEmpty()){ listofConfiguration[0].HIC_ShopifySync__AccountContactBatchCompleted__c = true; } } if(!listofConfiguration.isempty() && listofConfiguration != null ){ try{ update listofConfiguration; }catch(exception e){ } } }else //Call next batch for location inventory Item and level if( listofConfiguration[0].HIC_ShopifySync__Inventory_Location__c){ HIC_ShopifyUtility.fetchLocations(listofConfiguration,store,updated_at_min,updated_at_max); if(CheckAccessibility.isUpsertable('HIC_ShopifySync__AccountContactBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){ if(!listofConfiguration.isEmpty()){ listofConfiguration[0].HIC_ShopifySync__AccountContactBatchCompleted__c = true; } } if(!listofConfiguration.isempty() && listofConfiguration != null ){ try{ update listofConfiguration; }catch(exception e){ } } }else // Call next batch for Draft order if(listofConfiguration[0].HIC_ShopifySync__Draft_Order_Sync__c){ if(!test.isRunningTest()) { HIC_ShopifyUtility.fetchDraftOrders(listofConfiguration,store,updated_at_min,updated_at_max); } if(CheckAccessibility.isUpsertable('HIC_ShopifySync__AccountContactBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){ if(!listofConfiguration.isEmpty()){ listofConfiguration[0].HIC_ShopifySync__AccountContactBatchCompleted__c = true; } } if(!listofConfiguration.isempty() && listofConfiguration != null ){ try{ update listofConfiguration; }catch(exception e){ } } }else{ // IF not available next batch then update the Configuration for track batch updates on page if(CheckAccessibility.isUpsertable('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__OrderBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){ if(!listofConfiguration.isEmpty()){ listofConfiguration[0].HIC_ShopifySync__IsCurrencyChanged__c = false; listofConfiguration[0].HIC_ShopifySync__Batch_Is_Processing__c = false; listofConfiguration[0].HIC_ShopifySync__AccountContactBatchCompleted__c = true; } } if(!listofConfiguration.isempty() && listofConfiguration != null ){ try{ update listofConfiguration; EmailErrorCSV.SuccessMailSend(); }catch(exception e){ } } } } } public static void createLead(String customerResponse, String store){ list listofConfiguration = new list(); String companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey; String querys = 'Select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__DNCDAMissingAccounts__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 LeadFieldsList = new list(); 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 MapofCustomer = (Map) JSON.deserializeUntyped(customerResponse); if(!MapofCustomer.isEmpty() && MapofCustomer.containsKey('orders_count') && Integer.valueOf(MapofCustomer.get('orders_count')) < 1){ if(!MapofCustomer.isEmpty() && MapofCustomer.containskey('default_address')){ Map accMap = (Map)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{'company' => (String)MapofCustomer.get('first_name') + MapofCustomer.get('last_name')}); } } String listType1 = 'List<' + 'Lead' + '>'; list LeadListToupsert = (List)Type.forName(listType1).newInstance(); list updatedLeadFieldsList = new list(); 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 fieldMap1 = objectType1.getDescribe().fields.getMap(); Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c'); if(!Test.isRunningTest()){ try{ EmailErrorCSV.makeCsvAndSendInEmail(customerResponse,'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 listofConfiguration = new list(); String querys = 'Select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__DNCDAMissingAccounts__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 MapofCustomer = (Map) 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 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 ContactFieldsList = new list(); 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__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 MapofCustomer1 = (Map) 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 ContactListToupsert = (List)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 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 accountFieldsList = new list(); 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')+' = \'Account\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999'; accountFieldsList = database.query(query); list updatedAccountFieldsList = new list(); Map MapofCustomer = (Map) JSON.deserializeUntyped(customerResponse); if(!MapofCustomer.isEmpty() && MapofCustomer.containskey('default_address')){ Map accMap = (Map)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{'company' => (String)MapofCustomer.get('first_name') + MapofCustomer.get('last_name')}); } String listType = 'List<' + 'Account' + '>'; list accountListToupsert = (List)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 MapofCustomer1 = (Map) JSON.deserializeUntyped(customerResponse); list ContactFieldsList = new list(); 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 ContactListToupsert = (List)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 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 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 MapofCustomer2 = (Map) JSON.deserializeUntyped(customerResponse); list ContactFieldsList = new list(); 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')+' = \'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 ContactListToupsert = (List)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 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 MapofCustomer = (Map) JSON.deserializeUntyped(customerResponse); list PersonaccountFieldsList = new list([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 PersonaccountListToupsert = (List)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 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'); } } } }