/**
  * 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;
 }
 /**
  * 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;
 }
 /**
  *  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;
 }
 /**
  * @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;
 }
 /**
  * Get data fields.
  *
  * @return mixed
  */
 public function getDataFields()
 {
     $website = $this->helper->getWebsite();
     $client = $this->helper->getWebsiteApiClient($website);
     //grab the datafields request and save to register
     $datafields = $client->getDataFields();
     return $datafields;
 }
 /**
  * * Get api client.
  *
  * @return bool|mixed|object
  */
 public function _getApiClient()
 {
     if (empty($this->client)) {
         $website = $this->getCustomer()->getStore()->getWebsite();
         $client = $this->helper->getWebsiteApiClient($website);
         $client->setApiUsername($this->helper->getApiUsername($website))->setApiPassword($this->helper->getApiPassword($website));
         $this->client = $client;
     }
     return $this->client;
 }
 /**
  * Get address books.
  */
 public function getAddressBooks()
 {
     $website = $this->helper->getWebsite();
     $client = $this->helper->getWebsiteApiClient($website);
     $savedAddressBooks = $this->registry->registry('addressbooks');
     //get saved address books from registry
     if ($savedAddressBooks) {
         $addressBooks = $savedAddressBooks;
     } else {
         // api all address books
         $addressBooks = $client->getAddressBooks();
         $this->registry->register('addressbooks', $addressBooks);
     }
     return $addressBooks;
 }
 /**
  * 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);
             }
         }
     }
 }
 /**
  * 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;
 }
Exemplo n.º 10
0
 /**
  * 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.');
             }
         }
     }
 }
Exemplo n.º 11
0
 /**
  * Execute method.
  */
 public function execute()
 {
     $datafield = $this->getRequest()->getParam('name');
     $type = $this->getRequest()->getParam('type');
     $default = $this->getRequest()->getParam('default');
     $visibility = $this->getRequest()->getParam('visibility');
     $website = $this->getRequest()->getParam('website', 0);
     $client = $this->dataHelper->getWebsiteApiClient($website);
     if (!empty($datafield)) {
         $response = $client->postDataFields($datafield, $type, $visibility, $default);
         if (isset($response->message)) {
             $this->messageManager->addErrorMessage($response->message);
         } else {
             $this->messageManager->addSuccessMessage('Datafield : ' . $datafield . ' created.');
         }
     }
 }
Exemplo n.º 12
0
 /**
  * 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;
 }
 /**
  * Enrol contacts for a program.
  *
  * @param $contacts
  * @param $websiteId
  *
  * @return mixed
  */
 public function sendContactsToAutomation($contacts, $websiteId)
 {
     $client = $this->helper->getWebsiteApiClient($websiteId);
     $data = ['Contacts' => $contacts, 'ProgramId' => $this->programId, 'AddressBooks' => []];
     //api add contact to automation enrolment
     $result = $client->postProgramsEnrolments($data);
     return $result;
 }
 /**
  * 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;
 }
 /**
  * @param $website
  */
 public function _checkSendStatus($website)
 {
     $storeIds = $this->websiteFactory->create()->load($website->getId())->getStoreIds();
     $campaigns = $this->_getEmailCampaigns($storeIds, \Dotdigitalgroup\Email\Model\Campaign::PROCESSING, true);
     foreach ($campaigns as $campaign) {
         $client = $this->helper->getWebsiteApiClient($website);
         $response = $client->getSendStatus($campaign->getSendId());
         if (isset($response->message)) {
             //update  the failed to send email message
             $this->campaignResourceModel->setMessage([$campaign->getSendId()], $response->message);
         } elseif ($response->status == 'Sent') {
             $this->campaignResourceModel->setSent($campaign->getSendId());
         }
     }
 }
 /**
  * Get report info for contacts sync.
  *
  * @param int $id
  * @param int $websiteId
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function _processContactImportReportFaults($id, $websiteId)
 {
     $client = $this->helper->getWebsiteApiClient($websiteId);
     $response = $client->getContactImportReportFaults($id);
     if ($response) {
         $data = $this->_removeUtf8Bom($response);
         $fileName = $this->directoryList->getPath('var') . DIRECTORY_SEPARATOR . 'DmTempCsvFromApi.csv';
         $this->file->open();
         $check = $this->file->write($fileName, $data);
         if ($check) {
             $csvArray = $this->_csvToArray($fileName);
             $this->file->rm($fileName);
             $this->contact->unsubscribe($csvArray);
         } else {
             $this->helper->log('_processContactImportReportFaults: cannot save data to CSV file.');
         }
     }
 }
 /**
  * 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/');
 }