global with sharing class FetchCheckouts implements Database.Batchable, Database.allowscallouts, Database.Stateful{ Type typLstSObject; String linkForNextPage = ''; //Pagination link Boolean isEnd = false; String store = 'Default'; String updated_at_min = ''; String updated_at_max = ''; public List configurationList; global FetchCheckouts(String linkForNextPage,boolean isEnd){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; } global FetchCheckouts(String linkForNextPage,boolean isEnd, String store){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; this.store = store; } global FetchCheckouts(String linkForNextPage,boolean isEnd, String store, String updated_at_min, String updated_at_max){ this.linkForNextPage = linkForNextPage; this.isEnd = isEnd; this.store = store; this.updated_at_min = updated_at_min; this.updated_at_max = updated_at_max; } global Iterable start(Database.BatchableContext bc){ String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Chunk_Size__c,id,name,HIC_ShopifySync__ProductVariantBatchCompleted__c,HIC_ShopifySync__Inventory_Location__c,HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__AccountContactBatchCompleted__c,HIC_ShopifySync__Collection__c,HIC_ShopifySync__Number_of_pages_for_Account__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__Account_Contact__c, HIC_ShopifySync__Default_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 1'; configurationList = Database.query(query); String checkoutResponse = ''; String JSONResponse = ''; if(!Test.isRunningTest()){ // Get Shopif's Checkouts and CheckoutlineItem JSON Response if(String.isNotBlank(linkForNextPage) && !isEnd){ JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('checkouts.json?limit='+configurationList[0].HIC_ShopifySync__Chunk_Size__c+'&page_info='+linkForNextPage, configurationList); }else{ JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('checkouts.json?limit='+configurationList[0].HIC_ShopifySync__Chunk_Size__c+(updated_at_min!=''?'&updated_at_min='+updated_at_min:'')+(updated_at_max!=''?'&updated_at_max='+updated_at_max:''), configurationList); System.debug('JSONResponse---'+JSONResponse); } if(String.isNotBlank(JSONResponse)){ Map main = (Map) JSON.deserializeUntyped(JSONResponse); if(!main.isEmpty() && main.containskey('response') && main.containskey('link') ){ if( main.get('response') != null) checkoutResponse = String.valueof(main.get('response')); if(main.get('link') != null){ linkForNextPage = String.valueof(main.get('link')); }else{ isEnd = true; } } } }else{//satyam checkoutResponse ='{ "checkouts": [{"buyer_accepts_marketing": false,"cart_token": "db6fad21d337afce5a65831662cf44bf","closed_at": null,"completed_at": null,"created_at": "2023-04-27T09:15:41-04:00","currency": "INR","presentment_currency": "INR","customer_locale": "en-IN","device_id": null,"email": null,"gateway": null,"id": 36668717957399,"landing_site": "/password","location_id": null,"note": null,"note_attributes": [],"phone": "+917048948110","referring_site": "","source_identifier": null,"source_url": null,"taxes_included": false,"token": "f608708ffd25236f7e3a55623158c0ec","total_weight": 0,"updated_at": "2023-04-27T09:15:41-04:00","user_id": null,"customer": {"id": 6900902297879,"email": null,"accepts_marketing": false,"created_at": "2023-04-27T09:15:41-04:00","updated_at": "2023-04-27T09:15:41-04:00","first_name": "Satyam","last_name": "Mishra","orders_count": 0,"state": "disabled","total_spent": "0.00","last_order_id": null,"note": null,"verified_email": true,"multipass_identifier": null,"tax_exempt": false,"tags": "","last_order_name": null,"currency": "INR","phone": "+917048948110","accepts_marketing_updated_at": "2023-04-27T09:15:41-04:00","marketing_opt_in_level": null,"tax_exemptions": [],"email_marketing_consent": null,"sms_marketing_consent": {"state": "not_subscribed","opt_in_level": "single_opt_in","consent_updated_at": null,"consent_collected_from": "SHOPIFY"},"admin_graphql_api_id": "gid://shopify/Customer/6900902297879", "default_address": { "id": 9148733325591, "customer_id": 6900902297879, "first_name": "Satyam", "last_name": "Mishra", "company": null, "address1": "street noida 68", "address2": "Pegasus one", "city": "Noida", "province": "Uttar Pradesh", "country": "India", "zip": "201308", "phone": null, "name": "Satyam Mishra", "province_code": "UP", "country_code": "IN", "country_name": "India", "default": true } }, "source": null, "source_name": "web", "name": "#36668717957399", "discount_codes": [], "total_discounts": "0.00","total_line_items_price": "100.00", "total_price": "118.00", "total_tax": "18.00", "subtotal_price": "100.00", "total_duties": null, "abandoned_checkout_url": "https://demoorg10satyam.myshopify.com/74610213143/checkouts/ac/db6fad21d337afce5a65831662cf44bf/recover?key=6518c7ed0ee9cf500c429f4006633024", "shipping_lines": [ { "code": "Standard", "price": "0.00", "source": "shopify","title": "Standard","presentment_title": "Standard","validation_context": null,"phone": null,"markup": "0.00", "carrier_identifier": null, "carrier_service_id": null, "api_client_id": 580111, "delivery_option_group": {"token": "9b5edb8a4c172b33fbb617dd46ab0281","type": "one_time_purchase"},"delivery_expectation_range": null, "delivery_expectation_type": null, "tax_lines": [] } ], "tax_lines": [ { "position": 1, "price": "18.00", "rate": 0.18, "title": "IGST", "source": null, "compare_at": "18.00", "zone": null, "channel_liable": false, "identifier": null } ], "shipping_address": { "first_name": "Satyam", "address1": "street noida 68", "phone": null, "city": "Noida", "zip": "201308", "province": "UP", "country": "IN", "last_name": "Mishra", "address2": "Pegasus one", "company": null, "latitude": null, "longitude": null, "name": "Satyam Mishra", "country_code": "IN", "province_code": "UP" }, "billing_address": { "first_name": "Satyam", "address1": "street noida 68", "phone": null, "city": "Noida", "zip": "201308", "province": "UP", "country": "IN", "last_name": "Mishra", "address2": "Pegasus one", "company": null, "latitude": null, "longitude": null, "name": "Satyam Mishra", "country_code": "IN", "province_code": "UP" }, "line_items": [ { "key": null, "destination_location_id": null, "fulfillment_service": "manual", "gift_card": false, "grams": 0, "origin_location_id": null, "presentment_title": "Cap", "presentment_variant_title": "Default Title", "product_id": 8251589230871, "properties": [], "quantity": 1, "requires_shipping": true, "sku": "10", "taxable": true, "title": "Cap", "variant_id": 44935361200407, "variant_title": null, "variant_price": "100.00", "vendor": "demoorg10satyam", "unit_price_measurement": { "measured_type": "", "quantity_value": 0, "quantity_unit": "", "reference_value": 0, "reference_unit": "" }, "rank": null, "line_price": "100.00", "price": "100.00", "applied_discounts": [], "tax_lines": [ { "position": 0, "price": "18.00", "rate": 0.18, "title": "IGST", "source": null, "compare_at": "18.00", "zone": null, "channel_liable": false, "identifier": null } ] } ] }, { "buyer_accepts_marketing": false, "cart_token": "db6fad21d337afce5a65831662cf44bf", "closed_at": null, "completed_at": null, "created_at": "2023-04-27T09:15:41-04:00", "currency": "INR", "presentment_currency": "INR", "customer_locale": "en-IN", "device_id": null, "email": null, "gateway": null, "id": 36668717957399, "landing_site": "/password", "location_id": null, "note": null, "note_attributes": [], "phone": "+917048948110", "referring_site": "", "source_identifier": null, "source_url": null, "taxes_included": false, "token": "f608708ffd25236f7e3a55623158c0ec", "total_weight": 0, "updated_at": "2023-04-27T09:15:41-04:00", "user_id": null, "source": null, "source_name": "web", "name": "#36668717957399", "discount_codes": [], "total_discounts": "0.00", "total_line_items_price": "100.00", "total_price": "118.00", "total_tax": "18.00", "subtotal_price": "100.00", "total_duties": null, "abandoned_checkout_url": "https://demoorg10satyam.myshopify.com/74610213143/checkouts/ac/db6fad21d337afce5a65831662cf44bf/recover?key=6518c7ed0ee9cf500c429f4006633024", "shipping_lines": [ { "code": "Standard", "price": "0.00", "source": "shopify", "title": "Standard", "presentment_title": "Standard", "validation_context": null, "phone": null, "markup": "0.00", "carrier_identifier": null, "carrier_service_id": null, "api_client_id": 580111, "delivery_option_group": { "token": "9b5edb8a4c172b33fbb617dd46ab0281", "type": "one_time_purchase" }, "delivery_expectation_range": null, "delivery_expectation_type": null, "tax_lines": [] } ], "tax_lines": [ { "position": 1, "price": "18.00", "rate": 0.18, "title": "IGST", "source": null, "compare_at": "18.00", "zone": null, "channel_liable": false, "identifier": null } ], "shipping_address": { "first_name": "Satyam", "address1": "street noida 68", "phone": null, "city": "Noida", "zip": "201308", "province": "UP", "country": "IN", "last_name": "Mishra", "address2": "Pegasus one", "company": null, "latitude": null, "longitude": null, "name": "Satyam Mishra", "country_code": "IN", "province_code": "UP" }, "billing_address": { "first_name": "Satyam", "address1": "street noida 68", "phone": null, "city": "Noida", "zip": "201308", "province": "UP", "country": "IN", "last_name": "Mishra", "address2": "Pegasus one", "company": null, "latitude": null, "longitude": null, "name": "Satyam Mishra", "country_code": "IN", "province_code": "UP" }, "line_items": [ { "key": null, "destination_location_id": null, "fulfillment_service": "manual", "gift_card": false, "grams": 0, "origin_location_id": null, "presentment_title": "Cap", "presentment_variant_title": "Default Title", "product_id": 8251589230871, "properties": [], "quantity": 1, "requires_shipping": true, "sku": "10", "taxable": true, "title": "Cap", "variant_id": 44935361200407, "variant_title": null, "variant_price": "100.00", "vendor": "demoorg10satyam", "unit_price_measurement": { "measured_type": "", "quantity_value": 0, "quantity_unit": "", "reference_value": 0, "reference_unit": "" }, "rank": null, "line_price": "100.00", "price": "100.00", "applied_discounts": [], "tax_lines": [ { "position": 0, "price": "18.00", "rate": 0.18, "title": "IGST", "source": null, "compare_at": "18.00", "zone": null, "channel_liable": false, "identifier": null } ] } ] } ] }'; } Map meta = (Map) JSON.deserializeUntyped(checkoutResponse); List objectList = (List)meta.get('checkouts'); return objectList ; } global void execute(Database.BatchableContext bc , List Scope){ List listOfCheckLines = new List(); typLstSObject = Type.ForName('List'); //List checkOutLineListToupsert = (List)typLstSObject.NewInstance(); List listofallCheckLines = new List(); Map shopifyidvsAccountid = new Map(); List CheckoutList = new List(); for(Object checkObj : Scope ){ Map CheckoutMap = (Map)checkObj ; String checkoutId = ''; if(CheckoutMap != null && !CheckoutMap.isEmpty() && CheckoutMap.containskey('id')){ checkoutId = String.valueOf(CheckoutMap.get('id')); } if(CheckoutMap != null && !CheckoutMap.isEmpty() && CheckoutMap.containskey('line_items')){ //Map lineMap = (Map)CheckoutMap.get('line_items'); //if(lineMap != null && !lineMap.isEmpty() && lineMap.containskey('line_items')) listOfCheckLines = (list)CheckoutMap.get('line_items'); Map chekLineObj = new Map(); for(Object checkLine : listOfCheckLines){ chekLineObj = (Map)checkLine; chekLineObj.put('id', checkoutId+'-'+chekLineObj.get('variant_id')); chekLineObj.put('checkout_id', checkoutId); listofallCheckLines.add(chekLineObj); } //listofallCheckLines.addAll(listOfCheckLines); Map accMap = new Map (); if(CheckoutMap.containsKey('customer')){ accMap = (Map)CheckoutMap.get('customer'); } else{ accMap.put('id', 'Missing Account'); CheckoutMap.put('customer', accMap); } if(CheckoutMap.containsKey('company')){ //accMap = (Map)CheckoutMap.get('company'); } else{ Map companyMap = new Map(); companyMap.put('id', 'business missing account'); CheckoutMap.put('company', companyMap); } if(accMap != null && !accMap.isEmpty() && accMap.containsKey('id')){ if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )){ if (configurationList[0].HIC_ShopifySync__Person_Account__c ){ if(!(String.valueOf(accMap.get('id'))).contains('Person ')) ShopifyIdvsAccountId.put('Person '+String.valueof(accMap.get('id')),CheckoutMap.get('customer')); }else if(!configurationList[0].HIC_ShopifySync__Person_Account__c ){ if(!(String.valueOf(accMap.get('id'))).contains('Business ')) ShopifyIdvsAccountId.put('Business '+String.valueof(accMap.get('id')),CheckoutMap.get('customer')); } }else{ if(!(String.valueOf(accMap.get('id'))).contains('Business ')) ShopifyIdvsAccountId.put('Business '+String.valueof(accMap.get('id')),CheckoutMap.get('customer')); } } } CheckoutList.add(CheckoutMap); system.debug('CheckoutList----'+CheckoutList); } if(!ShopifyidvsAccountid.isEmpty() && ShopifyidvsAccountid != null){ if(!Test.isRunningTest() && configurationList[0].HIC_ShopifySync__Person_Account__c){ //HIC_ShopifyUtility.initializeAccount(ShopifyidvsAccountid, 'Account', true,configurationList); HIC_ShopifyUtility.InitializeAccount(ShopifyIdvsAccountId, configurationList, store); }else{ //HIC_ShopifyUtility.initializeAccount(ShopifyidvsAccountid, 'Account', false,configurationList); HIC_ShopifyUtility.InitializeAccount(ShopifyIdvsAccountId, configurationList, store); } }else{ shopifyidvsAccountid.put('Missing Account', JSON.deserializeUntyped('{"id":"Missing Account"}')); //HIC_ShopifyUtility.initializeAccount(ShopifyidvsAccountid, 'Account', false,configurationList); HIC_ShopifyUtility.InitializeAccount(ShopifyIdvsAccountId, configurationList, store); } List checkLineFieldsList = new List(); String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'HIC_ShopifySync__Checkout_LineItem__c\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999'; checkLineFieldsList = database.query(query); List checkoutFieldsList = new List(); query = ''; query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c , HIC_ShopifySync__IsSFID__c, HIC_ShopifySync__Default_Value__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'HIC_ShopifySync__Checkout__c\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999'; checkoutFieldsList = database.query(query); try{ if(!checkoutFieldsList.isEmpty() && !Scope.isEmpty()) { HIC_ShopifyUtility.processSobjectList(checkoutFieldsList,Scope,'HIC_ShopifySync__Checkout__c','HIC_ShopifySync__Shopify_Id__c',configurationList,false,store); } }catch(Exception e){ system.debug(e.getMessage()+' at line '+ e.getLineNumber()); system.debug('error-- '+e); } /*if(!Test.isRunningTest()){ checkOutLineListToupsert.addAll(HIC_ShopifyUtility.fillObjectValues(checkLineFieldsList,'HIC_ShopifySync__Checkout_LineItem__c',listofallCheckLines, configurationList)); }*/ try{ if(!checkLineFieldsList.isEmpty() && !listofallCheckLines.isEmpty()) { HIC_ShopifyUtility.processSobjectList(checkLineFieldsList,listofallCheckLines,'HIC_ShopifySync__Checkout_LineItem__c','HIC_ShopifySync__Shopify_Id__c', configurationList,false,store); } }catch(Exception e){ system.debug(e.getMessage()+' at line '+ e.getLineNumber()); system.debug('error-- '+e); } } global void finish(Database.BatchableContext bc){ if(!isEnd){ if(!Test.isRunningTest()){ //Call Batch Again FetchCheckouts callBatchAgain = new FetchCheckouts(linkForNextPage,false,store,updated_at_min,updated_at_max); Database.executeBatch(callBatchAgain,1); } } } }