<?php
namespace App\Controller;
use App\Entity\Appraisal;
use App\Entity\AppraisalForm;
use App\Entity\AppraisalComment;
use App\Entity\AppraisalNote;
use App\Entity\AppraisalQuestionnaire;
use App\Entity\AppraisalCategory;
use App\Entity\User;
use App\Entity\Office;
use App\Entity\Department;
use App\Form\AppraisalType;
use App\Form\AppraisalNoteType;
use App\Form\AppraisalRequestType;
use App\Form\AppraisalSettingsType;
use App\Form\AppraisalCategoryType;
use App\Repository\AppraisalCategoryRepository;
use App\Repository\AppraisalCommentRepository;
use App\Repository\AppraisalFormRepository;
use App\Repository\AppraisalNoteRepository;
use App\Repository\AppraisalRepository;
use App\Service\AppraisalService;
use App\Service\GoogleDriveService;
use App\Service\MailgunService;
use App\Service\LogService;
use App\Service\UserService;
use App\Service\ObjectiveService;
use App\Service\NotificationService;
use App\Service\ICSService;
use App\Service\LeaveService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Security;
class AppraisalController extends AbstractController
{
#[Route(path: '/settings/appraisal', name: 'appraisal_settings')]
public function appraisalSettings(): \Symfony\Component\HttpFoundation\Response
{
$user = $this->getUser();
$company = $user->assignedCompany();
$formSettings = $this->createForm(AppraisalSettingsType::class);
return $this->render('private/appraisal/edit-appraisal-v2.html.twig', [
'formSettings' => $formSettings->createView(),
'company' => $company
//'formAppraisal' => $formAppraisal->createView()
]);
}
#[Route(path: '/ajax/appraisal-settings/update', name: 'ajax_update_appraisal_settings')]
public function ajaxUpdateAppraisalSettings(Request $request, LogService $log, AppraisalService $appraisalService): JsonResponse
{
$user = $this->getUser();
$result['status'] = 'OK';
$form = $this->createForm(AppraisalSettingsType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
return new JsonResponse($result);
}
if ($form->isSubmitted() && $form->isValid()) {
//$result['status']
$company = $user->assignedCompany();
$attributes = $company->getAttributes();
$oldData = $attributes;
$entityManager = $this->getDoctrine()->getManager();
$currentAttributes = $company->getAttributes();
$currentUserSubmitAt = isset($currentAttributes['appraisalUserSubmitAt']) ? new \DateTime($currentAttributes['appraisalUserSubmitAt']['date'].' '.$currentAttributes['appraisalUserSubmitAt']['timezone']) : null;
$currentManagerSubmitAt = isset($currentAttributes['appraisalManagerSubmitAt']) ? new \DateTime($currentAttributes['appraisalManagerSubmitAt']['date'].' '.$currentAttributes['appraisalManagerSubmitAt']['timezone']) : null;
$attributes['appraisalStartAt'] = $form->get('appraisalStartAt')->getData();
$attributes['appraisalEndAt'] = $form->get('appraisalEndAt')->getData();
$attributes['appraisalUserSubmitAt'] = $form->get('appraisalUserSubmitAt')->getData();
$attributes['appraisalManagerSubmitAt'] = $form->get('appraisalManagerSubmitAt')->getData();
//$attributes['appraisalPulseCheck'] = $form->get('appraisalPulseCheck')->getData();
$company->setAttributes($attributes);
$startDate = isset($attributes['appraisalStartAt']) ? new \DateTime($attributes['appraisalStartAt']->format('Y-m-d')) : null;
$endDate = isset($attributes['appraisalEndAt']) ? new \DateTime($attributes['appraisalEndAt']->format('Y-m-d')) : null;
if($currentUserSubmitAt != $attributes['appraisalUserSubmitAt']) {
$appraisals = $this->getDoctrine()->getRepository(Appraisal::class)->findBy(['probation' => false, 'adHoc' => false, 'submitAt' => $currentUserSubmitAt, 'submittedAt' => null]);
foreach ($appraisals as $appraisal) {
$appraisal->setSubmitAt($attributes['appraisalUserSubmitAt']);
};
};
$employees = $this->getDoctrine()->getRepository(User::class)->findAllEligibleForAppraisal($company, $startDate);
foreach ($employees as $employee) {
$employee->getPersonalInfo()->setJobExpiryDate($form->get('appraisalEndAt')->getData());
};
$entityManager->flush();
$entityManager->refresh($company);
$appraisalService->syncAppraisalStatus();
$log->save($user, [
'owner' => $user,
'message' => 'log.appraisal.settings',
'old_data' => $oldData,
'new_data' => $attributes
]);
};
return new JsonResponse($result);
}
#[Route(path: '/ajax/appraisal/crud', name: 'ajax_crud_appraisal')]
public function ajaxCRUDAppraisal(Request $request, TranslatorInterface $translator, AppraisalService $appraisalService, LogService $log, AppraisalFormRepository $appraisalFormRepository): JsonResponse
{
$id = $request->get("id");
$userId = $request->get("userId");
//$officeId = $request->get("officeId");
$crud = $request->get("crud");
$user = $this->getUser();
$result['status'] = 'OK';
if (!$id) {
$appraisal = new AppraisalForm();
} else {
$appraisal = $this->getDoctrine()->getRepository(AppraisalForm::class)->find($id);
$oldData = clone $appraisal;
};
$form = $this->createForm(AppraisalType::class, $appraisal);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
return new JsonResponse($result);
}
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
if ($id === null) {
$appraisal->setCompany($user->assignedCompany());
$appraisal->setCreatedBy($user);
$appraisal->setCreatedAt(new \DateTimeImmutable());
$entityManager->persist($appraisal);
}
if ($id) {
$appraisal->setUpdatedBy($user);
$appraisal->setUpdatedAt(new \DateTimeImmutable());
}
$entityManager->flush();
$entityManager->refresh($appraisal);
$log->save($user, [
'owner' => $user,
'message' => $id === null ? 'log.appraisal.questionnaire.add' : 'log.appraisal.questionnaire.update',
'old_data' => $id === null ? null : $oldData,
'new_data' => $appraisal
]);
$result['id'] = $appraisal->getId();
$result['content'] = $this->renderView('private/appraisal/components/appraisal-row.html.twig', [
'appraisal' => $appraisal,
'waitForPage' => false
]);
$result['update'] = $id != null;
// if ($id != null && $appraisal->getIsHidden() != $oldData->getIsHidden()) $result['hide'] = true;
return new JsonResponse($result);
}
if ($crud === 'delete' && $appraisal !== null) {
if ($result['status'] == 'OK') {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($appraisal);
$entityManager->flush();
$log->save($user, [
'owner' => $user,
'message' => 'log.appraisal.questionnaire.delete',
'old_data' => $appraisal,
'new_data' => null,
]);
}
return new JsonResponse($result);
}
if ($crud === 'create' || $crud === 'update') {
$result['form'] = $this->renderView('private/appraisal/components/form-appraisal.html.twig', [
'id' => $id,
'form' => $form->createView(),
]);
return new JsonResponse($result);
};
$order = $request->get('order');
$orderBy = $request->get('orderBy');
$keyword = $request->get('keyword');
$type = $request->get('type');
$department = $request->get('department');
$page = intval($request->query->get('page'));
$limit = intval($request->query->get('limit'));
if ($limit === 0) $limit = 20;
$company = $user->assignedCompany();
$appraisals = $appraisalFormRepository->findByPage($page, $limit, $order, $orderBy, $company, $keyword, $type, $department);
$totalCount = $appraisalFormRepository->countByPage($company, $keyword, $type, $department);
$body = $this->renderView('private/appraisal/components/appraisal-list.html.twig', [
'appraisals' => $appraisals
]);
$result['content'] = [
'html' => $body,
'total' => $totalCount
];
return new JsonResponse($result);
}
#[Route(path: '/ajax/list/appraisal', name: 'ajax_list_appraisal')]
public function ajaxListAppraisal(TranslatorInterface $translator, AppraisalService $appraisalService, LogService $log): JsonResponse
{
}
#[Route(path: '/ajax/appraisal-schedule/crud', name: 'ajax_crud_appraisal_schedule')]
public function ajaxCRUDAppraisalSchedule(Request $request, AppraisalService $appraisalService, ObjectiveService $objectiveService, LogService $log): JsonResponse
{
$user = $this->getUser();
if ($_SERVER['APP_ENV'] != "prod" && $user->getAppraisalStatus() == null && $user->getObjectiveStatus() == null) {
$appraisalService->syncAppraisalStatus();
$objectiveService->syncObjectiveStatus();
$result['sync'] = 'OK';
};
$isManager = !$this->isGranted('ROLE_HR') && $user->getIsManager();
$page = intval($request->query->get('page'));
$limit = intval($request->query->get('limit'));
if ($limit === 0) $limit = 20;
$order = $request->get('order');
$orderBy = $request->get('orderBy');
$keyword = $request->get('keyword');
$manager = $isManager ? $user->getId() : $request->get('manager');
$subManager = $request->get('subManager');
$office = $request->get('office');
$employment = $request->get('employment');
$department = $request->get('department');
$appraisal = $request->get('appraisal');
$objective = $request->get('objective');
$waitForPage = $request->query->get('waitForPage');
$waitForPage === null ? $result['waitForPage'] = 'false' : $result['waitForPage'] = $waitForPage;
$result['status'] = 'OK';
// $appraisals = $this->getDoctrine()->getRepository(Appraisal::class)->findByPage($page, $limit, $order, $orderBy, $keyword);
// $totalCount = $this->getDoctrine()->getRepository(Appraisal::class)->countByPage($keyword);
$company = $user->assignedCompany();
$users = $this->getDoctrine()->getRepository(User::class)->findByAppraisalPage($page, $limit, $order, $orderBy, $company, $keyword, $manager, $subManager, $office, $employment, $department, $appraisal, $objective);
$totalCount = $this->getDoctrine()->getRepository(User::class)->countByAppraisalPage($company, $keyword, $manager, $subManager, $office,$employment, $department, $appraisal, $objective);
$body = $this->renderView('private/appraisal/components/appraisal-schedule-list.html.twig', [
// 'appraisals' => $appraisals
'users' => $users,
'testAccounts' => explode(',', str_replace(array("\r", "\n", " "), '',$_SERVER['TEST_ACCOUNTS']))
]);
$result['content'] = [
'html' => $body,
'total' => $totalCount
];
return new JsonResponse($result);
}
#[Route(path: '/ajax/appraisal-category/crud', name: 'ajax_crud_appraisal_category')]
public function ajaxCRUDAppraisalCategory(Request $request, LogService $log, AppraisalCategoryRepository $appraisalCategoryRepository): JsonResponse
{
$id = $request->get("id");
$userId = $request->get("userId");
//$officeId = $request->get("officeId");
$crud = $request->get("crud");
$user = $this->getUser();
$result['status'] = 'OK';
if (!$id) {
$category = new AppraisalCategory();
} else {
$category = $this->getDoctrine()->getRepository(AppraisalCategory::class)->find($id);
$oldData = clone $category;
};
$form = $this->createForm(AppraisalCategoryType::class, $category);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
return new JsonResponse($result);
}
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
if ($id === null) {
$category->setCompany($user->assignedCompany());
$questionnaires = $form->get('questionnaire')->getData();
foreach($questionnaires as $question){
$question->setCompany($user->assignedCompany());
$question->setType($category->getType());
$question->setDepartment($category->getDepartment());
$question->setCreatedAt(new \DateTime());
$question->setCreatedBy($user);
}
$category->setCreatedBy($user);
$category->setCreatedAt(new \DateTimeImmutable());
$entityManager->persist($category);
}
if ($id) {
$questionnaires = $form->get('questionnaire')->getData();
foreach($questionnaires as $question){
if(!$question->getCompany()) $question->setCompany($user->assignedCompany());
if(!$question->getType()) $question->setType($category->getType());
if(!$question->getDepartment()) $question->setDepartment($category->getDepartment());
$question->setCreatedAt(new \DateTime());
$question->setCreatedBy($user);
}
$category->setUpdatedBy($user);
$category->setUpdatedAt(new \DateTimeImmutable());
}
$entityManager->flush();
$entityManager->refresh($category);
$log->save($user, [
'owner' => $user,
'message' => $id === null ? 'log.appraisal.category.add' : 'log.appraisal.category.update',
'old_data' => $id === null ? null : $oldData,
'new_data' => $category
]);
$result['id'] = $category->getId();
$result['content'] = $this->renderView('private/appraisal/components/appraisal-category-row.html.twig', [
'category' => $category,
'waitForPage' => false
]);
$result['update'] = $id != null;
// if ($id != null && $category->getIsHidden() != $oldData->getIsHidden()) $result['hide'] = true;
return new JsonResponse($result);
}
if ($crud === 'delete' && $category !== null) {
if ($result['status'] == 'OK') {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($category);
$entityManager->flush();
$log->save($user, [
'owner' => $user,
'message' => 'log.appraisal.questionnaire.delete',
'old_data' => $category,
'new_data' => null,
]);
}
return new JsonResponse($result);
}
if ($crud === 'create' || $crud === 'update') {
$result['form'] = $this->renderView('private/appraisal/components/form-appraisal-category.html.twig', [
'id' => $id,
'form' => $form->createView(),
]);
return new JsonResponse($result);
};
$order = $request->get('order');
$orderBy = $request->get('orderBy');
$keyword = $request->get('keyword');
$type = $request->get('type');
$department = $request->get('department');
$page = intval($request->query->get('page'));
$limit = intval($request->query->get('limit'));
if ($limit === 0) $limit = 20;;
$company = $user->assignedCompany();
$categories = $appraisalCategoryRepository->findByPage($page, $limit, $order, $orderBy, $company, $keyword, $type, $department);
$totalCount = $appraisalCategoryRepository->countByPage($company, $keyword, $type, $department);
$body = $this->renderView('private/appraisal/components/appraisal-category-list.html.twig', [
'categories' => $categories
]);
$result['content'] = [
'html' => $body,
'total' => $totalCount
];
return new JsonResponse($result);
}
#[Route(path: '/ajax/appraisal-request', name: 'ajax_appraisal_request')]
public function ajaxAppraisalRequest(Request $request, TranslatorInterface $translator, AppraisalService $appraisalService, LogService $log): JsonResponse
{
$user = $this->getUser();
$appraisal = new Appraisal();
$form = $this->createForm(AppraisalRequestType::class, $appraisal);
$form->handleRequest($request);
$result['status'] = 'OK';
$editedUser = $this->getDoctrine()->getRepository(User::class)->find($request->get("userId"));
if ($editedUser == null) {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing') . ': UID';
}
if ($form->isSubmitted() && !$form->isValid() && $result['status'] == 'OK') {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
};
if ($result['status'] == 'OK') {
$result['content'] = $appraisalService->initiateAppraisal($request, $user, $editedUser, $form->get('title')->getData(), $form->get('submitAt')->getData(), $form->get('reviewAt')->getData(), $request->request->get('addonform-text'), $request->request->get('addonform-score'), $form->get('adHoc')->getData());
/*$log->save($user, [
'owner' => $editedUser,
'message' => 'log.appraisal.request',
'old_data' => null,
'new_data' => $appraisal
]);*/
$result['ordering'] = [
'key' => 'submit',
'sort' => 'desc'
];
};
return new JsonResponse($result);
}
#[Route(path: '/ajax/edit-appraisal-request', name: 'ajax_edit_appraisal_request', methods: 'POST')]
function ajaxEditAppraisalRequest(Request $request, AppraisalService $appraisalService, TranslatorInterface $translator): \Symfony\Component\HttpFoundation\Response
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($request->get("id"));
$formAppraisal = $this->createForm(AppraisalRequestType::class, $appraisal);
$addOnQuestions = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByAppraisal($appraisal);
$defaultQuestions = $this->getDoctrine()->getRepository(AppraisalQuestionnaire::class)->findByUser($appraisal->getUser());
return $this->render('private/appraisal/components/form-edit-appraisal-request.html.twig', array(
'userData' => $user,
'editedUser' => $appraisal->getUser(),
'dataId' => $appraisal->getId(),
'formAppraisal' => $formAppraisal->createView(),
'addOnQuestions' => $addOnQuestions ? $addOnQuestions : null,
'defaultQuestions' => $defaultQuestions ? $defaultQuestions : null
));
}
#[Route(path: '/ajax/update-appraisal-request', name: 'ajax_update_appraisal_request')]
public function ajaxUpdateRequestAppraisal(Request $request, TranslatorInterface $translator, AppraisalService $appraisalService, LogService $log, MailgunService $mailgunService, NotificationService $notification, ICSService $ics, SerializerInterface $serializer): JsonResponse
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($request->get("dataId"));
$oldData = clone $appraisal;
$result['status'] = 'OK';
$loggedIn = $request ? true : false;
if ($appraisal != null) {
/*
if ($user->isSubordinate($appraisal->getUser()->getId())) {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.security.forbidden');
};
*/
$form = $this->createForm(AppraisalRequestType::class, $appraisal);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid() && $result['status'] == 'OK') {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
};
if ($result['status'] == 'OK') {
$entityManager = $this->getDoctrine()->getManager();
if ($appraisal->getReviewAt() != $oldData->getReviewAt()) {
$appraisal->setReschedule($appraisal->getReschedule() + 1);
if ($appraisal->getAdHoc()) $appraisal->setSubmitAt($appraisal->getReviewAt());
};
$entityManager->flush();
$entityManager->refresh($appraisal);
//$addOnQuestions = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByAppraisal($appraisal);
$addOnFormTexts = $request->request->get('addonform-text');
if ($addOnFormTexts != null) {
$addOnFormId = $request->request->get('addonform-id');
$addOnFormDelete = $request->request->get('addonform-delete');
$addOnFormScores = $request->request->get('addonform-score');
$n = 1;
foreach ($addOnFormTexts as $addOnFormText) {
if ($addOnFormId[$n]) {
$appraisalForm = $this->getDoctrine()->getRepository(AppraisalForm::class)->findById($addOnFormId[$n]);
if ($addOnFormDelete[$n] == 'true') {
$entityManager->remove($appraisalForm);
$entityManager->flush();
$n++;
continue;
}
} else {
$appraisalForm = new AppraisalForm();
if ($addOnFormText == null) {
$n++;
continue;
}
}
$appraisalForm->setDescription($addOnFormText);
if ($addOnFormScores[$n] == 'true') {
$appraisalForm->setUseScore(true);
} else {
$appraisalForm->setUseScore(false);
};
$appraisalForm->setCreatedBy($user);
$appraisalForm->setCreatedAt(new \DateTime());
$appraisalForm->setCompany($user->assignedCompany());
if ($addOnFormId[$n] == null) {
$entityManager->persist($appraisalForm);
$appraisalForm->setAppraisal($appraisal);
$appraisal->setSubmittedAt(null);
};
$entityManager->flush();
$n++;
};
}
$attendee = [
[
'name' => $user->getPersonalInfo()->getFullName(),
'email' => $user->getEmail(),
'role' => $appraisal->getUser()->getManager() == $user ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
],
[
'name' => $appraisal->getUser()->getPersonalInfo()->getFullName(),
'email' => $appraisal->getUser()->getEmail(),
'role' => 'REQ-PARTICIPANT'
],
];
foreach ($appraisal->getUser()->getAllManager() as $manager) {
if ($manager != $user) {
array_push($attendee, [
'name' => $manager->getPersonalInfo()->getFullName(),
'email' => $manager->getEmail(),
'role' => $appraisal->getUser()->getManager() == $manager ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
]);
}
}
// if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
// foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
// if ($superAdmin != $user) {
// array_push($attendee, [
// 'name' => $superAdmin->getPersonalInfo()->getFullName(),
// 'email' => $superAdmin->getEmail(),
// 'role' => 'OPT-PARTICIPANT'
// ]);
// }
// }
// };
if ($appraisal->getReviewAt() != $oldData->getReviewAt() && in_array($appraisal->currentStep(), [3, 4])) {
$hrSetSchedule = $oldData->getReviewAt() == null && $appraisal->currentStep() == 3 && $appraisal->getUser()->inProbation() == false ? true : false;
if ($hrSetSchedule) {
$emailTemplate = 'email/user-notification/appraisal/hr-invitation-default.html.twig';
$titleTemplate = 'email.appraisal.invitation.default.';
} else {
if ($appraisal->getProbation()) {
if($oldData->getReschedule() == 0 && $oldData->getReviewAt() == null){
$emailTemplate = 'email/user-notification/appraisal/invitation-probation.html.twig';
$titleTemplate = 'email.appraisal.invitation.probation.';
} else {
$emailTemplate = 'email/user-notification/appraisal/reschedule-probation.html.twig';
$titleTemplate = 'email.appraisal.rescheduled.probation.';
}
} elseif ($oldData->getReschedule() == 0) {
$emailTemplate = 'email/user-notification/appraisal/hr-invitation-default.html.twig';
$titleTemplate = 'email.appraisal.invitation.default.';
} else {
$emailTemplate = 'email/user-notification/appraisal/reschedule-default.html.twig';
$titleTemplate = 'email.appraisal.rescheduled.default.';
};
}
$endTime = new \DateTime($appraisal->getReviewAt()->format('Ymd H:i:s'));
$endTime->modify('+ 30 minutes');
$ICSTitle = $appraisal->getUser()->inProbation() ? 'Review (Probation)' : 'Review';
$icsData = $ics->generateEventFile([
'uid' => $appraisal->getId() . $appraisal->getUser()->getId() . ':' . $appraisal->getUser()->getEmail(),
'title' => $ICSTitle . ': ' . $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'description' => $translator->trans('ics.appraisal.description', ['%uid%' => $appraisal->getUser()->getId(), '%user%' => strtolower($appraisal->getUser()->getPersonalInfo()->getFirstName()), '%link%' => $this->generateUrl('user_profile', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getUser()->getEmail() . '?g=appraisal&open=appraisal-' . $appraisal->getId()]),
'startDateTime' => $appraisal->getReviewAt()->format('Ymd') . 'T' . $appraisal->getReviewAt()->format('His'),
'endDateTime' => $appraisal->getReviewAt()->format('Ymd') . 'T' . $endTime->format('His'),
'location' => $this->generateUrl('submit_appraisal', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getId(),
'organizer' => [
'name' => $this->getParameter('systemEmailName'),
'email' => $_SERVER['APP_ENV'] == 'prod' ? $this->getParameter('systemEmailAddr') : 'devops@mediatropy.com'
],
'attendee' => $attendee,
'reschedule' => $appraisal->getReschedule(),
'reminderTime' => '-15M',
'reminderDescription' => $translator->trans('ics.appraisal.title') . ' ' . $appraisal->getTitle(),
'fileName' => 'Appraisal-' . $appraisal->getIcsToken()
], true);
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans($titleTemplate . 'user', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%date%' => $appraisal->getReviewAt()->format('l, d M Y')]),
'to' => $appraisal->getUser()->getEmail(),
'template' => $emailTemplate,
'params' => [
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user'
],
'ical' => $icsData
], $loggedIn);
// $notification->push($appraisal->getUser(), [
// 'message' => 'notification.appraisal.rescheduled_alt.user',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'name' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// 'time' => $appraisal->getReviewAt()->format('Ymd His'),
// ], 'json')
// ], true);
foreach ($appraisal->getUser()->getAllManager() as $manager) {
// $notification->push($manager, [
// 'message' => 'notification.appraisal.rescheduled_alt.manager',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'name' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// 'time' => $appraisal->getReviewAt()->format('Ymd His'),
// ], 'json')
// ], true);
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans($titleTemplate . 'manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFullName(), '%date%' => $appraisal->getReviewAt()->format('l, d M Y')]),
'to' => $manager->getEmail(),
'template' => $emailTemplate,
'params' => [
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager'
],
'ical' => $icsData
], $loggedIn);
}
$emailGroup = $this->getParameter('systemEmailGroup');
foreach ($emailGroup as $groupName => $groupEmail) {
if ($groupName == 'hr') { // only HR
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans($titleTemplate . 'hr', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFullName(), '%date%' => $appraisal->getReviewAt()->format('l, d M Y')]),
'to' => $groupEmail,
'template' => $emailTemplate,
'params' => [
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName
],
'ical' => $icsData
], $loggedIn);
};
};
/*if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
if ($superAdmin != $user && !in_array($superAdmin, $appraisal->getUser()->getAllManager())) {
$notification->push($superAdmin, [
'message' => 'notification.appraisal.rescheduled_alt.manager',
'entity' => 'Appraisal',
'objectId' => $appraisal->getId(),
'data' => $serializer->serialize([
'title' => $appraisal->getTitle(),
'name' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
'time' => $appraisal->getSubmitAt()->format('Ymd His'),
], 'json')
], true);
$mailgunService->sendEmailWithAttachment([
//'subject' => $translator->trans('email.appraisal.created_cc_updated') . ' ' . $appraisal->getSubmitAt()->format('d F Y').' at '.$appraisal->getSubmitAt()->format('H:i'),
'subject' => $translator->trans('email.system.copy_super_admin') . ' ' . $subject,
'to' => $superAdmin->getEmail(),
'template' => 'email/user-notification/appraisal/request-cc.html.twig',
'params' => [
'sender' => $user,
'recipient' => $superAdmin,
'appraisal' => $appraisal,
'reschedule' => true
],
//'attachments' => $this->generateUrl('download_ics_appraisal', array('token' => $appraisal->getIcsToken()))
'ical' => $icsData
]);
};
}
}*/
} elseif ($appraisal->getSubmitAt() != $oldData->getSubmitAt() and $appraisal->currentStep() <= 1) {
//TODO Add email or notification when user submit date changed?
};
/*
if ($appraisal->getReviewAt() != $oldData->getReviewAt()) {
$mailgunService->rescheduleEmail(new \DateTime($appraisal->getReviewAt()->format('Ymd H:i:s')), 'Appraisal', $appraisal->getId());
};*/
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.request_update',
'old_data' => $oldData,
'new_data' => $appraisal
]);
/*switch ($appraisal->currentStep($user)) {
case 1:
$action = $translator->trans('form.appraisal.pending.user');
$attr = 'disabled="disabled"';
break;
case 2:
$action = $translator->trans('form.appraisal.pending.manager');
$attr = '';
break;
case 3:
$action = $translator->trans('form.appraisal.pending.review');
$attr = '';
break;
case 4:
$action = $translator->trans('form.appraisal.ready');
$attr = '';
break;
default:
$action = $translator->trans('form.appraisal.done');
$attr = '';
break;
}
if ($appraisal->currentStep($user) == 1) {
if ($appraisal->getSubmitAt()->format('Ymd') <= date('Ymd')) {
$appraisalClass = 'b-danger';
} else {
$appraisalClass = 'b-warning';
};
} else {
$appraisalClass = '';
};*/
$result['id'] = $appraisal->getId();
if ($user != $appraisal->getUser()) {
$result['content'] = $this->renderView('private/user/components/tab-appraisal-list-manager.html.twig', [
'appraisal' => $appraisal
]);
} else {
$result['content'] = $this->renderView('private/user/components/tab-appraisal-list-user.html.twig', [
'appraisal' => $appraisal
]);
}
$result['update'] = true;
$result['ordering'] = [
'key' => 'submit',
'sort' => 'desc'
];
}
$appraisalService->syncAppraisalStatus($appraisal->getUser());
} else {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/edit-appraisal-questionnaire', name: 'ajax_edit_appraisal_questionnaire', methods: 'POST')]
function ajaxEditAppraisalQuestionnaire(Request $request, TranslatorInterface $translator)
{
$user = $this->getUser();
$editedUser = $this->getDoctrine()->getRepository(User::class)->find($request->get("id"));
if ($editedUser == null) return false;
$questionnaires = $this->getDoctrine()->getRepository(AppraisalQuestionnaire::class)->findByUser($editedUser);
return $this->render('private/appraisal/components/form-appraisal-questionnaire.html.twig', array(
'userData' => $user,
'editedUser' => $editedUser,
'questionnaires' => $questionnaires ? $questionnaires : null
));
}
#[Route(path: '/ajax/update-appraisal-questionnaire', name: 'ajax_update_appraisal_questionnaire')]
public function ajaxUpdateAppraisalQuestionnaire(Request $request, TranslatorInterface $translator, AppraisalService $appraisalService, SerializerInterface $serializer): JsonResponse
{
$user = $this->getUser();
$editedUser = $this->getDoctrine()->getRepository(User::class)->find($request->get("userId"));
$result['status'] = 'OK';
if ($editedUser == null) { // TODO: Make other error response like this
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
return new JsonResponse($result);
};
$result['content'] = $appraisalService->setDefaultQuestionnaire($request, $user, $editedUser);
return new JsonResponse($result);
}
#[Route(path: '/ajax/appraisal/addon-questionnaire/crud', name: 'ajax_crud_appraisal_addon_questionnaire')]
public function ajaxCRUDAppraisalAddonQuestionnaire(Request $request, TranslatorInterface $translator, AppraisalService $appraisalService, LogService $log): JsonResponse
{
$crud = $request->get("crud");
$user = $this->getUser();
$editedUser = $this->getDoctrine()->getRepository(User::class)->find($request->get("userId"));
$result['status'] = 'OK';
$entityManager = $this->getDoctrine()->getManager();
if ($editedUser == null) return false;
$questionnaires = $this->getDoctrine()->getRepository(AppraisalQuestionnaire::class)->findByUser($editedUser);
if ($crud == 'update') {
$result['form'] = $this->renderView('private/appraisal/components/form-appraisal-questionnaire.html.twig', [
'editedUser' => $editedUser,
'questionnaires' => $questionnaires ? $questionnaires : null,
'waitForPage' => false
]);
} else {
$result['total'] = $appraisalService->setDefaultQuestionnaire($request, $user, $editedUser);
$result['update'] = true;
$result['id'] = $request->get("userId");
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/remind-appraisal', name: 'ajax_remind_appraisal')]
public function ajaxRemindAppraisal(Request $request, TranslatorInterface $translator, LogService $log, MailgunService $mailgunService, NotificationService $notification, ICSService $ics, SerializerInterface $serializer): JsonResponse
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($request->get("id"));
$result['status'] = 'OK';
if ($appraisal != null) {
$attendee = [
[
'name' => $user->getPersonalInfo()->getFullName(),
'email' => $user->getEmail(),
'role' => $appraisal->getUser()->getManager() == $user ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
],
[
'name' => $appraisal->getUser()->getPersonalInfo()->getFullName(),
'email' => $appraisal->getUser()->getEmail(),
'role' => 'REQ-PARTICIPANT'
],
];
foreach ($appraisal->getUser()->getAllManager() as $manager) {
if ($manager != $user) {
array_push($attendee, [
'name' => $manager->getPersonalInfo()->getFullName(),
'email' => $manager->getEmail(),
'role' => $appraisal->getUser()->getManager() == $manager ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
]);
}
}
// if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
// foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
// if ($superAdmin != $user) {
// array_push($attendee, [
// 'name' => $superAdmin->getPersonalInfo()->getFullName(),
// 'email' => $superAdmin->getEmail(),
// 'role' => 'OPT-PARTICIPANT'
// ]);
// }
// }
// };
$scheduleDate = $appraisal->getReviewAt() != null ? $appraisal->getReviewAt() : $appraisal->getSubmitAt();
$subject = $appraisal->getTitle() . ' | ' . $appraisal->getUser()->getPersonalInfo()->getFirstName() . ' | ' . $scheduleDate->format('d F Y');
$endTime = new \DateTime($scheduleDate->format('Ymd H:i:s'));
$endTime->modify('+ 1 hour');
$ICSTitle = $appraisal->getUser()->inProbation() ? 'Review (Probation)' : 'Review';
$icsData = $ics->generateEventFile([
'uid' => $appraisal->getId() . $appraisal->getUser()->getId() . ':' . $appraisal->getUser()->getEmail(),
'title' => $ICSTitle . ': ' . $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'description' => $translator->trans('ics.appraisal.description', ['%uid%' => $appraisal->getUser()->getId(), '%user%' => strtolower($appraisal->getUser()->getPersonalInfo()->getFirstName()), '%link%' => $this->generateUrl('user_profile', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getUser()->getEmail() . '?g=appraisal&open=appraisal-' . $appraisal->getId()]),
'startDateTime' => $scheduleDate->format('Ymd') . 'T' . $scheduleDate->format('His'),
'endDateTime' => $scheduleDate->format('Ymd') . 'T' . $endTime->format('His'),
'location' => $this->generateUrl('submit_appraisal', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getId(),
'organizer' => [
'name' => $this->getParameter('systemEmailName'),
'email' => $request->getHost() == 'hr.mediatropy.com' ? $this->getParameter('systemEmailAddr') : 'devops@mediatropy.com'
],
'attendee' => $attendee,
'reminderTime' => '-15M',
'reminderDescription' => $translator->trans('ics.appraisal.title') . ' ' . $appraisal->getTitle(),
'fileName' => 'Appraisal-' . $appraisal->getIcsToken()
], true);
/*
$mailgunService->sendEmail(
$translator->trans('email.appraisal.scheduled') . ' ' . $appraisal->getSubmitAt()->format('d F Y'),
[$appraisal->getUser()->getEmail()],
'email/user-notification/appraisal/request.html.twig',
[
'user' => $appraisal->getUser(),
'appraisal' => $appraisal,
]
);*/
$mailgunService->sendEmailWithAttachment([
'subject' => $subject,
'to' => $appraisal->getUser()->getEmail(),
'template' => 'email/user-notification/appraisal/request.html.twig',
'params' => [
'recipient' => $appraisal->getUser(),
'sender' => $user,
'appraisal' => $appraisal,
'reschedule' => false
],
'ical' => $icsData
]);
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmailWithAttachment([
'subject' => $subject,
'to' => $manager->getEmail(),
'template' => 'email/user-notification/appraisal/request-cc.html.twig',
'params' => [
'sender' => $user,
'recipient' => $manager,
'appraisal' => $appraisal,
'reschedule' => false
],
'ical' => $icsData
]);
}
/*
if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
if ($superAdmin != $user && !in_array($superAdmin, $appraisal->getUser()->getAllManager())) {
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans('email.system.copy_super_admin').' '.$subject,
'to' => $superAdmin->getEmail(),
'template' => 'email/user-notification/appraisal/request-cc.html.twig',
'params' => [
'recipient' => $appraisal->getUser(),
'sender' => $user,
'cc' => $superAdmin,
'appraisal' => $appraisal,
'reschedule' => false
],
'ical' => $icsData
]);
};
}
};*/
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.reminder',
'old_data' => null,
'new_data' => null
]);
/*
if ($appraisal->currentStep($user) == 1) {
if ($appraisal->getSubmitAt()->format('Ymd') <= date('Ymd')) {
$appraisalClass = 'b-danger';
} else {
$appraisalClass = 'b-warning';
};
} else {
$appraisalClass = '';
};*/
$result['content'] = $this->renderView('private/user/components/tab-appraisal-list-manager.html.twig', [
'appraisal' => $appraisal
]);
} else {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/close-appraisal', name: 'ajax_close_appraisal')]
public function ajaxCloseAppraisal(Request $request, TranslatorInterface $translator, LogService $log, MailgunService $mailgunService, NotificationService $notification, ICSService $ics, SerializerInterface $serializer): JsonResponse
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($request->get("id"));
$result['status'] = 'OK';
if ($appraisal != null) {
$entityManager = $this->getDoctrine()->getManager();
// $appraisal->setReviewAt(new \DateTime());
// $appraisal->setReviewedBy($user);
// $appraisal->setReviewedAt(new \DateTime());
$appraisal->setConcludedAt(new \DateTime());
$entityManager->flush();
$entityManager->refresh($appraisal);
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.close',
'old_data' => null,
'new_data' => $appraisal
]);
// $notification->push($appraisal->getUser(), [
// 'message' => 'notification.appraisal.reviewed_alt',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// 'time' => $appraisal->getReviewAt()->format('Ymd His'),
// ], 'json')
// ], true);
$subject = $appraisal->getTitle() . ' | ' . $appraisal->getUser()->getPersonalInfo()->getFirstName() . ' | ' . $translator->trans('email.appraisal.result');
$mailgunService->sendEmail(
$subject,
[$appraisal->getUser()->getEmail()],
'email/user-notification/appraisal-result.html.twig',
[
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
]
);
} else {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/delete-appraisal-request', name: 'ajax_delete_appraisal_request', methods: 'POST')]
function ajaxDeleteAppraisalRequest(Request $request, TranslatorInterface $translator, MailgunService $mailgunService, ICSService $ics, NotificationService $notification, LogService $log, SerializerInterface $serializer): JsonResponse
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($request->get("id"));
//$oldData = clone $appraisal;
$result['status'] = 'OK';
if ($appraisal != null) {
$response = $this->forward('App\Controller\AppraisalController::deleteAppraisalRequest', [
'request' => $request,
'user' => $user,
'appraisal' => $appraisal,
'logged' => true
]);
//dump(json_decode($response->getContent(),true));
$result['status'] = json_decode($response->getContent(), true);
} else {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
}
return new JsonResponse($result);
}
#[Route(path: '/function/delete-appraisal-request', name: 'function_delete_appraisal_request', methods: 'POST')]
function deleteAppraisalRequest($request, $user, $appraisal, $logged = true, TranslatorInterface $translator, MailgunService $mailgunService, AppraisalService $appraisalService, ICSService $ics, NotificationService $notification, LogService $log, SerializerInterface $serializer): JsonResponse
{
$oldData = clone $appraisal;
$loggedIn = $request ? true : false;
if ($logged) {
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.request_delete',
'old_data' => $oldData,
'new_data' => null
]);
};
if (($appraisal->getAdHoc() || $appraisal->currentStep() > 2) && $appraisal->getReviewAt() != null && date('YmdHis') < $appraisal->getReviewAt()->format('YmdHis')) { // Only send notification if review set
$attendee = [
[
'name' => $user->getPersonalInfo()->getFullName(),
'email' => $user->getEmail(),
'role' => $appraisal->getUser()->getManager() == $user ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
],
[
'name' => $appraisal->getUser()->getPersonalInfo()->getFullName(),
'email' => $appraisal->getUser()->getEmail(),
'role' => 'REQ-PARTICIPANT'
],
];
foreach ($appraisal->getUser()->getAllManager() as $manager) {
try {
if ($manager != $user) {
array_push($attendee, [
'name' => $manager->getPersonalInfo()->getFullName(),
'email' => $manager->getEmail(),
'role' => $appraisal->getUser()->getManager() == $manager ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
]);
}
} catch (Exception $e) {
continue;
}
}
/*if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
if ($superAdmin != $user) {
array_push($attendee, [
'name' => $superAdmin->getPersonalInfo()->getFullName(),
'email' => $superAdmin->getEmail(),
'role' => 'OPT-PARTICIPANT'
]);
}
}
};*/
$subject = $appraisal->getTitle() . ' | ' . $appraisal->getUser()->getPersonalInfo()->getFirstName() . ' | ' . $translator->trans('email.appraisal.cancel');
$endTime = new \DateTime($appraisal->getReviewAt()->format('Ymd H:i:s'));
$endTime->modify('+ 1 hour');
$ICSTitle = $appraisal->getUser()->inProbation() ? 'Review (Probation)' : 'Review';
if ($appraisal->getAdHoc()) $ICSTitle = 'Ad hoc Review';
if ($appraisal->getAdHoc() || $appraisal->currentStep() > 2) {
$icsData = $ics->generateEventFile([
'uid' => $appraisal->getId() . $appraisal->getUser()->getId() . ':' . $appraisal->getUser()->getEmail(),
'title' => $ICSTitle . ': ' . $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'description' => null,
'startDateTime' => $appraisal->getReviewAt()->format('Ymd') . 'T' . $appraisal->getReviewAt()->format('His'),
'endDateTime' => $appraisal->getReviewAt()->format('Ymd') . 'T' . $endTime->format('His'),
'location' => $this->generateUrl('submit_appraisal', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getId(),
'organizer' => [
'name' => $this->getParameter('systemEmailName'),
'email' => $request->getHost() == 'hr.mediatropy.com' ? $this->getParameter('systemEmailAddr') : 'devops@mediatropy.com'
],
'attendee' => $attendee,
'reschedule' => $appraisal->getReschedule(),
'reminderTime' => '-15M',
'reminderDescription' => $translator->trans('ics.appraisal.title') . ' ' . $appraisal->getTitle(),
'fileName' => 'Appraisal-' . $appraisal->getIcsToken()
], true, 'CANCEL');
} else {
$icsData = null;
};
/*$notification->disable($appraisal->getUser(), [
'entity' => 'appraisal',
'objectId' => $appraisal->getId(),
]);*/
if ($logged) {
// $notification->push($appraisal->getUser(), [
// 'message' => 'notification.appraisal.canceled.user',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'name' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// 'time' => $appraisal->getReviewAt()->format('Ymd His'),
// ], 'json')
// ], true);
};
$mailgunService->sendEmailWithAttachment([
'subject' => $subject,
'to' => $appraisal->getUser()->getEmail(),
'template' => 'email/user-notification/appraisal/cancel.html.twig',
'params' => [
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user'
],
'ical' => $icsData
], $loggedIn);
foreach ($appraisal->getUser()->getAllManager() as $manager) {
try {
/*$notification->clear($manager, [
'entity' => 'appraisal',
'objectId' => $appraisal->getId(),
]);*/
// $notification->push($manager, [
// 'message' => 'notification.appraisal.canceled.manager',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'name' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// 'time' => $appraisal->getReviewAt()->format('Ymd His'),
// ], 'json')
// ], true);
$mailgunService->sendEmailWithAttachment([
'subject' => $subject,
'to' => $manager->getEmail(),
'template' => 'email/user-notification/appraisal/cancel-cc.html.twig',
'params' => [
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager'
],
'ical' => $icsData
], $loggedIn);
} catch (Exception $e) {
continue;
}
}
$emailGroup = $this->getParameter('systemEmailGroup');
foreach ($emailGroup as $groupName => $groupEmail) {
if ($appraisal->getUser()->inProbation() == false && $groupName == 'finance') continue;
try {
$mailgunService->sendEmailWithAttachment([
'subject' => $subject,
'to' => $groupEmail,
'template' => 'email/user-notification/appraisal/cancel-cc.html.twig',
'params' => [
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName
],
'ical' => $icsData
], $loggedIn);
} catch (Exception $e) {
continue;
}
};
/*if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
if ($superAdmin != $user && !in_array($superAdmin, $appraisal->getUser()->getAllManager())) {
// $notification->push($superAdmin, [
// 'message' => 'notification.appraisal.canceled.manager',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'name' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// ], 'json')
// ], true);
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans('email.system.copy_super_admin') . ' ' . $subject,
'to' => $superAdmin->getEmail(),
'template' => 'email/user-notification/appraisal/cancel-cc.html.twig',
'params' => [
'sender' => $user,
'recipient' => $superAdmin,
'appraisal' => $appraisal,
],
'ical' => $icsData
]);
};
}
};*/
} else if (in_array($appraisal->currentStep(), [1, 2])) {
$subject = $appraisal->getTitle() . ' | ' . $appraisal->getUser()->getPersonalInfo()->getFirstName() . ' | ' . $translator->trans('email.appraisal.cancel');
$emailTemplate = 'email/user-notification/appraisal/cancel.html.twig';
$mailgunService->sendEmail(
$subject,
[$appraisal->getUser()->getEmail()],
$emailTemplate,
[
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user'
]
);
$emailTemplate = 'email/user-notification/appraisal/cancel-cc.html.twig';
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmail(
$subject,
[$manager->getEmail()],
$emailTemplate,
[
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager'
]
);
};
$emailGroup = $this->getParameter('systemEmailGroup');
foreach ($emailGroup as $groupName => $groupEmail) {
if ($appraisal->getUser()->inProbation() == false && $groupName == 'finance') continue;
try {
$mailgunService->sendEmail(
$subject,
[$groupEmail],
$emailTemplate,
[
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName,
]
);
} catch (Exception $e) {
}
};
};
$entityManager = $this->getDoctrine()->getManager();
$appraisalComments = $this->getDoctrine()->getRepository(AppraisalComment::class)->findByAppraisal($appraisal);
if ($appraisalComments != null) {
foreach ($appraisalComments as $appraisalComment) {
$entityManager->remove($appraisalComment);
};
}
$appraisalForms = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByAppraisal($appraisal);
if ($appraisalForms != null) {
foreach ($appraisalForms as $appraisalForm) {
$entityManager->remove($appraisalForm);
};
};
$entityManager->remove($appraisal);
$entityManager->flush();
$appraisalService->syncAppraisalStatus($appraisal->getUser());
return new JsonResponse('OK');
}
#[Route(path: '/appraisal/{_id}', defaults: ['_id' => 0], name: 'submit_appraisal')]
public function submitAppraisal(string $_id, Request $request, TranslatorInterface $translator, SerializerInterface $serializer, MailgunService $mailgunService, NotificationService $notification, ICSService $ics, AppraisalService $appraisalService, LeaveService $leaveService, UserService $userService, LogService $log)
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($_id);
if ($appraisal == null) {
return $this->redirectToRoute('user_profile', ['g' => 'appraisal']);
};
$oldAppraisal = clone $appraisal;
$oldData = [];
$newData = [];
$userNote = null;
$appraisalNotes = null;
$userAppraisalNote = new AppraisalNote();
$loggedIn = $request ? true : false;
$concludeAppraisal = false;
$permanent=false;
if(!is_null($oldAppraisal)){
$permanent=$oldAppraisal->getUser()->getPersonalInfo()->getJobStatus();
if($permanent=='form.job_status.permanent'){$permanent=true;}else{$permanent=false;}
}
if ($appraisal->getAppraisalNotes() != null and count($appraisal->getAppraisalNotes()) > 0) {
$appraisalNotes = $this->getDoctrine()->getRepository(AppraisalNote::class)->findByAppraisal($appraisal);
$userNote = $this->getDoctrine()->getRepository(AppraisalNote::class)->findByAppraisalByUser($appraisal, $user);
if ($userNote != null) {
$userAppraisalNote = $userNote;
}
};
$oldUserNote = is_object($userNote) ? clone $userNote : null;
$appraisalNoteForm = $this->createForm(AppraisalNoteType::class, $userAppraisalNote);
// Only HR, Appraisse and included Manager access this function
if ($this->isGranted('ROLE_HR') || $appraisal->getUser() == $user || $appraisal->getUser()->getIsIncludedManager($user)) {
$categorizedAssessments = [];
$categories = $this->getDoctrine()->getRepository(AppraisalCategory::class)->findByCDT($appraisal->getUser()->assignedCompany(), $appraisal->getUser()->organizationDepartments(), $appraisal->getUser()->appraisalType($appraisal));
foreach($categories as $category){
foreach($category->getQuestionnaire() as $question){
$categorizedAssessments[] = $question;
}
}
if ($_SERVER['APP_ENV'] == "prod" && $appraisal->getUser()->inProbation() && $appraisal->getSubmitAt()->format('Ymd') < '20221001') {
$oldAssessments = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByCODA($appraisal->getUser()->assignedCompany(), $appraisal->getUser()->getOffice(), $appraisal->getUser()->organizationDepartments(), $appraisal);
} else {
$oldAssessments = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByType($appraisal->getUser()->assignedCompany(), $appraisal->getUser()->appraisalType($appraisal), $appraisal);
}
// This is to check between old and new assessments (has been categorized or not)
if(count($categorizedAssessments) > 0){
$assessments = $categorizedAssessments;
// Below are for combine old and new assessments
// if(count($oldAssessments) > 0){
// foreach($oldAssessments as $oldAssessment){
// $exist = false;
// foreach($categorizedAssessments as $assessment){
// if($oldAssessment->getId() == $assessment->getId()){
// $exist = true;
// break;
// }
// }
// if(!$exist){
// $assessments[] = $oldAssessment;
// }
// }
// }
} else {
$assessments = $oldAssessments;
}
if ($request->isMethod('post')) {
$entityManager = $this->getDoctrine()->getManager();
if ($user != $appraisal->getUser()) {
$requestNote = $request->request->get('appraisal_note');
$summary = false;
if ($userAppraisalNote->getId() && $userAppraisalNote->getNote() != '') {
$oldUserAppraisalNote = clone $userAppraisalNote;
} else {
$oldUserAppraisalNote = null;
};
if ($requestNote['note'] != '') {
$summary = $userAppraisalNote->getNote() == $requestNote['note'] ? false : $requestNote['note'];
$userAppraisalNote->setNote($requestNote['note']);
$userAppraisalNote->setDraft($request->request->get('draft') == "false" ? false : true);
};
if ($userNote == null) {
$userAppraisalNote->setAppraisal($appraisal);
$userAppraisalNote->setUser($user);
$userAppraisalNote->setCreatedAt(new \DateTime());
$entityManager->persist($userAppraisalNote);
} else {
$userAppraisalNote->setUpdatedAt(new \DateTime());
}
// Only proceed if it's not a draft anymore
if ($request->request->get('draft') == 'false') {
// Only proceed if it still not concluded yet
if (($appraisal->getConcludedAt() == null && $appraisal->getUser()->getIsIncludedManager($user)) || ($appraisal->getConcludedAt() == null && $this->isGranted('ROLE_HR'))) {
$currentStep = $appraisal->currentStep();
$objectiveInvitation = false;
$objectiveEmailTemplate = 'email/user-notification/appraisal/set-objective.html.twig';
$emailGroup = $this->getParameter('systemEmailGroup');
// Only proceed if in step 2 or 3
if ($currentStep == 2 && $appraisal->getUser()->getIsIncludedManager($user) || $currentStep == 3 && $appraisal->getUser()->getManager() == $user && $appraisal->getReviewAt() == null || $this->isGranted('ROLE_HR')) { // Manager or HR
if ($appraisal->getUser()->getManager() == $user) $appraisal->setReviewedAt(new \DateTime());
// if ($appraisal->getUser()->inProbation()) $appraisal->setReviewAt(\DateTime::createFromFormat('d/m/Y H:i', $request->request->get('reviewDate')));
if($request->request->get('reviewDate') != null){
$appraisal->setReviewAt(\DateTime::createFromFormat('d/m/Y H:i', $request->request->get('reviewDate')));
}
$entityManager->flush();
$entityManager->refresh($appraisal);
// Only proceed if user still in probation, so it can process to permanent or not
if ($appraisal->getUser()->inProbation() || $appraisal->getUser()->getManager() == $user && $appraisal->getConcludedAt() == null) {
$notificationData = [
'%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'%date%' => $appraisal->getReviewAt()->format('l, d M Y') . ' at ' . $appraisal->getReviewAt()->format('H:i')
];
$attendee = [
[
'name' => $user->getPersonalInfo()->getFullName(),
'email' => $user->getEmail(),
'role' => $appraisal->getUser()->getManager() == $user ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
],
[
'name' => $appraisal->getUser()->getPersonalInfo()->getFullName(),
'email' => $appraisal->getUser()->getEmail(),
'role' => 'REQ-PARTICIPANT'
],
];
foreach ($appraisal->getUser()->getAllManager() as $manager) {
if ($manager != $user) {
array_push($attendee, [
'name' => $manager->getPersonalInfo()->getFullName(),
'email' => $manager->getEmail(),
'role' => $appraisal->getUser()->getManager() == $manager ? 'REQ-PARTICIPANT' : 'OPT-PARTICIPANT'
]);
}
}
$endTime = new \DateTime($appraisal->getReviewAt()->format('Ymd H:i:s'));
$endTime->modify('+ 30 minutes');
$ICSTitle = $appraisal->getUser()->inProbation() ? 'Review (Probation)' : 'Review';
$icsData = $ics->generateEventFile([
'uid' => $appraisal->getId() . $appraisal->getUser()->getId() . ':' . $appraisal->getUser()->getEmail(),
'title' => $ICSTitle . ': ' . $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'description' => $translator->trans('ics.appraisal.description', ['%uid%' => $appraisal->getUser()->getId(), '%user%' => strtolower($appraisal->getUser()->getPersonalInfo()->getFirstName()), '%link%' => $this->generateUrl('user_profile', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getUser()->getEmail() . '?g=appraisal&open=appraisal-' . $appraisal->getId()]),
'startDateTime' => $appraisal->getReviewAt()->format('Ymd') . 'T' . $appraisal->getReviewAt()->format('His'),
'endDateTime' => $appraisal->getReviewAt()->format('Ymd') . 'T' . $endTime->format('His'),
'location' => $this->generateUrl('submit_appraisal', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getId(),
'organizer' => [
'name' => $this->getParameter('systemEmailName'),
'email' => $_SERVER['APP_ENV'] == 'prod' ? $this->getParameter('systemEmailAddr') : 'devops@mediatropy.com'
],
'attendee' => $attendee,
'reminderTime' => '-15M',
'reminderDescription' => $translator->trans('ics.appraisal.title') . ' ' . $appraisal->getTitle(),
'fileName' => 'Appraisal-' . $appraisal->getIcsToken()
], true);
if ($appraisal->getUser()->inProbation()) {
$emailTemplate = 'email/user-notification/appraisal/invitation-probation.html.twig';
$titleTemplate = 'email.appraisal.invitation.probation.';
$titleNotificationUser = $translator->trans('notification.appraisal.invitation.probation.user', ['%link%' => $this->generateURL('submit_appraisal') . '/' . $appraisal->getId()]);
$titleNotificationManager = $translator->trans('notification.appraisal.invitation.probation.manager', ['%link%' => $this->generateURL('submit_appraisal') . '/' . $appraisal->getId()]);
} else {
$emailTemplate = 'email/user-notification/appraisal/invitation-default.html.twig';
$titleTemplate = 'email.appraisal.invitation.default.';
$titleNotificationUser = $translator->trans('notification.appraisal.invitation.default.user', ['%link%' => $this->generateURL('submit_appraisal') . '/' . $appraisal->getId()]);
$titleNotificationManager = $translator->trans('notification.appraisal.invitation.default.manager', ['%link%' => $this->generateURL('submit_appraisal') . '/' . $appraisal->getId()]);
};
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans($titleTemplate . 'user', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%date%' => $appraisal->getReviewAt()->format('l, d M Y')]),
'to' => $appraisal->getUser()->getEmail(),
'template' => $emailTemplate,
'params' => [
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user'
],
'ical' => $icsData
], $loggedIn);
$notification->push($appraisal->getUser(), $titleNotificationUser, $notificationData, 'i-review', $appraisal->getId());
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans($titleTemplate . 'manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%date%' => $appraisal->getReviewAt()->format('l, d M Y')]),
'to' => $manager->getEmail(),
'template' => $emailTemplate,
'params' => [
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager'
],
'ical' => $icsData
], $loggedIn);
$notification->push($manager, $titleNotificationManager, $notificationData, 'i-review', $appraisal->getId());
}
foreach ($emailGroup as $groupName => $groupEmail) {
if ($groupName == 'hr') { // only HR
$mailgunService->sendEmailWithAttachment([
'subject' => $translator->trans($titleTemplate . 'hr', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%date%' => $appraisal->getReviewAt()->format('l, d M Y')]),
'to' => $groupEmail,
'template' => $emailTemplate,
'params' => [
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName
],
'ical' => $icsData
], $loggedIn);
};
};
} elseif ($appraisal->getUser()->getIsIncludedManager($user) && $appraisal->getConcludedAt() == null) { // Yearly
if ($appraisal->getProbation() == true) {
$emailTemplate = 'email/user-notification/appraisal/manager-submitted-probation.html.twig';
$titleTemplate = 'email.appraisal.submitted.manager_probation.';
} else {
$emailTemplate = 'email/user-notification/appraisal/manager-submitted-default.html.twig';
$titleTemplate = 'email.appraisal.submitted.manager_default.';
};
// $mailgunService->sendEmail(
// $translator->trans($titleTemplate . 'manager'),
// [$user->getEmail()],
// $emailTemplate,
// [
// 'recipient' => $user,
// 'sender' => $user,
// 'group' => 'manager',
// 'appraisal' => $appraisal,
// ]
// );
// foreach ($appraisal->getUser()->getAllManager() as $manager) {
// $mailgunService->sendEmail(
// $translator->trans($titleTemplate . 'manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
// [$manager->getEmail()],
// $emailTemplate,
// [
// 'recipient' => $manager,
// 'group' => 'manager',
// 'appraisal' => $appraisal,
// ]
// );
// }
// $appraisal->setReviewAt(new \DateTime());
foreach ($emailGroup as $groupName => $groupEmail) {
if ($groupName == 'hr') { // only HR
$mailgunService->sendEmail(
$translator->trans($titleTemplate . 'hr', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFullName()]),
[$groupEmail],
$emailTemplate,
[
'recipient' => strtoupper($groupName) . ' Team',
'group' => $groupName,
'appraisal' => $appraisal,
]
);
};
};
}
} elseif (in_array($currentStep, [4, 5]) == true && $appraisal->getUser()->inProbation() && $appraisal->getAdHoc() == false) { // Probation User
$expiryDate = $appraisal->getUser()->getPersonalInfo()->getJobExpiryDate() ? $appraisal->getUser()->getPersonalInfo()->getJobExpiryDate() : new \DateTime();
$joinDate = $appraisal->getUser()->getPersonalInfo()->getJobJoinDate();
$conclusion = $request->request->get('conclusion');
$notificationData = [
'%link%' => '<a href="' . $this->generateURL('submit_appraisal') . '/' . $appraisal->getId() . '">Probation\'s Appraisal Form</a>'
];
switch ($conclusion) {
case 'permanent':
//$newExpiryDate = date('Y-m-d', strtotime('6 months', $expiryDate->getTimestamp()));
/*$newExpiryDate = $userService->nextReviewDate();
$appraisal->getUser()->getPersonalInfo()->setJobExpiryDate(\DateTime::createFromFormat('Y-m-d', $newExpiryDate));
/*$totalProbation = 3 + $appraisal->getExtendedProbation();
echo $totalProbation.' '.$appraisal->getExtendedProbation();
$becomePermanentDate = $joinDate->modify('+'.$totalProbation.' months');
dump($becomePermanentDate);die;*/
//$appraisal->getUser()->getPersonalInfo()->setJobPermanentDate($joinDate->modify('+3 months'));
$attributes = $appraisal->getUser()->assignedCompany()->getAttributes();
$newExpiryDate = isset($attributes['appraisalEndAt']) ? new \DateTime($attributes['appraisalEndAt']['date']) : new \DateTime('+ 1 years');
$appraisal->getUser()->getPersonalInfo()->setJobExpiryDate($newExpiryDate);
$appraisal->getUser()->getPersonalInfo()->setJobPermanentDate($expiryDate);
$emailTemplate = 'email/user-notification/appraisal/conclude-pass.html.twig';
$titleTemplate = 'email.appraisal.concluded.pass.';
$objectiveInvitation = true;
$concludeAppraisal = true;
$notification->push($appraisal->getUser(), 'notification.appraisal.concluded.pass', $notificationData, 'i-star-svg', $appraisal->getId());
break;
case 'limited':
$newExpiryDate = date('Y-m-d', strtotime('3 months', $expiryDate->getTimestamp()));
$appraisal->getUser()->getPersonalInfo()->setJobExpiryDate(\DateTime::createFromFormat('Y-m-d', $newExpiryDate));
$emailTemplate = 'email/user-notification/appraisal/conclude-pass.html.twig';
$titleTemplate = 'email.appraisal.concluded.pass.';
$objectiveInvitation = true;
$concludeAppraisal = true;
$notification->push($appraisal->getUser(), 'notification.appraisal.concluded.pass', $notificationData, 'i-star-svg', $appraisal->getId());
break;
case 'temporary':
$newExpiryDate = date('Y-m-d', strtotime('3 months', $expiryDate->getTimestamp()));
$appraisal->getUser()->getPersonalInfo()->setJobExpiryDate(\DateTime::createFromFormat('Y-m-d', $newExpiryDate));
$emailTemplate = 'email/user-notification/appraisal/conclude-pass.html.twig';
$titleTemplate = 'email.appraisal.concluded.pass.';
$objectiveInvitation = true;
$concludeAppraisal = true;
$notification->push($appraisal->getUser(), 'notification.appraisal.concluded.pass', $notificationData, 'i-star-svg', $appraisal->getId());
break;
case 'fail':
$appraisal->getUser()->getPersonalInfo()->setJobTerminateReason('form.terminate_reason.probation_failed');
$appraisal->getUser()->getPersonalInfo()->setJobTerminateDate($expiryDate);
$emailTemplate = 'email/user-notification/appraisal/conclude-fail.html.twig';
$titleTemplate = 'email.appraisal.concluded.fail.';
break;
default: // Extended
$newExpiryDate = date('Y-m-d', strtotime($conclusion == 1 ? '1 month' : '3 months', $expiryDate->getTimestamp()));
$appraisal->getUser()->getPersonalInfo()->setJobExpiryDate(\DateTime::createFromFormat('Y-m-d', $newExpiryDate));
//$previousExtendedProbation = $appraisal->getUser()->getPersonalInfo()->getExtendedProbation();
//$appraisal->getUser()->getPersonalInfo()->setExtendedProbation($previousExtendedProbation + $conclusion);
$emailTemplate = 'email/user-notification/appraisal/conclude-extend.html.twig';
$titleTemplate = 'email.appraisal.concluded.extend.';
$concludeAppraisal = true;
$notification->push($appraisal->getUser(), 'notification.appraisal.concluded.extend', $notificationData, 'i-star-blank-svg', $appraisal->getId());
break;
};
$appraisal->setConcludedAt(new \DateTime());
// Email
$mailgunService->sendEmail(
$translator->trans($titleTemplate . 'user', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
[$appraisal->getUser()->getEmail()],
$emailTemplate,
[
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user',
'conclusion' => $conclusion
]
);
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmail(
$translator->trans($titleTemplate . 'manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
[$manager->getEmail()],
$emailTemplate,
[
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager',
'conclusion' => $conclusion
]
);
}
foreach ($emailGroup as $groupName => $groupEmail) {
if ($groupEmail != '') {
$mailgunService->sendEmail(
$translator->trans($titleTemplate . $groupName, ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
[$groupEmail],
$emailTemplate,
[
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName,
'conclusion' => $conclusion
]
);
};
};
switch ($conclusion) {
case 'permanent':
$appraisal->getUser()->getPersonalInfo()->setJobStatus('form.job_status.permanent');
break;
case 'limited':
$appraisal->getUser()->getPersonalInfo()->setJobStatus('form.job_status.time_limited');
break;
case 'temporary':
$appraisal->getUser()->getPersonalInfo()->setJobStatus('form.job_status.temporary');
break;
};
} elseif (in_array($currentStep, [4, 5]) == true && $appraisal->getUser()->inProbation() == false && $appraisal->getAdHoc() == false) { // Permanent User
//$expiryDate = $appraisal->getUser()->getPersonalInfo()->getJobExpiryDate();
//$newExpiryDate = $expiryDate ? date('Y-m-d', strtotime('6 months', $expiryDate->getTimestamp())) : date('Y-m-d');
/*$newExpiryDate = $userService->nextReviewDate();
$appraisal->getUser()->getPersonalInfo()->setJobExpiryDate(\DateTime::createFromFormat('Y-m-d', $newExpiryDate));*/
// $oldData = clone $appraisal->getUser()->getPersonalInfo();
if($appraisal->getUser()->getManager() == $user){
$appraisal->setConcludedAt(new \DateTime());
$concludeAppraisal = true;
}
} elseif ($appraisal->getAdHoc()) {
// $oldData = clone $appraisal->getUser()->getPersonalInfo();
$appraisal->setConcludedAt(new \DateTime());
$concludeAppraisal = true;
}
if ($summary) {
//$updateSummary = $userNote == null ? null : ' (update)';
$updateSummary = null;
if ($appraisal->getAdHoc()) {
$titleTemplate = 'email.appraisal.ad_hoc.';
$emailTemplate = 'email/user-notification/appraisal/summary-ad-hoc.html.twig';
} else {
$titleTemplate = 'email.appraisal.summary.';
$emailTemplate = 'email/user-notification/appraisal/summary.html.twig';
};
//Summary Copy
$mailgunService->sendEmail(
$translator->trans($titleTemplate . 'user', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%date%' => $appraisal->getReviewAt()->format('d F Y')]) . $updateSummary,
[$appraisal->getUser()->getEmail()],
$emailTemplate,
[
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'summary' => $summary,
'group' => 'user'
]
);
//$notification->push($appraisal->getUser(),'notification.objective.invitation.user', $notificationData, 'i-review', $appraisal->getId());
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmail(
$translator->trans($titleTemplate . 'manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFullName(), '%manager%' => $manager->getPersonalInfo()->getFirstName(), '%date%' => $appraisal->getReviewAt()->format('d F Y')]) . $updateSummary,
[$manager->getEmail()],
$emailTemplate,
[
'recipient' => $manager,
'appraisal' => $appraisal,
'summary' => $summary,
'group' => 'manager'
]
);
//$notification->push($manager,'notification.objective.invitation.manager', $notificationData, 'i-review', $appraisal->getId());
}
foreach ($emailGroup as $groupName => $groupEmail) {
if ($appraisal->getUser()->inProbation() == false && $groupName == 'finance') continue;
$mailgunService->sendEmail(
$translator->trans($titleTemplate . $groupName, ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFullName(), '%date%' => $appraisal->getReviewAt()->format('d F Y')]) . $updateSummary,
[$groupEmail],
$emailTemplate,
[
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'summary' => $summary,
'group' => $groupName,
]
);
};
};
//Objective Invitation
/*
if ($objectiveInvitation) {
$notificationData = [
'%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'%link%' => '<a href="' . $this->generateURL('user_profile') . '/' . $appraisal->getUser()->getEmail() . '?g=objective">Objectives</a>'
];
$mailgunService->sendEmail(
$translator->trans('email.objective.invitation.user', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
[$appraisal->getUser()->getEmail()],
$objectiveEmailTemplate,
[
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user'
]
);
$notification->push($appraisal->getUser(), 'notification.objective.invitation.user', $notificationData, 'i-review', $appraisal->getId());
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmail(
$translator->trans('email.objective.invitation.manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
[$manager->getEmail()],
$objectiveEmailTemplate,
[
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager'
]
);
$notification->push($manager, 'notification.objective.invitation.manager', $notificationData, 'i-review', $appraisal->getId());
}
foreach ($emailGroup as $groupName => $groupEmail) {
if ($groupName == 'hr') {
$mailgunService->sendEmail(
$translator->trans('email.objective.invitation.hr', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%manager%' => $appraisal->getUser()->getManager()->getPersonalInfo()->getFirstName()]),
[$groupEmail],
$objectiveEmailTemplate,
[
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName
]
);
}
};
}*/
};
};
};
// Only proceed if $user not yet in "reviewed" table or if it for amend purpose
if (!$appraisal->hasReviewed($user)){
foreach ($assessments as $assessment) {
try {
$comment = $assessment->appraisalCommentsByOwner($_id, $user->getId());
if ($comment != null) {
$_comment = clone $comment;
array_push($oldData, $_comment);
if ($request->request->get('score-' . $assessment->getId()) != null) $comment->setScore($request->request->get('score-' . $assessment->getId()));
if ($request->request->get('comment-' . $assessment->getId()) != null) $comment->setComment($request->request->get('comment-' . $assessment->getId()));
$comment->setDraft($request->request->get('draft') == "false" ? false : true);
$comment->setUpdatedAt(new \DateTime());
if ($user == $appraisal->getUser())
$comment->setFormContent($serializer->serialize($serializer->normalize($assessment, null, ['groups' => 'Appraisal']), 'json'));
} else {
$comment = new AppraisalComment();
if ($request->request->get('score-' . $assessment->getId()) != null) $comment->setScore($request->request->get('score-' . $assessment->getId()));
if ($request->request->get('comment-' . $assessment->getId()) != null) $comment->setComment($request->request->get('comment-' . $assessment->getId()));
$comment->setForm($assessment);
$comment->setAppraisal($appraisal);
$comment->setDraft($request->request->get('draft') == "false" ? false : true);
$comment->setCreatedAt(new \DateTime());
if ($user == $appraisal->getUser()) {
$comment->setUser($appraisal->getUser());
$comment->setType('submit');
} else {
$comment->setUser($user);
$comment->setType('review');
};
if ($user == $appraisal->getUser())
$comment->setFormContent($serializer->serialize($serializer->normalize($assessment, null, ['groups' => 'Appraisal']), 'json'));
$entityManager->persist($comment);
//$oldData = null;
}
array_push($newData, $comment);
} catch (Throwable $t) {
continue;
}
}
if ($user == $appraisal->getUser() && $request->request->get('draft') == 'false') {
$appraisal->setSubmittedAt(new \DateTime());
if ($appraisal->getUser()->inProbation()) {
$emailTitle = 'email.appraisal.submitted.probation.';
$emailTemplate = 'email/user-notification/appraisal/submitted-probation.html.twig';
$titleNotification = 'notification.appraisal.submitted.probation.';
$notificationLinkTitle = 'Appraisal (Probation) Form';
} else {
$emailTitle = 'email.appraisal.submitted.default.';
$emailTemplate = 'email/user-notification/appraisal/submitted-default.html.twig';
$titleNotification = 'notification.appraisal.submitted.default.';
$notificationLinkTitle = 'Appraisal Form';
};
$notificationData = [
'%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(),
'%link%' => '<a href="' . $this->generateURL('submit_appraisal') . '/' . $appraisal->getId() . '">' . $notificationLinkTitle . '</a>',
];
$mailgunService->sendEmail(
$translator->trans($emailTitle . 'user', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName()]),
[$appraisal->getUser()->getEmail()],
$emailTemplate,
[
'recipient' => $appraisal->getUser(),
'appraisal' => $appraisal,
'group' => 'user'
],
$loggedIn
);
$notification->push($appraisal->getUser(), $titleNotification . 'user', $notificationData, 'i-review', $appraisal->getId());
foreach ($appraisal->getUser()->getAllManager() as $manager) {
$mailgunService->sendEmail(
$translator->trans($emailTitle . 'manager', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%manager%' => $manager->getPersonalInfo()->getFirstName()]),
[$manager->getEmail()],
$emailTemplate,
[
'recipient' => $manager,
'appraisal' => $appraisal,
'group' => 'manager'
],
$loggedIn
);
$notification->push($manager, $titleNotification . 'manager', $notificationData, 'i-review', $appraisal->getId());
}
$emailGroup = $this->getParameter('systemEmailGroup');
foreach ($emailGroup as $groupName => $groupEmail) {
try {
if ($groupName == 'hr') {
$mailgunService->sendEmail(
$translator->trans($emailTitle . 'hr', ['%user%' => $appraisal->getUser()->getPersonalInfo()->getFirstName(), '%manager%' => $appraisal->getUser()->getManager()->getPersonalInfo()->getFirstName()]),
[$groupEmail],
$emailTemplate,
[
'recipient' => strtoupper($groupName) . ' Team',
'appraisal' => $appraisal,
'group' => $groupName,
],
$loggedIn
);
};
} catch (Exception $e) {
}
};
/*
if ($_SERVER['NOTIF_SUPER_ADMIN'] == 'true') {
foreach ($user->assignedCompany()->superAdmins($user) as $superAdmin) {
if ($superAdmin != $user && !in_array($superAdmin, $appraisal->getUser()->getAllManager())) {
$mailgunService->sendEmail(
$translator->trans('email.system.copy_super_admin').' '.$subject,
[$superAdmin->getEmail()],
'email/user-notification/appraisal-review.html.twig',
[
'user' => $appraisal->getUser(),
'user_creator' => $user,
'user_cc' => $superAdmin,
'appraisal' => $appraisal,
]
);
};
}
};*/
} elseif ($request->request->get('draft') == 'false') {
/*
$mailgunService->scheduleEmail([
'subject' => $appraisal->getTitle() . ' | ' .$appraisal->getUser()->getPersonalInfo()->getFirstName(). ' | '.$translator->trans('email.appraisal.result'),
'to' => [$appraisal->getUser()->getEmail()],
'template' => 'email/user-notification/appraisal-result.html.twig',
'params' => [
'user' => $appraisal->getUser(),
'appraisal' => $appraisal,
],
], $appraisal->getReviewAt(), $user, 'Appraisal', $appraisal->getId());*/
if ($appraisal->getUser()->getManager() != $user && $appraisal->getUser()->getisIncludedManager($user)) {
// $notification->push($appraisal->getUser(), [
// 'message' => 'notification.appraisal.reviewed_alt',
// 'entity' => 'Appraisal',
// 'objectId' => $appraisal->getId(),
// 'data' => $serializer->serialize([
// 'title' => $appraisal->getTitle(),
// 'url' => $this->generateUrl('submit_appraisal') . '/' . $appraisal->getId(),
// 'manager' => $user->getPersonalInfo()->getFirstName()
// ], 'json')
// ], true);
/*
$subject = $appraisal->getTitle() . ' | ' . $appraisal->getUser()->getPersonalInfo()->getFirstName() . ' | ' . $translator->trans('email.appraisal.result');
$mailgunService->sendEmail(
$subject,
[$appraisal->getUser()->getEmail()],
'email/user-notification/appraisal-review.html.twig',
[
'recipient' => $appraisal->getUser(),
'sender' => $user,
'appraisal' => $appraisal,
]
);*/
}
}
}
if ($user != $appraisal->getUser() && $request->request->get('draft') == "false" ){
// if($currentStep == 2) $appraisal->setReviewedBy($user);
$appraisal->addReviewer($user);
}
$entityManager->flush();
$entityManager->refresh($appraisal);
$appraisalService->syncAppraisalStatus($appraisal->getUser());
//$leaveService->leavePermanent($appraisal->getUser(),false,false,null,$permanent);
if ($concludeAppraisal && $appraisal->getUser()->latestAppraisal($appraisal)) {
/*
$inProbation = $appraisal->getUser()->inProbation();
$nextTitleDate = $inProbation ? '' : ucfirst(date('M'));
$appraisalService->initiateAppraisal($request, $user, $appraisal->getUser(), $translator->trans($inProbation ? 'page.appraisal.title.list.probation' : 'page.appraisal.title.list.objective').' '.$nextTitleDate, $appraisal->getUser()->getPersonalInfo()->getJobExpiryDate()->modify('- 1 weeks'), null, null, null);
*/
};
if ($request->request->get('draft') == 'false') {
if ($user == $appraisal->getUser()) {
$this->addFlash(
'success',
'messages.appraisal.submit'
);
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.submit',
'old_data' => $oldData,
'new_data' => $newData
]);
} else {
if ($request->request->get('note') == 'true') {
if ($appraisal->getAdHoc()) {
$this->addFlash(
'success',
'messages.appraisal.ad_hoc'
);
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.ad_hoc.update',
'old_data' => [],
'new_data' => $appraisal->getUser()->getPersonalInfo()
]);
} else if ($request->request->get('conclusion') || $concludeAppraisal) {
$this->addFlash(
'success',
'messages.appraisal.conclude'
);
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.conclude',
'old_data' => [],
'new_data' => $appraisal->getUser()->getPersonalInfo()
]);
} else {
$this->addFlash(
'success',
'messages.appraisal.summary.save'
);
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => $oldUserAppraisalNote ? 'log.appraisal.note.update' : 'log.appraisal.note.add',
'old_data' => $oldUserAppraisalNote,
'new_data' => $userAppraisalNote
]);
}
} else {
$this->addFlash(
'success',
'messages.appraisal.review'
);
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.review',
'old_data' => $oldData,
'new_data' => $newData
]);
}
}
/* $log->save($user, [
'owner' => $appraisal->getUser(),
'message' => $logDesc,
'old_data' => $oldData,
'new_data' => $newData
], false, true);*/
} else if ($user != $appraisal->getUser() && $request->request->get('note') == 'true' && $userAppraisalNote->getDraft()) {
$userAppraisalNote->setDraft(false);
$entityManager->flush();
$this->addFlash(
'success',
'messages.appraisal.summary.submit'
);
// $log->save($user, [
// 'owner' => $appraisal->getUser(),
// 'message' => 'log.appraisal.review',
// 'old_data' => $oldData,
// 'new_data' => $newData
// ]);
} else {
$log->save($user, [
'owner' => $appraisal->getUser(),
'message' => 'log.appraisal.draft',
'old_data' => $oldData,
'new_data' => $newData
]);
$this->addFlash(
'success',
'messages.appraisal.draft'
);
}
return $this->redirect($request->getUri());
};
return $this->render('private/appraisal/appraisal.html.twig', [
'appraisal' => $appraisal,
'assessments' => $assessments,
'categorizedAssessments' => $categorizedAssessments,
'appraisalNotes' => $appraisalNotes,
'appraisalNoteForm' => $appraisalNoteForm->createView()
//'formComments' => $formComments
//'form' => $form->createView()
]);
} else {
throw new \Exception($translator->trans('messages.security.forbidden'));
//throw $this->createNotFoundException($translator->trans('messages.error.not_found'));
}
}
#[Route(path: '/ajax/save-appraisal', name: 'ajax_save_appraisal')]
public function saveAppraisal(Request $request, TranslatorInterface $translator, SerializerInterface $serializer): JsonResponse
{
/*if (!$this->isGranted('ROLE_STAFF')) {
return new JsonResponse([
'status' => "TIMEOUT",
]);
}*/
$_id = $request->request->get('appraisalId');
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($_id);
if ($appraisal == null) {
return $this->redirectToRoute('user_profile', ['g' => 'appraisal']);
};
$oldData = [];
$newData = [];
$userNote = null;
$appraisalNotes = null;
$userAppraisalNote = new AppraisalNote();
if ($appraisal->getAppraisalNotes() != null and count($appraisal->getAppraisalNotes()) > 0) {
$appraisalNotes = $this->getDoctrine()->getRepository(AppraisalNote::class)->findByAppraisal($appraisal);
$userNote = $this->getDoctrine()->getRepository(AppraisalNote::class)->findByAppraisalByUser($appraisal, $user);
if ($userNote != null) {
$userAppraisalNote = $userNote;
}
};
$oldUserNote = is_object($userNote) ? clone $userNote : null;
$appraisalNoteForm = $this->createForm(AppraisalNoteType::class, $userAppraisalNote);
$result['status'] = 'OK';
if ($this->isGranted('ROLE_HR') || $appraisal->getUser() == $user || $appraisal->getUser()->getIsIncludedManager($user)) {
if ($_SERVER['APP_ENV'] == "prod" && $appraisal->getUser()->inProbation() && $appraisal->getSubmitAt()->format('Ymd') < '20221001') {
$assessments = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByCODA($appraisal->getUser()->assignedCompany(), $appraisal->getUser()->getOffice(), $appraisal->getUser()->organizationDepartments(), $appraisal);
} else {
$assessments = $this->getDoctrine()->getRepository(AppraisalForm::class)->findByType($appraisal->getUser()->assignedCompany(), $appraisal->getUser()->appraisalType($appraisal), $appraisal);
}
if ($request->isMethod('post')) {
$entityManager = $this->getDoctrine()->getManager();
if (!$appraisal->hasReviewed($user)) {
foreach ($assessments as $assessment) {
$comment = $assessment->appraisalCommentsByOwner($_id, $user->getId());
if ($comment != null) {
$_comment = clone $comment;
array_push($oldData, $_comment);
if ($request->request->get('score-' . $assessment->getId()) != null) $comment->setScore($request->request->get('score-' . $assessment->getId()));
if ($request->request->get('comment-' . $assessment->getId()) != null) $comment->setComment($request->request->get('comment-' . $assessment->getId()));
$comment->setDraft($request->request->get('draft') == "false" ? false : true);
$comment->setUpdatedAt(new \DateTime());
if ($user == $appraisal->getUser())
$comment->setFormContent($serializer->serialize($serializer->normalize($assessment, null, ['groups' => 'Appraisal']), 'json'));
} else {
$comment = new AppraisalComment();
if ($request->request->get('score-' . $assessment->getId()) != null) $comment->setScore($request->request->get('score-' . $assessment->getId()));
if ($request->request->get('comment-' . $assessment->getId()) != null) $comment->setComment($request->request->get('comment-' . $assessment->getId()));
$comment->setForm($assessment);
$comment->setAppraisal($appraisal);
$comment->setDraft($request->request->get('draft') == "false" ? false : true);
$comment->setCreatedAt(new \DateTime());
if ($user == $appraisal->getUser()) {
$comment->setUser($appraisal->getUser());
$comment->setType('submit');
} else {
$comment->setUser($user);
$comment->setType('review');
};
if ($user == $appraisal->getUser())
$comment->setFormContent($serializer->serialize($serializer->normalize($assessment, null, ['groups' => 'Appraisal']), 'json'));
$entityManager->persist($comment);
//$oldData = null;
}
array_push($newData, $comment);
}
}
if ($user != $appraisal->getUser()) {
$requestNote = $request->request->get('appraisal_note');
if ($requestNote != '') {
$userAppraisalNote->setNote($requestNote['note']);
$userAppraisalNote->setDraft($request->request->get('draft') == "false" ? false : true);
if ($userNote == null) {
$userAppraisalNote->setAppraisal($appraisal);
$userAppraisalNote->setUser($user);
$userAppraisalNote->setCreatedAt(new \DateTime());
$entityManager->persist($userAppraisalNote);
} else {
$userAppraisalNote->setUpdatedAt(new \DateTime());
}
};
};
}
$entityManager->flush();
} else {
$result['status'] = 'ERROR';
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/save-appraisal-field', name: 'ajax_save_appraisal_field')]
public function saveAppraisalField(Request $request, TranslatorInterface $translator, SerializerInterface $serializer): JsonResponse
{
/*if (!$this->isGranted('ROLE_STAFF')) {
return new JsonResponse([
'status' => "TIMEOUT",
]);
}*/
$appraisalId = $request->request->get('appraisalId');
$appraisalCommentValue = $request->request->get('comment');
$appraisalScoreValue = $request->request->get('score');
$formId = $request->request->get('formId');
if($appraisalId == null || $formId == null){
return new JsonResponse([
'status' => "ID Missing",
]);
}
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->find($appraisalId);
$appraisalForm = $this->getDoctrine()->getRepository(AppraisalForm::class)->find($formId);
$appraisalComment = $this->getDoctrine()->getRepository(AppraisalComment::class)->findByAppraisalForm($appraisalId, $formId, $user);
if($appraisalComment == null){
$appraisalComment = new AppraisalComment();
};
$result['status'] = 'OK';
if ($appraisalId && ($this->isGranted('ROLE_HR') || $appraisal->getUser() == $user || $appraisal->getUser()->getIsIncludedManager($user))) {
$entityManager = $this->getDoctrine()->getManager();
if($appraisalScoreValue) $appraisalComment->setScore($appraisalScoreValue);
if($appraisalCommentValue) $appraisalComment->setComment($appraisalCommentValue);
$appraisalComment->setFormContent($serializer->serialize($serializer->normalize($appraisalForm, null, ['groups' => 'Appraisal']), 'json'));
if($appraisalComment->getId() == null){
if ($user == $appraisal->getUser()) {
$appraisalComment->setUser($appraisal->getUser());
$appraisalComment->setType('submit');
} else {
$appraisalComment->setUser($user);
$appraisalComment->setType('review');
};
$appraisalComment->setAppraisal($appraisal);
$appraisalComment->setForm($appraisalForm);
$appraisalComment->setDraft(true);
$appraisalComment->setCreatedAt(new \DateTime());
$entityManager->persist($appraisalComment);
} else {
$appraisalComment->setUpdatedAt(new \DateTime());
}
$entityManager->flush();
if($appraisalComment->getDraft() == false && $appraisalScoreValue){
$result['questionScore'] = $appraisal->appraisalQuestionScore($appraisalComment);
$result['appraisalScore'] = $appraisal->appraisalScore();
}
} else {
$result['status'] = 'ERROR';
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/add-appraisal', name: 'ajax_add_appraisal')]
public function ajaxAddAppraisal(Request $request, TranslatorInterface $translator): JsonResponse
{
$user = $this->getUser();
$appraisal = new AppraisalForm();
$form = $this->createForm(AppraisalType::class, $appraisal);
if ($this->isGranted('ROLE_ACCESS_ALL_OFFICE')) {
$office_choices['form.office.all'] = null;
foreach ($user->assignedOffices() as $office) {
$office_choices[$office->getFullName()] = $office->getId();
};
$form->add('office', ChoiceType::class, [
'mapped' => false,
'label' => 'Office',
'choices' => $office_choices,
'placeholder' => 'form.placeholder.choice'
]);
};
$department_choices['form.department.all'] = null;
foreach ($user->assignedCompany()->getDepartments() as $department) {
$department_choices[$department->getName()] = $department->getId();
};
$form->add('department', ChoiceType::class, [
'mapped' => false,
'label' => 'Department',
'choices' => $department_choices,
'placeholder' => 'form.placeholder.choice'
]);
$form->handleRequest($request);
$result['status'] = 'OK';
if ($form->isSubmitted() && !$form->isValid() && $result['status'] == 'OK') {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
};
if ($result['status'] == 'OK') {
$appraisal->setCreatedBy($user);
$appraisal->setCreatedAt(new \DateTime());
$appraisal->setCompany($user->assignedCompany());
if ($this->isGranted('ROLE_ACCESS_ALL_OFFICE')) {
if ($form->get('office')->getData() != null) {
$office = $this->getDoctrine()->getRepository(Office::class)->find($form->get('office')->getData());
$appraisal->setOffice($office);
} else {
$appraisal->setOffice(null);
}
} else {
$appraisal->setOffice($user->getOffice());
}
if ($form->get('department')->getData() != null) {
$department = $this->getDoctrine()->getRepository(Department::class)->find($form->get('department')->getData());
$appraisal->setDepartment($department);
} else {
$appraisal->setDepartment(null);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($appraisal);
$entityManager->flush();
$result['content'] = $this->renderView('private/appraisal/components/edit-appraisal-list.html.twig', [
'appraisal' => $appraisal,
'waitForPage' => false
]);
};
return new JsonResponse($result);
}
#[Route(path: '/ajax/edit-appraisal', name: 'ajax_edit_appraisal')]
public function ajaxEditAppraisal(Request $request, TranslatorInterface $translator): \Symfony\Component\HttpFoundation\Response
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(AppraisalForm::class)->find($request->get("id"));
$formAppraisal = $this->createForm(AppraisalType::class, $appraisal);
if ($this->isGranted('ROLE_ACCESS_ALL_OFFICE')) {
$office_choices['form.office.all'] = null;
foreach ($user->assignedOffices() as $office) {
$office_choices[$office->getFullName()] = $office->getId();
};
$formAppraisal->add('office', ChoiceType::class, [
'mapped' => false,
'label' => 'Office',
'choices' => $office_choices,
'placeholder' => 'form.placeholder.choice',
'data' => $appraisal->getOffice() ? $appraisal->getOffice()->getId() : null,
]);
};
$department_choices['form.department.all'] = null;
foreach ($user->assignedCompany()->getDepartments() as $department) {
$department_choices[$department->getName()] = $department->getId();
};
$formAppraisal->add('department', ChoiceType::class, [
'mapped' => false,
'label' => 'Department',
'choices' => $department_choices,
'placeholder' => 'form.placeholder.choice',
'data' => $appraisal->getDepartment() ? $appraisal->getDepartment()->getId() : null,
]);
return $this->render('private/appraisal/components/form-appraisal.html.twig', [
'dataId' => $appraisal->getId(),
'formAppraisal' => $formAppraisal->createView()
]);
}
#[Route(path: '/ajax/update-appraisal', name: 'ajax_update_appraisal', methods: 'POST')]
function ajaxUpdateAppraisal(Request $request, TranslatorInterface $translator)
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(AppraisalForm::class)->find($request->get("dataId"));
$result['status'] = 'OK';
if ($appraisal != null) {
// if ($user->assignedCompany() != $appraisal->getCompany() || !$this->isGranted('ROLE_HR')) {
// $result['status'] = 'ERROR';
// $result['message'] = $translator->trans('messages.security.forbidden');
// };
$form = $this->createForm(AppraisalType::class, $appraisal);
if ($this->isGranted('ROLE_ACCESS_ALL_OFFICE')) {
$office_choices['form.office.all'] = null;
foreach ($user->assignedOffices() as $office) {
$office_choices[$office->getFullName()] = $office->getId();
};
$form->add('office', ChoiceType::class, [
'mapped' => false,
'label' => 'Office',
'choices' => $office_choices,
'placeholder' => 'form.placeholder.choice'
]);
};
$department_choices['form.department.all'] = null;
foreach ($user->assignedCompany()->getDepartments() as $department) {
$department_choices[$department->getName()] = $department->getId();
};
$form->add('department', ChoiceType::class, [
'mapped' => false,
'label' => 'Department',
'choices' => $department_choices,
'placeholder' => 'form.placeholder.choice'
]);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid() && $result['status'] == 'OK') {
$result['status'] = 'ERROR';
foreach ($form->getErrors(true) as $key => $error) {
$result['message'][$key] = $error->getMessage();
}
};
if ($result['status'] == 'OK') {
if ($this->isGranted('ROLE_ACCESS_ALL_OFFICE')) {
if ($form->get('office')->getData() != null) {
$office = $this->getDoctrine()->getRepository(Office::class)->find($form->get('office')->getData());
$appraisal->setOffice($office);
} else {
$appraisal->setOffice(null);
}
} else {
$appraisal->setOffice($user->getOffice());
}
if ($form->get('department')->getData() != null) {
$department = $this->getDoctrine()->getRepository(Department::class)->find($form->get('department')->getData());
$appraisal->setDepartment($department);
} else {
$appraisal->setDepartment(null);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
$result['id'] = $appraisal->getId();
$result['content'] = $this->renderView('private/appraisal/components/edit-appraisal-list.html.twig', [
'appraisal' => $appraisal,
'waitForPage' => false
]);
$result['update'] = true;
}
} else {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
}
return new JsonResponse($result);
}
#[Route(path: '/ajax/delete-appraisal', name: 'ajax_delete_appraisal', methods: 'POST')]
function ajaxDeleteAppraisal(Request $request, TranslatorInterface $translator): JsonResponse
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(AppraisalForm::class)->find($request->get("id"));
$result['status'] = 'OK';
if ($appraisal != null) {
// if ($user->assignedCompany() != $appraisal->getCompany() || !$this->isGranted('ROLE_HR')) {
// $result['status'] = 'ERROR';
// $result['message'] = $translator->trans('messages.security.forbidden');
// };
if ($result['status'] == 'OK') {
$entityManager = $this->getDoctrine()->getManager();
// The keep consistenty, the form will not be actually deleted if got some comments
if (count($appraisal->getAppraisalComments()) > 0) {
$appraisal->setIsHidden(true);
} else {
$entityManager->remove($appraisal);
}
$entityManager->remove($appraisal);
$entityManager->flush();
}
} else {
$result['status'] = 'ERROR';
$result['message'] = $translator->trans('messages.request.missing');
}
return new JsonResponse($result);
}
#[Route(path: '/download/ics/appraisal/{token}.ics', name: 'download_ics_appraisal')]
public function downloadAppraisalICS(Request $request, TranslatorInterface $translator, ICSService $ics)
{
$user = $this->getUser();
$appraisal = $this->getDoctrine()->getRepository(Appraisal::class)->findByToken($request->get("token"));
if ($appraisal != null) {
return $ics->generateEventFile([[
'title' => $translator->trans('ics.appraisal.title') . ' ' . $appraisal->getTitle(),
'description' => $translator->trans('ics.appraisal.description', ['%uid%' => $appraisal->getUser()->getId(), '%user%' => strtolower($appraisal->getUser()->getPersonalInfo()->getFirstName()), '%link%' => $this->generateUrl('user_profile', array(), UrlGeneratorInterface::ABSOLUTE_URL) . '/' . $appraisal->getUser()->getEmail() . '?g=appraisal&open=appraisal-' . $appraisal->getId()]),
'startDate' => $appraisal->getReviewAt()->format('Ymd'),
'startTime' => '090000',
'endDate' => $appraisal->getReviewAt()->format('Ymd'),
'endTime' => '180000',
'location' => 'HR Platfrom',
'reminderTime' => '-15M',
'reminderDescription' => $translator->trans('ics.appraisal.title') . ' ' . $appraisal->getTitle(),
'fileName' => 'Appraisal-' . $appraisal->getIcsToken()
]]);
} else {
throw $this->createNotFoundException($translator->trans('messages.error.not_found'));
}
}
#[Route(path: '/appraisal-export/{_type}/{_target}', defaults: ['_target' => 'local', '_type' => 'excel'], name: 'appraisal_export')]
public function exportAppraisal(string $_type, string $_target, Request $request, AppraisalService $appraisalService)
{
$appraisalId = $request->get('id') ?: null;
if($_type == 'excel' || empty($_type) || $_type == 'google'){
if($_type == 'google'){
$_target = $_type;
}
return $appraisalService->exportExcel($appraisalId, $_target);
}elseif($_type == 'pdf'){
return $appraisalService->exportPdf($appraisalId, $_target);
}
}
#[Route(path: '/appraisal-report/{_target}', defaults: ['_target' => 'local'], name: 'report_appraisal')]
public function reportAppraisal(string $_target, Request $request, TranslatorInterface $translator, LogService $log, GoogleDriveService $googleDriveService, AppraisalRepository $appraisalRepository, AppraisalNoteRepository $appraisalNoteRepository)
{
$appraisalYear = $request->get('year') ?: null;
$type = $request->get('type');
$department = $request->get('department') ?: null;
$queries = $appraisalRepository->createQueryBuilder('a')
->leftJoin('a.user', 'u')
->leftJoin('u.department', 'dept')
->andWhere('u.isActive = :ia')->setParameter('ia', 1);
// ->andWhere('a.user = :user')->setParameter('user', 128);
if($department){
$queries->andWhere('dept.id = :department')->setParameter('department', $department);
}
if ($type == 'probation') {
if ($appraisalYear) {
if (strpos($appraisalYear, '-end') !== false) {
$year = str_replace('-end', '', $appraisalYear);
} elseif (strpos($appraisalYear, '-mid') !== false) {
$year = str_replace('-mid', '', $appraisalYear);
} else {
$year = $appraisalYear;
}
$queries->andWhere('YEAR(a.reviewAt) = :year')->setParameter('year', $year);
}
$queries->andWhere('LOWER(a.title) LIKE LOWER(:probation)')->setParameter('probation', '%probation%');
} elseif ($type == 'permanent') {
if (strpos($appraisalYear, '-end') !== false) {
$year = str_replace('-end', '', $appraisalYear);
$queries->andWhere('LOWER(a.title) LIKE LOWER(:yearEnd)')
->setParameter('yearEnd', '%' . $year . '%end%');
} elseif (strpos($appraisalYear, '-mid') !== false) {
$year = str_replace('-mid', '', $appraisalYear);
$queries->andWhere('LOWER(a.title) LIKE LOWER(:yearMid)')
->setParameter('yearMid', '%' . $year . '%mid%');
} else {
$queries->andWhere('LOWER(a.title) LIKE LOWER(:year)')
->setParameter('year', '%' . $appraisalYear . '%');
}
$queries->andWhere('LOWER(a.title) NOT LIKE LOWER(:probation)')->setParameter('probation', '%probation%');
}
$appraisals = $queries->getQuery()->getResult();
usort($appraisals, function($a, $b) {
$scoreA = $a->appraisalScore();
$scoreB = $b->appraisalScore();
if ($scoreA === null && $scoreB === null) return 0;
if ($scoreA === null) return 1;
if ($scoreB === null) return -1;
return $scoreB <=> $scoreA;
});
$user = null;
$spreadsheet = new Spreadsheet();
$summarySheet = $spreadsheet->getActiveSheet()->setTitle('Summary');
$summarySheet->setCellValue('A1', 'Name');
$summarySheet->setCellValue('B1', 'Department');
$summarySheet->setCellValue('C1', 'Office');
$summarySheet->setCellValue('D1', 'Job Title');
// $summarySheet->setCellValue('E1', 'Appraisal Title');
$summarySheet->setCellValue('E1', 'Supervised By');
$summarySheet->setCellValue('F1', 'Reviewed At');
$summarySheet->setCellValue('G1', 'Overall Rating');
$lastCol = $summarySheet->getHighestColumn();
$summarySheet->getDefaultColumnDimension()->setWidth(25);
// $summarySheet->getColumnDimension('B')->setWidth(120);
$summarySheet->getStyle("A1:".$lastCol."1")->getFont()->setBold(true);
$summarySheet->getStyle("A1:".$lastCol."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$summarySheet->getStyle("A1:".$lastCol."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$summarySheet->getStyle("A2:".$lastCol."2")->getFont()->setBold(false);
$summarySheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$summarySheet->getStyle("A2:".$lastCol."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$filename = 'Appraisal-Report_';
if ($appraisalYear) {
if (strpos($appraisalYear, '-end') !== false) {
$filename .= str_replace('-end', '', $appraisalYear) . '-End-Year';
} elseif (strpos($appraisalYear, '-mid') !== false) {
$filename .= str_replace('-mid', '', $appraisalYear) . '-Year-Mid';
} else {
$filename .= $appraisalYear;
}
}
// $filename .= $user ? "-" . urlencode($user->getPersonalInfo()->getFullName()) : "";
// $filename .= '.xlsx';
$filename .= "_" . date('Y-m-d') . '.xlsx';
$row = $summarySheet->getHighestRow();
foreach($appraisals as $appraisal){
$user = $appraisal->getUser();
$summarySheet->setCellValue('A'.$row, $user->getPersonalInfo()->getFullName());
$summarySheet->setCellValue('B'.$row, $user->getDepartment()->getName());
$summarySheet->setCellValue('C'.$row, $user->getOffice()->getFullName());
$summarySheet->setCellValue('D'.$row, $user->organizationTitles());
$managerArray = [];
foreach ($user->getAllManager() as $manager) {
$managerArray[] = $manager->getPersonalInfo()->getFirstName();
}
// $summarySheet->setCellValue('E'.$row, $appraisal->getTitle());
$summarySheet->setCellValue('E'.$row, implode(', ', $managerArray));
$summarySheet->setCellValue('F'.$row, $appraisal->getReviewAt() ? $appraisal->getReviewAt()->format('d-M-Y') : '-');
$summarySheet->setCellValue('G'.$row, $appraisal->appraisalScore() ?: '-');
$summarySheet->getStyle('G'.$row)->getFont()->setBold(true);
$row++;
}
$summarySheet->setAutoFilter('A1:'.$lastCol.$summarySheet->getHighestRow());
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
}