<?php
namespace Blh\Bundle\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Workflow\Event\Event;
use Doctrine\ORM\EntityManagerInterface;
use Blh\Bundle\Handler\MailHandler;
use Blh\Bundle\Entity\Email;
use Blh\Bundle\Entity\Employee;
use Blh\Bundle\Repository\EmployeeRepository;
use Blh\Bundle\Entity\Position;
use Blh\Bundle\Entity\EntityContract;
class WorkflowLoggerSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
private MailHandler $mailHandler;
private ParameterBagInterface $parameters;
public function __construct(
EntityManagerInterface $entityManager,
MailHandler $mailHandler,
ParameterBagInterface $parameters
){
$this->parameters = $parameters;
$this->entityManager = $entityManager;
$this->mailHandler = $mailHandler;
}
public function onCompleted(Event $event): void
{
$this->sendNotificationEmail($event);
}
public function onCompletedVacation(Event $event): void
{
$this->sendAbsenceNotificationEmail($event);
}
private function sendNotificationEmail(Event $event): void
{
$emailToSend = $this->entityManager->getRepository(Email::class)->findOneBy([
'name' => 'workflow-'.$event->getWorkflowName().'-'.$event->getSubject()->getWorkflowStep()
]);
if(!isset($emailToSend)){
return;
}
$employee = $event->getSubject()->getContract()->getEmployee();
$typeMotive = $event->getSubject()->getprocessMotive()->getProcessType()->getId();
if(in_array($event->getSubject()->getContract()->getPosition()->getCode(), [Position::CODE_CM, Position::CODE_CC])){
$emailsForNotification = [ MailHandler::RECEIVER_TO => [ $employee->getImmediateBoss()->getCorporateEmail() ] ];
}else{
$emailsForNotification = [
MailHandler::RECEIVER_TO => array_merge(
$this->entityManager->getRepository(Employee::class)
->findEmployeePositionByEntity($event->getSubject()->getEntity(), Position::CODE_CM)
->map(fn($element) => $element->getContract()->getEmployee()->getCorporateEmail())
->toArray(),
$this->entityManager->getRepository(Employee::class)
->findEmployeePositionByEntity($event->getSubject()->getEntity(), Position::CODE_CC)
->map(fn($element) => $element->getContract()->getEmployee()->getCorporateEmail())
->toArray()
)
];
}
// if($employee->getCorporateEmail() !== null) $emailsForNotification[MailHandler::RECEIVER_TO][] = $employee->getCorporateEmail();
$subject = str_replace('{{employeeName}}', ucwords($employee->getFirstName().' '.$employee->getSurname()), $emailToSend->getSubject());
$dateProccessContract = ($typeMotive == 1 )?$event->getSubject()->getContract()->getStartDate(): $event->getSubject()->getContract()->getEndDate();
$subject = str_replace('{{date}}',$dateProccessContract->format('Y-m-d'), $subject );
$this->mailHandler->generateEmail(
//$emailToSend->setSubject(str_replace('{{employeeName}}', ucwords($employee->getFirstName().' '.$employee->getSurname()), $emailToSend->getSubject())),
$emailToSend->setSubject($subject),
$emailsForNotification,
['process' => $event->getSubject()]
);
$this->entityManager->detach($emailToSend);
}
public function sendAbsenceNotificationEmail($event)
{
//Identificamos si la ausencia fue cancelada por RRHH para identificar
//Cual es el template que se utilizara
if (isset($event->getSubject()->cancelByHR)){
$templateName = 'absence-canceled-ByHR';
}else{
$templateName = 'absence-'.$event->getSubject()->getWorkflowStep();
}
$emailToSend = $this->entityManager->getRepository(Email::class)->findOneBy([
'name' => $templateName
]);
if(!isset($emailToSend)){
return;
}
$employee = $event->getSubject()->getEmployee();
//dd("llego a esta opcion sendAbsenceNotificationEmail():", $emailToSend, $employee);
//Este pedazo de codigo busca a los empelados que tendran el rol de contabilidad en el pais, de la persona a la que se
//le esta gestionando la ausencia.
$contract = $this->entityManager->getRepository(Employee::class)->hasContractActive($event->getSubject()->getEmployee()->getId());
$entityContract = $this->entityManager->getRepository(EntityContract::class)->findOneBy(['contract'=>$contract[0]->getId(), 'isPrincipal'=>1]);
$a3code = $entityContract->getEntity()->getCountry()->getA3code();
$positionAccountant =$this->parameters->get('absence_position_notification_by_country')[$a3code];
$employeeAccountant = $this->entityManager->getRepository(Employee::class)->getEmployeeByCountryAndPosition($entityContract->getEntity()->getCountry()->getId(), $positionAccountant);
$emailAccountant = [];
foreach ($employeeAccountant as $contract) {
$emailAccountant[] = $contract->getEmployee()->getCorporateEmail();
}
//Buscamos el CM y CC
$cmEmail = $this->entityManager->getRepository(Employee::class)->findEmailsByPositionInCountry($employee, 'CM');
$ccEmail = $this->entityManager->getRepository(Employee::class)->findEmailsByPositionInCountry($employee, 'CC');
$cmEmail = array_merge($cmEmail,$ccEmail);
$cmEmail = implode(",",$cmEmail);
if($event->getSubject()->getWorkflowStep() == "Approved_by_Supervisor"){
/*$cmEmail = $this->entityManager->getRepository(Employee::class)->findEmailsByPositionInCountry($employee, 'CM');
$ccEmail = $this->entityManager->getRepository(Employee::class)->findEmailsByPositionInCountry($employee, 'CC');
$cmEmail = array_merge($cmEmail,$ccEmail);
$cmEmail = implode(",",$cmEmail);*/
$to_cc = ($cmEmail !='' && $emailToSend->getSendCc() !='')? $emailToSend->getSendCc().",$cmEmail": $emailToSend->getSendCc().$cmEmail;
$emailsForNotification =
[
MailHandler::RECEIVER_TO => [$employee->getCorporateEmail()],
MailHandler::RECEIVER_CC => explode(",",$to_cc.",".$employee->getImmediateBoss()->getCorporateEmail()),
MailHandler::RECEIVER_BCC => explode(",",$emailToSend->getSendBcc())
];
$subject = str_replace('{{employeeName}}', ucwords($employee->getFirstName().' '.$employee->getSurname()), $emailToSend->getSubject());
$this->mailHandler->sendEmailByApi(
$emailToSend->setSubject($subject),
$emailsForNotification,
['process' => $event->getSubject()]
);
$this->entityManager->detach($emailToSend);
//Buscamos el peronsal de contabilidad asociado al pais donde el empleado tiene el contrato.
$emailToSend = $this->entityManager->getRepository(Email::class)->findOneBy([
'name' => 'absence-notification-accountant'
]);
/*$contract = $this->entityManager->getRepository(Employee::class)->hasContractActive($event->getSubject()->getEmployee()->getId());
$entityContract = $this->entityManager->getRepository(EntityContract::class)->findOneBy(['contract'=>$contract[0]->getId(), 'isPrincipal'=>1]);
$a3code = $entityContract->getEntity()->getCountry()->getA3code();
$positionAccountant =$this->parameters->get('absence_position_notification_by_country')[$a3code];
$employeeAccountant = $this->entityManager->getRepository(Employee::class)->getEmployeeByCountryAndPosition($entityContract->getEntity()->getCountry()->getId(), $positionAccountant);
$emailAccountant = [];
foreach ($employeeAccountant as $contract) {
$emailAccountant[] = $contract->getEmployee()->getCorporateEmail();
}*/
$to_cc = ($cmEmail !='' && $emailToSend->getSendCc() !='')? $emailToSend->getSendCc().",$cmEmail": $emailToSend->getSendCc().$cmEmail;
//Buscamos a la persona con ese rol para ese pais.
$emailsForNotification = [ MailHandler::RECEIVER_TO => $emailAccountant,
MailHandler::RECEIVER_CC => explode(",",$to_cc.",".$employee->getImmediateBoss()->getCorporateEmail()),
MailHandler::RECEIVER_BCC => explode(",",$emailToSend->getSendBcc() ) ];
$subject = str_replace('{{employeeName}}', ucwords($employee->getFirstName().' '.$employee->getSurname()), $emailToSend->getSubject());
//dd($event->getSubject()->getWorkflowStep(), $emailToSend, $employee, $emailsForNotification, $subject, ['process' => $event->getSubject()]);
$this->mailHandler->sendEmailByApi(
$emailToSend->setSubject($subject),
$emailsForNotification,
['process' => $event->getSubject()]
);
$this->entityManager->detach($emailToSend);
}
if($event->getSubject()->getWorkflowStep() == "canceled")
{
// Si la ausencia fue cancelada por RRHH
if (isset($event->getSubject()->cancelByHR)){
$to_cc = ($cmEmail !='' && $emailToSend->getSendCc() !='')? $emailToSend->getSendCc().",$cmEmail": $emailToSend->getSendCc().$cmEmail;
//Buscamos a la persona con ese rol para ese pais.
$emailsForNotification = [ MailHandler::RECEIVER_TO => $emailAccountant,
MailHandler::RECEIVER_CC => explode(",",$to_cc.",".$employee->getImmediateBoss()->getCorporateEmail().",".$employee->getCorporateEmail()),
MailHandler::RECEIVER_BCC => explode(",",$emailToSend->getSendBcc() ) ];
/*$contract = $this->entityManager->getRepository(Employee::class)->hasContractActive($event->getSubject()->getEmployee()->getId());
$entityContract = $this->entityManager->getRepository(EntityContract::class)->findOneBy(['contract'=>$contract[0]->getId(), 'isPrincipal'=>1]);
$a3code = $entityContract->getEntity()->getCountry()->getA3code();
$positionAccountant =$this->parameters->get('absence_position_notification_by_country')[$a3code];
$employeeAccountant = $this->entityManager->getRepository(Employee::class)->getEmployeeByCountryAndPosition($entityContract->getEntity()->getCountry()->getId(), $positionAccountant);
$emailAccountant = [];
foreach ($employeeAccountant as $contract) {
$emailAccountant[] = $contract->getEmployee()->getCorporateEmail();
}*/
}else{
$to_cc = ($emailToSend->getSendCc())? $emailToSend->getSendCc().",".$employee->getCorporateEmail(): $employee->getCorporateEmail();
$emailsForNotification = [ MailHandler::RECEIVER_TO => [$employee->getImmediateBoss()->getCorporateEmail() ],
MailHandler::RECEIVER_CC => explode(",",$to_cc),
MailHandler::RECEIVER_BCC => explode(",", $emailToSend->getSendBcc()) ];
}
$subject = str_replace('{{employeeName}}', ucwords($employee->getFirstName().' '.$employee->getSurname()), $emailToSend->getSubject());
$this->mailHandler->sendEmailByApi(
$emailToSend->setSubject($subject),
$emailsForNotification,
['process' => $event->getSubject()]
);
$this->entityManager->detach($emailToSend);
}
if($event->getSubject()->getWorkflowStep() == "rejected")
{
$to_cc = ($emailToSend->getSendCc())? $emailToSend->getSendCc().",".$employee->getImmediateBoss()->getCorporateEmail(): $employee->getImmediateBoss()->getCorporateEmail();
$emailsForNotification = [ MailHandler::RECEIVER_TO => [$employee->getCorporateEmail() ],
MailHandler::RECEIVER_CC => explode(",",$to_cc),
MailHandler::RECEIVER_BCC => explode(",", $emailToSend->getSendBcc())];
$subject = str_replace('{{employeeName}}', ucwords($employee->getFirstName().' '.$employee->getSurname()), $emailToSend->getSubject());
$this->mailHandler->sendEmailByApi(
$emailToSend->setSubject($subject),
$emailsForNotification,
['process' => $event->getSubject()]
);
}
$this->entityManager->detach($emailToSend);
}
public static function getSubscribedEvents()
{
return [
//'workflow.completed' => 'onCompleted', //Este aplica para todos los workflow
'workflow.onboarding.completed' => 'onCompleted',
'workflow.offboarding.completed' => 'onCompleted',
'workflow.absenceVacation.completed' => 'onCompletedVacation'
];
}
}