/**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * 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();
     $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;
 }
 /**
  * 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, []);
     }
 }
 /**
  * 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
  */
 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, []);
     }
 }
 /**
  * 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);
             }
         }
     }
 }
 /**
  * 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 imported delete from account
             if ($item->getImported()) {
                 $this->deleteFromAccount($productId);
             }
             //delete from table
             $item->delete();
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * Gets the import status of a previously started transactional import.
  *
  * @param string $importId
  *
  * @return object
  */
 public function getContactsTransactionalDataImportByImportId($importId)
 {
     $url = $this->apiEndpoint . self::REST_TRANSACTIONAL_DATA_IMPORT . $importId;
     $this->setUrl($url)->setVerb('GET');
     $response = $this->execute();
     if (isset($response->message)) {
         $message = 'GET CONTACTS TRANSACTIONAL DATA IMPORT BY IMPORT ID ' . $response->message;
         $this->helper->debug('getContactsTransactionalDataImportByImportId', [$message]);
     }
     return $response;
 }
 /**
  * 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;
 }
 /**
  * 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, []);
         }
     }
 }
 /**
  * Set imported in bulk query.
  *
  * @param $ids
  */
 public function _setImported($ids)
 {
     try {
         $coreResource = $this->resource;
         $write = $coreResource->getConnection('core_write');
         $tableName = $coreResource->getTableName('email_review');
         $ids = implode(', ', $ids);
         $nowDate = $this->coreDate->gmtDate();
         $write->update($tableName, ['review_imported' => 1, 'updated_at' => $nowDate], "review_id IN ({$ids})");
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * save enrolment to queue for cron automation enrolment
  *
  * @param $data
  */
 public function doAutomationEnrolment($data)
 {
     //the program is not mapped
     if (!$data['programId']) {
         $this->helper->log('automation type : ' . $data['automationType'] . ' program id not found');
     } else {
         try {
             $this->automationFactory->create()->setEmail($data['email'])->setAutomationType($data['automationType'])->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($data['order_id'])->setWebsiteId($data['website_id'])->setStoreName($data['store_name'])->setProgramId($data['programId'])->save();
         } catch (\Exception $e) {
             $this->helper->debug((string) $e, []);
         }
     }
 }
 /**
  * New customer automation
  *
  * @param $customer
  */
 public function newCustomerAutomation($customer)
 {
     $email = $customer->getEmail();
     $websiteId = $customer->getWebsiteId();
     $customerId = $customer->getId();
     $store = $this->storeManager->getStore($customer->getStoreId());
     $storeName = $store->getName();
     try {
         //Api is enabled
         $apiEnabled = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_API_ENABLED, $websiteId);
         //Automation enrolment
         $programId = $this->helper->getWebsiteConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_AUTOMATION_STUDIO_CUSTOMER, $websiteId);
         //new contact program mapped
         if ($programId && $apiEnabled) {
             //save automation type
             $this->setEmail($email)->setAutomationType(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_NEW_CUSTOMER)->setEnrolmentStatus(\Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_STATUS_PENDING)->setTypeId($customerId)->setWebsiteId($websiteId)->setStoreName($storeName)->setProgramId($programId);
             $this->save();
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $creditmemo = $observer->getEvent()->getCreditmemo();
     $storeId = $creditmemo->getStoreId();
     $order = $creditmemo->getOrder();
     $orderId = $order->getEntityId();
     $quoteId = $order->getQuoteId();
     try {
         /*
          * Reimport transactional data.
          */
         $emailOrder = $this->emailOrderFactory->create()->loadByOrderId($orderId, $quoteId, $storeId);
         if (!$emailOrder->getId()) {
             $this->helper->log('ERROR Creditmemmo Order not found :' . $orderId . ', quote id : ' . $quoteId . ', store id ' . $storeId);
             return $this;
         }
         $emailOrder->setEmailImported(\Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_NOT_IMPORTED)->save();
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * Set imported in bulk query.
  *
  * @param            $ids
  * @param bool|false $modified
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function _setImported($ids, $modified = false)
 {
     try {
         $coreResource = $this->resource;
         $write = $coreResource->getConnection('core_write');
         $tableName = $coreResource->getTableName('email_order');
         $ids = implode(', ', $ids);
         if ($modified) {
             $write->update($tableName, ['modified' => 'null', 'updated_at' => gmdate('Y-m-d H:i:s')], "order_id IN ({$ids})");
         } else {
             $write->update($tableName, ['email_imported' => 1, 'updated_at' => gmdate('Y-m-d H:i:s')], "order_id IN ({$ids})");
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * Register import in queue.
  *
  * @param string $importType
  * @param        $importData
  * @param string $importMode
  * @param int $websiteId
  * @param bool $file
  *
  * @return bool
  */
 public function registerQueue($importType, $importData, $importMode, $websiteId, $file = false)
 {
     try {
         if (!empty($importData)) {
             $importData = serialize($importData);
         }
         if ($file) {
             $this->setImportFile($file);
         }
         $this->setImportType($importType)->setImportData($importData)->setWebsiteId($websiteId)->setImportMode($importMode)->save();
         return true;
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return false;
 }
 /**
  * @param      $ids
  * @param bool $modified
  */
 public function setImported($ids, $modified = false)
 {
     try {
         $coreResource = $this->resource;
         $write = $coreResource->getConnection('core_write');
         $tableName = $coreResource->getTableName('email_wishlist');
         $ids = implode(', ', $ids);
         $now = $this->datetime->gmtDate();
         //mark imported modified wishlists
         if ($modified) {
             $write->update($tableName, ['wishlist_modified' => 'null', 'updated_at' => $now], "wishlist_id IN ({$ids})");
         } else {
             $write->update($tableName, ['wishlist_imported' => 1, 'updated_at' => $now], "wishlist_id IN ({$ids})");
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
 }
 /**
  * Register review campaign.
  *
  * @param $collection
  * @param $websiteId
  */
 public function registerCampaign($collection, $websiteId)
 {
     //review campaign id
     $campaignId = $this->helper->getCampaign($websiteId);
     if ($campaignId) {
         foreach ($collection as $order) {
             $this->helper->log('-- Order Review: ' . $order->getIncrementId() . ' Campaign Id: ' . $campaignId);
             try {
                 $emailCampaign = $this->campaignFactory->create()->setEmail($order->getCustomerEmail())->setStoreId($order->getStoreId())->setCampaignId($campaignId)->setEventName('Order Review')->setCreatedAt($this->dateTime->formatDate(true))->setOrderIncrementId($order->getIncrementId())->setQuoteId($order->getQuoteId());
                 if ($order->getCustomerId()) {
                     $emailCampaign->setCustomerId($order->getCustomerId());
                 }
                 //@codingStandardsIgnoreStart
                 $emailCampaign->getResource()->save($emailCampaign);
                 //@codingStandardsIgnoreEnd
             } catch (\Exception $e) {
                 $this->helper->debug((string) $e, []);
             }
         }
     }
 }
 /**
  * Get attrubute value for the field.
  *
  * @param $field
  * @param $orderData
  *
  * @return float|int|null|string
  */
 public function _getCustomAttributeValue($field, $orderData)
 {
     $type = $field['DATA_TYPE'];
     $function = 'get';
     $exploded = explode('_', $field['COLUMN_NAME']);
     foreach ($exploded as $one) {
         $function .= ucfirst($one);
     }
     $value = null;
     try {
         switch ($type) {
             case 'int':
             case 'smallint':
                 $value = (int) $orderData->{$function}();
                 break;
             case 'decimal':
                 $value = (double) number_format($orderData->{$function}(), 2, '.', '');
                 break;
             case 'timestamp':
             case 'datetime':
             case 'date':
                 $value = $this->localeDate->date($orderData->{$function}())->format(\Zend_Date::ISO_8601);
                 break;
             default:
                 $value = $orderData->{$function}();
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $value;
 }