Current Path :
/
home
/
zrcdevco
/
public_html
/
zrc-email-program
/
Or
Select Your Path :
Upload File :
New :
File
Dir
/home/zrcdevco/public_html/zrc-email-program/cmd-netsuite-email.0.5.php
<?php // TEST VERSION ONLY 6/18/2022 // VERSION TO CHECK FOR LEED CERTIFICATION PROJECTS // copywrite - Trionia, Inc. // author - James H. Murphy // date - 10:50 AM 4/20/2019 // update - 12/15/2014 // This update is to utilize the new Reeds Insight data structure and includes some feature updates. // These include selecting a date range and automatic download of the files from the Reed Server // Add a date range picker // - Final update step move FTP processing into a single loop // update - 4/23/2015 // Updated the query to include contacts associated with the project. // update - 1/19/2016 // Include timezone declaration to meet new requirements for date/time functions // Complete re-write 9/2/2019 // Read in the CMD project and company contacts into Netsuite // Trigger a Netsuite email based on the company project role // Update to run automatically // Update - 6/18/2022 // Include a search for LEED Certification in project Detail. // add error checking for null values - in Project Role and other variables. // Update - 10/4/2022 // Add CMD information - CMD ID, CMD Company ID To store in the database and then in Hubspot. // // set_time_limit(12000); // code to prevent the MYSQL socket from timing out (fixes this error - "MySQL server has gone away") ini_set('mysql.connect_timeout', 300); ini_set('default_socket_timeout', 300); error_reporting(E_ALL); date_default_timezone_set('America/New_York'); include('zrc_ftp_files.php'); // 6/18/2022 // replace netsuite passport services with NetSuiteService.php require_once '../PHPToolkit/NetSuiteService.php'; //require_once 'netsuite-passport-service.php'; require_once 'ns_api_php_functions.php'; // set of php wrappers for NS API calls // Connect to Database $servername = "localhost"; $username = "trioniac_zrc_cmd"; $password = "vfw8BVB-yjm1xhv9afe"; $dbname = "trioniac_zrc_cmd"; $db_date = date("Y-m-d H:i:s"); // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Function to download the FTP files from the CMD Server (CMD was formely Reed) function download_reed_files_xml($newStart, $newEnd) { // Connect to FTP $conn_id = ftp_connect('ftp.cmdintegration.com'); // login with username and password $login_result = ftp_login($conn_id, 'zrcworldwide', 'ZrCW0rlD!'); ftp_pasv($conn_id, TRUE); echo "Login Results: $login_result\n"; // We are downloading the last weeks worth of files// Changing the days will change the total number of files $actualStart = date("Y-m-d",strtotime('-7 days')); $processDate = $actualStart; // Download ZIP format files using FTP - one per day while ($processDate <= $newEnd) { echo 'Process Date: '.$processDate.'</br>'; echo "<br />Start\n"; echo date("l jS \of F Y h:i:s A") . "<br>"; // Reed Insight files contain a date stamp so new code will be required to // add the date stamp. $file_date = str_replace('-','',$processDate); $zipfile_name = "1.3_DL_ZRCWorldwide_XML_" . $file_date . ".zip"; $local_file = $zipfile_name; $server_file = '/zrcworldwide_insight/'.$zipfile_name; // try to download $server_file and save to $local_file if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) { echo "Successfully written to $local_file\n"; } else { echo "There was a problem writing to $local_file\n"; } echo date("l jS \of F Y h:i:s A") . "<br>"; // increment process date $date = new DateTime($processDate); $date->add(new DateInterval('P1D')); $processDate = $date->format('Y-m-d'); echo date("l jS \of F Y h:i:s A") . "<br>"; } } // Set dates to download from FTP $newEnd = date("Y-m-d h:i:s"); $newStart = date("Y-m-d h:i:s",strtotime('-8 days')); echo 'New Start'.$newStart .'<br />'; echo 'New End'.$newEnd .'<br />'; // Download Files from CMD FTP server download_reed_files_xml($newStart, $newEnd); $firstPass = TRUE; $actualStart = date("Y-m-d",strtotime('-7 days')); $processDate = $actualStart; while ($processDate <= $newEnd) { echo 'Process Date: '.$processDate.'</br>'; echo "<br />Start\n"; echo date("l jS \of F Y h:i:s A") . "<br>"; // Unzip the results from CMD Connect // Code taken from the website http://www.timlinden.com/blog/website-development/unzip-files-with-php/ // CMD Insight files contain a date stamp for each file. $file_date = str_replace('-','',$processDate); $zipfile_name = "1.3_DL_ZRCWorldwide_XML_" . $file_date . ".zip"; $file = "1.3_DL_ZRCWorldwide_XML_" . $file_date . ".xml"; echo date("l jS \of F Y h:i:s A") . "<br>"; $zip = zip_open( $zipfile_name ); $filesToProcess = array($file); if (is_resource($zip)) { while ($zip_entry = zip_read($zip)) { $fp = fopen(zip_entry_name($zip_entry), "w"); if (zip_entry_open($zip, $zip_entry, "r")) { if (in_array(zip_entry_name($zip_entry), $filesToProcess) ) { $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); fwrite($fp,"$buf"); // echo "<br />".zip_entry_name($zip_entry); zip_entry_close($zip_entry); fclose($fp); } } } zip_close($zip); } echo "<br />files unzipped"; echo date("l jS \of F Y h:i:s A") . "<br>"; //Pull the Do Not Fax list // Not used this will be maintained on the Netsuite server // $exclude_numbers[] = ''; // Process each file foreach ($filesToProcess as $file_name) { if (file_exists($file_name)) { $xml = simplexml_load_file($file_name); $a=array("0"=>"Roles:"); // Step through each project - check for LEED Certification foreach($xml->Project as $project1){ $projectname = (string) $project1->attributes()->Title; // check for a LEED Certification Project echo "<h1>Projectname : ".$projectname."</h1>"; foreach($project1->Details->children() as $detail) { if ($detail->attributes()->DetailType == "Notes") { // echo $detail."<br>"; if(strpos((string) $detail, "LEED Certification") !== false){ $projectLeed = "1"; // true in NS echo "Leed Certification!"; } else { $projectLeed = "2"; // false in NS } } } // For each Project step through each company and identify Contact(s) foreach($project1->Companies->children() as $company){ // Check for project roles and contacts - if null skipe this loop if (!is_null($company->ParticipantRoles->ParticipantRole)) { // The Attributes of the $company have to be cast as strings $participantRoles = (string) $company->ParticipantRoles->ParticipantRole['RoleClassification']; array_push($a,"$participantRoles"); // Used to track all participant types $primary = (string) $company->ParticipantRoles->ParticipantRole['ContactName']; $companyName = (string) $company['Name']; $companyCmdId = (string) $company['CompanyID']; $companyCmdUrl = (string) $company['URL']; echo "<h2>Company Name: </h2>"; echo "<b>".$companyName."</b>"; if (preg_match("/(^Architect$|^Structural Engineer$|^General Contractor$|^Structural Steel$)/i",$participantRoles)) { echo "<br />A / E Loop"; // This is one of two main loops - this one to find the primary contact that has an email $contact_email_found = false; for( $i = 0; is_countable($company->Contacts->Contact) && $i < count($company->Contacts->Contact) && !$contact_email_found; $i++ ){ $contact = $company->Contacts->Contact[$i]; if ($primary == $contact['Name']) { echo "<br />Found Contact!!!<br />"; // two cases - main company email if( !empty( $company->Email )){ $contact_email_found = true; echo "<br />Contact to Update - company email<br />"; $email = (array)$company->Email; $email = $email[0]; } elseif( !empty( $contact->Email )){ $contact_email_found = true; echo "<br />Contact to Update - contact email<br />"; $email = (array)$contact->Email; $email = $email[0]; } } } // Second loop to find the address $address_found = false; for( $i = 0; $i < count($company->Addresses->Address) && !$address_found; $i++ ){ $address = $company->Addresses->Address[$i]; if ($address['AddressType'] == 'Street Address') { $address_found = true; echo "<br />Found Street Address!!!<br />"; } } if (!empty ($contact->PhoneNumber) ){ $phonenumber = (Array)$contact->PhoneNumber; $phonenumber = $phonenumber[0]; // format to (###) ###-#### // https://stackoverflow.com/questions/4708248/formatting-phone-numbers-in-php $phonenumber = preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $phonenumber); } if ($contact_email_found && $address_found) { // Update Company output with emails and addresses $name = explode( ' ', $contact['Name']); $first = array_shift($name); $last = array_pop($name); $name_middle = trim(implode(' ', $name)); echo '<br />Email: ' . $email; echo '<br />First: ' . $first; echo '<br />Last: ' . $last; if ($address->CountryRegion == 'UNITED STATES') { $country = '_unitedStates'; } $new_leads[] = array( 'email' => $email, 'phone' => $phonenumber, 'entityStatus' => 'subscribed', 'firstName' => $first, 'middleName' => $name_middle, 'lastName' => $last, 'custentityprojectname' => $projectname, 'companyName' => $companyName, 'custentityprojectrole' => $participantRoles, 'customlist145' => $projectLeed, 'addr1' => (string)$address->AddressLine1, 'addr2' => (string)$address->AddressLine2, 'city' => (string)$address->City, 'state' => (string)$address->StateProvince, 'zip' => (string)$address->ZipPostalCode, 'country' => $country, 'cmd_company_id' => $companyCmdId, 'cmd_url' => $companyCmdUrl, 'lifecyclestage' => "Marketing Qualified Lead", 'cmd_id' => $contact->ContactID, ); echo "<br />Company Loop - #Leads: ".count($new_leads); } } } // End of Company Loop } // End of Participant Role and Name If Statement } // End of Project Loop $a = array_unique($a); // print_r($a); //print_r( $architects ); } else { exit('Failed to open test.xml.'. $file_name); } $file = fopen($file_name,"r"); $table_name = substr($file_name,0,strpos($file_name,'.csv')); // Read in the header line $line = fgets($file); // Remove all double quotes (") from the header line $line = str_replace('"','',$line); //print_r($line); $column_names = explode(',',$line); while (!feof($file)) { $data_line = fgets($file); //print_r( $data_line); // Enter in blank strings to insert in the DB $data_line = str_replace(', ,',', "",',$data_line); $data_line = str_replace(', ,',',"",',$data_line); // Check for comma as the last character in the string. If so add an empty string. // last comma is 4 characters from the end due to cr, lf and space characters. if (strrpos($data_line,',',0) == (strlen($data_line)-4)) $data_line .= '""'; } fclose($file); echo "<br />$file_name loaded"; echo date("l jS \of F Y h:i:s A") . "<br>"; } echo "<br />all data loaded"; echo date("l jS \of F Y h:i:s A") . "<br>"; echo date("l jS \of F Y h:i:s A") . "<br>"; $firstPass = False; // increment process date $date = new DateTime($processDate); $date->add(new DateInterval('P1D')); $processDate = $date->format('Y-m-d'); echo date("l jS \of F Y h:i:s A") . "<br>"; } // close the FTP connection echo date("l jS \of F Y h:i:s A") . "<br>"; /* Code to add each lead to Netsuite This code will map the CMD fields to the Netsuite fields and then trigger an email to the new leads */ $project_role = array("Architect"=>"1", "Structural Engineer"=>"2", "General Contractor"=>"3", "Structural Steel"=>"4"); echo "UPLOAD AREA"; // Are the SOAP calls asynchronous!? this is a test to make sure // https://medium.com/@mouneyrac/php-soap-does-asynchronous-calls-sometimes-d09fd991f7a3 // This did not work //$options = array('features' => SOAP_WAIT_ONE_WAY_CALLS); $service = new NetSuiteService(); // Second loop to find the address /* Changed 9/11 to the complete set. RIGHT NOW JUST UPDATING A SINGLE LEAD WHILE TESTING */ echo "Count of new Leads: ".count($new_leads); $address_found = false; // New Lead Loop - adds new leads to Netsuite for( $i = 0; $i < count($new_leads); $i++ ) { $new_lead = $new_leads[$i]; // check if lead is in the Netsuite database // Only add new leads if (!(ns_search_contact_email($service, $new_lead['email']))) { echo "New Lead ".$i."</br>"; echo " Email = ".$new_lead['email']."</br>"; // Standard Add Customer $customer = new Customer(); $customer->firstName = $new_lead['firstName']; $customer->middleName = $new_lead['middleName']; $customer->lastName = $new_lead['lastName']; $customer->companyName = $new_lead['companyName']; $customer->phone = $new_lead['phone']; $customer->email = $new_lead['email']; // Set so this customer record is seen as a Lead based on this Status $customer->entityStatus = new ListOrRecordRef; $customer->entityStatus->name = 'LEAD-Unqualified'; $customer->entityStatus->internalId = '6'; // Update Address Fields $address = new Address(); $address->addr1 = $new_lead['addr1']; $address->addr2 = $new_lead['addr2']; $address->city = $new_lead['city']; $address->zip = $new_lead['zip']; $address->state = $new_lead['state']; $address->country = $new_lead['country']; $address_book = new CustomerAddressBook(); $address_book->defaultShipping = true; $address_book->defaultBilling = true; $address_book->isResidential = false; $address_book->addressbookAddress = $address; $address_book_list = new CustomerAddressbookList(); $address_book_list->addressbook = $address_book; $address_book_list->replaceAll = false; $customer->addressbookList = $address_book_list; //Updating Project Name $projectNameField = new StringCustomFieldRef(); $projectNameField->scriptId = 'custentityprojectname'; $projectNameField->value = $new_lead['custentityprojectname']; $customFieldList = new customFieldList(); $customFieldList->customField = array($projectNameField); //Updating Project Role $projectRoleField = new SelectCustomFieldRef(); $projectRoleField->value = new ListOrRecordRef; $projectRoleField->value->typeId = '63'; $projectRoleField->value->internalId = $project_role[$new_lead['custentityprojectrole']]; $projectRoleField->scriptId = 'custentityprojectrole'; array_push($customFieldList->customField, $projectRoleField); //Updating Project LEED $projectLeedField = new SelectCustomFieldRef(); $projectLeedField->value = new ListOrRecordRef; $projectLeedField->value->typeId = '145'; $projectLeedField->value->internalId = $new_lead['customlist145']; $projectLeedField->scriptId = 'customlist145'; array_push($customFieldList->customField, $projectLeedField); $customer->customFieldList = $customFieldList; $request = new AddRequest(); $request->record = $customer; print_r($request); $addResponse = $service->add($request); // Check DB connection - refactor by taking out of this loop /* check if server is alive */ if ($conn->ping()) { printf ("Our connection is ok!\n"); } else { printf ("Error: %s\n", $conn->error); // reconnect db $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } } // Store data into the database for reporting $sql = "INSERT INTO lead_company (company, name, email, project_role, project, leed_project, cmd_company_id, cmd_id, lifecyclestage, cmd_url, date_added) VALUES ('". $new_lead['companyName']."','". $new_lead['lastName']."','". $new_lead['email']."','". $new_lead['custentityprojectrole']."','". $new_lead['custentityprojectname']."','". $new_lead['customlist145']."','". $new_lead['cmd_company_id']."','". $new_lead['cmd_id']."','". $new_lead['lifecyclestage']."','". $new_lead['cmd_url']."','". $db_date."')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } sleep( 10 ); // sleep in seconds to wait for SOAP Request at Netsuite. if (!$addResponse->writeResponse->status->isSuccess) { echo "ADD ERROR"; print_r($addResponse); } else { echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId; } } else { echo "Duplicate Lead ".$i."</br>"; echo " Email = ".$new_lead['email']."</br>"; } } $conn->close(); // End of New Lead Loop ?>