/**
  * Get options.
  *
  * @return array
  */
 public function toOptionArray()
 {
     $fields = [];
     $fields[] = ['value' => '0', 'label' => '-- Disabled --'];
     $websiteName = $this->request->getParam('website', false);
     $website = $websiteName ? $this->storeManager->getWebsite($websiteName) : 0;
     if ($this->helper->isEnabled($website)) {
         $savedPrograms = $this->registry->registry('programs');
         //get saved datafileds from registry
         if (is_array($savedPrograms)) {
             $programs = $savedPrograms;
         } else {
             //grab the datafields request and save to register
             $client = $this->helper->getWebsiteApiClient($website);
             $programs = $client->getPrograms();
             $this->registry->unregister('programs');
             $this->registry->register('programs', $programs);
         }
         //set the api error message for the first option
         if (isset($programs->message)) {
             //message
             $fields[] = ['value' => 0, 'label' => $programs->message];
         } elseif (!empty($programs)) {
             //loop for all programs option
             foreach ($programs as $program) {
                 if (isset($program->id) && $program->status == 'Active') {
                     //@codingStandardsIgnoreStart
                     $fields[] = ['value' => $program->id, 'label' => addslashes($program->name)];
                     //@codingStandardsIgnoreEnd
                 }
             }
         }
     }
     return $fields;
 }
 /**
  * Products collection.
  *
  * @return array
  */
 public function getLoadedProductCollection()
 {
     $productsToDisplay = [];
     $mode = $this->getRequest()->getActionName();
     $customerId = $this->getRequest()->getParam('customer_id');
     $limit = $this->recommnededHelper->getDisplayLimitByMode($mode);
     //login customer to receive the recent products
     $session = $this->sessionFactory->create();
     $isLoggedIn = $session->loginById($customerId);
     $collection = $this->viewed;
     $productItems = $collection->getItemsCollection()->setPageSize($limit);
     //get the product ids from items collection
     $productIds = $productItems->getColumnValues('product_id');
     //get product collection to check for salable
     $productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id', ['in' => $productIds]);
     //show products only if is salable
     foreach ($productCollection as $product) {
         if ($product->isSalable()) {
             $productsToDisplay[$product->getId()] = $product;
         }
     }
     $this->helper->log('Recentlyviewed customer  : ' . $customerId . ', mode ' . $mode . ', limit : ' . $limit . ', items found : ' . count($productItems) . ', is customer logged in : ' . $isLoggedIn . ', products :' . count($productsToDisplay));
     $session->logout();
     return $productsToDisplay;
 }
 /**
  *  Datafields option.
  *
  * @return array
  */
 public function toOptionArray()
 {
     $fields = [];
     //default data option
     $fields[] = ['value' => '0', 'label' => '-- Please Select --'];
     $apiEnabled = $this->helper->isEnabled($this->helper->getWebsite());
     if ($apiEnabled) {
         $savedDatafields = $this->registry->registry('datafields');
         //get saved datafileds from registry
         if ($savedDatafields) {
             $datafields = $savedDatafields;
         } else {
             //grab the datafields request and save to register
             $client = $this->helper->getWebsiteApiClient();
             $datafields = $client->getDatafields();
             $this->registry->register('datafields', $datafields);
         }
         //set the api error message for the first option
         if (isset($datafields->message)) {
             //message
             $fields[] = ['value' => 0, 'label' => $datafields->message];
         } else {
             //loop for all datafields option
             foreach ($datafields as $datafield) {
                 if (isset($datafield->name)) {
                     $fields[] = ['value' => $datafield->name, 'label' => $datafield->name];
                 }
             }
         }
     }
     return $fields;
 }
 /**
  * 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);
         }
     }
 }
 /**
  * Retrieve list of options.
  *
  * @return array
  */
 public function toOptionArray()
 {
     $fields = [];
     // Add a "Do Not Map" Option
     $fields[] = ['value' => 0, 'label' => '-- Please Select --'];
     $apiEnabled = $this->helper->isEnabled($this->helper->getWebsite());
     if ($apiEnabled) {
         $savedAddressbooks = $this->registry->registry('addressbooks');
         if ($savedAddressbooks) {
             $addressBooks = $savedAddressbooks;
         } else {
             $client = $this->helper->getWebsiteApiClient();
             //make an api call an register the addressbooks
             $addressBooks = $client->getAddressBooks();
             if ($addressBooks) {
                 $this->registry->register('addressbooks', $addressBooks);
             }
         }
         //set up fields with book id and label
         foreach ($addressBooks as $book) {
             if (isset($book->id)) {
                 $fields[] = ['value' => (string) $book->id, 'label' => (string) $book->name];
             }
         }
     }
     return $fields;
 }
 /**
  * Execute method.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $order = $observer->getEvent()->getOrder();
     $email = $order->getCustomerEmail();
     $website = $this->storeManager->getWebsite($order->getWebsiteId());
     $storeName = $this->storeManager->getStore($order->getStoreId())->getName();
     //if api is not enabled
     if (!$this->helper->isEnabled($website)) {
         return $this;
     }
     //automation enrolment for order
     if ($order->getCustomerIsGuest()) {
         // guest to automation mapped
         $programType = 'XML_PATH_CONNECTOR_AUTOMATION_STUDIO_GUEST_ORDER';
         $automationType = \Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_GUEST_ORDER;
     } else {
         // customer to automation mapped
         $programType = 'XML_PATH_CONNECTOR_AUTOMATION_STUDIO_ORDER';
         $automationType = \Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_ORDER;
     }
     $programId = $this->helper->getAutomationIdByType($programType, $order->getWebsiteId());
     //the program is not mapped
     if (!$programId) {
         return $this;
     }
     try {
         $this->automationFactory->create()->setEmail($email)->setAutomationType($automationType)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($order->getId())->setWebsiteId($website->getId())->setStoreName($storeName)->setProgramId($programId)->save();
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * If it's configured to capture on shipment - do this.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $customer = $observer->getEvent()->getCustomer();
     $email = $customer->getEmail();
     $websiteId = $customer->getWebsiteId();
     $apiEnabled = $this->helper->isEnabled($websiteId);
     $customerSync = $this->helper->isCustomerSyncEnabled($websiteId);
     /*
      * Remove contact.
      */
     if ($apiEnabled && $customerSync) {
         try {
             //register in queue with importer
             $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_CONTACT, $email, \Dotdigitalgroup\Email\Model\Importer::MODE_CONTACT_DELETE, $websiteId);
             $contactModel = $this->contactFactory->create()->loadByCustomerEmail($email, $websiteId);
             if ($contactModel->getId()) {
                 //remove contact
                 $contactModel->delete();
             }
         } catch (\Exception $e) {
             $this->helper->debug((string) $e, []);
         }
     }
     return $this;
 }
 /**
  * If it's configured to capture on shipment - do this.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $object = $observer->getEvent()->getDataObject();
     $wishlist = $this->wishlist->create()->load($object->getWishlistId());
     $emailWishlist = $this->wishlistFactory->create();
     try {
         if ($object->getWishlistId()) {
             $itemCount = count($wishlist->getItemCollection());
             $item = $emailWishlist->getWishlist($object->getWishlistId());
             if ($item && $item->getId()) {
                 $preSaveItemCount = $item->getItemCount();
                 if ($itemCount != $item->getItemCount()) {
                     $item->setItemCount($itemCount);
                 }
                 if ($itemCount == 1 && $preSaveItemCount == 0) {
                     $item->setWishlistImported(null);
                 } elseif ($item->getWishlistImported()) {
                     $item->setWishlistModified(1);
                 }
                 $item->save();
             }
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * If it's configured to capture on shipment - do this.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $customer = $observer->getEvent()->getCustomer();
     $email = $customer->getEmail();
     $websiteId = $customer->getWebsiteId();
     $customerId = $customer->getEntityId();
     $isSubscribed = $customer->getIsSubscribed();
     try {
         // fix for a multiple hit of the observer
         $emailReg = $this->registry->registry($email . '_customer_save');
         if ($emailReg) {
             return $this;
         }
         $this->registry->register($email . '_customer_save', $email);
         $emailBefore = $this->customerFactory->create()->load($customer->getId())->getEmail();
         $contactModel = $this->contactFactory->create()->loadByCustomerEmail($emailBefore, $websiteId);
         //email change detection
         if ($email != $emailBefore) {
             $this->helper->log('email change detected : ' . $email . ', after : ' . $emailBefore . ', website id : ' . $websiteId);
             $data = ['emailBefore' => $emailBefore, 'email' => $email, 'isSubscribed' => $isSubscribed];
             $this->importerFactory->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_CONTACT_UPDATE, $data, \Dotdigitalgroup\Email\Model\Importer::MODE_CONTACT_EMAIL_UPDATE, $websiteId);
         } elseif (!$emailBefore) {
             //for new contacts update email
             $contactModel->setEmail($email);
         }
         $contactModel->setEmailImported(\Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_NOT_IMPORTED)->setCustomerId($customerId)->save();
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * @return array
  */
 public function toOptionArray()
 {
     $fields = [];
     $fields[] = ['value' => '0', 'label' => '-- Please Select --'];
     $apiEnabled = $this->helper->isEnabled($this->helper->getWebsite());
     if ($apiEnabled) {
         $savedCampaigns = $this->registry->registry('campaigns');
         if (is_array($savedCampaigns)) {
             $campaigns = $savedCampaigns;
         } else {
             //grab the datafields request and save to register
             $client = $this->helper->getWebsiteApiClient();
             $campaigns = $client->getCampaigns();
             $this->registry->register('campaigns', $campaigns);
         }
         //set the api error message for the first option
         if (isset($campaigns->message)) {
             //message
             $fields[] = ['value' => 0, 'label' => $campaigns->message];
         } elseif (!empty($campaigns)) {
             //loop for all campaing options
             foreach ($campaigns as $campaign) {
                 if (isset($campaign->name)) {
                     //@codingStandardsIgnoreStart
                     $fields[] = ['value' => $campaign->id, 'label' => addslashes($campaign->name)];
                     //@codingStandardsIgnoreEnd
                 }
             }
         }
     }
     return $fields;
 }
 /**
  * Execute method.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  * @codingStandardsIgnoreStart
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     //@codingStandardsIgnoreEnd
     $groups = $this->context->getRequest()->getPost('groups');
     if (isset($groups['api']['fields']['username']['inherit']) || isset($groups['api']['fields']['password']['inherit'])) {
         return $this;
     }
     $apiUsername = isset($groups['api']['fields']['username']['value']) ? $groups['api']['fields']['username']['value'] : false;
     $apiPassword = isset($groups['api']['fields']['password']['value']) ? $groups['api']['fields']['password']['value'] : false;
     //skip if the inherit option is selected
     if ($apiUsername && $apiPassword) {
         $this->helper->log('----VALIDATING ACCOUNT---');
         $isValid = $this->test->validate($apiUsername, $apiPassword);
         if ($isValid) {
             //save endpoint for account
             foreach ($isValid->properties as $property) {
                 if ($property->name == 'ApiEndpoint' && !empty($property->value)) {
                     $this->saveApiEndpoint($property->value);
                     break;
                 }
             }
             $this->messageManager->addSuccessMessage(__('API Credentials Valid.'));
         } else {
             $this->messageManager->addWarningMessage(__('Authorization has been denied for this request.'));
         }
     }
     return $this;
 }
 /**
  * Execute method.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     try {
         if (!$this->registry->registry('core_config_data_save_after_done')) {
             if ($groups = $observer->getEvent()->getConfigData()->getGroups()) {
                 if (isset($groups['catalog_sync']['fields']['catalog_values']['value'])) {
                     $configAfter = $groups['catalog_sync']['fields']['catalog_values']['value'];
                     $configBefore = $this->registry->registry('core_config_data_save_before');
                     if ($configAfter != $configBefore) {
                         //reset catalog to re-import
                         $this->connectorCatalogFactory->create()->reset();
                     }
                     $this->registry->register('core_config_data_save_after_done', true);
                 }
             }
         }
         if (!$this->registry->registry('core_config_data_save_after_done_status')) {
             if ($groups = $observer->getEvent()->getConfigData()->getGroups()) {
                 if (isset($groups['data_fields']['fields']['order_statuses']['value'])) {
                     $configAfter = $groups['data_fields']['fields']['order_statuses']['value'];
                     $configBefore = $this->registry->registry('core_config_data_save_before_status');
                     if ($configAfter != $configBefore) {
                         //reset all contacts
                         $this->connectorContactFactory->create()->resetAllContacts();
                     }
                     $this->registry->register('core_config_data_save_after_done_status', true);
                 }
             }
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * Register review.
  *
  * @param $review
  */
 public function registerReview($review)
 {
     try {
         $this->reviewFactory->create()->setReviewId($review->getReviewId())->setCustomerId($review->getCustomerId())->setStoreId($review->getStoreId())->save();
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * Returns custom order attributes.
  *
  * @return array
  */
 public function toOptionArray()
 {
     $fields = $this->dataHelper->getOrderTableDescription();
     $customFields[] = ['label' => __('---- Default Option ----'), 'value' => '0'];
     foreach ($fields as $field) {
         $customFields[] = ['value' => $field['COLUMN_NAME'], 'label' => $field['COLUMN_NAME']];
     }
     return $customFields;
 }
 /**
  * Execute method.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  * @codingStandardsIgnoreStart
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     //@codingStandardsIgnoreEnd
     $contactModel = $this->contactResourceFactory->create();
     $numImported = $this->contactFactory->create()->getNumberOfImportedContacs();
     $updated = $contactModel->resetAllContacts();
     $this->helper->log('-- Imported contacts: ' . $numImported . ' reseted :  ' . $updated . ' --');
     return $this;
 }
 /**
  * * Get api client.
  *
  * @return bool|mixed|object
  */
 public function _getApiClient()
 {
     if (empty($this->client)) {
         $website = $this->getCustomer()->getStore()->getWebsite();
         $client = $this->helper->getWebsiteApiClient($website);
         $client->setApiUsername($this->helper->getApiUsername($website))->setApiPassword($this->helper->getApiPassword($website));
         $this->client = $client;
     }
     return $this->client;
 }
 /**
  * Check for non empty content.
  *
  * @param      $output
  * @param bool $flag
  */
 public function checkContentNotEmpty($output, $flag = true)
 {
     try {
         if (strlen($output) < 3 && $flag == false) {
             $this->sendResponse();
         } elseif ($flag && !strpos($output, '<table') !== false) {
             $this->sendResponse();
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * Execute method.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $order = $observer->getEvent()->getOrder();
     $incrementId = $order->getIncrementId();
     $websiteId = $this->storeManager->getStore($order->getStoreId())->getWebsiteId();
     $orderSync = $this->helper->isOrderSyncEnabled($websiteId);
     if ($this->helper->isEnabled($websiteId) && $orderSync) {
         //register in queue with importer
         $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_ORDERS, [$incrementId], \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE_DELETE, $websiteId);
     }
     return $this;
 }
 /**
  * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
  *
  * @return string
  */
 public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
 {
     //generate base url
     $baseUrl = $this->dataHelper->generateDynamicUrl();
     $passcode = $this->dataHelper->getPasscode();
     if (empty($passcode)) {
         $passcode = '[PLEASE SET UP A PASSCODE]';
     }
     //full url for dynamic content
     $text = sprintf('%sconnector/product/push/code/%s', $baseUrl, $passcode);
     $element->setData('value', $text);
     return parent::_getElementHtml($element);
 }
 /**
  * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
  *
  * @return string
  */
 public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
 {
     $passcode = $this->helper->getPasscode();
     if (empty($passcode)) {
         $passcode = '[PLEASE SET UP A PASSCODE]';
     }
     //generate the base url and display for default store id
     $baseUrl = $this->helper->generateDynamicUrl();
     //display the full url
     $text = sprintf('%sconnector/feefo/score/code/%s', $baseUrl, $passcode);
     $element->setData('value', $text);
     return parent::_getElementHtml($element);
 }
 /**
  * Execute method.
  *
  * @param \Magento\Framework\Event\Observer $observer
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     try {
         $object = $observer->getEvent()->getDataObject();
         $productId = $object->getId();
         if ($item = $this->loadProduct($productId)) {
             if ($item->getImported()) {
                 $item->setModified(1)->save();
             }
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
  *
  * @return string
  */
 public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
 {
     //base url
     $baseUrl = $this->dataHelper->generateDynamicUrl();
     //config code
     $passcode = $this->dataHelper->getPasscode();
     if (empty($passcode)) {
         $passcode = '[PLEASE SET UP A PASSCODE]';
     }
     //full url
     $text = $baseUrl . 'connector/email/coupon/id/[INSERT ID HERE]/code/' . $passcode . '/expire_days/[INSERT NUMBER OF DAYS HERE]/@EMAIL@';
     $element->setData('value', $text);
     $element->setData('disabled', 'disabled');
     return parent::_getElementHtml($element);
 }
 /**
  * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
  *
  * @return string
  */
 public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
 {
     //base url
     $baseUrl = $this->dataHelper->generateDynamicUrl();
     //config passcode
     $passcode = $this->dataHelper->getPasscode();
     if (empty($passcode)) {
         $passcode = '[PLEASE SET UP A PASSCODE]';
     }
     //full url
     $text = sprintf('%sconnector/report/bestsellers/code/%s', $baseUrl, $passcode);
     $element->setData('value', $text);
     $element->setData('disabled', 'disabled');
     return parent::_getElementHtml($element);
 }
 /**
  * Get product reviews from feefo.
  *
  * @return array
  */
 public function getProductsReview()
 {
     $check = true;
     $reviews = [];
     $feefoDir = BP . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'Dotdigitalgroup' . DIRECTORY_SEPARATOR . 'Email' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'feefo';
     $logon = $this->helper->getFeefoLogon();
     $limit = $this->helper->getFeefoReviewsPerProduct();
     $products = $this->getQuoteProducts();
     foreach ($products as $sku => $name) {
         $url = 'http://www.feefo.com/feefo/xmlfeed.jsp?logon=' . $logon . '&limit=' . $limit . '&vendorref=' . $sku . '&mode=productonly';
         $doc = $this->domDocument;
         $xsl = $this->processor;
         //@codingStandardsIgnoreStart
         if ($check) {
             $doc->load($feefoDir . DIRECTORY_SEPARATOR . 'feedback.xsl');
         } else {
             $doc->load($feefoDir . DIRECTORY_SEPARATOR . 'feedback-no-th.xsl');
         }
         $xsl->importStyleSheet($doc);
         $doc->loadXML(file_get_contents($url));
         //@codingStandardsIgnoreEnd
         $productReview = $xsl->transformToXML($doc);
         if (strpos($productReview, '<td') !== false) {
             $reviews[$name] = $xsl->transformToXML($doc);
         }
         $check = false;
     }
     return $reviews;
 }
 /**
  * Easy email capture for Newsletter and Checkout.
  */
 public function execute()
 {
     if ($this->getRequest()->getParam('email') && ($quote = $this->checkoutSession->getQuote())) {
         $email = $this->getRequest()->getParam('email');
         if ($quote->hasItems()) {
             try {
                 $quote->setCustomerEmail($email);
                 $quote->getResource()->save($quote);
                 $this->helper->log('ajax emailCapture email: ' . $email);
             } catch (\Exception $e) {
                 $this->helper->debug((string) $e, []);
                 $this->helper->log('ajax emailCapture fail for email: ' . $email);
             }
         }
     }
 }
 /**
  * Automation new wishlist program.
  *
  * @param array $wishlist
  *
  * @return $this
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function registerWishlist($wishlist)
 {
     try {
         $emailWishlist = $this->wishlistFactory->create();
         $customer = $this->customerFactory->create();
         //if wishlist exist not to save again
         if (!$emailWishlist->getWishlist($wishlist['wishlist_id'])) {
             $customer->load($wishlist['customer_id']);
             $email = $customer->getEmail();
             $wishlistId = $wishlist['wishlist_id'];
             $websiteId = $customer->getWebsiteId();
             $emailWishlist->setWishlistId($wishlistId)->setCustomerId($wishlist['customer_id'])->setStoreId($customer->getStoreId())->save();
             $store = $this->storeManager->getStore($customer->getStoreId());
             $storeName = $store->getName();
             //if api is not enabled
             if (!$this->helper->isEnabled($websiteId)) {
                 return $this;
             }
             $programId = $this->helper->getWebsiteConfig('connector_automation/visitor_automation/wishlist_automation', $websiteId);
             //wishlist program mapped
             if ($programId) {
                 $automation = $this->automationFactory->create();
                 //save automation type
                 $automation->setEmail($email)->setAutomationType(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_WISHLIST)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($wishlistId)->setWebsiteId($websiteId)->setStoreName($storeName)->setProgramId($programId);
                 $automation->save();
             }
         }
     } catch (\Exception $e) {
         $this->helper->error((string) $e, []);
     }
 }
 /**
  * Search for orders to review per website.
  */
 public function searchOrdersForReview()
 {
     $websites = $this->helper->getwebsites(true);
     foreach ($websites as $website) {
         $apiEnabled = $this->helper->isEnabled($website);
         if ($apiEnabled && $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_ORDER_ENABLED, $website) && $this->helper->getOrderStatus($website) && $this->helper->getDelay($website)) {
             $storeIds = $website->getStoreIds();
             if (empty($storeIds)) {
                 continue;
             }
             $orderStatusFromConfig = $this->helper->getOrderStatus($website);
             $delayInDays = $this->helper->getDelay($website);
             $campaignCollection = $this->campaignCollection->create()->addFieldToFilter('event_name', 'Order Review');
             $campaignOrderIds = $campaignCollection->getColumnValues('order_increment_id');
             $fromTime = $this->date;
             $fromTime->subDay($delayInDays);
             $toTime = clone $fromTime;
             $to = $toTime->toString('YYYY-MM-dd HH:mm:ss');
             $from = $fromTime->subHour(2)->toString('YYYY-MM-dd HH:mm:ss');
             $created = ['from' => $from, 'to' => $to, 'date' => true];
             $collection = $this->orderCollection->create()->addFieldToFilter('main_table.status', $orderStatusFromConfig)->addFieldToFilter('main_table.created_at', $created)->addFieldToFilter('main_table.store_id', ['in' => $storeIds]);
             if (!empty($campaignOrderIds)) {
                 $collection->addFieldToFilter('main_table.increment_id', ['nin' => $campaignOrderIds]);
             }
             //process rules on collection
             $collection = $this->rulesFactory->create()->process($collection, \Dotdigitalgroup\Email\Model\Rules::REVIEW, $website->getId());
             if ($collection->getSize()) {
                 $this->reviewCollection[$website->getId()] = $collection;
             }
         }
     }
 }
 /**
  * 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;
 }
 /**
  * Register subscriber to automation.
  *
  * @param $email
  * @param $subscriber
  * @param $websiteId
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function addSubscriberToAutomation($email, $subscriber, $websiteId)
 {
     $storeId = $subscriber->getStoreId();
     $store = $this->storeManager->getStore($storeId);
     $programId = $this->helper->getWebsiteConfig('connector_automation/visitor_automation/subscriber_automation', $websiteId);
     //not mapped ignore
     if (!$programId) {
         return;
     }
     try {
         //@codingStandardsIgnoreStart
         //check the subscriber alredy exists
         $enrolmentCollection = $this->automationFactory->create()->getCollection()->addFieldToFilter('email', $email)->addFieldToFilter('automation_type', \Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_SUBSCRIBER)->addFieldToFilter('website_id', $websiteId)->setPageSize(1);
         $enrolment = $enrolmentCollection->getFirstItem();
         //@codingStandardsIgnoreEnd
         //add new subscriber to automation
         if (!$enrolment->getId()) {
             //save subscriber to the queue
             $automation = $this->automationFactory->create()->setEmail($email)->setAutomationType(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_SUBSCRIBER)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($subscriber->getId())->setWebsiteId($websiteId)->setStoreName($store->getName())->setProgramId($programId);
             $automation->save();
         }
     } catch (\Exception $e) {
         throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
     }
 }
 /**
  * Get addressbook by import type.
  *
  * @param $importType
  * @param $websiteId
  *
  * @return mixed|string
  */
 public function _getAddressBook($importType, $websiteId)
 {
     switch ($importType) {
         case \Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_CONTACT:
             $addressBook = $this->helper->getCustomerAddressBook($websiteId);
             break;
         case \Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_SUBSCRIBERS:
             $addressBook = $this->helper->getSubscriberAddressBook($websiteId);
             break;
         case \Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_GUEST:
             $addressBook = $this->helper->getGuestAddressBook($websiteId);
             break;
         default:
             $addressBook = '';
     }
     return $addressBook;
 }