/**
  * Handle Posted Data
  */
 public function postAction()
 {
     $post = $this->getRequest()->getPost();
     $storeId = isset($post['store_id']) ? (int) $post['store_id'] : NULL;
     if (empty($post)) {
         Mage::throwException($this->__('Invalid form data.'));
     }
     $config = Mage::getModel('mailup/config');
     /* @var $config MailUp_MailUpSync_Model_Config */
     //$subscriber = Mage::getModel('newsletter/subscriber');
     /* @var $subscriber Mage_Newsletter_Model_Subscriber */
     $sendOptinEmail = isset($post['send_optin_email_to_new_subscribers']) && $post['send_optin_email_to_new_subscribers'] == 1;
     // Only save message_id if passed and if opt_in is true
     $sendMessageId = $sendOptinEmail && isset($post['message_id']) ? $post['message_id'] : null;
     $mailupCustomerIds = Mage::getSingleton('core/session')->getMailupCustomerIds();
     //$totalCustomers = count($mailupCustomerIds);
     $batches = $this->_getBatches($mailupCustomerIds, $storeId);
     //$totalBatches = count($customerIdBatches);
     $db_write = Mage::getSingleton('core/resource')->getConnection('core_write');
     /**
      * Create a New Group on Mailup
      */
     $post["mailupNewGroupName"] = trim($post["mailupNewGroupName"]);
     if ($post["mailupNewGroup"] && strlen($post["mailupNewGroupName"])) {
         require_once dirname(__FILE__) . "/../../Model/MailUpWsImport.php";
         $wsImport = new MailUpWsImport($storeId);
         $post['mailupGroupId'] = $wsImport->CreaGruppo(array("idList" => $post['mailupIdList'], "listGUID" => $post['mailupListGUID'], "newGroupName" => $post["mailupNewGroupName"]));
     }
     /**
      * Makes batches if required. Separate the jobs into max amount of customers.
      * Create a new job for each batch.
      */
     foreach ($batches as $batchNumber => $batch) {
         try {
             $customerCount = 0;
             /**
              * We have split into subscribers and non-subscribers
              */
             foreach ($batch as $subscribeStatus => $customerIdArray) {
                 if (empty($customerIdArray)) {
                     continue;
                 }
                 // Default - set subscriptions as not pending with no confirmation email
                 $asPending = 0;
                 $sendOptin = 0;
                 /* If customer is not subscribed and confirmation email is requested,
                    then set as pending with a confirmation email */
                 if ($subscribeStatus != self::STATUS_SUBSCRIBED && $sendOptinEmail) {
                     $asPending = 1;
                     $sendOptin = 1;
                 }
                 $job = Mage::getModel('mailup/job');
                 /* @var $job MailUp_MailUpSync_Model_Job */
                 $job->setData(array("mailupgroupid" => $post['mailupGroupId'], "send_optin" => $sendOptin, 'as_pending' => $asPending, "status" => "queued", "queue_datetime" => gmdate("Y-m-d H:i:s"), 'store_id' => $storeId, 'list_id' => $post['mailupIdList'], 'list_guid' => $post['mailupListGUID']));
                 if ($sendMessageId) {
                     $job->setMessageId($sendMessageId);
                 }
                 try {
                     $job->save();
                     $config->dbLog(sprintf("Job [Insert] [Group:%s] [%s] [%d]", $post['mailupGroupId'], $subscribeStatus, count($customerIdArray)), $job->getId(), $storeId);
                 } catch (Exception $e) {
                     $config->dbLog("Job [Insert] [FAILED] [Group:{$post['mailupGroupId']}] ", 0, $storeId);
                     $config->log($e);
                     throw $e;
                 }
                 /**
                  * Each Customer
                  */
                 foreach ($customerIdArray as $customerId) {
                     $customerCount++;
                     //$customer = Mage::getModel('customer/customer');
                     /* @var $customer Mage_Customer_Model_Customer */
                     $jobTask = Mage::getModel('mailup/sync');
                     /* @var $jobTask MailUp_MailUpSync_Model_Sync */
                     try {
                         $jobTask->setData(array("customer_id" => $customerId, "entity" => "customer", "job_id" => $job->getId(), "needs_sync" => TRUE, "last_sync" => null, 'store_id' => $storeId));
                         $jobTask->save();
                     } catch (Exception $e) {
                         $config->dbLog("Job Task [Sync] [FAILED] [customer:{$customerId}] [Update]", $job->getId(), $storeId);
                         $config->log($e);
                     }
                 }
             }
             $config->dbLog("Job Task [Sync] [Customer Count:{$customerCount}]", $job->getId(), $storeId);
             /**
              * Insert a new scheduled Task for the job.
              */
             $cronDelay = (int) ($batchNumber * 15) + 2;
             $db_write->insert(Mage::getSingleton('core/resource')->getTableName('cron_schedule'), array("job_code" => "mailup_mailupsync", "status" => "pending", "created_at" => gmdate("Y-m-d H:i:s"), "scheduled_at" => gmdate("Y-m-d H:i:s", strtotime("+{$cronDelay}minutes"))));
             /*$schedule = Mage::getModel('cron/schedule');
               $schedule->setJobCode($jobCode)
                   ->setCreatedAt($timecreated)
                   ->setScheduledAt($timescheduled)
                   ->setStatus(Mage_Cron_Model_Schedule::STATUS_PENDING)
                   ->save();*/
             //$config->dbLog("Secheduled Task: " . gmdate("Y-m-d H:i:s"), $job_id, $storeId);
             $message = $this->__('Members have been sent correctly');
             Mage::getSingleton('adminhtml/session')->addSuccess($message);
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             $errorMessage = $this->__('Warning: no member has been selected');
             Mage::getSingleton('adminhtml/session')->addError($errorMessage);
         }
     }
     $this->_redirect('*/*');
 }
