/** * Run a particular job * * @param int */ public function runJob($jobId) { $config = Mage::getModel('mailup/config'); /* @var $config MailUp_MailUpSync_Model_Config */ require_once dirname(__FILE__) . '/../Helper/Data.php'; $db_read = Mage::getSingleton('core/resource')->getConnection('core_read'); $db_write = Mage::getSingleton('core/resource')->getConnection('core_write'); $syncTableName = Mage::getSingleton('core/resource')->getTableName('mailup/sync'); $jobsTableName = Mage::getSingleton('core/resource')->getTableName('mailup/job'); $lastsync = gmdate("Y-m-d H:i:s"); // reading customers (jobid == 0, their updates) $customer_entity_table_name = Mage::getSingleton('core/resource')->getTableName('customer_entity'); $jobModel = Mage::getModel('mailup/job')->load($jobId); /* @var $jobModel MailUp_MailUpSync_Model_Job */ if (!$jobModel) { throw new Mage_Exception('No Job Exists: ' . $jobId); } $job = $jobModel->getData(); $stmt = $db_write->query("UPDATE {$jobsTableName} \n SET status='started', start_datetime='" . gmdate("Y-m-d H:i:s") . "' \n WHERE id={$job["id"]}"); $storeId = isset($job['store_id']) ? $job['store_id'] : NULL; //$storeId = Mage::app()->getDefaultStoreView()->getStoreId(); // Fallback incase not set?!? $customers = array(); $job['mailupNewGroup'] = 0; $job['mailupIdList'] = Mage::getStoreConfig('mailup_newsletter/mailup/list', $storeId); $job["mailupGroupId"] = $job["mailupgroupid"]; $job["send_optin_email_to_new_subscribers"] = $job["send_optin"]; // If group is 0 and there is a default group, set group to this group $defaultGroupId = Mage::getStoreConfig('mailup_newsletter/mailup/default_group'); if ($job["mailupGroupId"] == 0 && $defaultGroupId !== null) { $job["mailupGroupId"] = $defaultGroupId; } $tmp = Mage::getSingleton('mailup/source_lists'); $tmp = $tmp->toOptionArray($storeId); // pass store id! foreach ($tmp as $t) { if ($t["value"] == $job['mailupIdList']) { $job['mailupListGUID'] = $t["guid"]; $job["groups"] = $t["groups"]; break; } } unset($tmp); unset($t); $stmt = $db_read->query("\n SELECT ms.*, ce.email \n FROM {$syncTableName} ms \n JOIN {$customer_entity_table_name} ce \n ON (ms.customer_id = ce.entity_id) \n WHERE ms.needs_sync=1 \n AND ms.entity='customer' \n AND job_id={$job["id"]}"); while ($row = $stmt->fetch()) { $customers[] = $row["customer_id"]; } /** * Send the Data! */ $returnCode = MailUp_MailUpSync_Helper_Data::generateAndSendCustomers($customers, $job, $storeId); /** * Check return OK */ if ($returnCode === 0) { $customerCount = count($customers); $db_write->query("\n UPDATE {$syncTableName} SET needs_sync=0, last_sync='{$lastsync}' \n WHERE job_id = {$job["id"]} \n AND entity='customer'"); $config->dbLog("Job Task [update] [Synced] [customer count:{$customerCount}]", $job["id"], $storeId); // finishing the job also $db_write->query("\n UPDATE {$jobsTableName} SET status='finished', finish_datetime='" . gmdate("Y-m-d H:i:s") . "' \n WHERE id={$job["id"]}"); $config->dbLog("Jobs [Update] [Complete] [{$job["id"]}]", $job["id"], $storeId); } else { $stmt = $db_write->query("UPDATE {$jobsTableName} SET status='queued' WHERE id={$job["id"]}"); if ($config->isLogEnabled()) { $config->dbLog(sprintf("generateAndSendCustomers [ReturnCode] [ERROR] [%d]", $returnCode), $job["id"], $storeId); } } }
/** * Generate CSV * * @todo include stores */ public function csvAction() { $post = $this->getRequest()->getPost(); $file = ''; if ($post['countPost'] > 0) { //preparo l'elenco degli iscritti da salvare nel csv $mailupCustomerIds = Mage::getSingleton('core/session')->getMailupCustomerIds(); //require_once(dirname(__FILE__) . '/../Helper/Data.php'); $customersData = MailUp_MailUpSync_Helper_Data::getCustomersData(); //CSV Column names $file = '"Email","First Name","Last Name"'; if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_mailup_synchro') == 1) { $file .= ',"Company","City","Province","Zip code","Region","Country code","Address","Fax","Phone","Customer id"'; $file .= ',"Last Order id","Last Order date","Last Order total","Last order product ids","Last order category ids"'; $file .= ',"Last sent order date","Last sent order id"'; $file .= ',"Last abandoned cart date","Last abandoned cart total","Last abandoned cart id"'; $file .= ',"Total orders amount","Last 12 months amount","Last 30 days amount","All products ids"'; } $file .= ';'; foreach ($mailupCustomerIds as $customerId) { foreach ($customersData as $subscriber) { if ($subscriber['email'] == $customerId['email']) { $file .= "\n"; $file .= '"' . $subscriber['email'] . '"'; $file .= ',"' . (!empty($subscriber['nome']) ? $subscriber['nome'] : '') . '"'; $file .= ',"' . (!empty($subscriber['cognome']) ? $subscriber['cognome'] : '') . '"'; $synchroConfig = Mage::getStoreConfig('mailup_newsletter/mailup/enable_mailup_synchro') == 1; $file .= ',"' . ($synchroConfig && !empty($subscriber['azienda']) ? $subscriber['azienda'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['città']) ? $subscriber['città'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['provincia']) ? $subscriber['provincia'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['cap']) ? $subscriber['cap'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['regione']) ? $subscriber['regione'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['paese']) ? $subscriber['paese'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['indirizzo']) ? $subscriber['indirizzo'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['fax']) ? $subscriber['fax'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['telefono']) ? $subscriber['telefono'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDCliente']) ? $subscriber['IDCliente'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDUltimoOrdine']) ? $subscriber['IDUltimoOrdine'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['DataUltimoOrdine']) ? $subscriber['DataUltimoOrdine'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['TotaleUltimoOrdine']) ? $subscriber['TotaleUltimoOrdine'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDProdottiUltimoOrdine']) ? $subscriber['IDProdottiUltimoOrdine'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDCategorieUltimoOrdine']) ? $subscriber['IDCategorieUltimoOrdine'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['DataUltimoOrdineSpedito']) ? $subscriber['DataUltimoOrdineSpedito'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDUltimoOrdineSpedito']) ? $subscriber['IDUltimoOrdineSpedito'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['DataCarrelloAbbandonato']) ? $subscriber['DataCarrelloAbbandonato'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['TotaleCarrelloAbbandonato']) ? $subscriber['TotaleCarrelloAbbandonato'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDCarrelloAbbandonato']) ? $subscriber['IDCarrelloAbbandonato'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['TotaleFatturato']) ? $subscriber['TotaleFatturato'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['TotaleFatturatoUltimi12Mesi']) ? $subscriber['TotaleFatturatoUltimi12Mesi'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['TotaleFatturatoUltimi30gg']) ? $subscriber['TotaleFatturatoUltimi30gg'] : '') . '"'; $file .= ',"' . ($synchroConfig && !empty($subscriber['IDTuttiProdottiAcquistati']) ? $subscriber['IDTuttiProdottiAcquistati'] : '') . '"'; $file .= ';'; continue 2; } } } } //lancio il download del file header("Content-type: application/csv"); header("Content-Disposition: attachment;Filename=filtered_customers.csv"); echo $file; }
/** * Run the Task * * IF ANY Job we run fails, due to another processes being run we should * gracefully exit and wait our next go! * * Also change auto sync to just create a job, and run a single job Queue! */ public function run() { if ($this->_config()->isLogEnabled()) { $this->_config()->dbLog("Cron [Triggered]"); } /** * This doesn't exist in 1.3.2! */ $indexProcess = new Mage_Index_Model_Process(); $indexProcess->setId(self::LOCK_INDEX_ID); if ($indexProcess->isLocked()) { // Check how old the lock is - unlock after 1hr if ($this->_lockIsOld(self::LOCK_INDEX_ID)) { $indexProcess->unlock(); } else { $this->_config()->log('MAILUP: cron already running or locked'); return false; } } $indexProcess->lockAndBlock(); try { require_once dirname(__FILE__) . '/../Helper/Data.php'; $db_read = Mage::getSingleton('core/resource')->getConnection('core_read'); $db_write = Mage::getSingleton('core/resource')->getConnection('core_write'); $syncTableName = Mage::getSingleton('core/resource')->getTableName('mailup/sync'); $jobsTableName = Mage::getSingleton('core/resource')->getTableName('mailup/job'); $lastsync = gmdate("Y-m-d H:i:s"); // reading customers (jobid == 0, their updates) $customer_entity_table_name = Mage::getSingleton('core/resource')->getTableName('customer_entity'); /** * Now Handle Jobs we need to Sync, and all customers attached to each job */ foreach (Mage::getModel('mailup/job')->fetchQueuedOrStartedJobsCollection() as $jobModel) { /* @var $jobModel MailUp_MailUpSync_Model_Job */ $job = $jobModel->getData(); $storeId = isset($job['store_id']) ? $job['store_id'] : NULL; // If job is auto-sync and cron is not enabled for the job's site, skip the job if ($jobModel->isAutoSync() && !$this->_config()->isCronExportEnabled($storeId)) { $this->_config()->dbLog("Auto-Task skipped as auto-sync disabled for site", $job["id"], $storeId); continue; } $stmt = $db_write->query("UPDATE {$jobsTableName}\n SET status='started', start_datetime='" . gmdate("Y-m-d H:i:s") . "'\n WHERE id={$job["id"]}"); $customers = array(); $job['mailupNewGroup'] = 0; $job['mailupIdList'] = Mage::getStoreConfig('mailup_newsletter/mailup/list', $storeId); $job["mailupGroupId"] = $job["mailupgroupid"]; $job["send_optin_email_to_new_subscribers"] = $job["send_optin"]; // If group is 0 and there is a default group, set group to this group $defaultGroupId = Mage::getStoreConfig('mailup_newsletter/mailup/default_group'); if ($job["mailupGroupId"] == 0 && $defaultGroupId !== null) { $job["mailupGroupId"] = $defaultGroupId; } $tmp = Mage::getSingleton('mailup/source_lists'); $tmp = $tmp->toOptionArray($storeId); // pass store id! foreach ($tmp as $t) { if ($t["value"] == $job['mailupIdList']) { $job['mailupListGUID'] = $t["guid"]; $job["groups"] = $t["groups"]; break; } } unset($tmp); unset($t); $stmt = $db_read->query("\n SELECT ms.*, ce.email\n FROM {$syncTableName} ms\n JOIN {$customer_entity_table_name} ce\n ON (ms.customer_id = ce.entity_id)\n WHERE ms.needs_sync=1\n AND ms.entity='customer'\n AND job_id={$job["id"]}"); while ($row = $stmt->fetch()) { $customers[] = $row["customer_id"]; } /** * Send the Data! */ $returnCode = MailUp_MailUpSync_Helper_Data::generateAndSendCustomers($customers, $job, $storeId); /** * Check return OK */ if ($returnCode === 0) { $customerCount = count($customers); $db_write->query("\n UPDATE {$syncTableName} SET needs_sync=0, last_sync='{$lastsync}'\n WHERE job_id = {$job["id"]}\n AND entity='customer'"); $this->_config()->dbLog("Job Task [update] [Synced] [customer count:{$customerCount}]", $job["id"], $storeId); // finishing the job also $db_write->query("\n UPDATE {$jobsTableName} SET status='finished', finish_datetime='" . gmdate("Y-m-d H:i:s") . "'\n WHERE id={$job["id"]}"); $this->_config()->dbLog("Jobs [Update] [Complete] [{$job["id"]}]", $job["id"], $storeId); } else { $stmt = $db_write->query("UPDATE {$jobsTableName} SET status='queued' WHERE id={$job["id"]}"); if ($this->_config()->isLogEnabled()) { $this->_config()->dbLog(sprintf("generateAndSendCustomers [ReturnCode] [ERROR] [%d]", $returnCode), $job["id"], $storeId); } } } } catch (Exception $e) { // In case of otherwise uncaught error, unlock and re-throw $indexProcess->unlock(); throw $e; } $indexProcess->unlock(); if ($this->_config()->isLogEnabled()) { $this->_config()->dbLog("Cron [Completed]"); } }