Skip to content

Commit

Permalink
Merge branch 'maintenance/pim_beta1' into feature/invalid-item-handling
Browse files Browse the repository at this point in the history
  • Loading branch information
gquemener committed Oct 18, 2013
2 parents fbfc531 + 334dfa3 commit a2794c9
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 21 deletions.
47 changes: 43 additions & 4 deletions Command/BatchCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator;
use Symfony\Component\Validator\Constraints as Assert;
use Monolog\Handler\StreamHandler;
use Doctrine\ORM\EntityManager;
use Oro\Bundle\BatchBundle\Entity\JobExecution;
Expand All @@ -31,7 +32,20 @@ protected function configure()
->setDescription('Launch a registered job instance')
->addArgument('code', InputArgument::REQUIRED, 'Job instance code')
->addArgument('execution', InputArgument::OPTIONAL, 'Job execution id')
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Override job configuration (formatted as json. ie: php app/console oro:batch:job -c \'[{"reader":{"filePath":"/tmp/foo.csv"}}]\' acme_product_import)');
->addOption(
'config',
'c',
InputOption::VALUE_REQUIRED,
'Override job configuration (formatted as json. ie: ' .
'php app/console oro:batch:job -c \'[{"reader":{"filePath":"/tmp/foo.csv"}}]\' ' .
'acme_product_import)'
)
->addOption(
'email',
null,
InputOption::VALUE_REQUIRED,
'The email to notify at the end of the job execution'
);
}

/**
Expand Down Expand Up @@ -62,17 +76,34 @@ protected function execute(InputInterface $input, OutputInterface $output)
);
}

$errors = $this->getValidator()->validate($jobInstance, array('Default', 'Execution'));
$validator = $this->getValidator();

// Override mail notifier recipient email
if ($email = $input->getOption('email')) {
$errors = $validator->validateValue($email, new Assert\Email());
if (count($errors) > 0) {
throw new \RuntimeException(
sprintf('Email "%s" is invalid: %s', $email, $this->getErrorMessages($errors))
);
}
$this
->getMailNotifier()
->setRecipientEmail($email);
}

$errors = $validator->validate($jobInstance, array('Default', 'Execution'));
if (count($errors) > 0) {
throw new \RuntimeException(sprintf('Job "%s" is invalid: %s', $code, $this->getErrorMessages($errors)));
throw new \RuntimeException(
sprintf('Job "%s" is invalid: %s', $code, $this->getErrorMessages($errors))
);
}

$executionId = $input->getArgument('execution');
if ($executionId) {
$jobExecution = $this->getEntityManager()->getRepository('OroBatchBundle:JobExecution')->find($executionId);
if (!$jobExecution) {
throw new \InvalidArgumentException(sprintf('Could not find job execution "%s".', $id));
}
}
if (!$jobExecution->getStatus()->isStarting()) {
throw new \RuntimeException(
sprintf('Job execution "%s" has invalid status: %s', $executionId, $jobExecution->getStatus())
Expand Down Expand Up @@ -124,6 +155,14 @@ protected function getValidator()
return $this->getContainer()->get('validator');
}

/**
* @return Validator
*/
protected function getMailNotifier()
{
return $this->getContainer()->get('oro_batch.mail_notifier');
}

/**
* @return \Oro\Bundle\BatchBundle\Connector\ConnectorRegistry
*/
Expand Down
1 change: 1 addition & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public function getConfigTreeBuilder()

$root
->children()
->booleanNode('enable_mail_notification')->defaultFalse()->end()
->scalarNode('sender_email')->defaultValue('[email protected]')->end()
->end()
->end();
Expand Down
5 changes: 5 additions & 0 deletions DependencyInjection/OroBatchExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,10 @@ public function load(array $configs, ContainerBuilder $container)
$loader->load('services.yml');

$container->setParameter('oro_batch.mail_notifier.sender_email', $config['sender_email']);
if ($config['enable_mail_notification']) {
$container
->getDefinition('oro_batch.mail_notifier')
->addTag('oro_batch.notifier');
}
}
}
35 changes: 28 additions & 7 deletions Notification/MailNotifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ class MailNotifier implements Notifier
*/
protected $senderEmail;

/**
* @var string $recipientEmail
*/
protected $recipientEmail;

/**
* @param BatchLogHandler $logger
* @param SecurityContextInterface $securityContext
Expand All @@ -58,18 +63,30 @@ public function __construct(
$this->senderEmail = $senderEmail;
}

/**
* Set the recipient email
*
* @param string $recipientEmail
*
* @return MailNotifier
*/
public function setRecipientEmail($recipientEmail)
{
$this->recipientEmail = $recipientEmail;

return $this;
}

