/**
  * 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)
 {
     $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;
 }
 /**
  * Refresh suppressed contacts.
  */
 public function execute()
 {
     $result = $this->importerFactory->create()->processQueue();
     $this->messageManager->addSuccessMessage($result['message']);
     $redirectBack = $this->_redirect->getRefererUrl();
     $this->_redirect($redirectBack);
 }
 /**
  * ChangeContactSubscription constructor.
  *
  * @param \Dotdigitalgroup\Email\Model\AutomationFactory $automationFactory
  * @param \Dotdigitalgroup\Email\Model\ContactFactory    $contactFactory
  * @param \Magento\Framework\Registry                    $registry
  * @param \Dotdigitalgroup\Email\Helper\Data             $data
  * @param \Magento\Store\Model\StoreManagerInterface     $storeManagerInterface
  * @param \Dotdigitalgroup\Email\Model\ImporterFactory   $importerFactory
  */
 public function __construct(\Dotdigitalgroup\Email\Model\AutomationFactory $automationFactory, \Dotdigitalgroup\Email\Model\ContactFactory $contactFactory, \Magento\Framework\Registry $registry, \Dotdigitalgroup\Email\Helper\Data $data, \Magento\Store\Model\StoreManagerInterface $storeManagerInterface, \Dotdigitalgroup\Email\Model\ImporterFactory $importerFactory)
 {
     $this->automationFactory = $automationFactory;
     $this->contactFactory = $contactFactory;
     $this->helper = $data;
     $this->storeManager = $storeManagerInterface;
     $this->registry = $registry;
     $this->importerFactory = $importerFactory->create();
 }
 /**
  * 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;
 }
 /**
  * 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);
         }
     }
 }
 /**
  * Sync reviews.
  *
  * @return array
  */
 public function sync()
 {
     $response = ['success' => true, 'message' => 'Done.'];
     $this->countReviews = 0;
     $this->reviews = [];
     $this->start = microtime(true);
     $websites = $this->helper->getwebsites(true);
     foreach ($websites as $website) {
         $apiEnabled = $this->helper->isEnabled($website);
         $reviewEnabled = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_REVIEW_ENABLED, $website);
         $storeIds = $website->getStoreIds();
         if ($apiEnabled && $reviewEnabled && !empty($storeIds)) {
             $this->_exportReviewsForWebsite($website);
         }
         if (isset($this->reviews[$website->getId()])) {
             $reviews = $this->reviews[$website->getId()];
             //send reviews as transactional data
             //register in queue with importer
             $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_REVIEWS, $reviews, \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website->getId());
             //if no error then set imported
             $this->_setImported($this->reviewIds);
             //@codingStandardsIgnoreStart
             $this->countReviews += count($reviews);
             //@codingStandardsIgnoreStop
         }
     }
     if ($this->countReviews) {
         $message = 'Total time for sync : ' . gmdate('H:i:s', microtime(true) - $this->start) . ', Total synced = ' . $this->countReviews;
         $this->helper->log($message);
         $response['message'] = $message;
     }
     return $response;
 }
 /**
  * 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;
 }
 /**
  * Initial sync the transactional data.
  *
  * @return array
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function sync()
 {
     $response = ['success' => true, 'message' => 'Done.'];
     // Initialise a return hash containing results of our sync attempt
     $this->_searchAccounts();
     foreach ($this->accounts as $account) {
         $orders = $account->getOrders();
         $orderIds = $account->getOrderIds();
         $ordersForSingleSync = $account->getOrdersForSingleSync();
         $orderIdsForSingleSync = $account->getOrderIdsForSingleSync();
         //@codingStandardsIgnoreStart
         $numOrdersForSingleSync = count($ordersForSingleSync);
         $website = $account->getWebsites();
         $numOrders = count($orders);
         //@codingStandardsIgnoreEnd
         $this->countOrders += $numOrders;
         $this->countOrders += $numOrdersForSingleSync;
         //send transactional for any number of orders set
         if ($numOrders) {
             $this->helper->log('--------- Order sync ---------- : ' . $numOrders);
             //queue order into importer
             $this->helper->error('orders', $orders);
             try {
                 $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_ORDERS, $orders, \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website[0]);
             } catch (\Exception $e) {
                 $this->helper->debug((string) $e, []);
             }
             $this->_setImported($orderIds);
             $this->helper->log('----------end order sync----------');
         }
         if ($numOrdersForSingleSync) {
             $error = false;
             foreach ($ordersForSingleSync as $order) {
                 $this->helper->log('--------- register Order sync in single with importer ---------- : ');
                 //register in queue with importer
                 $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_ORDERS, $order, \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE, $website[0]);
                 $this->helper->log('----------end order sync in single----------');
             }
             //if no error then set imported
             if (!$error) {
                 $this->_setImported($orderIdsForSingleSync, true);
             }
         }
         unset($this->accounts[$account->getApiUsername()]);
     }
     /**
      * Add guest to contacts table.
      */
     if (!empty($this->guests)) {
         $this->contactFactory->create()->insert($this->guests);
     }
     if ($this->countOrders) {
         $response['message'] = 'Orders updated ' . $this->countOrders;
     }
     return $response;
 }
 /**
  * @return \Magento\Backend\Model\View\Result\Redirect
  */
 public function execute()
 {
     $searchIds = $this->getRequest()->getParam('selected');
     if (!is_array($searchIds)) {
         $this->messageManager->addError(__('Please select importer.'));
     } else {
         try {
             foreach ($searchIds as $searchId) {
                 //@codingStandardsIgnoreStart
                 $model = $this->importerFactory->create()->setId($searchId);
                 $model->delete();
                 //@codingStandardsIgnoreEnd
             }
             $this->messageManager->addSuccess(__('Total of %1 record(s) were deleted.', count($searchIds)));
         } catch (\Exception $e) {
             $this->messageManager->addError($e->getMessage());
         }
     }
     /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     $resultRedirect->setPath('*/*/');
     return $resultRedirect;
 }
 /**
  * Export in single.
  *
  * @param $store
  * @param $collectionName
  * @param $websiteId
  */
 public function _exportInSingle($store, $collectionName, $websiteId)
 {
     $this->productIds = [];
     $products = $this->_getProductsToExport($store, true);
     if ($products) {
         foreach ($products as $product) {
             $connectorProduct = $this->connectorProductFactory->create();
             $connectorProduct->setProduct($product);
             $this->helper->log('---------- Start catalog single sync ----------');
             //register in queue with importer
             $this->importerFactory->create()->registerQueue($collectionName, $connectorProduct, \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE, $websiteId);
             $this->productIds[] = $product->getId();
         }
     }
     if (!empty($this->productIds)) {
         $this->_setImported($this->productIds, true);
         $this->countProducts += count($this->productIds);
     }
 }
 /**
  * Export single wishilist for website.
  *
  * @param \Magento\Store\Model\Website $website
  */
 public function exportWishlistForWebsiteInSingle(\Magento\Store\Model\Website $website)
 {
     //transactional data limit
     $limit = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_TRANSACTIONAL_DATA_SYNC_LIMIT, $website);
     $collection = $this->getModifiedWishlistToImport($website, $limit);
     $this->wishlistIds = [];
     //email_wishlist wishlist ids
     $wishlistIds = $collection->getColumnValues('wishlist_id');
     $wishlistCollection = $this->wishlist->create()->getCollection()->addFieldToFilter('wishlist_id', ['in' => $wishlistIds]);
     $wishlistCollection->getSelect()->joinLeft(['c' => $this->resource->getTableName('customer_entity')], 'c.entity_id = customer_id', ['email', 'store_id']);
     foreach ($wishlistCollection as $wishlist) {
         $wishlistId = $wishlist->getid();
         $wishlistItems = $wishlist->getItemCollection();
         $connectorWishlist = $this->wishlistFactory->create();
         $connectorWishlist->setId($wishlistId)->setUpdatedAt($wishlist->getUpdatedAt())->setCustomerId($wishlist->getCustomerId())->setEmail($wishlist->getEmail());
         if ($wishlistItems->getSize()) {
             foreach ($wishlistItems as $item) {
                 $product = $item->getProduct();
                 $wishlistItem = $this->itemFactory->create()->setProduct($product)->setQty($item->getQty())->setPrice($product);
                 //store for wishlists
                 $connectorWishlist->setItem($wishlistItem);
                 $this->countWishlists++;
             }
             //send wishlist as transactional data
             $this->start = microtime(true);
             //register in queue with importer
             $check = $this->importerFactory->create()->registerQueue(Importer::IMPORT_TYPE_WISHLIST, $connectorWishlist, Importer::MODE_SINGLE, $website->getId());
             if ($check) {
                 $this->wishlistIds[] = $wishlistId;
             }
         } else {
             //register in queue with importer
             $check = $this->importerFactory->create()->registerQueue(Importer::IMPORT_TYPE_WISHLIST, [$wishlist->getId()], Importer::MODE_SINGLE, $website->getId());
             if ($check) {
                 $this->wishlistIds[] = $wishlistId;
             }
         }
     }
     if (!empty($this->wishlistIds)) {
         $this->setImported($this->wishlistIds, true);
     }
 }
 /**
  * Delete piece of transactional data by key.
  *
  * @param int $key
  */
 public function deleteFromAccount($key)
 {
     $apiEnabled = $this->scopeConfig->getValue(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_API_ENABLED);
     $catalogEnabled = $this->helper->isCatalogSyncEnabled();
     if ($apiEnabled && $catalogEnabled) {
         $scope = $this->scopeConfig->getValue(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_CATALOG_VALUES);
         if ($scope == 1) {
             //register in queue with importer
             $this->importerFactory->create()->registerQueue('Catalog_Default', [$key], \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE_DELETE, \Magento\Store\Model\Store::DEFAULT_STORE_ID);
         }
         if ($scope == 2) {
             $stores = $this->storeManager->getStores();
             foreach ($stores as $store) {
                 $websiteCode = $store->getWebsite()->getCode();
                 $storeCode = $store->getCode();
                 //register in queue with importer
                 $this->importerFactory->create()->registerQueue('Catalog_' . $websiteCode . '_' . $storeCode, [$key], \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE_DELETE, $store->getWebsite()->getId());
             }
         }
     }
 }
 /**
  * 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();
 }