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

View File

@ -1,5 +1,7 @@
<?php
namespace MailPoet\API\Endpoints;
use \MailPoet\API\Endpoint as APIEndpoint;
use \MailPoet\API\Error as APIError;
use MailPoet\Subscribers\ImportExport\Import\MailChimp;
use MailPoet\Models\CustomField;
@ -7,42 +9,69 @@ use MailPoet\Models\Segment;
if(!defined('ABSPATH')) exit;
class ImportExport {
class ImportExport extends APIEndpoint {
function getMailChimpLists($data) {
try {
$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) {
try {
$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) {
$segment = Segment::createOrUpdate($data);
return (
($segment->id) ?
array(
'result' => true,
'segment' => $segment->asArray()
) :
array(
'result' => false
)
$errors = $segment->getErrors();
if(!empty($errors)) {
return $this->errorResponse($errors);
} else {
return $this->successResponse(
Segment::findOne($segment->id)->asArray()
);
}
}
function processImport($data) {
try {
$import = new \MailPoet\Subscribers\ImportExport\Import\Import(
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) {
try {
$export = new \MailPoet\Subscribers\ImportExport\Export\Export(
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 $created_at;
public $updated_at;
public $profiler_start;
public function __construct($data) {
$this->subscribers_data = $this->transformSubscribersData(
@ -40,7 +39,6 @@ class Import {
$this->subscribers_count = count(reset($this->subscribers_data));
$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->profiler_start = microtime(true);
}
function getSubscriberFieldsValidationRules($subscriber_fields) {
@ -92,10 +90,7 @@ class Import {
}
}
} catch(\PDOException $e) {
return array(
'result' => false,
'errors' => array($e->getMessage())
);
throw new \Exception($e->getMessage());
}
$import_factory = new ImportExportFactory('import');
$segments = $import_factory->getSegments();
@ -104,15 +99,11 @@ class Import {
Newsletter::getWelcomeNotificationsForSegments($this->segments) :
false;
return array(
'result' => true,
'data' => array(
'created' => count($created_subscribers),
'updated' => count($updated_subscribers),
'segments' => $segments,
'added_to_segment_with_welcome_notification' =>
($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() {
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');
if(!$connection) {
return $this->processError('connection');
return $this->throwException('connection');
} else {
$response = '';
while(!feof($connection)) {
@ -35,7 +35,7 @@ class MailChimp {
$response = json_decode($response);
if(!$response) {
return $this->processError('API');
return $this->throwException('API');
}
foreach($response->data as $list) {
@ -45,19 +45,16 @@ class MailChimp {
);
}
return array(
'result' => true,
'data' => $lists
);
return $lists;
}
function getSubscribers($lists = array()) {
if(!$this->api_key || !$this->data_center) {
return $this->processError('API');
return $this->throwException('API');
}
if(!$lists) {
return $this->processError('lists');
return $this->throwException('lists');
}
$bytes_fetched = 0;
@ -65,7 +62,7 @@ class MailChimp {
$url = sprintf($this->export_url, $this->data_center, $this->api_key, $list);
$connection = @fopen($url, 'r');
if(!$connection) {
return $this->processError('connection');
return $this->throwException('connection');
}
$i = 0;
$header = array();
@ -76,13 +73,13 @@ class MailChimp {
if($i === 0) {
$header = $obj;
if(is_object($header) && isset($header->error)) {
return $this->processError('lists');
return $this->throwException('lists');
}
if(!isset($header_hash)) {
$header_hash = md5(implode(',', $header));
} else {
if(md5(implode(',', $header) !== $header_hash)) {
return $this->processError('headers');
return $this->throwException('headers');
}
}
} else {
@ -92,25 +89,22 @@ class MailChimp {
}
$bytes_fetched += strlen($buffer);
if($bytes_fetched > $this->max_post_size) {
return $this->processError('size');
return $this->throwException('size');
}
}
fclose($connection);
}
if(!count($subscribers)) {
return $this->processError('subscribers');
return $this->throwException('subscribers');
}
return array(
'result' => true,
'data' => array(
'subscribers' => $subscribers,
'invalid' => false,
'duplicate' => false,
'header' => $header,
'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;
}
function processError($error) {
function throwException($error) {
switch($error) {
case 'API':
$errorMessage = __('Invalid API Key.');
@ -146,9 +140,6 @@ class MailChimp {
$errorMessage = __('Did not find any valid lists');
break;
}
return array(
'result' => false,
'errors' => array($errorMessage)
);
throw new \Exception($errorMessage);
}
}