converted import

This commit is contained in:
Jonathan Labreuille
2016-08-17 12:16:58 +02:00
parent 213bca8050
commit 9582e58dda
4 changed files with 214 additions and 248 deletions

View File

@ -191,39 +191,33 @@ define(
mailChimpKeyVerifyButtonElement.click(function () { mailChimpKeyVerifyButtonElement.click(function () {
MailPoet.Modal.loading(true); MailPoet.Modal.loading(true);
MailPoet.Ajax.post({ MailPoet.Ajax.post({
endpoint: 'ImportExport', endpoint: 'importExport',
action: 'getMailChimpLists', action: 'getMailChimpLists',
data: {api_key: mailChimpKeyInputElement.val()} data: {
api_key: mailChimpKeyInputElement.val()
}
}).always(function() {
MailPoet.Modal.loading(false);
}).done(function(response) { }).done(function(response) {
if (response.result === false) {
MailPoet.Notice.hide();
MailPoet.Notice.error(response.errors);
jQuery('.mailpoet_mailchimp-key-status')
.removeClass()
.addClass('mailpoet_mailchimp-key-status mailpoet_mailchimp-error');
mailChimpListsContainerElement.hide();
toggleNextStepButton(mailChimpProcessButtonElement, 'off');
} else {
jQuery('.mailpoet_mailchimp-key-status') jQuery('.mailpoet_mailchimp-key-status')
.html('') .html('')
.removeClass() .removeClass()
.addClass('mailpoet_mailchimp-key-status mailpoet_mailchimp-ok'); .addClass('mailpoet_mailchimp-key-status mailpoet_mailchimp-ok');
if (!response.data) { if (response.data.length === 0) {
jQuery('.mailpoet_mailchimp-key-status').html(MailPoet.I18n.t('noMailChimpLists')); jQuery('.mailpoet_mailchimp-key-status').html(MailPoet.I18n.t('noMailChimpLists'));
mailChimpListsContainerElement.hide(); mailChimpListsContainerElement.hide();
toggleNextStepButton(mailChimpProcessButtonElement, 'off'); toggleNextStepButton(mailChimpProcessButtonElement, 'off');
} else { } else {
displayMailChimpLists(response.data); displayMailChimpLists(response.data);
} }
} }).fail(function(response) {
MailPoet.Modal.loading(false); if (response.errors.length > 0) {
}).fail(function (error) {
MailPoet.Modal.loading(false);
MailPoet.Notice.error( MailPoet.Notice.error(
MailPoet.I18n.t('serverError') + error.statusText.toLowerCase() + '.' response.errors.map(function(error) { return error.message; }),
{ scroll: true }
); );
}
}); });
MailPoet.Modal.loading(false);
}); });
mailChimpProcessButtonElement.click(function () { mailChimpProcessButtonElement.click(function () {
@ -232,27 +226,24 @@ define(
} }
MailPoet.Modal.loading(true); MailPoet.Modal.loading(true);
MailPoet.Ajax.post({ MailPoet.Ajax.post({
endpoint: 'ImportExport', endpoint: 'importExport',
action: 'getMailChimpSubscribers', action: 'getMailChimpSubscribers',
data: { data: {
api_key: mailChimpKeyInputElement.val(), api_key: mailChimpKeyInputElement.val(),
lists: mailChimpListsContainerElement.find('select').val() lists: mailChimpListsContainerElement.find('select').val()
} }
}).always(function(response) {
MailPoet.Modal.loading(false);
}).done(function (response) { }).done(function (response) {
if (response.result === true) {
importData.step1 = response.data; importData.step1 = response.data;
router.navigate('step2', {trigger: true}); router.navigate('step2', {trigger: true});
}
else {
MailPoet.Notice.hide();
MailPoet.Notice.error(response.errors);
}
MailPoet.Modal.loading(false);
}).fail(function () { }).fail(function () {
MailPoet.Modal.loading(false); if (response.errors.length > 0) {
MailPoet.Notice.error( MailPoet.Notice.error(
MailPoet.I18n.t('serverError') + result.statusText.toLowerCase() + '.' response.errors.map(function(error) { return error.message; }),
{ scroll: true }
); );
}
}); });
}); });
@ -582,46 +573,27 @@ define(
} }
}); });
jQuery('#new_segment_process').click(function () { jQuery('#new_segment_process').click(function () {
var segmentName = jQuery('#new_segment_name').val().trim(), var segmentName = jQuery('#new_segment_name').val().trim();
segmentDescription = jQuery('#new_segment_description').val().trim(), var segmentDescription = jQuery('#new_segment_description').val().trim();
isDuplicateListName = ( jQuery.map(mailpoetSegments, function (el) {
if (el.name.toLowerCase() === segmentName.toLowerCase()) { MailPoet.Ajax.post({
return true;
}
}).length && segmentName) ? true : false;
if (segmentName === '') {
jQuery('.mailpoet_validation_error[data-error="segment_name_required"]:hidden').show();
} else {
jQuery('.mailpoet_validation_error[data-error="segment_name_required"]:visible').hide();
}
if (isDuplicateListName) {
jQuery('.mailpoet_validation_error[data-error="segment_name_not_unique"]:hidden').show();
} else {
jQuery('.mailpoet_validation_error[data-error="segment_name_not_unique"]:visible').hide();
}
if (segmentName && !isDuplicateListName) {
jQuery('.mailpoet_validation_error[data-error="segment_name_required"]:visible').hide();
MailPoet.Ajax
.post({
endpoint: 'ImportExport', endpoint: 'ImportExport',
action: 'addSegment', action: 'addSegment',
data: { data: {
name: segmentName, name: segmentName,
description: segmentDescription description: segmentDescription
} }
}) }).done(function(response) {
.done(function (response) {
if (response.result === true) {
mailpoetSegments.push({ mailpoetSegments.push({
'id': response.segment.id, 'id': response.data.id,
'name': response.segment.name 'name': response.data.name
}); });
var selected_values = segmentSelectElement.val(); var selected_values = segmentSelectElement.val();
if (selected_values === null) { if (selected_values === null) {
selected_values = [response.segment.id] selected_values = [response.data.id]
} else { } else {
selected_values.push(response.segment.id); selected_values.push(response.data.id);
} }
enableSegmentSelection(mailpoetSegments); enableSegmentSelection(mailpoetSegments);
@ -629,21 +601,15 @@ define(
jQuery('.mailpoet_segments:hidden').show(); jQuery('.mailpoet_segments:hidden').show();
jQuery('.mailpoet_no_segments:visible').hide(); jQuery('.mailpoet_no_segments:visible').hide();
MailPoet.Modal.close(); MailPoet.Modal.close();
} }).fail(function(response) {
else { if (response.errors.length > 0) {
MailPoet.Modal.close(); MailPoet.Notice.hide();
MailPoet.Notice.error( MailPoet.Notice.error(
MailPoet.I18n.t('segmentCreateError') + response.message + '.' response.errors.map(function(error) { return error.message; }),
{ positionAfter: '#new_segment_name' }
); );
} }
})
.fail(function (error) {
MailPoet.Modal.close();
MailPoet.Notice.error(
MailPoet.I18n.t('serverError') + error.statusText.toLowerCase() + '.'
);
}); });
}
}); });
jQuery('#new_segment_cancel').click(function () { jQuery('#new_segment_cancel').click(function () {
MailPoet.Modal.close(); MailPoet.Modal.close();
@ -769,12 +735,11 @@ define(
action: 'save', action: 'save',
data: data data: data
}).done(function(response) { }).done(function(response) {
if(response.result === true) {
var new_column_data = { var new_column_data = {
'id': response.field.id, 'id': response.data.id,
'name': response.field.name, 'name': response.data.name,
'type': response.field.type, 'type': response.data.type,
'params': response.field.params, 'params': response.data.params,
'custom': true 'custom': true
}; };
// if this is the first custom column, create an "optgroup" // if this is the first custom column, create an "optgroup"
@ -807,13 +772,12 @@ define(
filterSubscribers(); filterSubscribers();
// close popup // close popup
MailPoet.Modal.close(); MailPoet.Modal.close();
} }).fail(function(response) {
else {
if (response.errors.length > 0) { if (response.errors.length > 0) {
jQuery(response.errors).each(function(i, error) { MailPoet.Notice.error(
MailPoet.Notice.error(error, {positionAfter: '#field_name'}); response.errors.map(function(error) { return error.message; }),
}); { positionAfter: '#field_name' }
} );
} }
}); });
return false; return false;
@ -975,11 +939,11 @@ define(
nextStepButton.addClass(disabled); nextStepButton.addClass(disabled);
} }
previousStepButton.off().click(function () { previousStepButton.off().on('click', function () {
router.navigate('step1', { trigger: true }); router.navigate('step1', { trigger: true });
}); });
nextStepButton.off().click(function () { nextStepButton.off().on('click', function () {
if (jQuery(this).hasClass('button-disabled')) { if (jQuery(this).hasClass('button-disabled')) {
return; return;
} }
@ -1021,8 +985,7 @@ define(
_.each(subscribers, function () { _.each(subscribers, function () {
queue.add(function(queue) { queue.add(function(queue) {
queue.pause(); queue.pause();
MailPoet.Ajax MailPoet.Ajax.post({
.post({
endpoint: 'ImportExport', endpoint: 'ImportExport',
action: 'processImport', action: 'processImport',
data: JSON.stringify({ data: JSON.stringify({
@ -1032,23 +995,20 @@ define(
segments: segmentSelectElement.val(), segments: segmentSelectElement.val(),
updateSubscribers: (jQuery(':radio[name="subscriber_update_option"]:checked').val() === 'yes') ? true : false updateSubscribers: (jQuery(':radio[name="subscriber_update_option"]:checked').val() === 'yes') ? true : false
}) })
}) }).done(function(response) {
.done(function (response) {
if (response.result === false) {
importResults.errors.push(response.errors);
} else {
importResults.created = response.data.created; importResults.created = response.data.created;
importResults.updated = response.data.updated; importResults.updated = response.data.updated;
importResults.segments = response.data.segments; importResults.segments = response.data.segments;
importResults.added_to_segment_with_welcome_notification = response.data.added_to_segment_with_welcome_notification; importResults.added_to_segment_with_welcome_notification = response.data.added_to_segment_with_welcome_notification;
}
queue.run(); queue.run();
}) }).fail(function(response) {
.fail(function (error) { MailPoet.Modal.loading(false);
importResults.errors.push( if (response.errors.length > 0) {
MailPoet.I18n.t('serverError') + error.statusText.toLowerCase() + '.' MailPoet.Notice.error(
response.errors.map(function(error) { return error.message; }),
{ scroll: true }
); );
queue.run(); }
}); });
batchNumber++; batchNumber++;
}) })

View File

@ -1,5 +1,7 @@
<?php <?php
namespace MailPoet\API\Endpoints; namespace MailPoet\API\Endpoints;
use \MailPoet\API\Endpoint as APIEndpoint;
use \MailPoet\API\Error as APIError;
use MailPoet\Subscribers\ImportExport\Import\MailChimp; use MailPoet\Subscribers\ImportExport\Import\MailChimp;
use MailPoet\Models\CustomField; use MailPoet\Models\CustomField;
@ -7,42 +9,69 @@ use MailPoet\Models\Segment;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class ImportExport { class ImportExport extends APIEndpoint {
function getMailChimpLists($data) { function getMailChimpLists($data) {
try {
$mailChimp = new MailChimp($data['api_key']); $mailChimp = new MailChimp($data['api_key']);
return $mailChimp->getLists(); $lists = $mailChimp->getLists();
return $this->successResponse($lists);
} catch(\Exception $e) {
return $this->errorResponse(array(
$e->getCode() => $e->getMessage()
));
}
} }
function getMailChimpSubscribers($data) { function getMailChimpSubscribers($data) {
try {
$mailChimp = new MailChimp($data['api_key']); $mailChimp = new MailChimp($data['api_key']);
return $mailChimp->getSubscribers($data['lists']); $subscribers = $mailChimp->getSubscribers($data['lists']);
return $this->successResponse($subscribers);
} catch(\Exception $e) {
return $this->errorResponse(array(
$e->getCode() => $e->getMessage()
));
}
} }
function addSegment($data) { function addSegment($data) {
$segment = Segment::createOrUpdate($data); $segment = Segment::createOrUpdate($data);
return ( $errors = $segment->getErrors();
($segment->id) ?
array( if(!empty($errors)) {
'result' => true, return $this->errorResponse($errors);
'segment' => $segment->asArray() } else {
) : return $this->successResponse(
array( Segment::findOne($segment->id)->asArray()
'result' => false
)
); );
} }
}
function processImport($data) { function processImport($data) {
try {
$import = new \MailPoet\Subscribers\ImportExport\Import\Import( $import = new \MailPoet\Subscribers\ImportExport\Import\Import(
json_decode($data, true) json_decode($data, true)
); );
return $import->process(); $process = $import->process();
return $this->successResponse($process);
} catch(\Exception $e) {
return $this->errorResponse(array(
$e->getCode() => $e->getMessage()
));
}
} }
function processExport($data) { function processExport($data) {
try {
$export = new \MailPoet\Subscribers\ImportExport\Export\Export( $export = new \MailPoet\Subscribers\ImportExport\Export\Export(
json_decode($data, true) json_decode($data, true)
); );
return $export->process(); $process = $export->process();
return $this->successResponse($process);
} catch(\Exception $e) {
return $this->errorResponse(array(
$e->getCode() => $e->getMessage()
));
}
} }
} }

View File

@ -19,7 +19,6 @@ class Import {
public $subscribers_count; public $subscribers_count;
public $created_at; public $created_at;
public $updated_at; public $updated_at;
public $profiler_start;
public function __construct($data) { public function __construct($data) {
$this->subscribers_data = $this->transformSubscribersData( $this->subscribers_data = $this->transformSubscribersData(
@ -40,7 +39,6 @@ class Import {
$this->subscribers_count = count(reset($this->subscribers_data)); $this->subscribers_count = count(reset($this->subscribers_data));
$this->created_at = date('Y-m-d H:i:s', (int)$data['timestamp']); $this->created_at = date('Y-m-d H:i:s', (int)$data['timestamp']);
$this->updated_at = date('Y-m-d H:i:s', (int)$data['timestamp'] + 1); $this->updated_at = date('Y-m-d H:i:s', (int)$data['timestamp'] + 1);
$this->profiler_start = microtime(true);
} }
function getSubscriberFieldsValidationRules($subscriber_fields) { function getSubscriberFieldsValidationRules($subscriber_fields) {
@ -92,10 +90,7 @@ class Import {
} }
} }
} catch(\PDOException $e) { } catch(\PDOException $e) {
return array( throw new \Exception($e->getMessage());
'result' => false,
'errors' => array($e->getMessage())
);
} }
$import_factory = new ImportExportFactory('import'); $import_factory = new ImportExportFactory('import');
$segments = $import_factory->getSegments(); $segments = $import_factory->getSegments();
@ -104,15 +99,11 @@ class Import {
Newsletter::getWelcomeNotificationsForSegments($this->segments) : Newsletter::getWelcomeNotificationsForSegments($this->segments) :
false; false;
return array( return array(
'result' => true,
'data' => array(
'created' => count($created_subscribers), 'created' => count($created_subscribers),
'updated' => count($updated_subscribers), 'updated' => count($updated_subscribers),
'segments' => $segments, 'segments' => $segments,
'added_to_segment_with_welcome_notification' => 'added_to_segment_with_welcome_notification' =>
($welcome_notifications_in_segments) ? true : false ($welcome_notifications_in_segments) ? true : false
),
'profiler' => $this->timeExecution()
); );
} }
@ -415,9 +406,4 @@ class Import {
); );
} }
} }
function timeExecution() {
$profiler_end = microtime(true);
return ($profiler_end - $this->profiler_start) / 60;
}
} }

View File

@ -14,13 +14,13 @@ class MailChimp {
function getLists() { function getLists() {
if(!$this->api_key || !$this->data_center) { if(!$this->api_key || !$this->data_center) {
return $this->processError('API'); return $this->throwException('API');
} }
$connection = @fopen(sprintf($this->lists_url, $this->data_center, $this->api_key), 'r'); $connection = @fopen(sprintf($this->lists_url, $this->data_center, $this->api_key), 'r');
if(!$connection) { if(!$connection) {
return $this->processError('connection'); return $this->throwException('connection');
} else { } else {
$response = ''; $response = '';
while(!feof($connection)) { while(!feof($connection)) {
@ -35,7 +35,7 @@ class MailChimp {
$response = json_decode($response); $response = json_decode($response);
if(!$response) { if(!$response) {
return $this->processError('API'); return $this->throwException('API');
} }
foreach($response->data as $list) { foreach($response->data as $list) {
@ -45,19 +45,16 @@ class MailChimp {
); );
} }
return array( return $lists;
'result' => true,
'data' => $lists
);
} }
function getSubscribers($lists = array()) { function getSubscribers($lists = array()) {
if(!$this->api_key || !$this->data_center) { if(!$this->api_key || !$this->data_center) {
return $this->processError('API'); return $this->throwException('API');
} }
if(!$lists) { if(!$lists) {
return $this->processError('lists'); return $this->throwException('lists');
} }
$bytes_fetched = 0; $bytes_fetched = 0;
@ -65,7 +62,7 @@ class MailChimp {
$url = sprintf($this->export_url, $this->data_center, $this->api_key, $list); $url = sprintf($this->export_url, $this->data_center, $this->api_key, $list);
$connection = @fopen($url, 'r'); $connection = @fopen($url, 'r');
if(!$connection) { if(!$connection) {
return $this->processError('connection'); return $this->throwException('connection');
} }
$i = 0; $i = 0;
$header = array(); $header = array();
@ -76,13 +73,13 @@ class MailChimp {
if($i === 0) { if($i === 0) {
$header = $obj; $header = $obj;
if(is_object($header) && isset($header->error)) { if(is_object($header) && isset($header->error)) {
return $this->processError('lists'); return $this->throwException('lists');
} }
if(!isset($header_hash)) { if(!isset($header_hash)) {
$header_hash = md5(implode(',', $header)); $header_hash = md5(implode(',', $header));
} else { } else {
if(md5(implode(',', $header) !== $header_hash)) { if(md5(implode(',', $header) !== $header_hash)) {
return $this->processError('headers'); return $this->throwException('headers');
} }
} }
} else { } else {
@ -92,25 +89,22 @@ class MailChimp {
} }
$bytes_fetched += strlen($buffer); $bytes_fetched += strlen($buffer);
if($bytes_fetched > $this->max_post_size) { if($bytes_fetched > $this->max_post_size) {
return $this->processError('size'); return $this->throwException('size');
} }
} }
fclose($connection); fclose($connection);
} }
if(!count($subscribers)) { if(!count($subscribers)) {
return $this->processError('subscribers'); return $this->throwException('subscribers');
} }
return array( return array(
'result' => true,
'data' => array(
'subscribers' => $subscribers, 'subscribers' => $subscribers,
'invalid' => false, 'invalid' => false,
'duplicate' => false, 'duplicate' => false,
'header' => $header, 'header' => $header,
'subscribersCount' => count($subscribers) 'subscribersCount' => count($subscribers)
)
); );
} }
@ -125,7 +119,7 @@ class MailChimp {
return (preg_match('/[a-zA-Z0-9]{32}-[a-zA-Z0-9]{3,}/', $APIKey)) ? $APIKey : false; return (preg_match('/[a-zA-Z0-9]{32}-[a-zA-Z0-9]{3,}/', $APIKey)) ? $APIKey : false;
} }
function processError($error) { function throwException($error) {
switch($error) { switch($error) {
case 'API': case 'API':
$errorMessage = __('Invalid API Key.'); $errorMessage = __('Invalid API Key.');
@ -146,9 +140,6 @@ class MailChimp {
$errorMessage = __('Did not find any valid lists'); $errorMessage = __('Did not find any valid lists');
break; break;
} }
return array( throw new \Exception($errorMessage);
'result' => false,
'errors' => array($errorMessage)
);
} }
} }