/**
  * @return array
  */
 public function sync()
 {
     $response = ['success' => true, 'message' => ''];
     $this->start = microtime(true);
     $websites = $this->helper->getWebsites(true);
     $started = false;
     foreach ($websites as $website) {
         //if subscriber is enabled and mapped
         $apiEnabled = $this->helper->isEnabled($website->getid());
         $subscriberEnaled = $this->helper->isSubscriberSyncEnabled($website->getid());
         $addressBook = $this->helper->getSubscriberAddressBook($website->getId());
         //enabled and mapped
         if ($apiEnabled && $addressBook && $subscriberEnaled) {
             //ready to start sync
             $numUpdated = $this->exportSubscribersPerWebsite($website);
             if ($this->countSubscriber && !$started) {
                 $this->helper->log('---------------------- Start subscriber sync -------------------');
                 $started = true;
             }
             // show message for any number of customers
             if ($numUpdated) {
                 $response['message'] .= '</br>' . $website->getName() . ', updated subscribers = ' . $numUpdated;
             }
         }
     }
     return $response;
 }
 /**
  * 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;
 }
 /**
  * @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;
 }
 /**
  * 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;
 }
 /**
  *  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;
 }
 /**
  * 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)
 {
     $dataObject = $observer->getEvent()->getDataObject();
     if ($dataObject->getCustomerId() && $dataObject->getStatusId() == \Magento\Review\Model\Review::STATUS_APPROVED) {
         $customerId = $dataObject->getCustomerId();
         $this->helper->setConnectorContactToReImport($customerId);
         //save review info in the table
         $this->registerReview($dataObject);
         $store = $this->storeManager->getStore($dataObject->getStoreId());
         $storeName = $store->getName();
         $website = $this->storeManager->getStore($store)->getWebsite();
         $customer = $this->customerFactory->create()->load($customerId);
         //if api is not enabled
         if (!$this->helper->isEnabled($website)) {
             return $this;
         }
         $programId = $this->helper->getWebsiteConfig('connector_automation/visitor_automation/review_automation');
         if ($programId) {
             $automation = $this->automationFactory->create();
             $automation->setEmail($customer->getEmail())->setAutomationType(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_REVIEW)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($dataObject->getReviewId())->setWebsiteId($website->getId())->setStoreName($storeName)->setProgramId($programId);
             $automation->save();
         }
     }
     return $this;
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * Change contact subscription status.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $subscriber = $observer->getEvent()->getSubscriber();
     $email = $subscriber->getEmail();
     $storeId = $subscriber->getStoreId();
     $subscriberStatus = $subscriber->getSubscriberStatus();
     $websiteId = $this->storeManager->getStore($subscriber->getStoreId())->getWebsiteId();
     //check if enabled
     if (!$this->helper->isEnabled($websiteId)) {
         return $this;
     }
     try {
         $contactEmail = $this->contactFactory->create()->loadByCustomerEmail($email, $websiteId);
         // only for subscribers
         if ($subscriberStatus == \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED) {
             //Set contact as subscribed
             $contactEmail->setSubscriberStatus($subscriberStatus)->setIsSubscriber('1');
             //Subscriber subscribed when it is suppressed in table then re-subscribe
             if ($contactEmail->getSuppressed()) {
                 $this->importerFactory->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_SUBSCRIBER_RESUBSCRIBED, ['email' => $email], \Dotdigitalgroup\Email\Model\Importer::MODE_SUBSCRIBER_RESUBSCRIBED, $websiteId);
                 //Set to subscriber imported and reset the subscriber as suppressed
                 $contactEmail->setSubscriberImported(1)->setSuppressed(null);
             }
             //not subscribed
         } else {
             //skip if contact is suppressed
             if ($contactEmail->getSuppressed()) {
                 return $this;
             }
             //update contact id for the subscriber
             $contactId = $contactEmail->getContactId();
             //get the contact id
             if (!$contactId) {
                 $this->importerFactory->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_SUBSCRIBER_UPDATE, ['email' => $email, 'id' => $contactEmail->getId()], \Dotdigitalgroup\Email\Model\Importer::MODE_SUBSCRIBER_UPDATE, $websiteId);
             }
             $contactEmail->setIsSubscriber(null)->setSubscriberStatus(\Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED);
         }
         // fix for a multiple hit of the observer. stop adding the duplicates on the automation
         $emailReg = $this->registry->registry($email . '_subscriber_save');
         if ($emailReg) {
             return $this;
         }
         $this->registry->register($email . '_subscriber_save', $email);
         //add subscriber to automation
         $this->addSubscriberToAutomation($email, $subscriber, $websiteId);
         //update the contact
         $contactEmail->setStoreId($storeId);
         //update contact
         $contactEmail->save();
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * 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;
 }
 /**
  * Create certain address books.
  *
  * @param $username
  * @param $password
  *
  * @return bool
  */
 public function createAddressBooks($username, $password)
 {
     $addressBooks = [['name' => 'Magento_Customers', 'visibility' => 'Private'], ['name' => 'Magento_Subscribers', 'visibility' => 'Private'], ['name' => 'Magento_Guests', 'visibility' => 'Private']];
     $addressBookMap = ['Magento_Customers' => Config::XML_PATH_CONNECTOR_CUSTOMERS_ADDRESS_BOOK_ID, 'Magento_Subscribers' => Config::XML_PATH_CONNECTOR_SUBSCRIBERS_ADDRESS_BOOK_ID, 'Magento_Guests' => Config::XML_PATH_CONNECTOR_GUEST_ADDRESS_BOOK_ID];
     $error = false;
     $client = false;
     if ($this->helper->isEnabled()) {
         $client = $this->helper->getWebsiteApiClient(0, $username, $password);
     }
     if (!$client) {
         $error = true;
         $this->helper->log('createAddressBooks client is not enabled');
     } else {
         foreach ($addressBooks as $addressBook) {
             $addressBookName = $addressBook['name'];
             $visibility = $addressBook['visibility'];
             if (!empty($addressBookName)) {
                 $response = $client->postAddressBooks($addressBookName, $visibility);
                 if (isset($response->message)) {
                     $error = true;
                 } else {
                     //map the successfully created address book
                     $this->helper->saveConfigData($addressBookMap[$addressBookName], $response->id, 'default', 0);
                     $this->helper->log('successfully connected address book : ' . $addressBookName);
                 }
             }
         }
     }
     return $error == true ? false : true;
 }
 /**
  * Search the configuration data per website.
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function _searchAccounts()
 {
     $this->orderIds = [];
     $this->orderIdsForSingleSync = [];
     $websites = $this->helper->getWebsites(true);
     foreach ($websites as $website) {
         $apiEnabled = $this->helper->isEnabled($website);
         $storeIds = $website->getStoreIds();
         // api and order sync should be enabled, skip website with no store ids
         if ($apiEnabled && $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_ORDER_ENABLED, $website) && !empty($storeIds)) {
             $this->apiUsername = $this->helper->getApiUsername($website);
             $this->apiPassword = $this->helper->getApiPassword($website);
             // limit for orders included to sync
             $limit = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_TRANSACTIONAL_DATA_SYNC_LIMIT, $website);
             if (!isset($this->accounts[$this->apiUsername])) {
                 $account = $this->accountFactory->create()->setApiUsername($this->apiUsername)->setApiPassword($this->apiPassword);
                 $this->accounts[$this->apiUsername] = $account;
             }
             $this->accounts[$this->apiUsername]->setOrders($this->getConnectorOrders($website, $limit));
             $this->accounts[$this->apiUsername]->setOrderIds($this->orderIds);
             $this->accounts[$this->apiUsername]->setWebsites($website->getId());
             $this->accounts[$this->apiUsername]->setOrdersForSingleSync($this->getConnectorOrders($website, $limit, true));
             $this->accounts[$this->apiUsername]->setOrderIdsForSingleSync($this->orderIdsForSingleSync);
         }
     }
 }
 /**
  * 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;
             }
         }
     }
 }
 /**
  * Sync Wishlists.
  *
  * @return array
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function sync()
 {
     $response = ['success' => true, 'message' => 'Done.'];
     $websites = $this->helper->getWebsites();
     foreach ($websites as $website) {
         $wishlistEnabled = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_WISHLIST_ENABLED, $website);
         $apiEnabled = $this->helper->isEnabled($website);
         $storeIds = $website->getStoreIds();
         if ($wishlistEnabled && $apiEnabled && !empty($storeIds)) {
             //using bulk api
             $this->start = microtime(true);
             $this->exportWishlistForWebsite($website);
             //send wishlist as transactional data
             if (isset($this->wishlists[$website->getId()])) {
                 $websiteWishlists = $this->wishlists[$website->getId()];
                 //register in queue with importer
                 $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_WISHLIST, $websiteWishlists, \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website->getId());
                 //mark connector wishlist as  imported
                 $this->setImported($this->wishlistIds);
             }
             if (!empty($this->wishlists)) {
                 $message = 'Total time for wishlist bulk sync : ' . gmdate('H:i:s', microtime(true) - $this->start);
                 $this->helper->log($message);
             }
             //using single api
             $this->exportWishlistForWebsiteInSingle($website);
         }
     }
     $response['message'] = 'wishlists updated: ' . $this->countWishlists;
     return $response;
 }
 /**
  * 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, []);
     }
 }
 /**
  * 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;
 }
 /**
  * Sync.
  *
  * @param $collection
  */
 public function sync($collection)
 {
     foreach ($collection as $item) {
         $websiteId = $item->getWebsiteId();
         $file = $item->getImportFile();
         if ($this->helper->isEnabled($websiteId)) {
             $this->client = $this->helper->getWebsiteApiClient($websiteId);
             $addressBook = $this->_getAddressBook($item->getImportType(), $websiteId);
             if (!empty($file) && !empty($addressBook) && $this->client) {
                 //import contacts from csv file
                 $result = $this->client->postAddressBookContactsImport($file, $addressBook);
                 $this->_handleItemAfterSync($item, $result);
             }
         }
     }
 }
 /**
  * Execute method.
  */
 public function execute()
 {
     $addressBookName = $this->getRequest()->getParam('name');
     $visibility = $this->getRequest()->getParam('visibility');
     $website = $this->getRequest()->getParam('website', 0);
     if ($this->helperData->isEnabled($website)) {
         $client = $this->helperData->getWebsiteApiClient($website);
         if (!empty($addressBookName)) {
             $response = $client->postAddressBooks($addressBookName, $visibility);
             if (isset($response->message)) {
                 $this->messageManager->addErrorMessage($response->message);
             } else {
                 $this->messageManager->addSuccessMessage('Address book : ' . $addressBookName . ' created.');
             }
         }
     }
 }
 /**
  * Validate apiuser on save.
  *
  * @param string $apiUsername
  * @param string $apiPassword
  *
  * @return bool|mixed
  */
 public function validate($apiUsername, $apiPassword)
 {
     if (!$this->helper->isEnabled()) {
         return false;
     }
     $client = $this->helper->getWebsiteApiClient();
     if ($apiUsername && $apiPassword) {
         $client->setApiUsername($apiUsername)->setApiPassword($apiPassword);
         $accountInfo = $client->getAccountInfo();
         if (isset($accountInfo->message)) {
             $this->helper->log('VALIDATION ERROR :  ' . $accountInfo->message);
             return false;
         }
         return $accountInfo;
     }
     return false;
 }
 /**
  * Execute method.
  */
 public function execute()
 {
     $result = ['errors' => false, 'message' => ''];
     $website = $this->getRequest()->getParam('website', 0);
     $client = false;
     if ($this->data->isEnabled()) {
         $client = $this->data->getWebsiteApiClient($website);
     }
     $redirectUrl = $this->getUrl('adminhtml/system_config/edit', ['section' => 'connector_developer_settings']);
     if (!$client) {
         $this->messageManager->addNoticeMessage('Please enable api first.');
     } else {
         // get all possible datatifileds
         $datafields = $this->datafield->getContactDatafields();
         foreach ($datafields as $key => $datafield) {
             $response = $client->postDataFields($datafield);
             //ignore existing datafields message
             if (isset($response->message) && $response->message != \Dotdigitalgroup\Email\Model\Apiconnector\Client::API_ERROR_DATAFIELD_EXISTS) {
                 $result['errors'] = true;
                 $result['message'] .= ' Datafield ' . $datafield['name'] . ' - ' . $response->message . '</br>';
             } else {
                 if ($website) {
                     $scope = 'websites';
                     $scopeId = $website;
                 } else {
                     $scope = 'default';
                     $scopeId = '0';
                 }
                 /*
                  * map the succesful created datafield
                  */
                 $this->data->saveConfigData('connector_data_mapping/customer_data/' . $key, strtoupper($datafield['name']), $scope, $scopeId);
                 $this->data->log('successfully connected : ' . $datafield['name']);
             }
         }
         if ($result['errors']) {
             $this->messageManager->addNoticeMessage($result['message']);
         } else {
             $this->messageManager->addSuccessMessage('All Datafields Created And Mapped.');
         }
     }
     $this->_redirect($redirectUrl);
 }
 /**
  * Validate api user.
  */
 public function execute()
 {
     $params = $this->getRequest()->getParams();
     $apiUsername = $params['api_username'];
     //@codingStandardsIgnoreStart
     $apiPassword = base64_decode($params['api_password']);
     //@codingStandardsIgnoreEnd
     //validate api, check against account info.
     if ($this->data->isEnabled()) {
         $client = $this->data->getWebsiteApiClient();
         $result = $client->validate($apiUsername, $apiPassword);
         $resonseData['success'] = true;
         //validation failed
         if (!$result) {
             $resonseData['success'] = false;
             $resonseData['message'] = 'Authorization has been denied for this request.';
         }
         $this->getResponse()->representJson($this->jsonHelper->jsonEncode($resonseData));
     }
 }
 /**
  * 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;
     //api client is enabled
     $apiEnabled = $this->helper->isEnabled($website);
     if ($apiEnabled) {
         $client = $this->helper->getWebsiteApiClient($website);
         $programs = $client->getPrograms();
         foreach ($programs as $one) {
             if (isset($one->id)) {
                 if ($one->status == 'Active') {
                     $fields[] = ['value' => $one->id, 'label' => __($one->name)];
                 }
             }
         }
     }
     return $fields;
 }
 /**
  * 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();
     $customer = $this->customerFactory->create()->load($object->getCustomerId());
     $website = $this->storeManager->getStore($customer->getStoreId())->getWebsite();
     //sync enabled
     $syncEnabled = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_SYNC_WISHLIST_ENABLED, $website->getId());
     if ($this->helper->isEnabled($website->getId()) && $syncEnabled) {
         //Remove wishlist
         try {
             $item = $this->wishlistFactory->create()->getWishlist($object->getWishlistId());
             if ($item instanceof \Magento\Framework\DataObject && $item->getId()) {
                 //register in queue with importer
                 $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_WISHLIST, [$item->getId()], \Dotdigitalgroup\Email\Model\Importer::MODE_SINGLE_DELETE, $website->getId());
                 $item->delete();
             }
         } catch (\Exception $e) {
             $this->helper->debug((string) $e, []);
         }
     }
 }
 /**
  * Get options.
  *
  * @return array
  */
 public function toOptionArray()
 {
     $fields[] = ['label' => __('---- Default Option ----'), 'value' => '0'];
     $website = $this->helper->getWebsite();
     $apiEnabled = $this->helper->isEnabled($website);
     //get address books options
     if ($apiEnabled) {
         $addressBooks = $this->getAddressBooks();
         //set the error message to the select option
         if (isset($addressBooks->message)) {
             $fields[] = ['value' => 0, 'label' => __($addressBooks->message)];
         }
         $subscriberAddressBook = $this->helper->getSubscriberAddressBook($this->helper->getWebsite());
         //set up fields with book id and label
         foreach ($addressBooks as $book) {
             if (isset($book->id) && $book->visibility == 'Public' && $book->id != $subscriberAddressBook) {
                 $fields[] = ['value' => $book->id, 'label' => $book->name];
             }
         }
     }
     return $fields;
 }
 /**
  *  Datafields option.
  *
  * @return array
  */
 public function toOptionArray()
 {
     $fields[] = ['label' => __('---- Default Option ----'), 'value' => '0'];
     $apiEnabled = $this->helper->isEnabled($this->helper->getWebsite());
     //get datafields options
     if ($apiEnabled) {
         $datafields = $this->getDataFields();
         //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) && $datafield->visibility == 'Public') {
                     $fields[] = ['value' => $datafield->name, 'label' => __($datafield->name)];
                 }
             }
         }
     }
     return $fields;
 }
 /**
  * GUEST SYNC.
  */
 public function sync()
 {
     $this->start = microtime(true);
     $websites = $this->helper->getWebsites();
     $started = false;
     foreach ($websites as $website) {
         //check if the guest is mapped and enabled
         $addresbook = $this->helper->getGuestAddressBook($website);
         $guestSyncEnabled = $this->helper->isGuestSyncEnabled($website);
         $apiEnabled = $this->helper->isEnabled($website);
         if ($addresbook && $guestSyncEnabled && $apiEnabled) {
             //sync guests for website
             $this->exportGuestPerWebsite($website);
             if ($this->countGuests && !$started) {
                 $this->helper->log('----------- Start guest sync ----------');
                 $started = true;
             }
         }
     }
     if ($this->countGuests) {
         $this->helper->log('---- End Guest total time for guest sync : ' . gmdate('H:i:s', microtime(true) - $this->start));
     }
 }
 /**
  * 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;
                     }
                 }
             }
         }
     }
 }
 /**
  * Sending the campaigns
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function sendCampaigns()
 {
     foreach ($this->storeManager->getWebsites(true) as $website) {
         //check send status for processing
         $this->_checkSendStatus($website);
         //@codingStandardsIgnoreStart
         //start send process
         $storeIds = $this->websiteFactory->create()->load($website->getId())->getStoreIds();
         //@codingStandardsIgnoreEnd
         $emailsToSend = $this->_getEmailCampaigns($storeIds);
         $campaignsToSend = [];
         foreach ($emailsToSend as $campaign) {
             $email = $campaign->getEmail();
             $campaignId = $campaign->getCampaignId();
             $websiteId = $website->getId();
             $client = false;
             if ($this->helper->isEnabled($websiteId)) {
                 $client = $this->helper->getWebsiteApiClient($websiteId);
             }
             //Only if valid client is returned
             if ($client) {
                 //@codingStandardsIgnoreStart
                 if (!$campaignId) {
                     $campaign->setMessage('Missing campaign id: ' . $campaignId)->setSendStatus(\Dotdigitalgroup\Email\Model\Campaign::FAILED)->save();
                     continue;
                 } elseif (!$email) {
                     $campaign->setMessage('Missing email')->setSendStatus(\Dotdigitalgroup\Email\Model\Campaign::FAILED)->save();
                     continue;
                 }
                 //@codingStandardsIgnoreEnd
                 $campaignsToSend[$campaignId]['client'] = $client;
                 try {
                     $contactId = $this->helper->getContactId($campaign->getEmail(), $websiteId);
                     if (is_numeric($contactId)) {
                         //update data fields for order review camapigns
                         if ($campaign->getEventName() == 'Order Review') {
                             $order = $this->salesOrderFactory->create()->loadByIncrementId($campaign->getOrderIncrementId());
                             if ($lastOrderId = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_CUSTOMER_LAST_ORDER_ID, $websiteId)) {
                                 $data[] = ['Key' => $lastOrderId, 'Value' => $order->getId()];
                             }
                             if ($orderIncrementId = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_CUSTOMER_LAST_ORDER_INCREMENT_ID, $websiteId)) {
                                 $data[] = ['Key' => $orderIncrementId, 'Value' => $order->getIncrementId()];
                             }
                             if (!empty($data)) {
                                 //update data fields
                                 $client->updateContactDatafieldsByEmail($email, $data);
                             }
                         }
                         $campaignsToSend[$campaignId]['contacts'][] = $contactId;
                         $campaignsToSend[$campaignId]['ids'][] = $campaign->getId();
                     } else {
                         //@codingStandardsIgnoreStart
                         //update the failed to send email message error message
                         $campaign->setSendStatus(\Dotdigitalgroup\Email\Model\Campaign::FAILED)->setMessage('contact id returned is not numeric for email ' . $email)->save();
                         //@codingStandardsIgnoreEnd
                     }
                 } catch (\Exception $e) {
                     throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
                 }
             }
         }
         foreach ($campaignsToSend as $campaignId => $data) {
             if (isset($data['contacts']) && isset($data['client'])) {
                 $contacts = $data['contacts'];
                 /** @var \Dotdigitalgroup\Email\Model\Apiconnector\Client $client */
                 $client = $data['client'];
                 $response = $client->postCampaignsSend($campaignId, $contacts);
                 if (isset($response->message)) {
                     //update  the failed to send email message
                     $this->campaignResourceModel->setMessage($data['ids'], $response->message);
                 } elseif (isset($response->id)) {
                     $this->campaignResourceModel->setProcessing($campaignId, $response->id);
                 } else {
                     //update  the failed to send email message
                     $this->campaignResourceModel->setMessage($data['ids'], 'No send id returned.');
                 }
             }
         }
     }
 }
 /**
  * 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();
 }
 /**
  * @return \Magento\Framework\App\ResponseInterface
  */
 public function execute()
 {
     if (!$this->formKeyValidator->validate($this->getRequest()) or !$this->customerSession->getConnectorContactId()) {
         return $this->_redirect('customer/account/');
     }
     //params
     $additionalSubscriptions = $this->getRequest()->getParam('additional_subscriptions');
     $paramDataFields = $this->getRequest()->getParam('data_fields');
     $customerId = $this->customerSession->getConnectorContactId();
     $customerEmail = $this->customerSession->getCustomer()->getEmail();
     //client
     $website = $this->customerSession->getCustomer()->getStore()->getWebsite();
     //if enabled
     if ($this->helper->isEnabled($website)) {
         $client = $this->helper->getWebsiteApiClient($website);
         $client->setApiUsername($this->helper->getApiUsername($website))->setApiPassword($this->helper->getApiPassword($website));
         $contact = $client->getContactById($customerId);
         if (isset($contact->id)) {
             //contact address books
             $bookError = false;
             $addressBooks = $client->getContactAddressBooks($contact->id);
             $subscriberAddressBook = $this->helper->getSubscriberAddressBook($website);
             $processedAddressBooks = [];
             if (is_array($addressBooks)) {
                 foreach ($addressBooks as $addressBook) {
                     if ($subscriberAddressBook != $addressBook->id) {
                         $processedAddressBooks[$addressBook->id] = $addressBook->name;
                     }
                 }
             }
             if (isset($additionalSubscriptions)) {
                 foreach ($additionalSubscriptions as $additionalSubscription) {
                     if (!isset($processedAddressBooks[$additionalSubscription])) {
                         $bookResponse = $client->postAddressBookContacts($additionalSubscription, $contact);
                         if (isset($bookResponse->message)) {
                             $bookError = true;
                         }
                     }
                 }
                 foreach ($processedAddressBooks as $bookId => $name) {
                     if (!in_array($bookId, $additionalSubscriptions)) {
                         $bookResponse = $client->deleteAddressBookContact($bookId, $contact->id);
                         if (isset($bookResponse->message)) {
                             $bookError = true;
                         }
                     }
                 }
             } else {
                 foreach ($processedAddressBooks as $bookId => $name) {
                     $bookResponse = $client->deleteAddressBookContact($bookId, $contact->id);
                     if (isset($bookResponse->message)) {
                         $bookError = true;
                     }
                 }
             }
             //contact data fields
             $data = [];
             $dataFields = $client->getDataFields();
             $processedFields = [];
             foreach ($dataFields as $dataField) {
                 $processedFields[$dataField->name] = $dataField->type;
             }
             foreach ($paramDataFields as $key => $value) {
                 if (isset($processedFields[$key]) && $value) {
                     if ($processedFields[$key] == 'Numeric') {
                         $paramDataFields[$key] = (int) $value;
                     }
                     if ($processedFields[$key] == 'String') {
                         $paramDataFields[$key] = (string) $value;
                     }
                     if ($processedFields[$key] == 'Date') {
                         $paramDataFields[$key] = $this->localeDate->date($value)->format(\Zend_Date::ISO_8601);
                     }
                     $data[] = ['Key' => $key, 'Value' => $paramDataFields[$key]];
                 }
             }
             $contactResponse = $client->updateContactDatafieldsByEmail($customerEmail, $data);
             if (isset($contactResponse->message) && $bookError) {
                 $this->messageManager->addErrorMessage(__('An error occurred while saving your subscription preferences.'));
             } else {
                 $this->messageManager->addSuccessMessage(__('The subscription preferences has been saved.'));
             }
         } else {
             $this->messageManager->addErrorMessage(__('An error occurred while saving your subscription preferences.'));
         }
     }
     $this->_redirect('customer/account/');
 }