Exemple #2
0
 /**
  * Send Customer Data
  * 
  * @param   array $mailupCustomerIds
  * @param   array
  * @param   int
  * @return  int|FALSE ReturnCode
  */
 public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $storeId = NULL)
 {
     $config = Mage::getModel('mailup/config');
     /* @var $config MailUp_MailUpSync_Model_Config */
     $wsSend = new MailUpWsSend($storeId);
     require_once dirname(__FILE__) . "/../Model/MailUpWsImport.php";
     $wsImport = new MailUpWsImport($storeId);
     $accessKey = $wsSend->loginFromId();
     if (empty($mailupCustomerIds)) {
         if ($config->isLogEnabled($storeId)) {
             $config->log('generateAndSendCustomers [Empty Customer ID Array]');
         }
         return false;
     }
     $jobId = $post['id'];
     $jobModel = Mage::getModel('mailup/job')->load($post['id']);
     /* @var $jobModel MailUp_MailUpSync_Model_Job */
     if ($accessKey === false) {
         Mage::throwException('no access key returned');
     }
     $fields_mapping = $wsImport->getFieldsMapping($storeId);
     // Pass StoreId
     if (count($fields_mapping) == 0) {
         if ($config->isLogEnabled($storeId)) {
             $config->log('No mappings set, so cannot sync customers');
         }
         return false;
     }
     // Define the group we're adding customers to
     $groupId = $post['mailupGroupId'];
     $listGUID = $post['mailupListGUID'];
     $idList = $post['mailupIdList'];
     /**
      * Create a new Mailup Group.
      */
     if ($post['mailupNewGroup'] == 1) {
         $newGroup = array("idList" => $idList, "listGUID" => $listGUID, "newGroupName" => $post['mailupNewGroupName']);
         $groupId = $wsImport->CreaGruppo($newGroup);
     }
     // If message_id set, then pass this to define which message is sent to customers
     if (isset($post['message_id']) && $post['message_id'] !== null) {
         $idConfirmNL = $post['message_id'];
     } else {
         // Default to 0 (ignored)
         $idConfirmNL = 0;
     }
     $importProcessData = array("idList" => $idList, "listGUID" => $listGUID, "idGroup" => $groupId, "xmlDoc" => "", "idGroups" => $groupId, "importType" => self::IMPORT_TYPE_REPLACE_EMPTY_ONLY_EMAIL, "mobileInputType" => self::MOBILE_INPUT_TYPE_SPLIT_INTL_CODE, "asPending" => $jobModel->getAsPending() ? 1 : 0, "ConfirmEmail" => $jobModel->getSendOptin() ? 1 : 0, "asOptOut" => 0, "forceOptIn" => 0, "replaceGroups" => 0, "idConfirmNL" => $idConfirmNL);
     $xmlData = '';
     $subscribers_counter = 0;
     $totalCustomers = sizeof($mailupCustomerIds);
     foreach ($mailupCustomerIds as $customerId) {
         $subscribers_counter++;
         $xmlCurrentCust = self::_getCustomerXml($customerId, $fields_mapping, $storeId);
         if ($xmlCurrentCust !== false) {
             $xmlData .= $xmlCurrentCust;
         }
     }
     /**
      * We have Valid Data to send
      */
     if (strlen($xmlData) > 0) {
         $importProcessData["xmlDoc"] = "<subscribers>{$xmlData}</subscribers>";
         $xmlData = "";
         $subscribers_counter = 0;
         if ($config->isLogEnabled($storeId)) {
             Mage::log('ImportProcessData');
             Mage::log($importProcessData, 0);
         }
         $processID = $wsImport->newImportProcess($importProcessData);
         /**
          * Failure
          */
         if ($processID === FALSE || $processID < 0) {
             if ($config->isLogEnabled($storeId)) {
                 $config->dbLog(sprintf('newImportProcess [ERROR] [%d]', $processID), $jobId, $storeId);
             }
             return $processID;
         } else {
             $config->dbLog(sprintf("newImportProcess [SUCCESS] [ProcessID: %d]", $processID), $jobId, $storeId);
             $jobModel->setProcessId($processID);
         }
     }
     /**
      * Build Data for StartImportProcesses
      */
     $startImportProcessesData = array('listsIDs' => $post['mailupIdList'], 'listsGUIDs' => $post['mailupListGUID'], 'groupsIDs' => $groupId, "idList" => $idList, "importType" => self::IMPORT_TYPE_REPLACE_EMPTY_ONLY_EMAIL, "mobileInputType" => self::MOBILE_INPUT_TYPE_SPLIT_INTL_CODE, "asPending" => $jobModel->getAsPending() ? 1 : 0, "ConfirmEmail" => $jobModel->getSendOptin() ? 1 : 0, "asOptOut" => 0, "forceOptIn" => 0, "replaceGroups" => 0, "idConfirmNL" => $idConfirmNL);
     if ($config->isLogEnabled($storeId)) {
         $config->log("mailup: StartImportProcesses (STORE: {$storeId})", $storeId);
         $config->log($startImportProcessesData);
     }
     $startProcessesReturnCode = $wsImport->StartImportProcesses($startImportProcessesData);
     /**
      * Save the Job Model, and update the tries as we've just tried to Start the Process
      */
     $jobModel->incrementTries();
     try {
         $jobModel->save();
     } catch (Exception $e) {
         Mage::log($e->getMessage());
     }
     if ($config->isLogEnabled($storeId)) {
         if ($startProcessesReturnCode < 0) {
             $config->dbLog(sprintf("StartImportProcesses [ReturnCode] [ERROR] [%d]", $startProcessesReturnCode), $jobId, $storeId);
         } else {
             $config->dbLog(sprintf("StartImportProcesses [ReturnCode] [SUCCESS] [%d]", $startProcessesReturnCode), $jobId, $storeId);
         }
     }
     return (int) $startProcessesReturnCode;
 }