/**
  * @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;
 }
 /**
  * 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;
 }
 /**
  * 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);
         }
     }
 }
 /**
  * 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));
     }
 }
 /**
  * Contact sync.
  *
  * @return array
  */
 public function sync()
 {
     //result message
     $result = ['success' => true, 'message' => ''];
     //starting time for sync
     $this->start = microtime(true);
     //resourse allocation
     $started = false;
     //export bulk contacts
     foreach ($this->helper->getWebsites() as $website) {
         $apiEnabled = $this->helper->isEnabled($website);
         $customerSyncEnabled = $this->helper->isCustomerSyncEnabled($website);
         $customerAddressBook = $this->helper->getCustomerAddressBook($website);
         //api, customer sync and customer address book must be enabled
         if ($apiEnabled && $customerSyncEnabled && $customerAddressBook) {
             //start log
             $contactsUpdated = $this->exportCustomersForWebsite($website);
             if ($this->countCustomers && !$started) {
                 $this->helper->log('---------- Start customer sync ----------');
                 $started = true;
             }
             // show message for any number of customers
             if ($contactsUpdated) {
                 $result['message'] .= $website->getName() . ', exported contacts ' . $contactsUpdated;
             }
         }
     }
     //sync proccessed
     if ($this->countCustomers) {
         $message = 'Total time for sync : ' . gmdate('H:i:s', microtime(true) - $this->start) . ', Total contacts  ' . $this->countCustomers;
         $this->helper->log($message);
         $message .= $result['message'];
         $result['message'] = $message;
     }
     return $result;
 }
 /**
  * Sync.
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function sync()
 {
     $automationOrderStatusCollection = $this->automationFactory->create()->addFieldToFilter('enrolment_status', self::AUTOMATION_STATUS_PENDING);
     $automationOrderStatusCollection->addFieldToFilter('automation_type', ['like' => '%' . self::ORDER_STATUS_AUTOMATION . '%'])->getSelect()->group('automation_type');
     $statusTypes = $automationOrderStatusCollection->getColumnValues('automation_type');
     foreach ($statusTypes as $type) {
         $this->automationTypes[$type] = \Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_AUTOMATION_STUDIO_ORDER_STATUS;
     }
     //send the campaign by each types
     foreach ($this->automationTypes as $type => $config) {
         $contacts = [];
         $websites = $this->helper->getWebsites(true);
         foreach ($websites as $website) {
             if (strpos($type, self::ORDER_STATUS_AUTOMATION) !== false) {
                 //@codingStandardsIgnoreStart
                 $configValue = unserialize($this->helper->getWebsiteConfig($config, $website));
                 //@codingStandardsIgnoreEnd
                 if (is_array($configValue) && !empty($configValue)) {
                     foreach ($configValue as $one) {
                         if (strpos($type, $one['status']) !== false) {
                             $contacts[$website->getId()]['programId'] = $one['automation'];
                         }
                     }
                 }
             } else {
                 $contacts[$website->getId()]['programId'] = $this->helper->getWebsiteConfig($config, $website);
             }
         }
         //get collection from type
         $automationCollection = $this->automationFactory->create();
         $automationCollection->addFieldToFilter('enrolment_status', self::AUTOMATION_STATUS_PENDING);
         $automationCollection->addFieldToFilter('automation_type', $type);
         //limit because of the each contact request to get the id
         $automationCollection->getSelect()->limit($this->limit);
         foreach ($automationCollection as $automation) {
             $type = $automation->getAutomationType();
             //customerid, subscriberid, wishlistid..
             $email = $automation->getEmail();
             $this->typeId = $automation->getTypeId();
             $this->websiteId = $automation->getWebsiteId();
             $this->storeName = $automation->getStoreName();
             $typeDouble = $type;
             //Set type to generic automation status if type contains constant value
             if (strpos($typeDouble, self::ORDER_STATUS_AUTOMATION) !== false) {
                 $typeDouble = self::ORDER_STATUS_AUTOMATION;
             }
             $contactId = $this->helper->getContactId($email, $this->websiteId);
             //contact id is valid, can update datafields
             if ($contactId) {
                 //need to update datafields
                 $this->updateDatafieldsByType($typeDouble, $email);
                 $contacts[$automation->getWebsiteId()]['contacts'][$automation->getId()] = $contactId;
             } else {
                 // the contact is suppressed or the request failed
                 //@codingStandardsIgnoreStart
                 $automation->setEnrolmentStatus('Suppressed')->save();
                 //@codingStandardsIgnoreEnd
             }
         }
         foreach ($contacts as $websiteId => $websiteContacts) {
             if (isset($websiteContacts['contacts'])) {
                 $this->programId = $websiteContacts['programId'];
                 $contactsArray = $websiteContacts['contacts'];
                 //only for subscribed contacts
                 if (!empty($contactsArray) && $this->_checkCampignEnrolmentActive($this->programId)) {
                     $result = $this->sendContactsToAutomation(array_values($contactsArray), $websiteId);
                     //check for error message
                     if (isset($result->message)) {
                         $this->programStatus = 'Failed';
                         $this->programMessage = $result->message;
                     }
                     //program is not active
                 } elseif ($this->programMessage == 'Error: ERROR_PROGRAM_NOT_ACTIVE ') {
                     $this->programStatus = 'Deactivated';
                 }
                 //update contacts with the new status, and log the error message if failes
                 $coreResource = $this->resource;
                 $conn = $coreResource->getConnection('core_write');
                 try {
                     $contactIds = array_keys($contactsArray);
                     $bind = ['enrolment_status' => $this->programStatus, 'message' => $this->programMessage, 'updated_at' => $this->localeDate->date(null, null, false)->format('Y-m-d H:i:s')];
                     $where = ['id IN(?)' => $contactIds];
                     $num = $conn->update($coreResource->getTableName('email_automation'), $bind, $where);
                     //number of updated records
                     if ($num) {
                         $this->helper->log('Automation type : ' . $type . ', updated : ' . $num);
                     }
                 } catch (\Exception $e) {
                     throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
                 }
             }
         }
     }
 }