/**
* {@inheritdoc}
*/
public function notify(JobExecution $jobExecution)
{
$user = $this->getUser();
if (!$user) {
if (null === $email = $this->getEmail()) {
return;
}

$parameters = array(
'user' => $user,
'jobExecution' => $jobExecution,
'log' => $this->logger->getFilename(),
);
Expand All @@ -80,7 +97,7 @@ public function notify(JobExecution $jobExecution)
$message = $this->mailer->createMessage();
$message->setSubject('Job has been executed');
$message->setFrom($this->senderEmail);
$message->setTo($user->getEmail());
$message->setTo($email);
$message->setBody($txtBody, 'text/plain');
$message->addPart($htmlBody, 'text/html');

Expand All @@ -90,10 +107,14 @@ public function notify(JobExecution $jobExecution)
/**
* Get the current authenticated user
*
* @return null|UserInterface
* @return null|string
*/
private function getUser()
private function getEmail()
{
if ($this->recipientEmail) {
return $this->recipientEmail;
}

if (null === $token = $this->securityContext->getToken()) {
return;
}
Expand All @@ -102,6 +123,6 @@ private function getUser()
return;
}

return $user;
return $user->getEmail();
}
}
3 changes: 0 additions & 3 deletions Resources/config/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,6 @@ services:
- @twig
- @mailer
- %oro_batch.mail_notifier.sender_email%
# There is no need to send email on each job
# tags:
# - { name: oro_batch.notifier }

oro_batch.step_factory:
class: %oro_batch.step_factory.class%
Expand Down
2 changes: 0 additions & 2 deletions Resources/views/Mails/notification.html.twig
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
<p>{{ user.firstName }} {{ user.lastName }},</p>

<p>
Akeneo successfully completed your batch {{ jobExecution.jobInstance.type }}.<br />
<br />
Expand Down
4 changes: 1 addition & 3 deletions Resources/views/Mails/notification.txt.twig
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
{{ user.firstName }} {{ user.lastName }},

Akeneo successfully completed your batch {{ jobExecution.jobInstance.type }}.

Started on {{ jobExecution.startTime|date("Y-m-d") }} at {{ jobExecution.startTime|date("H:i:s") }}.
Expand All @@ -12,5 +10,5 @@ Results:
- {{ stepExecution.writeCount }} item(s) written
{% endfor %}

--
--
Oro Platform
2 changes: 1 addition & 1 deletion Tests/Unit/Job/JobTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ public function testAddStep()
$this->job->addStep('name1', $mockStep1);
$this->job->addStep('name2', $mockStep2);

$this->assertEquals(array('name1' => $mockStep1, 'name2' => $mockStep2), $this->job->getSteps());
$this->assertEquals(array($mockStep1, $mockStep2), $this->job->getSteps());
}

public function testSetSteps()
Expand Down
58 changes: 57 additions & 1 deletion Tests/Unit/Notification/MailNotifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ public function testNotifyWithLoggedInUserEmail()

$jobExecution = $this->getDisabledConstructorMock('Oro\Bundle\BatchBundle\Entity\JobExecution');
$parameters = array(
'user' => $user,
'jobExecution' => $jobExecution,
'log' => '/tmp/foo.log',
);
Expand Down Expand Up @@ -102,6 +101,63 @@ public function testNotifyWithLoggedInUserEmail()
$this->notifier->notify($jobExecution);
}

public function testNotifyIfRecipientEmailIsSet()
{
$this->handler
->expects($this->once())
->method('getFilename')
->will($this->returnValue('/tmp/foo.log'));

$jobExecution = $this->getDisabledConstructorMock('Oro\Bundle\BatchBundle\Entity\JobExecution');
$parameters = array(
'jobExecution' => $jobExecution,
'log' => '/tmp/foo.log',
);
$this->twig
->expects($this->exactly(2))
->method('render')
->will(
$this->returnValueMap(
array(
array('OroBatchBundle:Mails:notification.txt.twig', $parameters, 'notification'),
array('OroBatchBundle:Mails:notification.html.twig', $parameters, '<p>notification</p>'),
)
)
);

$message = $this->getDisabledConstructorMock('\Swift_Message');
$this->mailer
->expects($this->once())
->method('createMessage')
->will($this->returnValue($message));

$message->expects($this->once())
->method('setSubject')
->with('Job has been executed');

$message->expects($this->once())
->method('setFrom')
->with('[email protected]');

$message->expects($this->once())
->method('setTo')
->with('[email protected]');
$message->expects($this->once())
->method('setBody')
->with('notification', 'text/plain');
$message->expects($this->once())
->method('addPart')
->with('<p>notification</p>', 'text/html');

$this->mailer
->expects($this->once())
->method('send')
->with($message);

$this->notifier->setRecipientEmail('[email protected]');
$this->notifier->notify($jobExecution);
}

public function testDoNotNotifyIfNoUserLoggedIn()
{
$token = $this->getTokenMock(null);
Expand Down

0 comments on commit a2794c9

Please sign in to comment.