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

737 lines
68 KiB
OpenEdge ABL

/**
* ─────────────────────────────────────────────────────────────────────────────────────────────────┐
* This Batch class is use for upsert Shopify's Order and Draft Order into the Salesfroce
* Shopify API Documentation: https://shopify.dev/docs/admin-api/rest/reference
* Create Shopify Store: https://www.shopify.com/signup?itcat=identity&itterm=create-new-store
* Shopify API Release 2020: https://www.shopify.in/partners/blog/shopify-api-release-january-2020
* What is Person Account in Salesforce ? https://help.salesforce.com/articleView?id=account_person.htm&type=5
* ──────────────────────────────────────────────────────────────────────────────────────────────────
* @author Sumit <sumit@hicShopify.com>
* ──────────────────────────────────────────────────────────────────────────────────────────────────
*/
global with sharing class FetchOrders implements Database.Batchable<Object>, Database.allowscallouts, Database.Stateful{
String linkForNextPage = '';
Boolean isEnd = false;
String store = 'Default';
Type typLstSObject;
List<Object> objectList;
Boolean check = false; // If True then batch run for Order and if false then run for Draft Order
List<HIC_ShopifySync__HIC_Configuration__c > configurationList;
List<Object> orderproductList;
Boolean checkException;
Boolean checkExceptionForDraftOrder;
String updated_at_min = '';
String updated_at_max = '';
Boolean orderBypassFlag = false;
String shopifyResourceName;
global FetchOrders(String linkForNextPage, Boolean isEnd, Boolean check, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store){
this.linkForNextPage = linkForNextPage;
this.isEnd = isEnd;
this.check = check;
this.configurationList = configurationList;
checkExceptionForDraftOrder = false;
checkException = false;
this.store = store;
}
global FetchOrders(String linkForNextPage, Boolean isEnd, Boolean check, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store, String updated_at_min, String updated_at_max){
this.linkForNextPage = linkForNextPage;
this.isEnd = isEnd;
this.check = check;
this.configurationList = configurationList;
checkExceptionForDraftOrder = false;
checkException = false;
this.store = store;
this.updated_at_min = updated_at_min;
this.updated_at_max = updated_at_max;
}
global FetchOrders(String linkForNextPage, Boolean isEnd, Boolean check, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store, String updated_at_min, String updated_at_max, Boolean orderBypassFlag){
this.linkForNextPage = linkForNextPage;
this.isEnd = isEnd;
this.check = check;
this.configurationList = configurationList;
checkExceptionForDraftOrder = false;
checkException = false;
this.store = store;
this.updated_at_min = updated_at_min;
this.updated_at_max = updated_at_max;
this.orderBypassFlag = orderBypassFlag;
}
global FetchOrders(String linkForNextPage, Boolean isEnd, String shopifyResourceName, List<HIC_ShopifySync__HIC_Configuration__c > configurationList, String store, String updated_at_min, String updated_at_max){
this.linkForNextPage = linkForNextPage;
this.isEnd = isEnd;
this.shopifyResourceName = shopifyResourceName;
this.configurationList = configurationList;
checkExceptionForDraftOrder = false;
checkException = false;
this.store = store;
this.updated_at_min = updated_at_min;
this.updated_at_max = updated_at_max;
this.orderBypassFlag = orderBypassFlag;
}
//Depreceated
global FetchOrders(String linkForNextPage, Boolean isEnd, Boolean check, List<HIC_ShopifySync__Configuration__c > configurationList){
}
global Iterable<Object> start(Database.BatchableContext bc){
system.debug('check>>>');
system.debug('shopifyResourceName--->'+shopifyResourceName);
String orderResponse = '';
String JSONResponse = '';
configurationList = new List<HIC_ShopifySync__HIC_Configuration__c >();
String query = 'Select '+CheckAccessibility.isAccessible('Name,HIC_ShopifySync__Chunk_Size__c,HIC_ShopifySync__Order_Status_Activated_To_Draft__c,HIC_ShopifySync__Salesforce_Pricebook__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__Default_Field_Mapping__c,HIC_ShopifySync__API_Key__c,HIC_ShopifySync__Specify_Close_Date__c, HIC_ShopifySync__Private_Key_Password__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Order_Line_Item__c, HIC_ShopifySync__Account_Contact__c,HIC_ShopifySync__Default_Account__c, HIC_ShopifySync__Enable_Opportunity_for_SDO__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Enable_Draft_Order__c, HIC_ShopifySync__Customer_Email_Domain__c','HIC_ShopifySync__HIC_Configuration__c')+' from HIC_ShopifySync__HIC_Configuration__c where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Configuration__c')+' = \''+store+'\' limit 1';
configurationList = Database.query(query);
if(!Test.isRunningTest()){
if(check){
try{
// Get Shopif's Order JSON Response
if(String.isNotBlank(linkForNextPage) && !isEnd){
JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('orders.json?limit='+configurationList[0].HIC_ShopifySync__Chunk_Size__c+'&page_info='+linkForNextPage, configurationList);
}else{
JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('orders.json?limit='+configurationList[0].HIC_ShopifySync__Chunk_Size__c+'&status=any'+(updated_at_min!=''?'&updated_at_min='+updated_at_min:'')+(updated_at_max!=''?'&updated_at_max='+updated_at_max:''), configurationList);
}
if(String.isNotBlank(JSONResponse)){
Map<String,Object> main = (Map<String,Object>) JSON.deserializeUntyped(JSONResponse);
if(!main.isEmpty() && main.containskey('response') && main.containskey('link') ){
if( main.get('response') != null)
orderResponse = String.valueof(main.get('response'));
if(main.get('link') != null && String.isNotBlank(orderResponse)){
linkForNextPage = String.valueof(main.get('link'));
}else{
isEnd = true;
}
}
}
if(!String.isNotBlank(orderResponse)){
checkException = true;
}
}catch (Exception e){
checkException = true;
}
}else{
try{
// Get Shopif's Draft Order JSON Response
if(String.isNotBlank(linkForNextPage) && !isEnd){
JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage((shopifyResourceName != null? shopifyResourceName :'draft_orders') + '.json?limit='+configurationList[0].HIC_ShopifySync__Chunk_Size__c+'&page_info='+linkForNextPage, configurationList);
}else{
system.debug('shopifyResourceName>>>'+shopifyResourceName);
JSONResponse = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage((shopifyResourceName != null? shopifyResourceName :'draft_orders') + '.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);
}
if(String.isNotBlank(JSONResponse)){
Map<String,Object> main = (Map<String,Object>) JSON.deserializeUntyped(JSONResponse);
if(!main.isEmpty() && main.containskey('response') && main.containskey('link') ){
if( main.get('response') != null)
orderResponse = String.valueof(main.get('response'));
System.debug('main--'+main);
System.debug('link--'+main.get('link'));
if(main.get('link') != null && String.isNotBlank(orderResponse)){
linkForNextPage = String.valueof(main.get('link'));
}else{
isEnd = true;
}
}
}
if(!String.isNotBlank(orderResponse)){
checkExceptionForDraftOrder = true;
}
}
catch(Exception e){
checkExceptionForDraftOrder = true;
}
}
}else{
if(check){
orderResponse = '{ "orders": [{ "id": 618960158784, "email": "uv@gmail.com", "closed_at": null, "created_at": "2018-12-21T15:54:18+05:30", "updated_at": "2018-12-21T15:54:18+05:30", "number": 11, "note": "", "token": "7ad316e8c59b1d18877b242d8244eea3", "gateway": "manual", "test": false, "total_price": "5280.50", "subtotal_price": "4475.00", "total_weight": 195, "total_tax": "805.50", "taxes_included": false, "currency": "INR", "financial_status": "paid", "confirmed": true, "total_discounts": "0.00", "total_line_items_price": "4475.00", "cart_token": null, "buyer_accepts_marketing": false, "name": "#1011", "referring_site": null, "landing_site": null, "cancelled_at": "2018-12-21T15:54:18+05:30", "cancel_reason": "N/A", "total_price_usd": "74.70", "checkout_token": null, "reference": null, "user_id": 18963628096, "location_id": null, "source_identifier": null, "source_url": null, "processed_at": "2018-12-21T15:54:18+05:30", "device_id": null, "phone": null, "customer_locale": null, "app_id": 1354745, "browser_ip": null, "landing_site_ref": null, "order_number": 1011, "discount_applications": [], "discount_codes": [], "note_attributes": [], "payment_gateway_names": ["manual"], "processing_method": "manual", "checkout_id": null, "source_name": "shopify_draft_order", "fulfillment_status": null, "tax_lines": [{ "price": "805.50", "rate": 0.18, "title": "IGST", "price_set": { "shop_money": { "amount": "805.50", "currency_code": "INR" }, "presentment_money": { "amount": "805.50", "currency_code": "INR" } } }], "tags": "", "contact_email": "uv@gmail.com", "order_status_url": "https://checkout.shopify.com/10269687872/orders/7ad316e8c59b1d18877b242d8244eea3/authenticate?key=5415e623338fd5f08b77268cc72456b6", "presentment_currency": "INR", "total_line_items_price_set": { "shop_money": { "amount": "4475.00", "currency_code": "INR" }, "presentment_money": { "amount": "4475.00", "currency_code": "INR" } }, "total_discounts_set": { "shop_money": { "amount": "0.00", "currency_code": "INR" }, "presentment_money": { "amount": "0.00", "currency_code": "INR" } }, "total_shipping_price_set": { "shop_money": { "amount": "0.00", "currency_code": "INR" }, "presentment_money": { "amount": "0.00", "currency_code": "INR" } }, "subtotal_price_set": { "shop_money": { "amount": "4475.00", "currency_code": "INR" }, "presentment_money": { "amount": "4475.00", "currency_code": "INR" } }, "total_price_set": { "shop_money": { "amount": "5280.50", "currency_code": "INR" }, "presentment_money": { "amount": "5280.50", "currency_code": "INR" } }, "total_tax_set": { "shop_money": { "amount": "805.50", "currency_code": "INR" }, "presentment_money": { "amount": "805.50", "currency_code": "INR" } }, "total_tip_received": "0.0", "admin_graphql_api_id": "gid://shopify/Order/618960158784", "line_items": [ { "id": 1468975054912, "variant_id": 17732618027072, "title": "TestProduct", "quantity": 3, "price": "500.00", "sku": "50505", "variant_title": "5mm / red", "vendor": "SyncMyStore", "fulfillment_service": "manual", "product_id": 1798809452608, "requires_shipping": true, "taxable": true, "gift_card": false, "name": "TestProduct - 5mm / red", "variant_inventory_management": "shopify", "properties": [], "product_exists": true, "fulfillable_quantity": 3, "grams": 5, "total_discount": "0.00", "fulfillment_status": null, "price_set": { "shop_money": { "amount": "500.00", "currency_code": "INR" }, "presentment_money": { "amount": "500.00", "currency_code": "INR" } }, "total_discount_set": { "shop_money": { "amount": "0.00", "currency_code": "INR" }, "presentment_money": { "amount": "0.00", "currency_code": "INR" } }, "discount_allocations": [], "admin_graphql_api_id": "gid://shopify/LineItem/1468975054912", "tax_lines": [{ "title": "IGST", "price": "270.00", "rate": 0.18, "price_set": { "shop_money": { "amount": "270.00", "currency_code": "INR" }, "presentment_money": { "amount": "270.00", "currency_code": "INR" } } }] }], "shipping_lines": [], "billing_address": { "first_name": "firstname1", "address1": "Noida City Centre Metro Sector 39", "phone": null, "city": "Noida", "zip": "201301", "province": "Uttar Pradesh", "country": "India", "last_name": "lastname1", "address2": "noida", "company": "test", "latitude": 28.57447, "longitude": 77.35561, "name": "firstname1 lastname1", "country_code": "IN", "province_code": "UP" }, "shipping_address": { "first_name": "firstname1", "address1": "Noida City Centre Metro Sector 39", "phone": null, "city": "Noida", "zip": "201301", "province": "Uttar Pradesh", "country": "India", "last_name": "lastname1", "address2": "noida", "company": "test", "latitude": 28.57447, "longitude": 77.35561, "name": "firstname1 lastname1", "country_code": "IN", "province_code": "UP" }, "fulfillments": [{ "id": 732319416391, "order_id": 618960158784, "status": "success", "created_at": "2019-01-11T09:45:02-08:00", "service": "manual", "updated_at": "2019-01-16T17:09:00-08:00", "tracking_company": "FedEx", "shipment_status": "delivered", "location_id": 29079046, "tracking_number": "475684488534", "tracking_numbers": ["475684488534"], "tracking_url": "http://www.fedex.com/Tracking?tracknumbers=475684488534&action=track", "tracking_urls": ["http://www.fedex.com/Tracking?tracknumbers=475684488534&action=track"], "receipt": {}, "name": "#4662.1", "admin_graphql_api_id": "gid://shopify/Fulfillment/732319416391", "line_items": [{ "id": 1755951595591, "variant_id": 18985077244004, "title": "VICIS EDGE Shield by Oakley", "quantity": 1, "price": "90.00", "sku": "16082", "variant_title": "Clear", "vendor": "VICIS", "fulfillment_service": "manual", "product_id": 2053601755236, "requires_shipping": true, "taxable": true, "gift_card": false, "pre_tax_price": "81.00", "name": "VICIS EDGE Shield by Oakley - Clear", "variant_inventory_management": null, "properties": [], "product_exists": true, "fulfillable_quantity": 0, "grams": 953, "total_discount": "0.00", "fulfillment_status": "fulfilled", "price_set": { "shop_money": { "amount": "90.00", "currency_code": "USD" }, "presentment_money": { "amount": "90.00", "currency_code": "USD" } }, "pre_tax_price_set": { "shop_money": { "amount": "81.00", "currency_code": "USD" }, "presentment_money": { "amount": "81.00", "currency_code": "USD" } }, "total_discount_set": { "shop_money": { "amount": "0.00", "currency_code": "USD" }, "presentment_money": { "amount": "0.00", "currency_code": "USD" } }, "discount_allocations": [{ "amount": "9.00", "discount_application_index": 0, "amount_set": { "shop_money": { "amount": "9.00", "currency_code": "USD" }, "presentment_money": { "amount": "9.00", "currency_code": "USD" } } }], "admin_graphql_api_id": "gid://shopify/LineItem/1755951595591", "tax_lines": [{ "title": "AZ COUNTY TAX", "price": "0.57", "rate": 0.007, "price_set": { "shop_money": { "amount": "0.57", "currency_code": "USD" }, "presentment_money": { "amount": "0.57", "currency_code": "USD" } } }, { "title": "AZ STATE TAX", "price": "4.54", "rate": 0.056, "price_set": { "shop_money": { "amount": "4.54", "currency_code": "USD" }, "presentment_money": { "amount": "4.54", "currency_code": "USD" } } }, { "title": "AZ CITY TAX", "price": "1.22", "rate": 0.015, "price_set": { "shop_money": { "amount": "1.22", "currency_code": "USD" }, "presentment_money": { "amount": "1.22", "currency_code": "USD" } } }], "origin_location": { "id": 27506147349, "country_code": "US", "province_code": "WA", "name": "VICIS", "address1": "2123 W. Elmore St. ", "address2": "", "city": "Seattle", "zip": "98199" }, "destination_location": { "id": 769732804679, "country_code": "US", "province_code": "AZ", "name": "Brad Oyler", "address1": "3862 East Redwood Place", "address2": "", "city": "Chandler", "zip": "85286" } }] }], "refunds": [], "customer": { "id": 926016995392, "email": "uv@gmail.com", "accepts_marketing": false, "created_at": "2018-12-12T16:43:59+05:30", "updated_at": "2018-12-21T15:54:18+05:30", "first_name": "firstname1", "last_name": "lastname1", "orders_count": 5, "state": "disabled", "total_spent": "18732.50", "last_order_id": 618960158784, "note": "Noteee", "verified_email": true, "multipass_identifier": null, "tax_exempt": false, "phone": "+918604065624", "tags": "Tagsss", "last_order_name": "#1011", "currency": "INR", "admin_graphql_api_id": "gid://shopify/Customer/926016995392", "default_address": { "id": 1041332338752, "customer_id": 926016995392, "first_name": "firstname1", "last_name": "lastname1", "company": "test", "address1": "Noida City Centre Metro Sector 39", "address2": "noida", "city": "Noida", "province": "Uttar Pradesh", "country": "India", "zip": "201301", "phone": "", "name": "firstname1 lastname1", "province_code": "UP", "country_code": "IN", "country_name": "India", "default": true } } }] }';
}else{
orderResponse = '{ "draft_orders": [{ "id": 618960158784, "email": "uv@gmail.com", "closed_at": null, "created_at": "2018-12-21T15:54:18+05:30", "updated_at": "2018-12-21T15:54:18+05:30", "number": 11, "note": "", "token": "7ad316e8c59b1d18877b242d8244eea3", "gateway": "manual", "test": false, "total_price": "5280.50", "subtotal_price": "4475.00", "total_weight": 195, "total_tax": "805.50", "taxes_included": false, "currency": "INR", "financial_status": "paid", "confirmed": true, "total_discounts": "0.00", "total_line_items_price": "4475.00", "cart_token": null, "buyer_accepts_marketing": false, "name": "#1011", "referring_site": null, "landing_site": null, "cancelled_at": "2018-12-21T15:54:18+05:30", "cancel_reason": "N/A", "total_price_usd": "74.70", "checkout_token": null, "reference": null, "user_id": 18963628096, "location_id": null, "source_identifier": null, "source_url": null, "processed_at": "2018-12-21T15:54:18+05:30", "device_id": null, "phone": null, "customer_locale": null, "app_id": 1354745, "browser_ip": null, "landing_site_ref": null, "order_number": 1011, "discount_applications": [], "discount_codes": [], "note_attributes": [], "payment_gateway_names": ["manual"], "processing_method": "manual", "checkout_id": null, "source_name": "shopify_draft_order", "fulfillment_status": null, "tax_lines": [{ "price": "805.50", "rate": 0.18, "title": "IGST", "price_set": { "shop_money": { "amount": "805.50", "currency_code": "INR" }, "presentment_money": { "amount": "805.50", "currency_code": "INR" } } }], "tags": "", "contact_email": "uv@gmail.com", "order_status_url": "https://checkout.shopify.com/10269687872/orders/7ad316e8c59b1d18877b242d8244eea3/authenticate?key=5415e623338fd5f08b77268cc72456b6", "presentment_currency": "INR", "total_line_items_price_set": { "shop_money": { "amount": "4475.00", "currency_code": "INR" }, "presentment_money": { "amount": "4475.00", "currency_code": "INR" } }, "total_discounts_set": { "shop_money": { "amount": "0.00", "currency_code": "INR" }, "presentment_money": { "amount": "0.00", "currency_code": "INR" } }, "total_shipping_price_set": { "shop_money": { "amount": "0.00", "currency_code": "INR" }, "presentment_money": { "amount": "0.00", "currency_code": "INR" } }, "subtotal_price_set": { "shop_money": { "amount": "4475.00", "currency_code": "INR" }, "presentment_money": { "amount": "4475.00", "currency_code": "INR" } }, "total_price_set": { "shop_money": { "amount": "5280.50", "currency_code": "INR" }, "presentment_money": { "amount": "5280.50", "currency_code": "INR" } }, "total_tax_set": { "shop_money": { "amount": "805.50", "currency_code": "INR" }, "presentment_money": { "amount": "805.50", "currency_code": "INR" } }, "total_tip_received": "0.0", "admin_graphql_api_id": "gid://shopify/Order/618960158784", "line_items": [ { "id": 1468975054912, "variant_id": 17732618027072, "title": "TestProduct", "quantity": 3, "price": "500.00", "sku": "50505", "variant_title": "5mm / red", "vendor": "SyncMyStore", "fulfillment_service": "manual", "product_id": 1798809452608, "requires_shipping": true, "taxable": true, "gift_card": false, "name": "TestProduct - 5mm / red", "variant_inventory_management": "shopify", "properties": [], "product_exists": true, "fulfillable_quantity": 3, "grams": 5, "total_discount": "0.00", "fulfillment_status": null, "price_set": { "shop_money": { "amount": "500.00", "currency_code": "INR" }, "presentment_money": { "amount": "500.00", "currency_code": "INR" } }, "total_discount_set": { "shop_money": { "amount": "0.00", "currency_code": "INR" }, "presentment_money": { "amount": "0.00", "currency_code": "INR" } }, "discount_allocations": [], "admin_graphql_api_id": "gid://shopify/LineItem/1468975054912", "tax_lines": [{ "title": "IGST", "price": "270.00", "rate": 0.18, "price_set": { "shop_money": { "amount": "270.00", "currency_code": "INR" }, "presentment_money": { "amount": "270.00", "currency_code": "INR" } } }] }], "shipping_lines": [], "billing_address": { "first_name": "firstname1", "address1": "Noida City Centre Metro Sector 39", "phone": null, "city": "Noida", "zip": "201301", "province": "Uttar Pradesh", "country": "India", "last_name": "lastname1", "address2": "noida", "company": "test", "latitude": 28.57447, "longitude": 77.35561, "name": "firstname1 lastname1", "country_code": "IN", "province_code": "UP" }, "shipping_address": { "first_name": "firstname1", "address1": "Noida City Centre Metro Sector 39", "phone": null, "city": "Noida", "zip": "201301", "province": "Uttar Pradesh", "country": "India", "last_name": "lastname1", "address2": "noida", "company": "test", "latitude": 28.57447, "longitude": 77.35561, "name": "firstname1 lastname1", "country_code": "IN", "province_code": "UP" }, "fulfillments": [{ "id": 732319416391, "order_id": 618960158784, "status": "success", "created_at": "2019-01-11T09:45:02-08:00", "service": "manual", "updated_at": "2019-01-16T17:09:00-08:00", "tracking_company": "FedEx", "shipment_status": "delivered", "location_id": 29079046, "tracking_number": "475684488534", "tracking_numbers": ["475684488534"], "tracking_url": "http://www.fedex.com/Tracking?tracknumbers=475684488534&action=track", "tracking_urls": ["http://www.fedex.com/Tracking?tracknumbers=475684488534&action=track"], "receipt": {}, "name": "#4662.1", "admin_graphql_api_id": "gid://shopify/Fulfillment/732319416391", "line_items": [{ "id": 1755951595591, "variant_id": 18985077244004, "title": "VICIS EDGE Shield by Oakley", "quantity": 1, "price": "90.00", "sku": "16082", "variant_title": "Clear", "vendor": "VICIS", "fulfillment_service": "manual", "product_id": 2053601755236, "requires_shipping": true, "taxable": true, "gift_card": false, "pre_tax_price": "81.00", "name": "VICIS EDGE Shield by Oakley - Clear", "variant_inventory_management": null, "properties": [], "product_exists": true, "fulfillable_quantity": 0, "grams": 953, "total_discount": "0.00", "fulfillment_status": "fulfilled", "price_set": { "shop_money": { "amount": "90.00", "currency_code": "USD" }, "presentment_money": { "amount": "90.00", "currency_code": "USD" } }, "pre_tax_price_set": { "shop_money": { "amount": "81.00", "currency_code": "USD" }, "presentment_money": { "amount": "81.00", "currency_code": "USD" } }, "total_discount_set": { "shop_money": { "amount": "0.00", "currency_code": "USD" }, "presentment_money": { "amount": "0.00", "currency_code": "USD" } }, "discount_allocations": [{ "amount": "9.00", "discount_application_index": 0, "amount_set": { "shop_money": { "amount": "9.00", "currency_code": "USD" }, "presentment_money": { "amount": "9.00", "currency_code": "USD" } } }], "admin_graphql_api_id": "gid://shopify/LineItem/1755951595591", "tax_lines": [{ "title": "AZ COUNTY TAX", "price": "0.57", "rate": 0.007, "price_set": { "shop_money": { "amount": "0.57", "currency_code": "USD" }, "presentment_money": { "amount": "0.57", "currency_code": "USD" } } }, { "title": "AZ STATE TAX", "price": "4.54", "rate": 0.056, "price_set": { "shop_money": { "amount": "4.54", "currency_code": "USD" }, "presentment_money": { "amount": "4.54", "currency_code": "USD" } } }, { "title": "AZ CITY TAX", "price": "1.22", "rate": 0.015, "price_set": { "shop_money": { "amount": "1.22", "currency_code": "USD" }, "presentment_money": { "amount": "1.22", "currency_code": "USD" } } }], "origin_location": { "id": 27506147349, "country_code": "US", "province_code": "WA", "name": "VICIS", "address1": "2123 W. Elmore St. ", "address2": "", "city": "Seattle", "zip": "98199" }, "destination_location": { "id": 769732804679, "country_code": "US", "province_code": "AZ", "name": "Brad Oyler", "address1": "3862 East Redwood Place", "address2": "", "city": "Chandler", "zip": "85286" } }] }], "refunds": [], "customer": { "id": 926016995392, "email": "uv@gmail.com", "accepts_marketing": false, "created_at": "2018-12-12T16:43:59+05:30", "updated_at": "2018-12-21T15:54:18+05:30", "first_name": "firstname1", "last_name": "lastname1", "orders_count": 5, "state": "disabled", "total_spent": "18732.50", "last_order_id": 618960158784, "note": "Noteee", "verified_email": true, "multipass_identifier": null, "tax_exempt": false, "phone": "+918604065624", "tags": "Tagsss", "last_order_name": "#1011", "currency": "INR", "admin_graphql_api_id": "gid://shopify/Customer/926016995392", "default_address": { "id": 1041332338752, "customer_id": 926016995392, "first_name": "firstname1", "last_name": "lastname1", "company": "test", "address1": "Noida City Centre Metro Sector 39", "address2": "noida", "city": "Noida", "province": "Uttar Pradesh", "country": "India", "zip": "201301", "phone": "", "name": "firstname1 lastname1", "province_code": "UP", "country_code": "IN", "country_name": "India", "default": true } } }] }';
}
}
if(!checkException && !checkExceptionForDraftOrder) {
Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(orderResponse);
if(check){
objectList = (List<Object>) meta.get('orders');
}else if(shopifyResourceName != null){
objectList = (List<Object>) meta.get(shopifyResourceName);
}else{
objectList = (List<Object>) meta.get('draft_orders');
}
set<String> setofObjectid = new set<String>();
for(Object oppListobj : objectList ){
Map<String,Object> oppMap = (Map<String,Object>)oppListobj;
setofObjectid.add(String.valueof(oppMap.get('id')));
system.debug('setofObjectid-->'+setofObjectid);
}
/*System.debug('current selected pricebook'+configurationList[0].HIC_ShopifySync__Salesforce_Pricebook__c);
System.debug('orders pricebook'+[Select Pricebook2id from Order where HIC_ShopifySync__Shopify_Id__c in: setofObjectid]);
List<Order> orderList = [Select Pricebook2id from Order where HIC_ShopifySync__Shopify_Id__c in: setofObjectid];
List<Opportunity> oppList = [Select Pricebook2id from Opportunity where HIC_ShopifySync__Shopify_Id__c in: setofObjectid]; */
String query3 = '';
String query4 = '';
Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType');
if(multiCurrencyEnabled){
query3 = 'Select Pricebook2id, CurrencyIsoCode from opportunity where HIC_ShopifySync__Shopify_Id__c in: setofObjectid';
query4 = 'Select Pricebook2id, CurrencyIsoCode from Order where HIC_ShopifySync__Shopify_Id__c in: setofObjectid';
}else{
query3 = 'Select Pricebook2id from opportunity where HIC_ShopifySync__Shopify_Id__c in: setofObjectid';
query4 = 'Select Pricebook2id from Order where HIC_ShopifySync__Shopify_Id__c in: setofObjectid';
}
List<HIC_ShopifySync__HIC_Field_Mapping__c > currencyMappingList = new List<HIC_ShopifySync__HIC_Field_Mapping__c >();
String query2 = '';
if(multiCurrencyEnabled){
query2 = ' select '+CheckAccessibility.isAccessible('id,name,HIC_ShopifySync__Store_External_ID__c,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')+' from HIC_ShopifySync__HIC_Field_Mapping__c where ' +CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c') +'= \'CurrencyISOCODE\' AND ' +CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c', 'HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
currencyMappingList = database.query(query2);
}
List<opportunity> oppList = database.query(query3);
List<Order> orderList = database.query(query4);
system.debug('orderList-->'+orderList);
Boolean tempFlag = false;
for(Order ordr : orderList){
if(ordr.Pricebook2id != configurationList[0].HIC_ShopifySync__Salesforce_Pricebook__c || (multiCurrencyEnabled && !currencyMappingList.isEmpty() && ordr.get('CurrencyIsoCode') != currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c)){
tempFlag = true;
}
}
for(Opportunity ordr : oppList){
if(ordr.Pricebook2id != configurationList[0].HIC_ShopifySync__Salesforce_Pricebook__c || (multiCurrencyEnabled && !currencyMappingList.isEmpty() && ordr.get('CurrencyIsoCode') != currencyMappingList[0].HIC_ShopifySync__Shopify_Fields__c)){
tempFlag = true;
}
}
if(configurationList[0].HIC_ShopifySync__IsCurrencyChanged__c == true || tempFlag){
list<Order> listtodeleteOrder = new list<Order>();
if((orderBypassFlag || configurationList[0].HIC_ShopifySync__Order__c || !check) && configurationList[0].HIC_ShopifySync__Order_Line_Item__c){
listtodeleteOrder = [select id from order where HIC_ShopifySync__Shopify_Id__c in: setofObjectid WITH SECURITY_ENFORCED limit 9999];
for(Order order : [select id from order where HIC_ShopifySync__Shopify_Id__c in: setofObjectid WITH SECURITY_ENFORCED limit 9999]){
order.Status = 'Draft';
}
Database.Update(listtodeleteOrder, false);
}
Set<String> setofOrderid = new Set<String>();
for(order ord : listtodeleteOrder){
setofOrderid.add(ord.id) ;
}
list<OrderItem> listtodeleteOrderitem = new list<OrderItem>();
if(!listtodeleteOrder.isEmpty() && configurationList[0].HIC_ShopifySync__Order_Line_Item__c){
String Orderitemquery = 'Select '+CheckAccessibility.isAccessible('id,HIC_ShopifySync__Shopify_Id__c','OrderItem') +' from OrderItem Where '+CheckAccessibility.isAccessible('OrderId','OrderItem')+' in: setofOrderid limit 49999' ;
listtodeleteOrderitem = database.query(Orderitemquery);
}
list<Opportunity> listtoDeleteOpp = new list<Opportunity>();
if(configurationList[0].HIC_ShopifySync__Opportunity__c){
listtoDeleteOpp = [select id from Opportunity where HIC_ShopifySync__Shopify_Id__c in: setofObjectid WITH SECURITY_ENFORCED limit 9999];
}
setofOrderid.clear();
for(Opportunity opp : listtoDeleteOpp){
setofOrderid.add(opp.id) ;
}
list<OpportunityLineItem> listtodeleteOppitem = new list<OpportunityLineItem>();
if(!listtoDeleteOpp.isEmpty() && (configurationList[0].Opportunity_Line_Item__c || configurationList[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c)){
String Oppitemquery = 'Select '+CheckAccessibility.isAccessible('id,HIC_ShopifySync__Shopify_Id__c','OpportunityLineItem') +' from OpportunityLineItem Where '+CheckAccessibility.isAccessible('OpportunityId','OpportunityLineItem')+' in: setofOrderid limit 49999' ;
listtodeleteOppitem = database.query(Oppitemquery);
}
try{
if(!listtodeleteOrderitem.isEmpty()){
if(CheckAccessibility.isDeletable('OrderItem') && CheckAccessibility.isDeletable('OpportunityLineItem'))
database.delete (listtodeleteOrderitem,false);
}
}catch(Exception e){
system.debug('Error: '+e.getMessage());
}
try{
if(!listtodeleteOppitem.isEmpty()){
if(CheckAccessibility.isDeletable('OrderItem') && CheckAccessibility.isDeletable('OpportunityLineItem'))
database.delete(listtodeleteOppitem,false);
}
}catch(Exception e){
system.debug('Error: '+e.getMessage());
}
}
//Retunn list object data of Shopify
return objectList;
}else{
List<Object> objectList = new List<Object>();
return objectList;
}
}
global void execute(Database.BatchableContext bc , List<Object> scope){
if(!configurationList.isempty()){
List<HIC_ShopifySync__HIC_Field_Mapping__c> orderproductFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
List<Object> opplineItemList;
Map<String,Boolean> shopifyOrderIdVsExistMap = new Map<String,Boolean>();
Map<String,String> updatedProductVsPricebookEntryMap =new Map<String,String>();
Map<String,Boolean> shopifyOppIdVsExistMap = new Map<String,Boolean>();
List<HIC_ShopifySync__HIC_Field_Mapping__c> orderFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
List<HIC_ShopifySync__HIC_Field_Mapping__c> oppFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
Map<String,Object> shopifyidvsAccountid = new Map<String,Object>();
Map <String, String> nameVsId = new Map <String, String>();
List<sobject> sobjectList = new List<sobject>();
String presentmentCurrency = '';
Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Order');
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c');
//Update Account Shopify External ID
for(Object oppListobj : scope ){
Map<String,Object> oppMap = (Map<String,Object>)oppListobj;
Map<String,Object> accMap = new Map<String,Object> ();
if(oppMap != null && !oppMap.isEmpty() && oppMap.containsKey('customer') && oppMap.get('customer') != null){
accMap = (Map<String,Object>)oppMap.get('customer');
}
else{
accMap.put('id', 'Missing Account');
oppMap.put('customer', accMap);
}
if(oppMap != null && !oppMap.isEmpty() && oppMap.containsKey('company') && oppMap.get('company') != null){
//accMap = (Map<String,Object>)oppMap.get('company');
}
else{
Map<String, String> companyMap = new Map<String, String>();
companyMap.put('id', 'business missing account');
oppMap.put('company', companyMap);
}
if(accMap != null && !accMap.isEmpty() && accMap.containsKey('id')){
if(Schema.sObjectType.Account.fields.getMap().containsKey( 'ispersonaccount' )
&& configurationList[0].HIC_ShopifySync__Person_Account__c && !(String.valueOf(accMap.get('id'))).contains('Person ') ){
ShopifyIdvsAccountId.put('Person '+String.valueof(accMap.get('id')),oppMap.get('customer'));
}else if(!configurationList[0].HIC_ShopifySync__Person_Account__c && !(String.valueOf(accMap.get('id'))).contains('Business ')){
ShopifyIdvsAccountId.put('Business '+String.valueof(accMap.get('id')),oppMap.get('customer'));
}
}
if (oppMap != null && !oppMap.isEmpty() && oppMap.containsKey('presentment_currency') && oppMap.get('presentment_currency') != null) {
system.debug('check presentment value: ' + oppMap.get('presentment_currency'));
presentmentCurrency = (String) oppMap.get('presentment_currency');
system.debug('presentmentCurrency===>'+presentmentCurrency);
}
shopifyOrderIdVsExistMap.put(String.valueof(oppMap.get('id')),false);
shopifyOppIdVsExistMap.put(String.valueof(oppMap.get('id')),false);
}
// Initialize Default Account to the Order,Opportunity and Draft Order in case of not available into the Salesforce
if(!ShopifyidvsAccountid.isEmpty() && ShopifyidvsAccountid != null)
shopifyidvsAccountid.put('Missing Account', JSON.deserializeUntyped('{"id":"Missing Account"}'));
// ====== B2B Store Path ======
Boolean isB2B = !configurationList.isEmpty() && configurationList[0].HIC_ShopifySync__Customer_Email_Domain__c == true;
Map<String, Id> b2bOrderIdToAccountId = new Map<String, Id>();
Map<String, Id> b2bOrderIdToContactId = new Map<String, Id>();
if (isB2B) {
// B2B: Resolve Account by email domain and Contact by Shopify ID per order
for (Object oppListobj2 : scope) {
Map<String, Object> oppMap2 = (Map<String, Object>) oppListobj2;
String orderId = String.valueOf(oppMap2.get('id'));
Map<String, Object> accMap2 = new Map<String, Object>();
if (oppMap2.containsKey('customer') && oppMap2.get('customer') != null) {
accMap2 = (Map<String, Object>) oppMap2.get('customer');
}
String email = (accMap2.containsKey('email') && accMap2.get('email') != null)
? String.valueOf(accMap2.get('email'))
: (oppMap2.containsKey('email') ? String.valueOf(oppMap2.get('email')) : null);
if (String.isNotBlank(email) && email.contains('@')) {
String domain = email.substringAfter('@').substringBefore('.');
List<Account> existingAccounts = [SELECT Id, Name FROM Account WHERE Name = :domain LIMIT 1];
Id b2bAccountId;
if (!existingAccounts.isEmpty()) {
b2bAccountId = existingAccounts[0].Id;
} else {
Account acc = new Account(Name = domain);
insert acc;
b2bAccountId = acc.Id;
}
b2bOrderIdToAccountId.put(orderId, b2bAccountId);
// Find Contact by Shopify ID
if (accMap2.containsKey('id') && accMap2.get('id') != null) {
String customerId = String.valueOf(accMap2.get('id'));
String shopifyIdToSearch = 'Business ' + customerId;
List<Contact> contacts = [SELECT Id FROM Contact WHERE HIC_ShopifySync__Shopify_Id__c = :shopifyIdToSearch LIMIT 1];
if (!contacts.isEmpty()) {
b2bOrderIdToContactId.put(orderId, contacts[0].Id);
}
}
}
}
// Skip normal InitializeAccount for B2B
} else {
HIC_ShopifyUtility.InitializeAccount(ShopifyIdvsAccountId, configurationList, store);
}
/******************* Get Existing Records in Salesforce Start **************************************/
List<String> ListOfOrderid = new List<String>();
//Map of Existing Salesforce Opportunity
if( Schema.sObjectType.Opportunity.isAccessible() &&
Schema.sObjectType.Opportunity.fields.HIC_ShopifySync__Shopify_Id__c.isAccessible()){
for(Opportunity opp : [Select HIC_ShopifySync__Shopify_Id__c from Opportunity Where HIC_ShopifySync__Shopify_Id__c IN: shopifyOppIdVsExistMap.keyset() LIMIT 49999]){
shopifyOppIdVsExistMap.put(opp.HIC_ShopifySync__Shopify_Id__c, true);
}
}
//Map of Existing Salesforce Order
if(Schema.sObjectType.Order.isAccessible() &&
Schema.sObjectType.Order.fields.HIC_ShopifySync__Shopify_Id__c.isAccessible()){
Set<String> keyset = new Set<String>();
keyset.addAll(shopifyOrderIdVsExistMap.keyset());
String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__Shopify_Id__c','Order')+' from Order Where '+ CheckAccessibility.isAccessible('HIC_ShopifySync__Shopify_Id__c','Order') +' IN: keyset LIMIT 49999';
for(Order order : Database.query(query)){
shopifyOrderIdVsExistMap.put(order.HIC_ShopifySync__Shopify_Id__c, true);
}
}
/******************* Get Existing Records in Salesforce End **************************************/
/******************************************* Get Field Mapping Start ********************************************/
Boolean DraftOrderIntoOpportunty = false;
Boolean DraftOrderIntoOrder = false;
Boolean OrderIntoOpportunity = false;
Boolean OrderIntoOrder = false;
String OrderMappingResourceName = '';
if(check){
if((orderBypassFlag || configurationList[0].HIC_ShopifySync__Order__c == true)) OrderIntoOrder = true;
if(configurationList[0].HIC_ShopifySync__Opportunity__c) OrderIntoOpportunity = true;
OrderMappingResourceName = 'Order';
}
else{
if(configurationList[0].HIC_ShopifySync__Enable_Draft_Order__c == true) DraftOrderIntoOrder = true;
if(configurationList[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c) DraftOrderIntoOpportunty = true;
OrderMappingResourceName = 'DraftOrder';
}
Boolean IsOpportunity = (DraftOrderIntoOpportunty || OrderIntoOpportunity);
Boolean IsOrder = (DraftOrderIntoOrder || OrderIntoOrder);
//If Order is enable
if(OrderIntoOrder || DraftOrderIntoOrder){
orderFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Default_Value__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__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' AND '
+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = :OrderMappingResourceName';
if(!OrderIntoOpportunity && !DraftOrderIntoOpportunty)
query+= ' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' != \'OpportunityId\'';
query+= ' LIMIT 49999';
orderFieldsList = Database.query(query) ;
}
//if Opportunity is enable
if(OrderIntoOpportunity || DraftOrderIntoOpportunty){
oppFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
String query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c,HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'Opportunity\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
oppFieldsList = Database.query(query);
}
String query = '';
if(Check && configurationList[0].HIC_ShopifySync__Order_Line_Item__c){
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'OrderItem\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
}
else if(!check && IsOrder){
query = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'DraftOrderItem\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
}
system.debug('query___'+query);
if(query != ''){
orderproductFieldsList = Database.query(query);
}
/******************************************* Get Field Mapping Stop ********************************************/
/******************************************* Process for Line Items Start ********************************************/
Map<String,String> productVsPricebookEntryMap = new Map<String,String>(); //Use for Initilize Product's pricebookEntry into the Salesforce
Map<String,String> productVsUnitepriceMap = new Map<String,String>(); //Use for Initilize Product's Unit price into the Salesforce
List <Object> allProducts = new List <Object>();
Type typLstSObject = Type.forName('List<OpportunityLineItem>');
List<SObject> opplineItemListToupsert = (List<SObject>)typLstSObject.newInstance();
//If Opportunity is true only
if (IsOpportunity && !oppFieldsList.isEmpty() && !scope.isEmpty()){
if (isB2B) {
// B2B: Split processSobjectList to intercept for Account + Contact override
List<SObject> oppSobjList = HIC_ShopifyUtility.fillObjectValues(oppFieldsList, 'Opportunity', scope, configurationList);
// Override Account and Contact on each Opportunity
for (SObject opp : oppSobjList) {
String shopifyId = (String) opp.get('HIC_ShopifySync__Shopify_Id__c');
if (shopifyId != null && b2bOrderIdToAccountId.containsKey(shopifyId)) {
opp.putSObject('Account', null);
opp.put('AccountId', b2bOrderIdToAccountId.get(shopifyId));
if (b2bOrderIdToContactId.containsKey(shopifyId)) {
opp.put('HIC_ShopifySync__Contact__c', b2bOrderIdToContactId.get(shopifyId));
}
}
}
HIC_ShopifyUtility.upsertSobjectList(JSON.serialize(objectList), oppSobjList, 'Opportunity', 'HIC_ShopifySync__Shopify_Id__c', configurationList, false, store);
} else {
HIC_ShopifyUtility.processSobjectList(oppFieldsList,scope,'Opportunity','HIC_ShopifySync__Shopify_Id__c',configurationList,false,store);
}
}
if(IsOrder && !orderFieldsList.isEmpty() && !scope.isEmpty()){
sobjectList = HIC_ShopifyUtility.fillObjectValues(orderFieldsList, 'Order', scope, configurationList);
if(sobjectList.Isempty()) return;
// B2B: Override Account and Contact on each Order
if (isB2B) {
for (SObject ord : sobjectList) {
String shopifyId = (String) ord.get('HIC_ShopifySync__Shopify_Id__c');
if (shopifyId != null && b2bOrderIdToAccountId.containsKey(shopifyId)) {
ord.putSObject('Account', null);
ord.put('AccountId', b2bOrderIdToAccountId.get(shopifyId));
if (b2bOrderIdToContactId.containsKey(shopifyId)) {
ord.put('HIC_ShopifySync__Order_s_Contact__c', b2bOrderIdToContactId.get(shopifyId));
}
}
}
}
HIC_ShopifyUtility.upsertSobjectList(JSON.serialize(objectList),sobjectList,'Order','HIC_ShopifySync__Shopify_Id__c', configurationList,false,store);
}
Map <String, Map <String, Object>> mapToInsertProd = new Map <String, Map <String, Object>>();
List<HIC_ShopifySync__HIC_Field_Mapping__c> opproductFieldsList = new List<HIC_ShopifySync__HIC_Field_Mapping__c>();
if((check && configurationList[0].Opportunity_Line_Item__c== true) || (!check && configurationList[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c== true)){
String query2 = 'Select '+CheckAccessibility.isAccessible('HIC_ShopifySync__SF_Field__c, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c, HIC_ShopifySync__Nested__c, HIC_ShopifySync__IsSFID__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' from HIC_ShopifySync__HIC_Field_Mapping__c Where '+CheckAccessibility.isAccessible('HIC_ShopifySync__Object_Name__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \'OpportunityLineItem\' AND '+CheckAccessibility.isAccessible('HIC_ShopifySync__Store__c','HIC_ShopifySync__HIC_Field_Mapping__c')+' = \''+store+'\' LIMIT 49999';
opproductFieldsList = Database.query(query2);
}
typLstSObject = Type.ForName('List<OrderItem>');
List<SObject> orderproductListToupsert = (List<SObject>)typLstSObject.NewInstance();
Map<String,List<Object>> orderVSListofProductMAp = new Map<String,List<Object>>();
for(Object ordobj : scope ){
Map<String, Object> orderproductmap = (Map<String, Object>)ordobj;
system.debug('**orderproductmap '+ orderproductmap);
system.debug('**shopifyOppIdVsExistMap '+shopifyOppIdVsExistMap);
if(orderproductmap != null && !orderproductmap.isEmpty() && orderproductmap.containskey('line_items') ){
opplineItemList = (List<Object>)orderproductmap.get('line_items');
System.debug('opplineItemList!!'+opplineItemList);
for(Object oprodList : opplineItemList){
Map<String, Object> oprodMap = new Map<String, Object>();
oprodMap = (Map<String, Object>) oprodList;
system.debug('oprodMap-->'+oprodMap);
if(oprodMap.get('product_id') == null && oprodMap.get('variant_id') != null){
mapToInsertProd.put(String.valueOf(oprodMap.get('variant_id')), oprodMap);
}else if (oprodMap.get('product_id') != null){
productVsPricebookEntryMap.put(String.valueof(oprodMap.get('product_id')),null);
productVsUnitepriceMap.put(String.valueof(oprodMap.get('product_id')),String.valueof(oprodMap.get('price')));
}
oprodMap.put('opportunityId',String.valueOf(orderproductmap.get('id')));
oprodMap.put('orderid', String.valueof(orderproductmap.get('id')));
if(oprodMap.get('variant_id') == null) oprodMap.put('variant_id', 'N/A');
if(oprodMap.get('product_id') == null) oprodMap.put('product_id', 'N/A');
if(!oprodMap.containsKey('id') || oprodMap.get('id') == null)
oprodMap.put('id', String.valueof(orderproductmap.get('id')) +'-'+ String.valueOf(oprodMap.get('product_id')));
oprodMap.put('UnitPrice',oprodMap.get('price'));
oprodMap.put('orderId',String.valueOf(oprodMap.get('orderid')));
oprodMap.put('opportunityId',String.valueOf(orderproductmap.get('id')));
oprodList = (Object)oprodMap;
allProducts.add(oprodList);
}
orderVSListofProductMAp.put(String.valueof(orderproductmap.get('id')),opplineItemList);
}
}
/*if(mapToInsertProd != null && !mapToInsertProd.isEmpty()){
nameVsId = HIC_ShopifyUtility.insertProduct(mapToInsertProd,configurationList,false,store);
}*/
if(!allProducts.isEmpty())
HIC_ShopifyUtility.initializeProductandVaraint(allProducts);
for (Object obj : allProducts){
Map <String, Object> objMap = (Map<String, Object>)obj;
if(nameVsId != null && !nameVsId.isEmpty()){
productVsPricebookEntryMap.put(nameVsId.get(String.valueof(objMap.get('name'))),null);
productVsUnitepriceMap.put(nameVsId.get(String.valueof(objMap.get('name'))),String.valueof(objMap.get('price')));
}else{
productVsPricebookEntryMap.put(String.valueof(objMap.get('variant_id')),null);
productVsUnitepriceMap.put(String.valueof(objMap.get('variant_id')),String.valueof(objMap.get('price')));
}
}
if(presentmentCurrency!=null && presentmentCurrency!=' '){
updatedProductVsPricebookEntryMap = new Map<String,String>(HIC_ShopifyUtility.InitializePricebookEntryIdorder(productVsPricebookEntryMap,productVsUnitepriceMap,configurationList,presentmentCurrency,store));
}else{
updatedProductVsPricebookEntryMap = new Map<String,String>(HIC_ShopifyUtility.InitializePricebookEntryId(productVsPricebookEntryMap,productVsUnitepriceMap,configurationList,store));
}
List<Object> listOfAllOpportunityItem = new List<Object>();
for (Object obj : allProducts){
Map <String, Object> objMap = (Map<String, Object>)obj;
if(objMap.get('product_id') == null && objMap.get('variant_id') != null){
objMap.put('PricebookEntryId',String.valueOf(updatedProductVsPricebookEntryMap.get(String.valueOf(nameVsId.get(String.valueOf(objMap.get('name')))))));
}else if(objMap.get('product_id') != null){
objMap.put('PricebookEntryId',String.valueOf(updatedProductVsPricebookEntryMap.get(String.valueOf(objMap.get('product_id')))));
}
obj = (Object)objMap;
if((objMap.get('product_id') != null || objMap.get('variant_id') != null)){
if(objMap.containsKey('PricebookEntryId') && objMap.get('PricebookEntryId') != null && String.isNotBlank(String.valueof(objMap.get('PricebookEntryId'))))
listOfAllOpportunityItem.add(obj);
system.debug('listOfAllOpportunityItem--->'+listOfAllOpportunityItem);
}
}
if(opproductFieldsList != null && !opproductFieldsList.isEmpty() && listOfAllOpportunityItem != null && !listOfAllOpportunityItem.isEmpty()) {
HIC_ShopifyUtility.processSobjectList(opproductFieldsList,listOfAllOpportunityItem,'OpportunityLineItem','HIC_ShopifySync__Shopify_Id__c',configurationList,false,store);
}
if(orderproductFieldsList != null && !orderproductFieldsList.isEmpty() && listOfAllOpportunityItem != null && !listOfAllOpportunityItem.isEmpty()){
HIC_ShopifyUtility.processSobjectList(orderproductFieldsList,listOfAllOpportunityItem,'OrderItem', 'HIC_ShopifySync__Shopify_Id__c',configurationList,false,store);
}
// Call Order Fulfillment if user selected true in App page
if(configurationList[0].HIC_ShopifySync__Order_Fulfillment__c== true && check){
system.debug('check521');
HIC_ShopifyUtility.insertOrderfulfillments(scope,configurationList,false,store);
}
if(check && !configurationList[0].HIC_ShopifySync__Order_Status_Activated_To_Draft__c){
for(SObject ord : sobjectList){
ord.put('Status', 'Activated');
}
Database.upsert(sobjectList, theField, false);
}
/******************************************* Process for Line Items End ********************************************/
}
}
global void finish(Database.BatchableContext bc){
try{
if(Schema.sObjectType.HIC_ShopifySync__HIC_Configuration__c.isAccessible() && Schema.sObjectType.HIC_ShopifySync__HIC_Configuration__c.isCreateable()){
List <HIC_ShopifySync__HIC_Configuration__c> configListToCheckObjects = new List <HIC_ShopifySync__HIC_Configuration__c>();
String query = 'Select '+ CheckAccessibility.isAccessible('id,HIC_ShopifySync__DraftOrderBatchCompleted__c, HIC_ShopifySync__CollectionsBatchCompleted__c, HIC_ShopifySync__Collection__c,HIC_ShopifySync__OrderBatchCompleted__c,HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__Private_Key_Password__c,HIC_ShopifySync__Inventory_Location__c, HIC_ShopifySync__Draft_Order_Sync__c, HIC_ShopifySync__Enable_Draft_Order__c,HIC_ShopifySync__API_Key__c, name, 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';
configListToCheckObjects = Database.query(query);
if(shopifyResourceName != null && shopifyResourceName.trim() != '' && String.isNotBlank(linkForNextPage) && !isEnd && !Test.isRunningTest()){
FetchOrders forOrders = new FetchOrders(linkForNextPage,false, shopifyResourceName, configurationList,store,updated_at_min,updated_at_max);
Database.executeBatch(forOrders, 1);
}else if(checkException && !isEnd && !Test.isRunningTest()){
//Call batch again if any exception in callout
FetchOrders callBatchAgain = new FetchOrders(linkForNextPage,false, true, configurationList,store,updated_at_min,updated_at_max,orderBypassFlag);
Database.executeBatch(callBatchAgain,1);
}else if(checkExceptionForDraftOrder && !isEnd && !Test.isRunningTest()){
//Call batch again if any exception in callout
FetchOrders callBatchAgain = new FetchOrders(linkForNextPage,false, false, configurationList,store,updated_at_min,updated_at_max,orderBypassFlag);
Database.executeBatch(callBatchAgain,1);
}else if(!isEnd && !Test.isRunningTest()){
if(check){
//Call batch again for Order
FetchOrders callBatchAgain = new FetchOrders(linkForNextPage,false, true, configurationList,store,updated_at_min,updated_at_max,orderBypassFlag);
Database.executeBatch(callBatchAgain,1);
}else{
//Call batch again for Draft Order
FetchOrders callBatchAgain = new FetchOrders(linkForNextPage,false, false, configurationList,store,updated_at_min,updated_at_max,orderBypassFlag);
Database.executeBatch(callBatchAgain,1);
}
//Call next batch for collection and collects
}else if(!orderBypassFlag && check && configListToCheckObjects[0].HIC_ShopifySync__Collection__c){
HIC_ShopifyUtility.processCollections(configurationList,store,updated_at_min,updated_at_max);
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__OrderBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){
configListToCheckObjects[0].HIC_ShopifySync__OrderBatchCompleted__c = true;
}
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__CollectionsBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){
configListToCheckObjects[0].HIC_ShopifySync__CollectionsBatchCompleted__c = false;
}
if(!configListToCheckObjects.isempty() && configListToCheckObjects != null ){
try{
update configListToCheckObjects;
}catch(Exception e){
}
}
//Call next batch for location and Inventory item and level
}else if(!orderBypassFlag && check && configListToCheckObjects[0].HIC_ShopifySync__Inventory_Location__c){
HIC_ShopifyUtility.fetchLocations(configurationList,store,updated_at_min,updated_at_max);
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__OrderBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){
configListToCheckObjects[0].HIC_ShopifySync__OrderBatchCompleted__c = true;
}
if(!configListToCheckObjects.isempty() && configListToCheckObjects != null ){
try{
update configListToCheckObjects;
}catch(Exception e){
}
}
//Call next batch for Draft Oder
}else if(!orderBypassFlag && configListToCheckObjects[0].HIC_ShopifySync__Draft_Order_Sync__c && check){
HIC_ShopifyUtility.fetchDraftOrders(configListToCheckObjects,store,updated_at_min,updated_at_max);
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__OrderBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){
configListToCheckObjects[0].HIC_ShopifySync__OrderBatchCompleted__c = true;
}
if(!configListToCheckObjects.isempty() && configListToCheckObjects != null ){
try{
update configListToCheckObjects;
}catch(Exception e){
}
}
//Update Configure for tracking batch processing in the page
}else if(!orderBypassFlag && !configListToCheckObjects[0].HIC_ShopifySync__Draft_Order_Sync__c && !configListToCheckObjects[0].HIC_ShopifySync__Collection__c && !configListToCheckObjects[0].HIC_ShopifySync__Inventory_Location__c ){
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__OrderBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){
configListToCheckObjects[0].HIC_ShopifySync__IsCurrencyChanged__c = false;
configListToCheckObjects[0].HIC_ShopifySync__Batch_Is_Processing__c = false;
configListToCheckObjects[0].HIC_ShopifySync__OrderBatchCompleted__c = true;
}
if(!configListToCheckObjects.isempty() && configListToCheckObjects != null ){
try{
update configListToCheckObjects;
}catch(Exception e){
}
EmailErrorCSV.SuccessMailSend();
}
}else if(!orderBypassFlag && !check && configListToCheckObjects[0].HIC_ShopifySync__Draft_Order_Sync__c ){
if(CheckAccessibility.isUpsertable('HIC_ShopifySync__IsCurrencyChanged__c,HIC_ShopifySync__DraftOrderBatchCompleted__c,HIC_ShopifySync__Batch_Is_Processing__c,HIC_ShopifySync__OrderBatchCompleted__c','HIC_ShopifySync__HIC_Configuration__c')){
configListToCheckObjects[0].HIC_ShopifySync__IsCurrencyChanged__c = false;
configListToCheckObjects[0].HIC_ShopifySync__Batch_Is_Processing__c = false;
//configListToCheckObjects[0].HIC_ShopifySync__OrderBatchCompleted__c = true;
configListToCheckObjects[0].HIC_ShopifySync__DraftOrderBatchCompleted__c = true;
}
if(!configListToCheckObjects.isempty() && configListToCheckObjects != null ){
try{
update configListToCheckObjects;
}catch(Exception e){
}
//Sent notification mail
EmailErrorCSV.SuccessMailSend();
}
}
}
}catch(Exception e){
}
}
}