/**
  * Export guests for a website.
  *
  * @param $website
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function exportGuestPerWebsite($website)
 {
     $guests = $this->contactFactory->create()->getGuests($website);
     //found some guests
     if ($guests->getSize()) {
         $guestFilename = strtolower($website->getCode() . '_guest_' . date('d_m_Y_Hi') . '.csv');
         $this->helper->log('Guest file: ' . $guestFilename);
         $storeName = $this->helper->getMappedStoreName($website);
         $this->file->outputCSV($this->file->getFilePath($guestFilename), ['Email', 'emailType', $storeName]);
         foreach ($guests as $guest) {
             $email = $guest->getEmail();
             try {
                 //@codingStandardsIgnoreStart
                 $guest->setEmailImported(\Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_IMPORTED);
                 $guest->getResource()->save($guest);
                 //@codingStandardsIgnoreEnd
                 $storeName = $website->getName();
                 // save data for guests
                 $this->file->outputCSV($this->file->getFilePath($guestFilename), [$email, 'Html', $storeName]);
                 ++$this->countGuests;
             } catch (\Exception $e) {
                 throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
             }
         }
         if ($this->countGuests) {
             //register in queue with importer
             $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_GUEST, '', \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website->getId(), $guestFilename);
         }
     }
 }
 /**
  * Bulk creates, or bulk updates, contacts. Import format can either be CSV or Excel.
  * Must include one column called "Email". Any other columns will attempt to map to your custom data fields.
  * The ID of returned object can be used to query import progress.
  *
  * @param string|int $filename
  * @param string|int $addressBookId
  *
  * @return mixed
  */
 public function postAddressBookContactsImport($filename, $addressBookId)
 {
     $url = $this->apiEndpoint . "/v2/address-books/{$addressBookId}/contacts/import";
     //@codingStandardsIgnoreStart
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
     curl_setopt($ch, CURLOPT_USERPWD, $this->getApiUsername() . ':' . $this->getApiPassword());
     //case the deprication of @filename for uploading
     if (function_exists('curl_file_create')) {
         $args['file'] = curl_file_create($this->fileHelper->getFilePath($filename), 'text/csv');
         curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
     } else {
         //standart use of curl file
         curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => '@' . $this->fileHelper->getFilePath($filename)]);
     }
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
     // send contacts to address book
     $result = curl_exec($ch);
     $result = json_decode($result);
     //@codingStandardsIgnoreEnd
     if (isset($result->message)) {
         $message = 'POST ADDRESS BOOK ' . $addressBookId . ', CONTACT IMPORT : ' . ' filename ' . $filename . ' Username ' . $this->getApiUsername() . $result->message;
         $this->helper->debug('postAddressBookContactsImport', [$message]);
     }
     return $result;
 }
 /**
  * Export subscribers per website.
  *
  * @param $website
  *
  * @return int
  *
  * @throws LocalizedException
  */
 public function exportSubscribersPerWebsite($website)
 {
     $updated = 0;
     $limit = $this->helper->getSyncLimit($website->getId());
     //subscriber collection to import
     $subscribers = $this->contactFactory->create()->getSubscribersToImport($website, $limit);
     if ($subscribers->getSize()) {
         $subscribersFilename = strtolower($website->getCode() . '_subscribers_' . date('d_m_Y_Hi') . '.csv');
         //get mapped storename
         $subscriberStoreName = $this->helper->getMappedStoreName($website);
         //file headers
         $this->file->outputCSV($this->file->getFilePath($subscribersFilename), ['Email', 'emailType', $subscriberStoreName]);
         $emails = $subscribers->getColumnValues('email');
         $subscriberFactory = $this->subscriberFactory->create();
         $subscribersData = $subscriberFactory->getCollection()->addFieldToFilter('subscriber_email', ['in' => $emails])->addFieldToSelect(['subscriber_email', 'store_id'])->toArray();
         foreach ($subscribers as $subscriber) {
             $email = $subscriber->getEmail();
             $storeId = $this->getStoreIdForSubscriber($email, $subscribersData['items']);
             $storeName = $this->storeManager->getStore($storeId)->getName();
             // save data for subscribers
             $this->file->outputCSV($this->file->getFilePath($subscribersFilename), [$email, 'Html', $storeName]);
             //@codingStandardsIgnoreStart
             $subscriber->setSubscriberImported(1)->save();
             //@codingStandardsIgnoreEnd
             ++$updated;
         }
         $this->helper->log('Subscriber filename: ' . $subscribersFilename);
         //register in queue with importer
         $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_SUBSCRIBERS, '', \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website->getId(), $subscribersFilename);
     }
     //add updated number for the website
     $this->countSubscriber += $updated;
     return $updated;
 }
 /**
  * Cleaning for csv files and connector tables.
  *
  * @return string
  */
 public function cleaning()
 {
     //Clean tables
     $tables = ['automation' => 'email_automation', 'importer' => 'email_importer', 'campaign' => 'email_campaign'];
     $message = 'Cleaning cron job result :';
     foreach ($tables as $key => $table) {
         $result = $this->importerResource->cleanup($table);
         $message .= " {$result} records removed from {$key} .";
     }
     $archivedFolder = $this->fileHelper->getArchiveFolder();
     $result = $this->fileHelper->deleteDir($archivedFolder);
     $message .= ' Deleting archived folder result : ' . $result;
     $this->helper->log($message);
     return $message;
 }
 /**
  * Check importing status for pending import.
  */
 public function _checkImportStatus()
 {
     if ($items = $this->_getImportingItems($this->bulkSyncLimit)) {
         foreach ($items as $item) {
             $websiteId = $item->getWebsiteId();
             $client = false;
             if ($this->helper->isEnabled($websiteId)) {
                 $client = $this->helper->getWebsiteApiClient($websiteId);
             }
             if ($client) {
                 try {
                     if ($item->getImportType() == self::IMPORT_TYPE_CONTACT or $item->getImportType() == self::IMPORT_TYPE_SUBSCRIBERS or $item->getImportType() == self::IMPORT_TYPE_GUEST) {
                         $response = $client->getContactsImportByImportId($item->getImportId());
                     } else {
                         $response = $client->getContactsTransactionalDataImportByImportId($item->getImportId());
                     }
                 } catch (\Exception $e) {
                     //@codingStandardsIgnoreStart
                     $item->setMessage($e->getMessage())->setImportStatus(self::FAILED)->save();
                     continue;
                 }
                 if ($response) {
                     if ($response->status == 'Finished') {
                         $now = gmdate('Y-m-d H:i:s');
                         $item->setImportStatus(self::IMPORTED)->setImportFinished($now)->setMessage('')->save();
                         if ($item->getImportType() == self::IMPORT_TYPE_CONTACT or $item->getImportType() == self::IMPORT_TYPE_SUBSCRIBERS or $item->getImportType() == self::IMPORT_TYPE_GUEST) {
                             //if file
                             if ($file = $item->getImportFile()) {
                                 $this->fileHelper->archiveCSV($file);
                             }
                             if ($item->getImportId()) {
                                 $this->_processContactImportReportFaults($item->getImportId(), $websiteId);
                             }
                         }
                     } elseif (in_array($response->status, $this->importStatuses)) {
                         $item->setImportStatus(self::FAILED)->setMessage('Import failed with status ' . $response->status)->save();
                         //@codingStandardsIgnoreEnd
                     } else {
                         //Not finished
                         $this->totalItems += 1;
                     }
                 }
             }
         }
     }
 }
 /**
  * Sync a single contact.
  *
  * @param null $contactId
  *
  * @return mixed
  */
 public function syncContact($contactId = null)
 {
     if ($contactId) {
         $contact = $this->contactFactory->create()->load($contactId);
     } else {
         $contact = $this->registry->registry('current_contact');
     }
     if (!$contact->getId()) {
         $this->messageManager->addErrorMessage('No contact found!');
         return false;
     }
     $websiteId = $contact->getWebsiteId();
     $website = $this->storeManager->getWebsite($websiteId);
     $updated = 0;
     $customers = $headers = $allMappedHash = [];
     $this->helper->log('---------- Start single customer sync ----------');
     //skip if the mapping field is missing
     if (!$this->helper->getCustomerAddressBook($website)) {
         return false;
     }
     $customerId = $contact->getCustomerId();
     if (!$customerId) {
         $this->messageManager->addErrorMessage('Cannot manually sync guests!');
         return false;
     }
     if (!$this->helper->isEnabled($websiteId)) {
         $this->messageManager->addErrorMessage('Api is not enabled');
         return false;
     }
     $client = $this->helper->getWebsiteApiClient($website);
     //create customer filename
     $customersFile = strtolower($website->getCode() . '_customers_' . date('d_m_Y_Hi') . '.csv');
     $this->helper->log('Customers file : ' . $customersFile);
     /*
      * HEADERS.
      */
     $mappedHash = $this->helper->getWebsiteCustomerMappingDatafields($website);
     $headers = $mappedHash;
     //custom customer attributes
     $customAttributes = $this->helper->getCustomAttributes($website);
     foreach ($customAttributes as $data) {
         $headers[] = $data['datafield'];
         $allMappedHash[$data['attribute']] = $data['datafield'];
     }
     $headers[] = 'Email';
     $headers[] = 'EmailType';
     $this->file->outputCSV($this->file->getFilePath($customersFile), $headers);
     /*
      * END HEADERS.
      */
     $customerCollection = $this->_getCustomerCollection([$customerId], $website->getId());
     foreach ($customerCollection as $customer) {
         $contactModel = $this->contactFactory->create()->loadByCustomerEmail($customer->getEmail(), $websiteId);
         //contact with this email not found
         if (!$contactModel->getId()) {
             continue;
         }
         /*
          * DATA.
          */
         $connectorCustomer = $this->emailCustomer->create()->setMappingHash($mappedHash)->setCustomerData($customer);
         $customers[] = $connectorCustomer;
         foreach ($customAttributes as $data) {
             $attribute = $data['attribute'];
             $value = $customer->getData($attribute);
             $connectorCustomer->setData($value);
         }
         //contact email and email type
         $connectorCustomer->setData($customer->getEmail());
         $connectorCustomer->setData('Html');
         // save csv file data for customers
         $this->file->outputCSV($this->file->getFilePath($customersFile), $connectorCustomer->toCSVArray());
         /*
          * END DATA.
          */
         //mark the contact as imported
         $contactModel->setEmailImported(\Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_IMPORTED);
         $subscriber = $this->subscriberFactory->create()->loadByEmail($customer->getEmail());
         if ($subscriber->isSubscribed()) {
             $contactModel->setIsSubscriber('1')->setSubscriberStatus($subscriber->getSubscriberStatus());
         }
         //@codingStandardsIgnoreStart
         $contactModel->getResource()->save($contactModel);
         ++$updated;
     }
     if (is_file($this->file->getFilePath($customersFile))) {
         //@codingStandardsIgnoreEnd
         //import contacts
         if ($updated > 0) {
             //register in queue with importer
             $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_CONTACT, '', \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website->getId(), $customersFile);
             $client->postAddressBookContactsImport($customersFile, $this->helper->getCustomerAddressBook($website));
         }
     }
     return $contact->getEmail();
 }