/* ********************************************************* Apex Class Name : ShopifyController Created Date : 17/4/2024 @description : This class handles all LWC Component's 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 : SME Team Modification Log: Ver Date Author 1.0 03/05/2024 SME Team ********************************************************* */ public with sharing class ShopifyController { private static DescribeSObjectResult getSchemaType(String objectName){ return Schema.getGlobalDescribe().get(objectName).getDescribe(); } public static List getCryptoKey(){ DescribeSObjectResult configCustomSettingSchema = getSchemaType('HIC_ShopifySync__Configuration__c'); List cyptokeyquery = new List(); String query = 'select ' + Checkaccessibility.isAccessible('id,HIC_ShopifySync__Store__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__Refresh_Token__c,HIC_ShopifySync__Access_Token__c', configCustomSettingSchema ) +' from HIC_ShopifySync__Configuration__c where ' +Checkaccessibility.isAccessible( 'Name', configCustomSettingSchema ) +' = \'Default\' limit 1'; String sanitizedQuery = String.escapeSingleQuotes(query).remove('\\'); cyptokeyquery = database.query(sanitizedQuery); if (cyptokeyquery.isEmpty()){ return null; }else{ return cyptokeyquery; } } /* ********************************************************* @Method Name : removeStore @author : SME Team @description : To remove particular store configuration, webhooks, and field mappings. This method deletes all related data for the specified store, including: - Field mappings associated with the store - Configurations related to the store - Webhooks where the webhook ID is not null for the store The method also checks for accessibility and deletability permissions before deleting data. @param : store (String) - The name of the store to be removed. @return : Boolean - True if the removal process is successful, false otherwise. ******************************************************** */ @AuraEnabled public static Boolean removeStore(String store){ try{ DescribeSObjectResult fielMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); List listofallcustomSetting = new List(); String query = ' select '+CheckAccessibility.isAccessible('id',fielMappingSchema)+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fielMappingSchema)+' = \''+store+'\'WITH USER_MODE LIMIT 49999'; String sanitizedQuery = String.escapeSingleQuotes(query).remove('\\'); listofallcustomSetting = database.query(sanitizedQuery); if(!listofallcustomSetting.isEmpty()){ if(CheckAccessibility.isDeletable('HIC_ShopifySync__HIC_Field_Mapping__c') && !store.equalsIgnoreCase('default')){ database.delete (listofallcustomSetting,True,AccessLevel.USER_MODE); } } List ConfigListToDelete = new List(); DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); String query1 = ' select '+CheckAccessibility.isAccessible('id,HIC_ShopifySync__API_Key__c,HIC_ShopifySync__Private_Key_Password__c,HIC_ShopifySync__Shopify_URL__c',configSchema)+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',configSchema)+' = \''+store+'\' LIMIT 49999'; String sanitizedQuery1 = String.escapeSingleQuotes(query1).remove('\\'); ConfigListToDelete = database.query(sanitizedQuery1); List webhookList = [Select HIC_ShopifySync__Shopify_Object__c,HIC_ShopifySync__DML_Type__c,HIC_ShopifySync__SF_URL_Mapping__c, HIC_ShopifySync__Topic__c, HIC_ShopifySync__Webhook_Id__c from HIC_ShopifySync__HIC_Webhook__c where HIC_ShopifySync__Store__c =: store AND HIC_ShopifySync__Webhook_Id__c <> null WITH USER_MODE LIMIT 500]; if(webhookList != null && !webhookList?.isEmpty()){ for(HIC_ShopifySync__HIC_Webhook__c webhook:webhookList){ HICWebhookUtility.deleteWebhook(webhook.HIC_ShopifySync__Shopify_Object__c, webhook.HIC_ShopifySync__DML_Type__c, store, JSON.serialize(ConfigListToDelete)); } } if(!ConfigListToDelete.isEmpty()){ if(CheckAccessibility.isDeletable('HIC_ShopifySync__HIC_Configuration__c')){ database.delete (ConfigListToDelete,True,AccessLevel.USER_MODE); } } return true; }catch(Exception e){ return false; } } /* ********************************************************* @Method Name : fetchAccount @author : SME Team @description : Retrieves a list of Account records based on a search keyword. @param : searchKeyWord (String) - The keyword used for searching Account records. @return : List - A list of Account records matching the search keyword. ******************************************************** */ @AuraEnabled(cacheable=true) public static List fetchAccount(String searchKeyWord) { DescribeSObjectResult accountSchema = getSchemaType('account'); String searchKey = searchKeyWord + '%'; List returnList = new List(); List lstOfAccount=new List(); try{ // CHECK PERSON ACOUNT IS ENABLED Boolean checkPersonAccountEnabled = Schema.sObjectType.Account.fields.getMap().containsKey( 'isPersonAccount' ); String query; if(checkPersonAccountEnabled){ query = 'select ' + Checkaccessibility.isAccessible('id, Name', accountSchema) + ' from account where '+Checkaccessibility.isAccessible('IsPersonAccount', accountSchema)+' = false AND ' + Checkaccessibility.isAccessible('Name', accountSchema) + ' LIKE :searchKey LIMIT 10'; }else{ query = 'select ' + Checkaccessibility.isAccessible('id, Name', accountSchema) + ' from account where '+ Checkaccessibility.isAccessible('Name', accountSchema) + ' LIKE :searchKey LIMIT 10'; } // String query = // 'select ' + // Checkaccessibility.isAccessible('id, Name', accountSchema) + // ' from account where '+Checkaccessibility.isAccessible('IsPersonAccount', accountSchema)+' = false AND ' + // Checkaccessibility.isAccessible('Name', accountSchema) + // ' LIKE :searchKey LIMIT 10'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); lstOfAccount=Database.query(finalQuery); for (Account acc : lstOfAccount) { returnList.add(acc); } }catch(Exception e){ System.debug('Error in fetching account' + e.getMessage()); } return returnList; } /* ********************************************************* @Method Name : getConfigration @author : SME Team @description : Retrieves the saved configuration to display on the page. * The configuration is fetched from HIC_ShopifySync__Configuration__c * and returned in the form of a JSON string. @return : String - JSON representation of HIC_ShopifySync__Configuration__c ******************************************************** */ @AuraEnabled public static String getConfigration() { try { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } List config = new List(); String query1 = 'select ' + Checkaccessibility.isAccessible( 'id,HIC_ShopifySync__Store__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,name,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c', 'HIC_ShopifySync__HIC_Configuration__c' ) + ' from HIC_ShopifySync__HIC_Configuration__c Where HIC_ShopifySync__Store__c != \'Default\' order by LastModifiedDate desc Limit 1'; String finalQuery1 = String.escapeSingleQuotes(query1).remove('\\'); config = database.query(finalQuery1); if (config.isEmpty()) { String query2 = 'select ' + Checkaccessibility.isAccessible( 'id,HIC_ShopifySync__Store__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,name,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c', 'HIC_ShopifySync__HIC_Configuration__c' ) + ' from HIC_ShopifySync__HIC_Configuration__c Where HIC_ShopifySync__Store__c = \'Default\' order by LastModifiedDate desc Limit 1'; String finalQuery2 = String.escapeSingleQuotes(query2).remove('\\'); config = database.query(finalQuery2); config[0].Id = null; config[0].HIC_ShopifySync__Refresh_Token__c = cyptokeyquery[0] .HIC_ShopifySync__Refresh_Token__c; return JSON.serialize(config[0]); } config[0].HIC_ShopifySync__Refresh_Token__c = cyptokeyquery[0] .HIC_ShopifySync__Refresh_Token__c; if ( config[0].HIC_ShopifySync__Private_Key_Password__c != null && config[0].HIC_ShopifySync__Private_Key_Password__c != '' ) { String password = String.valueof( config[0].HIC_ShopifySync__Private_Key_Password__c ); Blob cryptoKey = Blob.valueOf( String.valueof(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c) ); Blob data = Blob.valueOf(password); Blob encryptedData = Crypto.encryptWithManagedIV( 'AES128', cryptoKey, data ); String b64Data = EncodingUtil.base64Encode(encryptedData) + 'True'; if (b64Data != null && b64Data != '') { config[0].HIC_ShopifySync__Private_Key_Password__c = b64Data; } } return JSON.serialize(config[0]); } catch (Exception e) { return null; } } /* ********************************************************* @Method Name : getConfigrations @author : SME Team @description : This method retrieves the configurations and encrypts the password. * It fetches configuration data from HIC_ShopifySync__HIC_Configuration__c * and encrypts the HIC_ShopifySync__Private_Key_Password__c field. @Return : String - JSON representation of the configuration list ******************************************************** */ @AuraEnabled public static String getConfigrations() { try { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } List configList = new List(); String query = 'select ' + Checkaccessibility.isAccessible( 'id,HIC_ShopifySync__Store__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,name,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c', 'HIC_ShopifySync__HIC_Configuration__c' ) + ' from HIC_ShopifySync__HIC_Configuration__c Where HIC_ShopifySync__Store__c != \'Default\' '; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); configList = database.query(finalQuery); if (configList.isEmpty()){ return null; } for (HIC_ShopifySync__HIC_Configuration__c config : configList) { if ( config.HIC_ShopifySync__Private_Key_Password__c != null && config.HIC_ShopifySync__Private_Key_Password__c != '' ) { String password = String.valueof( config.HIC_ShopifySync__Private_Key_Password__c ); Blob cryptoKey = Blob.valueOf( String.valueof(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c) ); Blob data = Blob.valueOf(password); Blob encryptedData = Crypto.encryptWithManagedIV( 'AES128', cryptoKey, data ); String b64Data = EncodingUtil.base64Encode(encryptedData); if (b64Data != null && b64Data != '') { config.HIC_ShopifySync__Private_Key_Password__c = b64Data; } } } return JSON.serialize(configList); } catch (Exception e) { return e.getMessage() + '' + e.getLineNumber(); } } /* ********************************************************* @Method Name : getConfigrationForDynamicRow @author : SME Team @description : Get Configuration for check current User what select like Opportunity/draft Order If not selected then based on configuration will hide and show field mapping @param : store (String) - Name of the store @Return : String - JSON representation of the configuration list ******************************************************** */ @AuraEnabled public static String getConfigrationForDynamicRow(string store) { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); List config = new List(); //HIC_ShopifySync__Private_Key_Password__c String fieldsToQueryforconfig = 'id , HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Private_Key_Password__c, CurrencyIsoCode, Name, HIC_ShopifySync__Specify_Close_Date__c,HIC_ShopifySync__Default_Account__c,HIC_ShopifySync__Default_Field_Mapping__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__Account_Contact__c,HIC_ShopifySync__Person_Account__c,HIC_ShopifySync__Store__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c'; String query= 'select ' + Checkaccessibility.isAccessible( fieldsToQueryforconfig, configSchema ) + ' from HIC_ShopifySync__HIC_Configuration__c where ' + CheckAccessibility.isAccessible( 'HIC_ShopifySync__Store__c', configSchema ) + ' = \'' + store + '\' LIMIT 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config=Database.query(finalQuery); if (config != null && !config.isEmpty()) { if(config[0].HIC_ShopifySync__Private_Key_Password__c != null && config[0].HIC_ShopifySync__Private_Key_Password__c != ''){ String password = String.valueof(config[0].HIC_ShopifySync__Private_Key_Password__c); Blob cryptoKey = Blob.valueOf(String.valueof(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c)); Blob data = Blob.valueOf(password); Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey, data ); String b64Data = EncodingUtil.base64Encode(encryptedData)+'True'; if(b64Data != null && b64Data != ''){ config[0].HIC_ShopifySync__Private_Key_Password__c = b64Data; } } system.debug('config[0]' + config[0]); return JSON.serialize(config[0]); } else { return null; } } /* ********************************************************* @Method Name : getBaseValue @author : SME Team @description : Encrypts the given password and returns its Base64 encoded value. The encryption is performed using a cryptographic key stored in Salesforce. @param : password (String) - The password to be encrypted. @Return : String - The Base64 encoded encrypted password. ******************************************************** */ @AuraEnabled public static string getBaseValue(String password){ String result = 'Error'; try { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } Blob cryptoKey = Blob.valueOf(String.valueof(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c)); Blob data = Blob.valueOf(password); Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey, data ); String b64Data = EncodingUtil.base64Encode(encryptedData)+'True'; if(b64Data != null && b64Data != ''){ result = b64Data; } } catch (Exception ex) { System.debug('@@@ Exception Occured at line :: '+ex.getLineNumber()+' With Message :: '+ex.getMessage()); } return result; } /* ********************************************************* @Method Name : isSiteSupportedOrg @author : SME Team @description : Check if the Salesforce org has access to Site object @param : @Return : Boolean ******************************************************** */ public static Boolean isSiteSupportedOrg(){ try{ // List organizationTypeList = new List{'Starter Edition', 'Essentials Edition', 'Pro Suite Edition'}; //List organizationTypeList = new List{'Starter Edition'}; DescribeSObjectResult siteSchema = getSchemaType('Site'); if(siteSchema.isAccessible()){ return true; // DescribeSObjectResult organizationSchema = getSchemaType('organization'); // Schema.SObjectField isSandboxFieldDescribe = organizationSchema.fields.getMap().get('IsSandbox'); // if(organizationSchema.isAccessible()){ // Organization orgRecord = [select id,issandbox,OrganizationType from organization WITH USER_MODE LIMIT 1 ]; // if(!organizationTypeList.contains(orgRecord.OrganizationType)){ // return true; // } // } } }catch(Exception ex){ return false; } return false; } /* ********************************************************* @Method Name : getSiteURLs @author : SME Team @description : Get User Site URls in Salesforce @param : @Return : String - list of sites ******************************************************** */ @AuraEnabled public static String getSiteURLs() { List siteList = new List(); list listofsitewrapper = new List(); List organizationTypeList = new List{'Starter Edition', 'Professional Edition'}; if(isSiteSupportedOrg()){ DescribeSObjectResult siteSchema = getSchemaType('Site'); String query= 'SELECT ' + Checkaccessibility.isAccessible( 'id,GuestUserId, Name,MasterLabel, Subdomain, SiteType,UrlPathPrefix', siteSchema ) + ' FROM Site WHERE '; DescribeSObjectResult organizationSchema = getSchemaType('organization'); Organization orgRecord = [select id,issandbox,OrganizationType from organization WITH USER_MODE LIMIT 1 ]; if(organizationTypeList.contains(orgRecord.OrganizationType)){ query = query+Checkaccessibility.isAccessible('SiteType', siteSchema)+' = \'ChatterNetwork\' AND '; } query = query+Checkaccessibility.isAccessible('Status', siteSchema) +' = \'Active\' Limit 1000'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); siteList=Database.query(finalQuery); system.debug('+++siteList' + siteList); set setofsiteid = new Set(); Map mapofsiteidvssiteurl = new Map(); for (SObject s : siteList) { setofsiteid.add(String.valueof(s.id)); } List siteFullUrlList = new List(); // list listOfsitedetail = new List(); String siteDetailQuery = 'SELECT DurableId, SecureURL ' + 'FROM SiteDetail ' + 'WHERE DurableId IN :setofsiteid ' + 'WITH USER_MODE ' + 'LIMIT 4999'; String finalSiteDetailQuery = String.escapeSingleQuotes(siteDetailQuery).remove('\\'); List listOfsitedetail = Database.query(finalSiteDetailQuery); system.debug('@@@ listOfsitedetail : '+listOfsitedetail); if (siteList != null && siteList.size() != 0) { // listOfsitedetail = [ // SELECT DurableId, SecureURL // FROM SiteDetail // WHERE DurableId IN :setofsiteid // WITH USER_MODE // LIMIT 4999 // ]; for (SObject sd : listOfsitedetail) { String durableId = (String)sd.get('durableid'); String secureUrl = (String)sd.get('secureurl'); mapofsiteidvssiteurl.put(durableid, secureurl.removeEnd('/')); } for (SObject s : siteList) { if((String)s.get('SiteType') != 'ChatterNetworkPicasso'){ SiteWrapper siteWrapper = new SiteWrapper(); siteWrapper.siteUrl = mapofsiteidvssiteurl.get(String.valueOf(s.get('Id')).left(15)); siteWrapper.siteGuestId = (String)s.get('GuestUserId'); siteWrapper.name = (String)s.get('Name'); siteWrapper.id = (String)s.get('Id'); listofsitewrapper.add(siteWrapper); } } } if (!listofsitewrapper.isEmpty()) { return JSON.serialize(listofsitewrapper); } }else{ return 'No access to site.'; } return null; } //Wrapper class for Salesfroce site details public class SiteWrapper { @AuraEnabled public String id { get; set; } @AuraEnabled public String siteUrl { get; set; } @AuraEnabled public String siteguestid { get; set; } @AuraEnabled public String name { get; set; } } /* ********************************************************* @Method Name : getIsPerson @author : SME Team @description : Check Salesforce Org have PersonAccount Enabled or not What is Person Account in Salesforce ? https://help.salesforce.com/articleView?id=account_person.htm&type=5 @param : @Return : Boolean - true if person account is enabled or false if not ******************************************************** */ @AuraEnabled(cacheable=true) public static boolean getIsPerson() { return Schema.sObjectType.Account.fields.getMap() .containsKey('isPersonAccount'); } /* ********************************************************* @Method Name : getGeneral @author : SME Team @description : Retrieves general configuration data for a given Shopify store. @param : store (String) - name of the store @Return : String - JSON representation of the configuration for the specified store. ******************************************************** */ @AuraEnabled public static String getGeneral(String store) { store = store.replace('https://', '') .replace('.myshopify.com', '') .remove('/') .remove('"'); System.debug('store url' + store); List config = new List(); String fieldtocheck = 'id, Name, HIC_ShopifySync__Store__c, HIC_ShopifySync__Enable_Opportunity_for_SDO__c,HIC_ShopifySync__Dynamic_Price_Enabled__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__BatchRunOnce__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c,HIC_ShopifySync__Inventory_Location_Sync__c,HIC_ShopifySync__Product_Sync__c,HIC_ShopifySync__Batch_Is_Processing__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Enable_Draft_Order__c, HIC_ShopifySync__Account_Contact__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Inventory_Location__c, HIC_ShopifySync__Collection__c'; String query = 'select ' + Checkaccessibility.isAccessible( fieldtocheck, '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'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config = database.query(finalQuery); System.debug('config' + config); return JSON.serialize(config[0]); } /**************************************getErrorMailList*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get list of Email for send email notifications after Batch process complete * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getErrorMailList() { DescribeSObjectResult emailSettingSchema = getSchemaType('HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c'); List listOfErrorMails = new List(); String query= 'select ' + Checkaccessibility.isAccessible( 'id,name', emailSettingSchema ) + ' from HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c LIMIT 10000'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); listOfErrorMails=database.query(finalQuery); if (!listOfErrorMails.isEmpty()) { return JSON.serialize(listOfErrorMails); } else { HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c errorMailMapping = new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(); if ( CheckAccessibility.isUpdateable( 'name', 'HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c' ) ) { errorMailMapping.name = UserInfo.getUserEmail(); } List withuserlistOfErrorMails = new List(); withuserlistOfErrorMails.add(errorMailMapping); return JSON.serialize(withuserlistOfErrorMails); } } /**************************************saveEmailSettings*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Save Emails into Salesforce for send email notifications * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static void saveEmailSettings(string emaiList) { if (emaiList != null && emaiList != '' && emaiList != '["null"]') { system.debug('emaiList---->' + emaiList); DescribeSObjectResult emailSettingSchema = getSchemaType('HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c'); if (emailSettingSchema.isAccessible() && (emailSettingSchema.isCreateable() || emailSettingSchema.isUpdateable() || emailSettingSchema.isDeletable()) ) { List emailListfrompage = new List(); emailListfrompage = (List) JSON.deserialize( emaiList, List.class ); List listOfErrorMails = new List(); String query= 'select ' + Checkaccessibility.isAccessible( 'id', emailSettingSchema ) + ' from HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c WITH USER_MODE LIMIT 10000'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); listOfErrorMails=database.query(finalQuery); set setofemailsfrompage = new Set(); for ( HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c pagemail : emailListfrompage ) { HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c emailObjct = new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(); if (Checkaccessibility.isUpsertable( 'name, id', 'HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c' )){ if (pagemail.name != null && pagemail.name != '') { emailObjct.name = pagemail.name; setofemailsfrompage.add(emailObjct); } } } set setofemailsfrombackend = new Set(); setofemailsfrombackend.addall(listOfErrorMails); list listtodeleteEmails = new List(); for ( HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c emailsfordelete : setofemailsfrombackend ) { if (!setofemailsfrompage.contains(emailsfordelete)) { listtodeleteEmails.add(emailsfordelete); } } system.debug('listtodeleteEmails-->' + listtodeleteEmails); system.debug('listtodeleteEmails Size-->' + listtodeleteEmails.size()); if (!listtodeleteEmails.isempty()) { if (CheckAccessibility.isDeletable( 'HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c' )){ database.delete(listtodeleteEmails,True,AccessLevel.USER_MODE); } } list listtoInsertNewEmails = new List(); if (!setofemailsfrompage.isEmpty()) { for ( HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c emailsfordelete : setofemailsfrompage ) { if (!setofemailsfrombackend.contains(emailsfordelete)) { listtoInsertNewEmails.add(emailsfordelete); } } } if (!listtoInsertNewEmails.isempty()) { if (CheckAccessibility.isUpsertable( 'name', 'HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c' )){ database.upsert(listtoInsertNewEmails,True,AccessLevel.USER_MODE); } } } } } /* ********************************************************* @Method Name : deleteFieldMappings @author : SME Team @description : This Method is used for deleting the field mapping into the Salesforce When every user delete the mapped data into the Salesforce. @params : This needs a list of Ids and store name. ******************************************************** */ @AuraEnabled public static String deleteFieldMappings(string deletedCustomSetting, string store){ String customSettingList =''; try{ system.debug('@@@@ This is the deletedCustomSetting--> '+deletedCustomSetting); if(Test.isRunningTest()){ deletedCustomSetting = '["Order-name","Account-HIC_Shopify__TAG__c","Account-BillingStreet","Account-BillingCity"]'; } if(String.isNotBlank(deletedCustomSetting) && !store.equalsIgnoreCase('default')){ List listofcustomsetting = new List(); listofcustomsetting = (List)JSON.deserialize(deletedCustomSetting,List.class); if(!listofcustomsetting.isEmpty()){ List listofallcustomSetting = new List(); DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); String query = ' select '+CheckAccessibility.isAccessible('id',fieldMappingSchema)+' from HIC_ShopifySync__HIC_Field_Mapping__c where id in : listofcustomsetting AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fieldMappingSchema)+' = \''+store+'\' WITH USER_MODE LIMIT 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); listofallcustomSetting = database.query(finalQuery); if(!listofallcustomSetting.isEmpty()){ if(CheckAccessibility.isDeletable('HIC_ShopifySync__HIC_Field_Mapping__c')){ database.delete(listofallcustomSetting,True,AccessLevel.USER_MODE); } customSettingList = JSON.serializePretty(listofallcustomSetting); } } } return customSettingList; } catch(Exception ex){ customSettingList = '@@@ this is the error::: '+ ex.getMessage()+ '@@@@ this is the line number::: '+ ex.getLineNumber(); return customSettingList; } } /* ********************************************************* @Method Name : saveFieldMapping @author : SME Team @description : This Method is used to save the Mapping of the Fields Choosed by customer at the time of configuring the Store. @params : This needs a list of Object in the form of JSON String. ******************************************************** */ @AuraEnabled public static String saveFieldMapping(String listofRecord) { String result = null; try{ if(String.isNotBlank(listofRecord)){ System.debug('this is the listofrecord' + listofRecord); List listofFieldMapping = new List(); List allChildValuesList = (List) JSON.deserializeUntyped(listofRecord); System.debug('this is the allChildValuesList' + allChildValuesList); DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); System.debug('this is the fieldMappingSchema' + fieldMappingSchema); CheckAccessibility.isAccessible('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c',fieldMappingSchema); CheckAccessibility.isUpsertable('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c'); for(Object fieldMapObj : allChildValuesList){ System.debug('this is the allChildValuesList' + allChildValuesList); Map fieldMap = (Map) fieldMapObj; HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping = new HIC_ShopifySync__HIC_Field_Mapping__c(); // Salesforce field Mapping if(fieldMap.containsKey('sobjectType') && String.isNotBlank((String) fieldMap.get('sobjectType'))){ fieldMapping.HIC_ShopifySync__Object_Name__c = (String) fieldMap.get('sobjectType'); System.debug('this is the fieldMapping' + fieldMapping); } if(fieldMap.containsKey('salesforcefields') && String.isNotBlank((String) fieldMap.get('salesforcefields'))){ fieldMapping.HIC_ShopifySync__SF_Field__c = (String) fieldMap.get('salesforcefields'); System.debug('this is the fieldMapping' + fieldMapping); System.debug('this is the fieldMapping.HIC_ShopifySync__SF_Field__c' + fieldMapping.HIC_ShopifySync__SF_Field__c); } // if(fieldMap.containsKey('salesforceFieldLabel')){ // fieldMapping.HIC_ShopifySync__SF_Field__c = (String) fieldMap.get('salesforceFieldLabel'); // } if(fieldMap.containsKey('salesforceFieldType') && String.isNotBlank((String) fieldMap.get('salesforceFieldType'))){ fieldMapping.HIC_ShopifySync__SF_Field_Type__c = (String) fieldMap.get('salesforceFieldType'); } if (fieldMap.containsKey('graphqlfield')) { String graphqlFieldValue = (String) fieldMap.get('graphqlfield'); if (graphqlFieldValue == null || graphqlFieldValue.trim().length() == 0) { // If the value is null or blank, set it to a blank space fieldMapping.HIC_ShopifySync__GQL_Field_API__c = ''; } else { // Otherwise, set it to the trimmed value fieldMapping.HIC_ShopifySync__GQL_Field_API__c = graphqlFieldValue.trim(); } } // if(fieldMap.containsKey('shopifyApiName'){ if(fieldMap.containsKey('sobjectType') && fieldMap.containsKey('salesforcefields') && fieldMap.containsKey('salesforceFieldType') && String.isNotBlank((String) fieldMap.get('salesforcefields'))){ // String tempName = (String) fieldMap.get('sobjectType') +'-'+ (String) fieldMap.get('salesforcefields') ; String tempName = (String) fieldMap.get('salesforcefields') ; // Using this mapping before // String tempName = (String)fieldMap.get('shopifyApiName'); if(tempName.contains('HIC_ShopifySync__') && (String) fieldMap.get('sobjectType') != 'Account'){ fieldMapping.Name = (String) fieldMap.get('sobjectType') +'-'+ tempName.replace('HIC_ShopifySync__','HIC_'); fieldMapping.Name = checkFieldLengthAndReturnValue(fieldMapping.Name); }else if((tempName.contains('HIC_ShopifySync__')) && ((String)fieldMap.get('salesforceFieldType') == 'Reference')){ fieldMapping.Name = (String) fieldMap.get('sobjectType') +'-'+ tempName.replace('HIC_ShopifySync__',''); fieldMapping.Name = checkFieldLengthAndReturnValue(fieldMapping.Name); }else{ fieldMapping.Name = (String) fieldMap.get('sobjectType') +'-'+ checkFieldLengthAndReturnValue(tempName).capitalize(); } } // if(fieldMap.containsKey('shopifyApiName')){ // fieldMapping.Name = (String) fieldMap.get('shopifyApiName'); // } if(fieldMap.containsKey('defaultValue')){ fieldMapping.HIC_ShopifySync__Default_Value__c = (Boolean) fieldMap.get('defaultValue'); } if(fieldMap.containsKey('HIC_ShopifySync__External_ID') && String.isNotBlank((String) fieldMap.get('HIC_ShopifySync__External_ID'))){ fieldMapping.HIC_ShopifySync__External_ID__c = (String) fieldMap.get('HIC_ShopifySync__External_ID'); } if(fieldMap.containsKey('HIC_ShopifySync__IsSFID')){ fieldMapping.HIC_ShopifySync__IsSFID__c = (Boolean) fieldMap.get('HIC_ShopifySync__IsSFID'); } // if(fieldMap.containsKey('shopifyNested') && String.isNotBlank((String) fieldMap.get('shopifyNested'))){ if(fieldMap.containsKey('shopifyNested')){ fieldMapping.HIC_ShopifySync__Nested__c = (String) fieldMap.get('shopifyNested'); } // Check for currencyISOCode // Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType'); if(fieldMap.containsKey('HIC_ShopifySync__IsSFID')){ fieldMapping.HIC_ShopifySync__IsSFID__c = (Boolean) fieldMap.get('HIC_ShopifySync__IsSFID'); } if(fieldMap.containsKey('selectedfields')){ // System.debug(' this is the selectedfields' + fieldMap.get('selectedfields')); if(fieldMap.containsKey('shopifyFieldType') && ((String)fieldMap.get('shopifyFieldType')).equalsIgnoreCase('BOOLEAN')){ // System.debug('@@ this is the selectedfields type if block' + fieldMap.get('selectedfields')); Object selectedFieldsValue = fieldMap.get('selectedfields'); if (selectedFieldsValue instanceof Boolean) { Boolean isSelected = (Boolean) selectedFieldsValue; fieldMapping.HIC_ShopifySync__Shopify_Fields__c = isSelected ? 'true' : 'false'; // System.debug('<<<<< Selected field is Boolean'+fieldMapping.HIC_ShopifySync__Shopify_Fields__c); } else if (selectedFieldsValue instanceof String) { String selectedFieldsString = (String) selectedFieldsValue; if (String.isNotBlank(selectedFieldsString) && selectedFieldsString.containsIgnoreCase('-')) { list strlist = selectedFieldsString.split('-'); fieldMapping.HIC_ShopifySync__Shopify_Fields__c = strlist.size() > 1 ? strlist[1].split('-')[0].toLowerCase() : null; // System.debug('<<<<< Selected field is String If Block'+fieldMapping.HIC_ShopifySync__Shopify_Fields__c); }else { fieldMapping.HIC_ShopifySync__Shopify_Fields__c = selectedFieldsString; // System.debug('<<<<< Selected field is String'+fieldMapping.HIC_ShopifySync__Shopify_Fields__c); } } }else if(String.isNotBlank((String) fieldMap.get('selectedfields'))){ String tempSelectedField = (String) fieldMap.get('selectedfields'); // System.debug('@@@@ this is the selected field ::: '+tempSelectedField); // System.debug('@@@@ THIS IS the salesforce type ::: ' + ((String) fieldMap.get('salesforceFieldType')) ); if((((String)fieldMap.get('salesforceFieldType') != 'DATETIME') && ((String)fieldMap.get('salesforceFieldType') != 'DATE') && ((String) fieldMap.get('salesforceFieldType') != 'URL')) && ((tempSelectedField.containsIgnoreCase('.') || tempSelectedField.containsIgnoreCase(',')))){ fieldMapping.HIC_ShopifySync__Shopify_Fields__c = ''; if(tempSelectedField.containsIgnoreCase(',')){ for(String str : tempSelectedField.split(',')){ List strList = new List(); strList = str.split('\\.'); if(!strList.isEmpty() && strList.size()>1){ fieldMapping.HIC_ShopifySync__Nested__c = strList[0]; fieldMapping.HIC_ShopifySync__Shopify_Fields__c += ','+strList[1]; }else if(!strList.isEmpty() && strList.size() == 1){ // fieldMapping.HIC_ShopifySync__Nested__c = strList[0]; fieldMapping.HIC_ShopifySync__Shopify_Fields__c += ','+strList[0]; } } fieldMapping.HIC_ShopifySync__Shopify_Fields__c = fieldMapping.HIC_ShopifySync__Shopify_Fields__c.removeStart(','); if(fieldMapping.HIC_ShopifySync__Shopify_Fields__c.length() > 255){ fieldMapping.HIC_ShopifySync__Shopify_Fields__c = fieldMapping.HIC_ShopifySync__Shopify_Fields__c.substring(0,255); Integer index = fieldMapping.HIC_ShopifySync__Shopify_Fields__c.lastIndexOf(','); fieldMapping.HIC_ShopifySync__Shopify_Fields__c = fieldMapping.HIC_ShopifySync__Shopify_Fields__c.substring(0,index); // System.debug('@@@ this is the fields having maxlenth 255'+ fieldMapping.HIC_ShopifySync__Shopify_Fields__c); } }else{ List strList = new List(); strList = tempSelectedField.split('\\.'); // System.debug('strList-->'+strList); if(!strList.isEmpty()){ fieldMapping.HIC_ShopifySync__Nested__c = strList[0]; fieldMapping.HIC_ShopifySync__Shopify_Fields__c = strList[1]; } } }else if(String.isNotBlank(tempSelectedField) && tempSelectedField.containsIgnoreCase('-')){ list strlist = tempSelectedField.split('-'); fieldMapping.HIC_ShopifySync__Shopify_Fields__c = strlist.size() > 1 ? strlist[1].split('-')[0].toLowerCase() : null; }else{ // if((String) fieldMap.get('sobjectType') == 'Contact'){ // System.debug('CONTACT REQUIRED SELECTED FIELDS ::: '+tempSelectedField); // } fieldMapping.HIC_ShopifySync__Shopify_Fields__c = tempSelectedField; } } } // if(fieldMap.containsKey('selectedfields')){ // fieldMapping.HIC_ShopifySync__Shopify_Fields__c = (String) fieldMap.get('selectedfields'); // // fieldMapping.Name = (String) fieldMap.get('selectedfields'); // } if(fieldMap.containsKey('shopifyFieldType') && String.isNotBlank((String) fieldMap.get('shopifyFieldType'))){ fieldMapping.HIC_ShopifySync__Shopify_Field_Type__c = (String) fieldMap.get('shopifyFieldType'); } if (fieldMap.containsKey('graphqlfield')) { String graphqlFieldValue = (String) fieldMap.get('graphqlfield'); if (graphqlFieldValue == null || graphqlFieldValue.trim().length() == 0) { fieldMapping.HIC_ShopifySync__GQL_Field_API__c = ''; } else { fieldMapping.HIC_ShopifySync__GQL_Field_API__c = graphqlFieldValue.trim(); } } if(fieldMap.containsKey('HIC_ShopifySync__Store') && String.isNotBlank((String) fieldMap.get('HIC_ShopifySync__Store'))){ fieldMapping.HIC_ShopifySync__Store__c = (String) fieldMap.get('HIC_ShopifySync__Store'); // storeName = (String) fieldMap.get('HIC_ShopifySync__Store'); } if(fieldMap.containsKey('HIC_ShopifySync__Store_External_ID') && String.isNotBlank((String) fieldMap.get('HIC_ShopifySync__Store_External_ID'))){ fieldMapping.HIC_ShopifySync__Store_External_ID__c = (String) fieldMap.get('HIC_ShopifySync__Store_External_ID'); } // if(fieldMap.containsKey('salesforceId') && String.isNotBlank((String)fieldMap.get('salesforceId'))){ // fieldMapping.Id = (String) fieldMap.get('salesforceId'); // } system.debug('this is the fieldMapping '+ fieldMapping); listofFieldMapping.add(fieldMapping); system.debug('this is the listofFieldMapping '+ listofFieldMapping); } if (!listofFieldMapping?.isEmpty() && CheckAccessibility.isUpsertable('id','HIC_ShopifySync__HIC_Field_Mapping__c')) { // upsert listofFieldMapping HIC_ShopifySync__Store_External_ID__c; database.upsert(listofFieldMapping,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c,True,AccessLevel.USER_MODE); result = JSON.serializePretty(listofFieldMapping); // return true; } } return result; } catch(Exception e){ throw new AuraHandledException('ERROR MESSAGE :: '+e.getMessage() + ' LINE NUMBER :: '+ e.getLineNumber()); // result = 'Error @@@@ getmessage' + e.getMessage()+' @@@@@ get line number:::: '+ e.getLineNumber(); // return null; } // return result; } /* ********************************************************* @Method Name : handleDefaultFieldMapping @author : SME Team @description : This Method is designed to handle default value of account and opportunity stage and opportunity value @params : String Accountid String Opportunity stage String Opporunity close days String @result : This needs a list of Object in the form of JSON String. ******************************************************** */ @AuraEnabled public static string handleDefaultFieldMapping(String accountId, String oppDefaultStage, String oppCloseDays, String storeName){ String result = 'Error'; List listofFieldMapping = new List(); DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); CheckAccessibility.isAccessible('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c',fieldMappingSchema); // CheckAccessibility.isUpsertable('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c','HIC_ShopifySync__Field_Mapping__c'); CheckAccessibility.isUpsertable('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c'); // List fieldMappings = new List(); listofFieldMapping = [Select Id, Name,HIC_ShopifySync__External_ID__c,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__Nested__c,HIC_ShopifySync__Shopify_Field_Type__c,HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Object_Name__c , HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Store__c, HIC_ShopifySync__Store_External_ID__c from HIC_ShopifySync__HIC_Field_Mapping__c where HIC_ShopifySync__Store__c = 'default' and HIC_ShopifySync__SF_Field__c = 'Accountid' WITH USER_MODE limit 49999 ]; for(HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping:listofFieldMapping){ if(String.isNotBlank(accountId)){ if( fieldMapping.HIC_ShopifySync__Store_External_ID__c == 'Opportunity-Accountid'){ fieldMapping.HIC_ShopifySync__Nested__c = null; } fieldMapping.HIC_ShopifySync__Shopify_Field_Type__c = 'String'; fieldMapping.HIC_ShopifySync__Default_Value__c = true; fieldMapping.HIC_ShopifySync__Shopify_Fields__c = accountId; fieldMapping.HIC_ShopifySync__GQL_Field_API__c = accountId; } fieldMapping.HIC_ShopifySync__Store__c = storeName; fieldMapping.HIC_ShopifySync__Store_External_ID__c = storeName+fieldMapping.HIC_ShopifySync__External_ID__c; } if(String.isNotBlank(oppDefaultStage)){ HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping5 = new HIC_ShopifySync__HIC_Field_Mapping__c(); fieldMapping5.Name = 'Opportunity-StageName'; fieldMapping5.HIC_ShopifySync__External_ID__c = 'Opportunity-StageName'; fieldMapping5.HIC_ShopifySync__Default_Value__c = true; fieldMapping5.HIC_ShopifySync__Object_Name__c = 'Opportunity'; fieldMapping5.HIC_ShopifySync__SF_Field__c = 'StageName'; fieldMapping5.HIC_ShopifySync__Shopify_Field_Type__c = 'pickList'; fieldMapping5.HIC_ShopifySync__SF_Field_Type__c = 'pickList'; fieldMapping5.HIC_ShopifySync__Shopify_Fields__c = oppDefaultStage; fieldMapping5.HIC_ShopifySync__GQL_Field_API__c = oppDefaultStage; fieldMapping5.HIC_ShopifySync__Store__c = storeName; fieldMapping5.HIC_ShopifySync__Store_External_ID__c = storeName+fieldMapping5.HIC_ShopifySync__External_ID__c; listofFieldMapping.add(fieldMapping5); } if (listofFieldMapping != null && !listofFieldMapping?.isEmpty() && CheckAccessibility.isUpsertable('id','HIC_ShopifySync__HIC_Field_Mapping__c')) { // upsert listofFieldMapping Id; database.upsert(listofFieldMapping,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c,True,AccessLevel.USER_MODE); result = JSON.serializePretty(listofFieldMapping); } return result; } /******************************************************************************************** * Created Date:- 31/07/2023 * 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 * * * **********************************************************************************************/ @AuraEnabled public static string getShopifyRecordCounts(String storeName,String objectName) { String result = 'Error!'; try { // String password; // String store = 'demoorg25'; DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); String query = 'Select ' + CheckAccessibility.isAccessible( 'HIC_ShopifySync__Chunk_Size__c,name,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__InventoryBatchCompleted__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c ,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c ', configSchema ) + ' from HIC_ShopifySync__HIC_Configuration__c where ' + CheckAccessibility.isAccessible( 'HIC_ShopifySync__Store__c', configSchema ) + ' = \'' + storeName + '\' LIMIT 49999'; List configurationList; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); configurationList = database.query(finalQuery); system.debug('@@@@ this is the Confiuguration List ' + configurationList); String password = configurationList[0] .HIC_ShopifySync__Private_Key_Password__c; String storeUrl; if(configurationList[0].HIC_ShopifySync__Shopify_URL__c.endsWith('/')){ storeUrl = configurationList[0].HIC_ShopifySync__Shopify_URL__c; }else{ storeUrl = configurationList[0].HIC_ShopifySync__Shopify_URL__c+'/'; } // result = HIC_ShopifyUtility.getShopifyRecordCounts(storeUrl, objectName, password); } catch (Exception ex) { System.debug('@@@ some Error Occured at line : ' + ex.getLineNumber() + ' with Error : ' + ex.getMessage() ); result = '@@@ some Error Occured at line : ' +ex.getLineNumber() +' with Error : ' +ex.getMessage(); } return result; } /**************************************CheckingBatchDetails*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Current batch status and errors * @param String ObjectName - Shopify Entity's Name (Object name) * @param String ApexClassName - batch Class name for check current status * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @auraEnabled public static String CheckingBatchDetails( String ObjectName, String ApexClassName, String store ) { List apList = new List( [SELECT Id, name FROM ApexClass WHERE Name = :ApexClassName] ); map MapOfApexClassvsObjectName = new Map(); if (apList.isEmpty()) return 'Not Class present'; if ( ObjectName == 'Product2' || ObjectName == 'HIC_ShopifySync__Variant__c' || ObjectName == 'Account' || ObjectName == 'Contact' || ObjectName == 'Order' || ObjectName == 'Opportunity' || ObjectName == 'Draftorder' || ObjectName == 'HIC_ShopifySync__Inventory__c' ) { List config = new List(); DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); String query; query = 'select ' + Checkaccessibility.isAccessible( 'id,HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__InventoryBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Batch_Is_Processing__c ,HIC_ShopifySync__Refresh_Token__c,name,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c', configSchema ) + ' from HIC_ShopifySync__HIC_Configuration__c where ' + CheckAccessibility.isAccessible( 'HIC_ShopifySync__Store__c', configSchema ) + ' = \'' + store + '\' LIMIT 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config=Database.query(finalQuery); list listofAsyncApexJobNotCompleted = new List(); listofAsyncApexJobNotCompleted = [ SELECT ApexClassID, Status FROM AsyncApexJob WHERE JobType = 'BatchApex' AND (Status = 'Processing' OR Status = 'Holding' OR Status = 'Queued' OR Status = 'Preparing') AND ApexClassID = :apList[0].Id WITH USER_MODE ORDER BY createddate DESC LIMIT 1 ]; if (!config.isEmpty()) { system.debug('config::'+config.isEmpty()); system.debug('config::'+config); system.debug('config hic::'+config[0].HIC_ShopifySync__ProductVariantBatchCompleted__c); system.debug('ObjectName::'+ObjectName); if ( listofAsyncApexJobNotCompleted.isEmpty() && config[0].HIC_ShopifySync__ProductVariantBatchCompleted__c == true && (ObjectName == 'Product2' || ObjectName == 'HIC_ShopifySync__Variant__c') ) { Integer totalCount = GetRealtimeData(ObjectName, store); return 'Completed' + String.valueOf(totalCount); } if ( listofAsyncApexJobNotCompleted.isEmpty() && config[0].HIC_ShopifySync__AccountContactBatchCompleted__c == true && (ObjectName == 'Account' || ObjectName == 'Contact') ) { Integer totalCount = GetRealtimeData(ObjectName, store); return 'Completed' + String.valueOf(totalCount); } if ( (listofAsyncApexJobNotCompleted.isEmpty() || config[0].HIC_ShopifySync__Enable_Draft_Order__c) && config[0].HIC_ShopifySync__OrderBatchCompleted__c == true && (ObjectName == 'Order' || ObjectName == 'Opportunity') ) { Integer totalCount = GetRealtimeData(ObjectName, store); return 'Completed' + String.valueOf(totalCount); } if ( listofAsyncApexJobNotCompleted.isEmpty() && config[0].HIC_ShopifySync__InventoryBatchCompleted__c == true && ObjectName == 'HIC_ShopifySync__Inventory__c' ) { Integer totalCount = GetRealtimeData(ObjectName, store); return 'Completed' + String.valueOf(totalCount); } if ( listofAsyncApexJobNotCompleted.isEmpty() && config[0].HIC_ShopifySync__DraftOrderBatchCompleted__c == true && (ObjectName == 'Draftorder' || (ObjectName == 'Opportunity' && config[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c == true)) ) { Integer totalCount = GetRealtimeData(ObjectName, store); return 'Completed' + String.valueOf(totalCount); } } } list listofAsyncApexJob = new List(); listofAsyncApexJob = [ SELECT ApexClassID, Status, ExtendedStatus FROM AsyncApexJob WHERE JobType = 'BatchApex' AND (Status = 'Processing' OR Status = 'Holding' OR Status = 'Queued' OR Status = 'Preparing' OR Status = 'Aborted' OR Status = 'Completed' OR Status = 'Failed') AND ApexClassID = :apList[0].Id WITH USER_MODE ORDER BY createddate DESC LIMIT 1 ]; String ResultValue; if (!listofAsyncApexJob.isEmpty()) { if ( listofAsyncApexJob[0].Status == 'Processing' || listofAsyncApexJob[0].Status == 'Completed' || listofAsyncApexJob[0].Status == 'Preparing' || listofAsyncApexJob[0].Status == 'Holding1' || listofAsyncApexJob[0].Status == 'Queued' ) { if (ObjectName != null && ObjectName != '') { Integer totalCount = GetRealtimeData(ObjectName, store); if ( listofAsyncApexJob[0].Status == 'Processing' || listofAsyncApexJob[0].Status == 'Preparing' || listofAsyncApexJob[0].Status == 'Holding1' || listofAsyncApexJob[0].Status == 'Queued' ) { ResultValue = String.valueOf(totalCount); } else if (listofAsyncApexJob[0].Status == 'Completed') { list listofAsyncApexJobNotCompleted = new List(); listofAsyncApexJobNotCompleted = [ SELECT ApexClassID, Status FROM AsyncApexJob WHERE JobType = 'BatchApex' AND (Status = 'Processing' OR Status = 'Holding1' OR Status = 'Queued' OR Status = 'Preparing') AND ApexClassID = :apList[0].Id WITH USER_MODE ORDER BY createddate DESC LIMIT 1 ]; if ( ObjectName == 'Product2' || ObjectName == 'HIC_ShopifySync__Variant__c' || ObjectName == 'Account' || ObjectName == 'Contact' || ObjectName == 'Draftorder' || ObjectName == 'Opportunity' || ObjectName == 'Order' || ObjectName == 'HIC_ShopifySync__Inventory__c' ) { ResultValue = String.valueOf(totalCount); } else if (listofAsyncApexJobNotCompleted.isEmpty()) { ResultValue = 'Completed' + String.valueOf(totalCount); } else { ResultValue = String.valueOf(totalCount); } } return ResultValue; } } else if ( listofAsyncApexJob[0].Status == 'Aborted' || listofAsyncApexJob[0].Status == 'Failed' ) { list listofAsyncApexJobNotCompleted = new List(); listofAsyncApexJobNotCompleted = [ SELECT ApexClassID, Status FROM AsyncApexJob WHERE JobType = 'BatchApex' AND (Status = 'Processing' OR Status = 'Holding1' OR Status = 'Queued' OR Status = 'Preparing') AND ApexClassID = :apList[0].Id WITH USER_MODE ORDER BY createddate DESC LIMIT 1 ]; if (listofAsyncApexJobNotCompleted.isEmpty()) { string abortError; if ( listofAsyncApexJob[0].ExtendedStatus != null && listofAsyncApexJob[0].ExtendedStatus != '' ) { abortError = '-' + listofAsyncApexJob[0].ExtendedStatus; } if (abortError != null && abortError != '') { return ResultValue = 'Aborted' + abortError; } return ResultValue = 'Aborted'; } else { return String.valueOf(GetRealtimeData(ObjectName, store)); } } } return ''; } /**************************************CheckingBatchDetails*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Shopify Record counts based on Object name * @param String ObjectName - Shopify Entity's Name (Object name) * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ public static Integer GetRealtimeData(String ObjectName, String storeName) { string query; list groupedResults = new List(); if (ObjectName == 'Order') { query = 'SELECT count(Id) totalCount FROM ' + ObjectName + ' Where HIC_ShopifySync__Shopify_Id__c != null And recordtype.name = \'Order\' AND HIC_ShopifySync__Store__c = \'' + storeName + '\' AND recordtype.NamespacePrefix = \'HIC_ShopifySync\' '; } else if (ObjectName == 'DraftOrder') { ObjectName = 'Order'; query = 'SELECT count(Id) totalCount FROM ' + ObjectName + ' Where HIC_ShopifySync__Shopify_Id__c != null And recordtype.name = \'Draft Order\' AND HIC_ShopifySync__Store__c = \'' + storeName + '\'AND recordtype.NamespacePrefix = \'HIC_ShopifySync\' '; } else { query = 'SELECT count(Id) totalCount FROM ' + ObjectName + ' Where HIC_ShopifySync__Shopify_Id__c != null AND HIC_ShopifySync__Store__c = \'' + storeName + '\''; } String finalQuery = String.escapeSingleQuotes(query).remove('\\'); try { groupedResults = Database.query(finalQuery); } catch (Exception ex) { system.debug( '@@@ Exception Occured at line : ' + ex.getLineNumber() + ' with message : ' + ex.getMessage() ); } Object totalCount = groupedResults[0].get('totalCount'); return (Integer) totalCount; } /* ********************************************************* @Method Name : refreshTokenCheck @author : SME Team @description : Get Refresh Token to check remote site @params : @result : String - Access token ******************************************************** */ @AuraEnabled public static string refreshTokenCheck() { try { List cryptokeyquery = getCryptoKey(); if (cryptokeyquery == null || cryptokeyquery.isEmpty()) { return 'No refresh token found'; } else { String refreshToken = cryptokeyquery[0].HIC_ShopifySync__Refresh_Token__c; String accessToken = cryptokeyquery[0].HIC_ShopifySync__Access_Token__c; if (String.isBlank(refreshToken)) { return 'No refresh token found'; } // ROTATION-SAFE: do NOT rotate on every setup load, and do NOT call out after any token // DML. Reuse the stored access token when present (store-add / sync self-heal a stale one // via TokenService). Only when there is a refresh token but no access token do we refresh, // through the serialized TokenService (refresh callout + committed save, nothing after it). if (String.isNotBlank(accessToken)) { return accessToken; } try { return TokenService.getFreshAccessToken(null, false); } catch (TokenService.ReauthRequiredException e) { return 'No refresh token found'; // genuinely dead → setup shows Initialize } catch (Exception e) { return 'No access token found'; // transient → user retries } } } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } } /* ********************************************************* @Method Name : preAuthSetupCheck @author : SME Team @description : Checks Remote Site Settings and Certificate existence WITHOUT an access token (used before the Initialize/OAuth step). RSS existence is detected by making a dummy callout and catching 'Unauthorized endpoint' CalloutException. Certificate existence is detected via Crypto.signWithCertificate in try/catch. @result : Map - domainRemoteSite, authRemoteSite, certificate ******************************************************** */ @AuraEnabled public static Map preAuthSetupCheck() { Map resultMap = new Map(); try { String domainEndpoint = isSiteSupportedOrg() ? URL.getOrgDomainUrl().toExternalForm() : getMiddleWareUrl(); resultMap.put('domainRemoteSite', isEndpointWhitelisted(domainEndpoint)); resultMap.put('authRemoteSite', isEndpointWhitelisted(getAuthenticateURL())); resultMap.put('certificate', shopifyCertificateExists()); } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } return resultMap; } private static Boolean isEndpointWhitelisted(String endpoint) { if (String.isBlank(endpoint)) { return false; } try { HttpRequest req = new HttpRequest(); req.setEndpoint(endpoint); req.setMethod('GET'); req.setTimeout(10000); if (!Test.isRunningTest()) { new Http().send(req); } return true; } catch (System.CalloutException ce) { // 'Unauthorized endpoint' => Remote Site Setting missing. Any other callout // failure (timeout, read error) means the endpoint IS whitelisted. return !ce.getMessage().containsIgnoreCase('Unauthorized endpoint'); } catch (Exception e) { return true; } } private static Boolean shopifyCertificateExists() { try { Crypto.signWithCertificate('RSA-SHA256', Blob.valueOf('SMECertCheck'), 'Shopify'); return true; } catch (Exception e) { return false; } } /* ********************************************************* @Method Name : checkBatchIsProcessing @author : SME Team @description : This method check if any batch is processing @params : @result : String - JSON of HIC_ShopifySync__Configuration__c ******************************************************** */ @AuraEnabled public static String checkBatchIsProcessing(){ try { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } List configList = new List(); DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); String Query = 'select '+Checkaccessibility.isAccessible('id,HIC_ShopifySync__Store__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,name,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c',configSchema)+' from HIC_ShopifySync__HIC_Configuration__c Where HIC_ShopifySync__Store__c != \'Default\' AND HIC_ShopifySync__HIC_Configuration__c.HIC_ShopifySync__Batch_Is_Processing__c = true LIMIT 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); configList=database.query(finalQuery); // System.debug('@@@@ configList'+ configList); if(!configList?.isEmpty()){ return JSON.serialize(configList[0] ); }else{ return null; } } catch (Exception e) { return e.getMessage()+''+e.getLineNumber(); } } /* ********************************************************* @Method Name : oauthLogin @author : SME Team @description : Get Access Token to check remote site @params : String - refresh token @result : String - Access token ******************************************************** */ @AuraEnabled public static String oauthLogin(String refreshToken) { String responseBody; try { system.debug('@@@ refreshToken : '+refreshToken); list listofConfiguration = new list(); DescribeSObjectResult configCustomSettingSchema = getSchemaType('HIC_ShopifySync__Configuration__c'); system.debug('@@@ configCustomSettingSchema: '+configCustomSettingSchema); String query = 'Select '+CheckAccessibility.isAccessible('id,Name,HIC_ShopifySync__ClientId__c,HIC_ShopifySync__ClientSecret__c',configCustomSettingSchema)+' from HIC_ShopifySync__Configuration__c where '+CheckAccessibility.isAccessible('Name',configCustomSettingSchema)+' = \'Default\' LIMIT 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); listofConfiguration = database.query(finalQuery); system.debug('@@@ listofConfiguration : '+listofConfiguration); //listofConfiguration = [select id,name,HIC_ShopifySync__ClientId__c,HIC_ShopifySync__ClientSecret__c from HIC_ShopifySync__Configuration__c where name = 'Default' limit 1]; if(listofConfiguration.isEmpty()){ return null; } if(isSiteSupportedOrg()){ String clientIdProduction = listofConfiguration[0].HIC_ShopifySync__ClientId__c; String clientSecretproduction = listofConfiguration[0].HIC_ShopifySync__ClientSecret__c; responseBody = HIC_ShopifyUtility.oauthLogin(refreshToken, clientIdProduction, clientSecretproduction); system.debug('@@@ responseBody :'+responseBody); }else{ String clientIdProduction; String clientSecretproduction; DescribeSObjectResult organizationSchema = getSchemaType('organization'); // Schema.SObjectField isSandboxFieldDescribe = organizationSchema.fields.getMap().get('IsSandbox'); if(organizationSchema.isAccessible()){ organization orgRecord = [select id,issandbox from organization WITH USER_MODE LIMIT 1 ]; if(orgRecord.issandbox){ clientIdProduction = '3MVG9G9pzCUSkzZv4NsQV0kOphuwhNCDbV2xJ4wazQQkD_nyOa73sUwa0Z0DtHz1t5woA9d9AVNwcHvqbQy45'; clientSecretproduction = 'FE5D62CA3C108BF836DDD3DB01C6B063E66F28FFAC5EC3BF43BC6EB248466F4A'; }else{ clientIdProduction = '3MVG9G9pzCUSkzZv4NsQV0kOphm0Il0eDJK5e0YicZLcCZKQcDHS0FORFMYHW8LzqJWPeMxzGUxeyshwEBOin'; clientSecretproduction = '2CF544F99E959C43977763BFBFA5999D4488E0C69757A99149D101EEB62E92B3'; } } responseBody = HIC_ShopifyUtility.oauthLogin(refreshToken, clientIdProduction, clientSecretproduction); system.debug('@@@ responseBody :'+responseBody); } } catch (Exception e) { return 'No access token found'; } return responseBody; } /**************************************checkStoreNameRemoteSite*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Verfiy RemoteSite Setting exist or not for the store * @param String shopifyStoreUrl - RemoteSite based on value check existance * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean checkStoreNameRemoteSite(String shopifyStoreUrl){ try{ String acessToken = getAccessToken(); Boolean remoteSiteStatus = HIC_ShopifyUtility.CheckshopifycertificateandRemotesite('RemoteSite',acessToken, shopifyStoreUrl); return remoteSiteStatus; } catch (Exception e) { return false; } } /**************************************CheckshopifycertificateandRemotesite*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Verfiy RemoteSite Setting exist or not * @param String Urltype - certificate/RemoteSite based on value check existance * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean CheckshopifycertificateandRemotesite(String Urltype, String AccessToken) { boolean exist = false; System.debug('Urltype---' + Urltype); String SFdomainUrl; if(isSiteSupportedOrg()){ SFdomainUrl = URL.getOrgDomainUrl().toExternalForm(); }else{ SFdomainUrl = getMiddleWareUrl(); } try { exist = HIC_ShopifyUtility.CheckshopifycertificateandRemotesite(Urltype,AccessToken,SFdomainUrl); return exist; } catch (Exception e) { return exist; } } public class readToken { public string access_token { get; set; } public string instance_url { get; set; } } /**************************************checkAccesScope*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * check Shopify store access for the entity * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String checkAccesScope(String shopifyUrl, String PASSWORD){ try{ List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } if(password.containsIgnoreCase('True')){ password = password.removeEnd('True'); Blob cryptoKey1 = Blob.valueOf(String.valueOf(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c)); Blob data = EncodingUtil.base64Decode(password); Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey1, data); String dryptDatapsd = decryptedData.toString(); if(dryptDatapsd != null && dryptDatapsd != ''){ password = dryptDatapsd; } } String result = HIC_ShopifyUtility.checkAccesScope(shopifyUrl, password); return result; }catch(exception e){ return null; } } /**************************************checkCreds*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Verify Shopify Credetials via callout into the Shopify * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static Boolean checkCreds(String shopifyUrl, String PASSWORD){ try { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } if(password.containsIgnoreCase('True')){ password = password.removeEnd('True'); Blob cryptoKey1 = Blob.valueOf(String.valueOf(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c)); Blob data = EncodingUtil.base64Decode(password); Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey1, data); String dryptDatapsd = decryptedData.toString(); if(dryptDatapsd != null && dryptDatapsd != ''){ password = dryptDatapsd; } } return HIC_ShopifyUtility.checkCreds(shopifyUrl, password ); }catch(Exception e){ return false; } } /**************************************getAccessToken*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Access Token to check remote site * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static string getAccessToken() { try{ List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return 'No refresh token found'; }else{ if (cyptokeyquery[0].HIC_ShopifySync__Access_Token__c != null && cyptokeyquery[0].HIC_ShopifySync__Access_Token__c != '') { return cyptokeyquery[0].HIC_ShopifySync__Access_Token__c; } else { return 'No refresh token found'; } } }catch(exception ex){ throw new AuraHandledException(ex.getMessage()); } } /**************************************createRemoteSiteSettings*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Create RemoteSite Setting for Authentication URL * @param String URL - URL for Create RemoteSite Setting * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static string createRemoteSiteSettings(String URL){ String result = 'Error'; String accessToken = ShopifyController.getAccessToken(); try{ if(URL == null || URL == '' || CheckingRemotesiteExistence(URL, accessToken)){ return 'Remote Site setting'; } // ROTATION-SAFE: use the stored access token directly. This synchronous @AuraEnabled path // does NOT rotate the token inline — rotation is centralized in the serialized TokenService, // and rotating here would either lose the rotated token if a governor limit skipped the save // or create a callout-after-DML conflict with the Metadata callouts below. If the Metadata // API rejects the token as an expired session, we refresh via TokenService for the NEXT // attempt (a refresh callout then a committed save, with nothing after it) and ask the admin // to retry — no token can ever be lost on this path. MetadataServiceNew.MetadataPort service = createService(accessToken); MetadataServiceNew.RemoteSiteSetting remoteSiteSettings = new MetadataServiceNew.RemoteSiteSetting(); remoteSiteSettings.fullName = 'HICShopifysyncmadeeasy'+DateTime.now().getTime(); remoteSiteSettings.url = URL; remoteSiteSettings.description='HIC Shopify Made Easy'; remoteSiteSettings.isActive=true; remoteSiteSettings.disableProtocolSecurity=false; if(!Test.isRunningTest()){ MetadataServiceNew.AsyncResult[] results = service.create(new List { remoteSiteSettings }); MetadataServiceNew.AsyncResult[] checkResults = service.checkStatus(new List {string.ValueOf(results[0].Id)}); System.debug('@@@ this is the Result :: '+checkResults); return 'Success'; } }catch(Exception e){ System.debug('@@@ Remote site setting created :: '+e.getMessage()+' at line number '+e.getLineNumber()); String msg = e.getMessage(); // An expired/invalid session means the stored access token is stale. Refresh it via the // serialized authority (refresh callout + committed save, nothing after) so the NEXT click // succeeds. This runs AFTER the failed Metadata callout, so it is not a callout-after-DML. if(String.isNotBlank(msg) && (msg.containsIgnoreCase('INVALID_SESSION_ID') || msg.containsIgnoreCase('Session not found') || msg.containsIgnoreCase('session'))){ try { TokenService.tryRefresh(accessToken); } catch(Exception ignore){} return 'Session refreshed. Please click Check Credentials again.'; } return '@@@ Remote site setting created :: '+e.getMessage()+' at line number '+e.getLineNumber(); } return result; } /**************************************createService*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * MetaData Service Class * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ public static MetadataServiceNew.MetadataPort createService(String accessToken){ MetadataServiceNew.MetadataPort service = new MetadataServiceNew.MetadataPort(); service.SessionHeader = new MetadataServiceNew.SessionHeader_element(); service.SessionHeader.sessionId = accessToken; // service.SessionHeader.sessionId = UserInfo.getSessionId(); return service; } public static MetadataServiceNew.MetadataPort createServices(){ MetadataServiceNew.MetadataPort service = new MetadataServiceNew.MetadataPort(); service.SessionHeader = new MetadataServiceNew.SessionHeader_element(); service.SessionHeader.sessionId = UserInfo.getSessionId(); return service; } /**************************************CheckingRemotesiteExistence*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Verfiy RemoteSite Setting exist or not * @param String SFdomainUrl - RemoteSite based on value check existance * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean CheckingRemotesiteExistence(String SFdomainUrl, String accessToken){ boolean exist = false; String OrgURl = URL.getOrgDomainUrl().toExternalForm(); exist = HIC_ShopifyUtility.CheckingRemotesiteExistence(SFdomainUrl,accessToken, OrgURl); return exist; } /**************************************saveRecordTypeMapping*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Save Salesforce Object's Recordtypes * ────────────────────────────────────────────────────────────────────────────────────────────── * @param String PersonAccountRecordTypeId - personAccount RecordtypeID selected by user in page * @param String AccountRecordTypeId - business account RecordtypeID selected by user in page * @param String ContactRecordTypeId - contact RecordtypeID selected by user in page * @param String OrderRecordTypeId - order RecordtypeID selected by user in page * @param String OpportunityRecordTypeId - Opportunity RecordtypeID selected by user in page * @param String DraftorderRecordTypeId - draft order RecordtypeID selected by user in page * @param String productRecordTypeId - product Record Type RecordtypeID selected by user in page * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean saveRecordTypeMapping(String PersonAccountRecordTypeId,String AccountRecordTypeId,String ContactRecordTypeId,String OrderRecordTypeId,String OpportunityRecordTypeId, String DraftorderRecordTypeId, String productRecordTypeId, String storeName){ System.debug('PersonAccountRecordTypeId'+PersonAccountRecordTypeId); System.debug('AccountRecordTypeId'+AccountRecordTypeId); System.debug('ContactRecordTypeId'+ContactRecordTypeId); System.debug('OrderRecordTypeId'+OrderRecordTypeId); System.debug('OpportunityRecordTypeId'+OpportunityRecordTypeId); System.debug('DraftorderRecordTypeId'+DraftorderRecordTypeId); System.debug('productRecordTypeId'+productRecordTypeId); try{ List fmList = new List(); if(PersonAccountRecordTypeId != null && PersonAccountRecordTypeId != ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('PersonAccount', PersonAccountRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('PersonAccount', PersonAccountRecordTypeId, storeName)); } if(AccountRecordTypeId != null && AccountRecordTypeId != ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('Account', AccountRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('Account', AccountRecordTypeId, storeName)); } if(ContactRecordTypeId != null && ContactRecordTypeId != ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('Contact', ContactRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('Contact', ContactRecordTypeId, storeName)); } if(OrderRecordTypeId != null && OrderRecordTypeId != ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('Order', OrderRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('Order', OrderRecordTypeId, storeName)); } if(DraftorderRecordTypeId != null && DraftorderRecordTypeId!= ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('DraftOrder', DraftOrderRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('DraftOrder', DraftOrderRecordTypeId, storeName)); } if(OpportunityRecordTypeId != null && OpportunityRecordTypeId != ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('Opportunity', OpportunityRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('Opportunity', OpportunityRecordTypeId, storeName)); } if(productRecordTypeId != null && productRecordTypeId != ''){ // HIC_ShopifySync__HIC_Field_Mapping__c fm = ShopifyController.createRecordTypeMapping('Product2', productRecordTypeId, storeName); // fmList.add(fm); fmList.add(ShopifyController.createRecordTypeMapping('Product2', productRecordTypeId, storeName)); } if(fmList.size() > 0){ for(HIC_ShopifySync__HIC_Field_Mapping__c checkname :fmList ){ if(checkname.name != null && checkname.name != ''){ checkname.name = checkFieldLengthAndReturnValue(checkname.name); } } // upsert fmList HIC_ShopifySync__Store_External_ID__c; if(CheckAccessibility.isUpsertable('name,HIC_ShopifySync__External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c')){ database.upsert(fmList,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c,True,AccessLevel.USER_MODE); } } return true; }catch( Exception e ){ System.debug('Exception'+e.getMessage()+'at line'+e.getLineNumber()); } return false; } /* ********************************************************* @Method Name : createRecordTypeMapping @author : SME Team @description : Creates a field mapping record for the RecordTypeId of a specified object @params : objectName (String) - The name of the Salesforce object. recordTypeId (String) - The ID of the record type to be mapped. storeName (String) - The name of the store for which the mapping is created. @result : HIC_ShopifySync__HIC_Field_Mapping__c - The created field mapping record. ******************************************************** */ public static HIC_ShopifySync__HIC_Field_Mapping__c createRecordTypeMapping(String objectName, String recordTypeId, String storeName){ HIC_ShopifySync__HIC_Field_Mapping__c fm = new HIC_ShopifySync__HIC_Field_Mapping__c(); fm.Name = objectName+'-RecordTypeId'; fm.HIC_ShopifySync__External_ID__c = objectName+'-RecordTypeId'; fm.HIC_ShopifySync__Default_Value__c = true; fm.HIC_ShopifySync__Object_Name__c = objectName; fm.HIC_ShopifySync__SF_Field__c = 'RecordTypeId'; //fm.Shopify_Field_Type__c = 'date'; fm.HIC_ShopifySync__SF_Field_Type__c = 'reference'; fm.HIC_ShopifySync__Shopify_Field_Type__c = 'Refrence'; fm.HIC_ShopifySync__Shopify_Fields__c = recordTypeId; fm.HIC_ShopifySync__GQL_Field_API__c = recordTypeId; fm.HIC_ShopifySync__Store__c = storeName; fm.HIC_ShopifySync__Store_External_ID__c = storeName+objectName+'-RecordTypeId'; return fm; } /**************************************checkFieldLengthAndReturnValue*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * check Saleforce field length * return trimed shopify trimed value based on salesforce field length * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ public static String checkFieldLengthAndReturnValue(String body){ if(body != null){ system.debug('*****BodyLength*** '+ body.length()); if( body.length() <= 40){ return body; }else{ return body.subString(0,40); } }else{ return ''; } } /* ********************************************************* @Method Name : fetchLookupData @author : SME Team @description : Custom account lookup fetch the lookup search data @params : searchKey (String) - The search keyword to lookup records. sObjectApiName (String) - The API name of the sObject to search within. @result : List - A list of sObjects matching the search criteria. ******************************************************** */ @AuraEnabled(cacheable=true) public static list fetchLookupData(string searchKey , string sObjectApiName) { Boolean checkPersonAccountEnabled = Schema.sObjectType.Account.fields.getMap().containsKey( 'isPersonAccount' ); List < sObject > returnList = new List < sObject > (); string sWildCardText = '%' + searchKey + '%'; String finalQuery=''; string sQuery =''; if(checkPersonAccountEnabled){ sQuery = 'SELECT ' + CheckAccessibility.isAccessible('Id,Name', sObjectApiName) + ' FROM ' + sObjectApiName + ' WHERE ' + CheckAccessibility.isAccessible('Name', sObjectApiName) + ' LIKE :sWildCardText' + ' AND '+Checkaccessibility.isAccessible('IsPersonAccount', sObjectApiName)+' = FALSE '+ ' ORDER BY CreatedDate DESC LIMIT 5'; finalQuery = String.escapeSingleQuotes(sQuery).remove('\\'); }else{ sQuery = 'SELECT ' + CheckAccessibility.isAccessible('Id,Name', sObjectApiName) + ' FROM ' + sObjectApiName + ' WHERE ' + CheckAccessibility.isAccessible('Name', sObjectApiName) + ' LIKE :sWildCardText' + ' ORDER BY CreatedDate DESC LIMIT 5'; finalQuery = String.escapeSingleQuotes(sQuery).remove('\\'); } // string sQuery = 'Select Id,Name From ' + sObjectApiName + ' Where Name Like : sWildCardText order by createdDate DESC LIMIT 5'; for (sObject obj: database.query(finalQuery)) { returnList.add(obj); } return returnList; } /* ********************************************************* @Method Name : fetchDefaultRecord @author : SME Team @description : Fetches a specific record based on the provided record ID and sObject API name @params : recordId (String) - The ID of the record to be fetched. sObjectApiName (String) - The API name of the sObject to query. @result : sObject - The fetched record ******************************************************** */ @AuraEnabled public static sObject fetchDefaultRecord(string recordId , string sObjectApiName) { string sRecId = recordId; // string sQuery = 'Select Id,Name From ' + sObjectApiName + ' Where Id = : sRecId LIMIT 1'; string sQuery = 'SELECT ' + CheckAccessibility.isAccessible('Id,Name', sObjectApiName) + ' FROM ' + sObjectApiName + ' WHERE ' + CheckAccessibility.isAccessible('Id', sObjectApiName) + ' = : sRecId LIMIT 1'; String finalQuery = String.escapeSingleQuotes(sQuery).remove('\\'); for (sObject obj: database.query(finalQuery)) { return obj; } return null; } /* ********************************************************* @Method Name : saveCurrencyMappingList @author : SME Team @description : Save the currency Iso @params : store (String) - name of the store storeSelectedCurrency (String) - selected currency for the store @result : String - JSON data of HIC_ShopifySync__HIC_Field_Mapping__c ******************************************************** */ @AuraEnabled public static String saveCurrencyMappingList(String store, String storeSelectedCurrency){ List currencyMappingList = new List(); try { list configurationList = new list(); String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Chunk_Size__c,HIC_ShopifySync__Dynamic_Price_Enabled__c,HIC_ShopifySync__Run_Order_And_Account_Together__c,name,HIC_ShopifySync__Draft_Order_Sync__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__InventoryBatchCompleted__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c ,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c ','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' LIMIT 49999'; configurationList = database.query(query); if(configurationList[0].HIC_ShopifySync__Dynamic_Price_Enabled__c == false){ currencyMappingList.add(processFieldMappingSobjectWithAllFields('Opportunity','CurrencyISOCODE',storeSelectedCurrency,'',true,false,'PICKLIST','string',store,storeSelectedCurrency)); currencyMappingList.add(processFieldMappingSobjectWithAllFields('Order','CurrencyISOCODE',storeSelectedCurrency,'',true,false,'PICKLIST','string',store,storeSelectedCurrency)); currencyMappingList.add(processFieldMappingSobjectWithAllFields('DraftOrder','CurrencyISOCODE',storeSelectedCurrency,'',true,false,'PICKLIST','string',store,storeSelectedCurrency)); currencyMappingList.add(processFieldMappingSobjectWithAllFields('Product2','CurrencyISOCODE',storeSelectedCurrency,'',true,false,'PICKLIST','string',store,storeSelectedCurrency)); }else{ } // System.debug('@@@@ currency mapping list :::: '+ currencyMappingList); // upsert currencyMappingList HIC_ShopifySync__Store_External_ID__c; if(CheckAccessibility.isUpsertable('name,HIC_ShopifySync__External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c')){ database.upsert(currencyMappingList,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c,True,AccessLevel.USER_MODE); } return JSON.serialize(currencyMappingList); } catch (Exception e) { System.debug('@@@ Error currency mapping message:: '+ e.getMessage()+ ' @@@ Error line number::: '+ e.getLineNumber()); return 'Error'; } } /* ********************************************************* @Method Name : processFieldMappingSobjectWithAllFields @author : SME Team @description : Processes and creates a field mapping record for a given Salesforce object and Shopify field. The method handles special cases for object and field names and ensures proper naming conventions. @params : objectName (String) - The API name of the Salesforce object. sfField (String) - The Salesforce field to be mapped. shopifyField (String) - The corresponding Shopify field. nested (String) - Indicates if the field is nested. isDefault (Boolean) - Indicates if the mapping is a default value. isSfId (Boolean) - Indicates if the field is an Salesforce ID. sfFieldType (String) - The type of the Salesforce field. shopifyType (String) - The type of the Shopify field. store (String) - The name of the store. @result : HIC_ShopifySync__HIC_Field_Mapping__c - The created field mapping record ******************************************************** */ public static HIC_ShopifySync__HIC_Field_Mapping__c processFieldMappingSobjectWithAllFields(string objectName, string sfField, string shopifyField, string nested, boolean isDefault, boolean isSfId, String sfFieldType, String shopifyType, String Store, String graphqlfield){ HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping = new HIC_ShopifySync__HIC_Field_Mapping__c(); try{ String tempObname=objectName; String tempfieldname=sfField; if(objectName.contains('HIC_ShopifySync__')){ tempObname= objectName.subString(17); /* ___________________________________________*/ if(tempObname.contains('Fulfillment')){ String tempHold= tempObname.replace('Order','Ord'); tempHold= tempHold.replace('Fulfillment','Ful'); tempObname=tempHold; } /* ___________________________________________*/ } if(sfField.contains('HIC_ShopifySync__')){ tempfieldname= sfField.subString(17); } if(string.valueOf(tempObname+'-'+tempfieldname).length() >38){ fieldMapping.name = string.valueOf(tempObname+'-'+tempfieldname).substring(0,38); }else{ fieldMapping.name = tempObname+'-'+tempfieldname; } if(sfField != null && sfField != ''){ fieldMapping.HIC_ShopifySync__Object_Name__c = objectName; fieldMapping.HIC_ShopifySync__SF_Field__c = sfField; fieldMapping.HIC_ShopifySync__Shopify_Fields__c = shopifyField; fieldMapping.HIC_ShopifySync__GQL_Field_API__c = graphqlfield; fieldMapping.HIC_ShopifySync__Nested__c = nested; fieldMapping.HIC_ShopifySync__Default_Value__c = isDefault; fieldMapping.HIC_ShopifySync__IsSFID__c = isSfId; fieldMapping.HIC_ShopifySync__External_ID__c = objectName+'-'+sfField; fieldMapping.HIC_ShopifySync__Store_External_ID__c = Store+objectName+'-'+sfField; fieldMapping.HIC_ShopifySync__SF_Field_Type__c=sfFieldType; fieldMapping.HIC_ShopifySync__Shopify_Field_Type__c=shopifyType; fieldMapping.HIC_ShopifySync__Store__c = store; return fieldMapping; } return null; }catch(Exception e){ return null; } } /**************************************getActiveCurrencies*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get List of Currency from Salesforce * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static List getActiveCurrencies() { try{ Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType'); list ListofcurrncyvalueAndValue = new list(); if(multiCurrencyEnabled){ String ListType = 'List'; List listOfAllCurrencyCode = (List)Type.forName(ListType).newInstance(); list Listofcurrency = new list(); String query = 'SELECT id,ISOCode FROM CurrencyType WHERE IsActive=TRUE WITH USER_MODE limit 999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); listOfAllCurrencyCode = database.query(finalQuery); for(sobject obj1 : listOfAllCurrencyCode){ CurrencyISOList CurrencyWrapper = new CurrencyISOList(); CurrencyWrapper.ISOCode = String.valueof(obj1.get('ISOCode')); Listofcurrency.add(CurrencyWrapper); } ListofcurrncyvalueAndValue.add(UserInfo.getDefaultCurrency()); ListofcurrncyvalueAndValue.add(JSON.serialize(Listofcurrency)); // System.debug('@@@@@ ListofcurrncyvalueAndValue list :::::: '+ ListofcurrncyvalueAndValue); return ListofcurrncyvalueAndValue; }else{ ListofcurrncyvalueAndValue.add(UserInfo.getDefaultCurrency()); ListofcurrncyvalueAndValue.add(''); return ListofcurrncyvalueAndValue; } } catch(Exception ex){ system.debug('@@@@ Error getmessage'+ ex.getMessage() + '@@@@ error Line Number'+ex.getLineNumber()); return null; } } /**************************************getlistofCurrencyISOCode*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get List of Currency from Salesforce * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static list getlistofCurrencyISOCode(String store){ List currencyMappingList = new List(); try{ Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType'); list ListofcurrncyvalueAndValue = new list(); DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); String query = ' select '+CheckAccessibility.isAccessible('name,HIC_ShopifySync__External_ID__c,HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c',fieldMappingSchema)+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c',fieldMappingSchema)+ ' = \'order\' And ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c',fieldMappingSchema) +'= \'CurrencyISOCODE\' And '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fieldMappingSchema)+' = \''+store+'\'WITH USER_MODE limit 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); currencyMappingList = database.query(finalQuery); system.debug('@@@@ currencyMappingList :: '+currencyMappingList); if(currencyMappingList.isEmpty()){ system.debug('@@@ if block currencyMapping List is empty '); // if(currencyMappingList.isEmpty() && store != null && store != ''){ list configurationList = new list(); String configsquery = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Chunk_Size__c,HIC_ShopifySync__Dynamic_Price_Enabled__c,HIC_ShopifySync__Run_Order_And_Account_Together__c,name,HIC_ShopifySync__Draft_Order_Sync__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__InventoryBatchCompleted__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c ,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c ','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' LIMIT 49999'; configurationList = database.query(configsquery); if(configurationList[0].HIC_ShopifySync__Dynamic_Price_Enabled__c == false){ currencyMappingList.add(processFieldMappingSobjectWithAllFields('Opportunity','CurrencyISOCODE','','',true,false,'PICKLIST','string',store,'')); currencyMappingList.add(processFieldMappingSobjectWithAllFields('Order','CurrencyISOCODE','','',true,false,'PICKLIST','string',store,'')); currencyMappingList.add(processFieldMappingSobjectWithAllFields('DraftOrder','CurrencyISOCODE','','',true,false,'PICKLIST','string',store,'')); currencyMappingList.add(processFieldMappingSobjectWithAllFields('Product2','CurrencyISOCODE','','',true,false,'PICKLIST','string',store,'')); }else{ } // upsert currencyMappingList HIC_ShopifySync__Store_External_ID__c; // system.debug('@@@@ currencymapping list is upserted: '+ currencyMappingList); if(CheckAccessibility.isUpsertable('name,HIC_ShopifySync__External_ID__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')){ database.upsert(currencyMappingList,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c,True,AccessLevel.USER_MODE); } system.debug('@@@@ currencymapping list is upserted: '+ currencyMappingList); } if(multiCurrencyEnabled){ String ListType = 'List'; List listOfAllCurrencyCode = (List)Type.forName(ListType).newInstance(); list Listofcurrency = new list(); String query1 = 'SELECT id,ISOCode FROM CurrencyType WHERE IsActive=TRUE WITH USER_MODE limit 999'; listOfAllCurrencyCode = database.query(String.escapeSingleQuotes(query).remove('\\')); System.debug('@@@ listOfAllCurrencyCode :: '+ listOfAllCurrencyCode); for(sobject obj1 : listOfAllCurrencyCode){ CurrencyISOList CurrencyWrapper = new CurrencyISOList(); CurrencyWrapper.ISOCode = String.valueof(obj1.get('ISOCode')); Listofcurrency.add(CurrencyWrapper); } if(currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c != null && currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c != ''){ ListofcurrncyvalueAndValue.add(currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c); }else{ ListofcurrncyvalueAndValue.add(UserInfo.getDefaultCurrency()); } ListofcurrncyvalueAndValue.add(JSON.serialize(Listofcurrency)); System.debug('@@@@@ ListofcurrncyvalueAndValue list :::::: '+ ListofcurrncyvalueAndValue); return ListofcurrncyvalueAndValue; }else{ if( !currencyMappingList.isEmpty() && currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c != null && currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c != ''){ ListofcurrncyvalueAndValue.add(currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c); }else{ ListofcurrncyvalueAndValue.add(UserInfo.getDefaultCurrency()); } ListofcurrncyvalueAndValue.add(''); return ListofcurrncyvalueAndValue; } }catch(Exception e){ return null; } } //Wrapper list for Currency public class CurrencyISOList{ @AuraEnabled public String ISOCode; } /**************************************Fetch Record Type of all the Objects used in Shopify LWC*************************************************/ /* * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get list of the Salesforce recordtypes : Contact and Opportunity * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getRecordTypes(String storeName){ try{ DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); List config = new List(); //HIC_ShopifySync__Private_Key_Password__c String fieldsToQueryforconfig = 'id , HIC_ShopifySync__Private_Key_Password__c, CurrencyIsoCode, Name, HIC_ShopifySync__Specify_Close_Date__c,HIC_ShopifySync__Default_Account__c,HIC_ShopifySync__Default_Field_Mapping__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__Account_Contact__c,HIC_ShopifySync__Person_Account__c,HIC_ShopifySync__Store__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c, HIC_ShopifySync__Enable_Opportunity_for_SDO__c'; String query = 'select ' + Checkaccessibility.isAccessible( fieldsToQueryforconfig, configSchema ) + ' from HIC_ShopifySync__HIC_Configuration__c where ' + CheckAccessibility.isAccessible( 'HIC_ShopifySync__Store__c', configSchema ) + ' = \'' + storeName + '\' LIMIT 1' ; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config = database.query(finalQuery); if (config != null && !config.isEmpty()) { Map recordTypeMap = new Map(); if(config[0].HIC_ShopifySync__Person_Account__c){ RecordTypeWrapper recordTypeWrap = new RecordTypeWrapper(); recordTypeWrap.recordTypeList = getRecordTypeList('PersonAccount'); recordTypeWrap.recordTypeId = getRecordTypeByName('PersonAccount', storeName); recordTypeMap.put('PersonAccount', recordTypeWrap); } if(config[0].HIC_ShopifySync__Account_Contact__c){ RecordTypeWrapper recordTypeWrap = new RecordTypeWrapper(); recordTypeWrap.recordTypeList = getRecordTypeList('Account'); recordTypeWrap.recordTypeId = getRecordTypeByName('Account', storeName); recordTypeMap.put('Account', recordTypeWrap); RecordTypeWrapper recordTypeWrap2 = new RecordTypeWrapper(); recordTypeWrap2.recordTypeList = getRecordTypeList('Contact'); recordTypeWrap2.recordTypeId = getRecordTypeByName('Contact', storeName); recordTypeMap.put('Contact', recordTypeWrap2); } if(config[0].HIC_ShopifySync__Order__c){ RecordTypeWrapper recordTypeWrap = new RecordTypeWrapper(); recordTypeWrap.recordTypeList = getRecordTypeList('Order'); recordTypeWrap.recordTypeId = getRecordTypeByName('Order', storeName); recordTypeMap.put('Order', recordTypeWrap); } if(config[0].HIC_ShopifySync__Enable_Draft_Order__c){ RecordTypeWrapper recordTypeWrap = new RecordTypeWrapper(); recordTypeWrap.recordTypeList = getRecordTypeList('DraftOrder'); recordTypeWrap.recordTypeId = getRecordTypeByName('DraftOrder', storeName); recordTypeMap.put('DraftOrder', recordTypeWrap); } if(config[0].HIC_ShopifySync__Opportunity__c || config[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c){ RecordTypeWrapper recordTypeWrap = new RecordTypeWrapper(); recordTypeWrap.recordTypeList = getRecordTypeList('Opportunity'); recordTypeWrap.recordTypeId = getRecordTypeByName('Opportunity', storeName); recordTypeMap.put('Opportunity', recordTypeWrap); } if(config[0].HIC_ShopifySync__Product_Sync__c){ RecordTypeWrapper recordTypeWrap = new RecordTypeWrapper(); recordTypeWrap.recordTypeList = getRecordTypeList('Product2'); recordTypeWrap.recordTypeId = getRecordTypeByName('Product2', storeName); recordTypeMap.put('Product2', recordTypeWrap); } return JSON.serialize(recordTypeMap); } return null; }catch(Exception e){ return 'Exception Occured at line '+e.getLineNumber()+' with error '+e.getMessage(); } } /** * Record Type Wrapper Class */ public class RecordTypeWrapper{ public List recordTypeList; public String recordTypeId; } /**************************************getRecordTypeList*************************************************/ /* * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get list of the Salesforce recordtypes : Contact and Opportunity * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static List getRecordTypeList(String objectName){ try{ string personAccountEnable; DescribeSObjectResult recordTypeSchema = getSchemaType('RecordType'); if(objectName == 'Account' || objectName == 'PersonAccount'){ personAccountEnable = Checkaccessibility.isAccessible('isPersonType',recordTypeSchema); } List recordTypes = new List(); if((personAccountEnable == null || personAccountEnable == '') && objectName == 'Account'){ String recordTypesQuery = 'SELECT '+ Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+ ' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Account\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+ Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+ ' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Account\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true limit 200'); }else if((personAccountEnable != null || personAccountEnable != '') && objectName == 'Account'){ String recordTypesQuery = 'SELECT '+ Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+ ' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Account\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true and '+personAccountEnable+' = false limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+ Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+ ' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Account\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true and '+personAccountEnable+' = false limit 200'); }else if((personAccountEnable == null || personAccountEnable == '') && objectName == 'PersonAccount'){ String recordTypesQuery = 'SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+ ' = \'Account\' and '+Checkaccessibility.isAccessible('isActive', recordTypeSchema)+' = true limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+ ' = \'Account\' and '+Checkaccessibility.isAccessible('isActive', recordTypeSchema)+' = true limit 200'); }else if((personAccountEnable != null || personAccountEnable != '') && objectName == 'PersonAccount'){ String recordTypesQuery = 'SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+ ' = \'Account\' and '+Checkaccessibility.isAccessible('isActive', recordTypeSchema)+' = true and '+personAccountEnable+' = true limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema)+' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+ ' = \'Account\' and '+Checkaccessibility.isAccessible('isActive', recordTypeSchema)+' = true and '+personAccountEnable+' = true limit 200'); }else if(objectName == 'DraftOrder'){ String recordTypesQuery = 'SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema) +' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Order\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema) +' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Order\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true limit 200'); System.debug('***recordTypes***'+recordTypes); }else if(objectName == 'Order'){ String recordTypesQuery = 'SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema) +' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Order\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+ ' = true and '+Checkaccessibility.isAccessible('DeveloperName', recordTypeSchema)+'!= \'Draft_Order\' limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema) +' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'Order\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+ ' = true and '+Checkaccessibility.isAccessible('DeveloperName', recordTypeSchema)+'!= \'Draft_Order\' limit 200'); System.debug('***recordTypes***'+recordTypes); }else{ String recordTypesQuery = 'SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema) +' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'' + objectName + '\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true limit 200'; String sanitizedrecordTypesQuery = String.escapeSingleQuotes(recordTypesQuery).remove('\\'); recordTypes = database.query(sanitizedrecordTypesQuery); // recordTypes = database.query('SELECT '+Checkaccessibility.isAccessible('DeveloperName,Id,IsActive,Name,SobjectType', recordTypeSchema) +' FROM RecordType where '+Checkaccessibility.isAccessible('SobjectType',recordTypeSchema)+' = \'' + objectName + '\' and '+Checkaccessibility.isAccessible('IsActive', recordTypeSchema)+' = true limit 200'); } if( !recordTypes.isEmpty()){ System.debug('***recordTypes***'+recordTypes); // return JSON.serialize( recordTypes ); return recordTypes; } return null; }catch(Exception e){ throw new AuraHandledException(e.getMessage()); } } /**************************************getRecordTypeByName*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get all the Salesforce recordtypes base on Object name * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getRecordTypeByName(string objectname, string store){ List fm = new List(); DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); // fm = database.query('select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c',fieldMappingSchema) +' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__Object_Name__c',fieldMappingSchema)+' = \''+Objectname+'\' and '+Checkaccessibility.isAccessible('HIC_ShopifySync__SF_Field__c',fieldMappingSchema) +' = \'RecordTypeId\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fieldMappingSchema)+' = \''+store+'\' LIMIT 49999'); String fmQuery = 'select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__Shopify_Fields__c',fieldMappingSchema) +' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__Object_Name__c',fieldMappingSchema)+' = \''+Objectname+'\' and '+Checkaccessibility.isAccessible('HIC_ShopifySync__SF_Field__c',fieldMappingSchema) +' = \'RecordTypeId\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fieldMappingSchema)+' = \''+store+'\' LIMIT 49999'; String sanitizedFmQuery = String.escapeSingleQuotes(fmQuery).remove('\\'); fm = database.query(sanitizedFmQuery); if(!fm.isEmpty() && fm[0].HIC_ShopifySync__Shopify_Fields__c != null && fm[0].HIC_ShopifySync__Shopify_Fields__c != ''){ return fm[0].HIC_ShopifySync__Shopify_Fields__c; } return null; } /**************************************saveConfigration*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Save Configuration setting based on User * If Check true then its called from Step -2 else Other * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean saveConfigration( String configObj, String check ){ try{ List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } HIC_ShopifySync__HIC_Configuration__c config = new HIC_ShopifySync__HIC_Configuration__c(); config = ( HIC_ShopifySync__HIC_Configuration__c )JSON.deserialize(configObj, HIC_ShopifySync__HIC_Configuration__c.class); String store = ''; if(config.HIC_ShopifySync__Shopify_URL__c != null) store = config.HIC_ShopifySync__Shopify_URL__c.replace('https://','').replace('.myshopify.com','').removeEnd('/'); if(store != '') config.HIC_ShopifySync__Store__c = store; config.name = store; // DescribeSObjectResult siteSchema = getSchemaType('Site'); if(!isSiteSupportedOrg()) { String remoteSiteUrl = ShopifyController.getMiddleWareUrl(); config.HIC_ShopifySync__Salesforce_Site_URL__c = remoteSiteUrl; } List storeFMappingList; DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); system.debug('@@@ fieldMappingSchema :: '+fieldMappingSchema); if( fieldMappingSchema.isAccessible() ) { storeFMappingList = [SELECT name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__Object_Name__c, HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Store__c, HIC_ShopifySync__Store_External_ID__c FROM HIC_ShopifySync__HIC_Field_Mapping__c where HIC_ShopifySync__Store__c =:store WITH USER_MODE LIMIT 49999]; System.debug('@@@ storeFMappingList :: '+storeFMappingList); } if(storeFMappingList.isEmpty()){ List InitialList = new List(); List listOfFieldMappingofFixedFields = [SELECT name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__Object_Name__c, HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Store__c, HIC_ShopifySync__Store_External_ID__c FROM HIC_ShopifySync__HIC_Field_Mapping__c where HIC_ShopifySync__Store__c = 'Default' WITH USER_MODE LIMIT 49999]; if(!listOfFieldMappingofFixedFields.isEmpty()){ System.debug('listOfFieldMappingofFixedFields-->if'); for(HIC_ShopifySync__HIC_Field_Mapping__c fixedField : listOfFieldMappingofFixedFields ){ HIC_ShopifySync__HIC_Field_Mapping__c cloned = fixedField.clone(false,false,false,false); InitialList.add(cloned); } } for(HIC_ShopifySync__HIC_Field_Mapping__c checkname :InitialList ){ checkname.HIC_ShopifySync__Store__c = store; checkname.HIC_ShopifySync__Store_External_ID__c = store+checkname.HIC_ShopifySync__External_ID__c; if(checkname.name != null && checkname.name != ''){ checkname.name = checkFieldLengthAndReturnValue(checkname.name); } } if(!InitialList.isEmpty()){ database.upsert(InitialList,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c, True, AccessLevel.USER_MODE); //upsert InitialList HIC_ShopifySync__Store_External_ID__c; } } if(String.isNotBlank(String.valueof(config.HIC_ShopifySync__Private_Key_Password__c)) ){ String PASSWORD = String.valueof(config.HIC_ShopifySync__Private_Key_Password__c); //System.debug('Password------'+PASSWORD); if(PASSWORD.containsIgnoreCase('True')){ //System.debug('Password------in '+PASSWORD); PASSWORD = PASSWORD.removeEnd('True'); If(!Test.isRunningTest()){ Blob cryptoKey1 = Blob.valueOf(String.valueOf(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c)); Blob data = EncodingUtil.base64Decode(PASSWORD); Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey1, data); String dryptDatapsd = decryptedData.toString(); if(dryptDatapsd != null && dryptDatapsd != ''){ config.HIC_ShopifySync__Private_Key_Password__c = dryptDatapsd; } } } System.debug('in true section'); } if(check == 'True'){ config.HIC_ShopifySync__Product_Sync__c = true; config.HIC_ShopifySync__Customer_Sync__c = true; List configList = new List (); DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); if(configSchema.isAccessible()) { configList = [Select HIC_ShopifySync__Enable_Draft_Order__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Inventory_Location__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Product_Sync__c from HIC_ShopifySync__HIC_Configuration__c Where Name = :store WITH USER_MODE Limit 1]; } if(configList != null && !configList.isEmpty()){ List objectName = new List(); if(configList[0].HIC_ShopifySync__Collection_Sync__c == True && config.HIC_ShopifySync__Collection_Sync__c == False){ objectName.add('HIC_ShopifySync__Collection__c'); } if(configList[0].HIC_ShopifySync__Customer_Sync__c == True && config.HIC_ShopifySync__Customer_Sync__c == False) { objectName.add('Customer'); } if(configList[0].HIC_ShopifySync__Inventory_Location__c == True && config.HIC_ShopifySync__Inventory_Location__c == False){ objectName.add('HIC_ShopifySync__Inventory_Level__c'); objectName.add('HIC_ShopifySync__Location__c'); } if(configList[0].HIC_ShopifySync__Product_Sync__c == True && config.HIC_ShopifySync__Product_Sync__c == False){ objectName.add('Product2'); } if(configList[0].HIC_ShopifySync__Draft_Order_Sync__c == True && config.HIC_ShopifySync__Draft_Order_Sync__c == False){ objectName.add('DraftOrder'); } // if(configList[0].HIC_ShopifySync__Enable_Draft_Order__c == True && config.HIC_ShopifySync__Enable_Draft_Order__c == False){ // objectName.add('DraftOrder'); // } if(configList[0].HIC_ShopifySync__Order_Sync__c == True && config.HIC_ShopifySync__Order_Sync__c == False) { objectName.add('Order'); } List webhookExistList = new List(); webhookExistList = [Select Name, HIC_ShopifySync__DML_Type__c, HIC_ShopifySync__SF_URL_Mapping__c, HIC_ShopifySync__Shopify_Object__c, HIC_ShopifySync__Topic__c from HIC_ShopifySync__HIC_Webhook__c where HIC_ShopifySync__Store__c = :store AND HIC_ShopifySync__Shopify_Object__c IN :objectName WITH USER_MODE Limit 200]; if(webhookExistList != null && !webhookExistList?.isEmpty()){ for(HIC_ShopifySync__HIC_Webhook__c webhook:webhookExistList){ HICWebhookUtility.deleteWebhook(webhook.HIC_ShopifySync__Shopify_Object__c, webhook.HIC_ShopifySync__DML_Type__c, store); } } } List webhookExistList = new List(); DescribeSObjectResult webhookCustomSettingSchema = getSchemaType('HIC_ShopifySync__HIC_Webhook__c'); if(webhookCustomSettingSchema.isAccessible()) { webhookExistList = [Select Name, HIC_ShopifySync__DML_Type__c, HIC_ShopifySync__SF_URL_Mapping__c, HIC_ShopifySync__Shopify_Object__c, HIC_ShopifySync__Topic__c from HIC_ShopifySync__HIC_Webhook__c where HIC_ShopifySync__Store__c = :store WITH USER_MODE Limit 200]; } if(webhookExistList == null || webhookExistList.isEmpty()){ System.debug('in else section'); List defaultWebhookList = new List(); if( webhookCustomSettingSchema.isAccessible() ) { defaultWebhookList = [Select Name, HIC_ShopifySync__DML_Type__c, HIC_ShopifySync__SF_URL_Mapping__c, HIC_ShopifySync__Shopify_Object__c, HIC_ShopifySync__Topic__c from HIC_ShopifySync__Webhook__c WITH USER_MODE Limit 200]; } String jsonString = JSON.serialize(defaultWebhookList); List storeWebhookList = (List)JSON.deserialize(jsonString, List.Class); for(HIC_ShopifySync__HIC_Webhook__c webhook : storeWebhookList){ webhook.HIC_ShopifySync__Store__c = store; webhook.HIC_ShopifySync__External_Id__c = webhook.Name+'-'+webhook.HIC_ShopifySync__Store__c; webhook.Id = null; } try{ if(CheckAccessibility.isUpsertable('HIC_ShopifySync__External_Id__c', 'HIC_ShopifySync__HIC_Webhook__c')){ System.debug('storeWebhookList--'+storeWebhookList); database.upsert(storeWebhookList,HIC_ShopifySync__HIC_Webhook__c.HIC_ShopifySync__External_Id__c, True, AccessLevel.USER_MODE); //upsert storeWebhookList HIC_ShopifySync__External_Id__c; } } catch(Exception e){ System.debug(e); } } List pricebook2MappingList = new List(); if(config.HIC_ShopifySync__Salesforce_Pricebook__c != null && config.HIC_ShopifySync__Salesforce_Pricebook__c != '' ){ system.debug('HIC_ShopifySync__Salesforce_Pricebook__c-->'); // DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__Field_Mapping__c'); String query = 'select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__External_ID__c,HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__GQL_Field_API__c,HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c',fieldMappingSchema)+' from HIC_ShopifySync__Field_Mapping__c where ( '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c',fieldMappingSchema)+ ' = \'order\' or '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c',fieldMappingSchema) +' = \'DraftOrder\' or '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c',fieldMappingSchema) +' = \'Opportunity\' ) And (' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c',fieldMappingSchema) +'= \'Pricebook2Id\' OR '+ CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c',fieldMappingSchema)+' = \'RecordTypeId\' ) limit 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); pricebook2MappingList = database.query(finalQuery); system.debug('pricebook2MappingList-->'+pricebook2MappingList); String RecordtypeidForOrder; Schema.DescribeSObjectResult dsr = order.SObjectType.getDescribe(); Schema.RecordTypeInfo defaultRecordType; for(Schema.RecordTypeInfo rti : dsr.getRecordTypeInfos()) { if(rti.isDefaultRecordTypeMapping()) { RecordtypeidForOrder = rti.getRecordTypeId() ; } } System.debug('RecordtypeidForOrder++'+RecordtypeidForOrder); if(!pricebook2MappingList.isEmpty() && pricebook2MappingList.size() == 3 ){ List fmList = new List(); if(RecordtypeidForOrder != null && RecordtypeidForOrder != ''){ //System.debug('acc '+acc); HIC_ShopifySync__Field_Mapping__c fmord = new HIC_ShopifySync__Field_Mapping__c(); fmord.Name = 'Order-RecordTypeId'; fmord.HIC_ShopifySync__External_ID__c = 'Order-RecordTypeId'; fmord.HIC_ShopifySync__Default_Value__c = true; fmord.HIC_ShopifySync__Object_Name__c = 'Order'; fmord.HIC_ShopifySync__SF_Field__c = 'RecordTypeId'; //fm.Shopify_Field_Type__c = 'date'; fmord.HIC_ShopifySync__SF_Field_Type__c = 'reference'; fmord.HIC_ShopifySync__Shopify_Fields__c = RecordtypeidForOrder; pricebook2MappingList.add(fmord); //System.debug('acc '+acc); HIC_ShopifySync__Field_Mapping__c fmdrford = new HIC_ShopifySync__Field_Mapping__c(); fmdrford.Name = 'DraftOrder-RecordTypeId'; fmdrford.HIC_ShopifySync__External_ID__c = 'DraftOrder-RecordTypeId'; fmdrford.HIC_ShopifySync__Default_Value__c = true; fmdrford.HIC_ShopifySync__Object_Name__c = 'Draftorder'; fmdrford.HIC_ShopifySync__SF_Field__c = 'RecordTypeId'; //fm.Shopify_Field_Type__c = 'date'; fmdrford.HIC_ShopifySync__SF_Field_Type__c = 'reference'; fmdrford.HIC_ShopifySync__Shopify_Fields__c = RecordtypeidForOrder; pricebook2MappingList.add(fmdrford); } } for(HIC_ShopifySync__Field_Mapping__c fd : pricebook2MappingList){ if(String.valueof(fd.HIC_ShopifySync__SF_Field__c).toUpperCase() == ('Pricebook2Id').toUpperCase()){ fd.HIC_ShopifySync__Shopify_Fields__c = config.HIC_ShopifySync__Salesforce_Pricebook__c ; } if(String.valueof(fd.HIC_ShopifySync__SF_Field__c).toUpperCase() == ('RecordTypeId').toUpperCase() && (String.valueof(fd.Name).toUpperCase() == ('DraftOrder-RecordTypeId').toUpperCase() && String.valueof(fd.Name).toUpperCase() == ('Order-RecordTypeId').toUpperCase() ) && (fd.HIC_ShopifySync__Shopify_Fields__c == null || fd.HIC_ShopifySync__Shopify_Fields__c == '' ) ){ fd.HIC_ShopifySync__Shopify_Fields__c = RecordtypeidForOrder ; } } // pricebook2MappingList[0].HIC_ShopifySync__Shopify_Fields__c = config.HIC_ShopifySync__Salesforce_Pricebook__c ; // pricebook2MappingList[1].HIC_ShopifySync__Shopify_Fields__c = config.HIC_ShopifySync__Salesforce_Pricebook__c ; } try{ if(!pricebook2MappingList.isempty()){ if(CheckAccessibility.isUpsertable('HIC_ShopifySync__Object_Name__c', 'HIC_ShopifySync__Field_Mapping__c')){ database.upsert(pricebook2MappingList,HIC_ShopifySync__Field_Mapping__c.HIC_ShopifySync__External_ID__c, True, AccessLevel.USER_MODE); //upsert pricebook2MappingList HIC_ShopifySync__External_ID__c ; } } if(CheckAccessibility.isUpsertable('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')){ config.Id = null; database.upsert(config,HIC_ShopifySync__HIC_Configuration__c.HIC_ShopifySync__Store__c, True, AccessLevel.USER_MODE); //upsert config HIC_ShopifySync__Store__c; } } catch(Exception e){ System.debug(e); } BatchForCreateWebhookMultiStore callBatch = new BatchForCreateWebhookMultiStore(store); Database.executeBatch(callBatch, 1); }else if(check == 'False'){ system.debug('**check'+check); system.debug('**config'+config); if( config.HIC_ShopifySync__order__c != null && config.HIC_ShopifySync__Opportunity__c != null){ if(config.HIC_ShopifySync__order__c == false){ config.HIC_ShopifySync__Order_Line_Item__c = false; }else{ config.HIC_ShopifySync__Order_Line_Item__c = true; } if(config.HIC_ShopifySync__Opportunity__c == false){ config.HIC_ShopifySync__Opportunity_Line_Item__c = false; } if(config.HIC_ShopifySync__order__c == false && config.HIC_ShopifySync__Opportunity__c == true ){ config.HIC_ShopifySync__Opportunity_Line_Item__c = true; } } if(CheckAccessibility.isUpsertable('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')){ database.upsert(config,HIC_ShopifySync__HIC_Configuration__c.HIC_ShopifySync__Store__c, True, AccessLevel.USER_MODE); //upsert config HIC_ShopifySync__Store__c; } }else if(check == 'Normal'){ if(CheckAccessibility.isUpsertable('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')){ database.upsert(config,HIC_ShopifySync__HIC_Configuration__c.HIC_ShopifySync__Store__c, True, AccessLevel.USER_MODE); //upsert config HIC_ShopifySync__Store__c; } } return true; }catch( Exception e ){ //CustomSettingRecordInsert.SuccessMailSend('Error message '+e.getMessage() + ' at line number ' + e.getLineNumber()); System.debug('Error message '+e.getMessage() + ' at line number ' + e.getLineNumber()); return false; } // return false; } /********************************************************* @Method Name : getFieldMappings @author : SME Team @Description : Method to get fieldMapping of Different Objects. @Return : list of Object Mapping ********************************************************/ // @Depricated @AuraEnabled public static string getFieldMappings(String storeName){ String result = 'Error'; try { List config = new List (); DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); String FieldsToQueryforconfig = 'id,Name,HIC_ShopifySync__Store__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Specify_Close_Date__c,HIC_ShopifySync__Default_Account__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__Account_Contact__c,HIC_ShopifySync__Person_Account__c'; // config = Database.query('select '+ Checkaccessibility.isAccessible(FieldsToQueryforconfig,configSchema)+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', configSchema)+' = \''+storeName+'\' LIMIT 1'); String configQuery = 'select '+ Checkaccessibility.isAccessible(FieldsToQueryforconfig,configSchema)+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', configSchema)+' = \''+storeName+'\' LIMIT 1'; String sanitizedconfigQuery = String.escapeSingleQuotes(configQuery).remove('\\'); config = Database.query(sanitizedconfigQuery); system.debug('@@@ config :: '+config); Map objectFieldMappingMap = new Map(); if(config != null && !config?.isEmpty()){ objectFieldMappingMap.put('Account', getEverythingForObjects(storeName, 'Account', config)); if(config[0].HIC_ShopifySync__Account_Contact__c){ objectFieldMappingMap.put('Contact', getEverythingForObjects(storeName, 'Contact', config)); } if(config[0].HIC_ShopifySync__Product_Sync__c){ objectFieldMappingMap.put('Product2', getEverythingForObjects(storeName, 'Product2', config)); objectFieldMappingMap.put('HIC_ShopifySync__Variant__c', getEverythingForObjects(storeName, 'HIC_ShopifySync__Variant__c', config)); } if(config[0].HIC_ShopifySync__Order__c){ objectFieldMappingMap.put('Order', getEverythingForObjects(storeName, 'Order', config)); objectFieldMappingMap.put('OrderItem', getEverythingForObjects(storeName, 'OrderItem', config)); } if(config[0].HIC_ShopifySync__Enable_Draft_Order__c){ objectFieldMappingMap.put('DraftOrder', getEverythingForObjects(storeName, 'DraftOrder', config)); objectFieldMappingMap.put('DraftOrderItem', getEverythingForObjects(storeName, 'DraftOrderItem', config)); } if(config[0].HIC_ShopifySync__Opportunity__c || config[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c){ objectFieldMappingMap.put('Opportunity', getEverythingForObjects(storeName, 'Opportunity', config)); } if(config[0].HIC_ShopifySync__Opportunity_Line_Item__c || config[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c){ objectFieldMappingMap.put('OpportunityLineItem', getEverythingForObjects(storeName, 'OpportunityLineItem',config)); } } return JSON.serialize(objectFieldMappingMap); } catch (Exception ex) { return 'Exception Occured at line '+ex.getLineNumber()+' with Message :: '+ex.getMessage(); } // return result; } /********************************************************* @Method Name : getObjectFieldMapping @author : SME Team @Description : Method to get fieldMapping of Different Objects. @Return : list of Object Mapping ********************************************************/ @AuraEnabled public static string getObjectFieldMapping(String storeName, String objectName){ String result = 'Error'; try { List config = new List (); DescribeSObjectResult configSchema = getSchemaType('HIC_ShopifySync__HIC_Configuration__c'); String FieldsToQueryforconfig = 'id,Name,HIC_ShopifySync__Store__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Specify_Close_Date__c,HIC_ShopifySync__Default_Account__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__Account_Contact__c,HIC_ShopifySync__Person_Account__c'; // config = Database.query('select '+ Checkaccessibility.isAccessible(FieldsToQueryforconfig,configSchema)+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', configSchema)+' = \''+storeName+'\' LIMIT 1'); String configQuery = 'select '+ Checkaccessibility.isAccessible(FieldsToQueryforconfig,configSchema)+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', configSchema)+' = \''+storeName+'\' LIMIT 1'; String sanitizedconfigQuery = String.escapeSingleQuotes(configQuery).remove('\\'); config = Database.query(sanitizedconfigQuery); system.debug('@@@ config :: '+config); Map objectFieldMappingMap = new Map(); if(config != null && !config?.isEmpty()){ if(objectName == 'Account'){ objectFieldMappingMap.put('Account', getEverythingForObjects(storeName, 'Account', config)); } if(config[0].HIC_ShopifySync__Account_Contact__c && objectName == 'Contact'){ objectFieldMappingMap.put('Contact', getEverythingForObjects(storeName, 'Contact', config)); } if(config[0].HIC_ShopifySync__Product_Sync__c && objectName == 'Product2'){ objectFieldMappingMap.put('Product2', getEverythingForObjects(storeName, 'Product2', config)); } if(config[0].HIC_ShopifySync__Product_Sync__c && objectName == 'HIC_ShopifySync__Variant__c'){ objectFieldMappingMap.put('HIC_ShopifySync__Variant__c', getEverythingForObjects(storeName, 'HIC_ShopifySync__Variant__c', config)); } if(config[0].HIC_ShopifySync__Order__c && objectName == 'Order'){ objectFieldMappingMap.put('Order', getEverythingForObjects(storeName, 'Order', config)); } if(config[0].HIC_ShopifySync__Order__c && objectName == 'OrderItem'){ objectFieldMappingMap.put('OrderItem', getEverythingForObjects(storeName, 'OrderItem', config)); } if(config[0].HIC_ShopifySync__Enable_Draft_Order__c && objectName == 'DraftOrder'){ objectFieldMappingMap.put('DraftOrder', getEverythingForObjects(storeName, 'DraftOrder', config)); } if(config[0].HIC_ShopifySync__Enable_Draft_Order__c && objectName == 'DraftOrderItem'){ objectFieldMappingMap.put('DraftOrderItem', getEverythingForObjects(storeName, 'DraftOrderItem', config)); } if((config[0].HIC_ShopifySync__Opportunity__c || config[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c) && objectName == 'Opportunity'){ objectFieldMappingMap.put('Opportunity', getEverythingForObjects(storeName, 'Opportunity', config)); } if((config[0].HIC_ShopifySync__Opportunity_Line_Item__c || config[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c) && objectName == 'OpportunityLineItem'){ objectFieldMappingMap.put('OpportunityLineItem', getEverythingForObjects(storeName, 'OpportunityLineItem',config)); } } return JSON.serialize(objectFieldMappingMap); } catch (Exception ex) { return 'Exception Occured at line '+ex.getLineNumber()+' with Message :: '+ex.getMessage(); } // return result; } /********************************************************* @Method Name : getEverythingForObject @author : SME Team @Description : Method to get fieldMapping of Different Objects. @Return : list of Object Mapping ********************************************************/ @AuraEnabled public static String getEverythingForObjects(String storeName, String objectName, List config){ List ListOfEverything = new List (); Map mapOfEverything = new Map(); String FieldsToQueryforShopifyFields = 'Name,HIC_ShopifySync__UI_Label_Name__c,HIC_ShopifySync__Field_Name__c,HIC_ShopifySync__Data_Type__c,HIC_ShopifySync__Nested__c'; //Method - 0 (Business and Person Account 0-4) // List OptionalfieldWrapperList = new List(); List optionalFields = new List(); // List RequiredfieldForWrapperList = new List(); List requiredFields = new List(); List RequiredfieldForPersonAccountWrapperList = new List(); FieldWrapper wrapper= new FieldWrapper(); // Get the SObjectType dynamically Map fieldMap = new Map(); Schema.SObjectType objectType; if(objectName == 'DraftOrder'){ objectType = Schema.getGlobalDescribe().get('Order'); }else if(objectName == 'DraftOrderItem'){ objectType = Schema.getGlobalDescribe().get('OrderItem'); }else{ objectType = Schema.getGlobalDescribe().get(objectName); } system.debug('@@@@ this is the dynamic object type name :::: '+ objectType); if (objectType != null) { // Get the fields map for the specified object Schema.DescribeSObjectResult objectDescribe = objectType.getDescribe(); fieldMap = objectDescribe.fields.getMap(); System.debug('The key set of fieldMap is ==> '+fieldMap.keySet()); } Schema.DescribeFieldResult fieldResult; // Map fieldMap = Schema.SObjectType.Account.fields.getMap(); for(String keyfield : fieldMap.keySet() ){ fieldResult = fieldMap.get(keyfield).getDescribe(); if(ShopifyController.checkFieldMapping(objectName, keyfield, fieldResult)){ // Object optional field Mapping if(objectName == 'Account'){ System.debug('<<< Account Optional field '+ keyfield); if((fieldResult.isNillable() || fieldResult.getType() == Schema.DisplayType.Boolean) && fieldResult.isUpdateable() && fieldResult.isCreateable() ){ if(keyfield != 'name' && keyfield != 'lastname' && !keyfield.Contains('__pc') && !keyfield.contains('person') && config[0].HIC_ShopifySync__Account_Contact__c && keyfield != 'firstname' && keyfield != 'salutation' && !fieldResult.isDependentPicklist() && !fieldResult.isRestrictedPicklist() && !fieldResult.isCalculated() && keyfield != 'cleanstatus' && keyfield != 'jigsaw'){ if(String.valueOf(fieldResult.getType()) != 'REFERENCE'){ System.debug('<<< Account Optional field Label '+ String.valueOf( fieldResult.getLabel() )); System.debug('<<< Account Optional field Name '+ String.valueOf( fieldResult.getName() )); System.debug('<<< Account Optional field Type '+ String.valueOf( fieldResult.getType() )); wrapper = new FieldWrapper(); wrapper.filedlabel = String.valueOf( fieldResult.getLabel() ); wrapper.filedApiName = String.valueOf( fieldResult.getName() ); wrapper.dataType = String.valueOf( fieldResult.getType() ); optionalFields.add(wrapper); } }else if(keyfield != 'name' && keyfield != 'lastname' && keyfield != 'cleanstatus' && keyfield != 'salutation' && !fieldResult.isDependentPicklist() && !fieldResult.isCalculated() && keyfield != 'HIC_ShopifySync__shopify_id__pc' && !config[0].HIC_ShopifySync__Account_Contact__c && keyfield != 'jigsaw'){ System.debug('<<< ELSE Account Optional field Label '+ String.valueOf( fieldResult.getLabel() )); System.debug('<<< ELSE Account Optional field Name '+ String.valueOf( fieldResult.getName() )); System.debug('<<< ELSE Account Optional field Type '+ String.valueOf( fieldResult.getType() )); if(String.valueOf(fieldResult.getType()) != 'REFERENCE'){ //(fieldResult.isUpdateable() || fieldResult.isCreateable()) && wrapper = new FieldWrapper(); wrapper.filedlabel = String.valueOf( fieldResult.getLabel() ); wrapper.filedApiName = String.valueOf( fieldResult.getName() ); wrapper.dataType = String.valueOf( fieldResult.getType() ); optionalFields.add(wrapper); } } } }else { if( (fieldResult.isNillable() || fieldResult.getType() == Schema.DisplayType.Boolean)){ wrapper = new FieldWrapper(); wrapper.filedlabel = String.valueOf( fieldResult.getLabel() ); wrapper.filedApiName = String.valueOf( fieldResult.getName() ); wrapper.dataType = String.valueOf( fieldResult.getType() ); optionalFields.add(wrapper); } } // Object Required Fields if(objectName == 'Account'){ if((fieldResult.isUpdateable() || fieldResult.isCreateable()) && !fieldResult.isRestrictedPicklist() && String.valueOf(fieldResult.getType()) != 'REFERENCE' && String.valueOf(fieldResult.getType()) != 'BOOLEAN'){ if(keyfield == 'name'){ FieldWrapper businesswrapper = new FieldWrapper(); businesswrapper.filedlabel = String.valueOf( fieldResult.getLabel() ); businesswrapper.filedApiName = String.valueOf( fieldResult.getName() ); businesswrapper.dataType = String.valueOf( fieldResult.getType() ); requiredFields.add(businesswrapper); system.debug('if condition result = '+requiredFields); // } else if(keyfield != 'name' && !fieldResult.isNillable() && fieldResult.isCreateable() && fieldResult.isUpdateable() && !keyfield.Contains('__pc')){ FieldWrapper businesswrapper= new FieldWrapper(); businesswrapper.filedlabel = String.valueOf( fieldResult.getLabel() ); businesswrapper.filedApiName = String.valueOf( fieldResult.getName() ); businesswrapper.dataType = String.valueOf( fieldResult.getType() ); requiredFields.add(businesswrapper); } if(keyfield == 'lastname'){ FieldWrapper personwrapper = new FieldWrapper(); personwrapper.filedlabel = String.valueOf( fieldResult.getLabel() ); personwrapper.filedApiName = String.valueOf( fieldResult.getName() ); personwrapper.dataType = String.valueOf( fieldResult.getType() ); RequiredfieldForPersonAccountWrapperList.add(personwrapper); } } }else { if(objectName == 'Contact' && !fieldResult.isNillable() && String.valueOf(fieldResult.getType()) != 'BOOLEAN' && fieldResult.isUpdateable() && fieldResult.isCreateable()){ FieldWrapper wrapper1 = new FieldWrapper(); wrapper1.filedlabel = String.valueOf( fieldResult.getLabel() ); wrapper1.filedApiName = String.valueOf( fieldResult.getName() ); wrapper1.dataType = String.valueOf( fieldResult.getType() ); requiredFields.add(wrapper1); }else if(objectName == 'Opportunity' && String.valueOf(fieldResult.getType()) != 'BOOLEAN' && !fieldResult.isNillable() && !fieldResult.isRestrictedPicklist() && keyfield != 'stagename' && fieldResult.isUpdateable() && fieldResult.isCreateable()){ FieldWrapper wrapper2 = new FieldWrapper(); wrapper2.filedlabel = String.valueOf( fieldResult.getLabel() ); wrapper2.filedApiName = String.valueOf( fieldResult.getName() ); wrapper2.dataType = String.valueOf( fieldResult.getType() ); requiredFields.add(wrapper2); }else if(((objectName == 'Product2' ) || (objectName == 'HIC_ShopifySync__Variant__c') || (objectName == 'OpportunityLineItem' && keyfield != 'stagename' ) || (((objectName == 'Order' || objectName == 'DraftOrder' && keyfield != 'status') || (objectName == 'OrderItem' || objectName == 'DraftOrderItem' && keyfield != 'unitprice')) && keyfield != 'statuscode' )) && !fieldResult.isNillable() && (fieldResult.isUpdateable() || fieldResult.isCreateable()) && String.valueOf(fieldResult.getType()) != 'REFERENCE' && String.valueOf(fieldResult.getType()) != 'BOOLEAN' && !fieldResult.isRestrictedPicklist() && fieldResult.isUpdateable() && fieldResult.isCreateable()){ FieldWrapper wrapper3 = new FieldWrapper(); wrapper3.filedlabel = String.valueOf( fieldResult.getLabel() ); wrapper3.filedApiName = String.valueOf( fieldResult.getName() ); wrapper3.dataType = String.valueOf( fieldResult.getType() ); requiredFields.add(wrapper3); } } } } if(optionalFields != null && !optionalFields.isEmpty()){ mapOfEverything.put('optionalFields', JSON.serialize( optionalFields ) ); // ListOfEverything.add(JSON.serialize( optionalFields )); }else{ mapOfEverything.put('optionalFields', null ); // ListOfEverything.add(''); } if(requiredFields != null && !requiredFields.isEmpty()){ mapOfEverything.put('requiredFields', JSON.serialize( requiredFields ) ); }else{ mapOfEverything.put('requiredFields', null ); } // Add this for Account object only if(objectName == 'Account'){ if(RequiredfieldForPersonAccountWrapperList != null && !RequiredfieldForPersonAccountWrapperList.isEmpty()){ mapOfEverything.put('personAccountFields', JSON.serialize( RequiredfieldForPersonAccountWrapperList ) ); //ListOfEverything.add(JSON.serialize( RequiredfieldForPersonAccountWrapperList )); //2 - 1 }else{ mapOfEverything.put('personAccountFields', null ); //ListOfEverything.add(''); } } /********************************************************* @Name : getShopifyFields @Parameters : Object name @Return type : String @Description : Method to get object's shopify fieldMapping . @Name : getDefaultFieldMapping @Parameters : Object name, ispersonAccount , store name @Return type : String @Description : Method to get object's default fieldMapping . ********************************************************/ if(objectName == 'Account'){ mapOfEverything.put('shopifyFields' , HIC_ShopifyUtility.getShopifyFields(objectName)); mapOfEverything.put('defaultMapping' , HIC_ShopifyUtility.getDefaultFieldMapping(objectName, config[0].HIC_ShopifySync__Person_Account__c, storeName)); }else if(objectName == 'Opportunity'){ mapOfEverything.put('shopifyFields' , HIC_ShopifyUtility.getShopifyFields('Order')); mapOfEverything.put('defaultMapping' , HIC_ShopifyUtility.getDefaultFieldMapping(objectName, false, storeName)); }else if(objectName == 'OpportunityLineItem'){ mapOfEverything.put('shopifyFields', HIC_ShopifyUtility.getShopifyFields('OrderItem') ); mapOfEverything.put('defaultMapping' , HIC_ShopifyUtility.getDefaultFieldMapping(objectName, false, storeName)); }else if(objectName == 'HIC_ShopifySync__Variant__c'){ mapOfEverything.put('shopifyFields', HIC_ShopifyUtility.getShopifyFields('Variant__c')); mapOfEverything.put('defaultMapping' , HIC_ShopifyUtility.getDefaultFieldMapping(objectName, false, storeName)); }else{ mapOfEverything.put('shopifyFields' , HIC_ShopifyUtility.getShopifyFields(objectName)); mapOfEverything.put('defaultMapping' , HIC_ShopifyUtility.getDefaultFieldMapping(objectName, false, storeName)); } if(!mapOfEverything?.isEmpty()){ return JSON.serializePretty(mapOfEverything); }else{ return null; } } /********************************************************* @Method Name : checkFieldMapping @author : SME Team @Description : Check if field map is to map with another field or not @Return : Boolean (True or False) ********************************************************/ public static Boolean checkFieldMapping(String objectName, String keyfield, Schema.DescribeFieldResult fieldResult){ Boolean result = false; if(fieldResult.isDependentPicklist() || fieldResult.isRestrictedPicklist() || fieldResult.isCalculated() || keyfield == 'HIC_ShopifySync__Store__c' || keyfield == 'HIC_ShopifySync__Store__pc' || keyfield == 'HIC_ShopifySync__Is_identified__c' || keyfield == 'HIC_ShopifySync__Is_identified__pc' || keyfield == 'HIC_ShopifySync__Shopify_Id__pc ' || keyfield == 'HIC_ShopifySync__shopify_id__c' || keyfield == 'HIC_ShopifySync__Store_External_Id__c' || keyfield == 'HIC_ShopifySync__Store_External_Id__pc' || String.valueOf(fieldResult.getType()) == 'REFERENCE' || (!fieldResult.isUpdateable() && !fieldResult.isCreateable()) || keyfield =='billinglatitude' || keyfield == 'billinglongitude' || keyfield == 'billinggeocodeaccuracy' || keyfield == 'shippinglatitude' || keyfield == 'shippinglongitude' || keyfield == 'shippinggeocodeaccuracy' || keyfield == 'otherlatitude' || keyfield == 'otherlongitude' || keyfield == 'othergeocodeaccuracy' || keyfield == 'mailinglatitude' || keyfield == 'mailinglongitude' || keyfield == 'mailinggeocodeaccuracy' || keyfield == 'personotherlatitude' || keyfield == 'personemail' || keyfield == 'personemailbouncedreason' || keyfield == 'personemailbounceddate' || keyfield == 'personotherlongitude' || keyfield == 'personothergeocodeaccuracy' || keyfield == 'personmailinglatitude' || keyfield == 'personmailinglongitude' || keyfield == 'personmailinggeocodeaccuracy'){ return result; } //keyfield != 'ownerid' && if(objectName == 'Account' && (keyfield != 'jigsaw')){ result = true; }else if(objectName == 'Contact' && (keyfield != 'cleanstatus' && keyfield != 'email' && keyfield != 'jigsaw')){ result = true; }else if(objectName == 'Opportunity'){ result = true; }else if((objectName == 'Order' || objectName == 'DraftOrder') && (keyfield != 'activateddate' && keyfield != 'activatedby' && keyfield != 'status' ) ){ result = true; }else if((objectName == 'OpportunityLineItem') && keyfield != 'totalprice' && keyfield != 'unitprice'){ result = true; }else if((objectName == 'OrderItem' || objectName == 'DraftOrderItem') && (keyfield != 'unitprice' )){ result = true; }else if ((objectName == 'Product2') && ( keyfield != 'status')){ result = true; }else if ((objectName == 'HIC_ShopifySync__Variant__c')&& (keyfield != 'HIC_ShopifySync__Inventory_Item_Id__c' && keyfield != 'HIC_ShopifySync__Store__c')){ result = true; } return result; } //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;} } /********************************************************* @Method Name : saveDefaultOppStageName @author : SME Team @Description : Save the default opportunity datge name for the selected store @param : storeName (String) - Name of the store @Return type : Boolean (True or False) ********************************************************/ @AuraEnabled public static Boolean saveDefaultOppStageName(String storeName){ Boolean result = false; try{ List fm = new List(); DescribeSObjectResult fieldMappingSchema = getSchemaType('HIC_ShopifySync__HIC_Field_Mapping__c'); CheckAccessibility.isAccessible('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c',fieldMappingSchema); CheckAccessibility.isUpsertable('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c'); CheckAccessibility.isInsertable('Id, HIC_ShopifySync__Object_Name__c,HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, CurrencyIsoCode, Name, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Store__c ,HIC_ShopifySync__Store_External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c'); // System.debug('select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('Name','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Opportunity-StageName\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+storeName+'\' limit 1'); // fm = database.query('select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c',fieldMappingSchema)+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('Name',fieldMappingSchema)+' = \'Opportunity-StageName\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fieldMappingSchema)+' = \''+storeName+'\' limit 1'); String fmQuery = 'select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c,HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__Shopify_Fields__c',fieldMappingSchema)+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('Name',fieldMappingSchema)+' = \'Opportunity-StageName\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c',fieldMappingSchema)+' = \''+storeName+'\' limit 1'; String sanitizedFmQuery=String.escapeSingleQuotes(fmQuery).remove('\\'); fm = database.query(sanitizedFmQuery); String oppStageName = ''; if(fm?.isEmpty()){ Schema.DescribeFieldResult fieldResult = Opportunity.stageName.getDescribe(); List ple = fieldResult.getPickListValues(); if(!ple.isEmpty() && ple != null){ oppStageName = String.valueOf(ple[0].getLabel()); }else{ oppStageName = null; } }else{ return true; } if(String.isNotBlank(oppStageName)){ HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping = new HIC_ShopifySync__HIC_Field_Mapping__c(); fieldMapping.Name = 'Opportunity-StageName'; fieldMapping.HIC_ShopifySync__External_ID__c = 'Opportunity-StageName'; fieldMapping.HIC_ShopifySync__Default_Value__c = true; fieldMapping.HIC_ShopifySync__Object_Name__c = 'Opportunity'; fieldMapping.HIC_ShopifySync__SF_Field__c = 'StageName'; fieldMapping.HIC_ShopifySync__Shopify_Field_Type__c = 'pickList'; fieldMapping.HIC_ShopifySync__SF_Field_Type__c = 'pickList'; fieldMapping.HIC_ShopifySync__Shopify_Fields__c = oppStageName; fieldMapping.HIC_ShopifySync__GQL_Field_API__c = oppStageName; fieldMapping.HIC_ShopifySync__Store__c = storeName; fieldMapping.HIC_ShopifySync__Store_External_ID__c = storeName+fieldMapping.HIC_ShopifySync__External_ID__c; if(CheckAccessibility.isUpsertable('HIC_ShopifySync__Store_External_ID__c,HIC_ShopifySync__Default_Value__c','HIC_ShopifySync__HIC_Field_Mapping__c')){ database.upsert(fieldMapping,HIC_ShopifySync__HIC_Field_Mapping__c.HIC_ShopifySync__Store_External_ID__c,True, AccessLevel.USER_MODE); } result = true; }else{ result = false; } return result; }catch(Exception e){ system.debug('@@@ error message:::'+e.getMessage()+'@@@@ errorline::: '+ e.getLineNumber()); return result; } } /**************************************remoteSite*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * METHOD USED TO CALL REMOTESITESETTING IN THE HOME PAGE * CALL FUTURE METHOD * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static void remoteSite() { System.debug('@@@ this is the future Methods '); // DescribeSObjectResult siteSchema = getSchemaType('Site'); try{ String domainUrl = URL.getOrgDomainUrl().toExternalForm(); // Boolean resultDomainUrl = ShopifyController.createRemoteSiteDynamic('HIC_Shopifymadeeasy_Site_URl', domainUrl); ShopifyController.createRemoteSiteDynamic('HIC_Shopifymadeeasy_Site_URl', domainUrl); // if(resultDomainUrl){ String AuthenticateUrl = ShopifyController.getAuthenticateURL(); if(String.isNotBlank(AuthenticateUrl)){ // String name = 'HICShopifysyncmadeeasy'+DateTime.now().getTime(); String name = 'HIC_SME_AuthenticateUrl'; ShopifyController.createRemoteSiteDynamic(name, AuthenticateUrl); } if(!isSiteSupportedOrg()){ String remoteSiteUrl = ShopifyController.getMiddleWareUrl(); ShopifyController.createRemoteSiteDynamic('HIC_SME_RealTimeUrl', remoteSiteUrl); } // } }Catch(Exception ex){ System.debug('@@@ this is the exception occured at line '+ex.getLineNumber()+' with message :: '+ex.getMessage()); } } /********************************************************* @Method Name : getMiddleWareUrl @author : SME Team @Description : getting url for real time sync @Return : String ********************************************************/ public static String getMiddleWareUrl() { String remoteSiteUrl = null; try { List listofConfiguration = new List(); DescribeSObjectResult configCustomSettingSchema = getSchemaType('HIC_ShopifySync__Configuration__c'); String query = 'SELECT ' + Checkaccessibility.isAccessible('HIC_ShopifySync__Salesforce_Site_URL__c, Name', 'HIC_ShopifySync__Configuration__c') + ' FROM HIC_ShopifySync__Configuration__c WHERE ' + Checkaccessibility.isAccessible('Name', 'HIC_ShopifySync__Configuration__c') + ' = \'Default\' LIMIT 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); listofConfiguration = Database.query(finalQuery); if (!listofConfiguration.isEmpty()) { remoteSiteUrl = listofConfiguration[0].HIC_ShopifySync__Salesforce_Site_URL__c; } } catch (Exception e) { System.debug('Error in getMiddleWareUrl: ' + e.getMessage()); } return remoteSiteUrl; } /********************************************************* @Method Name : createRemoteSiteDynamic @author : SME Team @Description : create the remote site @param : name (String) - Remote site setting name remoteSiteUrl (String) - remote site url @Return : ********************************************************/ @future(callout=true) public static void createRemoteSiteDynamic(String name, String remoteSiteUrl){ Boolean result = false; try{ system.debug('@@@ remoteSiteUrl : '+remoteSiteUrl); system.debug('@@@ name : '+name); if(remoteSiteUrl == null || remoteSiteUrl == '' || checkRemotesiteExists(remoteSiteUrl)){ return; } MetadataServiceNew.MetadataPort service = createServices(); system.debug('@@@ service : '+service); MetadataServiceNew.RemoteSiteSetting remoteSiteSettings = new MetadataServiceNew.RemoteSiteSetting(); remoteSiteSettings.fullName = name; remoteSiteSettings.url = remoteSiteUrl; remoteSiteSettings.description='HIC Shopify Made Easy'; remoteSiteSettings.isActive=true; remoteSiteSettings.disableProtocolSecurity=false; system.debug('@@@ remoteSiteSettings : '+remoteSiteSettings); if(!Test.isRunningTest()){ MetadataServiceNew.AsyncResult[] results = service.create(new List { remoteSiteSettings }); system.debug('@@@ results : '+results); MetadataServiceNew.AsyncResult[] checkResults = service.checkStatus(new List {string.ValueOf(results[0].Id)}); system.debug('@@@ checkResults : '+checkResults); result = true; } system.debug('@@@ final result : '+result); }catch(Exception e){ System.debug('@@@ Remote site setting created :: '+e.getMessage()+' at line number '+e.getLineNumber()); result = false; } // return result; } /**************************************CheckingRemotesiteExistence*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Verfiy RemoteSite Setting exist or not * @param String SFdomainUrl - RemoteSite based on value check existance * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ public static boolean checkRemotesiteExists(String remoteSiteUrl){ boolean result = false; // String OrgURl = URL.getSalesforceBaseUrl().toExternalForm(); String domainUrl = URL.getOrgDomainUrl().toExternalForm(); // String OrgURl = (String) domainUrl; result = HIC_ShopifyUtility.checkRemotesiteExists(remoteSiteUrl,domainUrl ); return result; } /**************************************get Authenticate Url*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Create RemoteSite Setting for Authentication URL * https://test.salesforce.com * https://login.salesforce.com * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getAuthenticateURL(){ Organization orgRecord; String URL = null; DescribeSObjectResult organizationSchema = getSchemaType('organization'); // Schema.SObjectField isSandboxFieldDescribe = organizationSchema.fields.getMap().get('IsSandbox'); if(organizationSchema.isAccessible()){ orgRecord = [select id,issandbox from organization WITH USER_MODE LIMIT 1 ]; if(orgRecord.issandbox){ URL = 'https://test.salesforce.com'; }else{ URL = 'https://login.salesforce.com'; } } return URL; } /**************************************getWriteReviewURL*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get URL For Shopify APP Review * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static string getWriteReviewURL(){ list listofDocument = new list(); list listofDocumentWrapper = new list(); listofDocument = [SELECT Id, Name,Url, FolderId, Folder.Name FROM Document WHERE Folder.Name = 'Hic Shopify made easy logo' and URl != null WITH USER_MODE limit 100]; if(listofDocument.isEmpty()) return null; for(Document dc : listofDocument){ // MapofDocumentNameVsURL.put(dc.name,dc.Url); DocumentWrapper DcObj = new DocumentWrapper(); DcObj.name = dc.name; DcObj.Url = dc.Url; listofDocumentWrapper.add(DcObj); } return JSON.serialize(listofDocumentWrapper); } //Wrapper class for Documents public class DocumentWrapper{ @AuraEnabled public String name{get;set;} @AuraEnabled public String Url{get;set;} } /**************************************setupAccessCheck*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * METHOD TO CHECK THE SITE CLASS , PAGE ACCESS , * SHOPIFY CERTIFICATE AND REMOTE SITE ON SETUP PAGE * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static Map setupAccessCheck(String guestUserId, String accessToken) { Map resultMap = new Map(); try { System.debug('<<<< CHECK PAGE ACCESS :: '); // DescribeSObjectResult siteSchema = getSchemaType('Site'); Boolean hasSiteAccess = isSiteSupportedOrg(); system.debug('@@@ THIS IS GUEST USER ID :: '+guestUserId); resultMap.put('classAndPageAccess', hasSiteAccess ? checkSiteClassandPageAccess(guestUserId) : true); // Use the same reliable methods as preAuthSetupCheck() — the Tooling API path // failed silently when the org domain changed (Hyperforce migration) or returned // unexpected JSON, causing remoteSite/certificate to always show as unchecked. String domainEndpoint = hasSiteAccess ? URL.getOrgDomainUrl().toExternalForm() : getMiddleWareUrl(); resultMap.put('remoteSite', isEndpointWhitelisted(domainEndpoint) && isEndpointWhitelisted(getAuthenticateURL())); resultMap.put('certificate', shopifyCertificateExists()); System.debug('<<<<< THIS IS THE RESULT MAP: ' + resultMap); } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } return resultMap; } /**************************************CheckSiteClassandPageAccess*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Check package class access in Site User * Apex class Name: AuthenticateAllApexClass * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean checkSiteClassandPageAccess(String Guestuserid){ boolean exist = false; try{ List siteList = new List(); list listofsitewrapper = new list(); //OptionsRequireHttps // siteList = database.query('SELECT '+Checkaccessibility.isAccessible('GuestUserId, Name,MasterLabel, Subdomain, UrlPathPrefix', 'Site') +' FROM Site WHERE '+Checkaccessibility.isAccessible('Status','Site') + ' = \'Active\' and '+Checkaccessibility.isAccessible('GuestUserId','Site') + ' = \''+Guestuserid+'\' Limit 1'); String siteQuery = 'SELECT '+Checkaccessibility.isAccessible('GuestUserId, Name,MasterLabel, Subdomain, UrlPathPrefix', 'Site') +' FROM Site WHERE '+Checkaccessibility.isAccessible('Status','Site') + ' = \'Active\' and '+Checkaccessibility.isAccessible('GuestUserId','Site') + ' = \''+Guestuserid+'\' Limit 1'; String sanitizedSiteQuery = String.escapeSingleQuotes(siteQuery).remove('\\'); siteList = database.query(sanitizedSiteQuery); if(!Test.isRunningTest()){ // if(siteList.isEmpty()) return false; if(siteList.isEmpty()) exist = false; } boolean SiteAccess = false; list listofApexclass = new list(); list listofAllApexclass = new list(); list listofApexPage = new list(); list listofALlApexPage = new list(); list listofuser = new list(); Integer NumberOfApexClass =0; Integer NumberOfApexPage=0; listofuser = [select id,profileid from user where usertype= 'Guest' and id =: Guestuserid WITH USER_MODE]; if(!listofuser.isEmpty()){ String profileid = listofuser[0].profileid; NumberOfApexClass = Integer.valueof(System.Label.NumberofApexClasses); listofApexclass = [SELECT NamespacePrefix, Name FROM ApexClass WHERE Id IN (SELECT SetupEntityId FROM SetupEntityAccess WHERE Parent.Profileid =: profileid ) and NamespacePrefix = 'HIC_ShopifySync' and name = 'AuthenticateAllApexClass' WITH USER_MODE limit 1 ]; if(!listofApexclass.isEmpty() && listofApexclass != null ){ exist = true; // return true; } } // return false; return exist; }catch(Exception ex){ System.debug('@@@ EXception Occured at line '+ex.getLineNumber()+' with message '+ex.getMessage()+' with stack trace :: '+ex.getStackTraceString()); return exist; } } /**************************************updateFieldMappingAndConfigration*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * METHOD TO HANDLE saveConfigration , saveFieldMapping AND handleDefaultFieldMapping * FIELD MAPPING PAGE * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static Map updateFieldMappingAndConfigration(Boolean defaultAccount, String configObj, String listofRecord, String accountId, String oppDefaultStage, String oppCloseDays, String storeName){ Map resultMap = new Map(); try{ if(String.isNotBlank(configObj)){ resultMap.put('configration',saveConfigration(configObj,'Normal')); } if(String.isNotBlank(listofRecord)){ resultMap.put('fieldMapping',saveFieldMapping(listofRecord)); } if(defaultAccount != null && defaultAccount){ resultMap.put('defaultFieldMapping',handleDefaultFieldMapping(accountId, oppDefaultStage, oppCloseDays, storeName)); } return resultMap; }catch (Exception e) { throw new AuraHandledException('ERROR MESSAGE :: '+e.getMessage() + 'LINE NUMBER :: '+ e.getLineNumber()); } } /**************************************syncShopify*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Called When Batch Processing is Completed / Started * Update the Configuration setting base in the requirements * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static void syncShopify(String store) { List configurationList = new List(); String query = 'Select ' + CheckAccessibility.isAccessible('name,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Store__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__CollectionsBatchCompleted__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__InventoryBatchCompleted__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c,HIC_ShopifySync__Inventory_Location__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__Batch_Is_Processing__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c', 'HIC_ShopifySync__HIC_Configuration__c') + ' from HIC_ShopifySync__HIC_Configuration__c where ' + CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c') + ' = \'' + store + '\' WITH USER_MODE LIMIT 49999'; String sanitizedQuery = String.escapeSingleQuotes(query).remove('\\'); configurationList = Database.query(sanitizedQuery); if (configurationList.isEmpty()) return; configurationList[0].HIC_ShopifySync__BatchRunOnce__c = true; configurationList[0].HIC_ShopifySync__Batch_Is_Processing__c = true; configurationList[0].HIC_ShopifySync__BatchisAborted__c = false; // Always run the product batch System.debug('Running product batch'); HIC_ShopifyUtility.fetchProducts(configurationList, store); // Update the configuration record if (CheckAccessibility.isUpdateable('name,HIC_ShopifySync__Store__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__CollectionsBatchCompleted__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__InventoryBatchCompleted__c,HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c,HIC_ShopifySync__Inventory_Location__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__Batch_Is_Processing__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c', 'HIC_ShopifySync__HIC_Configuration__c')) { Database.update(configurationList, True, AccessLevel.USER_MODE); } } /**************************************Checkemaildeliverability*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Verify Salesforce Org deliveribilty on or not. * Having email send limits or not * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean checkemaildeliverability(){ Boolean emailsTurnedOn = false; try { Messaging.reserveSingleEmailCapacity(0); emailsTurnedOn = true; } catch (System.NoAccessException e) { } return emailsTurnedOn; } /**************************************SendingMailtoShopifySupport*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Send user message to our Support team * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean sendingMailtoShopifySupport(String issue){ List activeSalesforceUsers = [SELECT COUNT(Id) FROM User WHERE IsActive = TRUE AND Profile.UserLicense.Name = 'Salesforce']; Integer countUsers = (Integer)activeSalesforceUsers[0].get('expr0'); issue = issue + '\n'+ 'Active Users : '+countUsers; boolean emailsend = false; List toAddresses = new List (); toAddresses.add('support@syncmadeasy.com'); String subject = '( Sync Made Easy - New Inquiry ) Organization Id ' + String.valueof(UserInfo.getOrganizationId()); Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage(); email.setSubject(subject); if(!toAddresses.isEmpty() ){ String syncResult = 'sendEmail'; PageReference pageRef = new PageReference('/apex/ShopifyConfigurationResultTemplate?result='+syncResult+'&emailContent='+issue); email.setToAddresses(toAddresses ); if(!Test.isRunningTest()){ email.setHtmlBody(pageRef.getContent().toString().UnescapeHTML4()); } // email.setPlainTextBody(String.valueof(UserInfo.getName()) + ', \n ' + Issue); try{ Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); emailsend = true; }catch(Exception e){ return emailsend; } } return emailsend; } /**************************************getUIThemeDescription*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Salesforce Currennt Theme * Lightnig / Classic * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getUIThemeDescription() { String theme = UserInfo.getUiThemeDisplayed(); return theme; } /**************************************returnDomainUrl*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Salesforce Base URl for Authentication * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static string returnDomainUrl(){ return URL.getOrgDomainUrl().toExternalForm(); } /**************************************checkSitefromConfiguration*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get last saved Salesforce Site URL in Configuration * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static string checkSitefromConfiguration(){ List config = new List(); String query = 'select '+Checkaccessibility.isAccessible('HIC_ShopifySync__Salesforce_Site_URL__c,name ','HIC_ShopifySync__Configuration__c')+' from HIC_ShopifySync__Configuration__c where '+Checkaccessibility.isAccessible('Name','HIC_ShopifySync__Configuration__c')+' = \'Default\' limit 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config = database.query(finalQuery); // config = database.query('select '+Checkaccessibility.isAccessible('HIC_ShopifySync__Salesforce_Site_URL__c,name ','HIC_ShopifySync__Configuration__c')+' from HIC_ShopifySync__Configuration__c where '+Checkaccessibility.isAccessible('Name','HIC_ShopifySync__Configuration__c')+' = \'Default\' limit 1'); if(config.isEmpty()) return 'false'; if(config[0].HIC_ShopifySync__Salesforce_Site_URL__c != null && config[0].HIC_ShopifySync__Salesforce_Site_URL__c != '') { return config[0].HIC_ShopifySync__Salesforce_Site_URL__c; } else{ return 'false'; } } /**************************************savesiteurlconfig*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Save Salesforce's Site URL into Configuration settings * @param String siteurl - Salesforce's Site URl Selected by User * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean savesiteurlconfig(String siteurl){ List config = new List(); String query = 'select '+Checkaccessibility.isAccessible('HIC_ShopifySync__Salesforce_Site_URL__c,name ','HIC_ShopifySync__Configuration__c')+' from HIC_ShopifySync__Configuration__c where '+Checkaccessibility.isAccessible('Name','HIC_ShopifySync__Configuration__c')+' = \'Default\' WITH USER_MODE limit 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config = database.query(finalQuery); if(config.isEmpty()) return false; config[0].HIC_ShopifySync__Salesforce_Site_URL__c = siteurl; try{ // upsert config name ; if(Checkaccessibility.isUpsertable('HIC_ShopifySync__Salesforce_Site_URL__c,name ','HIC_ShopifySync__Configuration__c')){ Database.upsert(config,HIC_ShopifySync__Configuration__c.name,True,AccessLevel.USER_MODE); return true; } else{ return false; } }catch(exception e){ return false; } } /**************************************getActivePricebook*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get list of Active PriceBook from Salesforce * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getActivePricebook(){ List pricebookList = new List(); String query = 'select '+Checkaccessibility.isAccessible('id,name, isStandard', 'pricebook2')+' from pricebook2 where '+Checkaccessibility.isAccessible('IsActive', 'pricebook2')+' = true LIMIT 10000'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); pricebookList = database.query(finalQuery); // pricebookList = database.query('select '+Checkaccessibility.isAccessible('id,name', 'pricebook2')+' from pricebook2 where '+Checkaccessibility.isAccessible('IsActive', 'pricebook2')+' = true LIMIT 10000'); if( !pricebookList.isEmpty() ){ return JSON.serialize( pricebookList ); } return null; } /**************************************savePriceBookMapping*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Save Pricebook field mapping for order and opportunity * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean savePriceBookMapping( String storename, String pricebookId ){ try{ List pricebook2MappingList = new List(); 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__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c') +'= \'Pricebook2Id\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+storename+'\'WITH USER_MODE LIMIT 49999'; String sanitizedQuery = String.escapeSingleQuotes(query).remove('\\'); pricebook2MappingList = database.query(sanitizedQuery); for(HIC_ShopifySync__HIC_Field_Mapping__c mapping : pricebook2MappingList){ mapping.HIC_ShopifySync__Shopify_Fields__c = pricebookId; } // update pricebook2MappingList; if(CheckAccessibility.isUpdateable('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')){ Database.update(pricebook2MappingList,True,AccessLevel.USER_MODE); return true; } else{ return false; } }catch(Exception e){ return false; } } /**************************************updateconfigurationpbatchprocessingfield*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Update Configuration When Batch Processig is completed * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static boolean updateconfigurationpbatchprocessingfield(String store, Boolean isHeapSize){ List config = new List(); String query = 'select '+Checkaccessibility.isAccessible('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__BatchisAborted__c,name ','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' WITH USER_MODE LIMIT 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); config = database.query(finalQuery); // config = database.query('select '+Checkaccessibility.isAccessible('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__BatchisAborted__c,name ','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' WITH USER_MODE LIMIT 49999'); if(config.isempty()) return false; config[0].HIC_ShopifySync__Batch_Is_Processing__c = false; config[0].HIC_ShopifySync__BatchisAborted__c = false; config[0].HIC_ShopifySync__IsCurrencyChanged__c = false; if(isHeapSize){ if(config[0].HIC_ShopifySync__Chunk_Size__c == '250'){ config[0].HIC_ShopifySync__Chunk_Size__c = '100'; }else if(config[0].HIC_ShopifySync__Chunk_Size__c == '100'){ config[0].HIC_ShopifySync__Chunk_Size__c = '50'; }else if(config[0].HIC_ShopifySync__Chunk_Size__c == '50'){ config[0].HIC_ShopifySync__Chunk_Size__c = '25'; } } try{ // if(Checkaccessibility.isUpsertable('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__BatchisAborted__c,name ','HIC_ShopifySync__HIC_Configuration__c')){ // upsert config name ; // return true; if(Checkaccessibility.isUpsertable('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__BatchisAborted__c,name ','HIC_ShopifySync__HIC_Configuration__c')){ // upsert config name ; database.upsert(config,HIC_ShopifySync__HIC_Configuration__c.name, True, AccessLevel.USER_MODE); return true; }else{ return false; } }catch(exception e){ return false; } } /**************************************getSampeledata*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Use for get all sample records from the Shopify's store with limit of 5 in each recoord * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static list getSampeledata(String store){ list listofallsampledata = new list(); List configurationList = new List(); String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c, name,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Order_Sync__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__Batch_Is_Processing__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c ','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' LIMIT 49999'; String sanitizedQuery = String.escapeSingleQuotes(query).remove('\\'); configurationList = database.query(sanitizedQuery); System.debug('configurationList-'+configurationList); listofallsampledata = getlistofobjecforsample('products.json',configurationList,listofallsampledata); listofallsampledata = getlistofobjecforsample('customers.json',configurationList,listofallsampledata); if(configurationList[0].HIC_ShopifySync__Collection_Sync__c){ listofallsampledata = getlistofobjecforsample('custom_collections.json',configurationList,listofallsampledata); }else{ listofallsampledata.add('null'); } if(configurationList[0].HIC_ShopifySync__Order_Sync__c == True ){ listofallsampledata = getlistofobjecforsample('orders.json',configurationList,listofallsampledata); }else{ listofallsampledata.add('null'); } if(configurationList[0].HIC_ShopifySync__Draft_Order_Sync__c ){ listofallsampledata = getlistofobjecforsample('draft_orders.json',configurationList,listofallsampledata); }else{ listofallsampledata.add('null'); } if(configurationList[0].HIC_ShopifySync__Inventory_Location_Sync__c ){ listofallsampledata = getlistofobjecforsample('locations.json',configurationList,listofallsampledata); }else{ listofallsampledata.add('null'); } if(!listofallsampledata.isEmpty()){ return listofallsampledata; }else{ return null; } } /**************************************getlistofobjecforsample*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Use for get all sample records from the Shopify's store with limit of 5 in each recoord * @param String objectname - Shopify's Entity Name (Oject Name) * @param list configurationList - ListofConfigurationSettings * @param list listofallsampledata - list of all sample records * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static list getlistofobjecforsample(String objectname,list configurationList, list listofallsampledata){ String JSONbody; if(configurationList.isEmpty()) return null; JSONbody = HIC_ShopifyUtility.fetchAllDataUsingId(objectname+'?limit=5',configurationList); if(Test.isRunningTest()){ JSONbody = '{"smart_collections":["abc","bcd"]}'; } System.debug('JSONbody:::'+JSONbody); if((JSONbody == '' || JSONbody == null || JSONbody == '{}') ) { listofallsampledata.add('null'); }else{ Map meta = (Map) JSON.deserializeUntyped(JSONbody); if(!meta.isEmpty() && meta.containsKey(objectname.remove('.json'))){ List objectList = (List) meta.get(objectname.remove('.json')); if((objectList.isEmpty() || objectList == null ) && objectname == 'custom_collections.json'){ JSONbody = HIC_ShopifyUtility.fetchAllDataUsingId('smart_collections.json?limit=5',configurationList); if((JSONbody == '' || JSONbody == null || JSONbody == '{}') ) { listofallsampledata.add('null'); return listofallsampledata; }else{ Map metanew = (Map) JSON.deserializeUntyped(JSONbody); if(!meta.isEmpty() && metanew.containsKey('smart_collections')){ objectList = (List) metanew.get('smart_collections'); } } } if(!objectList.isEmpty() && objectList != null ){ listofallsampledata.add(JSON.serialize(objectList)); }else{ listofallsampledata.add('null'); } } } return listofallsampledata; } /**************************************getDefaultAccForConts*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Default Account ID * Saved in Field Mapping * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static HIC_ShopifySync__HIC_Field_Mapping__c getDefaultAccForConts(string store){ System.debug('store in default Account method'+store); List fm = new List(); list AccountExisting = new list(); String fieldtocheck = 'id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c'; String query = 'select '+Checkaccessibility.isAccessible(fieldtocheck, 'HIC_ShopifySync__Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__External_ID__c', 'HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact-Accountid\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' limit 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); fm = database.query(finalQuery); // fm = database.query('select '+Checkaccessibility.isAccessible(fieldtocheck, 'HIC_ShopifySync__Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__External_ID__c', 'HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Contact-Accountid\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' limit 49999'); // system.debug('fm:::'+fm[0]); return fm[0]; } /**************************************getAccountDetails*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get selected Account details to display into the page * Based on Account ID * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static Account getAccountDetails(String accId){ List acc = new List(); String query ='select '+Checkaccessibility.isAccessible('id, Name','Account')+' from Account where '+Checkaccessibility.isAccessible('id','Account')+' =: accId limit 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); acc = database.query(finalQuery); // acc = database.query('select '+Checkaccessibility.isAccessible('id, Name','Account')+' from Account where '+Checkaccessibility.isAccessible('id','Account')+' =: accId limit 1'); if(acc != null && !acc.isEmpty()){ return acc[0]; } return null; } /**************************************getDefaultOppClosedate*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Saved Default Opportunity Closed date * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static HIC_ShopifySync__HIC_Field_Mapping__c getDefaultOppClosedate(string store){ List fm = new List(); String query = 'select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c','HIC_ShopifySync__HIC_Field_Mapping__c') +' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Opportunity-CloseDate\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' limit 49999'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); fm = database.query(finalQuery); // fm = database.query('select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c','HIC_ShopifySync__HIC_Field_Mapping__c') +' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('HIC_ShopifySync__External_ID__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Opportunity-CloseDate\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' limit 49999'); if(!fm.isEmpty()){ return fm[0]; }else{ return null; } } /**************************************getDefaultOppStage*************************************************/ /** * ─────────────────────────────────────────────────────────────────────────────────────────────┐ * Get Default Opportunity's Stage * ────────────────────────────────────────────────────────────────────────────────────────────── * ─────────────────────────────────────────────────────────────────────────────────────────────┘ */ @AuraEnabled public static String getDefaultOppStage(string store){ List fm = new List(); String query = 'select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('Name','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Opportunity-StageName\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' limit 1'; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); fm = database.query(finalQuery); // fm = database.query('select '+Checkaccessibility.isAccessible('id, Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c where '+Checkaccessibility.isAccessible('Name','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Opportunity-StageName\' and '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' limit 1'); // system.debug('getDefaultOppStage'+ fm); if(!fm.isempty() && fm != null && String.isNotBlank(fm[0].HIC_ShopifySync__Shopify_Fields__c)){ return fm[0].HIC_ShopifySync__Shopify_Fields__c; }else{ Schema.DescribeFieldResult fieldResult = Opportunity.stageName.getDescribe(); List ple = fieldResult.getPickListValues(); if(!ple.isEmpty() && ple != null){ return String.valueOf(ple[0].getLabel()); } return null; } } /* ********************************************************* @Method Name : getOpportunityStages @author : SME Team @description : Returns ALL active Opportunity stages from OpportunityStage (setup object), ordered by SortOrder. Unlike the UI API getPicklistValues wire, this is NOT limited to the default record type's picklist assignment, so newly added stages always appear. @return : List> - label/value pairs for combobox ********************************************************* */ @AuraEnabled(cacheable=true) public static List> getOpportunityStages() { List> options = new List>(); try { for (OpportunityStage stage : [ SELECT MasterLabel, ApiName FROM OpportunityStage WHERE IsActive = true WITH USER_MODE ORDER BY SortOrder ASC NULLS LAST ]) { options.add(new Map{ 'label' => stage.MasterLabel, 'value' => stage.ApiName }); } } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } return options; } /* ********************************************************* @Method Name : updatePriceBookCurrencyStage @author : SME Team @description : This Method updates Opportunity Stage Name in field Mapping, Pricebook Id and Currency ISO code ********************************************************* */ @AuraEnabled public static Map updatePriceBookCurrencyStage(String storeName, String defaultStageName, String priceBookId, String currencyCode, String configObj){ Map result = new Map{'OppStageName' => null, 'PriceBook' => null, 'Currency' => null}; try { if (String.isNotBlank(configObj)) { result.put('ConfigObj', saveConfigration(configObj, 'True')); } if (String.isNotBlank(defaultStageName)) { result.put('OppStageName', saveDefaultOppStageName(storeName)); } if (String.isNotBlank(priceBookId)) { result.put('PriceBook', savePriceBookMapping(storeName, pricebookId)); } if (String.isNotBlank(currencyCode)) { result.put('Currency', saveCurrencyMappingList(storeName, currencyCode)); } } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } return result; } /* ********************************************************* @Method Name : getReports @author : SME Team @description : This method is used to get all the report details form the SME Report folder. @params : @return : Map Map of all object with their associated report Id's ********************************************************* */ @AuraEnabled(cacheable=true) public static Map getReports(){ Map mapObjectVsReportId = new Map(); try { String reportFolder = 'SME LWC Reports'; List reportList = new List(); String query = 'SELECT Id, DeveloperName, Name, FolderName ' + 'FROM Report ' + 'WHERE FolderName = \''+reportFolder+'\' WITH USER_MODE LIMIT 49999'; String sanitizedQuery = String.escapeSingleQuotes(query).remove('\\'); reportList = database.query(sanitizedQuery); if(!reportList?.isEmpty()){ for(Report report : reportList){ if(report.DeveloperName == 'SME_Business_Accounts'){ mapObjectVsReportId.put('BusinessAccount', report.Id); }else if(report.DeveloperName == 'SME_Person_Accounts'){ mapObjectVsReportId.put('PersonAccount', report.Id); }else if(report.DeveloperName == 'SME_Contacts'){ mapObjectVsReportId.put('Contact', report.Id); }else if(report.DeveloperName == 'SME_Products'){ mapObjectVsReportId.put('Product', report.Id); }else if(report.DeveloperName == 'SME_Variants'){ mapObjectVsReportId.put('Variant', report.Id); }else if(report.DeveloperName == 'SME_Orders'){ mapObjectVsReportId.put('Order', report.Id); }else if(report.DeveloperName == 'SME_Draft_Orders'){ mapObjectVsReportId.put('DraftOrders', report.Id); }else if(report.DeveloperName == 'SME_Opportunities'){ mapObjectVsReportId.put('Opportunity', report.Id); }else if(report.DeveloperName == 'SME_Locations'){ mapObjectVsReportId.put('Location', report.Id); }else if(report.DeveloperName == 'SME_Collects'){ mapObjectVsReportId.put('Collect', report.Id); }else if(report.DeveloperName == 'SME_Collections'){ mapObjectVsReportId.put('Collection', report.Id); }else if(report.DeveloperName == 'SME_Inventories'){ mapObjectVsReportId.put('Inventory', report.Id); } } } } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } return mapObjectVsReportId; } /* ********************************************************* @Method Name : runPostInstallScript @author : SME Team @description : This method is used to run the post install script. @params : @return : String ********************************************************* */ @AuraEnabled public static String runPostInstallScript(){ try { CustomSettingRecordInsert.runPostScriptAgain(); return 'Success'; } catch (Exception e) { System.debug('Error: ' + e.getMessage()); return 'Error'; } } /* ********************************************************* @Method Name : abortBatch @author : SME Team @description : This method is used to Abort the Batch. @params : @return : Void ********************************************************* */ @AuraEnabled public static Boolean abortBatch() { List jobsToAbort = [SELECT Id, CronTriggerId, JobType from AsyncApexJob WHERE ApexClass.Name IN ('BatchToCreateProducts','FetchAccounts','FetchOrders','FetchSmartCollection_Batch','FetchCollections_Batch','FetchCollects_Batch','FetchLocations_Batch','FetchInventoryItems') AND (Status = 'Queued' OR Status = 'Preparing' OR Status = 'Processing' OR Status = 'Holding') LIMIT 200]; for (AsyncApexJob jobToAbort : jobsToAbort) { if (jobToAbort.JobType == 'BatchApex') { System.abortJob(jobToAbort.Id); } else { System.abortJob(jobToAbort.CronTriggerId); } } return true; } @AuraEnabled(cacheable=true) public static String getOrgEnvironment(){ Organization org = [SELECT IsSandbox FROM Organization LIMIT 1]; return org.IsSandbox ? 'sandbox' : 'production'; } @AuraEnabled public static void copyFieldMapping(String fromStore, String toStore) { if (String.isBlank(fromStore) || String.isBlank(toStore)) { throw new AuraHandledException('Both fromStore and toStore are required.'); } // 1️⃣ Delete esxisting mappings for toStore with error handling List oldMappings = [ SELECT Id FROM HIC_ShopifySync__HIC_Field_Mapping__c WHERE HIC_ShopifySync__Store__c = :toStore ]; if (!oldMappings.isEmpty()) { // Use Database.delete to get results and allOrNone=false to partial success Database.DeleteResult[] deleteResults = Database.delete(oldMappings, false); // Check if delete was successful for (Database.DeleteResult dr : deleteResults) { if (!dr.isSuccess()) { // Get first error String errorMsg = dr.getErrors()[0].getMessage(); throw new AuraHandledException('Failed to delete existing mappings: ' + errorMsg); } } } // 2️⃣ Only proceed if delete succeeded - Query source mappings List sourceMappings = [ SELECT Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__External_ID__c, HIC_ShopifySync__GQL_Field_API__c, HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__Object_Mapping__c, HIC_ShopifySync__Object_Name__c, HIC_ShopifySync__SF_Field_Type__c, HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Field_Type__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Shopify_Object__c, HIC_ShopifySync__Store_External_ID__c, HIC_ShopifySync__Store__c FROM HIC_ShopifySync__HIC_Field_Mapping__c WHERE HIC_ShopifySync__Store__c = :fromStore ]; if (sourceMappings.isEmpty()) { throw new AuraHandledException('No mappings found for store: ' + fromStore); } List newMappings = new List(); for (HIC_ShopifySync__HIC_Field_Mapping__c mapRec : sourceMappings) { // Clone record (no Id) HIC_ShopifySync__HIC_Field_Mapping__c newRec = mapRec.clone(false, true, false, false); // Set new store newRec.HIC_ShopifySync__Store__c = toStore; String oldExternalId = mapRec.HIC_ShopifySync__Store_External_ID__c; if (fromStore == 'Default') { // ✅ YOUR RULE FOR DEFAULT - Just prefix new store, NO replace newRec.HIC_ShopifySync__Store_External_ID__c = toStore + oldExternalId; } else { // Normal case — replace old store with new store newRec.HIC_ShopifySync__Store_External_ID__c = oldExternalId.replace(fromStore, toStore); } newMappings.add(newRec); } // 3️⃣ Insert with error handling Database.SaveResult[] insertResults = Database.insert(newMappings, false); // Check for insert errors List insertErrors = new List(); for (Database.SaveResult sr : insertResults) { if (!sr.isSuccess()) { insertErrors.add(sr.getErrors()[0].getMessage()); } } if (!insertErrors.isEmpty()) { throw new AuraHandledException('Failed to insert new mappings: ' + String.join(insertErrors, '; ')); } System.debug('Successfully copied ' + newMappings.size() + ' mappings from ' + fromStore + ' to ' + toStore); } @AuraEnabled public static String getConfigrationForMultipleStore() { try { List cyptokeyquery = getCryptoKey(); if(cyptokeyquery == null || cyptokeyquery.isEmpty()){ return null; } List configList = new List(); String query = 'select ' + Checkaccessibility.isAccessible( 'id,HIC_ShopifySync__Store__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Cryptokey__c,HIC_ShopifySync__BatchRunOnce__c,HIC_ShopifySync__BatchisAborted__c,HIC_ShopifySync__Order__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Enable_Draft_Order__c ,HIC_ShopifySync__Refresh_Token__c,name,HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Shopify_URL__c,HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Salesforce_Site_URL__c, HIC_ShopifySync__Opportunity_Sync__c, HIC_ShopifySync__Inventory_Location_Sync__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Product_Sync__c, HIC_ShopifySync__Customer_Sync__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Salesforce_Pricebook__c', 'HIC_ShopifySync__HIC_Configuration__c' ) + ' from HIC_ShopifySync__HIC_Configuration__c '; String finalQuery = String.escapeSingleQuotes(query).remove('\\'); configList = database.query(finalQuery); if (configList.isEmpty()){ return null; } for (HIC_ShopifySync__HIC_Configuration__c config : configList) { if ( config.HIC_ShopifySync__Private_Key_Password__c != null && config.HIC_ShopifySync__Private_Key_Password__c != '' ) { String password = String.valueof( config.HIC_ShopifySync__Private_Key_Password__c ); Blob cryptoKey = Blob.valueOf( String.valueof(cyptokeyquery[0].HIC_ShopifySync__Cryptokey__c) ); Blob data = Blob.valueOf(password); Blob encryptedData = Crypto.encryptWithManagedIV( 'AES128', cryptoKey, data ); String b64Data = EncodingUtil.base64Encode(encryptedData); if (b64Data != null && b64Data != '') { config.HIC_ShopifySync__Private_Key_Password__c = b64Data; } } } return JSON.serialize(configList); } catch (Exception e) { return e.getMessage() + '' + e.getLineNumber(); } } @AuraEnabled public static String getStoreAccessToken(String storename) { try { if (String.isBlank(storename)) { return null; } List configList = [ SELECT HIC_ShopifySync__Private_Key_Password__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = :storename LIMIT 1 ]; if (configList.isEmpty()) { return null; } return configList[0].HIC_ShopifySync__Private_Key_Password__c; } catch (Exception e) { System.debug('Error in getStoreAccessToken: ' + e.getMessage()); throw new AuraHandledException('Unable to fetch access token'); } } /** * Builds a Shopify OAuth authorization URL for offline (permanent) access token generation. * Encodes store credentials in the state parameter so the callback VF page can exchange * the code without needing server-side credential storage. * * Scopes requested: all scopes required by SyncMadeEasy (products, orders, customers, * draft orders, inventory, locations, fulfillments, checkouts). */ @AuraEnabled public static String initShopifyTokenGeneration(String storeName, String clientId, String clientSecret, String redirectUri) { try { if (String.isBlank(storeName) || String.isBlank(clientId) || String.isBlank(clientSecret) || String.isBlank(redirectUri)) { throw new AuraHandledException('Store name, Client ID, Client Secret, and Redirect URI are required.'); } // Encode storeName + credentials as URL-safe base64 JSON for the state param. // The callback VF page decodes this to retrieve the credentials needed for the token exchange. Map statePayload = new Map{ 'store' => storeName, 'clientId' => clientId, 'clientSecret' => clientSecret }; String stateJson = JSON.serialize(statePayload); String stateBase64 = EncodingUtil.base64Encode(Blob.valueOf(stateJson)); // Make base64 URL-safe (RFC 4648) String state = stateBase64.replace('+', '-').replace('/', '_').replace('=', ''); // All scopes needed for SyncMadeEasy objects String scopes = 'read_products,write_products,' + 'read_customers,write_customers,' + 'read_orders,write_orders,' + 'read_draft_orders,write_draft_orders,' + 'read_inventory,write_inventory,' + 'read_locations,' + 'read_fulfillments,write_fulfillments,' + 'read_checkouts,write_checkouts'; String authUrl = 'https://' + storeName + '.myshopify.com/admin/oauth/authorize' + '?client_id=' + EncodingUtil.urlEncode(clientId, 'UTF-8') + '&scope=' + EncodingUtil.urlEncode(scopes, 'UTF-8') + '&redirect_uri=' + EncodingUtil.urlEncode(redirectUri,'UTF-8') + '&state=' + state; return authUrl; } catch (AuraHandledException e) { throw e; } catch (Exception e) { throw new AuraHandledException('Failed to build token generation URL: ' + e.getMessage()); } } @AuraEnabled public static String updateAutoConfiguration(String storeName, Boolean isAuto) { System.Debug('Method is Executed'); try { List configs = [ SELECT Id, HIC_ShopifySync__Auto_Configuration__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Name = :storeName LIMIT 1 ]; if(configs.isEmpty()) { return 'Error: Store not found'; } System.debug('Configuration list are : '+configs); HIC_ShopifySync__HIC_Configuration__c config = configs[0]; config.HIC_ShopifySync__Auto_Configuration__c = isAuto; update config; return 'Success'; } catch(Exception e) { throw new AuraHandledException('Error updating Auto Configuration in Store: ' + e.getMessage()); } } @AuraEnabled public static Boolean getAutoConfigurationStatus(String storeName) { try { if (String.isBlank(storeName)) { return false; } List configs = [ SELECT HIC_ShopifySync__Auto_Configuration__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Name = :storeName LIMIT 1 ]; return !configs.isEmpty() && configs[0].HIC_ShopifySync__Auto_Configuration__c == true; } catch (Exception e) { System.debug('Error in getAutoConfigurationStatus: ' + e.getMessage()); return false; } } //This method is used to checkt the SME Pro Package is installed or not @AuraEnabled(cacheable=true) // ← cacheable=true works now — no callout needed ✅ public static Boolean isPackageInstalled(String namespace) { try { List licenses = [ SELECT Id, NamespacePrefix, Status FROM PackageLicense WHERE NamespacePrefix = :namespace LIMIT 1 ]; System.debug('PackageLicense found: ' + licenses.size()); System.debug('PackageLicense: ' + licenses); return licenses.size() > 0; } catch (Exception e) { System.debug('isPackageInstalled Error: ' + e.getMessage()); return false; } } //This method is used to check the installed package is valid or not @AuraEnabled(cacheable=true) public static Boolean isPackageValid(String namespace){ try{ // SANDBOX BYPASS: sandbox installs always carry Trial/short-expiry licenses, // so expiry/status validation only applies to production. The LWC only calls // this when the package IS installed, so returning true here is safe. Organization orgRecord = [SELECT IsSandbox FROM Organization LIMIT 1]; if(orgRecord.IsSandbox){ return true; } PackageLicense packLicense = [SELECT Id, NamespacePrefix, Status,ExpirationDate FROM PackageLicense WHERE NamespacePrefix = :namespace LIMIT 1]; if((packLicense.Status == 'Active'||packLicense.Status == 'Trial') && (packLicense.ExpirationDate == null || packLicense.ExpirationDate > System.now())){ return true; } return false; }catch(Exception e){ System.debug('isPackageValid Error: ' + e.getMessage()); return false; } } @AuraEnabled(cacheable=true) public static String getDefaultSiteUrl() { try { List defaultConfigs = [ SELECT Id, HIC_ShopifySync__Salesforce_Site_URL__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = 'Default' LIMIT 1 ]; if (!defaultConfigs.isEmpty() && defaultConfigs[0].HIC_ShopifySync__Salesforce_Site_URL__c != null) { return defaultConfigs[0].HIC_ShopifySync__Salesforce_Site_URL__c; } return null; } catch (Exception e) { throw new AuraHandledException('Error fetching default site URL: ' + e.getMessage()); } } @AuraEnabled public static Boolean saveSiteUrlOnHicConfig(String siteurl){ try { List config = [ SELECT Id, HIC_ShopifySync__Salesforce_Site_URL__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Name = 'Default' WITH USER_MODE LIMIT 1 ]; if (config.isEmpty()) return false; config[0].HIC_ShopifySync__Salesforce_Site_URL__c = siteurl; if (Checkaccessibility.isUpdateable('HIC_ShopifySync__Salesforce_Site_URL__c', 'HIC_ShopifySync__HIC_Configuration__c')) { Database.update(config, true, AccessLevel.USER_MODE); return true; } return false; } catch (Exception e) { System.debug('saveSiteUrlOnHicConfig error: ' + e.getMessage() + ' at line ' + e.getLineNumber()); return false; } } /* ******************************************************** @Method Name : getLastOrderSyncTime @author : SME Team @description : DISPLAY-ONLY. Read-only. Returns the CreatedDate (epoch millis, as String) of the most recently synced paid Order/ Opportunity for the given store, so the UI can render "Last order synced X ago". CreatedDate = the actual sync-in moment (LastModifiedDate would move on later re-syncs). Returns null when the store has no synced orders yet. No DML. @param : store (String) - Name of the store @Return : String - epoch milliseconds of the last synced order, or null ******************************************************** */ // NOT cacheable: this value changes over time (new orders sync in) and is // called imperatively, so it must always hit the server fresh rather than // risk returning a stale client-cached result. @AuraEnabled public static String getLastOrderSyncTime(String store) { try { if (String.isBlank(store)) return null; // Which target object(s) does THIS store actually sync into? // A store can sync paid orders as Order records, Opportunity records, // or both — so read its config toggles first. List cfg = [ SELECT HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = :store WITH USER_MODE LIMIT 1 ]; System.debug('Store-->'+ store ); if (cfg.isEmpty()) return null; Boolean orderOn = cfg[0].HIC_ShopifySync__Order__c == true; Boolean oppOn = cfg[0].HIC_ShopifySync__Opportunity__c == true; Datetime latest = null; // Paid Order = Payment_Status populated, synced from Shopify for this store. // CreatedDate = when the record was first synced into Salesforce (the // actual "synced" moment), NOT LastModifiedDate which a later re-sync // or field update would bump forward. if (orderOn && !oppOn) { List ords = [ SELECT CreatedDate FROM Order WHERE HIC_ShopifySync__Shopify_Id__c != null AND HIC_ShopifySync__Store__c = :store AND HIC_ShopifySync__Payment_Status__c != null WITH USER_MODE ORDER BY CreatedDate DESC LIMIT 1 ]; if (!ords.isEmpty()) latest = ords[0].CreatedDate; system.debug('latest-->'+latest); system.debug('now-->'+system.now()); } // Paid Opportunity (when the store syncs orders as Opportunities). if (oppOn && !orderOn) { List opps = [ SELECT CreatedDate FROM Opportunity WHERE HIC_ShopifySync__Shopify_Id__c != null AND HIC_ShopifySync__Store__c = :store AND HIC_ShopifySync__Payment_Status__c != null WITH USER_MODE ORDER BY CreatedDate DESC LIMIT 1 ]; if (!opps.isEmpty() && (latest == null || opps[0].CreatedDate > latest)) { latest = opps[0].CreatedDate; } } if (orderOn && oppOn) { List ords = [ SELECT CreatedDate FROM Order WHERE HIC_ShopifySync__Shopify_Id__c != null AND HIC_ShopifySync__Store__c = :store AND HIC_ShopifySync__Payment_Status__c != null WITH USER_MODE ORDER BY CreatedDate DESC LIMIT 1 ]; if (!ords.isEmpty()) latest = ords[0].CreatedDate; system.debug('latest-->'+latest); system.debug('now-->'+system.now()); } // null => no paid order/opportunity ever synced from this store => // the LWC hides the "Last order synced" line entirely. if (latest == null) return null; // Compute the elapsed time on the server using Datetime.now(). // Both getTime() values are absolute epoch millis (GMT-based), so the // difference is timezone-independent and always correct. Datetime nowDt = Datetime.now(); // Get current user's timezone dynamically TimeZone userTz = UserInfo.getTimeZone(); // Get the timezone offset for the current datetime Integer offsetSeconds = userTz.getOffset(nowDt) / 1000; // Add the user's timezone offset to nowDt Datetime userNowDt = nowDt.addSeconds(offsetSeconds); System.debug('Now GMT --> ' + nowDt); System.debug('Now User Time --> ' + userNowDt); Long diffMs = userNowDt.getTime() - latest.getTime(); if (diffMs < 0) { diffMs = 0; } Long totalMin = diffMs / 60000; // whole minutes Long days = totalMin / 1440; Long hours = Math.mod(totalMin, 1440) / 60; Long minutes = Math.mod(totalMin, 60); String ago; if (totalMin < 1) { ago = 'just now'; } else if (days > 0) { ago = days + (days == 1 ? ' day' : ' days'); if (hours > 0) ago += ' ' + hours + (hours == 1 ? ' hour' : ' hours'); ago += ' ago'; } else if (hours > 0) { ago = hours + (hours == 1 ? ' hour' : ' hours'); if (minutes > 0) ago += ' ' + minutes + ' min'; ago += ' ago'; } else { ago = minutes + ' min ago'; } return (ago == 'just now') ? 'Last order synced just now' : 'Last order synced ' + ago; } catch (Exception e) { System.debug('getLastOrderSyncTime error: ' + e.getMessage() + ' at line ' + e.getLineNumber()); return null; } } @AuraEnabled(cacheable=true) public static String getOrganizationName() { return [ SELECT Name FROM Organization LIMIT 1 ].Name; } }