Licitator 1.0
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

5 years ago
5 years ago
  1. <?php
  2. namespace Zitec\RuleEngineBundle\Command;
  3. use App\Entity\Respuestas;
  4. use App\Entity\RespuestasHistoricas;
  5. use App\Entity\MailLogger;
  6. use FOS\UserBundle\Model\UserManagerInterface;
  7. use Sonata\UserBundle\GoogleAuthenticator\Helper;
  8. use Sonata\UserBundle\Model\UserInterface;
  9. use Symfony\Component\Console\Command\Command as ContainerAwareCommand;
  10. use Symfony\Component\Console\Input\InputArgument;
  11. use Symfony\Component\Console\Input\InputInterface;
  12. use Symfony\Component\Console\Input\InputOption;
  13. use Symfony\Component\Console\Output\OutputInterface;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Zitec\RuleEngineBundle\Entity\Rule;
  17. use Symfony\Component\PropertyAccess\PropertyAccess;
  18. use \Swift_Message;
  19. use Symfony\Component\DependencyInjection\ContainerInterface;
  20. class ActionProcessorCommand extends ContainerAwareCommand
  21. {
  22. private $em;
  23. private $trueActions=[];
  24. private $falseActions=[];
  25. private $proceso;
  26. private $tarea;
  27. private $condition;
  28. private $pregunta;
  29. private $respuesta;
  30. private $usuario;
  31. public $output;
  32. public $mailer;
  33. public function __construct(EntityManagerInterface $em, ContainerInterface $container, \Swift_Mailer $mailer)
  34. {
  35. parent::__construct();
  36. $this->em = $em;
  37. $this->templating = $container->get('templating');
  38. $this->mailer=$mailer;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function configure(): void
  44. {
  45. $this->setName('zitec:action:execute');
  46. $this->addArgument(
  47. 'action',
  48. InputArgument::REQUIRED,
  49. 'Actions to execute'
  50. );
  51. $this->addArgument(
  52. 'condition',
  53. InputArgument::REQUIRED,
  54. 'Condition true or false'
  55. );
  56. $this->addArgument(
  57. 'userid',
  58. InputArgument::REQUIRED,
  59. 'User Identifier'
  60. );
  61. $this->setDescription(
  62. 'Execute actions passed'
  63. );
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function execute(InputInterface $input, OutputInterface $output): int
  69. {
  70. //Get EntityManager
  71. $this->output=$output;
  72. $this->usuario = $this->em->getRepository('App:Licitador')
  73. ->findOneById($input->getArgument('userid'));
  74. if(empty($this->usuario)){
  75. $this->output->writeln(json_encode(array('error'=>'Usuario no existe')));
  76. exit(-1);
  77. }
  78. // echo $input->getArgument('action');
  79. $prepost="Postcondicion";
  80. $rule = $this->em->getRepository('App:Postcondition')
  81. ->findOneById((int)$input->getArgument('action'));
  82. if(empty($rule)){
  83. $prepost="Precondicion";
  84. $rule = $this->em->getRepository('App:Precondition')
  85. ->findOneById((int)$input->getArgument('action'));
  86. }
  87. if(empty($rule)){
  88. $prepost="Regla";
  89. $rule = $this->em->getRepository('App:Rules')
  90. ->findOneById($input->getArgument('action'));
  91. }
  92. if(empty($rule)){
  93. $this->output->writeln(json_encode(array('error'=>'La regla no existe')));
  94. exit(-1);
  95. }
  96. $acciones=json_decode($rule->getAction(), true);
  97. $prepost='';
  98. if($input->getArgument('condition')==='true' or $input->getArgument('condition')==='false'){
  99. $this->condition=$input->getArgument('condition');
  100. }else{
  101. $this->output->writeln(json_encode(array('error'=>'Valor de la condicion invalida')));
  102. exit(-1);
  103. }
  104. $this->tarea = $rule->getTarea();
  105. $this->proceso = $this->tarea->getProcesosId();
  106. //Divide actions between true or false
  107. $this->parseActions($acciones);
  108. //Execute actions dates
  109. // $output->writeln([
  110. // sprintf('<info>Actions</info> : %s', $input->getArgument('action')),
  111. // sprintf('<info>Condition</info> : %s', $input->getArgument('condition')),
  112. // sprintf('<info>UserId</info> : %s', $input->getArgument('userid')),
  113. // sprintf('<info>RuleId</info> : %s', $rule->getId()),
  114. // sprintf('<info>TareaId</info> : %s', $this->tarea->getId()),
  115. // ]);
  116. return 0;
  117. }
  118. public function parseActions($acciones){
  119. foreach($acciones as $accion){
  120. if($accion['condicion']==='true'){
  121. $this->trueActions[]=$accion;
  122. }else{
  123. $this->falseActions[]=$accion;
  124. }
  125. }
  126. // echo $this->condition;
  127. if($this->condition==='true'){
  128. $this->executeTrueActions();
  129. }else{
  130. $this->executeFalseActions();
  131. }
  132. }
  133. public function executeTrueActions()
  134. {
  135. $asignacion=[];
  136. foreach($this->trueActions as $action){
  137. if($action['tipo']==='asignacion'){
  138. // echo $action['campo'];
  139. if(!isset($asignacion[$action['campo']])) $asignacion[$action['campo']]=[];
  140. $asignacion[$action['campo']][]=$action['valor'];
  141. }
  142. }
  143. foreach($this->trueActions as $action){
  144. if($action['tipo']==='asignacion'){
  145. $this->makeAsignation($action['entidades'], $action['campo'], $asignacion[$action['campo']]);
  146. }elseif($action['tipo']==='redireccion'){
  147. $this->returnRedirection($action['entidades'],$action['valor']);
  148. }elseif($action['tipo']==='sendmail'){
  149. $this->sendMail($action['entidades'],$action['campo'],$action['valor']);
  150. }elseif($action['tipo']==='calendarevent'){
  151. $this->calendarEvent($action['entidades'],$action['valor']);
  152. }
  153. }
  154. }
  155. public function executeFalseActions()
  156. {
  157. $asignacion=[];
  158. $mailerReceivers=[];
  159. foreach($this->falseActions as $action){
  160. if($action['tipo']==='asignacion'){
  161. if(!isset($asignacion[$action['campo']])) $asignacion[$action['campo']]=[];
  162. $asignacion[$action['campo']][]=$action['valor']."\n";
  163. }
  164. }
  165. foreach($this->falseActions as $action){
  166. if($action['tipo']==='asignacion'){
  167. $this->makeAsignation($action['entidades'], $action['campo'], $asignacion[$action['campo']]);
  168. }elseif($action['tipo']==='redireccion'){
  169. $this->returnRedirection($action['entidades'],$action['valor']);
  170. }elseif($action['tipo']==='sendmail'){
  171. $this->sendMail($action['entidades'],$action['campo'],$action['valor']);
  172. }elseif($action['tipo']==='calendarevent'){
  173. $this->calendarEvent($action['entidades'],$action['valor']);
  174. }
  175. }
  176. }
  177. // TODO revisar el salto de linea de las respuestas
  178. public function makeAsignation($entity, $field, $value){
  179. // $entidad=$this->getEntidad($entity);
  180. switch($entity){
  181. case 'preguntas':
  182. $target=$this->em->getRepository('App:Preguntas')->findOneById($field);
  183. $source=$this->em->getRepository('App:Preguntas')->findById($value);
  184. $respuestaFuente = $this->em->getRepository('App:Respuestas')
  185. ->findBy(['preguntas'=>$source,'greenEntrepreneur'=> $this->usuario ]);
  186. // @TODO: gestionar en activos
  187. // if(empty($respuestaFuente)) {
  188. // $this->output->writeln(json_encode(array('error'=>'Respuesta/s Origen no existe')));
  189. // exit(-1);
  190. // }
  191. $respuestacomplex='';
  192. foreach($respuestaFuente as $respf){
  193. $respuestacomplex.=$respf->getValor()."\n";
  194. }
  195. // echo $respuestacomplex;
  196. $repuestaAnterior = $this->em->getRepository('App:Respuestas')
  197. ->findOneBy(['preguntas'=>$target,'greenEntrepreneur'=> $this->usuario ]);
  198. if($repuestaAnterior){
  199. $repuestaAnterior->setPreguntas($target);
  200. $repuestaAnterior->setValor( $respuestacomplex);
  201. $repuestaAnterior->setFecha(\DateTime::createFromFormat('Y-m-d H:i:s',date('Y-m-d H:i:s')));
  202. $respuesta=$repuestaAnterior;
  203. }else{
  204. $respuesta=new Respuestas();
  205. $respuesta->setPreguntas($target);
  206. $respuesta->setValor( $respuestacomplex);
  207. $respuesta->setFecha(\DateTime::createFromFormat('Y-m-d H:i:s',date('Y-m-d H:i:s')));
  208. $respuesta->setGreenEntrepreneur($this->usuario);
  209. }
  210. $this->em->persist($respuesta);
  211. $this->em->flush();
  212. if($respuesta){
  213. $respuestaHistorica=new RespuestasHistoricas();
  214. $respuestaHistorica->setValor($respuesta->getValor());
  215. $respuestaHistorica->setFecha(\DateTime::createFromFormat('Y-m-d H:i:s',date('Y-m-d H:i:s')));
  216. $respuestaHistorica->setRespuestas($respuesta);
  217. $this->em->persist($respuestaHistorica);
  218. }
  219. $this->em->flush();
  220. }
  221. // $accessor = PropertyAccess::createPropertyAccessor();
  222. // if ($accessor->isWritable($entidad, $field)) {
  223. // $accessor->setValue($entidad, $field, $value);
  224. // } else {
  225. // throw new \Exception('fieldName is not writable');
  226. // }
  227. }
  228. public function returnRedirection($entidad,$value){
  229. $route='';
  230. switch($entidad){
  231. case 'tareas': $route='admin.procesos.realizartarea';break;
  232. case 'procesos':$route='admin.procesos.listartareas';break;
  233. }
  234. $this->output->writeln(json_encode(array("route"=>$route, "id"=>$value)));
  235. //return $value;
  236. }
  237. public function sendMail($entity,$from="info@theswitcherstoolbox.com",$to=null){
  238. $respuestas=[];
  239. switch($entity) {
  240. case 'email':
  241. $target=$this->em->getRepository('App:Preguntas')->findOneById((int)$to);
  242. if(!$target->getTarea()->isSendable()){
  243. $this->output->writeln(json_encode(array('error'=>'Tarea no es enviable')));
  244. exit(-1);
  245. }
  246. $preguntas = $target->getTarea()->getPreguntasId();
  247. $mapPreguntas=[];
  248. foreach($preguntas as $pregunta){
  249. $mapPreguntas[]=$pregunta->getId();
  250. }
  251. if($this->usuario->getType()=='green_entrepreneur'){
  252. $respuestasRepo = $this->em->getRepository('App:Respuestas')
  253. ->findBy(['preguntas'=>$mapPreguntas, 'greenEntrepreneur'=> $this->usuario->getId()]);
  254. //userdashboard\realizar_tarea.html.twig
  255. foreach($respuestasRepo as $respuestaitem){
  256. $respuestas[$respuestaitem->getPreguntas()->getAlias()]=$respuestaitem->getValor();
  257. }
  258. $respuestasArray=[];
  259. if($target->getTarea()->getRepetible()==true){
  260. foreach($respuestas as $respuestaItem){
  261. $respuestasArray[$respuestaItem->getPreguntas()->getId()]=json_decode($respuestaItem->getValor());
  262. }
  263. }
  264. }else{
  265. $respuestas=null;
  266. $respuestasArray=null;
  267. }
  268. $respuesta = $this->em->getRepository('App:Respuestas')
  269. ->findOneBy(['preguntas'=>$target,'greenEntrepreneur'=> $this->usuario ]);
  270. $resp=[];
  271. if (strpos($respuesta->getValor(), '[')!==false || strpos($respuesta->getValor(), '{')!==false){
  272. preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $respuesta->getValor(), $resp);
  273. }else{
  274. $resp=[$respuesta->getValor()];
  275. }
  276. print_r($resp,true);
  277. $transport = new \Swift_SmtpTransport();
  278. $transport->setHost('smtp.gmail.com')
  279. ->setEncryption('tls')
  280. ->setPort(587)
  281. ->setUsername('prometeo.tests')
  282. ->setPassword('#Pr0met3o&2019^');
  283. //Creamos la instancia del envío
  284. $this->mailer = new \Swift_Mailer($transport);
  285. foreach($resp as $destinatario) {
  286. $message = (new \Swift_Message('The Switchers Toolbox Email'))
  287. ->setFrom($from)
  288. ->setTo($destinatario)
  289. ->setBody(
  290. $this->templating->render(
  291. // templates/emails/registration.html.twig
  292. $this->tarea->getTemplateId()->getEmailfilename(),
  293. ['tarea' => $this->tarea, 'respuestas' => $respuestas, 'user' => $this->usuario, 'email' => $destinatario]
  294. ),
  295. 'text/html'
  296. )
  297. // you can remove the following code if you don't define a text version for your emails
  298. // ->addPart(
  299. // $this->renderView(
  300. // // templates/emails/registration.txt.twig
  301. // 'emails/registration.txt.twig',
  302. // ['name' => $name]
  303. // ),
  304. // 'text/plain'
  305. // )
  306. ;
  307. $errors = null;
  308. if (!$this->mailer->send($message, $errors)) {
  309. // Dump the log contents
  310. // NOTE: The EchoLogger dumps in realtime so dump() does nothing for it. We use ArrayLogger instead.
  311. $newlog = new MailLogger();
  312. $newlog->setFrom($from);
  313. $newlog->setTo(json_encode($resp, true));
  314. $newlog->setType('mail');
  315. $newlog->setMessage(json_encode($errors, true));
  316. $this->output->writeln(json_encode(array('error' => 'Error de envio de email')));
  317. }
  318. }
  319. break;
  320. }
  321. }
  322. public function calendarEvent($entity,$value){
  323. switch($entity) {
  324. case 'eventos':
  325. $date=new \DateTime();
  326. switch($value){
  327. case 1: $date->add(new DateInterval('P15D'));break;
  328. case 2: $date->add(new DateInterval('P1M'));break;
  329. case 3: $date->add(new DateInterval('P2M'));break;
  330. case 4: $date->add(new DateInterval('P4Y'));break;
  331. }
  332. $eventCalendar = new EventCalendar();
  333. $eventCalendar->setBeginAt($date);
  334. $eventCalendar->setAllDay(true);
  335. $eventCalendar->setColor('green');
  336. $eventCalendar->setEndAt($date);
  337. $eventCalendar->setTitle($this->expediente->getNombre());
  338. $em = $this->getDoctrine()->getManager();
  339. try{
  340. $em->persist($eventCalendar);
  341. $em->flush();
  342. }catch(\Exception $e){
  343. $response[]=$e->getMessage();
  344. }
  345. break;
  346. }
  347. }
  348. public function getEntidad($entity){
  349. switch($entity){
  350. case 'proceso': return $this->proceso;
  351. case 'tarea': return $this->tarea;
  352. case 'preguntas':return $this->em->getRepository('App:Preguntas')->findAll();
  353. case 'respuesta':return $this->tarea->getPreguntas()[0]->getRespuestas();
  354. default:
  355. throw new \Exception('Entity does not exists');
  356. }
  357. }
  358. }