You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
377 lines
17 KiB
377 lines
17 KiB
<?php
|
|
|
|
namespace Zitec\RuleEngineBundle\Command;
|
|
|
|
use App\Entity\Respuestas;
|
|
use App\Entity\RespuestasHistoricas;
|
|
use App\Entity\MailLogger;
|
|
use FOS\UserBundle\Model\UserManagerInterface;
|
|
use Sonata\UserBundle\GoogleAuthenticator\Helper;
|
|
use Sonata\UserBundle\Model\UserInterface;
|
|
use Symfony\Component\Console\Command\Command as ContainerAwareCommand;
|
|
use Symfony\Component\Console\Input\InputArgument;
|
|
use Symfony\Component\Console\Input\InputInterface;
|
|
use Symfony\Component\Console\Input\InputOption;
|
|
use Symfony\Component\Console\Output\OutputInterface;
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
|
use Zitec\RuleEngineBundle\Entity\Rule;
|
|
use Symfony\Component\PropertyAccess\PropertyAccess;
|
|
use \Swift_Message;
|
|
use Symfony\Component\DependencyInjection\ContainerInterface;
|
|
class ActionProcessorCommand extends ContainerAwareCommand
|
|
{
|
|
|
|
private $em;
|
|
private $trueActions=[];
|
|
private $falseActions=[];
|
|
private $proceso;
|
|
private $tarea;
|
|
private $condition;
|
|
private $pregunta;
|
|
private $respuesta;
|
|
private $usuario;
|
|
public $output;
|
|
public $mailer;
|
|
|
|
public function __construct(EntityManagerInterface $em, ContainerInterface $container, \Swift_Mailer $mailer)
|
|
{
|
|
parent::__construct();
|
|
$this->em = $em;
|
|
$this->templating = $container->get('templating');
|
|
$this->mailer=$mailer;
|
|
}
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public function configure(): void
|
|
{
|
|
$this->setName('zitec:action:execute');
|
|
$this->addArgument(
|
|
'action',
|
|
InputArgument::REQUIRED,
|
|
'Actions to execute'
|
|
);
|
|
$this->addArgument(
|
|
'condition',
|
|
InputArgument::REQUIRED,
|
|
'Condition true or false'
|
|
);
|
|
$this->addArgument(
|
|
'userid',
|
|
InputArgument::REQUIRED,
|
|
'User Identifier'
|
|
);
|
|
$this->setDescription(
|
|
'Execute actions passed'
|
|
);
|
|
}
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public function execute(InputInterface $input, OutputInterface $output): int
|
|
{
|
|
//Get EntityManager
|
|
$this->output=$output;
|
|
$this->usuario = $this->em->getRepository('App:Licitador')
|
|
->findOneById($input->getArgument('userid'));
|
|
|
|
if(empty($this->usuario)){
|
|
$this->output->writeln(json_encode(array('error'=>'Usuario no existe')));
|
|
exit(-1);
|
|
}
|
|
// echo $input->getArgument('action');
|
|
$prepost="Postcondicion";
|
|
$rule = $this->em->getRepository('App:Postcondition')
|
|
->findOneById((int)$input->getArgument('action'));
|
|
if(empty($rule)){
|
|
$prepost="Precondicion";
|
|
$rule = $this->em->getRepository('App:Precondition')
|
|
->findOneById((int)$input->getArgument('action'));
|
|
}
|
|
if(empty($rule)){
|
|
$prepost="Regla";
|
|
$rule = $this->em->getRepository('App:Rules')
|
|
->findOneById($input->getArgument('action'));
|
|
}
|
|
if(empty($rule)){
|
|
$this->output->writeln(json_encode(array('error'=>'La regla no existe')));
|
|
exit(-1);
|
|
}
|
|
$acciones=json_decode($rule->getAction(), true);
|
|
$prepost='';
|
|
if($input->getArgument('condition')==='true' or $input->getArgument('condition')==='false'){
|
|
$this->condition=$input->getArgument('condition');
|
|
|
|
}else{
|
|
$this->output->writeln(json_encode(array('error'=>'Valor de la condicion invalida')));
|
|
exit(-1);
|
|
}
|
|
$this->tarea = $rule->getTarea();
|
|
$this->proceso = $this->tarea->getProcesosId();
|
|
|
|
//Divide actions between true or false
|
|
$this->parseActions($acciones);
|
|
|
|
//Execute actions dates
|
|
|
|
// $output->writeln([
|
|
// sprintf('<info>Actions</info> : %s', $input->getArgument('action')),
|
|
// sprintf('<info>Condition</info> : %s', $input->getArgument('condition')),
|
|
// sprintf('<info>UserId</info> : %s', $input->getArgument('userid')),
|
|
// sprintf('<info>RuleId</info> : %s', $rule->getId()),
|
|
// sprintf('<info>TareaId</info> : %s', $this->tarea->getId()),
|
|
// ]);
|
|
return 0;
|
|
}
|
|
public function parseActions($acciones){
|
|
foreach($acciones as $accion){
|
|
if($accion['condicion']==='true'){
|
|
$this->trueActions[]=$accion;
|
|
}else{
|
|
$this->falseActions[]=$accion;
|
|
}
|
|
}
|
|
// echo $this->condition;
|
|
if($this->condition==='true'){
|
|
$this->executeTrueActions();
|
|
}else{
|
|
$this->executeFalseActions();
|
|
}
|
|
}
|
|
public function executeTrueActions()
|
|
{
|
|
$asignacion=[];
|
|
foreach($this->trueActions as $action){
|
|
if($action['tipo']==='asignacion'){
|
|
// echo $action['campo'];
|
|
if(!isset($asignacion[$action['campo']])) $asignacion[$action['campo']]=[];
|
|
$asignacion[$action['campo']][]=$action['valor'];
|
|
}
|
|
}
|
|
foreach($this->trueActions as $action){
|
|
if($action['tipo']==='asignacion'){
|
|
$this->makeAsignation($action['entidades'], $action['campo'], $asignacion[$action['campo']]);
|
|
}elseif($action['tipo']==='redireccion'){
|
|
$this->returnRedirection($action['entidades'],$action['valor']);
|
|
}elseif($action['tipo']==='sendmail'){
|
|
$this->sendMail($action['entidades'],$action['campo'],$action['valor']);
|
|
}elseif($action['tipo']==='calendarevent'){
|
|
$this->calendarEvent($action['entidades'],$action['valor']);
|
|
}
|
|
}
|
|
}
|
|
public function executeFalseActions()
|
|
{
|
|
$asignacion=[];
|
|
$mailerReceivers=[];
|
|
foreach($this->falseActions as $action){
|
|
if($action['tipo']==='asignacion'){
|
|
if(!isset($asignacion[$action['campo']])) $asignacion[$action['campo']]=[];
|
|
$asignacion[$action['campo']][]=$action['valor']."\n";
|
|
}
|
|
}
|
|
foreach($this->falseActions as $action){
|
|
if($action['tipo']==='asignacion'){
|
|
$this->makeAsignation($action['entidades'], $action['campo'], $asignacion[$action['campo']]);
|
|
}elseif($action['tipo']==='redireccion'){
|
|
$this->returnRedirection($action['entidades'],$action['valor']);
|
|
}elseif($action['tipo']==='sendmail'){
|
|
$this->sendMail($action['entidades'],$action['campo'],$action['valor']);
|
|
}elseif($action['tipo']==='calendarevent'){
|
|
$this->calendarEvent($action['entidades'],$action['valor']);
|
|
}
|
|
}
|
|
}
|
|
// TODO revisar el salto de linea de las respuestas
|
|
public function makeAsignation($entity, $field, $value){
|
|
// $entidad=$this->getEntidad($entity);
|
|
switch($entity){
|
|
case 'preguntas':
|
|
$target=$this->em->getRepository('App:Preguntas')->findOneById($field);
|
|
$source=$this->em->getRepository('App:Preguntas')->findById($value);
|
|
$respuestaFuente = $this->em->getRepository('App:Respuestas')
|
|
->findBy(['preguntas'=>$source,'greenEntrepreneur'=> $this->usuario ]);
|
|
// @TODO: gestionar en activos
|
|
// if(empty($respuestaFuente)) {
|
|
// $this->output->writeln(json_encode(array('error'=>'Respuesta/s Origen no existe')));
|
|
// exit(-1);
|
|
// }
|
|
$respuestacomplex='';
|
|
foreach($respuestaFuente as $respf){
|
|
$respuestacomplex.=$respf->getValor()."\n";
|
|
}
|
|
// echo $respuestacomplex;
|
|
$repuestaAnterior = $this->em->getRepository('App:Respuestas')
|
|
->findOneBy(['preguntas'=>$target,'greenEntrepreneur'=> $this->usuario ]);
|
|
if($repuestaAnterior){
|
|
$repuestaAnterior->setPreguntas($target);
|
|
$repuestaAnterior->setValor( $respuestacomplex);
|
|
$repuestaAnterior->setFecha(\DateTime::createFromFormat('Y-m-d H:i:s',date('Y-m-d H:i:s')));
|
|
$respuesta=$repuestaAnterior;
|
|
}else{
|
|
$respuesta=new Respuestas();
|
|
$respuesta->setPreguntas($target);
|
|
$respuesta->setValor( $respuestacomplex);
|
|
$respuesta->setFecha(\DateTime::createFromFormat('Y-m-d H:i:s',date('Y-m-d H:i:s')));
|
|
$respuesta->setGreenEntrepreneur($this->usuario);
|
|
}
|
|
$this->em->persist($respuesta);
|
|
$this->em->flush();
|
|
if($respuesta){
|
|
$respuestaHistorica=new RespuestasHistoricas();
|
|
$respuestaHistorica->setValor($respuesta->getValor());
|
|
$respuestaHistorica->setFecha(\DateTime::createFromFormat('Y-m-d H:i:s',date('Y-m-d H:i:s')));
|
|
$respuestaHistorica->setRespuestas($respuesta);
|
|
$this->em->persist($respuestaHistorica);
|
|
|
|
}
|
|
$this->em->flush();
|
|
}
|
|
// $accessor = PropertyAccess::createPropertyAccessor();
|
|
// if ($accessor->isWritable($entidad, $field)) {
|
|
// $accessor->setValue($entidad, $field, $value);
|
|
// } else {
|
|
// throw new \Exception('fieldName is not writable');
|
|
// }
|
|
}
|
|
public function returnRedirection($entidad,$value){
|
|
|
|
$route='';
|
|
switch($entidad){
|
|
case 'tareas': $route='admin.procesos.realizartarea';break;
|
|
case 'procesos':$route='admin.procesos.listartareas';break;
|
|
}
|
|
$this->output->writeln(json_encode(array("route"=>$route, "id"=>$value)));
|
|
|
|
|
|
//return $value;
|
|
}
|
|
public function sendMail($entity,$from="info@theswitcherstoolbox.com",$to=null){
|
|
$respuestas=[];
|
|
switch($entity) {
|
|
case 'email':
|
|
$target=$this->em->getRepository('App:Preguntas')->findOneById((int)$to);
|
|
if(!$target->getTarea()->isSendable()){
|
|
$this->output->writeln(json_encode(array('error'=>'Tarea no es enviable')));
|
|
exit(-1);
|
|
}
|
|
$preguntas = $target->getTarea()->getPreguntasId();
|
|
|
|
$mapPreguntas=[];
|
|
foreach($preguntas as $pregunta){
|
|
$mapPreguntas[]=$pregunta->getId();
|
|
}
|
|
if($this->usuario->getType()=='green_entrepreneur'){
|
|
$respuestasRepo = $this->em->getRepository('App:Respuestas')
|
|
->findBy(['preguntas'=>$mapPreguntas, 'greenEntrepreneur'=> $this->usuario->getId()]);
|
|
//userdashboard\realizar_tarea.html.twig
|
|
foreach($respuestasRepo as $respuestaitem){
|
|
$respuestas[$respuestaitem->getPreguntas()->getAlias()]=$respuestaitem->getValor();
|
|
}
|
|
$respuestasArray=[];
|
|
if($target->getTarea()->getRepetible()==true){
|
|
foreach($respuestas as $respuestaItem){
|
|
$respuestasArray[$respuestaItem->getPreguntas()->getId()]=json_decode($respuestaItem->getValor());
|
|
}
|
|
}
|
|
}else{
|
|
$respuestas=null;
|
|
$respuestasArray=null;
|
|
}
|
|
$respuesta = $this->em->getRepository('App:Respuestas')
|
|
->findOneBy(['preguntas'=>$target,'greenEntrepreneur'=> $this->usuario ]);
|
|
|
|
$resp=[];
|
|
if (strpos($respuesta->getValor(), '[')!==false || strpos($respuesta->getValor(), '{')!==false){
|
|
preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $respuesta->getValor(), $resp);
|
|
}else{
|
|
$resp=[$respuesta->getValor()];
|
|
}
|
|
print_r($resp,true);
|
|
|
|
$transport = new \Swift_SmtpTransport();
|
|
|
|
$transport->setHost('smtp.gmail.com')
|
|
->setEncryption('tls')
|
|
->setPort(587)
|
|
->setUsername('prometeo.tests')
|
|
->setPassword('#Pr0met3o&2019^');
|
|
|
|
//Creamos la instancia del envío
|
|
$this->mailer = new \Swift_Mailer($transport);
|
|
foreach($resp as $destinatario) {
|
|
$message = (new \Swift_Message('The Switchers Toolbox Email'))
|
|
->setFrom($from)
|
|
->setTo($destinatario)
|
|
->setBody(
|
|
$this->templating->render(
|
|
// templates/emails/registration.html.twig
|
|
$this->tarea->getTemplateId()->getEmailfilename(),
|
|
['tarea' => $this->tarea, 'respuestas' => $respuestas, 'user' => $this->usuario, 'email' => $destinatario]
|
|
),
|
|
'text/html'
|
|
)
|
|
|
|
// you can remove the following code if you don't define a text version for your emails
|
|
// ->addPart(
|
|
// $this->renderView(
|
|
// // templates/emails/registration.txt.twig
|
|
// 'emails/registration.txt.twig',
|
|
// ['name' => $name]
|
|
// ),
|
|
// 'text/plain'
|
|
// )
|
|
;
|
|
$errors = null;
|
|
if (!$this->mailer->send($message, $errors)) {
|
|
// Dump the log contents
|
|
// NOTE: The EchoLogger dumps in realtime so dump() does nothing for it. We use ArrayLogger instead.
|
|
$newlog = new MailLogger();
|
|
$newlog->setFrom($from);
|
|
$newlog->setTo(json_encode($resp, true));
|
|
$newlog->setType('mail');
|
|
$newlog->setMessage(json_encode($errors, true));
|
|
$this->output->writeln(json_encode(array('error' => 'Error de envio de email')));
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
public function calendarEvent($entity,$value){
|
|
switch($entity) {
|
|
case 'eventos':
|
|
$date=new \DateTime();
|
|
switch($value){
|
|
case 1: $date->add(new DateInterval('P15D'));break;
|
|
case 2: $date->add(new DateInterval('P1M'));break;
|
|
case 3: $date->add(new DateInterval('P2M'));break;
|
|
case 4: $date->add(new DateInterval('P4Y'));break;
|
|
}
|
|
$eventCalendar = new EventCalendar();
|
|
$eventCalendar->setBeginAt($date);
|
|
$eventCalendar->setAllDay(true);
|
|
$eventCalendar->setColor('green');
|
|
$eventCalendar->setEndAt($date);
|
|
$eventCalendar->setTitle($this->expediente->getNombre());
|
|
$em = $this->getDoctrine()->getManager();
|
|
try{
|
|
$em->persist($eventCalendar);
|
|
$em->flush();
|
|
}catch(\Exception $e){
|
|
$response[]=$e->getMessage();
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
public function getEntidad($entity){
|
|
switch($entity){
|
|
case 'proceso': return $this->proceso;
|
|
case 'tarea': return $this->tarea;
|
|
case 'preguntas':return $this->em->getRepository('App:Preguntas')->findAll();
|
|
case 'respuesta':return $this->tarea->getPreguntas()[0]->getRespuestas();
|
|
default:
|
|
throw new \Exception('Entity does not exists');
|
|
}
|
|
}
|
|
}
|