@istest public class EmailErrorCSV_test { @istest public static void testEmailErrorCSV(){ boolean check = false; list emailErrorList = new list(); HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c emailError = new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(); emailError.Name = 'abc'; //emailError.HIC_ShopifySync__Email_Id__c = 'abc@gmail.com'; emailErrorList.add(emailError); Database.upsertResult[] upsertResultList = Database.upsert(emailErrorList, false); list acclist = new list(); Account acc = new Account(); acc.Name = 'Account'; acc.HIC_ShopifySync__Shopify_Id__c = '123'; accList.add(acc); Database.UpsertResult[] updateResult = Database.Upsert(acclist,false); Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account'); Map fieldMap = objectType.getDescribe().fields.getMap(); Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c'); list Contactlist = new list(); Contact cc = new Contact(); cc.HIC_ShopifySync__Shopify_Id__c = '123'; cc.Email = 'test@gmail.com'; Contactlist.add(cc); Database.UpsertResult[] updateResult1 = Database.Upsert(Contactlist,false); Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact'); Map fieldMap1 = objectType1.getDescribe().fields.getMap(); Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c'); HIC_ShopifySync__Error_Mapping__c newError = new HIC_ShopifySync__Error_Mapping__c(); newError.HIC_ShopifySync__Shopify_Field__c = 'name'; newError.Name = 'Account'; insert newError; HIC_ShopifySync__Error_Message__c errorObj = new HIC_ShopifySync__Error_Message__c(); errorObj.HIC_ShopifySync__Delivered__c = false; errorObj.HIC_ShopifySync__Error_id__c= 'Contact'; errorobj.HIC_ShopifySync__Important_Field__c= 'Contact'; errorObj.HIC_ShopifySync__Message__c = 'Contact'; errorObj.HIC_ShopifySync__IsWebhook__c = false; errorObj.Name = 'Contact'; insert errorObj; HIC_ShopifySync__Error_Message__c errorObj1 = new HIC_ShopifySync__Error_Message__c(); errorObj1.HIC_ShopifySync__Delivered__c = false; errorObj1.HIC_ShopifySync__Error_id__c= 'Account'; errorObj1.HIC_ShopifySync__Important_Field__c= 'Account'; errorObj1.HIC_ShopifySync__Message__c = 'Account'; errorObj1.Name = 'Account'; insert errorObj1; List recordList = New List(); HIC_ShopifySync__HIC_Configuration__c shopifyRecord = New HIC_ShopifySync__HIC_Configuration__c(); shopifyRecord.Name = 'Default'; shopifyRecord.HIC_ShopifySync__Upsert_Customer_basis_on_Email__c=true; shopifyRecord.HIC_ShopifySync__Store__c = '123'; shopifyRecord.HIC_ShopifySync__Account_Contact__c = false; shopifyRecord.HIC_ShopifySync__Person_Account__c = true; shopifyRecord.HIC_ShopifySync__Default_Account__c = true; shopifyRecord.HIC_ShopifySync__Shopify_URL__c = '123@gmail.com'; shopifyRecord.HIC_ShopifySync__API_Key__c = 'test'; shopifyRecord.HIC_ShopifySync__Private_Key_Password__c = 'Test'; shopifyRecord.HIC_ShopifySync__Opportunity__c = true; shopifyRecord.HIC_ShopifySync__Order__c = true; shopifyRecord.HIC_ShopifySync__Opportunity_Line_Item__c = true; shopifyRecord.HIC_ShopifySync__Order_Line_Item__c = true; recordList.add(shopifyRecord); insert recordList; EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Account',acclist,theField,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Account',acclist,theField,false); //EmailErrorCSV.makeCsvAndSendInEmail('contact',Contactlist,theField1); EmailErrorCSV.SendErrormail('Account'); //EmailErrorCSV.nestedRecordsJSONBody('{"order":{"id":5397659255067,"admin_graphql_api_id":"gid:\/\/shopify\/Order\/5397659255067","app_id":1354745,"browser_ip":"203.123.32.186","buyer_accepts_marketing":false,"cancel_reason":null,"cancelled_at":null,"cart_token":null,"checkout_id":36747476730139,"checkout_token":"555a5ecf2af75a05a04872886dcacd73","client_details":{"accept_language":"en-US,en;q=0.9","browser_height":null,"browser_ip":"203.123.32.186","browser_width":null,"session_hash":null,"user_agent":"Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/113.0.0.0 Safari\/537.36"},"closed_at":"2023-05-30T07:36:37-04:00","confirmed":true,"contact_email":"amandasilva@gmail.com","created_at":"2023-05-30T07:36:26-04:00","currency":"CAD","current_subtotal_price":"0.00","current_subtotal_price_set":{"shop_money":{"amount":"0.00","currency_code":"CAD"},"presentment_money":{"amount":"0.00","currency_code":"CAD"}},"current_total_discounts":"380.95","current_total_discounts_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"current_total_duties_set":null,"current_total_price":"11.30","current_total_price_set":{"shop_money":{"amount":"11.30","currency_code":"CAD"},"presentment_money":{"amount":"11.30","currency_code":"CAD"}},"current_total_tax":"1.30","current_total_tax_set":{"shop_money":{"amount":"1.30","currency_code":"CAD"},"presentment_money":{"amount":"1.30","currency_code":"CAD"}},"customer_locale":"en","device_id":null,"discount_codes":[{"code":"","amount":"380.95","type":"fixed_amount"}],"email":"amandasilva@gmail.com","estimated_taxes":false,"financial_status":"paid","fulfillment_status":"fulfilled","gateway":"manual","landing_site":null,"landing_site_ref":null,"location_id":null,"name":"#1414","note":null,"note_attributes":[],"number":414,"order_number":1414,"order_status_url":"https:\/\/staging-jacuzzi-hot-tubs-ontario.myshopify.com\/73690874139\/orders\/3b95777c7dbe2dfbe08c583db9109b21\/authenticate?key=4bf4ed8dd52f7dc94bf7894508bae71a","original_total_duties_set":null,"payment_gateway_names":["manual"],"phone":null,"presentment_currency":"CAD","processed_at":"2023-05-30T07:36:25-04:00","processing_method":"manual","reference":"5a6495e235ccdc6f96b62b434cd60ec1","referring_site":null,"source_identifier":"5a6495e235ccdc6f96b62b434cd60ec1","source_name":"shopify_draft_order","source_url":null,"subtotal_price":"0.00","subtotal_price_set":{"shop_money":{"amount":"0.00","currency_code":"CAD"},"presentment_money":{"amount":"0.00","currency_code":"CAD"}},"tags":"","tax_lines":[{"price":"1.30","rate":0.13,"title":"HST","price_set":{"shop_money":{"amount":"1.30","currency_code":"CAD"},"presentment_money":{"amount":"1.30","currency_code":"CAD"}},"channel_liable":false}],"taxes_included":false,"test":false,"token":"3b95777c7dbe2dfbe08c583db9109b21","total_discounts":"380.95","total_discounts_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"total_line_items_price":"380.95","total_line_items_price_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"total_outstanding":"0.00","total_price":"11.30","total_price_set":{"shop_money":{"amount":"11.30","currency_code":"CAD"},"presentment_money":{"amount":"11.30","currency_code":"CAD"}},"total_price_usd":"8.31","total_shipping_price_set":{"shop_money":{"amount":"10.00","currency_code":"CAD"},"presentment_money":{"amount":"10.00","currency_code":"CAD"}},"total_tax":"1.30","total_tax_set":{"shop_money":{"amount":"1.30","currency_code":"CAD"},"presentment_money":{"amount":"1.30","currency_code":"CAD"}},"total_tip_received":"0.00","total_weight":50,"updated_at":"2023-05-30T07:36:37-04:00","user_id":94024630555,"billing_address":{"first_name":"Amanda","address1":"4040 Finch Avenue East","phone":null,"city":"Toronto","zip":"M1S 4V5","province":"Ontario","country":"Canada","last_name":"Silva","address2":null,"company":null,"latitude":43.8024388,"longitude":-79.293892,"name":"Amanda Silva","country_code":"CA","province_code":"ON"},"customer":{"id":7052758319387,"email":"amandasilva@gmail.com","accepts_marketing":false,"created_at":"2023-04-14T10:34:43-04:00","updated_at":"2023-05-30T09:15:29-04:00","first_name":"Amanda","last_name":"Silva","orders_count":19,"state":"disabled","total_spent":"13942.42","last_order_id":5397699232027,"note":null,"verified_email":true,"multipass_identifier":null,"tax_exempt":false,"phone":null,"sms_marketing_consent":null,"tags":"","currency":"CAD","last_order_name":"#1417","accepts_marketing_updated_at":"2023-04-14T10:34:44-04:00","marketing_opt_in_level":null,"tax_exemptions":[],"admin_graphql_api_id":"gid:\/\/shopify\/Customer\/7052758319387","default_address":{"id":9311319130395,"customer_id":7052758319387,"first_name":"Amanda","last_name":"Silva","company":"","address1":"4040 Finch Avenue East","address2":"","city":"Toronto","province":"Ontario","country":"Canada","zip":"M1S 4V5","phone":"","name":"Amanda Silva","province_code":"ON","country_code":"CA","country_name":"Canada","default":true}},"discount_applications":[{"target_type":"line_item","type":"manual","value":"380.95","value_type":"fixed_amount","allocation_method":"across","target_selection":"all","title":"","description":null}],"fulfillments":[{"id":4787371180315,"admin_graphql_api_id":"gid:\/\/shopify\/Fulfillment\/4787371180315","created_at":"2023-05-30T07:36:37-04:00","location_id":80205185307,"name":"#1414.1","order_id":5397659255067,"origin_address":{},"receipt":{},"service":"manual","shipment_status":null,"status":"success","tracking_company":null,"tracking_number":null,"tracking_numbers":[],"tracking_url":null,"tracking_urls":[],"updated_at":"2023-05-30T07:36:37-04:00","line_items":[{"id":14006273376539,"admin_graphql_api_id":"gid:\/\/shopify\/LineItem\/14006273376539","fulfillable_quantity":0,"fulfillment_service":"manual","fulfillment_status":"fulfilled","gift_card":false,"grams":50,"name":"(2013-2016) J-235, J-245, J-275 & J-280 Synthetic Skirt Panels - 8104-427M","origin_location":{"id":3768906219803,"country_code":"CA","province_code":"ON","name":"930 Century Drive","address1":"930 Century Drive","address2":"","city":"Burlington","zip":"L7L 5P2"},"price":"380.95","price_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"product_exists":true,"product_id":8198058410267,"properties":[],"quantity":1,"requires_shipping":true,"sku":"8104-427M","taxable":true,"title":"(2013-2016) J-235, J-245, J-275 & J-280 Synthetic Skirt Panels","total_discount":"0.00","total_discount_set":{"shop_money":{"amount":"0.00","currency_code":"CAD"},"presentment_money":{"amount":"0.00","currency_code":"CAD"}},"variant_id":44825545310491,"variant_inventory_management":null,"variant_title":"8104-427M","vendor":"Hot Tub Store","tax_lines":[{"channel_liable":false,"price":"0.00","price_set":{"shop_money":{"amount":"0.00","currency_code":"CAD"},"presentment_money":{"amount":"0.00","currency_code":"CAD"}},"rate":0.13,"title":"HST"}],"duties":[],"discount_allocations":[{"amount":"380.95","amount_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"discount_application_index":0}]}]}],"line_items":[{"id":14006273376539,"admin_graphql_api_id":"gid:\/\/shopify\/LineItem\/14006273376539","fulfillable_quantity":0,"fulfillment_service":"manual","fulfillment_status":"fulfilled","gift_card":false,"grams":50,"name":"(2013-2016) J-235, J-245, J-275 & J-280 Synthetic Skirt Panels - 8104-427M","origin_location":{"id":3768906219803,"country_code":"CA","province_code":"ON","name":"930 Century Drive","address1":"930 Century Drive","address2":"","city":"Burlington","zip":"L7L 5P2"},"price":"380.95","price_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"product_exists":true,"product_id":8198058410267,"properties":[],"quantity":1,"requires_shipping":true,"sku":"8104-427M","taxable":true,"title":"(2013-2016) J-235, J-245, J-275 & J-280 Synthetic Skirt Panels","total_discount":"0.00","total_discount_set":{"shop_money":{"amount":"0.00","currency_code":"CAD"},"presentment_money":{"amount":"0.00","currency_code":"CAD"}},"variant_id":44825545310491,"variant_inventory_management":null,"variant_title":"8104-427M","vendor":"Hot Tub Store","tax_lines":[{"channel_liable":false,"price":"0.00","price_set":{"shop_money":{"amount":"0.00","currency_code":"CAD"},"presentment_money":{"amount":"0.00","currency_code":"CAD"}},"rate":0.13,"title":"HST"}],"duties":[],"discount_allocations":[{"amount":"380.95","amount_set":{"shop_money":{"amount":"380.95","currency_code":"CAD"},"presentment_money":{"amount":"380.95","currency_code":"CAD"}},"discount_application_index":0}]}],"payment_terms":null,"refunds":[],"shipping_address":{"first_name":"Amanda","address1":"4040 Finch Avenue East","phone":null,"city":"Toronto","zip":"M1S 4V5","province":"Ontario","country":"Canada","last_name":"Silva","address2":null,"company":null,"latitude":43.8024388,"longitude":-79.293892,"name":"Amanda Silva","country_code":"CA","province_code":"ON"},"shipping_lines":[{"id":4414364385563,"carrier_identifier":"4084464f694a06e6683c491d00cef27f","code":"custom","delivery_category":null,"discounted_price":"10.00","discounted_price_set":{"shop_money":{"amount":"10.00","currency_code":"CAD"},"presentment_money":{"amount":"10.00","currency_code":"CAD"}},"phone":null,"price":"10.00","price_set":{"shop_money":{"amount":"10.00","currency_code":"CAD"},"presentment_money":{"amount":"10.00","currency_code":"CAD"}},"requested_fulfillment_service_id":null,"source":"shopify","title":"Custom","tax_lines":[{"channel_liable":false,"price":"1.30","price_set":{"shop_money":{"amount":"1.30","currency_code":"CAD"},"presentment_money":{"amount":"1.30","currency_code":"CAD"}},"rate":0.13,"title":"HST"}],"discount_allocations":[]}]}}'); EmailErrorCSV.SuccessMailSend(); check = true; system.assertEquals(check,true); } @istest public static void testEmailErrorCSV2(){ boolean check = false; list emailErrorList = new list(); HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c emailError = new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(); emailError.Name = 'abc'; // emailError.HIC_ShopifySync__Email_Id__c = 'abc@gmail.com'; emailErrorList.add(emailError); Database.upsertResult[] upsertResultList = Database.upsert(emailErrorList, false); list acclist = new list(); Account acc = new Account(); acc.HIC_ShopifySync__Shopify_Id__c = '123'; accList.add(acc); Database.UpsertResult[] updateResult = Database.Upsert(acclist,false); Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account'); Map fieldMap = objectType.getDescribe().fields.getMap(); Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c'); list Contactlist = new list(); Contact cc = new Contact(); cc.HIC_ShopifySync__Shopify_Id__c = '123'; cc.Email='test@mgail'; Contactlist.add(cc); Database.UpsertResult[] updateResult1 = Database.Upsert(Contactlist,false); Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact'); Map fieldMap1 = objectType1.getDescribe().fields.getMap(); Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c'); Schema.SobjectField theField111 = fieldMap1.get(''); HIC_ShopifySync__Error_Mapping__c newError = new HIC_ShopifySync__Error_Mapping__c(); newError.HIC_ShopifySync__Shopify_Field__c = 'name'; newError.Name = 'Account'; insert newError; HIC_ShopifySync__Error_Message__c errorObj = new HIC_ShopifySync__Error_Message__c(); errorObj.HIC_ShopifySync__Delivered__c = false; errorObj.HIC_ShopifySync__IsWebhook__c = false; errorObj.HIC_ShopifySync__Error_id__c= 'Contact'; errorobj.HIC_ShopifySync__Important_Field__c= 'Contact'; errorObj.HIC_ShopifySync__Shopify_id__c='Contact'; errorObj.HIC_ShopifySync__Message__c = 'Contact'; errorObj.Name = 'Contact'; insert errorObj; list hicerr = new list(); HIC_ShopifySync__Error_Message__c errorObj1 = new HIC_ShopifySync__Error_Message__c(); errorObj1.HIC_ShopifySync__Delivered__c = false; errorObj1.HIC_ShopifySync__Error_id__c= 'Account'; errorObj1.HIC_ShopifySync__Shopify_id__c='Account'; errorobj1.HIC_ShopifySync__Iswebhook__c = false; errorObj1.HIC_ShopifySync__Important_Field__c= 'Account'; errorObj1.HIC_ShopifySync__Message__c = 'Account'; errorObj1.Name = 'Account'; hicerr.add(errorObj1); insert errorObj1; List pdList= new List(); Product2 prod = new Product2(Name = 'Test product', Description = 'This is test product', Family = 'None'); pdList.add(prod); Database.UpsertResult[] updateResult2 = Database.Upsert(pdList,false); Schema.SObjectType objectType2 = Schema.getGlobalDescribe().get('Product2'); Map fieldMap2 = objectType2.getDescribe().fields.getMap(); Schema.SobjectField theField2 = fieldMap2.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Product2',pdList,theField2,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Contact',Contactlist,theField1,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Contact',Contactlist,theField111,true); List oppList = new List(); Opportunity opp = new Opportunity(Name = 'test opp', StageName = 'Prospecting', CloseDate = system.Today()); oppList.add(opp); Database.UpsertResult[] updateResult3 = Database.Upsert(oppList,false); Schema.SObjectType objectType3 = Schema.getGlobalDescribe().get('Opportunity'); Map fieldMap3 = objectType3.getDescribe().fields.getMap(); Schema.SobjectField theField3 = fieldMap3.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Opportunity',oppList,theField3,true); Id pricebookId = Test.getStandardPricebookId(); //Create your pricebook entry PricebookEntry pbEntry = new PricebookEntry( Pricebook2Id = pricebookId, Product2Id = pdList[0].Id, UnitPrice = 100.00, IsActive = true ); insert pbEntry; List oliList = new List(); OpportunityLineItem oli = new OpportunityLineItem( OpportunityId = oppList[0].Id, Quantity = 5, PricebookEntryId = pbEntry.Id, TotalPrice = pbEntry.UnitPrice ); oliList.add(oli); //insert oli; Database.UpsertResult[] updateResult4 = Database.Upsert(oliList,false); Schema.SObjectType objectType4 = Schema.getGlobalDescribe().get('OpportunityLineItem'); Map fieldMap4 = objectType4.getDescribe().fields.getMap(); Schema.SobjectField theField4 = fieldMap4.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','OpportunityLineItem', oliList, theField4,true); List odList = new List(); Order orderRecord = new Order(); orderRecord.AccountId = accList[0].id; orderRecord.Description = 'Test'; orderRecord.Status = 'Draft'; orderRecord.EffectiveDate = Date.today(); orderRecord.Name = 'Test Order'; orderRecord.PriceBook2Id = pricebookId; odList.add(orderRecord); Database.UpsertResult[] updateResult5 = Database.Upsert(odList,false); Schema.SObjectType objectType5 = Schema.getGlobalDescribe().get('Order'); Map fieldMap5 = objectType5.getDescribe().fields.getMap(); Schema.SobjectField theField5 = fieldMap5.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Order', odList, theField5,true); List odItemList = new List(); OrderItem odItem = new OrderItem(); odItem.quantity = oliList[0].quantity; odItem.PriceBookEntryId = pbEntry.Id; odItem.OrderId = odList[0].id; odItemList.add(odItem); Database.UpsertResult[] updateResult6 = Database.Upsert(odItemList,false); Schema.SObjectType objectType6 = Schema.getGlobalDescribe().get('OrderItem'); Map fieldMap6 = objectType6.getDescribe().fields.getMap(); Schema.SobjectField theField6 = fieldMap6.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','OrderItem', odItemList, theField6,true); List collectionObjList = new List(); HIC_ShopifySync__Collection__c collectionObj = new HIC_ShopifySync__Collection__c(); collectionObj.name='TestCollection'; collectionObjList.add(collectionObj); Database.UpsertResult[] updateResult7 = Database.Upsert(collectionObjList,false); Schema.SObjectType objectType7 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Collection__c'); Map fieldMap7 = objectType7.getDescribe().fields.getMap(); Schema.SobjectField theField7 = fieldMap7.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Collection__c', collectionObjList, theField7,true); List collectObjList = new List(); HIC_ShopifySync__Collect__c collectObj = new HIC_ShopifySync__Collect__c(); collectObj.name='Test Collect'; collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; collectObjList.add(collectObj); Database.UpsertResult[] updateResult8 = Database.Upsert(collectObjList,false); Schema.SObjectType objectType8 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Collect__c'); Map fieldMap8 = objectType8.getDescribe().fields.getMap(); Schema.SobjectField theField8 = fieldMap8.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Collect__c', collectObjList, theField8,true); List invenObjList = new List(); HIC_ShopifySync__Inventory__c InvObj = new HIC_ShopifySync__Inventory__c(); //InvObj.name='Test Collect'; //collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; invenObjList.add(InvObj); Database.UpsertResult[] updateResult9 = Database.Upsert(collectObjList,false); Schema.SObjectType objectType9 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Inventory__c'); Map fieldMap9 = objectType9.getDescribe().fields.getMap(); Schema.SobjectField theField9 = fieldMap9.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Inventory__c', invenObjList, theField9,true); List invenLevelObjList = new List(); HIC_ShopifySync__Inventory_Level__c InvlevelObj = new HIC_ShopifySync__Inventory_Level__c(); //InvlevelObj.name='Test Collect'; //collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; invenLevelObjList.add(InvlevelObj); Schema.SObjectType objectType10 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Inventory_Level__c'); Map fieldMap10 = objectType10.getDescribe().fields.getMap(); Schema.SobjectField theField10 = fieldMap10.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Inventory_Level__c', invenLevelObjList, theField10,true); List LevelObjList = new List(); HIC_ShopifySync__Location__c levelObj = new HIC_ShopifySync__Location__c(); levelObj.HIC_ShopifySync__Shopify_Id__c = NULL; //InvlevelObj.name='Test Collect'; //collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; LevelObjList.add(levelObj); Schema.SObjectType objectType11 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Location__c'); Map fieldMap11 = objectType11.getDescribe().fields.getMap(); Schema.SobjectField theField11 = fieldMap11.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Location__c', invenLevelObjList, theField11,true); EmailErrorCSV.makeCsvAndSendInEmail('{"id":123456}','HIC_ShopifySync__Location__c', invenLevelObjList, theField11,true); EmailErrorCSV.makeCsvAndSendInEmail('{"id":123456}','HIC_ShopifySync__Location__c', invenLevelObjList, theField11,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Missing_Order__c', invenLevelObjList, theField11,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Order_Fulfillment__c', invenLevelObjList, theField11,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Order_Fulfillment_Item__c', invenLevelObjList, theField11,true); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Variant__c', invenLevelObjList, theField11,true); check = true; system.assertEquals(check,true); List mssngLst = new List(); HIC_ShopifySync__Missing_Order__c shpmssing = new HIC_ShopifySync__Missing_Order__c(); shpmssing.HIC_ShopifySync__Missing_Order_Info__c = 'test'; mssngLst.add(shpmssing); insert mssngLst; List fulfilLst = new List(); HIC_ShopifySync__Order_Fulfillment__c fulfil = new HIC_ShopifySync__Order_Fulfillment__c(); fulfil.HIC_ShopifySync__Created_At_Shopify__c = system.today(); fulfilLst.add(fulfil); insert fulfilLst; List orfulfilLst = new List(); HIC_ShopifySync__Order_Fulfillment_Item__c orfulfil = new HIC_ShopifySync__Order_Fulfillment_Item__c(); orfulfil.HIC_ShopifySync__Order_Fulfillment__c = fulfil.id; orfulfilLst.add(orfulfil); insert orfulfilLst; List vrntLst = new List(); HIC_ShopifySync__Variant__c vrnt = new HIC_ShopifySync__Variant__c(); vrnt.HIC_ShopifySync__Inventory_Item_Id__c = 'test'; vrntLst.add(vrnt); insert vrntLst; list deleteresult = Database.Delete(hicerr,false); test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Product2', pdList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Account', acclist, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Contact', Contactlist, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Opportunity', oppList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'OpportunityLineItem', oliList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Order', odList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'OrderItem', odItemList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Collect__c', collectObjList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Collection__c', collectionObjList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Inventory__c', invenObjList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Inventory_Level__c', invenLevelObjList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Location__c', LevelObjList, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Missing_Order__c', mssngLst, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Order_Fulfillment__c', fulfilLst, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Order_Fulfillment_Item__c', orfulfilLst, theField8, true,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Variant__c', vrntLst, theField8, true,'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Error_Message__c', 'jSONRequestBody', deleteresult, Contactlist, 'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Shopify_Log__c', '', deleteresult, Contactlist, 'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Error_Message__c', 'jSONRequestBody',deleteresult,Contactlist); test.stopTest(); } @istest public static void testEmailErrorCSV3(){ boolean check = false; list emailErrorList = new list(); HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c emailError = new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(); emailError.Name = 'abc'; // emailError.HIC_ShopifySync__Email_Id__c = 'abc@gmail.com'; emailErrorList.add(emailError); Database.upsertResult[] upsertResultList = Database.upsert(emailErrorList, false); list acclist = new list(); Account acc = new Account(); acc.HIC_ShopifySync__Shopify_Id__c = '123'; accList.add(acc); Database.UpsertResult[] updateResult = Database.Upsert(acclist,false); Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Account'); Map fieldMap = objectType.getDescribe().fields.getMap(); Schema.SobjectField theField = fieldMap.get('HIC_ShopifySync__Shopify_Id__c'); list Contactlist = new list(); Contact cc = new Contact(); cc.HIC_ShopifySync__Shopify_Id__c = '123'; cc.Email='test@mgail'; Contactlist.add(cc); Database.UpsertResult[] updateResult1 = Database.Upsert(Contactlist,false); Schema.SObjectType objectType1 = Schema.getGlobalDescribe().get('Contact'); Map fieldMap1 = objectType1.getDescribe().fields.getMap(); Schema.SobjectField theField1 = fieldMap1.get('HIC_ShopifySync__Shopify_Id__c'); Schema.SobjectField theField111 = fieldMap1.get(''); HIC_ShopifySync__Error_Mapping__c newError = new HIC_ShopifySync__Error_Mapping__c(); newError.HIC_ShopifySync__Shopify_Field__c = 'name'; newError.Name = 'Account'; insert newError; HIC_ShopifySync__Error_Message__c errorObj = new HIC_ShopifySync__Error_Message__c(); errorObj.HIC_ShopifySync__Delivered__c = false; errorObj.HIC_ShopifySync__IsWebhook__c = false; errorObj.HIC_ShopifySync__Error_id__c= 'Contact'; errorobj.HIC_ShopifySync__Important_Field__c= 'Contact'; errorObj.HIC_ShopifySync__Shopify_id__c='Contact'; errorObj.HIC_ShopifySync__Message__c = 'Contact'; errorObj.Name = 'Contact'; insert errorObj; list hicerr = new list(); HIC_ShopifySync__Error_Message__c errorObj1 = new HIC_ShopifySync__Error_Message__c(); errorObj1.HIC_ShopifySync__Delivered__c = false; errorObj1.HIC_ShopifySync__Error_id__c= 'Account'; errorObj1.HIC_ShopifySync__Shopify_id__c='Account'; errorobj1.HIC_ShopifySync__Iswebhook__c = false; errorObj1.HIC_ShopifySync__Important_Field__c= 'Account'; errorObj1.HIC_ShopifySync__Message__c = 'Account'; errorObj1.Name = 'Account'; hicerr.add(errorObj1); insert errorObj1; List pdList= new List(); Product2 prod = new Product2(Name = 'Test product', Description = 'This is test product', Family = 'None'); pdList.add(prod); Database.UpsertResult[] updateResult2 = Database.Upsert(pdList,false); Schema.SObjectType objectType2 = Schema.getGlobalDescribe().get('Product2'); Map fieldMap2 = objectType2.getDescribe().fields.getMap(); Schema.SobjectField theField2 = fieldMap2.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Product2',pdList,theField2,false); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Contact',Contactlist,theField1,false); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Contact',Contactlist,theField111,false); List oppList = new List(); Opportunity opp = new Opportunity(Name = 'test opp', StageName = 'Prospecting', CloseDate = system.Today()); oppList.add(opp); Database.UpsertResult[] updateResult3 = Database.Upsert(oppList,false); Schema.SObjectType objectType3 = Schema.getGlobalDescribe().get('Opportunity'); Map fieldMap3 = objectType3.getDescribe().fields.getMap(); Schema.SobjectField theField3 = fieldMap3.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Opportunity',oppList,theField3,false); Id pricebookId = Test.getStandardPricebookId(); //Create your pricebook entry PricebookEntry pbEntry = new PricebookEntry( Pricebook2Id = pricebookId, Product2Id = pdList[0].Id, UnitPrice = 100.00, IsActive = true ); insert pbEntry; List oliList = new List(); OpportunityLineItem oli = new OpportunityLineItem( OpportunityId = oppList[0].Id, Quantity = 5, PricebookEntryId = pbEntry.Id, TotalPrice = pbEntry.UnitPrice ); oliList.add(oli); //insert oli; Database.UpsertResult[] updateResult4 = Database.Upsert(oliList,false); Schema.SObjectType objectType4 = Schema.getGlobalDescribe().get('OpportunityLineItem'); Map fieldMap4 = objectType4.getDescribe().fields.getMap(); Schema.SobjectField theField4 = fieldMap4.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','OpportunityLineItem', oliList, theField4,false); List odList = new List(); Order orderRecord = new Order(); orderRecord.AccountId = accList[0].id; orderRecord.Description = 'Test'; orderRecord.Status = 'Draft'; orderRecord.EffectiveDate = Date.today(); orderRecord.Name = 'Test Order'; orderRecord.PriceBook2Id = pricebookId; odList.add(orderRecord); Database.UpsertResult[] updateResult5 = Database.Upsert(odList,false); Schema.SObjectType objectType5 = Schema.getGlobalDescribe().get('Order'); Map fieldMap5 = objectType5.getDescribe().fields.getMap(); Schema.SobjectField theField5 = fieldMap5.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','Order', odList, theField5,false); List odItemList = new List(); OrderItem odItem = new OrderItem(); odItem.quantity = oliList[0].quantity; odItem.PriceBookEntryId = pbEntry.Id; odItem.OrderId = odList[0].id; odItemList.add(odItem); Database.UpsertResult[] updateResult6 = Database.Upsert(odItemList,false); Schema.SObjectType objectType6 = Schema.getGlobalDescribe().get('OrderItem'); Map fieldMap6 = objectType6.getDescribe().fields.getMap(); Schema.SobjectField theField6 = fieldMap6.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','OrderItem', odItemList, theField6,false); List collectionObjList = new List(); HIC_ShopifySync__Collection__c collectionObj = new HIC_ShopifySync__Collection__c(); collectionObj.name='TestCollection'; collectionObjList.add(collectionObj); Database.UpsertResult[] updateResult7 = Database.Upsert(collectionObjList,false); Schema.SObjectType objectType7 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Collection__c'); Map fieldMap7 = objectType7.getDescribe().fields.getMap(); Schema.SobjectField theField7 = fieldMap7.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Collection__c', collectionObjList, theField7,false); List collectObjList = new List(); HIC_ShopifySync__Collect__c collectObj = new HIC_ShopifySync__Collect__c(); collectObj.name='Test Collect'; collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; collectObjList.add(collectObj); Database.UpsertResult[] updateResult8 = Database.Upsert(collectObjList,false); Schema.SObjectType objectType8 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Collect__c'); Map fieldMap8 = objectType8.getDescribe().fields.getMap(); Schema.SobjectField theField8 = fieldMap8.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Collect__c', collectObjList, theField8,false); List invenObjList = new List(); HIC_ShopifySync__Inventory__c InvObj = new HIC_ShopifySync__Inventory__c(); //InvObj.name='Test Collect'; //collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; invenObjList.add(InvObj); Database.UpsertResult[] updateResult9 = Database.Upsert(collectObjList,false); Schema.SObjectType objectType9 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Inventory__c'); Map fieldMap9 = objectType9.getDescribe().fields.getMap(); Schema.SobjectField theField9 = fieldMap9.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Inventory__c', invenObjList, theField9,false); List invenLevelObjList = new List(); HIC_ShopifySync__Inventory_Level__c InvlevelObj = new HIC_ShopifySync__Inventory_Level__c(); //InvlevelObj.name='Test Collect'; //collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; invenLevelObjList.add(InvlevelObj); Schema.SObjectType objectType10 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Inventory_Level__c'); Map fieldMap10 = objectType10.getDescribe().fields.getMap(); Schema.SobjectField theField10 = fieldMap10.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Inventory_Level__c', invenLevelObjList, theField10,false); List LevelObjList = new List(); HIC_ShopifySync__Location__c levelObj = new HIC_ShopifySync__Location__c(); levelObj.HIC_ShopifySync__Shopify_Id__c = NULL; //InvlevelObj.name='Test Collect'; //collectObj.HIC_ShopifySync__Collection__c= collectionObjList[0].id ; LevelObjList.add(levelObj); Schema.SObjectType objectType11 = Schema.getGlobalDescribe().get('HIC_ShopifySync__Location__c'); Map fieldMap11 = objectType11.getDescribe().fields.getMap(); Schema.SobjectField theField11 = fieldMap11.get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Location__c', invenLevelObjList, theField11,false); EmailErrorCSV.makeCsvAndSendInEmail('{"id":123456}','HIC_ShopifySync__Location__c', invenLevelObjList, theField11,false); EmailErrorCSV.makeCsvAndSendInEmail('{"id":123456}','HIC_ShopifySync__Location__c', invenLevelObjList, theField11,false); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Missing_Order__c', invenLevelObjList, theField11,false); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Order_Fulfillment__c', invenLevelObjList, theField11,false); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Order_Fulfillment_Item__c', invenLevelObjList, theField11,false); EmailErrorCSV.makeCsvAndSendInEmail('[{"id":123456}]','HIC_ShopifySync__Variant__c', invenLevelObjList, theField11,false); check = true; system.assertEquals(check,true); List mssngLst = new List(); HIC_ShopifySync__Missing_Order__c shpmssing = new HIC_ShopifySync__Missing_Order__c(); shpmssing.HIC_ShopifySync__Missing_Order_Info__c = 'test'; mssngLst.add(shpmssing); insert mssngLst; List fulfilLst = new List(); HIC_ShopifySync__Order_Fulfillment__c fulfil = new HIC_ShopifySync__Order_Fulfillment__c(); fulfil.HIC_ShopifySync__Created_At_Shopify__c = system.today(); fulfilLst.add(fulfil); insert fulfilLst; List orfulfilLst = new List(); HIC_ShopifySync__Order_Fulfillment_Item__c orfulfil = new HIC_ShopifySync__Order_Fulfillment_Item__c(); orfulfil.HIC_ShopifySync__Order_Fulfillment__c = fulfil.id; orfulfilLst.add(orfulfil); insert orfulfilLst; List vrntLst = new List(); HIC_ShopifySync__Variant__c vrnt = new HIC_ShopifySync__Variant__c(); vrnt.HIC_ShopifySync__Inventory_Item_Id__c = 'test'; vrntLst.add(vrnt); insert vrntLst; list deleteresult = Database.Delete(hicerr,false); test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Product2', pdList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Account', acclist, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Contact', Contactlist, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Opportunity', oppList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'OpportunityLineItem', oliList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'Order', odList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'OrderItem', odItemList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Collect__c', collectObjList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Collection__c', collectionObjList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Inventory__c', invenObjList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Inventory_Level__c', invenLevelObjList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Location__c', LevelObjList, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Missing_Order__c', mssngLst, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Order_Fulfillment__c', fulfilLst, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Order_Fulfillment_Item__c', orfulfilLst, theField8, false,'store'); EmailErrorCSV.makeCsvAndSendInEmail('jSONRequestBody', 'HIC_ShopifySync__Variant__c', vrntLst, theField8, false,'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Error_Message__c', 'jSONRequestBody', deleteresult, Contactlist, 'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Shopify_Log__c', '', deleteresult, Contactlist, 'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Error_Message__c', 'jSONRequestBody',deleteresult,Contactlist); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Error_Message__c', 'jSONRequestBody', deleteresult, Contactlist, 'store'); EmailErrorCSV.DeleteRecords('HIC_ShopifySync__Error_Message__c', 'jSONRequestBody', deleteresult, Contactlist, 'store'); test.stopTest(); } @isTest static void testProduct2EqualsRule() { // Insert configuration with the Product2 prevent duplicate rule insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'TestConfig', HIC_ShopifySync__Store__c = 'test_store', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"title","SalesforceFieldApiName":"Name","MatchingOperator":"equals","SalesforceObject":"Product2"}]' ); // Existing Product2 record Product2 prod = new Product2(Name='Test Title', HIC_ShopifySync__Shopify_Id__c='oldProdId'); insert prod; // Simulated Shopify JSON with "title":"Test Title" String shopifyJson = '{"title":"Test Title"}'; // New Product2 record with same Name but different Shopify Id List prodList = new List{ new Product2(Name='Test Title', HIC_ShopifySync__Shopify_Id__c='newProdId') }; // Get external Id field reference Schema.SObjectField extId = Schema.getGlobalDescribe().get('Product2').getDescribe().fields.getMap().get('HIC_ShopifySync__Shopify_Id__c'); // Call your method (replace MyClass with your actual class name if needed) EmailErrorCSV.makeCsvAndSendInEmail(shopifyJson, 'Product2', prodList, extId, false, 'test_store'); // Assert that the original Product2 record got updated Product2 updated = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Product2 WHERE Name='Test Title' LIMIT 1]; System.assertEquals('oldProdId', updated.HIC_ShopifySync__Shopify_Id__c, 'Shopify Id should be updated after deduplication'); } @isTest static void testAccountContainsRule() { // Insert configuration with the Account prevent duplicate rule insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'TestConfig', HIC_ShopifySync__Store__c = 'test_store', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"default_address.company","SalesforceFieldApiName":"Name","MatchingOperator":"contains","SalesforceObject":"Account"}]' ); // Existing Account record Account acc = new Account(Name='Acme Corp', HIC_ShopifySync__Shopify_Id__c='oldAccId'); insert acc; // Simulated Shopify JSON with company name containing "Acme" String shopifyJson = '{"default_address": {"company": "Acme"}}'; // New Account record with the same Name but a new Shopify Id List accList = new List{ new Account(Name='Acme Corp', HIC_ShopifySync__Shopify_Id__c='newAccId') }; // Get external Id field reference Schema.SObjectField extId = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().get('HIC_ShopifySync__Shopify_Id__c'); // Call your method (replace MyClass with your actual class name if needed) EmailErrorCSV.makeCsvAndSendInEmail(shopifyJson, 'Account', accList, extId, false, 'test_store'); // Assert that the original Account record got updated Account updated = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Account WHERE Name='Acme Corp' LIMIT 1]; System.assertEquals('oldAccId', updated.HIC_ShopifySync__Shopify_Id__c, 'Shopify Id should be updated after deduplication'); } @isTest static void testContactEmailContainsRule() { insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'TestConfig', HIC_ShopifySync__Store__c = 'test_store', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"email","SalesforceFieldApiName":"Email","MatchingOperator":"contains","SalesforceObject":"Contact"}]' ); Contact con = new Contact(LastName='Test Contact', Email='user@example.com', HIC_ShopifySync__Shopify_Id__c='oldConId'); insert con; String shopifyJson = '{"email":"user@example.com"}'; List conList = new List{ new Contact(LastName='Test Contact', Email='user@example.com', HIC_ShopifySync__Shopify_Id__c='newConId') }; Schema.SObjectField extId = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap().get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail(shopifyJson, 'Contact', conList, extId, false, 'test_store'); Contact updated = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Contact WHERE Email='user@example.com' LIMIT 1]; //System.assertEquals('oldConId', updated.HIC_ShopifySync__Shopify_Id__c, 'Shopify Id should be updated after deduplication'); } @isTest static void testLeadEmailContainsRule() { // Insert configuration with the Lead prevent duplicate rule insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'TestConfig', HIC_ShopifySync__Store__c = 'test_store', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"email","SalesforceFieldApiName":"Email","MatchingOperator":"contains","SalesforceObject":"Lead"}]' ); Lead lead = new Lead(LastName='Test Lead', Email='user@example.com', HIC_ShopifySync__Shopify_Id__c='oldLeadId', Company='Acme'); insert lead; String shopifyJson = '{"email":"user@example.com"}'; List leadList = new List{ new Lead(LastName='Test Lead', Email='user@example.com', Company='Acme', HIC_ShopifySync__Shopify_Id__c='newLeadId') }; Schema.SObjectField extId = Schema.getGlobalDescribe().get('Lead').getDescribe().fields.getMap().get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail(shopifyJson, 'Lead', leadList, extId, false, 'test_store'); Lead updated = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Lead WHERE Email='user@example.com' LIMIT 1]; } @isTest static void testOpportunityEqualsRule() { insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'TestConfig', HIC_ShopifySync__Store__c = 'test_store', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"cancel_reason","SalesforceFieldApiName":"HIC_ShopifySync__Cancelled_Reason__c","MatchingOperator":"equals","SalesforceObject":"Opportunity"}]' ); Opportunity opp = new Opportunity( Name='OppCancel', StageName='Prospecting', CloseDate=Date.today(), HIC_ShopifySync__Cancelled_Reason__c='ReasonX', HIC_ShopifySync__Shopify_Id__c='oldOppId' ); insert opp; String shopifyJson = '{"cancel_reason":"ReasonX"}'; List oppList = new List{ new Opportunity( Name='OppCancel', StageName='Prospecting', CloseDate=Date.today(), HIC_ShopifySync__Cancelled_Reason__c='ReasonX', HIC_ShopifySync__Shopify_Id__c='newOppId' ) }; Schema.SObjectField extId = Schema.getGlobalDescribe().get('Opportunity').getDescribe().fields.getMap().get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail(shopifyJson, 'Opportunity', oppList, extId, false, 'test_store'); Opportunity updated = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Opportunity WHERE HIC_ShopifySync__Cancelled_Reason__c='ReasonX' LIMIT 1]; System.assertEquals('oldOppId', updated.HIC_ShopifySync__Shopify_Id__c, 'Shopify Id should be updated after deduplication'); } @isTest static void testOrderEqualsRule() { insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'TestConfig', HIC_ShopifySync__Store__c = 'test_store', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"billing_address.name","SalesforceFieldApiName":"HIC_ShopifySync__Billing_Customer_Name__c","MatchingOperator":"equals","SalesforceObject":"Order"}]' ); Account acc = new Account(Name='OrderTestAcc'); insert acc; Order ord = new Order( Name='OrderTest', AccountId=acc.Id, HIC_ShopifySync__Billing_Customer_Name__c='Bill Name', HIC_ShopifySync__Shopify_Id__c='oldOrderId', Status='Draft', EffectiveDate=Date.today() ); insert ord; String shopifyJson = '{"billing_address":{"name":"Bill Name"}}'; List ordList = new List{ new Order( Name='OrderTest', AccountId=acc.Id, HIC_ShopifySync__Billing_Customer_Name__c='Bill Name', HIC_ShopifySync__Shopify_Id__c='newOrderId', Status='Draft', EffectiveDate=Date.today() ) }; Schema.SObjectField extId = Schema.getGlobalDescribe().get('Order').getDescribe().fields.getMap().get('HIC_ShopifySync__Shopify_Id__c'); EmailErrorCSV.makeCsvAndSendInEmail(shopifyJson, 'Order', ordList, extId, false, 'test_store'); Order updated = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Order WHERE HIC_ShopifySync__Billing_Customer_Name__c='Bill Name' LIMIT 1]; System.assertEquals('oldOrderId', updated.HIC_ShopifySync__Shopify_Id__c, 'Shopify Id should be updated after deduplication'); } private static HIC_ShopifySync__HIC_Configuration__c makeConfig( String store, Boolean upsertByEmail, Boolean personAccount, Boolean upsertByCompany, Boolean updateIdentifiedAccount, Boolean updateIdentifiedContact, Boolean updateIdentifiedLead, String dynamicDedupe) { HIC_ShopifySync__HIC_Configuration__c cfg = new HIC_ShopifySync__HIC_Configuration__c( Name = 'Config-' + store, HIC_ShopifySync__Store__c = store, HIC_ShopifySync__Upsert_Customer_basis_on_Email__c = upsertByEmail, HIC_ShopifySync__Person_Account__c = personAccount, HIC_ShopifySync__Upsert_Account_basis_on_Customer_Company__c = upsertByCompany, HIC_ShopifySync__Update_Identified_Account_Records__c = updateIdentifiedAccount, HIC_ShopifySync__Update_Identified_Contact_Records__c = updateIdentifiedContact, HIC_ShopifySync__Update_Identified_Lead_Records__c = updateIdentifiedLead, HIC_ShopifySync__Dynamic_prevent_duplicate__c = dynamicDedupe, HIC_ShopifySync__Shopify_URL__c = 'test.myshopify.com', HIC_ShopifySync__API_Key__c = 'key', HIC_ShopifySync__Private_Key_Password__c = 'pwd', HIC_ShopifySync__Opportunity__c = true, HIC_ShopifySync__Order__c = true, HIC_ShopifySync__Opportunity_Line_Item__c = true, HIC_ShopifySync__Order_Line_Item__c = true ); insert cfg; return cfg; } private static Schema.SObjectField extId(String objName) { return Schema.getGlobalDescribe() .get(objName) .getDescribe() .fields.getMap() .get('HIC_ShopifySync__Shopify_Id__c'); } // ───────────────────────────────────────────────────────────────────────── // 1. flushFeatureParameters – fpOrd and fpOrdItem > 0 branch // ───────────────────────────────────────────────────────────────────────── @isTest static void testFlushFeatureParameters_nonZero() { // Drive fpOrd via an Order upsert that has a Payment_Status value makeConfig('storeFlush', false, false, false, false, false, false, null); Account acc = new Account(Name = 'FlushAcc'); insert acc; Id pbId = Test.getStandardPricebookId(); List ods = new List{ new Order( AccountId = acc.Id, Status = 'Draft', EffectiveDate = Date.today(), Pricebook2Id = pbId, HIC_ShopifySync__Shopify_Id__c = 'flush-order-001', HIC_ShopifySync__Payment_Status__c = 'paid' ) }; insert ods; // Reset to simulate a fresh run //EmailErrorCSV.fpOrd = 0; //EmailErrorCSV.fpOrdItem = 0; // Produce a new order so fpOrd increments List newOds = new List{ new Order( AccountId = acc.Id, Status = 'Draft', EffectiveDate = Date.today(), Pricebook2Id = pbId, HIC_ShopifySync__Shopify_Id__c = 'flush-order-002', HIC_ShopifySync__Payment_Status__c = 'paid' ) }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"flush-order-002","payment_status":"paid"}]', 'Order', newOds, extId('Order'), true, 'storeFlush'); EmailErrorCSV.flushFeatureParameters(); Test.stopTest(); // No exception = pass; FeatureParameter.incrementAsync is a void call System.assert(true, 'flushFeatureParameters completed without error'); } @isTest static void testFlushFeatureParameters_zero() { // When counters are already 0 the map is empty and incrementAsync is NOT called //EmailErrorCSV.fpOrd = 0; //EmailErrorCSV.fpOrdItem = 0; Test.startTest(); EmailErrorCSV.flushFeatureParameters(); Test.stopTest(); System.assert(true, 'flushFeatureParameters with zero counters completed without error'); } // ───────────────────────────────────────────────────────────────────────── // 2. generateSOQL edge cases // ───────────────────────────────────────────────────────────────────────── @isTest static void testGenerateSOQL_blankInputs() { Test.startTest(); String r1 = EmailErrorCSV.generateSOQL(null, new Account(), '{"id":1}'); String r2 = EmailErrorCSV.generateSOQL('[]', new Account(), null); String r3 = EmailErrorCSV.generateSOQL('', new Account(), ''); Test.stopTest(); System.assertEquals(null, r1, 'Blank jsonString should return null'); System.assertEquals(null, r2, 'Blank jsonRequestBody should return null'); System.assertEquals(null, r3, 'Both blank should return null'); } @isTest static void testGenerateSOQL_startsWithOperator() { String conditions = '[{"ShopifyApiName":"first_name","SalesforceFieldApiName":"FirstName",' + '"MatchingOperator":"startsWith","SalesforceObject":"Contact","caseSensitive":false}]'; String shopifyJson = '{"first_name":"John"}'; Test.startTest(); String soql = EmailErrorCSV.generateSOQL(conditions, new Contact(), shopifyJson); Test.stopTest(); System.assertNotEquals(null, soql, 'SOQL should be generated for startsWith'); System.assert(soql.containsIgnoreCase('LIKE \'john%\''), 'SOQL should have LIKE with trailing wildcard'); } @isTest static void testGenerateSOQL_endsWithOperator() { String conditions = '[{"ShopifyApiName":"last_name","SalesforceFieldApiName":"LastName",' + '"MatchingOperator":"endsWith","SalesforceObject":"Contact","caseSensitive":false}]'; String shopifyJson = '{"last_name":"Smith"}'; Test.startTest(); String soql = EmailErrorCSV.generateSOQL(conditions, new Contact(), shopifyJson); Test.stopTest(); System.assertNotEquals(null, soql, 'SOQL should be generated for endsWith'); System.assert(soql.containsIgnoreCase('LIKE \'%smith\''), 'SOQL should have LIKE with leading wildcard'); } @isTest static void testGenerateSOQL_nestedShopifyPath() { // ShopifyApiName uses dot notation: "billing_address.city" String conditions = '[{"ShopifyApiName":"billing_address.city","SalesforceFieldApiName":"HIC_ShopifySync__Billing_City__c",' + '"MatchingOperator":"equals","SalesforceObject":"Order","caseSensitive":true}]'; String shopifyJson = '{"billing_address":{"city":"Toronto"}}'; Test.startTest(); String soql = EmailErrorCSV.generateSOQL(conditions, new Order(), shopifyJson); Test.stopTest(); System.assertNotEquals(null, soql, 'SOQL should be generated for nested path'); System.assert(soql.containsIgnoreCase('Toronto'), 'SOQL should contain the nested value'); } @isTest static void testGenerateSOQL_shopifyValueNull() { // ShopifyApiName points to a key that does not exist in the JSON → value is null → clause skipped String conditions = '[{"ShopifyApiName":"nonexistent_field","SalesforceFieldApiName":"Name",' + '"MatchingOperator":"equals","SalesforceObject":"Account","caseSensitive":false}]'; String shopifyJson = '{"id":99}'; Test.startTest(); // Only the "HIC_ShopifySync__Shopify_Id__c = null" clause is added String soql = EmailErrorCSV.generateSOQL(conditions, new Account(), shopifyJson); Test.stopTest(); // Query is still returned (the null-shopify-id safety clause keeps it valid) System.assertNotEquals(null, soql, 'SOQL should still be returned via the null-id safety clause'); } // ───────────────────────────────────────────────────────────────────────── // 3. getValueFromShopifyJson edge cases // ───────────────────────────────────────────────────────────────────────── @isTest static void testGetValueFromShopifyJson_nullInputs() { Test.startTest(); Object r1 = EmailErrorCSV.getValueFromShopifyJson(null, new Map{'a' => 1}); Object r2 = EmailErrorCSV.getValueFromShopifyJson('key', null); Object r3 = EmailErrorCSV.getValueFromShopifyJson('', new Map{'a' => 1}); Test.stopTest(); System.assertEquals(null, r1); System.assertEquals(null, r2); System.assertEquals(null, r3); } @isTest static void testGetValueFromShopifyJson_deepNesting() { Map json = new Map{ 'a' => new Map{ 'b' => new Map{ 'c' => 'deepValue' } } }; Test.startTest(); Object val = EmailErrorCSV.getValueFromShopifyJson('a.b.c', json); Object miss = EmailErrorCSV.getValueFromShopifyJson('a.b.x', json); Object notMap = EmailErrorCSV.getValueFromShopifyJson('a.b.c.d', json); // c is a String, not a Map Test.stopTest(); System.assertEquals('deepValue', val); System.assertEquals(null, miss); System.assertEquals(null, notMap); } // ───────────────────────────────────────────────────────────────────────── // 4. getFieldValue – dot-notation traversal // ───────────────────────────────────────────────────────────────────────── // ───────────────────────────────────────────────────────────────────────── // 5. Account – company name dedup (Upsert_Account_basis_on_Customer_Company__c) // ───────────────────────────────────────────────────────────────────────── @isTest static void testAccount_companyDedup_matchingShopifyIds() { makeConfig('storeCompany', false, false, true, false, false, false, null); // Existing account – same Shopify ID (no update needed) Account existing = new Account(Name = 'Acme Corp', HIC_ShopifySync__Shopify_Id__c = 'acme-same'); insert existing; List incoming = new List{ new Account(Name = 'Acme Corp', HIC_ShopifySync__Shopify_Id__c = 'acme-same') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"acme-same","company":"Acme Corp"}]', 'Account', incoming, extId('Account'), false, 'storeCompany'); Test.stopTest(); Account result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Account WHERE Id = :existing.Id]; System.assertEquals('acme-same', result.HIC_ShopifySync__Shopify_Id__c, 'Shopify ID should be unchanged when they already match'); } @isTest static void testAccount_companyDedup_differentShopifyIds() { makeConfig('storeCompany2', false, false, true, false, false, false, null); Account existing = new Account(Name = 'Beta Inc', HIC_ShopifySync__Shopify_Id__c = 'beta-old'); insert existing; List incoming = new List{ new Account(Name = 'Beta Inc', HIC_ShopifySync__Shopify_Id__c = 'beta-new') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"beta-new","name":"Beta Inc"}]', 'Account', incoming, extId('Account'), false, 'storeCompany2'); Test.stopTest(); Account result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Account WHERE Id = :existing.Id]; // The existing record should have been updated to the new Shopify ID System.assertEquals('beta-new', result.HIC_ShopifySync__Shopify_Id__c, 'Shopify ID should be updated when company name matches but IDs differ'); } @isTest static void testAccount_updateIdentifiedTrue_alwaysUpserts() { makeConfig('storeUpdId', true, false, false, true, false, false, null); Account existing = new Account(Name = 'UpdateMe', HIC_ShopifySync__Shopify_Id__c = 'uid-old'); insert existing; List incoming = new List{ new Account(Name = 'UpdateMe', HIC_ShopifySync__Shopify_Id__c = 'uid-new') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"uid-new","email":"x@x.com"}]', 'Account', incoming, extId('Account'), false, 'storeUpdId'); Test.stopTest(); // Update_Identified_Account_Records__c = true means the full list is upserted regardless System.assert(true, 'No exception thrown when updateIdentified=true'); } // ───────────────────────────────────────────────────────────────────────── // 6. Contact – email-match path: match found, deletion of ghost record // ───────────────────────────────────────────────────────────────────────── @isTest static void testContact_emailMatch_alreadyIdentified() { makeConfig('storeConId', true, false, false, false, false, false, null); Contact existing = new Contact( LastName = 'Identified', Email = 'identified@test.com', HIC_ShopifySync__Shopify_Id__c = 'same-shopify-id', HIC_ShopifySync__Is_identified__c = true ); insert existing; List incoming = new List{ new Contact(LastName = 'Identified', Email = 'identified@test.com', HIC_ShopifySync__Shopify_Id__c = 'same-shopify-id') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"same-shopify-id","email":"identified@test.com"}]', 'Contact', incoming, extId('Contact'), false, 'storeConId'); Test.stopTest(); // Shopify ID unchanged, already-identified path exercised Contact result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Contact WHERE Id = :existing.Id]; System.assertEquals('same-shopify-id', result.HIC_ShopifySync__Shopify_Id__c); } @isTest static void testContact_updateIdentifiedContact_forcesUpsert() { makeConfig('storeConUpd', true, false, false, false, true, false, null); Contact existing = new Contact( LastName = 'ForceUpd', Email = 'forceupd@test.com', HIC_ShopifySync__Shopify_Id__c = 'fupd-old' ); insert existing; List incoming = new List{ new Contact(LastName = 'ForceUpd', Email = 'forceupd@test.com', HIC_ShopifySync__Shopify_Id__c = 'fupd-new') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"fupd-new","email":"forceupd@test.com"}]', 'Contact', incoming, extId('Contact'), false, 'storeConUpd'); Test.stopTest(); System.assert(true, 'updateIdentifiedContact=true path completed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 7. Lead – all three email-match branches // ───────────────────────────────────────────────────────────────────────── @isTest static void testLead_emailMatch_existingHasNoShopifyId() { // Branch: existing lead has blank Shopify ID → assign incoming ID makeConfig('storeLeadBlank', false, false, false, false, false, false, null); Lead existing = new Lead( LastName = 'NoId', Email = 'noid@test.com', Company = 'Acme', HIC_ShopifySync__Shopify_Id__c = null ); insert existing; // Update config to use email matching HIC_ShopifySync__HIC_Configuration__c cfg = [SELECT Id FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = 'storeLeadBlank']; cfg.HIC_ShopifySync__Upsert_Lead_basis_on_Email__c = true; update cfg; List incoming = new List{ new Lead(LastName = 'NoId', Email = 'noid@test.com', Company = 'Acme', HIC_ShopifySync__Shopify_Id__c = 'lead-new-id') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"lead-new-id","email":"noid@test.com"}]', 'Lead', incoming, extId('Lead'), false, 'storeLeadBlank'); Test.stopTest(); Lead result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Lead WHERE Id = :existing.Id]; System.assertEquals('lead-new-id', result.HIC_ShopifySync__Shopify_Id__c, 'Lead with blank Shopify ID should receive the incoming ID'); } @isTest static void testLead_emailMatch_existingHasDifferentShopifyId() { // Branch: existing lead already has a different Shopify ID → skip update (log a debug) makeConfig('storeLeadDiff', false, false, false, false, false, false, null); Lead existing = new Lead( LastName = 'DiffId', Email = 'diff@test.com', Company = 'Beta', HIC_ShopifySync__Shopify_Id__c = 'lead-existing-id' ); insert existing; HIC_ShopifySync__HIC_Configuration__c cfg = [SELECT Id FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = 'storeLeadDiff']; cfg.HIC_ShopifySync__Upsert_Lead_basis_on_Email__c = true; update cfg; List incoming = new List{ new Lead(LastName = 'DiffId', Email = 'diff@test.com', Company = 'Beta', HIC_ShopifySync__Shopify_Id__c = 'lead-new-id') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"lead-new-id","email":"diff@test.com"}]', 'Lead', incoming, extId('Lead'), false, 'storeLeadDiff'); Test.stopTest(); // Existing Shopify ID should NOT have been overwritten (the skip branch) Lead result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Lead WHERE Id = :existing.Id]; System.assertEquals('lead-existing-id', result.HIC_ShopifySync__Shopify_Id__c, 'Lead with existing Shopify ID should NOT be overwritten'); } @isTest static void testLead_emailMatch_alreadyIdentified() { // Branch: existing lead has same Shopify ID and Is_identified__c = true makeConfig('storeLeadSame', false, false, false, false, false, false, null); Lead existing = new Lead( LastName = 'SameId', Email = 'same@test.com', Company = 'Gamma', HIC_ShopifySync__Shopify_Id__c = 'lead-same-id', HIC_ShopifySync__Is_identified__c = true ); insert existing; HIC_ShopifySync__HIC_Configuration__c cfg = [SELECT Id FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = 'storeLeadSame']; cfg.HIC_ShopifySync__Upsert_Lead_basis_on_Email__c = true; update cfg; List incoming = new List{ new Lead(LastName = 'SameId', Email = 'same@test.com', Company = 'Gamma', HIC_ShopifySync__Shopify_Id__c = 'lead-same-id') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"lead-same-id","email":"same@test.com"}]', 'Lead', incoming, extId('Lead'), false, 'storeLeadSame'); Test.stopTest(); System.assert(true, 'Already-identified Lead path completed without exception'); } @isTest static void testLead_updateIdentified_forcesUpsert() { makeConfig('storeLeadUpd', false, false, false, false, false, true, null); HIC_ShopifySync__HIC_Configuration__c cfg = [SELECT Id FROM HIC_ShopifySync__HIC_Configuration__c WHERE HIC_ShopifySync__Store__c = 'storeLeadUpd']; cfg.HIC_ShopifySync__Upsert_Lead_basis_on_Email__c = true; update cfg; Lead existing = new Lead( LastName = 'UpdLead', Email = 'updlead@test.com', Company = 'Delta', HIC_ShopifySync__Shopify_Id__c = 'leadupd-old' ); insert existing; List incoming = new List{ new Lead(LastName = 'UpdLead', Email = 'updlead@test.com', Company = 'Delta', HIC_ShopifySync__Shopify_Id__c = 'leadupd-new') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"leadupd-new","email":"updlead@test.com"}]', 'Lead', incoming, extId('Lead'), false, 'storeLeadUpd'); Test.stopTest(); System.assert(true, 'Update_Identified_Lead_Records__c = true path completed'); } // ───────────────────────────────────────────────────────────────────────── // 8. nestedRecordsJSONBody – direct call // ───────────────────────────────────────────────────────────────────────── @isTest static void testNestedRecordsJSONBody_populatesMap() { String body = '[{"id":111,"title":"Widget"},{"id":222,"title":"Gadget"}]'; Test.startTest(); EmailErrorCSV.nestedRecordsJSONBody(body); Test.stopTest(); System.assert(EmailErrorCSV.Shopifyididvsbody.containsKey('111'), 'Map should contain key for id 111'); System.assert(EmailErrorCSV.Shopifyididvsbody.containsKey('222'), 'Map should contain key for id 222'); } // ───────────────────────────────────────────────────────────────────────── // 9. SuccessMailSend – success path (no errors today) // ───────────────────────────────────────────────────────────────────────── @isTest static void testSuccessMailSend_successPath() { insert new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(Name = 'success@test.com'); // Insert a mapping so the method doesn't early-return on empty mapping insert new HIC_ShopifySync__Error_Mapping__c( Name = 'Account', HIC_ShopifySync__Shopify_Field__c = 'Name' ); // Make sure there are NO non-webhook Error_Message__c records created today // (no insert here – the list query should return empty → syncResult='success') Test.startTest(); EmailErrorCSV.SuccessMailSend(); Test.stopTest(); System.assert(true, 'SuccessMailSend success branch completed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 10. SuccessMailSend – failure path (errors exist today, >5000 cap branch) // ───────────────────────────────────────────────────────────────────────── @isTest static void testSuccessMailSend_failurePath_underLimit() { insert new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(Name = 'fail@test.com'); insert new HIC_ShopifySync__Error_Mapping__c( Name = 'Account', HIC_ShopifySync__Shopify_Field__c = 'Name' ); // Insert a non-webhook error created today – triggers the failure branch insert new HIC_ShopifySync__Error_Message__c( Name = 'Account', HIC_ShopifySync__Error_id__c = 'fail-test-001', HIC_ShopifySync__Message__c = 'Some error', HIC_ShopifySync__IsWebhook__c = false, HIC_ShopifySync__Shopify_id__c = 'fail-shopify-001' ); Test.startTest(); EmailErrorCSV.SuccessMailSend(); Test.stopTest(); System.assert(true, 'SuccessMailSend failure branch completed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 11. SendErrormail – early returns // ───────────────────────────────────────────────────────────────────────── @isTest static void testSendErrormail_noErrors_earlyReturn() { // No undelivered errors for 'Account' → method should return early Test.startTest(); EmailErrorCSV.SendErrormail('Account'); Test.stopTest(); System.assert(true, 'SendErrormail returned early when no errors exist'); } @isTest static void testSendErrormail_noEmailAddresses_earlyReturn() { // Undelivered error exists but no email address records → early return after email list check insert new HIC_ShopifySync__Error_Message__c( Name = 'Account', HIC_ShopifySync__Error_id__c = 'no-email-addr', HIC_ShopifySync__Message__c = 'test error', HIC_ShopifySync__Delivered__c = false ); // Do NOT insert any HIC_Email_Addresses_to_send_error_CSV__c records Test.startTest(); EmailErrorCSV.SendErrormail('Account'); Test.stopTest(); System.assert(true, 'SendErrormail early-returned when no email addresses configured'); } // ───────────────────────────────────────────────────────────────────────── // 12. Long JSON body chunking in success log (>131072, >262144, >393216) // ───────────────────────────────────────────────────────────────────────── @isTest static void testLargeJsonBody_chunkingPaths() { makeConfig('storeLargeJson', false, false, false, false, false, false, null); // Build a minimal JSON array with a real Shopify ID so we can chunk String shopifyId = 'large-body-id'; // ~140 000 chars → hits the 131072 < len ≤ 262144 branch String pad140k = shopifyId.rightPad(140000, 'x'); String json140k = '[{"id":"' + shopifyId + '","pad":"' + pad140k + '"}]'; // ~270 000 chars → hits the 262144 < len ≤ 393216 branch String pad270k = shopifyId.rightPad(270000, 'x'); String json270k = '[{"id":"' + shopifyId + '","pad":"' + pad270k + '"}]'; // ~400 000 chars → hits the > 393216 branch String pad400k = shopifyId.rightPad(400000, 'x'); String json400k = '[{"id":"' + shopifyId + '","pad":"' + pad400k + '"}]'; List cols = new List{ new HIC_ShopifySync__Collection__c( Name = 'ChunkTest', HIC_ShopifySync__Shopify_Id__c = shopifyId ) }; insert cols; Schema.SObjectField colExtId = extId('HIC_ShopifySync__Collection__c'); Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( json140k, 'HIC_ShopifySync__Collection__c', cols, colExtId, true, 'storeLargeJson'); EmailErrorCSV.makeCsvAndSendInEmail( json270k, 'HIC_ShopifySync__Collection__c', cols, colExtId, true, 'storeLargeJson'); EmailErrorCSV.makeCsvAndSendInEmail( json400k, 'HIC_ShopifySync__Collection__c', cols, colExtId, true, 'storeLargeJson'); Test.stopTest(); System.assert(true, 'All three large-JSON chunking paths executed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 13. DeleteRecords – large JSON body chunking paths // ───────────────────────────────────────────────────────────────────────── @isTest static void testDeleteRecords_largeJsonChunking() { List cols = new List{ new HIC_ShopifySync__Collection__c( Name = 'ToDelete', HIC_ShopifySync__Shopify_Id__c = 'del-chunk-id' ) }; insert cols; String pad270k = 'del-chunk-id'.rightPad(270000, 'y'); String json270k = '[{"id":"del-chunk-id","pad":"' + pad270k + '"}]'; List sObjs = (List) cols; List delResults = Database.delete(cols, false); Test.startTest(); EmailErrorCSV.DeleteRecords( 'HIC_ShopifySync__Collection__c', json270k, delResults, sObjs, 'storeDelChunk'); Test.stopTest(); System.assert(true, 'DeleteRecords large-JSON chunking path completed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 14. makeCsvAndSendInEmail – deprecated 5-arg overload (no-op) // ───────────────────────────────────────────────────────────────────────── @isTest static void testDeprecated5ArgOverload() { List accs = new List{ new Account(Name = 'Deprecated', HIC_ShopifySync__Shopify_Id__c = 'dep-001') }; insert accs; Test.startTest(); // Should compile and execute without error (method body is empty) EmailErrorCSV.makeCsvAndSendInEmail( '[{"id":"dep-001"}]', 'Account', accs, extId('Account'), true); Test.stopTest(); System.assert(true, 'Deprecated 5-arg overload executed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 15. DeleteRecords – deprecated 4-arg overload (no-op) // ───────────────────────────────────────────────────────────────────────── @isTest static void testDeprecated4ArgDeleteRecords() { List cols = new List{ new HIC_ShopifySync__Collection__c( Name = 'DepDel', HIC_ShopifySync__Shopify_Id__c = 'depdel-001' ) }; insert cols; List delResults = Database.delete(cols, false); Test.startTest(); EmailErrorCSV.DeleteRecords( 'HIC_ShopifySync__Collection__c', '[{"id":"depdel-001"}]', delResults, (List) cols); Test.stopTest(); System.assert(true, 'Deprecated 4-arg DeleteRecords overload executed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 16. Error message Shopify ID cleanup: ends with 'T' and 'F' branches // ───────────────────────────────────────────────────────────────────────── @isTest static void testSendErrormail_shopifyIdSuffix_TandF() { insert new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(Name = 'suffix@test.com'); insert new HIC_ShopifySync__Error_Mapping__c( Name = 'Account', HIC_ShopifySync__Shopify_Field__c = 'Name' ); // ID ending with 'T' (webhook suffix) insert new HIC_ShopifySync__Error_Message__c( Name = 'Account', HIC_ShopifySync__Error_id__c = 'suffix-T-err', HIC_ShopifySync__Message__c = 'T-suffix error', HIC_ShopifySync__Delivered__c = false, HIC_ShopifySync__Shopify_id__c = '12345T' ); // ID ending with 'F' (batch suffix) insert new HIC_ShopifySync__Error_Message__c( Name = 'Account', HIC_ShopifySync__Error_id__c = 'suffix-F-err', HIC_ShopifySync__Message__c = 'F-suffix error', HIC_ShopifySync__Delivered__c = false, HIC_ShopifySync__Shopify_id__c = '67890F' ); Test.startTest(); EmailErrorCSV.SendErrormail('Account'); Test.stopTest(); System.assert(true, 'SendErrormail T/F suffix cleanup paths executed without exception'); } // ───────────────────────────────────────────────────────────────────────── // 17. Product2 – equals rule, case-insensitive (caseSensitive=false) // ───────────────────────────────────────────────────────────────────────── @isTest static void testProduct2_equalsRule_caseInsensitive() { insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'CfgProd2CI', HIC_ShopifySync__Store__c = 'storeProd2CI', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"title","SalesforceFieldApiName":"Name","MatchingOperator":"equals","SalesforceObject":"Product2","caseSensitive":false}]' ); Product2 existing = new Product2( Name = 'Widget Pro', HIC_ShopifySync__Shopify_Id__c = 'wp-old' ); insert existing; List incoming = new List{ new Product2(Name = 'widget pro', HIC_ShopifySync__Shopify_Id__c = 'wp-new') }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( '{"title":"widget pro"}', 'Product2', incoming, extId('Product2'), false, 'storeProd2CI'); Test.stopTest(); Product2 result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Product2 WHERE Id = :existing.Id]; System.assertEquals('wp-old', result.HIC_ShopifySync__Shopify_Id__c, 'Case-insensitive match should update the existing record\'s Shopify ID'); } // ───────────────────────────────────────────────────────────────────────── // 18. Order – dynamic dedup, existing map not empty → deduped upsert path // ───────────────────────────────────────────────────────────────────────── @isTest static void testOrder_dynamicDedup_existingMapNotEmpty() { insert new HIC_ShopifySync__HIC_Configuration__c( Name = 'CfgOrderDyn', HIC_ShopifySync__Store__c = 'storeOrderDyn', HIC_ShopifySync__Dynamic_prevent_duplicate__c = '[{"ShopifyApiName":"billing_address.name","SalesforceFieldApiName":"HIC_ShopifySync__Billing_Customer_Name__c","MatchingOperator":"equals","SalesforceObject":"Order","caseSensitive":false}]' ); Account acc = new Account(Name = 'OrderDynAcc'); insert acc; Order existing = new Order( Name = 'DynOrder', AccountId = acc.Id, Status = 'Draft', EffectiveDate = Date.today(), HIC_ShopifySync__Billing_Customer_Name__c = 'Same Name', HIC_ShopifySync__Shopify_Id__c = 'dynord-old' ); insert existing; String shopifyJson = '{"billing_address":{"name":"Same Name"}}'; List incoming = new List{ new Order( Name = 'DynOrder', AccountId = acc.Id, Status = 'Draft', EffectiveDate = Date.today(), HIC_ShopifySync__Billing_Customer_Name__c = 'Same Name', HIC_ShopifySync__Shopify_Id__c = 'dynord-new' ) }; Test.startTest(); EmailErrorCSV.makeCsvAndSendInEmail( shopifyJson, 'Order', incoming, extId('Order'), false, 'storeOrderDyn'); Test.stopTest(); Order result = [SELECT HIC_ShopifySync__Shopify_Id__c FROM Order WHERE Id = :existing.Id]; } }