Current Path :
/
home
/
zrcdevco
/
public_html
/
medrio
/
Or
Select Your Path :
Upload File :
New :
File
Dir
/home/zrcdevco/public_html/medrio/excelupload_newfields.php
<?php // Changes due to field updates // change array lookup indices // new fields - Company Name, // Clinical Leader - Company Type (new field - Matt will provide) : cl_company_type__c // Clinical Leader - Content Titles Engaged With : clinical_leader___content_titles_engaged_with // Clinical Leader - Content Topics Engaged With : clinical_leader___content_topics_engaged_with // Clinical Leader - Number of Engagements : clinicalleaderdownloads__c // Clinical Leader - Most Recent Engagement Date (use Activity Date - date picker field - MM/DD/YYYY) : clinical_leader_engagements__most_recent_update_ // Company Name (use Reader Company) // SFDC State/Province (along with state) - sfdc_state // SFDC Country (along with Country) - sfdc_country // Add a space after commas on titles and topics // Production Medrio Token - // pat-na1-4d0456ec-772d-4a2a-b16b-3f9a5fe3b749 // Testing Token // pat-na1-e33479fd-da09-4d3f-b7ba-883334bb0751 // // write to a file instead of to the screen // // 2/16/2023 // Some users in production are not getting the Clinical Leader // Engagement date updates. // Matt requested new lists for each file upload. // need to add a search for each possible list name. // Lists will be named DATE+static_list+LISTNUM // LISTNUM will start at 01 and go up by 1 per new list // 01, 02, 03 ... // // 4/17/2023 Remove sfdc_state from upload - this fiedl has been deleted from // the HubSpot database. // ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(~0); set_time_limit(0); date_default_timezone_set("America/New_York"); include 'hubspot_functions.php'; $processDate = date("Y-m-d",strtotime('today')); $listDate = str_replace('-','',$processDate); $outFileName=$listDate."outputfile.txt"; $outFile = fopen($outFileName, "w"); echo("<h1>Medrio Clinical Leader => HubSpot</h1>"); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if file already exists if (file_exists($target_file)) { exit("Sorry, file ".$target_file." has already been processed.</br>"); $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large.</br>"; $uploadOk = 0; } // Allow Excel file formats if($imageFileType != "xls" && $imageFileType != "xlsx" ) { echo "Sorry, only Excel files are allowed.</br>"; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded.</br>"; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "<p>The file <b>". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). "</b> has been uploaded.</p>"; } else { echo "<p>Sorry, there was an error uploading your file.</p>"; } } // Test program to read in a test excel sheet and then upload to the test HubSpot Account /* data to upload to HS: * - first name (6), last name (7), email (10), phone number (11), company name (3 - Reader Company), street address , content_title(unique), content_topic (unique) */ require 'vendor/autoload.php'; // exclude companies - includes Medrio and Competitors $excludeCompanies = array("Medrio","Trionia"); $contactList = array(); use PhpOffice\PhpSpreadsheet\Spreadsheet; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load($target_file); $sheetData = $spreadsheet->getActiveSheet()->toArray(); $lineCount=0; $userUpdateCount=0; $userAddedCount=0; unset($sheetData[0]); // removes the header row (first row) foreach ($sheetData as $t) { // process element here; // access column by index // create a new array removing duplicates (using email address) and excluded companies $key = $t[8]; // Email is the unique key for all users if (!is_null($key)) { // check for blank lines if (!in_array($t[2],$excludeCompanies)) { if (isset($contactList[$key])) { // duplicate contact // summarize content_titles $contactList[$key]["content_title"] .= ", ".$t[12]; $tempContactTitle = preg_split('/, */',$contactList[$key]["content_title"]); // remove duplicates $contactList[$key]["content_title"] = implode(", ",array_unique($tempContactTitle)); // summarize content_topics $contactList[$key]["content_topic"] .= ", ".$t[16]; $tempContactTopic = preg_split('/, */',$contactList[$key]["content_topic"]); // remove duplicates $contactList[$key]["content_title"] = implode(", ",array_unique($tempContactTitle)); // Increment Engagement using new column names // keep original column name as a check $contactList[$key]["number_of_engagements"]++; $contactList[$key]["clinicalleaderdownloads__c"]++; } else { // new contact $contactEmails[]=$key; // Clean up Country field and only keep US and CA States $country = ucwords(strtolower($t[11])); $city = ucwords(strtolower($t[9])); if (($country == "United States")||($country == "Canada")) { $state = ucwords(strtolower($t[10])); } else { $state=""; } if ($country == "Korea, Republic Of") { $country = "South Korea"; } // Reformat activity_date to HubSpot expected format // YYYY-MM-DD $activity_date_array = explode("/",$t[0]); $activity_date = $activity_date_array[2]."-".substr("00{$activity_date_array[0]}", -2)."-".substr("00{$activity_date_array[1]}", -2); // add spaces after ',' $tempContactTopic_array = preg_split('/, */',$t[16]); $tempContactTopic = implode(", ",array_unique($tempContactTopic_array)); // Update the Contact List with cleaned up data $contactList[$key] = array("activity_date"=>$activity_date,"firstname"=>$t[5],"lastname"=>$t[6],"company"=>$t[2],"company_type"=>$t[4],"jobtitle"=>$t[7],"email"=>$t[8],"phone"=>"","content_title"=>$t[12],"content_topic"=>$tempContactTopic,"city"=>$city,"state"=>$state,"country"=>$country,"number_of_engagements"=>1, "clinicalleaderdownloads__c"=>1); } } $lineCount++; } } //var_dump($contactList); // Update HubSpot Contacts use HubSpot\Factory; use HubSpot\Client\Crm\Contacts\ApiException; use HubSpot\Client\Crm\Contacts\Model\Filter; use HubSpot\Client\Crm\Contacts\Model\FilterGroup; use HubSpot\Client\Crm\Contacts\Model\PublicObjectSearchRequest; use HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput; /************** * * Production * We need both the new API client created as well as * the Authentication header for using the older API. * **************/ $client = Factory::createWithAccessToken("pat-na1-cd2727ee-95c4-4477-9878-713b7294291a"); // Production Authentication Header $authorization = "Authorization: Bearer pat-na1-cd2727ee-95c4-4477-9878-713b7294291a"; /************** * * Test Token * We need both the new API client created as well as * the Authentication header for using the older API. * **************/ // test client //$client = Factory::createWithAccessToken("pat-na1-e33479fd-da09-4d3f-b7ba-883334bb0751"); // Test Authentication Header //$authorization = "Authorization: Bearer pat-na1-e33479fd-da09-4d3f-b7ba-883334bb0751"; // Setup Filters to check if contact in database? $filter1 = new Filter([ 'value' => '', 'property_name' => 'email', 'operator' => 'EQ' ]); $filterGroup1 = new FilterGroup([ 'filters' => [$filter1] ]); $publicObjectSearchRequest = new PublicObjectSearchRequest([ 'filter_groups' => [$filterGroup1], 'properties' => [ 'clinical_leader___content_titles_engaged_with', 'clinical_leader___content_topics_engaged_with', 'clinicalleaderdownloads__c'] ]); $contactInput = new \HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput(); foreach ($contactList as $c) { $contactInput->setProperties([ "company" => $c["company"], "cl_company_type__c" => $c["company_type"], "firstname" => $c["firstname"], "lastname" => $c["lastname"], "jobtitle" => $c["jobtitle"], "phone" => $c["phone"], "email" => $c["email"], "city" => $c["city"], "state" => $c["state"], // clear if country no US OR CA // sfdc_state removed from the HubSpot database // "sfdc_state" => $c["state"], "country" => $c["country"], // set to proper case "sfdc_country" => $c["country"], "clinical_leader___content_titles_engaged_with" => $c["content_title"], // check for dups on update "clinical_leader___content_topics_engaged_with" => $c["content_topic"], // check for dups on update "clinicalleaderdownloads__c" => $c["clinicalleaderdownloads__c"], "clinical_leader_engagements__most_recent_update_" => $c["activity_date"], ]); // Check for client in HubSpot - searching by email address // If user is new Create the user otherwise Update the user if (!is_null($c["email"])) { $filter1['value']= $c["email"]; try { // echo "Search = </br>"; // var_dump($filter1['value']); $apiResponse = $client->crm()->contacts()->searchApi()->doSearch($publicObjectSearchRequest); // Contact not in HubSpot database if (empty($apiResponse["results"])) { // Create a new user $contact = $client->crm()->contacts()->basicApi()->create($contactInput); fwrite($outFile,"Added - ".$c["email"]." to HubSpot\n"); $userAddedCount++; //echo "Added - ".$c["email"]." to HubSpot <br>"; } else { // var_dump($apiResponse["results"]); // Contact is in HubSpot - update using Contact ID $contactId = $apiResponse["results"][0]["id"]; // Update existing user $c["content_title"] .= ", ".$apiResponse["results"][0]["properties"]["clinical_leader___content_titles_engaged_with"]; $tempContactTitle = preg_split('/, */',$c["content_title"]); $c["content_title"] = implode(", ",array_unique($tempContactTitle)); $c["content_topic"] .= ", ".$apiResponse["results"][0]["properties"]["clinical_leader___content_topics_engaged_with"]; $tempContactTopic = preg_split('/, */',$c["content_topic"]); $c["content_topic"] = implode(", ",array_unique($tempContactTopic)); $contactInput->setProperties([ "company" => $c["company"], "cl_company_type__c" => $c["company_type"], "firstname" => $c["firstname"], "lastname" => $c["lastname"], "jobtitle" => $c["jobtitle"], "phone" => $c["phone"], "city" => $c["city"], "state" => $c["state"], // clear if country no US OR CA // sfdc_state removed from HubSpot database // "sfdc_state" => $c["state"], "country" => $c["country"], // set to proper case "sfdc_country" => $c["country"], "clinical_leader___content_titles_engaged_with" => $c["content_title"], // check for dups on update "clinical_leader___content_topics_engaged_with" => $c["content_topic"], // check for dups on update "clinicalleaderdownloads__c" => $c["clinicalleaderdownloads__c"], "clinical_leader_engagements__most_recent_update_" => $c["activity_date"], ]); // now with Client ID we can update fwrite($outFile,"Updated - ".$c["email"]." to HubSpot\n"); $userUpdateCount++; //echo "Updated - ".$c["email"]." to HubSpot <br>"; try { // var_dump($contactInput); $apiResponse = $client->crm()->contacts()->basicApi()->update($contactId, $contactInput); } catch (ApiException $e) { echo "Exception when calling basic_api->update: ", $e->getMessage(); } } } catch (ApiException $e) { echo "Exception when calling search_api->do_search: ", $e->getMessage(); } } } // Create a List and add the Contacts from this Upload to the list echo "<h3>Contact List</h3>"; // Setup varaibles for static list name $listDate = str_replace('-','',$processDate); $listNum = 0; // Retrieve all the lists in HubSpot $lists=array(); getHubSpotLists($lists,$authorization); $listExists=false; // search the lists until we find a name that has not been // created yet. do { $listExists = false; // look for next list $listLength = count($lists); $listNum++; // check next possible list name $listName = $listDate.'-upload-staticlist'.sprintf('%1$02d',$listNum); for($i = 0; $i < $listLength; $i++){ if ($lists[$i]["name"] == $listName) { $listExists=true; // list name found } } } while ($listExists == true); // Create list with the new list name //fwrite($outFile,"List Name is = ".$listName." exists list\n"); $listId=createHubSpotList($listName,$authorization); echo "List Name is = ".$listName."- new list</br>"; echo "List ID is = ".$listId."</br>"; // Add all users to list with email address $result=addEmailsToHubSpotList($contactEmails,$listId,$authorization); //var_dump($result); fwrite($outFile," ----------- Summary ----------- \n"); fwrite($outFile," Process Date = ".$processDate."\n"); fwrite($outFile," File Uploaded = '".$target_file."'\n"); fwrite($outFile,"List Name is = ".$listName."\n"); fwrite($outFile,"List ID is = ".$listId."\n"); fwrite($outFile,$lineCount." Lines Processed\n"); fwrite($outFile,$userUpdateCount." Users Updated\n"); fwrite($outFile,$userAddedCount." New Users Added\n"); fclose($outFile); echo "<p>View Output file here - <a href=https://www.trionia.com/medrio/".$outFileName.">file upload results</a></p>"; echo "<p>".$lineCount." Lines Processed</p>"; echo "<p>".$userUpdateCount." Users Updated</p>"; echo "<p>".$userAddedCount." New Users Added</p>";