/** * @description : Use for Generic Method * @author : Satyam Mishra * @group : * @last modified on : 21-jan- 2025 * @last modified by : Satyam Mishra **/ global with sharing class SyncShopifyBatch implements Database.Batchable, Database.allowscallouts, Database.Stateful{ Boolean checkException = false; String linkForNextPage = ''; Boolean isRelatedUrl = false; Boolean isEnd = false; String store = 'Default'; String updated_at_min = ''; String updated_at_max = ''; String resourceName=''; String parentResource =''; List listOfConfiguration; List relatedObjectMapping; List objectMappingList; List listOfparentId = new List(); String companyTimeZone; global SyncShopifyBatch(String linkForNextPage,Boolean isEnd, String store, String updated_at_min, String updated_at_max,String resourceName, List objectMappingList){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; this.objectMappingList =objectMappingList; this.isRelatedUrl =false; checkException = false; this.store = store; this.updated_at_min = updated_at_min; this.updated_at_max = updated_at_max; this.resourceName=resourceName; this.companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey; } global SyncShopifyBatch(String linkForNextPage, Boolean isEnd, List listOfparentId, String parentResource, String resourceName ,List relatedObjectMapping, String updated_at_min, String updated_at_max, String store){ this.resourceName =resourceName; this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; this.store = store; this.isRelatedUrl = true; this.parentResource = parentResource; this.relatedObjectMapping = relatedObjectMapping; //this.objectMappingList = relatedObjectMapping; this.listOfparentId = listOfparentId; this.companyTimeZone = [SELECT Id, TimeZoneSidKey FROM Organization Limit 1][0].TimeZoneSidKey; } global Iterable start(Database.BatchableContext bc) { String JSONResponseBody = ''; String JSONResponse = ''; String queryForConfig = 'Select ' + CheckAccessibility.isAccessible('HIC_ShopifySync__Chunk_Size__c,id,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__Draft_Order_Sync__c,HIC_ShopifySync__Order_Sync__c,HIC_ShopifySync__Collection_Sync__c,HIC_ShopifySync__Inventory_Location_Sync__c, name,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__Collection__c, HIC_ShopifySync__Number_of_pages_for_Account__c,HIC_ShopifySync__OrderBatchCompleted__c, HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__Specify_Close_Date__c, HIC_ShopifySync__Default_Account__c,HIC_ShopifySync__InventoryBatchCompleted__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__API_Key__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Account_Contact__c', 'HIC_ShopifySync__HIC_Configuration__c') + ' from HIC_ShopifySync__HIC_Configuration__c where ' + CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c') + ' = \'' + store + '\' limit 1'; listOfConfiguration = Database.query(queryForConfig); if (listOfConfiguration.isEmpty()) { return new List(); } Map main = new Map(); try { if (String.isNotBlank(linkForNextPage) && !isEnd) { if (!isRelatedUrl) { if (resourceName == 'orders') { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(resourceName + '.json?status=any&limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + '&page_info=' + linkForNextPage, listOfConfiguration); } else { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(resourceName + '.json?limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + '&page_info=' + linkForNextPage, listOfConfiguration); } } else { if (resourceName == 'orders') { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(parentResource + '/' + listOfparentId[0] + '/' + resourceName + '.json?status=any&limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + '&page_info=' + linkForNextPage, listOfConfiguration); } else { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(parentResource + '/' + listOfparentId[0] + '/' + resourceName + '.json?limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + '&page_info=' + linkForNextPage, listOfConfiguration); } } } else { if (!isRelatedUrl) { if (resourceName == 'orders') { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(resourceName + '.json?status=any&limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + (updated_at_min != '' ? '&updated_at_min=' + updated_at_min : '') + (updated_at_max != '' ? '&updated_at_max=' + updated_at_max : ''), listOfConfiguration); } else { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(resourceName + '.json?limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + (updated_at_min != '' ? '&updated_at_min=' + updated_at_min : '') + (updated_at_max != '' ? '&updated_at_max=' + updated_at_max : ''), listOfConfiguration); } } else { if (resourceName == 'orders') { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(parentResource + '/' + listOfparentId[0] + '/' + resourceName + '.json?status=any&limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + (updated_at_min != '' ? '&updated_at_min=' + updated_at_min : '') + (updated_at_max != '' ? '&updated_at_max=' + updated_at_max : ''), listOfConfiguration); listOfparentId.remove(0); } else { JSONResponse = SyncBatchUtility.fetchAllDataWithLinkForNextPage(parentResource + '/' + listOfparentId[0] + '/' + resourceName + '.json?limit=' + listOfConfiguration[0].HIC_ShopifySync__Chunk_Size__c + (updated_at_min != '' ? '&updated_at_min=' + updated_at_min : '') + (updated_at_max != '' ? '&updated_at_max=' + updated_at_max : ''), listOfConfiguration); listOfparentId.remove(0); } } } if (String.isNotBlank(JSONResponse)) { main = (Map) JSON.deserializeUntyped(JSONResponse); if (!main.isEmpty() && main.containsKey('response') && main.containsKey('link')) { if (main.get('response') != null) { JSONResponseBody = String.valueOf(main.get('response')); } if (main.get('link') != null) { linkForNextPage = String.valueOf(main.get('link')); } else { isEnd = true; } } else { isEnd = true; } } else { isEnd = true; } if (String.isBlank(JSONResponseBody)) { checkException = true; } } catch (Exception e) { checkException = true; System.debug('Exception: ' + e.getMessage()); } if (!checkException) { Map meta = (Map) JSON.deserializeUntyped(JSONResponseBody); return (List) meta.get(resourceName); } else { return new List(); } } global void execute(Database.BatchableContext bc , List scope){ objectMappingList =[ SELECT Id, Name, HIC_ShopifySync__Resource__c, HIC_ShopifySync__Default__c,HIC_ShopifySync__Batch_Size__c,HIC_ShopifySync__Store__c, HIC_ShopifySync__Preference__c, HIC_ShopifySync__sObject_Name__c, HIC_ShopifySync__JSON_Nested__c, (SELECT Id, Name, HIC_ShopifySync__Object_Mapping__c, HIC_ShopifySync__Resource__c, HIC_ShopifySync__JSON_Nested__c, HIC_ShopifySync__Default__c,HIC_ShopifySync__Store__c, HIC_ShopifySync__Preference__c, HIC_ShopifySync__sObject_Name__c FROM HIC_ShopifySync__Object_Mappings__r LIMIT 200), (Select Id, Default__c, Key__c, Value_Of__c FROM Data_Mappings__r LIMIT 200) FROM HIC_ShopifySync__Object_Mapping__c WHERE HIC_ShopifySync__Resource__c = :resourceName AND HIC_ShopifySync__Store__c = :store ORDER BY HIC_ShopifySync__Preference__c ]; if(!scope.isEmpty() && !objectMappingList.isEmpty()){ for (HIC_ShopifySync__Object_Mapping__c webhookObjToUpsert : objectMappingList) { String fmQuery = GenericAPIWebUtility.generateFieldMappingQuery(webhookObjToUpsert.Id); list listOfFiledMapping = new list(); listOfFiledMapping = database.query(fmQuery); String listType = 'List<' +webhookObjToUpsert.HIC_ShopifySync__sObject_Name__c+ '>'; list listOfSobjToUpsert = (List)Type.forName(listType).newInstance(); for(Object JsonObject : scope){ Map JsonObjectMap = (Map) JsonObject; if (webhookObjToUpsert.HIC_ShopifySync__JSON_Nested__c != null && webhookObjToUpsert.HIC_ShopifySync__JSON_Nested__c.contains('.')) { String[] nestedKeys = webhookObjToUpsert.HIC_ShopifySync__JSON_Nested__c.split('\\.'); Object nestedValue = JsonObjectMap.get(nestedKeys[0]); if (nestedValue instanceof Map) { JsonObjectMap = (Map) nestedValue; } else if (nestedValue instanceof List) { List nestedList = (List) nestedValue; if (!nestedList.isEmpty() && nestedList[0] instanceof Map) { JsonObjectMap = (Map) nestedList[0]; } else { return; } } else { return; // Exit or handle the error } webhookObjToUpsert.HIC_ShopifySync__JSON_Nested__c = nestedKeys[1]; } List jsonList = new List(); String requestBody=JSON.serialize(JsonObjectMap); jsonList = GenericAPIWebUtility.processDataMapping(webhookObjToUpsert.HIC_ShopifySync__Json_Nested__c, webhookObjToUpsert.Data_Mappings__r, JsonObjectMap); //Satyam needs to check //List JSONList = GenericAPIWebUtility.filterAndImproveJSONBody(webhookObjToUpsert.HIC_ShopifySync__Default__c, webhookObjToUpsert.HIC_ShopifySync__Nested_Key__c, JsonObjectMap, webhookObjToUpsert.HIC_ShopifySync__Other_Relationship_Name__c, webhookObjToUpsert.HIC_ShopifySync__Other_Relationship_Key__c, requestBody, webhookObjToUpsert.HIC_ShopifySync__Relationship_field_Name__c, webhookObjToUpsert.HIC_ShopifySync__Relationship_Key__c); for(object obj : JSONList){ //JsonObjectMap = (Map) obj; Sobject sobjRecord = GenericAPIWebUtility.processFieldTypeAndMapping(listOfFiledMapping, String.valueOf(webhookObjToUpsert.HIC_ShopifySync__sObject_Name__c), (Map)obj ,companyTimeZone, store); if(sobjRecord != null) listOfSobjToUpsert.add(sobjRecord); } } Schema.SObjectType SfObject = Schema.getGlobalDescribe().get(webhookObjToUpsert.HIC_ShopifySync__sObject_Name__c); Map sfFieldsMap = SfObject.getDescribe().fields.getMap(); Schema.SobjectField ShopifyId = sfFieldsMap.get('HIC_ShopifySync__Shopify_Id__c'); List updateResult = new List (); try{ if(CheckAccessibility.isUpsertable(String.valueOf(ShopifyId),webhookObjToUpsert.HIC_ShopifySync__sObject_Name__c)){ Map mapToRestricDuplicateRecord = new map(); for(SObject record: listOfSobjToUpsert) { if(record.get('HIC_ShopifySync__Shopify_Id__c') !=null) { mapToRestricDuplicateRecord.put(record.get('HIC_ShopifySync__Shopify_Id__c'),record ); if(webhookObjToUpsert.HIC_ShopifySync__Object_Mappings__r.size()>0){ listOfparentId.add(String.valueOf(record.get('HIC_ShopifySync__Shopify_Id__c'))); parentResource = webhookObjToUpsert.HIC_ShopifySync__Resource__c; relatedObjectMapping = webhookObjToUpsert.HIC_ShopifySync__Object_Mappings__r; } } } updateResult = Database.upsert(mapToRestricDuplicateRecord.values(),ShopifyId, false); SyncBatchUtility.updateErrorMassage(updateResult, webhookObjToUpsert.HIC_ShopifySync__sObject_Name__c, mapToRestricDuplicateRecord.values(), ShopifyId, false, store); } }catch(DmlException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } //updateAllSfRecordFromShopifyUtility.upsertSFRecords( bodyMap, webhookObjToUpsert, requestBody, storeName ); } } } global void finish(Database.BatchableContext bc) { if (!listOfparentId.isEmpty() && isEnd) { if (relatedObjectMapping != null && !relatedObjectMapping.isEmpty()) { SyncShopifyBatch callBatchAgain = new SyncShopifyBatch( linkForNextPage, false, listOfparentId, parentResource, String.valueOf(relatedObjectMapping[0].HIC_ShopifySync__Resource__c), relatedObjectMapping, updated_at_min, updated_at_max, store ); Database.executeBatch(callBatchAgain, 50); } else { } } if (!checkException && !isEnd && listOfparentId.isEmpty()) { // Call batch again if got any exception on page if (objectMappingList != null && !objectMappingList.isEmpty()) { SyncShopifyBatch callBatchAgain = new SyncShopifyBatch( linkForNextPage, false, store, updated_at_min, updated_at_max, resourceName, objectMappingList ); Database.executeBatch(callBatchAgain, integer.valueOf(objectMappingList[0].HIC_ShopifySync__Batch_Size__c)); } else { System.debug('objectMappingList is null or empty line 261'); } } else if (checkException && !isEnd && listOfparentId.isEmpty()) { if (String.isNotBlank(linkForNextPage)) { // Call batch again for next page of record pagination if (objectMappingList != null && !objectMappingList.isEmpty()) { SyncShopifyBatch callBatchAgain = new SyncShopifyBatch( linkForNextPage, false, store, updated_at_min, updated_at_max, resourceName, objectMappingList ); Database.executeBatch(callBatchAgain, integer.valueOf(objectMappingList[0].HIC_ShopifySync__Batch_Size__c)); } else { System.debug('objectMappingList is null or empty line 278'); } } } else if (isEnd && listOfparentId.isEmpty()) { if (listOfConfiguration != null && !listOfConfiguration.isEmpty()) { HIC_ShopifySync__HIC_Configuration__c config = listOfConfiguration[0]; if (resourceName == 'products') { config.HIC_ShopifySync__ProductVariantBatchCompleted__c = true; update config; SyncBatchUtility.fetchCustomer(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (resourceName == 'customers') { config.HIC_ShopifySync__AccountContactBatchCompleted__c = true; update config; if (config.HIC_ShopifySync__Order_Sync__c || config.HIC_ShopifySync__Opportunity__c) { SyncBatchUtility.fetchOrderAndOpportunity(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (config.HIC_ShopifySync__Collection_Sync__c) { SyncBatchUtility.processCollect(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (config.HIC_ShopifySync__Inventory_Location_Sync__c && config.HIC_ShopifySync__Inventory_Location__c) { SyncBatchUtility.fetchLocationsAndInventoryLevels(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (config.HIC_ShopifySync__Draft_Order_Sync__c || config.HIC_ShopifySync__Enable_Draft_Order__c || config.HIC_ShopifySync__Enable_Opportunity_for_SDO__c) { SyncBatchUtility.fetchDraftorders(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (!config.HIC_ShopifySync__Order_Sync__c && config.HIC_ShopifySync__Opportunity__c && !config.HIC_ShopifySync__Draft_Order_Sync__c && !config.HIC_ShopifySync__Collection_Sync__c) { config.HIC_ShopifySync__Batch_Is_Processing__c = false; update config; } } else if (resourceName == 'orders') { config.HIC_ShopifySync__OrderBatchCompleted__c = true; update config; if (config.HIC_ShopifySync__Collection_Sync__c) { SyncBatchUtility.processCollect(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (config.HIC_ShopifySync__Inventory_Location_Sync__c && config.HIC_ShopifySync__Inventory_Location__c) { SyncBatchUtility.fetchLocationsAndInventoryLevels(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (config.HIC_ShopifySync__Draft_Order_Sync__c || config.HIC_ShopifySync__Enable_Draft_Order__c || config.HIC_ShopifySync__Enable_Opportunity_for_SDO__c) { SyncBatchUtility.fetchDraftorders(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (!config.HIC_ShopifySync__Draft_Order_Sync__c && !config.HIC_ShopifySync__Collection_Sync__c) { config.HIC_ShopifySync__Batch_Is_Processing__c = false; update config; } } else if (resourceName == 'collections') { config.HIC_ShopifySync__CollectionsBatchCompleted__c = true; update config; if (config.HIC_ShopifySync__Inventory_Location_Sync__c && config.HIC_ShopifySync__Inventory_Location__c) { SyncBatchUtility.fetchLocationsAndInventoryLevels(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (config.HIC_ShopifySync__Draft_Order_Sync__c || config.HIC_ShopifySync__Enable_Draft_Order__c || config.HIC_ShopifySync__Enable_Opportunity_for_SDO__c) { SyncBatchUtility.fetchDraftorders(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (!config.HIC_ShopifySync__Draft_Order_Sync__c) { config.HIC_ShopifySync__Batch_Is_Processing__c = false; update config; } } else if (resourceName == 'locations') { config.HIC_ShopifySync__InventoryBatchCompleted__c = true; update config; if (config.HIC_ShopifySync__Draft_Order_Sync__c) { SyncBatchUtility.fetchDraftorders(store, updated_at_min, updated_at_max, listOfConfiguration); } else if (!config.HIC_ShopifySync__Draft_Order_Sync__c) { config.HIC_ShopifySync__Batch_Is_Processing__c = false; update config; } } else if (resourceName == 'draft_orders') { config.HIC_ShopifySync__DraftOrderBatchCompleted__c = true; config.HIC_ShopifySync__Batch_Is_Processing__c = false; update config; } else { config.HIC_ShopifySync__Batch_Is_Processing__c = false; update config; } } else { System.debug('listOfConfiguration is null or empty'); } } } }