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

3019 lines
205 KiB
OpenEdge ABL

/**
* ─────────────────────────────────────────────────────────────────────────────────────────────────┐
* This class is use for Shopify utility
* 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>
* ──────────────────────────────────────────────────────────────────────────────────────────────────
*/
public with sharing class HIC_ShopifyUtility {
public static integer i = 0;
public static String USER_NAME ; // Shopify's API Key
public static String PASSWORD ; // Shopify's Password
public static String shopifyUrl ; // Shopify's Store URL
public static String store; //Shopify's Store Name
/**************************************HIC_ShopifyUtility*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Class Constructor to set Shopify Details
* Get Shopify Store credentials from custom Object configurationList (HIC_ShopifySync__HIC_Configuration__c)
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public HIC_ShopifyUtility(List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
USER_NAME = configurationList[0].HIC_ShopifySync__API_Key__c;
PASSWORD = configurationList[0].HIC_ShopifySync__Private_Key_Password__c;
shopifyUrl = configurationList[0].HIC_ShopifySync__Shopify_URL__c;
store = configurationList[0].Name;
}
//Wrapper class for field Mapping
public class FieldWrapper{
@AuraEnabled
public String filedlabel{get;set;}
@AuraEnabled
public String filedApiName{get;set;}
@AuraEnabled
public String dataType{get;set;}
}
//Wrapper class for tracking Batch process
public class WrapperforBatchResponse{
public String response;
public String link;
}
/************************************** Batch Process start *************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Collecting all Shopify Store data and upsert into the Salesfroce.
* fetchProducts - BatchToCreateProducts
* fetchCustomer - FetchAccounts
* fetchOrderAndOpportunity - FetchOrders
* processCollections - FetchSmartCollection_Batch
* fetchLocations - FetchLocations_Batch
* fetchDraftOrders - FetchOrders
* ──────────────────────────────────────────────────────────────────────────────────────────────
*/
//Product2
public static void fetchProducts(List<HIC_ShopifySync__HIC_Configuration__c> configurationList,String store){
new HIC_ShopifyUtility(configurationList);
BatchToCreateProducts doInBatch = new BatchToCreateProducts('',false,store);
if(!Test.isRunningTest()){
Database.executeBatch(doInBatch, 1);
}
}
//Accounts and Contact / Person Account
public static void fetchCustomer(List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store){
new HIC_ShopifyUtility(configurationList);
FetchAccounts getAcc = new FetchAccounts('',false,store);
if(!Test.isRunningTest()){
Database.executeBatch(getAcc, 1);
}else{
Database.executeBatch(getAcc);
}
}
//Accounts and Contact / Person Account
public static void fetchCustomer(List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store, String updated_at_min, String updated_at_max){
new HIC_ShopifyUtility(configurationList);
FetchAccounts getAcc = new FetchAccounts('',false,store,updated_at_min,updated_at_max);
if(!Test.isRunningTest()){
Database.executeBatch(getAcc, 1);
}else{
Database.executeBatch(getAcc);
}
}
// Order & Order LineItem / Opportunity & Opportunity LineItem
public static void fetchOrderAndOpportunity(List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store){
new HIC_ShopifyUtility(configurationList);
FetchOrders forOrders = new FetchOrders('',false, true, configurationList, store);
Database.executeBatch(forOrders, 1);
}
// Order & Order LineItem / Opportunity & Opportunity LineItem
public static void fetchOrderAndOpportunity(List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store, String updated_at_min, String updated_at_max){
new HIC_ShopifyUtility(configurationList);
FetchOrders forOrders = new FetchOrders('',false, true, configurationList, store, updated_at_min, updated_at_max);
Database.executeBatch(forOrders, 1);
}
//Smart and Custom Collection and Collects
public static void processCollections(List<HIC_ShopifySync__HIC_Configuration__c > configurationList,String Store){
new HIC_ShopifyUtility(configurationList);
Integer noOfPages = getNoOfRecordsFromShopify('smart_collections', configurationList);
Database.executeBatch(new FetchSmartCollection_Batch('',store),1);
}
//Smart and Custom Collection and Collects
public static void processCollections(List<HIC_ShopifySync__HIC_Configuration__c > configurationList,String Store, String updated_at_min, String updated_at_max){
new HIC_ShopifyUtility(configurationList);
Integer noOfPages = getNoOfRecordsFromShopify('smart_collections', configurationList);
Database.executeBatch(new FetchSmartCollection_Batch('',store, updated_at_min, updated_at_max),1);
}
//Location / Inventory Item / Inventory Level
public static void fetchLocations(List<HIC_ShopifySync__HIC_Configuration__c > configurationList,String store){
new HIC_ShopifyUtility(configurationList);
Integer noOfPages = hic_shopifyUtility.getNoOfRecordsFromShopify('locations', configurationList);
FetchLocations_Batch callBatch = new FetchLocations_Batch(noOfPages,store);
if(!Test.isRunningTest()){
Database.executeBatch(callBatch, 1);
}
}
//Location / Inventory Item / Inventory Level
public static void fetchLocations(List<HIC_ShopifySync__HIC_Configuration__c > configurationList,String store, String updated_at_min, String updated_at_max){
new HIC_ShopifyUtility(configurationList);
//Integer noOfPages = hic_shopifyUtility.getNoOfRecordsFromShopify('locations', configurationList);
FetchLocations_Batch callBatch = new FetchLocations_Batch('',store, updated_at_min, updated_at_max);
if(!Test.isRunningTest()){
Database.executeBatch(callBatch, 1);
}
}
//Draft Order As Salesforce Order with diffrente recordtype
public static void fetchDraftOrders(List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store){
new HIC_ShopifyUtility(configurationList);
FetchOrders forDraftOrders = new FetchOrders('',false, false, configurationList,store);
Database.executeBatch(forDraftOrders, 1);
}
//Draft Order As Salesforce Order with diffrente recordtype
public static void fetchDraftOrders(List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store, String updated_at_min, String updated_at_max){
new HIC_ShopifyUtility(configurationList);
FetchOrders forDraftOrders = new FetchOrders('',false, false, configurationList,store, updated_at_min, updated_at_max);
Database.executeBatch(forDraftOrders, 1);
}
/************************************** Batch Process End *************************************************/
/**************************************fetchAllDataWithLinkForNextPage*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get next page records links - Used for Pagination with Shopify records
* more details: https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> ShopifyidvsAccountid - Map of Shopify's External Id Vs Accout's Shopify's ID
* @param String ObjectName - Shopify Entity's Name
* @param Boolean isPersonAccount - Identify records its person account or not
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static String fetchAllDataWithLinkForNextPage(String shopifyUrlWithId, List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
new HIC_ShopifyUtility(configurationList);
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String endPointValue = shopifyUrl + '/admin/'+shopifyUrlWithId;
req.setEndpoint(endPointValue);
req.setClientCertificateName('Shopify');
/*Blob headerValue = Blob.valueOf(USER_NAME + ':' + PASSWORD);
String authorizationHeader = 'Basic ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);*/
req.setHeader('X-Shopify-Access-Token', PASSWORD);
req.setHeader('content-type', 'application/json');
req.setMethod('GET');
req.setTimeout(120000);
try {
HttpResponse res ;
res = h.send(req);
responseBody = res.getBody();
if(res.getStatusCode() == 200){
WrapperforBatchResponse rs = new WrapperforBatchResponse();
rs.response = responseBody;
if(String.isNotBlank(res.getHeader('link'))){
rs.link = getPageInfo(res.getHeader('link'));
}else{
rs.link = null;
}
return JSON.serialize(rs);
}
}catch(Exception e){
return null;
}
return null;
}
/**************************************deleteSmartCollectionRules*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Deleting old collections rules when update collections or its rules
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param set<String> CollectionID - Set of Collection Shopify External ID
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void deleteSmartCollectionRules(set<String> CollectionID){
list<HIC_ShopifySync__Rules__c> listOfRules = new list<HIC_ShopifySync__Rules__c>();
listOfRules = [select id from HIC_ShopifySync__Rules__c where HIC_ShopifySync__Collection__r.HIC_ShopifySync__Shopify_Id__c IN : CollectionID ];
if(!listOfRules.isEmpty() && listOfRules != null && Schema.getGlobalDescribe().get('HIC_ShopifySync__Rules__c').getDescribe().isDeletable()){
delete listOfRules ;
}
}
/**************************************insertSmartCollectionRules*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for usert Smart Collection rules whenwever its update or insert in Shopify
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> CollectionIdVsRulesResponse - Map of Collection Shopify External ID Vs Rule JSON Response
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void insertSmartCollectionRules(Map<String,String> CollectionIdVsRulesResponse){
list<HIC_ShopifySync__Rules__c> listOfRules = new list<HIC_ShopifySync__Rules__c>();
String sObjectName = 'HIC_ShopifySync__Collection__c'.trim();
sObjectType schemaType = Schema.getGlobalDescribe().get(sObjectName) ;
Map<String, SObjectField> fieldsMap = schemaType.getDescribe().fields.getMap();
for(String CollectionID : CollectionIdVsRulesResponse.keySet()){
list<Object> allRules = (list<Object>) JSON.deserializeUntyped(CollectionIdVsRulesResponse.get(CollectionID));
for(Object rule : allRules){
map<string,object> ruleMap = (map<string,object>) rule;
if(!ruleMap.isEmpty() && ruleMap.containsKey('condition') && ruleMap.containsKey('relation') && ruleMap.containsKey('column')
&& Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Relation__c.isUpdateable() && Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Relation__c.isCreateable() && CheckAccessibility.isUpdateable('HIC_ShopifySync__Relation__c','HIC_ShopifySync__Rules__c' )
&& Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Condition__c.isUpdateable() && Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Condition__c.isCreateable() && CheckAccessibility.isUpdateable('HIC_ShopifySync__Condition__c','HIC_ShopifySync__Rules__c' )
&& Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Column__c.isUpdateable() && Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Column__c.isCreateable() && CheckAccessibility.isUpdateable('HIC_ShopifySync__Column__c','HIC_ShopifySync__Rules__c' )
&& Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Collection__c.isUpdateable() && Schema.sObjectType.HIC_ShopifySync__Rules__c.fields.HIC_ShopifySync__Collection__c.isCreateable() && CheckAccessibility.isUpdateable('HIC_ShopifySync__Collection__c','HIC_ShopifySync__Rules__c' )
){
HIC_ShopifySync__Rules__c RuleObj = new HIC_ShopifySync__Rules__c();
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__Shopify_Id__c',fieldsMap)){
HIC_ShopifySync__Collection__c collection = new HIC_ShopifySync__Collection__c();
collection.HIC_ShopifySync__Shopify_Id__c = CollectionID;
RuleObj.HIC_ShopifySync__Collection__r = collection;
}
RuleObj.HIC_ShopifySync__Column__c = String.valueOf(ruleMap.get('column'));
RuleObj.HIC_ShopifySync__Condition__c = String.valueOf(ruleMap.get('condition'));
RuleObj.HIC_ShopifySync__Relation__c = String.valueOf(ruleMap.get('relation'));
listOfRules.add(RuleObj);
}
}
}
if(!listOfRules.isEmpty() && listOfRules != null){
if(Schema.getGlobalDescribe().get('HIC_ShopifySync__Rules__c').getDescribe().isCreateable() && Schema.getGlobalDescribe().get('HIC_ShopifySync__Rules__c').getDescribe().isUpdateable())
Insert listOfRules;
}
}
/**************************************getPageInfo*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for split the next page details for Shopify Pagination
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> fulllink - Complete URL for next page records details (Pagination)
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static string getPageInfo(String fulllink){
String finalLink = null;
System.debug('fulllink--'+fulllink);
list<String> listofrels = fulllink.split(',');
if(!listofrels.isEmpty() && listofrels.size() == 2){
list<String> listofLinkandRel = listofrels[1].split(';');
if(!listofLinkandRel.isEmpty() && listofLinkandRel[1].trim().equalsIgnoreCase('rel="next"')){
finalLink = listofLinkandRel[0].remove('<').remove('>').trim().split('page_info=')[1];
}else if(!listofLinkandRel.isEmpty()){
listofLinkandRel = listofrels[0].split(';');
if(listofLinkandRel[1].trim().equalsIgnoreCase('rel="next"')){
finalLink = listofLinkandRel[0].remove('<').remove('>').trim().split('page_info=')[1];
}
}
}else if(!listofrels.isEmpty() && listofrels.size() == 1){
list<String> listofLinkandRel = listofrels[0].split(';');
if(!listofLinkandRel.isEmpty() && listofLinkandRel[1].trim().equalsIgnoreCase('rel="next"')){
finalLink = listofLinkandRel[0].remove('<').remove('>').trim().split('page_info=')[1];
}
}
return finalLink;
}
/**************************************getPageInfo*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for get Shopify's fields which includes in collout response(JSON)
*
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> ObjectName - Pass the Shopify Entity's name (Object name)
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static string getShopifyFields(String ObjectName){
List<HIC_ShopifySync__Shopify_Fields__c> shopifyAccountFieldSet = new List<HIC_ShopifySync__Shopify_Fields__c>();
List<HIC_ShopifySync__Shopify_Fields__c> shopifyAccountFieldSet2 = new List<HIC_ShopifySync__Shopify_Fields__c>();
String FieldsToQueryforShopifyFields = 'Name,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__UI_Label_Name__c,HIC_ShopifySync__Field_Name__c,HIC_ShopifySync__Data_Type__c,HIC_ShopifySync__Nested__c';
shopifyAccountFieldSet = database.query( 'select '+Checkaccessibility.isAccessible(FieldsToQueryforShopifyFields,'HIC_ShopifySync__Shopify_Fields__c')+' from HIC_ShopifySync__Shopify_Fields__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__Shopify_Fields__c')+' = \'' +ObjectName+ '\' and '+Checkaccessibility.isAccessible('HIC_ShopifySync__Data_Type__c','HIC_ShopifySync__Shopify_Fields__c')+' != \'Reference\' LIMIT 49999');
for(HIC_ShopifySync__Shopify_Fields__c fm : shopifyAccountFieldSet){
system.debug('fm'+fm);
if(fm.HIC_ShopifySync__Nested__c != null){
if(fm.HIC_ShopifySync__Field_Name__c.contains(',')){
string temp = '';
for(string sf : fm.HIC_ShopifySync__Field_Name__c.split(',')){
if(temp == ''){
temp += fm.HIC_ShopifySync__Nested__c+'.'+sf;
}else{
temp += ','+fm.HIC_ShopifySync__Nested__c+'.'+sf;
}
}
fm.HIC_ShopifySync__UI_Label_Name__c = temp;//+' ('+fm.HIC_ShopifySync__Data_Type__c+')';
shopifyAccountFieldSet2.add(fm);
}else{
fm.HIC_ShopifySync__UI_Label_Name__c = fm.HIC_ShopifySync__Nested__c+'.'+fm.HIC_ShopifySync__Field_Name__c;//;+' ('+fm.HIC_ShopifySync__Data_Type__c+')';
shopifyAccountFieldSet2.add(fm);
}
}else{
fm.HIC_ShopifySync__UI_Label_Name__c = fm.HIC_ShopifySync__Field_Name__c;//+' ('+fm.HIC_ShopifySync__Data_Type__c+')';
shopifyAccountFieldSet2.add(fm);
}
}
if(shopifyAccountFieldSet2 != null && !shopifyAccountFieldSet2.isEmpty() ){
return JSON.serialize( shopifyAccountFieldSet2 );
}else{
return 'Null';
}
}
/**************************************getDefaultFieldMapping*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get Default fieldmapping from the Configuration Object
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param String ObjecetName
* @param String isPersonAccount
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/ //Deprecated
public static string getDefaultFieldMapping(String ObjecetName, boolean isPersonAccount){
List<HIC_ShopifySync__Field_Mapping__c> fm = new List<HIC_ShopifySync__Field_Mapping__c>();
List<HIC_ShopifySync__Field_Mapping__c> listofupdatedAccountFieldMapping = new List<HIC_ShopifySync__Field_Mapping__c>();
if(isPersonAccount ){
fm = [select id,HIC_ShopifySync__GQL_Field_API__c,name,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__SF_Field_Type__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__Nested__c from HIC_ShopifySync__Field_Mapping__c where (HIC_ShopifySync__Object_Name__c =: ObjecetName or HIC_ShopifySync__Object_Name__c = 'PersonAccount' ) and HIC_ShopifySync__SF_Field__c != 'name' and HIC_ShopifySync__SF_Field__c != 'Account-RecordTypeId' and HIC_ShopifySync__SF_Field__c != 'PersonAccount-company' and HIC_ShopifySync__Shopify_Field_Type__c != 'Reference' order by HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Fields__c asc limit 49999];
}else{
fm = [select id,HIC_ShopifySync__GQL_Field_API__c,name,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__SF_Field_Type__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__Nested__c from HIC_ShopifySync__Field_Mapping__c where HIC_ShopifySync__Object_Name__c =: ObjecetName and HIC_ShopifySync__Shopify_Field_Type__c != 'Reference' order by HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Fields__c asc limit 49999];
}
Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
Map<Id,Schema.RecordTypeInfo> rtMapById = d.getRecordTypeInfosById();
for(HIC_ShopifySync__Field_Mapping__c fmm : fm){
/*if(fmm.HIC_ShopifySync__SF_Field__c != null && fmm.HIC_ShopifySync__SF_Field__c != '' && fmm.HIC_ShopifySync__SF_Field__c == 'RecordTypeId'){
fmm.HIC_ShopifySync__SF_Field__c = 'Record Type Name';
Schema.RecordTypeInfo rtById = rtMapById.get(fmm.HIC_ShopifySync__Shopify_Fields__c);
if(rtById != null){
fmm.HIC_ShopifySync__Shopify_Fields__c = rtById.getName() ;
}else{
fmm.HIC_ShopifySync__Shopify_Fields__c = '';
}
}
if(fmm.HIC_ShopifySync__SF_Field__c != null && fmm.HIC_ShopifySync__SF_Field__c != '' ){
if(ObjecetName.equalsIgnoreCase('DraftOrder')){
ObjecetName = 'order';
}
if(ObjecetName.equalsIgnoreCase('DraftOrderItem')){
ObjecetName = 'OrderItem';
}
if(AddDeleteCOntroller.CheckingFieldExisting((fmm.HIC_ShopifySync__SF_Field__c).toLowerCase().trim(),ObjecetName.toLowerCase())){
listofupdatedAccountFieldMapping.add(fmm);
}
}*/
}
if(listofupdatedAccountFieldMapping != null && !listofupdatedAccountFieldMapping.isEmpty()){
return JSON.serialize(listofupdatedAccountFieldMapping);
}
else{
return 'Null';
}
}
public static string getDefaultFieldMapping(String ObjecetName, boolean isPersonAccount, String store){
List<HIC_ShopifySync__HIC_Field_Mapping__c> fm = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
List<HIC_ShopifySync__HIC_Field_Mapping__c> listofupdatedAccountFieldMapping = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
if(isPersonAccount ){
fm = [select id,name,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__SF_Field_Type__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__Nested__c from HIC_ShopifySync__HIC_Field_Mapping__c where (HIC_ShopifySync__Object_Name__c =: ObjecetName or HIC_ShopifySync__Object_Name__c = 'PersonAccount' ) and HIC_ShopifySync__SF_Field__c != 'name' and HIC_ShopifySync__SF_Field__c != 'Account-RecordTypeId' and HIC_ShopifySync__SF_Field__c != 'PersonAccount-company' and HIC_ShopifySync__Shopify_Field_Type__c != 'Reference' AND HIC_ShopifySync__Object_Mapping__c = null AND HIC_ShopifySync__Store__c =: store order by HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Fields__c asc limit 49999];
}else{
fm = [select id,name,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__SF_Field_Type__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__Nested__c from HIC_ShopifySync__HIC_Field_Mapping__c where HIC_ShopifySync__Object_Name__c =: ObjecetName and HIC_ShopifySync__Shopify_Field_Type__c != 'Reference' AND HIC_ShopifySync__Object_Mapping__c = null and HIC_ShopifySync__Store__c =: store order by HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Fields__c asc limit 49999];
}
if(fm.isEmpty()){
store = 'Default';
if(isPersonAccount ){
fm = [select id,name,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__SF_Field_Type__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__Nested__c from HIC_ShopifySync__HIC_Field_Mapping__c where (HIC_ShopifySync__Object_Name__c =: ObjecetName or HIC_ShopifySync__Object_Name__c = 'PersonAccount' ) and HIC_ShopifySync__SF_Field__c != 'name' and HIC_ShopifySync__SF_Field__c != 'Account-RecordTypeId' and HIC_ShopifySync__SF_Field__c != 'PersonAccount-company' and HIC_ShopifySync__Shopify_Field_Type__c != 'Reference' AND HIC_ShopifySync__Object_Mapping__c = null and HIC_ShopifySync__Store__c =: store order by HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Fields__c asc limit 49999];
}else{
fm = [select id,name,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__SF_Field_Type__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__Nested__c from HIC_ShopifySync__HIC_Field_Mapping__c where HIC_ShopifySync__Object_Name__c =: ObjecetName and HIC_ShopifySync__Shopify_Field_Type__c != 'Reference' AND HIC_ShopifySync__Object_Mapping__c = null and HIC_ShopifySync__Store__c =: store order by HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Fields__c asc limit 49999];
}
}
Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
Map<Id,Schema.RecordTypeInfo> rtMapById = d.getRecordTypeInfosById();
for(HIC_ShopifySync__HIC_Field_Mapping__c fmm : fm){
if(fmm.HIC_ShopifySync__SF_Field__c != null && fmm.HIC_ShopifySync__SF_Field__c != '' && fmm.HIC_ShopifySync__SF_Field__c == 'RecordTypeId'){
fmm.HIC_ShopifySync__SF_Field__c = 'Record Type Name';
Schema.RecordTypeInfo rtById = rtMapById.get(fmm.HIC_ShopifySync__Shopify_Fields__c);
if(rtById != null){
fmm.HIC_ShopifySync__Shopify_Fields__c = rtById.getName() ;
}else{
fmm.HIC_ShopifySync__Shopify_Fields__c = '';
}
}
if(fmm.HIC_ShopifySync__SF_Field__c != null && fmm.HIC_ShopifySync__SF_Field__c != '' ){
if(ObjecetName.equalsIgnoreCase('DraftOrder')){
ObjecetName = 'order';
}
if(ObjecetName.equalsIgnoreCase('DraftOrderItem')){
ObjecetName = 'OrderItem';
}
if(AddDeleteCOntroller.CheckingFieldExisting((fmm.HIC_ShopifySync__SF_Field__c).toLowerCase().trim(),ObjecetName.toLowerCase())){
listofupdatedAccountFieldMapping.add(fmm);
}
}
}
if(listofupdatedAccountFieldMapping != null && !listofupdatedAccountFieldMapping.isEmpty()){
return JSON.serialize(listofupdatedAccountFieldMapping);
}
else{
return 'Null';
}
}
/**************************************fetchAllData*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get Default fieldmapping from the Configuration Object
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param String objectType - Shopify Entity's Name (Object's name)
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static String fetchAllData(String objectType, List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
new HIC_ShopifyUtility(configurationList);
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String endPointValue = shopifyUrl + '/admin/'+objectType;//+'.json';
String queryParam = '';
req.setEndpoint(endPointValue);
//Adding certificate to HTTP Requests
req.setClientCertificateName('Shopify');
/*Blob headerValue = Blob.valueOf(USER_NAME + ':' + PASSWORD);
String authorizationHeader = 'Basic ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);*/
req.setHeader('X-Shopify-Access-Token', PASSWORD);
req.setHeader('content-type', 'application/json');
//Use get Method as we are retrieving data from shopify
req.setMethod('GET');
req.setTimeout(120000);
try {
HttpResponse res ;
// if(!Test.isRunningTest()){
res = h.send(req);
responseBody = res.getBody();
if(res.getStatusCode() == 200){
return responseBody;
}
}catch(Exception e){
}
return null;
}
/**************************************getNoOfRecordsFromShopify*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get count of Shopify records in Shopofy platform
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param String objectType - Shopify Entity's Name (Object's name)
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Integer getNoOfRecordsFromShopify(String objectType, List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
new HIC_ShopifyUtility(configurationList);
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String endPointValue;
if (objectType != 'orders'){
endPointValue = shopifyUrl + '/admin/'+objectType+'/count.json';
}
else{
endPointValue = shopifyUrl + '/admin/'+objectType+'/count.json?status=any';
}
String queryParam = '';
req.setEndpoint(endPointValue);
//Adding certificate to HTTP Requests
req.setClientCertificateName('Shopify');
/*Blob headerValue = Blob.valueOf(USER_NAME + ':' + PASSWORD);
String authorizationHeader = 'Basic ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);*/
req.setHeader('X-Shopify-Access-Token', PASSWORD);
req.setHeader('content-type', 'application/json');
//Use get Method as we are retrieving data from shopify
req.setMethod('GET');
req.setTimeout(120000);
try {
HttpResponse res ;
if(!Test.isRunningTest()){
res = h.send(req);
responseBody = res.getBody();
}
else{
responseBody = '{"count":66}';
}
if(Test.isRunningTest() || res.getStatusCode() == 200 ){
Map<String, Object> countSize = (Map<String, Object>)JSON.deserializeUntyped(responseBody);
Integer intCountSize = Integer.valueOf(countSize.get('count'));
if(intCountSize > 50){
decimal noOfPages = intCountSize/50.0;
if(String.ValueOf(noOfPages).Contains('.')){
List <String> splittedCount = String.valueOf(noOfPages).split('\\.');
if(Integer.valueOf(splittedCount[1]) > 0){
Integer newCountSize = Integer.valueOf(splittedCount[0]) + 1;
return newCountSize;
}
}else{
return Integer.valueOf(noOfPages);
}
}else{
return 1;
}
}
}catch(Exception e){
}
return null;
}
/**************************************fetchAllDataUsingId*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for collouts in shopify with record's Id
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param String shopifyUrlWithId - PostFix Value of EndPoint URL
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static String fetchAllDataUsingId(String shopifyUrlWithId, List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
new HIC_ShopifyUtility(configurationList);
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String endPointValue = shopifyUrl + '/admin/'+shopifyUrlWithId;
String queryParam = '';
req.setEndpoint(endPointValue);
//Adding certificate to HTTP Requests
req.setClientCertificateName('Shopify');
/*Blob headerValue = Blob.valueOf(USER_NAME + ':' + PASSWORD);
String authorizationHeader = 'Basic ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);*/
req.setHeader('X-Shopify-Access-Token', PASSWORD);
req.setHeader('content-type', 'application/json');
//Use get Method as we are retrieving data from shopify
req.setMethod('GET');
req.setTimeout(120000);
try {
HttpResponse res ;
res = h.send(req);
responseBody = res.getBody();
if(res.getStatusCode() == 200){
return responseBody;
}
}catch(Exception e){
}
return null;
}
/**************************************upsertSobjectList*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for upsert Records in Salesforce Dynamically
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param String singleJSONobj - Shopify Record JSON Respons
* @param List<sobject> sObjectList - List Of Record with field Mapping
* @param String sObjectName - Shopify's Entity Name (Object's Name)
* @param String externalFieldName - Field Name which includes in CSV body while sending mail to the user
* @param List<sobject> sObjectList - ListofConfigurationSettings
* @param Boolean IsWebhook - Identify records its process for webhook record or Batch records
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void upsertSobjectList(String singleJSONobj,List<sobject> sObjectList, String sObjectName, String externalFieldName, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, Boolean IsWebhook, String store){
new HIC_ShopifyUtility(configurationList);
if(sObjectList.Isempty()) return;
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(sObjectName);
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theField = fieldMap.get(externalFieldName);
system.debug('theField-->'+theField);
if(!sObjectList.isEmpty()){
EmailErrorCSV.makeCsvAndSendInEmail(singleJSONobj,sObjectName,sObjectList,theField,IsWebhook,store);
}
}
/**************************************processSobjectList*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for upsert Records in Salesforce Dynamically
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<HIC_ShopifySync__HIC_Field_Mapping__c> FieldsList - Pass Shopify's Entity Field Mapping from the Object HIC_ShopifySync__HIC_Field_Mapping__c
* @param List<sobject> sObjectList - List Of Record with field Mapping
* @param String sObjectName - Shopify's Entity Name (Object's Name)
* @param String externalFieldName - Field Name which includes in CSV body while sending mail to the user
* @param List<sobject> sObjectList - ListofConfigurationSettings
* @param Boolean IsWebhook - Identify records its process for webhook record or Batch records
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void processSobjectList(List<HIC_ShopifySync__HIC_Field_Mapping__c> FieldsList,List<Object> objectList,String sObjectName, String externalFieldName, List<HIC_ShopifySync__HIC_Configuration__c > configurationList,Boolean IsWebhook, String store){
new HIC_ShopifyUtility(configurationList);
List<sobject> sobjectList = fillObjectValues(FieldsList, sObjectName, objectList, configurationList);
if(sobjectList.Isempty()) return;
upsertSobjectList(JSON.serialize(objectList),sobjectList,sObjectName,externalFieldName, configurationList,IsWebhook,store);
}
/**************************************insertOrderfulfillments*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for upsert Orderfulfillment Records in Salesforce
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<sobject> objectList - List Of Record with field Mapping
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* @param Boolean IsWebhook - Identify records its process for webhook record or Batch records
* @param Boolean store - Shopify's Store name
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void insertOrderfulfillments(List<Object> objectList, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, boolean IsWebhook, String store){
new HIC_ShopifyUtility(configurationList);
Map<String, Object> oProdMap = new Map<String, Object>();
List<Object> listOfAllfullfillmentOrderitem = new List<Object>();
List<Object> orderfulfillmentproductList = new List<Object>();
List<Object> listOfAllfullfillmentOrder = new List<Object>();
List<Object> orderFulfillmentsList = new List<Object>();
List<HIC_ShopifySync__HIC_Field_Mapping__c> orderfulfillmentFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>([Select HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c from HIC_ShopifySync__HIC_Field_Mapping__c Where HIC_ShopifySync__Object_Name__c = 'HIC_ShopifySync__Order_Fulfillment__c' AND HIC_ShopifySync__Store__c =: store]);
List<HIC_ShopifySync__HIC_Field_Mapping__c> orderfulfillmentitemFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>([Select HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c from HIC_ShopifySync__HIC_Field_Mapping__c Where HIC_ShopifySync__Object_Name__c = 'HIC_ShopifySync__Order_Fulfillment_Item__c' AND HIC_ShopifySync__Store__c =: store]);
for(Object ordobjforfulfillment : objectList ){
Map<String, Object> orderproductMap = (Map<String, Object>)ordobjforfulfillment;
if(orderproductMap != null && !orderproductMap.isEmpty() && orderproductMap.containskey('fulfillments') ){
orderFulfillmentsList = (List<Object>)orderproductMap.get('fulfillments');
listOfAllfullfillmentOrder.addall(orderFulfillmentsList);
}
}
try{
if(!listOfAllfullfillmentOrder.isEmpty() && !orderfulfillmentFieldsList.isEmpty()){
processSobjectList(orderfulfillmentFieldsList,listOfAllfullfillmentOrder,'HIC_ShopifySync__Order_Fulfillment__c', 'HIC_ShopifySync__Shopify_Id__c', configurationList,IsWebhook,store);
}
}catch(Exception e){
system.debug('For OrderFulfillment '+ e.getMessage() + 'at line '+e.getLineNumber());
}
if(orderFulfillmentsList != null && !orderFulfillmentsList.isEmpty()){
for(Object orderfulfillmentitem : orderFulfillmentsList){
Map<String, Object> orderfulfillmentitemMap = (Map<String, Object>)orderfulfillmentitem;
if(orderfulfillmentitemMap != null && !orderfulfillmentitemMap.isEmpty() && orderfulfillmentitemMap.containskey('line_items')){
orderfulfillmentproductList = (List<Object>)orderfulfillmentitemMap.get('line_items');
for(Object orderfuilmentitem : orderfulfillmentproductList){
oProdMap = (Map<String, Object>)orderfuilmentitem;
oProdMap.put('orderfulfillmentId',String.valueOf(orderfulfillmentitemMap.get('id')));
oProdmap.put('id', string.valueOf(orderfulfillmentItemmap.get('id'))+oProdmap.get('id'));
orderfuilmentitem = (Object)oProdMap;
}
listOfAllfullfillmentOrderitem.addAll(orderfulfillmentproductList);
}
}
}
try{
if(!listOfAllfullfillmentOrder.isEmpty() && !orderfulfillmentFieldsList.isEmpty()){
processSobjectList(orderfulfillmentitemFieldsList,listOfAllfullfillmentOrderitem,'HIC_ShopifySync__Order_Fulfillment_Item__c', 'HIC_ShopifySync__Shopify_Id__c', configurationList,IsWebhook,store);
}
}catch(Exception e){
system.debug('For OrderFulfillment '+ e.getMessage() + 'at line '+e.getLineNumber());
}
}
/**************************************initailizeProductandVaraint*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Insert Default ProductandVaraint in Salesforce.
* Whenever Shopify's ProductandVaraint is not found in Shopify and records are in Salesforce and its required on records
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<Object > lineItems - ListoflineItems
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void initializeProductandVaraint(List<Object> lineItems){
Set<String> shProductIdSet = new Set<String>();
Set<String> shVariantIdSet = new Set<String>();
Map<String,String> shProductMap = new Map<String,String>();
Map<String,String> shVariantMap = new Map<String,String>();
for(Object line : lineItems){
map<string,object> lineMap = (map<string,object>) line;
if(lineMap.get('product_id') != null){
shProductIdSet.add(string.valueof(lineMap.get('product_id')));
System.debug('shProductIdSet-->'+shProductIdSet);
}
if(lineMap.get('variant_id') != null){// || ordproduct.Product2Id == 'null'
shVariantIdSet.add(string.valueof(lineMap.get('variant_id')));
System.debug('shVariantIdSet-->'+shVariantIdSet);
}
}
System.debug('lineItems-->'+lineItems);
for(Product2 pro : [Select HIC_ShopifySync__Shopify_Id__c,Name from Product2 where HIC_ShopifySync__Shopify_Id__c IN :shProductIdSet ]){
System.debug('pro-->'+pro);
shProductMap.put(pro.HIC_ShopifySync__Shopify_Id__c, pro.Name);
System.debug('shProductMap-->'+shProductMap);
}
List<Product2> productListToCreate = new List<Product2>();
for(String shProductId : shProductIdSet){
System.debug('shProductId-->'+shProductId);
if(shProductMap.isEmpty() || !shProductMap.containsKey(shProductId)){
System.debug('shProductMap-->'+shProductMap);
Product2 product = new Product2();
product.Name = 'Does not exist in Shopify anymore';
product.HIC_ShopifySync__Shopify_Id__c = shProductId;
productListToCreate.add(product);
System.debug('productListToCreate-->'+productListToCreate);
}
}
if(!productListToCreate.isEmpty())
insert productListToCreate;
System.debug('productListToCreate-->'+productListToCreate);
for(HIC_ShopifySync__Variant__c vari : [Select HIC_ShopifySync__Shopify_Id__c,Name from HIC_ShopifySync__Variant__c where HIC_ShopifySync__Shopify_Id__c IN :shVariantIdSet ]){
if(vari != null){
shVariantMap.put(vari.HIC_ShopifySync__Shopify_Id__c, vari.Name);
}
System.debug('shVariantMap-->'+shVariantMap);
}
List<HIC_ShopifySync__Variant__c> variantListToCreate = new List<HIC_ShopifySync__Variant__c>();
for(String shVariantId : shVariantIdSet){
System.debug('shVariantId-->'+shVariantId);
if(shVariantMap.isEmpty() || !shVariantMap.containsKey(shVariantId)){
HIC_ShopifySync__Variant__c variant = new HIC_ShopifySync__Variant__c();
variant.Name = 'Does not exist in Shopify anymore';
variant.HIC_ShopifySync__Shopify_Id__c = shVariantId;
variantListToCreate.add(variant);
System.debug('variantListToCreate-->'+variantListToCreate);
}
}
if(!variantListToCreate.isEmpty())
insert variantListToCreate;
System.debug('variantListToCreate-->'+variantListToCreate);
}
/**************************************InitializeAccount*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Insert Default Account in Salesforce.
* Whenever Shopify's Account is not found in Salesforce and its required on records
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> ShopifyidvsAccountid - Map of Shopify's External Id Vs Accout's Shopify's ID
* @param String ObjectName - Shopify Entity's Name
* @param Boolean isPersonAccount - Identify records its person account or not
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void InitializeAccount (Map<String,Object> ShopifyidvsCustomersBody, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store){
try{
String ObjectName = 'Account';
new HIC_ShopifyUtility(configurationList);
//Map<String,String> ShopifyidvsObjectidPresent = new Map<String,String>(ShopifyidvsAccountid);
Set<String> SetofShopifyId = ShopifyidvsCustomersBody.keyset();
String query = 'select id, HIC_ShopifySync__Shopify_id__c from ' + ObjectName + ' where HIC_ShopifySync__Shopify_id__c IN: SetofShopifyId ';
Type typLstSObject = Type.forName('List<'+ObjectName+'>');
List<SObject> sObjectListToSearch = (List<SObject>)typLstSObject.newInstance();
sObjectListToSearch = Database.query(query);
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(ObjectName);
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theFieldShopif = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
Schema.SobjectField theFieldId = fieldMap.get('id');
for(SObject obj :sObjectListToSearch){
//ShopifyidvsObjectidPresent.put((String)obj.get('HIC_ShopifySync__Shopify_Id__c'),(String)obj.get('Id'));
ShopifyidvsCustomersBody.remove((String)obj.get('HIC_ShopifySync__Shopify_Id__c'));
}
if(!ShopifyidvsCustomersBody.isEmpty()){
updateCustomer(ShopifyidvsCustomersBody.values(), configurationList, store);
}
}catch(Exception e){
// CustomSettingRecordInsert.SuccessMailSend('Error message from shopifyUtility '+e.getMessage() + ' at line number ' + e.getLineNumber());
}
}
public static void updateCustomer(List<Object> scope, List<HIC_ShopifySync__HIC_Configuration__c > listofConfiguration, String store){
Integer count = 0;
String JSONsingleobj;
for(Object obj : scope){
JSONsingleobj = JSON.serialize(obj);
}
for(Object customerObj : scope){
Map<String,Object> customerMap = (Map<String,Object>)customerObj;
customerMap.put('Accountid',String.valueof(customerMap.get('id')));
system.debug('customerMap--->>> '+customerMap);
if(!customerMap.isEmpty() && customerMap.containskey('default_address')){
Map<String,Object> accMap = (Map<String,Object>)customerMap.get('default_address');
if(!accMap.isEmpty() && accMap.containsKey('company') && (accMap.get('company') == null || accMap.get('company') == '' || accMap.get('company') == 'null')){
/*if(accMap.get('first_name') != null || accMap.get('last_name') != null)
accMap.put('company', accMap.get('first_name')+' '+ accMap.get('last_name'));
else
accMap.put('company', customerMap.get('first_name')+' '+ customerMap.get('last_name'));
customerMap.put('default_address', accMap);
//Update On 18/102023
// --------------------------------------------------------- Start
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)customerMap.get('first_name')) ? '' : (String)customerMap.get('first_name')) +
(String.isBlank((String)customerMap.get('last_name')) ? '' : ' ' + (String)customerMap.get('last_name'))
);
}*/
String FirstName = (accMap.get('first_name') != null ? ''+accMap.get('first_name') : '') ;
String LastName = (accMap.get('last_name') != null ? ''+accMap.get('last_name') : '');
String DefaultFirst = (customerMap.get('first_name') != null ? ''+customerMap.get('first_name') : '');
String DefaultLast = (customerMap.get('last_name') != null ? ''+customerMap.get('last_name') : '');
String fullName = (String.isNotBlank(FirstName) ? FirstName : '') + (String.isNotBlank(LastName) ? ' ' + LastName : '');
String defaultFullName = (String.isNotBlank(DefaultFirst) ? DefaultFirst + ' ' : '') + (String.isNotBlank(DefaultLast) ? DefaultLast : '');
String finalFullName = String.isNotBlank(fullName) ? fullName.trim() : defaultFullName.trim();
System.debug(finalFullName);
accMap.put('company', finalFullName);
customerMap.put('default_address', accMap);
// --------------------------------------------------------- End
}
}else if((customerMap.containsKey('first_name') && customerMap.get('first_name') != null) || (customerMap.containsKey('last_name') && customerMap.get('last_name') != null)){
customerMap.put('default_address', new Map<String, Object>{'company' => (String)customerMap.get('first_name') + customerMap.get('last_name')});
}
customerObj = (Object)customerMap;
}
//If Account And Contact True Only
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 = '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);
if(!accountFieldsList.isEmpty() && !scope.isEmpty()){
if(!Test.isRunningTest()){
HIC_ShopifyUtility.processSobjectList(accountFieldsList,scope,'Account','HIC_ShopifySync__Shopify_Id__c',listOfConfiguration,false,store);
}
}
List<HIC_ShopifySync__HIC_Field_Mapping__c> contactFieldsList = 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 from HIC_ShopifySync__HIC_Field_Mapping__c Where HIC_ShopifySync__Object_Name__c = 'Contact' AND HIC_ShopifySync__Store__c =: store]);
try{
if(!contactFieldsList.isEmpty() && !scope.isEmpty()){
HIC_ShopifyUtility.processSobjectList(contactFieldsList,scope,'Contact','HIC_ShopifySync__Shopify_Id__c',listOfConfiguration,false,store);
}
}catch(Exception e){
}
}else
//IF Account & Contact and Defuault Account Ture Only
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 ){
String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__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';
List<HIC_ShopifySync__HIC_Field_Mapping__c> contactFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
contactFieldsList = Database.query(query);
for(Object customerObj : scope){
Map<String,Object> customerMap = (Map<String,Object>)customerObj;
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' ) || Test.isRunningTest() ){
if(listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(customerMap.get('id'))).contains('Person ')){
customerMap.put('id','Person '+String.valueof(customerMap.get('id')));
}
}else if(!listofConfiguration[0].HIC_ShopifySync__Person_Account__c){
if(!(String.valueOf(customerMap.get('id'))).contains('Business ')){
customerMap.put('id','Business '+String.valueof(customerMap.get('id')));
}
}
}else{
if(!(String.valueOf(customerMap.get('id'))).contains('Business '))
customerMap.put('id','Business '+String.valueof(customerMap.get('id')));
}
customerObj = (Object)customerMap;
system.debug('mapid-->'+customerMap.get('id'));
}
for(Object customerObj : scope){
Map<String,Object> customerMap = (Map<String,Object>)customerObj;
system.debug('mapid2-->'+customerMap.get('id'));
}
try{
if(!contactFieldsList.isEmpty() && !scope.isEmpty()){
HIC_ShopifyUtility.processSobjectList(contactFieldsList,scope,'Contact','HIC_ShopifySync__Shopify_Id__c',listOfConfiguration,false,store);
}
}catch(Exception e){
system.debug('exception at line no '+e.getLineNumber()+' error '+e.getMessage());
}
}else
//IF Person Account True And Default Account is False
if(!listofConfiguration.isEmpty() && listofConfiguration[0].HIC_ShopifySync__Person_Account__c == true && 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 = '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__Object_name__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\' OR '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'PersonAccount\' ) And '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' != \'name\' AND '+CheckAccessibility.isAccessible('Name','HIC_ShopifySync__HIC_Field_Mapping__c')+' != \'Account-RecordTypeId\'AND '+CheckAccessibility.isAccessible('Name','HIC_ShopifySync__HIC_Field_Mapping__c')+' != \'PersonAccount-company\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999' ;
accountFieldsList = Database.query(query);
for(Object customerObj : scope){
Map<String,Object> customerMap = (Map<String,Object>)customerObj;
if(customerMap.get('last_name') == null || customerMap.get('last_name') == ''){
customerMap.put('last_name','REQ'+string.valueof(system.now().getTime()+ count++));
}
}
if(!accountFieldsList.isEmpty() && !scope.isEmpty()){
HIC_ShopifyUtility.processSobjectList(accountFieldsList,scope,'Account','HIC_ShopifySync__Shopify_Id__c',listOfConfiguration,false,store);
}
}
}
/**************************************InitializeAccount*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Insert Default Account in Salesforce.
* Whenever Shopify's Account is not found in Salesforce and its required on records
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> ShopifyidvsAccountid - Map of Shopify's External Id Vs Accout's Shopify's ID
* @param String ObjectName - Shopify Entity's Name
* @param Boolean isPersonAccount - Identify records its person account or not
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static void InitializeAccount (Map<String,String> ShopifyidvsAccountid,String ObjectName, Boolean isPersonAccount, List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
try{
new HIC_ShopifyUtility(configurationList);
Map<String,String> ShopifyidvsObjectidPresent = new Map<String,String>(ShopifyidvsAccountid);
Set<String> SetofShopifyId = ShopifyidvsAccountid.keyset();
String query = 'select id, HIC_ShopifySync__Shopify_id__c from ' + ObjectName + ' where HIC_ShopifySync__Shopify_id__c IN: SetofShopifyId ';
Type typLstSObject = Type.forName('List<'+ObjectName+'>');
List<SObject> sObjectListToSearch = (List<SObject>)typLstSObject.newInstance();
sObjectListToSearch = Database.query(query);
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(ObjectName);
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theFieldShopif = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
Schema.SobjectField theFieldId = fieldMap.get('id');
for(SObject obj :sObjectListToSearch){
ShopifyidvsObjectidPresent.put((String)obj.get('HIC_ShopifySync__Shopify_Id__c'),(String)obj.get('Id'));
}
Map<String, SObjectField> allRequiredFieldMap = objectType.getDescribe().fields.getMap();
Map<String,Boolean> fieldMapVsrequired = new Map<String,Boolean>();
List<SObject> sObjectListToupsert = (List<SObject>)typLstSObject.NewInstance();
for(String ShopifyID : ShopifyidvsObjectidPresent.keySet()){
if(sObjectListToSearch.IsEmpty() || ShopifyidvsObjectidPresent.get(ShopifyID) == 'false' ){
for(String fieldName : allRequiredFieldMap.keySet())
{
Schema.SObjectField field = allRequiredFieldMap.get(fieldName);
Schema.DescribeFieldResult f = field.getDescribe();
if(!f.isNillable() && f.isUpdateable() && f.isCreateable() && isPersonAccount && fieldName.contains('__pc')){
if(f.isNamefield() && fieldName == 'Name'){
fieldMapVsrequired.put(fieldName,true);
}
}else if((!f.isNillable() || f.isNamefield()) && f.isUpdateable() && f.isCreateable() && !isPersonAccount && !fieldName.contains('__pc')){
if(f.isNamefield() && (fieldName == 'first Name' || fieldName == 'Last Name')){
fieldMapVsrequired.put(fieldName,true);
}
}
}
if(fieldMapVsrequired.containsKey('ownerid')){
fieldMapVsrequired.remove('ownerid');
}
SObject sObjRecord = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;
for(String fld : fieldMapVsrequired.keySet()){
Schema.SObjectType t = Schema.getGlobalDescribe().get(ObjectName);
Schema.DescribeSObjectResult ObjectResult = t.getDescribe();
Schema.DescribeFieldResult fieldResult = ObjectResult.fields.getMap().get(fld).getDescribe();
String fieldType = fieldResult.getType().name().toLowerCase();
if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'decimal' || fieldType == 'percent'){
sObjRecord.put(fld , Double.valueof(1));
}else if(fieldType == 'integer'){
sObjRecord.put(fld , Integer.valueof(1));
}
else if(fieldType == 'String'){
sObjRecord.put(fld,'DE');
}else if(fieldType == 'date'){
sObjRecord.put(fld,System.today());
}else if(fieldType == 'datetime'){
sObjRecord.put(fld,System.now());
}else if(fieldType == 'email'){
sObjRecord.put(fld,'test@gmail.com');
}
}
sObjRecord.put('HIC_ShopifySync__Shopify_id__c',ShopifyID);
sObjRecord.put('name',ShopifyID);
sObjectListToupsert.add(sObjRecord);
}
}
Database.upsert(sObjectListToupsert);
}catch(Exception e){
// CustomSettingRecordInsert.SuccessMailSend('Error message from shopifyUtility '+e.getMessage() + ' at line number ' + e.getLineNumber());
}
}
/**************************************InsertProduct*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Insert Default Account in Salesforce.
* Whenever Shopify's Account is not found in Salesforce and its required on records
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String, Map <String, Object>> oProdMap - Map of Shopify's Product vs name vs Id
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* @param Boolean IsWebhook - Identify records its webhook or Batch record
* @param String store - Shopify's Store Name
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Map <String, String> InsertProduct(Map<String, Map <String, Object>> oProdMap, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, boolean IsWebhook, String store){
new HIC_ShopifyUtility(configurationList);
List<HIC_ShopifySync__HIC_Field_Mapping__c> productFieldsList = 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 from HIC_ShopifySync__HIC_Field_Mapping__c Where HIC_ShopifySync__Object_Name__c = 'Product2' AND HIC_ShopifySync__Store__c =: store ]);
List <Product2> prodListToQuery = new List <Product2>();
Set <String> shopifyIds = new Set <String>();
Set <String> names = new Set <String>();
for (String str : oProdMap.keySet()){
if(oProdMap.get(str) != null && oProdMap.get(str).get('name') != null){
names.add((String)oProdMap.get(str).get('name'));
}
}
prodListToQuery = [Select id, HIC_ShopifySync__Shopify_Id__c, Name From Product2 Where HIC_ShopifySync__Shopify_Id__c IN : oProdMap.keySet() OR Name IN : names];
Map <String, String> nameVsId = new Map <String, String>();
for(Product2 proObj : prodListToQuery){
if(proObj.Name != null && proObj.HIC_ShopifySync__Shopify_Id__c != null){
nameVsId.put(proObj.Name, proObj.HIC_ShopifySync__Shopify_Id__c);
}
else if(proObj.HIC_ShopifySync__Shopify_Id__c != null){
shopifyIds.add(proObj.HIC_ShopifySync__Shopify_Id__c);
}
}
Map <String, Object> prodMapToInsert = new Map <String, Object>();
//List <sObject> sObjecListToUpsert = new List <sObject>();
List<Object> objl = new List<Object>();
if ((shopifyIds != null && !shopifyIds.isEmpty()) || prodListToQuery.isEmpty()){
for (String str : oProdMap.keySet()){
if((prodListToQuery != null && !prodListToQuery.isEmpty() && !shopifyIds.contains(str)) || prodListToQuery.isEmpty()){
Map <String, Object> productMap = (Map<String,Object>) oProdMap.get(str);
productMap.put('id', str);
oProdMap.put(str, productMap);
objl.add((object)oProdMap.get(str));
if((nameVsId != null && !nameVsId.isEmpty() && !nameVsId.containsKey((String)oProdMap.get(str).get('name'))) || nameVsId == null || nameVsId.isEmpty()){
nameVsId.put((String)oProdMap.get(str).get('name'), str);
}
}
}
if(productFieldsList != null && !productFieldsList.isEmpty() && objl != null && !objl.isEmpty()){
HIC_ShopifyUtility.processSobjectList(productFieldsList, objl, 'Product2', 'HIC_ShopifySync__Shopify_Id__c', configurationList,IsWebhook,store);
}
}
if(nameVsId != null && !nameVsId.isEmpty()){
return nameVsId;
}
return null;
}
/**************************************InitializePricebookEntryId*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Insert Pricebook Entry in Salesforce.
* Whenever Shopify's Product insert/upsert or order insert/upsert upsert Pricebook Entry as per the user selection on the page
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Map<String,String> productVsPricebookEntryMap - Map of Shopify's Product External ID vs Pricebook Entry ID
* @param Map<String,String> productVsUnitePriceMap - Map of Shopify's Product External ID vs Product Unit Price value
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Map<String,String> InitializePricebookEntryIdorder(Map<String,String> productVsPricebookEntryMap ,Map<String,String> productVsUnitePriceMap,List<HIC_ShopifySync__HIC_Configuration__c > configurationList, string presentmentCurrency,string store){
new HIC_ShopifyUtility(configurationList);
Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType');
/*List<HIC_ShopifySync__HIC_Field_Mapping__c > pricebook2MappingList = new List<HIC_ShopifySync__HIC_Field_Mapping__c >();
String query = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__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')+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c') +'= \'Pricebook2Id\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
pricebook2MappingList = database.query(query);*/
List<HIC_ShopifySync__HIC_Configuration__c > conList = new List<HIC_ShopifySync__HIC_Configuration__c >();
String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c, name,HIC_ShopifySync__Salesforce_Pricebook__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';
conList = database.query(query);
List<HIC_ShopifySync__HIC_Field_Mapping__c > currencyMappingList = new List<HIC_ShopifySync__HIC_Field_Mapping__c >();
query = '';
String CurrencyShopifyFieldValue = '';
if(multiCurrencyEnabled){
query = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__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')+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c') +'= \'CurrencyISOCODE\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
currencyMappingList = database.query(query);
if (!currencyMappingList.isEmpty()) {
if (currencyMappingList[0].HIC_ShopifySync__Default_Value__c) {
CurrencyShopifyFieldValue = currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c;
} else {
CurrencyShopifyFieldValue = presentmentCurrency;
}
}
}
String PricebookShopifyFieldValue = conList[0].HIC_ShopifySync__Salesforce_Pricebook__c;
if(Test.isRunningTest() && PricebookShopifyFieldValue == null) PricebookShopifyFieldValue = Test.getStandardPricebookId();
Map<String,String> shopifyidVSproductidMap = new Map<String,String>();
String queryFields = '';
if(Schema.sObjectType.Product2.fields.id.isAccessible()){
queryFields += 'Product2Id,';
}
if(multiCurrencyEnabled){
//if(Schema.SObjectType.PricebookEntry.fields.getMap().containsKey('CurrencyISOCODE') && Schema.sObjectType.PricebookEntry.fields.getMap().containsKey('CurrencyISOCODE').isAccessible()){
if(Checkaccessibility.isAccessible('CurrencyISOCODE','PricebookEntry').equalsIgnoreCase('CurrencyISOCODE')){
queryFields += 'CurrencyISOCODE,';
}
}
if(Schema.sObjectType.Product2.fields.Name.isAccessible()){
queryFields += 'Product2.Name,';
}
if(Schema.sObjectType.Product2.fields.HIC_ShopifySync__Shopify_Id__c.isAccessible()){
queryFields += 'Product2.HIC_ShopifySync__Shopify_Id__c,';
}
if(Schema.sObjectType.PricebookEntry.fields.Pricebook2Id.isAccessible()){
queryFields += 'Pricebook2Id ';
}
Set <String> pbEntry = new Set <String>();
pbEntry = productVsPricebookEntryMap.keyset();
system.debug('pbEntry-->'+pbEntry);
query = '';
if(multiCurrencyEnabled){
query = 'Select '+ queryFields + 'From PricebookEntry Where Pricebook2Id = \''+ PricebookShopifyFieldValue + '\' And CurrencyISOCODE = \'' + CurrencyShopifyFieldValue + '\' And Product2.HIC_ShopifySync__Shopify_Id__c IN : pbEntry and Product2.HIC_ShopifySync__Shopify_Id__c != null';
}else{
query = 'Select '+ queryFields + 'From PricebookEntry Where Pricebook2Id = \''+ PricebookShopifyFieldValue + '\' And Product2.HIC_ShopifySync__Shopify_Id__c IN : pbEntry and Product2.HIC_ShopifySync__Shopify_Id__c != null' ;
}
List<PricebookEntry> listOfPriceBookEntry = new List<PricebookEntry>();
System.debug('query--'+query);
listOfPriceBookEntry = Database.query(query);
if(!listOfPriceBookEntry.isEmpty()){
for(PricebookEntry obj : listOfPriceBookEntry){
if(productVsPricebookEntryMap.containskey(obj.Product2.HIC_ShopifySync__Shopify_Id__c)){
if(obj.Pricebook2Id == PricebookShopifyFieldValue)
productVsPricebookEntryMap.put(obj.Product2.HIC_ShopifySync__Shopify_Id__c,obj.id);
}
}
}
// system.debug('productVsUnitePriceMap.get(obj)-->'+productVsUnitePriceMap.get(obj));
List<PricebookEntry> pricebookEntryListToInsert = new List<PricebookEntry>();
List<Pricebook2> StandarPricebookList = new List<Pricebook2>();
StandarPricebookList = database.query('select '+Checkaccessibility.isAccessible('id,HIC_ShopifySync__Shopify_Id__c,name', 'pricebook2')+' from pricebook2 where '+Checkaccessibility.isAccessible('IsStandard', 'pricebook2')+ ' = true LIMIT 1');
if(!productVsPricebookEntryMap.isEmpty()){
for(String obj : productVsPricebookEntryMap.keyset()){
if((productVsPricebookEntryMap.get(obj) == null || productVsPricebookEntryMap.get(obj) == '') && obj != null )
{
if(!StandarPricebookList.isEmpty() && StandarPricebookList[0].id != PricebookShopifyFieldValue){
sObject standardPbEntry = Schema.getGlobalDescribe().get('PricebookEntry').newSObject() ;
standardPbEntry.put('Pricebook2id',StandarPricebookList[0].id);
if(multiCurrencyEnabled){
standardPbEntry.put('CurrencyISOCODE',CurrencyShopifyFieldValue);
}
standardPbEntry.put('isActive',true);
Product2 product = new Product2();
product.HIC_ShopifySync__shopify_Id__c = obj;
standardPbEntry.putSObject('Product2',product);
standardPbEntry.put('UnitPrice',decimal.valueof(productVsUnitePriceMap.get(obj)));
standardPbEntry.put('HIC_ShopifySync__Shopify_Id__c',string.valueof(obj));
PricebookEntry pbe = (PricebookEntry)standardPbEntry;
pricebookEntryListToInsert.add(pbe);
}
sObject NewPbEntry = Schema.getGlobalDescribe().get('PricebookEntry').newSObject() ;
NewPbEntry.put('Pricebook2id',PricebookShopifyFieldValue);
if(multiCurrencyEnabled){
NewPbEntry.put('CurrencyISOCODE', CurrencyShopifyFieldValue);
}
NewPbEntry.put('isActive',true);
Product2 product = new Product2();
product.HIC_ShopifySync__shopify_Id__c = obj;
NewPbEntry.putSObject('Product2',product);
NewPbEntry.put('UnitPrice',decimal.valueof(productVsUnitePriceMap.get(obj)));
NewPbEntry.put('HIC_ShopifySync__Shopify_Id__c',string.valueof(obj)+DateTime.now().format('yyyy-MM-dd HH:mm:ss.SSS'));
PricebookEntry pbe = (PricebookEntry)NewPbEntry;
pricebookEntryListToInsert.add(pbe);
}
}
if(pricebookEntryListToInsert.IsEmpty()) return productVsPricebookEntryMap;
try{
Database.upsertResult[] updateResult;
if(CheckAccessibility.isUpsertable('Pricebook2Id,HIC_ShopifySync__Shopify_Id__c,isActive,Product2Id,UnitPrice', 'PricebookEntry')){
try{
system.debug('pricebookEntryListToInsert-->'+pricebookEntryListToInsert);
updateResult = Database.upsert(pricebookEntryListToInsert,PricebookEntry.HIC_ShopifySync__Shopify_Id__c,false);
}catch(Exception e){
system.debug('error--> '+e.getMessage()+' error all '+e);
}
}
set<id> setofinsert = new set<id>();
for(Integer index = 0 ; index < updateResult.size() ; index ++){
if( updateResult[index].isSuccess() ){
setofinsert.add(updateResult[index].getId());
}else{
for(Database.Error error : updateResult[index].getErrors()){
system.debug('errorMsg--> '+error.getMessage());
}
}
}
List<PricebookEntry> listofinsetedpricebookEntry = new List<PricebookEntry>();
String InsertedPbQuery;
if(multiCurrencyEnabled){
InsertedPbQuery = 'Select id,Pricebook2Id,Product2.HIC_ShopifySync__Shopify_Id__c '+ + 'From PricebookEntry Where '+ CheckAccessibility.isAccessible('CurrencyISOCODE','PricebookEntry') +' = \'' + CurrencyShopifyFieldValue + '\' And id IN : setofinsert';
}else{
InsertedPbQuery = 'Select id,Pricebook2Id,Product2.HIC_ShopifySync__Shopify_Id__c '+ CheckAccessibility.isAccessible('Product2.HIC_ShopifySync__Shopify_Id__c','PricebookEntry') + 'From PricebookEntry Where id IN : setofinsert';
}
listofinsetedpricebookEntry = Database.query(InsertedPbQuery);
if(!listofinsetedpricebookEntry.isEmpty()){
for(PricebookEntry pbe : listofinsetedpricebookEntry){
if(pbe.Pricebook2Id == PricebookShopifyFieldValue){
productVsPricebookEntryMap.put(pbe.Product2.HIC_ShopifySync__Shopify_Id__c,pbe.Id);
}
}
}
}
catch(Exception e){
system.debug('error '+e.getMessage()+' at line number' +e.getLineNumber());
}
}
return productVsPricebookEntryMap;
}
public static Map<String,String> InitializePricebookEntryId(Map<String,String> productVsPricebookEntryMap ,Map<String,String> productVsUnitePriceMap,List<HIC_ShopifySync__HIC_Configuration__c > configurationList, string store){
new HIC_ShopifyUtility(configurationList);
Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType');
/*List<HIC_ShopifySync__HIC_Field_Mapping__c > pricebook2MappingList = new List<HIC_ShopifySync__HIC_Field_Mapping__c >();
String query = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__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')+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c') +'= \'Pricebook2Id\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
pricebook2MappingList = database.query(query);*/
List<HIC_ShopifySync__HIC_Configuration__c > conList = new List<HIC_ShopifySync__HIC_Configuration__c >();
String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c, name,HIC_ShopifySync__Salesforce_Pricebook__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';
conList = database.query(query);
List<HIC_ShopifySync__HIC_Field_Mapping__c > currencyMappingList = new List<HIC_ShopifySync__HIC_Field_Mapping__c >();
query = '';
String CurrencyShopifyFieldValue = '';
if(multiCurrencyEnabled){
query = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__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')+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c') +'= \'CurrencyISOCODE\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
currencyMappingList = database.query(query);
CurrencyShopifyFieldValue = currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c;
}
String PricebookShopifyFieldValue = conList[0].HIC_ShopifySync__Salesforce_Pricebook__c;
if(Test.isRunningTest() && PricebookShopifyFieldValue == null) PricebookShopifyFieldValue = Test.getStandardPricebookId();
Map<String,String> shopifyidVSproductidMap = new Map<String,String>();
String queryFields = '';
if(Schema.sObjectType.Product2.fields.id.isAccessible()){
queryFields += 'Product2Id,';
}
if(multiCurrencyEnabled){
//if(Schema.SObjectType.PricebookEntry.fields.getMap().containsKey('CurrencyISOCODE') && Schema.sObjectType.PricebookEntry.fields.getMap().containsKey('CurrencyISOCODE').isAccessible()){
if(Checkaccessibility.isAccessible('CurrencyISOCODE','PricebookEntry').equalsIgnoreCase('CurrencyISOCODE')){
queryFields += 'CurrencyISOCODE,';
}
}
if(Schema.sObjectType.Product2.fields.Name.isAccessible()){
queryFields += 'Product2.Name,';
}
if(Schema.sObjectType.Product2.fields.HIC_ShopifySync__Shopify_Id__c.isAccessible()){
queryFields += 'Product2.HIC_ShopifySync__Shopify_Id__c,';
}
if(Schema.sObjectType.PricebookEntry.fields.Pricebook2Id.isAccessible()){
queryFields += 'Pricebook2Id ';
}
Set <String> pbEntry = new Set <String>();
pbEntry = productVsPricebookEntryMap.keyset();
system.debug('pbEntry-->'+pbEntry);
query = '';
if(multiCurrencyEnabled){
query = 'Select '+ queryFields + 'From PricebookEntry Where Pricebook2Id = \''+ PricebookShopifyFieldValue + '\' And CurrencyISOCODE = \'' + CurrencyShopifyFieldValue + '\' And Product2.HIC_ShopifySync__Shopify_Id__c IN : pbEntry and Product2.HIC_ShopifySync__Shopify_Id__c != null';
}else{
query = 'Select '+ queryFields + 'From PricebookEntry Where Pricebook2Id = \''+ PricebookShopifyFieldValue + '\' And Product2.HIC_ShopifySync__Shopify_Id__c IN : pbEntry and Product2.HIC_ShopifySync__Shopify_Id__c != null' ;
}
List<PricebookEntry> listOfPriceBookEntry = new List<PricebookEntry>();
System.debug('query--'+query);
listOfPriceBookEntry = Database.query(query);
if(!listOfPriceBookEntry.isEmpty()){
for(PricebookEntry obj : listOfPriceBookEntry){
if(productVsPricebookEntryMap.containskey(obj.Product2.HIC_ShopifySync__Shopify_Id__c)){
if(obj.Pricebook2Id == PricebookShopifyFieldValue)
productVsPricebookEntryMap.put(obj.Product2.HIC_ShopifySync__Shopify_Id__c,obj.id);
}
}
}
// system.debug('productVsUnitePriceMap.get(obj)-->'+productVsUnitePriceMap.get(obj));
List<PricebookEntry> pricebookEntryListToInsert = new List<PricebookEntry>();
List<Pricebook2> StandarPricebookList = new List<Pricebook2>();
StandarPricebookList = database.query('select '+Checkaccessibility.isAccessible('id,HIC_ShopifySync__Shopify_Id__c,name', 'pricebook2')+' from pricebook2 where '+Checkaccessibility.isAccessible('IsStandard', 'pricebook2')+ ' = true LIMIT 1');
if(!productVsPricebookEntryMap.isEmpty()){
for(String obj : productVsPricebookEntryMap.keyset()){
if((productVsPricebookEntryMap.get(obj) == null || productVsPricebookEntryMap.get(obj) == '') && obj != null )
{
if(!StandarPricebookList.isEmpty() && StandarPricebookList[0].id != PricebookShopifyFieldValue){
sObject standardPbEntry = Schema.getGlobalDescribe().get('PricebookEntry').newSObject() ;
standardPbEntry.put('Pricebook2id',StandarPricebookList[0].id);
if(multiCurrencyEnabled){
standardPbEntry.put('CurrencyISOCODE',currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c);
}
standardPbEntry.put('isActive',true);
Product2 product = new Product2();
product.HIC_ShopifySync__shopify_Id__c = obj;
standardPbEntry.putSObject('Product2',product);
standardPbEntry.put('UnitPrice',decimal.valueof(productVsUnitePriceMap.get(obj)));
standardPbEntry.put('HIC_ShopifySync__Shopify_Id__c',string.valueof(obj));
PricebookEntry pbe = (PricebookEntry)standardPbEntry;
pricebookEntryListToInsert.add(pbe);
}
sObject NewPbEntry = Schema.getGlobalDescribe().get('PricebookEntry').newSObject() ;
NewPbEntry.put('Pricebook2id',PricebookShopifyFieldValue);
if(multiCurrencyEnabled){
NewPbEntry.put('CurrencyISOCODE', currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c);
}
NewPbEntry.put('isActive',true);
Product2 product = new Product2();
product.HIC_ShopifySync__shopify_Id__c = obj;
NewPbEntry.putSObject('Product2',product);
NewPbEntry.put('UnitPrice',decimal.valueof(productVsUnitePriceMap.get(obj)));
NewPbEntry.put('HIC_ShopifySync__Shopify_Id__c',string.valueof(obj)+DateTime.now().format('yyyy-MM-dd HH:mm:ss.SSS'));
PricebookEntry pbe = (PricebookEntry)NewPbEntry;
pricebookEntryListToInsert.add(pbe);
}
}
if(pricebookEntryListToInsert.IsEmpty()) return productVsPricebookEntryMap;
try{
Database.upsertResult[] updateResult;
if(CheckAccessibility.isUpsertable('Pricebook2Id,HIC_ShopifySync__Shopify_Id__c,isActive,Product2Id,UnitPrice', 'PricebookEntry')){
try{
system.debug('pricebookEntryListToInsert-->'+pricebookEntryListToInsert);
updateResult = Database.upsert(pricebookEntryListToInsert,PricebookEntry.HIC_ShopifySync__Shopify_Id__c,false);
}catch(Exception e){
system.debug('error--> '+e.getMessage()+' error all '+e);
}
}
set<id> setofinsert = new set<id>();
for(Integer index = 0 ; index < updateResult.size() ; index ++){
if( updateResult[index].isSuccess() ){
setofinsert.add(updateResult[index].getId());
}else{
for(Database.Error error : updateResult[index].getErrors()){
system.debug('errorMsg--> '+error.getMessage());
}
}
}
List<PricebookEntry> listofinsetedpricebookEntry = new List<PricebookEntry>();
String InsertedPbQuery;
if(multiCurrencyEnabled){
InsertedPbQuery = 'Select id,Pricebook2Id,Product2.HIC_ShopifySync__Shopify_Id__c '+ + 'From PricebookEntry Where '+ CheckAccessibility.isAccessible('CurrencyISOCODE','PricebookEntry') +' = \'' + CurrencyShopifyFieldValue + '\' And id IN : setofinsert';
}else{
InsertedPbQuery = 'Select id,Pricebook2Id,Product2.HIC_ShopifySync__Shopify_Id__c '+ CheckAccessibility.isAccessible('Product2.HIC_ShopifySync__Shopify_Id__c','PricebookEntry') + 'From PricebookEntry Where id IN : setofinsert';
}
listofinsetedpricebookEntry = Database.query(InsertedPbQuery);
if(!listofinsetedpricebookEntry.isEmpty()){
for(PricebookEntry pbe : listofinsetedpricebookEntry){
if(pbe.Pricebook2Id == PricebookShopifyFieldValue){
productVsPricebookEntryMap.put(pbe.Product2.HIC_ShopifySync__Shopify_Id__c,pbe.Id);
}
}
}
}
catch(Exception e){
system.debug('error '+e.getMessage()+' at line number' +e.getLineNumber());
}
}
return productVsPricebookEntryMap;
}
//Deprecated
public static Map<String,String> InitializePricebookEntryId(Map<String,String> productVsPricebookEntryMap ,Map<String,String> productVsUnitePriceMap,List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
/*new HIC_ShopifyUtility(configurationList);
Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType');
List<HIC_ShopifySync__Field_Mapping__c > pricebook2MappingList = new List<HIC_ShopifySync__Field_Mapping__c >();
String query = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c','HIC_ShopifySync__Field_Mapping__c')+' from HIC_ShopifySync__Field_Mapping__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__Field_Mapping__c')+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__Field_Mapping__c') +'= \'Pricebook2Id\' limit 49999';
pricebook2MappingList = database.query(query);
List<HIC_ShopifySync__Field_Mapping__c > currencyMappingList = new List<HIC_ShopifySync__Field_Mapping__c >();
query = '';
String CurrencyShopifyFieldValue = '';
if(multiCurrencyEnabled){
query = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c','HIC_ShopifySync__Field_Mapping__c')+' from HIC_ShopifySync__Field_Mapping__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__Field_Mapping__c')+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__Field_Mapping__c') +'= \'CurrencyISOCODE\' limit 49999';
currencyMappingList = database.query(query);
CurrencyShopifyFieldValue = currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c;
}
String PricebookShopifyFieldValue = pricebook2MappingList[0].HIC_ShopifySync__Shopify_Fields__c;
Map<String,String> shopifyidVSproductidMap = new Map<String,String>();
String queryFields = '';
if(Schema.sObjectType.Product2.fields.id.isAccessible()){
queryFields += 'Product2Id,';
}
if(multiCurrencyEnabled){
//if(Schema.SObjectType.PricebookEntry.fields.getMap().containsKey('CurrencyISOCODE') && Schema.sObjectType.PricebookEntry.fields.getMap().containsKey('CurrencyISOCODE').isAccessible()){
if(Checkaccessibility.isAccessible('CurrencyISOCODE','PricebookEntry').equalsIgnoreCase('CurrencyISOCODE')){
queryFields += 'CurrencyISOCODE,';
}
}
if(Schema.sObjectType.Product2.fields.Name.isAccessible()){
queryFields += 'Product2.Name,';
}
if(Schema.sObjectType.Product2.fields.HIC_ShopifySync__Shopify_Id__c.isAccessible()){
queryFields += 'Product2.HIC_ShopifySync__Shopify_Id__c,';
}
if(Schema.sObjectType.PricebookEntry.fields.Pricebook2Id.isAccessible()){
queryFields += 'Pricebook2Id ';
}
Set <String> pbEntry = new Set <String>();
pbEntry = productVsPricebookEntryMap.keyset();
query = '';
if(multiCurrencyEnabled){
query = 'Select '+ queryFields + 'From PricebookEntry Where Pricebook2Id = \''+ PricebookShopifyFieldValue + '\' And CurrencyISOCODE = \'' + CurrencyShopifyFieldValue + '\' And Product2.HIC_ShopifySync__Shopify_Id__c IN : pbEntry and Product2.HIC_ShopifySync__Shopify_Id__c != null';
}else{
query = 'Select '+ queryFields + 'From PricebookEntry Where Pricebook2Id = \''+ PricebookShopifyFieldValue + '\' And Product2.HIC_ShopifySync__Shopify_Id__c IN : pbEntry and Product2.HIC_ShopifySync__Shopify_Id__c != null' ;
}
List<PricebookEntry> listOfPriceBookEntry = new List<PricebookEntry>();
listOfPriceBookEntry = Database.query(query);
if(!listOfPriceBookEntry.isEmpty()){
for(PricebookEntry obj : listOfPriceBookEntry){
if(productVsPricebookEntryMap.containskey(obj.Product2.HIC_ShopifySync__Shopify_Id__c)){
if(obj.Pricebook2Id == pricebook2MappingList[0].HIC_ShopifySync__Shopify_Fields__c)
productVsPricebookEntryMap.put(obj.Product2.HIC_ShopifySync__Shopify_Id__c,obj.id);
}
}
}
List<PricebookEntry> pricebookEntryListToInsert = new List<PricebookEntry>();
List<Pricebook2> StandarPricebookList = new List<Pricebook2>();
StandarPricebookList = database.query('select '+Checkaccessibility.isAccessible('id,name', 'pricebook2')+' from pricebook2 where '+Checkaccessibility.isAccessible('IsStandard', 'pricebook2')+ ' = true LIMIT 1');
if(!productVsPricebookEntryMap.isEmpty()){
for(String obj : productVsPricebookEntryMap.keyset()){
if((productVsPricebookEntryMap.get(obj) == null || productVsPricebookEntryMap.get(obj) == '') && obj != null )
{
if(!StandarPricebookList.isEmpty() && StandarPricebookList[0].id != pricebook2MappingList[0].HIC_ShopifySync__Shopify_Fields__c){
sObject standardPbEntry = Schema.getGlobalDescribe().get('PricebookEntry').newSObject() ;
standardPbEntry.put('Pricebook2id',StandarPricebookList[0].id);
if(multiCurrencyEnabled){
standardPbEntry.put('CurrencyISOCODE',currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c);
}
standardPbEntry.put('isActive',true);
Product2 product = new Product2();
product.HIC_ShopifySync__shopify_Id__c = obj;
standardPbEntry.putSObject('Product2',product);
standardPbEntry.put('UnitPrice',decimal.valueof(productVsUnitePriceMap.get(obj)));
PricebookEntry pbe = (PricebookEntry)standardPbEntry;
pricebookEntryListToInsert.add(pbe);
}
sObject NewPbEntry = Schema.getGlobalDescribe().get('PricebookEntry').newSObject() ;
NewPbEntry.put('Pricebook2id',pricebook2MappingList[0].HIC_ShopifySync__Shopify_Fields__c);
if(multiCurrencyEnabled){
NewPbEntry.put('CurrencyISOCODE', currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c);
}
NewPbEntry.put('isActive',true);
Product2 product = new Product2();
product.HIC_ShopifySync__shopify_Id__c = obj;
NewPbEntry.putSObject('Product2',product);
NewPbEntry.put('UnitPrice',decimal.valueof(productVsUnitePriceMap.get(obj)));
PricebookEntry pbe = (PricebookEntry)NewPbEntry;
pricebookEntryListToInsert.add(pbe);
}
}
if(pricebookEntryListToInsert.IsEmpty()) return productVsPricebookEntryMap;
try{
Database.SaveResult[] updateResult;
if(CheckAccessibility.isInsertable('Pricebook2Id,isActive,Product2Id,UnitPrice', 'PricebookEntry')){
try{
updateResult = Database.insert(pricebookEntryListToInsert,false);
}catch(Exception e){
system.debug('error--> '+e.getMessage()+' error all '+e);
}
}
set<id> setofinsert = new set<id>();
for(Integer index = 0 ; index < updateResult.size() ; index ++){
if( updateResult[index].isSuccess() ){
setofinsert.add(updateResult[index].getId());
}else{
for(Database.Error error : updateResult[index].getErrors()){
system.debug('errorMsg--> '+error.getMessage());
}
}
}
List<PricebookEntry> listofinsetedpricebookEntry = new List<PricebookEntry>();
String InsertedPbQuery;
if(multiCurrencyEnabled){
InsertedPbQuery = 'Select id,Pricebook2Id,Product2.HIC_ShopifySync__Shopify_Id__c '+ + 'From PricebookEntry Where '+ CheckAccessibility.isAccessible('CurrencyISOCODE','PricebookEntry') +' = \'' + CurrencyShopifyFieldValue + '\' And id IN : setofinsert';
}else{
InsertedPbQuery = 'Select id,Pricebook2Id,Product2.HIC_ShopifySync__Shopify_Id__c '+ CheckAccessibility.isAccessible('Product2.HIC_ShopifySync__Shopify_Id__c','PricebookEntry') + 'From PricebookEntry Where id IN : setofinsert';
}
listofinsetedpricebookEntry = Database.query(InsertedPbQuery);
if(!listofinsetedpricebookEntry.isEmpty()){
for(PricebookEntry pbe : listofinsetedpricebookEntry){
if(pbe.Pricebook2Id == pricebook2MappingList[0].HIC_ShopifySync__Shopify_Fields__c){
productVsPricebookEntryMap.put(pbe.Product2.HIC_ShopifySync__Shopify_Id__c,pbe.Id);
}
}
}
}
catch(Exception e){
system.debug('error '+e.getMessage()+' at line number' +e.getLineNumber());
}
}*/
return productVsPricebookEntryMap;
}
/**************************************fillObjectValues*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Dynamic Field Mapping
* Map Salesfoce field with Shopify Field
* Map Shopify Field values into Salesforce based on Salesforce Field DataType
* Retun list of Maped Salesforce and Shopify Field Values
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<HIC_ShopifySync__HIC_Field_Mapping__c> FieldsList - Map of Shopify's Product External ID vs Pricebook Entry ID
* @param String ObjectName - Shopify Entity's Name (Object name)
* @param List<Object> objectList - list of records object to upser in Salesfroce
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static List<sobject> fillObjectValues(List<HIC_ShopifySync__HIC_Field_Mapping__c> FieldsList, String ObjectName, List<Object> objectList, List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
new HIC_ShopifyUtility(configurationList);
String companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey;
String ListType = 'List<' + ObjectName + '>';
List<sobject> sobjListToUpsert = (List<SObject>)Type.forName(ListType).newInstance();
List <Account> accListToQuery = new List <Account>();
for(Object obj : objectList){
Map<String, Object> ObjectMap = (Map<String, Object>)obj;
if(ObjectMap != null && !ObjectMap.isEmpty()){
SObject sObjRecord = processFieldTypeAndMapping(FieldsList,ObjectName,ObjectMap, configurationList, companyTimeZone);
if(sObjRecord != null){
sobjListToUpsert.add(sObjRecord);
}
}
}
return sobjListToUpsert;
}
/**************************************processFieldTypeAndMapping*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Dynamic Field Mapping
* Map Salesfoce field with Shopify Field
* Map Shopify Field values into Salesforce based on Salesforce Field DataType
* Retun Maped Salesforce and Shopify Field Values
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldsMappingList - Map of Shopify's Product External ID vs Pricebook Entry ID
* @param String ObjectName - Shopify Entity's Name (Object name)
* @param Map<String, Object> objectMap - Map of single record of shopify
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static SObject processFieldTypeAndMapping(List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldsMappingList, String ObjectName, Map<String, Object> objectMap, List<HIC_ShopifySync__HIC_Configuration__c> configurationList, String companyTimeZone){
new HIC_ShopifyUtility(configurationList);
//system.debug('check field---> '+ objectMap.get('default_address'));
//system.debug('check MapJason---> '+ objectMap);
system.debug('check MapJson!!!---> ' + JSON.serializePretty(objectMap));
system.debug('configlist---> ' + configurationList);
if(ObjectName != null && ObjectName == 'Account'){
Decimal numberOfPages;
try {
numberOfPages = configurationList[0].HIC_ShopifySync__Number_of_pages_for_Account__c;
} catch (Exception e) {
// Field not queried in parent SOQL, fetch it here
String configName = configurationList[0].Name;
HIC_ShopifySync__HIC_Configuration__c configRecord = [
SELECT HIC_ShopifySync__Number_of_pages_for_Account__c
FROM HIC_ShopifySync__HIC_Configuration__c
WHERE Name = :configName
LIMIT 1
];
numberOfPages = configRecord.HIC_ShopifySync__Number_of_pages_for_Account__c;
}
// ✅ Apply nulling logic based on numberOfPages
/* if (numberOfPages != 1 && numberOfPages != 3) {
if (objectMap.containsKey('tags')) {
objectMap.put('tags', null);
}
}*/
/* if (numberOfPages != 2 && numberOfPages != 3) {
if (objectMap.containsKey('sms_marketing_consent')) {
objectMap.put('sms_marketing_consent', null);
}
if (objectMap.containsKey('email_marketing_consent')) {
objectMap.put('email_marketing_consent', null);
}
}*/
}
//String companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey;
SObject sObjRecord = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;
//Object type
Schema.sObjectType objectDef = Schema.getGlobalDescribe().get(ObjectName).getDescribe().getSObjectType();
//Get Field Of Object
Map<String, Schema.SobjectField> ObjectFieldsMap = objectDef.getDescribe().fields.getMap();
System.debug('objectMap---'+objectMap);
//System.debug('objectMap!!!---> ' + JSON.serializePretty(objectMap));
/************ Update Account and Contact Shopify External ID Based on their recordtype (Bussiness Account/ Person Account) ********/
//^^^^^^^^^Add account and id check in first outher if rather in each inner if statement
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){
//check if person account is selected by admin
if (configurationList[0].HIC_ShopifySync__Person_Account__c && ObjectName == 'Account' ){
if(!(String.valueOf(objectMap.get('id'))).contains('Person '))
objectMap.put('id','Person '+String.valueOf(objectMap.get('id')));
//check if person account is not selected by admin
}else if(!configurationList[0].HIC_ShopifySync__Person_Account__c && (ObjectName == 'Account' || ObjectName == 'Contact')){
if(!(String.valueOf(objectMap.get('id'))).contains('Business '))
objectMap.put('id','Business '+String.valueOf(objectMap.get('id')));
}
}else{
//check if person account is not enabled in the org
if( (ObjectName == 'Account' || ObjectName == 'Contact') && objectMap.containsKey('id') && !(String.valueOf(objectMap.get('id'))).contains('Business ')){
objectMap.put('id','Business '+String.valueOf(objectMap.get('id')));
}
}
//^^^^remove this line no where used
Boolean personAccountExists = false;
/******************* END ********************************/
if(ObjectFieldsMap.containsKey('HIC_ShopifySync__Store__c')){
sObjRecord.put('HIC_ShopifySync__Store__c', store);
}
/************ "Don't Override" field mapping support ********************
* HIC_ShopifySync__Is_Override__c (default true = current behaviour, always sync the value).
* When an admin unchecks it on a field mapping, that field should only ever be *filled* by
* Shopify (new record, or field currently blank on the existing record) and must never
* clobber a value someone already set/edited in Salesforce.
* fm.isSet(...) is used (instead of direct field access) so this stays a no-op for any
* fieldsMappingList that wasn't queried with this field - i.e. callers/objects not yet
* migrated to this behaviour are completely unaffected.
***************************************************************************/
Set<String> noOverrideFieldNames = new Set<String>();
for(HIC_ShopifySync__HIC_Field_Mapping__c fm : fieldsMappingList){
if(fm.isSet('HIC_ShopifySync__Is_Override__c') && fm.HIC_ShopifySync__Is_Override__c == false
&& String.isNotBlank(fm.HIC_ShopifySync__SF_Field__c) && ObjectFieldsMap.containsKey(fm.HIC_ShopifySync__SF_Field__c)){
noOverrideFieldNames.add(fm.HIC_ShopifySync__SF_Field__c);
}
}
SObject existingRecordForOverrideCheck = null;
if(!noOverrideFieldNames.isEmpty() && ObjectFieldsMap.containsKey('HIC_ShopifySync__Shopify_Id__c') && objectMap.get('id') != null){
String shopifyIdValue = String.valueOf(objectMap.get('id'));
String existingRecordQuery = 'SELECT Id, ' + String.join(new List<String>(noOverrideFieldNames), ', ')
+ ' FROM ' + ObjectName + ' WHERE HIC_ShopifySync__Shopify_Id__c = :shopifyIdValue LIMIT 1';
List<SObject> existingRecordList = Database.query(existingRecordQuery);
if(!existingRecordList.isEmpty()){
existingRecordForOverrideCheck = existingRecordList[0];
}
}
/******************* END "Don't Override" setup ********************/
// Loop on all field Mapping defined by the user on the page
for(HIC_ShopifySync__HIC_Field_Mapping__c fieldMappingObj : fieldsMappingList){
System.debug('fieldMappingObj--'+fieldMappingObj);
//Use for make Unique key
i= i+1;
//Update the Opportunity Close date base on User values if filled.
if (configurationList[0].HIC_ShopifySync__Specify_Close_Date__c && ObjectName == 'Opportunity' && fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'CloseDate' ){
fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c = String.valueof(system.today() + integer.valueof(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, date.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
continue;
}
//Update OrderFulfillment's Order and Opportunity field mapping based on user selection of Order/Opportunity
if (!configurationList[0].HIC_ShopifySync__Opportunity__c && ObjectName == 'HIC_ShopifySync__Order_Fulfillment__c' && fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'HIC_ShopifySync__Opportunity__c' ){
continue;
}
if (!configurationList[0].HIC_ShopifySync__Order__c && ObjectName == 'HIC_ShopifySync__Order_Fulfillment__c' && fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'HIC_ShopifySync__Order__c' ){
continue;
}
//Get Field detail based on User Fill
Schema.SobjectField dynamicObjField = ObjectFieldsMap.get(fieldMappingObj.HIC_ShopifySync__SF_Field__c);
//If Salesfroce Field deleted then return
//^^^^^^this should be happening on 1st line of this method
if(dynamicObjField == null ){
continue;
}
//Get Field detail based on User Fill
Schema.DescribeFieldResult fieldResult = dynamicObjField.getDescribe();
//Get DataType of Saleforce Field
String fieldType = fieldResult.getType().name().toLowerCase();
// "Don't Override": field already has a value on the existing Salesforce record -> leave it alone.
if(existingRecordForOverrideCheck != null && noOverrideFieldNames.contains(fieldMappingObj.HIC_ShopifySync__SF_Field__c)){
Object existingFieldValue = existingRecordForOverrideCheck.get(fieldMappingObj.HIC_ShopifySync__SF_Field__c);
if(existingFieldValue != null && String.valueOf(existingFieldValue) != ''){
continue;
}
}
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c != null){
//Check field Access
if(fieldResult.isUpdateable() || fieldResult.isCreateable()){
// Mapped default values into the Salesforce Field. Which either comes from user or custom code
if(fieldMappingObj.HIC_ShopifySync__Default_Value__c == true){
if(fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'RecordTypeId' && string.valueof(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null && string.valueof(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != '' ){
Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
Schema.SObjectType sobjType = gd.get(ObjectName);
Schema.DescribeSObjectResult describeResult = sobjType.getDescribe();
Map<Id,Schema.RecordTypeInfo> rtMapByIdForCon = describeResult.getRecordTypeInfosById();
if(rtMapByIdForCon.containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c))
{
Schema.RecordTypeInfo rtById = rtMapByIdForCon.get(String.valueof(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
if(rtById.isActive()){
}else{
continue;
}
}else{
continue;
}
}
System.debug('fieldMappingObj'+fieldMappingObj.HIC_ShopifySync__SF_Field__c+'--'+fieldMappingObj);
System.debug('fieldType--'+fieldType);
if(fieldType == 'boolean'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, Boolean.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
}else if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'decimal' ){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, double.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
}else if( fieldType == 'percent' ){
if(double.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) > 100) {
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, double.valueOf(100));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, double.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
}
}else if(fieldType == 'integer'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, integer.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
}
else if(fieldType == 'date'){
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c != null && fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c != 'null'){
fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c = String.valueof(system.today() + integer.valueof(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, date.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c));
}
}else if(fieldType == 'datetime'){
Datetime dt = dateTime.valueOf(String.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c).replace('T',' '));
DateTime dtTimeTimeZone=new TimeZoneServiceNew().convertDateTimeToOtherTimeZone(dt, 'UTC',companyTimeZone);
//dtTimeTimeZone=new TimeZoneServiceNew().convertDateTimeToOtherTimeZone(dtTimeTimeZone, 'UTC',companyTimeZone);
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, dtTimeTimeZone);
}
else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, checkFieldLengthAndReturnValue(fieldResult,String.valueOf(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c), configurationList));
}
continue;
}
//Mappped Field which are defined by Code eg. OrderItem-PricebookEntryId
if(fieldMappingObj.HIC_ShopifySync__IsSFID__c == true ){
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, checkFieldLengthAndReturnValue(fieldResult,String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)), configurationList));
}
continue;
}
/******************** Mapped Field which have nested field Mapping with Shopify's field *********************/
/**************SHOPIFY NESTED FIELD MAPPING ********************************/
if(fieldMappingObj.HIC_ShopifySync__Nested__c != null && fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c != null){
/*********************Check Salesfroce's Field DataType****************/
//Salesforce Field DataTyep = currency, double, decimal, percent
if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'decimal' || fieldType == 'percent' ){
Double doublevalue = 0;
//Check Multiple Field Mapping
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.contains(',')){
for(String shopifyField : fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.split(',')){
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c) && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(shopifyField)){
object objectFieldValue = ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(shopifyField);
if(objectFieldValue != null && objectFieldValue != '' ){
doublevalue += double.valueof(objectFieldValue);
}
}
}
}else{
String nestedvalue = String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c));
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c) && nestedvalue != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
object objectFieldValue = ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c);
if(objectFieldValue != null && objectFieldValue != '' ){
doublevalue += double.valueof(objectFieldValue);
}
}
}
//percentage
if(fieldType == 'percent' && doublevalue > 100){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, double.valueof(100));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, doublevalue);
}
}
// Saleforce Field DataType = integer
else if(fieldType == 'integer'){
Integer doublevalue = 0;
//Check Multiple Field Mapping
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.contains(',')){
for(String shopifyField : fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.split(',')){
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c) && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(shopifyField)){
object objectFieldValue = ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(shopifyField);
if(objectFieldValue != null && objectFieldValue != '' ){
doublevalue += Integer.valueof(Double.valueOf(objectFieldValue));
}
}
}
}else{
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c) && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
object objectFieldValue = ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c);
if(objectFieldValue != null && objectFieldValue != '' ){
doublevalue += Integer.valueof(Double.valueOf(objectFieldValue));
}
}
}
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, doublevalue);
}
// Saleforce Field DataType = LookUp
else if(fieldType == 'reference')
{
String relationshipName = fieldResult.getRelationshipName();
SObject parentObj = fieldResult.getReferenceTo()[0].newSObject();
String parentObjectName = fieldResult.getReferenceTo()[0].getDescribe().getName();
//If Salefroce Field Lookup on Account then we must update its Shopify External ID
if((parentObjectName == 'Account' || parentObjectName == 'Contact') && objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c ) != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase()) != null){
if(configurationList[0].HIC_ShopifySync__Person_Account__c){
if(String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())).contains('Person')){
parentObj.put('HIC_ShopifySync__Shopify_Id__c',String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())));
}else{
parentObj.put('HIC_ShopifySync__Shopify_Id__c','Person '+String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())));
}
}else{
if(String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())).containsIgnoreCase('business')){
parentObj.put('HIC_ShopifySync__Shopify_Id__c',String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())));
}else{
parentObj.put('HIC_ShopifySync__Shopify_Id__c','Business '+String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())));
}
}
sObjRecord.putSObject(relationshipName, parentObj);
}
// Mapped Lookup fields
else if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c ) != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase()) != null){
parentObj.put('HIC_ShopifySync__Shopify_Id__c',String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())));
sObjRecord.putSObject(relationshipName, parentObj);
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, null);
}
}
else if(fieldType == 'boolean'){
if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c ) != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase()) != null && objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != ''){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, Boolean.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase())));
}
}else
//Salesforce DataType = Date
if(fieldType == 'date')
{//
if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c ) != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase()) != null){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, Date.valueOf((String)((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, null);
}
}
else
//Salesforce DataType = Date
if(fieldType == 'datetime')
{
if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c ) != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.toLowerCase()) != null){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, DateTime.valueOf(String.valueOf(((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)).replace('T',' ')));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, null);
}
}
else{
//Salesforce Field DataType is String
String stringvalue = '';
if(fieldType != 'boolean' && fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.contains(',')){
for(String shopifyField : fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.split(',')){
//System.debug('shopifyField===='+shopifyField);
//System.debug('objectMap===='+objectMap);
//System.debug('fieldMappingObj===='+fieldMappingObj);
//System.debug('objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c)===='+objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c));
//System.debug('((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c))===='+((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)));
//System.debug('((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(shopifyField)===='+((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(shopifyField));
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c) && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)) != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(shopifyField) ){
Object objectFieldValue = ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(shopifyField);
if(objectFieldValue != null){
stringvalue += String.valueof(objectFieldValue)+' ';
}
}
}
}else{
String nestedvalue = String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c));
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Nested__c) && nestedvalue != null && ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
system.debug('nestesvalue-->>> '+fieldMappingObj.HIC_ShopifySync__Nested__c+' objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)===>> '+objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c));
Object objectFieldValue = ((Map<String,object>)objectMap.get(fieldMappingObj.HIC_ShopifySync__Nested__c)).get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c);
if(objectFieldValue != null && objectFieldValue != '' ){
stringvalue += String.valueof(objectFieldValue);
}
}
}
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, checkFieldLengthAndReturnValue(fieldResult, stringvalue, configurationList));
// Insert Default Values into the Salesforce Field which are required in the Salesforce
if((!fieldResult.isNillable() || ((ObjectName == 'Account'|| ObjectName == 'Personaccount' ) && (fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'LastName' ||fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'lastname' || fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'name' || fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'Name'))) && (stringvalue == '' || stringvalue == null)){
if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'decimal' || fieldType == 'percent'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c , Double.valueof(1));
}
else if(fieldType == 'integer'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c , Integer.valueof(1));
}
else if(fieldType == 'String'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,'REQ'+string.valueof(system.now().getTime()+ i+1));
}else if(fieldType == 'date'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,System.today());
}else if(fieldType == 'datetime'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,System.now());
}else if(fieldType == 'email'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,'required@hic.com');
}
}
}
continue;
}
/************** SHOPIFY NESTED FIELD MAPPING END ********************************/
/************************** SHOPIFY SINGLE FIELD MAPPING ***************************************/
if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'decimal' || fieldType == 'percent' )
{
Double doublevalue = 0;
//Check Shopify multiple Field Mapping
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.contains(',')){
for(String shopifyField : fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.split(',')){
if(objectMap.containsKey(shopifyField)){
Object objectFieldValue = objectMap.get(shopifyField);
if(objectFieldValue != null && objectFieldValue != '' ){
doublevalue += Double.valueof(objectFieldValue);
}
}
}
}else{
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
Object objectFieldValue = objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c);
if(objectFieldValue != null && objectFieldValue != ''){
doublevalue += Double.valueof(objectFieldValue);
}
}
}
//DataType = Percentage
if(fieldType == 'percent' && doublevalue > 100){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, Double.valueof(100));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, doublevalue);
}
}else
// Salesforce Field Data Type = Integer
if(fieldType == 'integer'){
Integer doublevalue = 0;
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.contains(',')){
for(String shopifyField : fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.split(',')){
if(objectMap.containsKey(shopifyField)){
Object objectFieldValue = objectMap.get(shopifyField);
if(objectFieldValue != null && objectFieldValue != ''){
doublevalue += Integer.valueof(double.valueof(objectFieldValue));
}
}
}
}else{
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
Object objectFieldValue = objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c);
if(objectFieldValue != null && objectFieldValue != '' ){
doublevalue += Integer.valueof(double.valueof(objectFieldValue));
}
}
}
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, doublevalue);
}
else
//Salesforce DataType = Boolean
if(fieldType == 'boolean')
{
if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null && objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != ''){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, Boolean.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}
}
else
//Salesforce DataType = Date
if(fieldType == 'date')
{
if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null && objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != ''){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, Date.valueOf((String)objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, null);
}
}
else
//Salesforce DataType = Date
if(fieldType == 'datetime')
{
if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null && objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != ''){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, DateTime.valueOf(String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)).replace('T',' ')));
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, null);
}
}
else
//Salesforce DataType = LookUp
if(fieldType == 'reference')
{
String relationshipName = fieldResult.getRelationshipName();
String parentObjectName = fieldResult.getReferenceTo()[0].getDescribe().getName();
SObject parentObj = fieldResult.getReferenceTo()[0].newSObject();
// Define Variant and Inventory Item lookup relationship
if(parentObjectName == 'HIC_ShopifySync__Variant__c' && objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null){
System.debug('ObjectName--'+ObjectName);
if(ObjectName=='OrderItem' || ObjectName=='DraftOrderItem' || ObjectName=='OpportunityLineItem' || ObjectName == 'HIC_ShopifySync__Checkout_LineItem__c'){
parentObj.put('HIC_ShopifySync__Shopify_id__c',String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}else{
parentObj.put('HIC_ShopifySync__Inventory_Item_Id__c',String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}
sObjRecord.putSObject(relationshipName, parentObj);
}
// Define Account's Shopify External ID
else if((parentObjectName == 'Account' || parentObjectName == 'Contact') && objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null){
if(configurationList[0].HIC_ShopifySync__Person_Account__c){
if(String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)).contains('Person')){
parentObj.put('HIC_ShopifySync__Shopify_Id__c',String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}else{
parentObj.put('HIC_ShopifySync__Shopify_Id__c','Person '+String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}
}else{
if(String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)).containsIgnoreCase('business')){
parentObj.put('HIC_ShopifySync__Shopify_Id__c',String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}else{
parentObj.put('HIC_ShopifySync__Shopify_Id__c','Business '+String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
}
}
sObjRecord.putSObject(relationshipName, parentObj);
}else if(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c) != null){
parentObj.put('HIC_ShopifySync__Shopify_Id__c',String.valueOf(objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)));
sObjRecord.putSObject(relationshipName, parentObj);
}else{
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, null);
}
}
else
{
// Salesforce Single field Mapping and DataType = string
String stringvalue = '';
if(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.contains(',')){
for(String shopifyField : fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c.split(',')){
if(objectMap.containsKey(shopifyField)){
Object objectFieldValue = objectMap.get(shopifyField);
if(objectFieldValue != null){
stringvalue += String.valueof(objectFieldValue)+' ';
}
}
}
}else{
if(objectMap.containsKey(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c)){
Object objectFieldValue = objectMap.get(fieldMappingObj.HIC_ShopifySync__Shopify_Fields__c);
if(objectFieldValue != null){
stringvalue += JSON.serialize(objectFieldValue).removeEnd('"').removeStart('"');
}
}
}
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c, checkFieldLengthAndReturnValue(fieldResult, stringvalue, configurationList));
}
}
}
// Insert Default Values into the Salesforce Field which are required in the Salesforce
if((!fieldResult.isNillable() || ((ObjectName == 'Account'|| ObjectName == 'Personaccount' ) && (fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'LastName' || fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'lastname' || fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'name' || fieldMappingObj.HIC_ShopifySync__SF_Field__c == 'Name' ))) && (sObjRecord.get(fieldMappingObj.HIC_ShopifySync__SF_Field__c) == null || sObjRecord.get(fieldMappingObj.HIC_ShopifySync__SF_Field__c) == '' )){ if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'decimal' || fieldType == 'percent'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c , Double.valueof(1));
}
else if(fieldType == 'integer'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c , Integer.valueof(1));
}
else if(fieldType == 'String'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,'REQ'+string.valueof(system.now().getTime()+ i+1)) ;
}else if(fieldType == 'date'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,System.today());
}else if(fieldType == 'datetime'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,System.now());
}else if(fieldType == 'email'){
sObjRecord.put(fieldMappingObj.HIC_ShopifySync__SF_Field__c,string.valueof(i++)+ 'required@hic.com');
}
}
/************************** SHOPIFY SINGLE FIELD MAPPING END ***************************************/
}
// Return Object with Salesfroce Field And Shopify Field Value base user configure field mapping on the page
System.debug('sObjRecord---'+sObjRecord);
return sObjRecord;
}
/**************************************checkFieldLengthAndReturnValue*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Use for Dynamic Field Mapping
* Map Salesfoce field with Shopify Field
* Map Shopify Field values into Salesforce based on Salesforce Field DataType
* Retun Maped Salesforce and Shopify Field Values
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param Schema.DescribeFieldResult fieldResult - for get field length and more details
* @param String body - Shopify Entity's field value
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static String checkFieldLengthAndReturnValue(Schema.DescribeFieldResult fieldResult, String body, List<HIC_ShopifySync__HIC_Configuration__c> configurationList){
new HIC_ShopifyUtility(configurationList);
if(fieldResult.getLength() > 0 && body != null && body != ''){
if( body.length() <= fieldResult.getLength()){
return body;
}else{
return body.subString(0,fieldResult.getLength());
}
}else{
return '';
}
}
/**************************************deleteCustomAppFromStore*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Delete Custom app form Shopify Store - When uninstall package from Salesforce
* more details: https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Boolean deleteCustomAppFromStore(List<HIC_ShopifySync__HIC_Configuration__c > configurationList){
//new HIC_ShopifyUtility(configurationList);
for(HIC_ShopifySync__HIC_Configuration__c config : configurationList){
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String endPointValue = config.HIC_ShopifySync__Shopify_URL__c + '/admin/api_permissions/current.json';
req.setEndpoint(endPointValue);
req.setClientCertificateName('Shopify');
req.setHeader('X-Shopify-Access-Token', config.HIC_ShopifySync__Private_Key_Password__c);
req.setHeader('content-type', 'application/json');
req.setMethod('DELETE');
req.setTimeout(120000);
try {
HttpResponse res ;
res = h.send(req);
responseBody = res.getBody();
if(res.getStatusCode() == 200){
return true;
}
}catch(Exception e){
return false;
}
}
return false;
}
/**************************************FetchCustomerJob*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Delete Custom app form Shopify Store - When uninstall package from Salesforce
* more details: https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api
* ──────────────────────────────────────────────────────────────────────────────────────────────
* @param List<HIC_ShopifySync__HIC_Configuration__c > configurationList - ListofConfigurationSettings
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public without sharing class FetchCustomerJob implements Queueable, Database.AllowsCallouts {
private final String configId;
private final String customerId;
private final String store;
private final String originalPayload;
public FetchCustomerJob(String configId, String customerId, String store, String originalPayload) {
this.configId = configId;
this.customerId = customerId;
this.store = store;
this.originalPayload = originalPayload;
}
public void execute(QueueableContext ctx) {
try {
List<HIC_ShopifySync__HIC_Configuration__c> configList = [
SELECT Name,
HIC_ShopifySync__Shopify_URL__c,
HIC_ShopifySync__Private_Key_Password__c
FROM HIC_ShopifySync__HIC_Configuration__c
WHERE Id = :configId
LIMIT 1
];
if (configList.isEmpty()) {
System.debug('No configuration found for Id: ' + configId);
return;
}
HIC_ShopifySync__HIC_Configuration__c config = configList[0];
if (String.isBlank(config.HIC_ShopifySync__Shopify_URL__c) ||
String.isBlank(config.HIC_ShopifySync__Private_Key_Password__c)) {
System.debug('Missing Shopify URL or Access Token for config: ' + configId);
return;
}
Http http = new Http();
HttpRequest req1 = new HttpRequest();
String endpoint1 = config.HIC_ShopifySync__Shopify_URL__c +
'/admin/customers/' + customerId + '.json';
req1.setEndpoint(endpoint1);
req1.setHeader('X-Shopify-Access-Token', config.HIC_ShopifySync__Private_Key_Password__c);
req1.setHeader('Content-Type', 'application/json');
req1.setMethod('GET');
HttpResponse res1 = http.send(req1);
if (res1.getStatusCode() != 200) {
System.debug('Shopify Customer Error: ' + res1.getStatusCode() + ' → ' + res1.getBody());
return;
}
Map<String, Object> resMap =
(Map<String, Object>) JSON.deserializeUntyped(res1.getBody());
if (resMap == null || !resMap.containsKey('customer')) {
System.debug('Unexpected Customer JSON: ' + res1.getBody());
return;
}
Map<String, Object> customerJson =
(Map<String, Object>) resMap.get('customer');
Integer ordersCount = 0;
if (customerJson.containsKey('orders_count')) {
ordersCount = Integer.valueOf(String.valueOf(customerJson.get('orders_count')));
}
System.debug('Shopify Orders Count = ' + ordersCount);
List<HIC_ShopifySync__HIC_Field_Mapping__c> mappingList = [
SELECT Id,
HIC_ShopifySync__Shopify_Fields__c,
HIC_ShopifySync__Object_Name__c
FROM HIC_ShopifySync__HIC_Field_Mapping__c
WHERE HIC_ShopifySync__Object_Name__c IN ('Account', 'Contact', 'PersonAccount')
AND HIC_ShopifySync__Shopify_Fields__c = 'metafields'
AND HIC_ShopifySync__Store__c = :config.Name
LIMIT 1
];
String metafieldsPayload = null;
if (!mappingList.isEmpty()) {
HttpRequest req2 = new HttpRequest();
String endpoint2 = config.HIC_ShopifySync__Shopify_URL__c +
'/admin/customers/' + customerId + '/metafields.json';
req2.setEndpoint(endpoint2);
req2.setHeader('X-Shopify-Access-Token', config.HIC_ShopifySync__Private_Key_Password__c);
req2.setHeader('Content-Type', 'application/json');
req2.setMethod('GET');
HttpResponse res2 = http.send(req2);
if (res2.getStatusCode() == 200) {
metafieldsPayload = res2.getBody();
} else {
System.debug('Metafields API Error: ' + res2.getStatusCode() + ' → ' + res2.getBody());
}
}
if (metafieldsPayload != null) {
try {
Map<String, Object> metaJson =
(Map<String, Object>) JSON.deserializeUntyped(metafieldsPayload);
if (metaJson != null && metaJson.containsKey('metafields')) {
List<Object> metafieldsList =
(List<Object>) metaJson.get('metafields');
// Insert metafields list into customer JSON
customerJson.put('metafields', metafieldsList);
}
} catch (Exception mergeEx) {
System.debug('Error merging metafields: ' + mergeEx.getMessage());
}
}
String finalMergedPayload = JSON.serialize(customerJson);
// Deserialize to modify email
Map<String, Object> customerMap =
(Map<String, Object>) JSON.deserializeUntyped(finalMergedPayload);
// Normalize email to lowercase
if (customerMap.containsKey('email') && customerMap.get('email') != null) {
customerMap.put(
'email',
String.valueOf(customerMap.get('email')).toLowerCase()
);
}
// Serialize back and overwrite SAME variable
finalMergedPayload = JSON.serialize(customerMap);
System.debug('Updated finalMergedPayload: ' + finalMergedPayload);
System.enqueueJob(
new RouteAfterCount(
finalMergedPayload,
store,
ordersCount
)
);
} catch (Exception e) {
System.debug('FetchCustomerJob Error: ' + e.getMessage());
}
}
}
// ------------------------------------------------------------
public without sharing class RouteAfterCount implements Queueable {
private final String payload;
private final String store;
private final Integer ordersNow;
public RouteAfterCount(String payload, String store, Integer ordersNow) {
this.payload = payload;
this.store = store;
this.ordersNow = ordersNow;
}
public void execute(QueueableContext ctx) {
try {
// Fetch configuration
List<HIC_ShopifySync__HIC_Configuration__c> configList = [
SELECT HIC_ShopifySync__Enable_Lead__c,
HIC_ShopifySync__Upsert_Customer_basis_on_Email__c,
HIC_ShopifySync__Person_Account__c
FROM HIC_ShopifySync__HIC_Configuration__c
WHERE Name = :store
LIMIT 1
];
System.debug('payload-->>' + payload);
Boolean enableLead = false;
Boolean upsertCustomerOnEmail = false;
if (!configList.isEmpty()) {
enableLead = configList[0].HIC_ShopifySync__Enable_Lead__c;
upsertCustomerOnEmail = configList[0].HIC_ShopifySync__Upsert_Customer_basis_on_Email__c;
} else {
System.debug('No configuration found for store: ' + store);
}
// -----------------------------------------
// Extract email from Shopify payload (ROOT LEVEL)
// -----------------------------------------
Map<String, Object> parsed =
(Map<String, Object>) JSON.deserializeUntyped(payload);
String customerEmail = String.valueOf(parsed.get('email'));
System.debug('Extracted Shopify Email ==>' + customerEmail);
if (ordersNow == 0 && enableLead) {
// Case 1.1 — DO NOT UPSERT ON EMAIL
if (!upsertCustomerOnEmail) {
System.debug('Lead creation because upsertCustomerOnEmail = FALSE');
HIC_ShopifySync.UpdateCustomerFromShopify.createLead(payload, store);
}
// Case 1.2 — UPSERT ON EMAIL = TRUE
else {
System.debug('upsertCustomerOnEmail = TRUE, Checking Contact by Email...');
List<Contact> conLst = [
SELECT Id, Email
FROM Contact
WHERE Email = :customerEmail order by createddate DESC
LIMIT 1
];
System.debug('Contact Lookup Result ==>' + conLst);
if (!conLst.isEmpty()) {
System.debug('Contact exists. Calling createAccountContact()');
HIC_ShopifySync.UpdateCustomerFromShopify.createAccountContact(payload, store);
}
else {
// CONTACT NOT FOUND → CREATE LEAD BRANCH
System.debug('No Contact found. Creating Lead...');
HIC_ShopifySync.UpdateCustomerFromShopify.createLead(payload, store);
}
}
}
else if (ordersNow > 0 && enableLead) {
System.debug('Existing Lead detected. Converting...');
HIC_ShopifySync.UpdateCustomerFromShopify.convertLead(payload, store);
}
else {
System.debug('Lead disabled. Calling createAccountContact().');
HIC_ShopifySync.UpdateCustomerFromShopify.createAccountContact(payload, store);
}
} catch (Exception e) {
System.debug('RouteAfterCount Error: ' + e.getMessage());
}
}
}
/*
* ADDED NEW METHOD FROM SHOPIFYCONTROLLER CLASS
*/
/********************************************************************************************
* Created Date:- 29/04/2024
* Modified Date :- 29/04/2024
* Description:- This method is used to count the records of the Shopify.
* We have to pass the store name and the object names to count the number of records
* at shopify side.
* Object name:- locations, products, customers(Account)variants, orders, collects,
* locations, draft_orders
*
*
*
**********************************************************************************************/
public static string getShopifyRecordCounts(String storeUrl, String objectName, String password){
String result = 'Error!';
try{
Http h = new Http();
HttpRequest req = new HttpRequest();
String endPointValue;
if(objectName == 'orders'){
endPointValue = storeUrl + 'admin/' + objectName + '/count.json?status=any';
}else{
endPointValue = storeUrl + 'admin/' + objectName + '/count.json';
}
req.setEndpoint(endPointValue);
req.setMethod('GET');
req.setTimeout(120000);
req.setHeader('X-Shopify-Access-Token', password);
req.setHeader('content-type', 'application/json');
req.setMethod('GET');
HttpResponse res = h.send(req);
if (res.getStatusCode() == 200) {
result = res.getBody();
}
}catch(Exception e){
result = '@@@ some Error Occured at line : ' +e.getLineNumber() +' with Error : ' +e.getMessage();
}
return result;
}
/**************************************oauthLogin*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* METHOD TO FETCH THE ACCESS TOKEN
*
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
/**
* ROTATION-SAFE: this method no longer performs its own grant_type=refresh_token exchange.
*
* It used to. Under mandatory Refresh Token Rotation that exchange consumed the stored refresh token
* and issued a replacement, but the replacement was persisted through ShopifyController.getCryptoKey()
* — a CheckAccessibility-filtered dynamic query that returns null/empty whenever the running user
* lacks FLS. In that case the old code logged 'No refresh token found' and then STILL RETURNED the
* access token as if everything had worked, discarding the only copy of the new refresh token. The
* DML was also wrapped in a catch that only called System.debug. Either way the org was left holding
* a dead token, with no error surfaced, and died on the next refresh days later.
*
* All rotation is now centralised in TokenService, which locks the row, persists fail-loud, and never
* throws a rotated token away. The refreshToken/clientId/clientSecret arguments are retained for
* signature compatibility but are no longer used to mint tokens.
*/
public static String oauthLogin(String refreshToken, String clientIdProduction, String clientSecretproduction ){
if (String.isBlank(refreshToken)) {
return 'No access token found';
}
try {
String token = TokenService.getFreshAccessToken(null, false);
return String.isNotBlank(token) ? token : 'No access token found';
} catch (TokenService.ReauthRequiredException e) {
return 'INVALID_GRANT';
} catch (Exception e) {
System.debug('HIC_ShopifyUtility.oauthLogin delegated refresh failed: ' + e.getMessage());
return 'No access token found';
}
}
public class readToken {
public string access_token { get; set; }
public string instance_url { get; set; }
}
/**************************************CheckshopifycertificateandRemotesite*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Verfiy RemoteSite Setting exist or not
* @param String Urltype - certificate/RemoteSite based on value check existance
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Boolean CheckshopifycertificateandRemotesite(String Urltype, String AccessToken, String SFdomainUrl) {
Boolean exist = false;
HttpRequest req = new HttpRequest();
req.setHeader(
'Authorization',
'Bearer ' + AccessToken
);
req.setHeader('Content-Type', 'application/json');
String query;
if (Urltype == 'certificate') {
query = 'select+id,+DeveloperName+from+Certificate+where+DeveloperName=+\'Shopify\'+and+ExpirationDate+>=+today';
system.debug('@ this is the certificate block :: '+query);
} else {
query =
'select+id,+EndpointUrl+from+Remotesitesetting+where+EndpointUrl=+\'' +
SFdomainUrl +
'\'';
}
String domainUrl = URL.getOrgDomainUrl().toExternalForm();
req.setEndpoint(
domainUrl + '/services/data/v58.0/tooling/query/?q=' + query
);
req.setMethod('GET');
req.setTimeout(120000);
try{
Http h = new Http();
HttpResponse response;
String CertificateResponse;
system.debug('@@@ this is the request ::: ' + req);
if (!Test.isRunningTest()) {
response = h.send(req);
CertificateResponse = response.getBody().trim();
system.debug('This is the certificate response:::: ' + CertificateResponse);
} else {
CertificateResponse = '{"size":1,"totalSize":1,"done":true,"queryLocator":null,"entityTypeName":"Certificate","records":[{"attributes":{"type":"Certificate","url":"/services/data/v58.0/tooling/sobjects/Certificate/0P12v000006b5K9CAI"},"Id":"0P12v000006b5K9CAI","DeveloperName":"Shopify"}]}';
}
Map<String, object> mapofcertificate = (Map<String, object>) JSON.deserializeUntyped(CertificateResponse);
if (
!mapofcertificate.isempty() &&
mapofcertificate != null &&
mapofcertificate.containskey('size')
) {
if (Integer.valueof(mapofcertificate.get('size')) > 0) {
exist = true;
}
}
}catch(Exception e){
exist = false;
}
return exist;
}
/**************************************checkCreds*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Verify Shopify Credetials via callout into the Shopify
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Boolean checkCreds(String shopifyUrl, String password){
try{
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String endPointValue = shopifyUrl + '/admin/shop.json';
req.setEndpoint(endPointValue);
//Adding certificate to HTTP Requests
req.setClientCertificateName('Shopify');
req.setHeader('X-Shopify-Access-Token', password);
req.setHeader('content-type', 'application/json');
req.setMethod('GET');
req.setTimeout(120000);
HttpResponse res ;
res = h.send(req);
responseBody = res.getBody();
if(res.getStatusCode() == 200){
return True;
}
}catch(Exception e){
return false;
}
return false;
}
/**************************************CheckingRemotesiteExistence*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Verfiy RemoteSite Setting exist or not
* @param String SFdomainUrl - RemoteSite based on value check existance
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static boolean CheckingRemotesiteExistence(String SFdomainUrl, String accessToken, String OrgURl){
boolean exist = false;
try{
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + accessToken);
req.setHeader('Content-Type', 'application/json');
String query='select+id,+EndpointUrl+from+Remotesitesetting+where+EndpointUrl=+\''+SFdomainUrl+'\'';
req.setEndpoint(OrgURl+'/services/data/v58.0/tooling/query/?q='+query);
req.setMethod('GET');
req.setTimeout(120000);
Http h = new Http();
HttpResponse response;
String RemotesitesettingResponse;
if(!Test.isRunningTest()){
response = h.send(req);
RemotesitesettingResponse = response.getBody().trim();
}else{
RemotesitesettingResponse = '{"size":0,"totalSize":1,"done":true,"queryLocator":null,"entityTypeName":"Certificate","records":[{"attributes":{"type":"Certificate","url":"/services/data/v58.0/tooling/sobjects/Certificate/0P12v000006b5K9CAI"},"Id":"0P12v000006b5K9CAI","DeveloperName":"Shopify"}]}';
}
if(RemotesitesettingResponse == null || RemotesitesettingResponse =='') return false;
Map<String,object> mapofRemoteSitesettings = (Map<String,object>) JSON.deserializeUntyped(RemotesitesettingResponse);
if(!mapofRemoteSitesettings.isempty() && mapofRemoteSitesettings != null && mapofRemoteSitesettings.containskey('size')){
if(Integer.valueof(mapofRemoteSitesettings.get('size')) > 0){
exist = true;
}
}
return exist;
}catch(Exception e){
System.debug('Error '+ e.getMessage() + ' Line Number '+ e.getLineNumber());
return exist;
}
}
/**************************************CheckingRemotesiteExistence*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Verfiy RemoteSite Setting exist or not
* @param String SFdomainUrl - RemoteSite based on value check existance
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static Boolean checkRemotesiteExists(String remoteSiteUrl, String domainUrl){
Boolean result = false;
try{
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); //Get user Session ID
req.setHeader('Content-Type', 'application/json');
String query='select+id,+EndpointUrl+from+Remotesitesetting+where+EndpointUrl=+\''+remoteSiteUrl+'\'';
req.setEndpoint(domainUrl+'/services/data/v58.0/tooling/query/?q='+query);
req.setMethod('GET');
req.setTimeout(120000);
Http h = new Http();
HttpResponse response;
String RemotesitesettingResponse;
if(!Test.isRunningTest()){
response = h.send(req);
RemotesitesettingResponse = response.getBody().trim();
}else{
RemotesitesettingResponse = '{"size":0,"totalSize":1,"done":true,"queryLocator":null,"entityTypeName":"Certificate","records":[{"attributes":{"type":"Certificate","url":"/services/data/v58.0/tooling/sobjects/Certificate/0P12v000006b5K9CAI"},"Id":"0P12v000006b5K9CAI","DeveloperName":"Shopify"}]}';
}
if(RemotesitesettingResponse == null || RemotesitesettingResponse =='') return false;
Map<String,object> mapofRemoteSitesettings = (Map<String,object>) JSON.deserializeUntyped(RemotesitesettingResponse);
if(!mapofRemoteSitesettings.isempty() && mapofRemoteSitesettings != null && mapofRemoteSitesettings.containskey('size')){
if(Integer.valueof(mapofRemoteSitesettings.get('size')) > 0){
result = true;
}
}
return result;
}Catch(Exception e){
System.debug('Exception---- '+ e);
return result;
}
}
/**************************************checkAccesScope*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* check Shopify store access for the entity
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
public static String checkAccesScope(String shopifyUrl, String password){
Http h = new Http();
HttpRequest req = new HttpRequest();
String responseBody;
String AccessResponse = '';
String endPointValue = shopifyUrl + '/admin/oauth/access_scopes.json';
req.setEndpoint(endPointValue);
req.setClientCertificateName('Shopify');
req.setHeader('X-Shopify-Access-Token', password);
req.setHeader('content-type', 'application/json');
req.setMethod('GET');
req.setTimeout(120000);
try {
HttpResponse res ;
res = h.send(req);
responseBody = res.getBody();
if(res.getStatusCode() == 200){
map<string, Object> main = (map<string,object>) JSON.deserializeUntyped(responseBody);
if(!main.isempty() && main.containskey('access_scopes')){
List<Object> objectList = (list<object>) main.get('access_scopes');
for(object accessobj : objectList){
map<String,object> accessScopeMap = (map<string,object>)accessobj ;
if(!accessScopeMap.isEmpty() && accessScopeMap.containskey('handle') && accessScopeMap.get('handle') != null){
AccessResponse += accessScopeMap.get('handle')+ ',';
}
}
}if(AccessResponse != null || AccessResponse != '' ){
AccessResponse.removeEnd(',');
return AccessResponse;
}
}
}catch(Exception e){
return null;
}
return null;
}
}