src/ApplicationBundle/Controller/HumanResourceController.php line 10893

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\BuddybeeConstant;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\HumanResourceConstant;
  6. use ApplicationBundle\Constants\MeetingSchedulingConstant;
  7. use ApplicationBundle\Entity\AttendanceAmendment;
  8. use ApplicationBundle\Entity\BankList;
  9. use ApplicationBundle\Entity\BonusPolicy;
  10. use ApplicationBundle\Entity\Branch;
  11. use ApplicationBundle\Entity\ConsultancyTopic;
  12. use ApplicationBundle\Entity\EducationQualification;
  13. use ApplicationBundle\Entity\Employee;
  14. use ApplicationBundle\Entity\EmployeeAttendance;
  15. use ApplicationBundle\Entity\EmployeeAttendanceLog;
  16. use ApplicationBundle\Entity\EmployeeDetails;
  17. use ApplicationBundle\Entity\EmployeeLeaveApplication;
  18. use ApplicationBundle\Entity\EvaluationCategory;
  19. use ApplicationBundle\Entity\HolidayCalendar;
  20. use ApplicationBundle\Entity\HolidayCalendarDates;
  21. use ApplicationBundle\Entity\IncrementPolicy;
  22. use ApplicationBundle\Entity\LeaveSettings;
  23. use ApplicationBundle\Entity\PayrollPolicy;
  24. use ApplicationBundle\Entity\PlanningItem;
  25. use ApplicationBundle\Entity\Questionnaire;
  26. use ApplicationBundle\Entity\ScheduledMeeting;
  27. use ApplicationBundle\Entity\Skill;
  28. use ApplicationBundle\Entity\SysDepartment;
  29. use ApplicationBundle\Entity\SysDepartmentPosition;
  30. use ApplicationBundle\Entity\SysUser;
  31. use ApplicationBundle\Entity\TrainingCourse;
  32. use ApplicationBundle\Entity\WorkHourPolicy;
  33. use ApplicationBundle\Helper\EmployeePayloadNormalizer;
  34. use ApplicationBundle\Helper\ResponseStructure;
  35. use ApplicationBundle\Interfaces\SessionCheckInterface;
  36. use ApplicationBundle\Modules\Accounts\Accounts;
  37. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  38. use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  39. use ApplicationBundle\Modules\Buddybee\Buddybee;
  40. use ApplicationBundle\Modules\HumanResource\HumanResource;
  41. use ApplicationBundle\Modules\HumanResource\HumanResourceHelper;
  42. use ApplicationBundle\Modules\Inventory\Inventory;
  43. use ApplicationBundle\Modules\Sales\Client;
  44. use ApplicationBundle\Modules\System\DeleteDocument;
  45. use ApplicationBundle\Modules\System\DocValidation;
  46. use ApplicationBundle\Modules\System\MiscActions;
  47. use ApplicationBundle\Modules\System\System;
  48. use ApplicationBundle\Modules\User\Company;
  49. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  50. use CompanyGroupBundle\Entity\EntityCountryConsultantRequirements;
  51. use CompanyGroupBundle\Entity\EntityCreateBlog;
  52. use CompanyGroupBundle\Entity\EntityCreateDocument;
  53. use CompanyGroupBundle\Entity\EntityCreateTopic;
  54. use CompanyGroupBundle\Entity\EntityFile;
  55. use CompanyGroupBundle\Entity\EntityInvoice;
  56. use CompanyGroupBundle\Entity\EntitySkill;
  57. use CompanyGroupBundle\Entity\PromoCode;
  58. use CompanyGroupBundle\Modules\ApplicantM;
  59. use DateTime;
  60. use Ps\PdfBundle\Annotation\Pdf;
  61. use Symfony\Component\HttpFoundation\JsonResponse;
  62. use Symfony\Component\HttpFoundation\Request;
  63. use Symfony\Component\HttpFoundation\Response;
  64. use Symfony\Component\Routing\Generator\UrlGenerator;
  65. use Throwable;
  66. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  67. //use Symfony\Component\Console\Input\ArrayInput;
  68. //use Symfony\Component\Console\Output\NullOutput;
  69. class HumanResourceController extends GenericController implements SessionCheckInterface
  70. {
  71. //temporary for adding session
  72.     public function CheckoutPageAction(Request $request$encData '')
  73.     {
  74.         $em $this->getDoctrine()->getManager('company_group');
  75.         $em_goc $em;
  76.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  77.         $systemType $this->container->getParameter('system_type') ?: '_CENTRAL_';
  78.         $stripe_secret_key $this->container->getParameter('stripe_secret_key_live');
  79.         $paymentService $this->container->get('eco_system_payment_service');
  80.         $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  81.         if ($encData != "") {
  82.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  83.             if ($encryptedData == null$encryptedData = [];
  84.             if (isset($encryptedData['invoiceId'])) $invoiceId $encryptedData['invoiceId'];
  85.         }
  86.         $session $request->getSession();
  87.         $currencyForGateway 'eur';
  88.         $gatewayInvoice null;
  89.         if ($invoiceId != 0)
  90.             $gatewayInvoice $em->getRepository(EntityInvoice::class)->find($invoiceId);
  91.         $paymentGateway $request->request->get('paymentGateway''stripe'); //aamarpay,bkash
  92.         $retailerId $request->request->get('retailerId'0);
  93.         if ($request->query->has('currency'))
  94.             $currencyForGateway $request->query->get('currency');
  95.         else
  96.             $currencyForGateway $request->request->get('currency''eur');
  97.         $setupOnlyCheckout = (int)$request->request->get('setupOnly'$request->query->get('setupOnly'0)) === 1;
  98.         $checkoutFlow $request->request->get('flow'$request->query->get('flow''payment'));
  99.         $isCompanySetupCheckout $setupOnlyCheckout && $checkoutFlow === 'company_setup';
  100.         $isSaasSubscriptionCheckout = (int)$request->request->get('saasSubscription'$request->query->get('saasSubscription'0)) === 1;
  101.         $companySetupRedirectUrl $request->request->get('companySetupRedirectUrl'$request->query->get('companySetupRedirectUrl'''));
  102.         $ownerId = (int)$request->request->get('ownerId'$request->query->get('ownerId'0));
  103.         $currentUserBalance 0;
  104.         $gatewayAmount 0;
  105.         $redeemedAmount 0;
  106.         $redeemedSessionCount 0;
  107.         $toConsumeSessionCount 0;
  108.         $invoiceSessionCount 0;
  109.         $payableAmount 0;
  110.         $promoClaimedAmount 0;
  111.         $promoCodeId 0;
  112.         $promoClaimedSession 0;
  113.         $bookingExpireTs 0;
  114.         $imageBypackageId = [
  115.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  116.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  117.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  118.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  119.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  120.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  121.         ];
  122.         $imageBySessionCount = [
  123.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  124.             100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  125.             200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  126.             300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  127.             400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  128.             500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  129.             600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  130.             700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  131.             800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  132.             900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  133.             1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  134.             1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  135.             1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  136.             1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  137.             1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  138.             1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  139.             1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  140.             1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  141.             1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  142.             1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  143.             2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  144.             2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  145.             2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  146.             2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  147.             2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  148.             2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  149.             2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  150.             2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  151.             2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  152.             2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  153.             3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  154.             3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  155.             3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  156.             3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  157.             3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  158.             3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  159.             3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  160.             3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  161.         ];
  162.         if (!$gatewayInvoice) {
  163.             if ($request->isMethod('POST')) {
  164.                 $bookedById 0;
  165.                 $bookingRefererId 0;
  166.                 if ($session->get(UserConstants::USER_ID)) {
  167.                     $bookedById $session->get(UserConstants::USER_ID);
  168.                     $bookingRefererId 0;
  169.                     $invoiceSessionCount * ($request->request->get('sessionCount'0) == '' $request->request->get('sessionCount'0));
  170.                     $dataAppId $request->request->get('appId'$session->get(UserConstants::USER_APP_ID));
  171.                     $expireTsAddition $request->request->get('expireTsAddition',
  172.                         $request->request->get('billingFrequency'2) == 30 24 3600 365 24 2600
  173.                     );
  174.                     $expireTsModification $request->request->get('expireTsModification'0);
  175.                     $userAddition $request->request->get('userAddition'0);
  176.                     $userModification $request->request->get('userModification'0);
  177.                     $adminAddition $request->request->get('adminAddition'0);
  178.                     $adminModification $request->request->get('adminModification'0);
  179.                     $packageId $request->request->get('packageId'1);
  180.                     if($packageId == 0)
  181.                         $packageId=1;
  182.                     $successActionData = [
  183.                         'appId' => $dataAppId,
  184.                         'packageId' => $packageId,
  185.                         'expireTsAddition' => $expireTsAddition,/// can also be - if needed
  186.                         'expireTsModification' => $expireTsModification,/// can also be - if needed
  187.                         'userAddition' => $userAddition,/// can also be - if needed
  188.                         'userModification' => $userModification,/// can also be - if needed
  189.                         'adminAddition' => $adminAddition,/// can also be - if needed
  190.                         'adminModification' => $adminModification,/// can also be - if needed
  191.                     ];
  192.                     if ($request->request->has('purchasePackage')) {
  193.                         $beeCodeSerial $request->request->get('beeCodeSerial''');
  194.                         $promoCode $request->request->get('promoCode''');
  195.                         $beeCodePin $request->request->get('beeCodePin''');
  196.                         $userId $request->request->get('userId'$session->get(UserConstants::USER_ID));
  197.                         $studentDetails null;
  198.                         $studentDetails $em->getRepository(EntityApplicantDetails::class)->find($userId);
  199.                         if ($studentDetails) {
  200.                             $currentUserBalance $studentDetails->getAccountBalance();
  201.                         }
  202.                         if ($beeCodeSerial != '' && $beeCodePin != '') {
  203.                             $claimData MiscActions::ClaimBeeCode($em,
  204.                                 [
  205.                                     'claimFlag' => 1,
  206.                                     'pin' => $beeCodePin,
  207.                                     'serial' => $beeCodeSerial,
  208.                                     'userId' => $userId,
  209.                                 ]);
  210.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  211.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  212.                                 $claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
  213.                                 $claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
  214.                             }
  215.                             $redeemedAmount $claimData['data']['claimedAmount'];
  216.                             $redeemedSessionCount $claimData['data']['claimedCoin'];
  217.                         } else
  218.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  219.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  220.                             }
  221.                         $payableAmount round($request->request->get('payableAmount'0), 0);
  222.                         $totalAmountWoDiscount round($request->request->get('totalAmountWoDiscount'0), 0);
  223.                         //now claim and process promocode
  224.                         if ($promoCode != '') {
  225.                             $claimData MiscActions::ClaimPromoCode($em,
  226.                                 [
  227.                                     'claimFlag' => 1,
  228.                                     'promoCode' => $promoCode,
  229.                                     'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
  230.                                     'orderValue' => $totalAmountWoDiscount,
  231.                                     'currency' => $currencyForGateway,
  232.                                     'orderCoin' => $invoiceSessionCount,
  233.                                     'userId' => $userId,
  234.                                 ]);
  235.                             $promoClaimedAmount 0;
  236. //                            $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
  237.                             $promoCodeId $claimData['promoCodeId'];
  238.                             $promoClaimedSession $claimData['data']['claimedCoin'];
  239.                         }
  240.                         if ($userId == $session->get(UserConstants::USER_ID)) {
  241.                             MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  242.                             $currentUserBalance $session->get('BUDDYBEE_BALANCE');
  243.                         } else {
  244.                             if ($bookingRefererId == 0)
  245.                                 $bookingRefererId $session->get(UserConstants::USER_ID);
  246.                             $studentDetails $em->getRepository(EntityApplicantDetails::class)->find($userId);
  247.                             if ($studentDetails) {
  248.                                 $currentUserBalance $studentDetails->getAccountBalance();
  249.                                 if ($bookingRefererId != $userId && $bookingRefererId != 0) {
  250.                                     $bookingReferer $em->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
  251.                                     if ($bookingReferer)
  252.                                         if ($bookingReferer->getIsAdmin()) {
  253.                                             $studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
  254.                                             $em->flush();
  255.                                         }
  256.                                 }
  257.                             }
  258.                         }
  259.                         Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
  260.                         Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
  261.                         if ($request->request->get('isRecharge'0) == 1) {
  262.                             if (($redeemedAmount $promoClaimedAmount) >= $payableAmount) {
  263.                                 $payableAmount = ($redeemedAmount $promoClaimedAmount);
  264.                                 $gatewayAmount 0;
  265.                             } else
  266.                                 $gatewayAmount $payableAmount - ($redeemedAmount $promoClaimedAmount);
  267.                         } else if ($isSaasSubscriptionCheckout) {
  268.                             $gatewayAmount max(0round($payableAmount - ($redeemedAmount $promoClaimedAmount), 2));
  269.                         } else {
  270.                             $gatewayAmount $payableAmount <= ($currentUserBalance + ($redeemedAmount $promoClaimedAmount)) ? : ($payableAmount $currentUserBalance - ($redeemedAmount $promoClaimedAmount));
  271.                         }
  272.                         $gatewayAmount round($gatewayAmount2);
  273.                         $dueAmount round($request->request->get('dueAmount'$payableAmount), 0);
  274.                         if ($request->request->has('gatewayProductData'))
  275.                             $gatewayProductData $request->request->get('gatewayProductData');
  276.                         $gatewayProductData = [[
  277.                             'price_data' => [
  278.                                 'currency' => $currencyForGateway,
  279.                                 'unit_amount' => $gatewayAmount != ? ((100 $gatewayAmount) / 1) : 200000,
  280.                                 'product_data' => [
  281. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  282.                                     'name' => 'HoneyBee Hive Subscription- ' GeneralConstant::$packageDetails[$packageId]['packageName'],
  283.                                     'images' => [$imageBypackageId[$packageId]],
  284.                                 ],
  285.                             ],
  286.                             'quantity' => 1,
  287.                         ]];
  288.                         $new_invoice null;
  289.                         if (!$new_invoice) {
  290.                             $new_invoice = new EntityInvoice();
  291.                             $invoiceDate = new \DateTime();
  292.                             $new_invoice->setInvoiceDate($invoiceDate);
  293.                             $new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
  294.                             $new_invoice->setStudentId($userId);
  295.                             $new_invoice->setBillerId($retailerId == $retailerId);
  296.                             $new_invoice->setRetailerId($retailerId);
  297.                             $new_invoice->setBillToId($userId);
  298.                             $new_invoice->setAmountTransferGateWayHash($paymentGateway);
  299.                             $new_invoice->setAmountCurrency($currencyForGateway);
  300.                             $cardIds $request->request->get('cardIds', []);
  301.                             $new_invoice->setMeetingId(0);
  302.                             $new_invoice->setGatewayBillAmount($gatewayAmount);
  303.                             $new_invoice->setRedeemedAmount($redeemedAmount);
  304.                             $new_invoice->setPromoDiscountAmount($promoClaimedAmount);
  305.                             $new_invoice->setPromoCodeId($promoCodeId);
  306.                             $new_invoice->setRedeemedSessionCount($redeemedSessionCount);
  307.                             $new_invoice->setPaidAmount($payableAmount $dueAmount);
  308.                             $new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
  309.                             $new_invoice->setDueAmount($dueAmount);
  310.                             $new_invoice->setInvoiceType($request->request->get('invoiceType'BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
  311.                             $new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' microtime(true)));
  312.                             $new_invoice->setCardIds(json_encode($cardIds));
  313.                             $new_invoice->setAmountType($request->request->get('amountType'1));
  314.                             $new_invoice->setAmount($payableAmount);
  315.                             $new_invoice->setConsumeAmount($payableAmount);
  316.                             $new_invoice->setSessionCount($invoiceSessionCount);
  317.                             $new_invoice->setConsumeSessionCount($toConsumeSessionCount);
  318.                             $new_invoice->setIsPaidfull(0);
  319.                             $new_invoice->setIsProcessed(0);
  320.                             $new_invoice->setAppId($dataAppId);
  321.                             $new_invoice->setApplicantId($userId);
  322.                             $new_invoice->setBookedById($bookedById);
  323.                             $new_invoice->setBookingRefererId($bookingRefererId);
  324.                             $new_invoice->setIsRecharge($request->request->get('isRecharge'0));
  325.                             $new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting'0));
  326.                             $new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting'0));
  327.                             $new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards'0));
  328.                             $new_invoice->setIsPayment(0); //0 means receive
  329.                             $new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
  330.                             $new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
  331.                             $new_invoice->setSuccessActionData(json_encode($successActionData)); //0 means receive
  332.                             if ($bookingExpireTs == 0) {
  333.                                 $bookingExpireTs = (new \DateTime('+30 day'))->format('U');
  334.                             }
  335.                             $new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
  336.                             $new_invoice->setBookingExpireTs($bookingExpireTs);
  337.                             $new_invoice->setConfirmationExpireTs($bookingExpireTs);
  338.                             $em->persist($new_invoice);
  339.                             $em->flush();
  340.                         }
  341.                         $invoiceId $new_invoice->getId();
  342.                         $gatewayInvoice $new_invoice;
  343.                         if ($request->request->get('isRecharge'0) != 1) {
  344.                         }
  345.                     }
  346.                 } else {
  347.                     $url $this->generateUrl(
  348.                         'user_login'
  349.                     );
  350.                     $session->set('LAST_REQUEST_URI_BEFORE_LOGIN'$this->generateUrl(
  351.                         'pricing_plan_page', [
  352.                         'autoRedirected' => 1
  353.                     ],
  354.                         UrlGenerator::ABSOLUTE_URL
  355.                     ));
  356.                     $output = [
  357.                         'proceedToCheckout' => 0,
  358.                         'redirectUrl' => $url,
  359.                         'clearLs' => 0
  360.                     ];
  361.                     return new JsonResponse($output);
  362.                 }
  363.                 //now proceed to checkout page if the user has lower balance or recharging
  364.                 //$invoiceDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->
  365.             }
  366.         }
  367.         if ($gatewayInvoice) {
  368.             $stripeCustomerId null;
  369.             if ($gatewayInvoice->getInvoiceType() == BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE) {
  370.                 $companyGroup $em_goc
  371.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  372.                     ->findOneBy(
  373.                         array(
  374.                             'appId' => $gatewayInvoice->getAppId(),
  375.                         )
  376.                     );
  377.                 if ($companyGroup)
  378.                     $stripeCustomerId $companyGroup->getStripeCustomerId();
  379.             } else
  380.                 $stripeCustomerId $gatewayInvoice->getStripeCustomerId();
  381.             $route $request->attributes->get('_route');
  382.             if ($gatewayAmount 0) {
  383.                 $processType = ($route == 'app_checkout_page_api') ? 'intent' 'session';
  384.             } else if ($isCompanySetupCheckout) {
  385.                 $processType 'session';
  386.             } else if (!$stripeCustomerId) {
  387.                 $processType 'setup';
  388.             } else if ($gatewayAmount <= 0) {
  389.                 $meetingId 0;
  390.                 if ($invoiceId != 0) {
  391.                     $retData Buddybee::ProcessEntityInvoice($em$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
  392.                         $this->container->getParameter('kernel.root_dir'),
  393.                         false,
  394.                         $this->container->getParameter('notification_enabled'),
  395.                         $this->container->getParameter('notification_server')
  396.                     );
  397.                     $meetingId $retData['meetingId'];
  398.                 }
  399. //
  400. //                MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
  401.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  402.                     $billerDetails = [];
  403.                     $billToDetails = [];
  404.                     $invoice $gatewayInvoice;
  405.                     if ($invoice) {
  406.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  407.                             ->findOneBy(
  408.                                 array(
  409.                                     'applicantId' => $invoice->getBillerId(),
  410.                                 )
  411.                             );
  412.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  413.                             ->findOneBy(
  414.                                 array(
  415.                                     'applicantId' => $invoice->getBillToId(),
  416.                                 )
  417.                             );
  418.                     }
  419.                     $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  420.                     $bodyData = array(
  421.                         'page_title' => 'Invoice',
  422.                         'billerDetails' => $billerDetails,
  423.                         'billToDetails' => $billToDetails,
  424.                         'invoice' => $invoice,
  425.                         'currencyList' => BuddybeeConstant::$currency_List,
  426.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  427.                     );
  428.                     $attachments = [];
  429.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  430.                     $new_mail $this->get('mail_module');
  431.                     $new_mail->sendMyMail(array(
  432.                         'senderHash' => '_CUSTOM_',
  433.                         'forwardToMailAddress' => $forwardToMailAddress,
  434.                         'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  435.                         'attachments' => $attachments,
  436.                         'toAddress' => $forwardToMailAddress,
  437.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  438.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  439.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  440.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  441.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  442. //                            'emailBody' => $bodyHtml,
  443.                         'mailTemplate' => $bodyTemplate,
  444.                         'templateData' => $bodyData,
  445.                         'embedCompanyImage' => 0,
  446.                         'companyId' => 0,
  447.                         'companyImagePath' => ''
  448. //                        'embedCompanyImage' => 1,
  449. //                        'companyId' => $companyId,
  450. //                        'companyImagePath' => $company_data->getImage()
  451.                     ));
  452.                 }
  453.                 $url $this->generateUrl(
  454.                     $systemType == '_BUDDYBEE_' 'buddybee_dashboard' 'central_landing'
  455.                 );
  456.                 $output = [
  457.                     'invoiceId' => $gatewayInvoice->getId(),
  458.                     'meetingId' => 0,
  459.                     'proceedToCheckout' => 0,
  460.                     'redirectUrl' => $url
  461.                 ];
  462.                 return new JsonResponse($output);
  463.             } else {
  464.             }
  465.             $gatewayProductData json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
  466.             if ($gatewayProductData == null$gatewayProductData = [];
  467.             if (empty($gatewayProductData))
  468.                 $gatewayProductData = [
  469.                     [
  470.                         'price_data' => [
  471.                             'currency' => 'eur',
  472.                             'unit_amount' => $gatewayAmount != ? (100 $gatewayAmount) : 200000,
  473.                             'product_data' => [
  474. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  475.                                 'name' => 'Bee Coins',
  476.                                 'images' => [$imageBySessionCount[0]],
  477.                             ],
  478.                         ],
  479.                         'quantity' => 1,
  480.                     ]
  481.                 ];
  482.             $productDescStr '';
  483.             $productDescArr = [];
  484.             foreach ($gatewayProductData as $gpd) {
  485.                 $productDescArr[] = $gpd['price_data']['product_data']['name'];
  486.             }
  487.             $productDescStr implode(','$productDescArr);
  488.             $paymentGatewayFromInvoice $gatewayInvoice->getAmountTransferGateWayHash();
  489.             if (GeneralConstant::EMAIL_ENABLED == 1) {
  490.                 $billerDetails = [];
  491.                 $billToDetails = [];
  492.                 $invoice $gatewayInvoice;
  493.                 if ($invoice) {
  494.                     $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  495.                         ->findOneBy(
  496.                             array(
  497.                                 'applicantId' => $invoice->getBillerId(),
  498.                             )
  499.                         );
  500.                     $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  501.                         ->findOneBy(
  502.                             array(
  503.                                 'applicantId' => $invoice->getBillToId(),
  504.                             )
  505.                         );
  506.                 }
  507.                 $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  508.                 $bodyData = array(
  509.                     'page_title' => 'Invoice',
  510. //            'studentDetails' => $student,
  511.                     'billerDetails' => $billerDetails,
  512.                     'billToDetails' => $billToDetails,
  513.                     'invoice' => $invoice,
  514.                     'currencyList' => BuddybeeConstant::$currency_List,
  515.                     'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  516.                 );
  517.                 $attachments = [];
  518.                 $forwardToMailAddress $billToDetails->getOAuthEmail();
  519. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  520.                 $new_mail $this->get('mail_module');
  521.                 $new_mail->sendMyMail(array(
  522.                     'senderHash' => '_CUSTOM_',
  523.                     //                        'senderHash'=>'_CUSTOM_',
  524.                     'forwardToMailAddress' => $forwardToMailAddress,
  525.                     'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  526. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  527.                     'attachments' => $attachments,
  528.                     'toAddress' => $forwardToMailAddress,
  529.                     'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  530.                     'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  531.                     'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  532.                     'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  533.                     'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  534. //                            'emailBody' => $bodyHtml,
  535.                     'mailTemplate' => $bodyTemplate,
  536.                     'templateData' => $bodyData,
  537.                     'embedCompanyImage' => 0,
  538.                     'companyId' => 0,
  539.                     'companyImagePath' => ''
  540. //                        'embedCompanyImage' => 1,
  541. //                        'companyId' => $companyId,
  542. //                        'companyImagePath' => $company_data->getImage()
  543.                 ));
  544.             }
  545.             if ($paymentGatewayFromInvoice == 'bkash' || $paymentGatewayFromInvoice == 'stripe') {
  546.                 $successPayload = [
  547.                     'invoiceId' => $gatewayInvoice->getId(),
  548.                     'autoRedirect' => $request->request->get('autoRedirect'$request->query->get('autoRedirect'1)),
  549.                 ];
  550.                 $successMetadata = [];
  551.                 if ($setupOnlyCheckout || $isCompanySetupCheckout) {
  552.                     $successPayload['setupOnly'] = 1;
  553.                     $successPayload['appId'] = (int)$gatewayInvoice->getAppId();
  554.                     $successPayload['ownerId'] = $ownerId;
  555.                     if ($companySetupRedirectUrl !== '') {
  556.                         $successPayload['redirectUrl'] = $companySetupRedirectUrl;
  557.                     }
  558.                     $successMetadata = [
  559.                         'app_id' => (string)((int)$gatewayInvoice->getAppId()),
  560.                         'owner_id' => (string)$ownerId,
  561.                         'redirect_url' => (string)$companySetupRedirectUrl,
  562.                     ];
  563.                 }
  564.                 $successUrl $this->generateUrl(
  565.                     'payment_gateway_success',
  566.                     [
  567.                         'encData' => $this->get('url_encryptor')->encrypt(json_encode($successPayload)),
  568.                         'hbeeSessionToken' => $session->get('token'0),
  569.                     ],
  570.                     UrlGenerator::ABSOLUTE_URL
  571.                 );
  572.                 $successUrl .= (strpos($successUrl'?') !== false '&' '?') . 'session_id={CHECKOUT_SESSION_ID}';
  573.                 $cancelUrl $this->generateUrl(
  574.                     'payment_gateway_cancel',
  575.                     [
  576.                         'invoiceId' => $gatewayInvoice->getId(),
  577.                         'autoRedirect' => $request->request->get('autoRedirect'$request->query->get('autoRedirect'1)),
  578.                         'hbeeSessionToken' => $session->get('token'0),
  579.                     ],
  580.                     UrlGenerator::ABSOLUTE_URL
  581.                 );
  582.                 $result $paymentService->processPayment(
  583.                     $gatewayInvoice,
  584.                     null,
  585.                     $processType,
  586.                     $paymentGatewayFromInvoice,
  587.                     [
  588.                         'setupOnly' => $setupOnlyCheckout 0,
  589.                         'success_url' => $successUrl,
  590.                         'cancel_url' => $cancelUrl,
  591.                         'metadata' => $successMetadata,
  592.                     ]
  593.                 );
  594.                 $output = [
  595.                     'clientSecret' => $result['client_secret'] ?? '',
  596.                     'type' => $processType,
  597.                     'id' => $result['id'] ?? '',
  598.                     'paymentGateway' => $paymentGatewayFromInvoice,
  599.                     'proceedToCheckout' => $result['success'] ? 0,
  600.                     'error' => $result['error'] ?? null,
  601.                     'mode' => $result['mode'] ?? null,
  602.                     'paymentIntentId' => $processType == 'intent' $result['id'] : ''
  603.                 ];
  604.                 return new JsonResponse($output);
  605.             } else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
  606.                 $meetingId 0;
  607.                 if ($gatewayInvoice->getId() != 0) {
  608.                     if ($gatewayInvoice->getDueAmount() <= 0) {
  609.                         $retData Buddybee::ProcessEntityInvoice($em_goc$gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
  610.                             $this->container->getParameter('notification_enabled'),
  611.                             $this->container->getParameter('notification_server')
  612.                         );
  613.                         $meetingId $retData['meetingId'];
  614.                     }
  615.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  616.                         $billerDetails = [];
  617.                         $billToDetails = [];
  618.                         $invoice $gatewayInvoice;
  619.                         if ($invoice) {
  620.                             $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  621.                                 ->findOneBy(
  622.                                     array(
  623.                                         'applicantId' => $invoice->getBillerId(),
  624.                                     )
  625.                                 );
  626.                             $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  627.                                 ->findOneBy(
  628.                                     array(
  629.                                         'applicantId' => $invoice->getBillToId(),
  630.                                     )
  631.                                 );
  632.                         }
  633.                         $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  634.                         $bodyData = array(
  635.                             'page_title' => 'Invoice',
  636. //            'studentDetails' => $student,
  637.                             'billerDetails' => $billerDetails,
  638.                             'billToDetails' => $billToDetails,
  639.                             'invoice' => $invoice,
  640.                             'currencyList' => BuddybeeConstant::$currency_List,
  641.                             'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  642.                         );
  643.                         $attachments = [];
  644.                         $forwardToMailAddress $billToDetails->getOAuthEmail();
  645. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  646.                         $new_mail $this->get('mail_module');
  647.                         $new_mail->sendMyMail(array(
  648.                             'senderHash' => '_CUSTOM_',
  649.                             //                        'senderHash'=>'_CUSTOM_',
  650.                             'forwardToMailAddress' => $forwardToMailAddress,
  651.                             'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  652. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  653.                             'attachments' => $attachments,
  654.                             'toAddress' => $forwardToMailAddress,
  655.                             'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  656.                             'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  657.                             'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  658.                             'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  659.                             'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  660. //                            'emailBody' => $bodyHtml,
  661.                             'mailTemplate' => $bodyTemplate,
  662.                             'templateData' => $bodyData,
  663.                             'embedCompanyImage' => 0,
  664.                             'companyId' => 0,
  665.                             'companyImagePath' => ''
  666. //                        'embedCompanyImage' => 1,
  667. //                        'companyId' => $companyId,
  668. //                        'companyImagePath' => $company_data->getImage()
  669.                         ));
  670.                     }
  671.                 }
  672.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  673.                 if ($meetingId != 0) {
  674.                     $url $this->generateUrl(
  675.                         'consultancy_session'
  676.                     );
  677.                     $output = [
  678.                         'proceedToCheckout' => 0,
  679.                         'invoiceId' => $gatewayInvoice->getId(),
  680.                         'meetingId' => $meetingId,
  681.                         'redirectUrl' => $url '/' $meetingId
  682.                     ];
  683.                 } else {
  684.                     $url $this->generateUrl(
  685.                         'buddybee_dashboard'
  686.                     );
  687.                     $output = [
  688.                         'proceedToCheckout' => 0,
  689.                         'invoiceId' => $gatewayInvoice->getId(),
  690.                         'meetingId' => $meetingId,
  691.                         'redirectUrl' => $url
  692.                     ];
  693.                 }
  694.                 return new JsonResponse($output);
  695.             }
  696.         }
  697.         $output = [
  698.             'clientSecret' => 0,
  699.             'id' => 0,
  700.             'proceedToCheckout' => 0
  701.         ];
  702.         return new JsonResponse($output);
  703.     }
  704.     //changes dev
  705.     public function AddEmployeeAction(Request $data$id 0)
  706.     {
  707.         $em $this->getDoctrine()->getManager();
  708.         $em_goc $this->getDoctrine()->getManager('company_group');
  709.         $connection $em->getConnection();
  710.         $connection->beginTransaction();
  711.         $skills $em->getRepository(Skill::class)->findAll();
  712.         $session $data->getSession();
  713.         $ownOnly 0;
  714.         $consultancyLevel HumanResourceConstant::$consultantLevel;
  715.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  716.         $banks $em->getRepository(BankList::class)->findAll();
  717.         $bankListObj = [];
  718.         $deviceList $em_goc->getRepository('CompanyGroupBundle\\Entity\\Device')->findBy([
  719.             'appId' => $session->get(UserConstants::USER_APP_ID)
  720.         ]);
  721.         $id $data->request->get('employeeId'$id);
  722.         foreach ($banks as $bank) {
  723.             $bankListObj[$bank->getBankId()] = $bank->getName();
  724.         }
  725.         if ($id === "my") {
  726.             $id $session->get(UserConstants::USER_EMPLOYEE_ID);
  727.             $ownOnly 1;
  728.             if ($id == || $id == null) {
  729.                 return $this->redirectToRoute('permission_denied_page');
  730.             }
  731.         }
  732.         if ($id) {
  733.             if ($data->isMethod('GET')) {
  734.                 $Employee $this->getDoctrine()->getRepository(EmployeeDetails::class)->find($id);
  735.                 if (!$Employee) {
  736.                     $this->addFlash(
  737.                         'error',
  738.                         'Invalid User ID!'
  739.                     );
  740.                     return $this->redirectToRoute('add_employee');
  741.                 } else {
  742.                     $EmployeeRes HumanResource::TwigDataForAddEmployee($em$id);
  743.                     $Employee $EmployeeRes['employee'];
  744.                     $EmployeeMain $EmployeeRes['employeeMain'];
  745.                     $sysUserId $EmployeeRes['sysId'];
  746.                     $existingSysUser $sysUserId $em->getRepository('ApplicationBundle\\Entity\\SysUser')->find($sysUserId) : [];
  747.                     $regionIdsArray json_decode($EmployeeMain->getRegionIds(), true) ?: [];
  748.                     $regionLeaderFlagsArray json_decode($EmployeeMain->getRegionLeaderFlags(), true) ?: [];
  749.                     $existingRegionAssociations = [];
  750.                     if (!empty($regionIdsArray)) {
  751.                         $regionRepo $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\Region');
  752.                         $regions $regionRepo->findBy(['id' => $regionIdsArray]);
  753.                         $regionMap = [];
  754.                         foreach ($regions as $region) {
  755.                             $regionMap[$region->getId()] = $region;
  756.                         }
  757.                         foreach ($regionIdsArray as $index => $regionId) {
  758.                             if (!isset($regionMap[$regionId])) continue;
  759.                             $region $regionMap[$regionId];
  760.                             $existingRegionAssociations[] = [
  761.                                 'regionLevelId' => $region->getRegionLevelId(),
  762.                                 'regionId' => $region->getId(),
  763.                                 'isLeader' => isset($regionLeaderFlagsArray[$index]) ? (int)$regionLeaderFlagsArray[$index] : 0
  764.                             ];
  765.                         }
  766.                     }
  767.                     $TwigData HumanResource::TwigDataForAddEmployee($em0);
  768.                     return $this->render(
  769.                         '@Application/pages/human_resource/input_forms/add_employee.html.twig',
  770.                         array(
  771.                             'page_title' => 'Update Employee',
  772.                             'ownOnly' => $ownOnly,
  773.                             'deviceList' => $deviceList,
  774.                             'branches' => $TwigData['branches'],
  775.                             'bankListObj' => $bankListObj,
  776.                             'heads' => Accounts::getLedgerHeadsWithParents($em),
  777.                             'departments' => $TwigData['departments'],
  778.                             'departmentPositions' => $TwigData['departmentPositions'],
  779.                             'regions' => $TwigData['regions'],
  780.                             'supervisors' => $TwigData['supervisors'],
  781.                             'sysUsers' => $TwigData['sysUser'],
  782.                             'EmploymentStatus' => $TwigData['EmploymentStatus'],
  783.                             'AccountStatus' => $TwigData['AccountStatus'],
  784.                             'sex' => $TwigData['sex'],
  785.                             'BloodGroup' => $TwigData['BloodGroup'],
  786.                             'days' => $TwigData['days'],
  787.                             'employeeMain' => $EmployeeMain,
  788.                             'employee' => $Employee,
  789.                             'skills' => $skills,
  790.                             'existingSysUser' => $existingSysUser,
  791.                             'id' => $id,
  792.                             'default_route' => $EmployeeRes['defaultRoute'],
  793.                             'user_type' => $EmployeeRes['userType'],
  794.                             'user_type_data' => HumanResourceConstant::$userType,
  795.                             'AccountTypes' => $TwigData['AccountType'],
  796.                             'weekends' => explode(','$Employee->getWeeklyHoliday()),
  797.                             'consultancyLevel' => $consultancyLevel,
  798.                             'module_data_array' => $TwigData['module_data_array'],
  799.                             'HasUpdateMode' => true,
  800.                             'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($data)),
  801.                             'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  802.                             'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  803.                             'leaveSettings' => $TwigData['leaveSettings'],
  804.                             'leaveData' => $EmployeeRes['leaveData'],
  805.                             'positions' => $EmployeeRes['positions'],
  806.                             'existing_region_associations' => $existingRegionAssociations
  807.                         )
  808.                     );
  809.                 }
  810.             } else {
  811.                 $approveHash $data->request->get('approvalHash');
  812.                 $loginId $data->getSession()->get(UserConstants::USER_LOGIN_ID);
  813.                 $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  814.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
  815.                 $image $data->files->get('img');
  816.                 $profileImage $this->uploadImage($image$data);
  817.                 $path '';
  818.                 if ($isSignatureOk) {
  819.                     $CompanyId 1;
  820.                     $emailQryStr=" 1=0 ";
  821.                     $emails=explode(',',$data->get('email'));
  822.                     foreach ($emails as $emailSingle) {
  823.                         $emailQryStr.=" or m.email like '%" $emailSingle "%' or m.oAuthEmail like '%" $emailSingle "%'";
  824.                     }
  825.                     $user=null;
  826.                     $users $em->getRepository('ApplicationBundle\\Entity\\SysUser')
  827.                         ->createQueryBuilder('m')
  828.                         ->where(" ( ".$emailQryStr." )")
  829.                         ->getQuery()
  830.                         ->setMaxResults(1)
  831.                         ->getResult();
  832.                     if(!empty($users)) {
  833.                         $user $users[0];
  834.                     }
  835.                     if ($user) {
  836.                         $sysUserId $user->getUserId();
  837.                         $message $this->get('user_module')->updateUser(
  838.                             $sysUserId,
  839.                             $data->request->get('firstname') . " " $data->request->get('lastname'),
  840.                             $data->request->has('email') ? $data->request->get('email') : '_UNCHANGED_',
  841.                             $data->request->has('username') ? $data->request->get('username') : '_UNCHANGED_',
  842.                             $data->request->get('password'),
  843.                             $data->request->get('empStatus'),
  844.                             $data->request->get('user_type''_UNCHANGED_'),
  845.                             $data->request->get('supervisor'),
  846.                             $data->request->get('default_route'),
  847.                             $data->request->get('branch'),
  848.                             $data->request->has('access_module') ? 0,
  849.                             $data->getSession()->get(UserConstants::USER_LOGIN_ID),
  850.                             $data->request->get('global_user_id'null),
  851.                             $profileImage,
  852.                             $upl_dir
  853.                         );
  854.                         if (isset($message[0]) && $message[0] === 'success') {
  855.                             HumanResource::StoreDataForAddEmployee($em$data$id$CompanyId$profileImage);
  856.                             $connection->commit();
  857.                             if ($systemType == '_CENTRAL_') {
  858.                             } else {
  859.                                 $Employee $em->getRepository(Employee::class)->find($id);
  860.                                 $EmployeeDetails $em->getRepository(EmployeeDetails::class)->findOneBy(
  861.                                     array(
  862.                                         'id' => $id
  863.                                     )
  864.                                 );
  865.                                 $em_goc $this->getDoctrine()->getManager('company_group');
  866.                                 $em_goc->getConnection()->connect();
  867.                                 $connected $em_goc->getConnection()->isConnected();
  868.                                 $gocDataList = [];
  869.                                 $gocDataListByAppId = [];
  870.                                 $retDataDebug = array();
  871.                                 $appIds $message[3]->getUserAppId();
  872.                                 $userIds $message[3]->getUserId();
  873.                                 if ($connected) {
  874.                                     $findByQuery = array(
  875.                                         'active' => 1
  876.                                     );
  877.                                     if ($appIds !== '_UNSET_')
  878.                                         $findByQuery['appId'] = $appIds;
  879.                                     $gocList $this->getDoctrine()->getManager('company_group')
  880.                                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  881.                                         ->findBy($findByQuery);
  882.                                     foreach ($gocList as $entry) {
  883.                                         $d = array(
  884.                                             'name' => $entry->getName(),
  885.                                             'id' => $entry->getId(),
  886.                                             'image' => $entry->getImage(),
  887.                                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  888.                                             'dbName' => $entry->getDbName(),
  889.                                             'dbUser' => $entry->getDbUser(),
  890.                                             'dbPass' => $entry->getDbPass(),
  891.                                             'dbHost' => $entry->getDbHost(),
  892.                                             'appId' => $entry->getAppId(),
  893.                                             'companyRemaining' => $entry->getCompanyRemaining(),
  894.                                             'companyAllowed' => $entry->getCompanyAllowed(),
  895.                                         );
  896.                                         $gocDataList[$entry->getId()] = $d;
  897.                                         $gocDataListByAppId[$entry->getAppId()] = $d;
  898.                                     }
  899.                                     $debugCount 0;
  900.                                     foreach ($gocDataList as $gocId => $entry) {
  901.                                         $skipSend 1;
  902.                                         $connector $this->container->get('application_connector');
  903.                                         $connector->resetConnection(
  904.                                             'default',
  905.                                             $gocDataList[$gocId]['dbName'],
  906.                                             $gocDataList[$gocId]['dbUser'],
  907.                                             $gocDataList[$gocId]['dbPass'],
  908.                                             $gocDataList[$gocId]['dbHost'],
  909.                                             $reset true);
  910.                                         $em $this->getDoctrine()->getManager();
  911.                                         if ($userIds !== '_UNSET_')
  912.                                             $users $this->getDoctrine()
  913.                                                 ->getRepository('ApplicationBundle\\Entity\\SysUser')
  914.                                                 ->findBy(
  915.                                                     array(
  916.                                                         'userId' => $userIds
  917.                                                     )
  918.                                                 );
  919.                                         else
  920.                                             $users $this->getDoctrine()
  921.                                                 ->getRepository('ApplicationBundle\\Entity\\SysUser')
  922.                                                 ->findBy(
  923.                                                     array()
  924.                                                 );
  925.                                         $output '';
  926.                                         $userData = array();
  927.                                         $userFiles = array();
  928.                                         foreach ($users as $user) {
  929.                                             $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  930.                                             if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  931.                                                 $mime mime_content_type($file);
  932.                                                 $info pathinfo($file);
  933.                                                 $name $info['basename'];
  934.                                                 if (strpos($mime'image') !== false) {
  935.                                                     $output = new \CURLFile($file$mime$name);
  936.                                                 }
  937.                                                 $skipSend 0;
  938.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  939.                                             } else {
  940.                                                 $user->setImage(null);
  941.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  942.                                                 $em->flush();
  943.                                             }
  944.                                             $getters array_filter(get_class_methods($user), function ($method) {
  945.                                                 return 'get' === substr($method03);
  946.                                             });
  947.                                             $userDataSingle = array();
  948.                                             foreach ($getters as $getter) {
  949.                                                 if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  950.                                                     continue;
  951.                                                 if ($user->{$getter}() instanceof \DateTime) {
  952.                                                     $ggtd $user->{$getter}();
  953.                                                     $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  954.                                                 } else
  955.                                                     $userDataSingle[$getter] = $user->{$getter}();
  956.                                             }
  957.                                             $employeeGetters = array(
  958.                                                 'getFirstname''getLastname''getImage''getIsImgLegal''getNid''getDob''getSex''getReligion''getFather',
  959.                                                 'getMother''getSpouse''getChild1''getChild2''getBlood''getPhone''getOfficailPhone''getCurrAddr',
  960.                                                 'getCurrAddrLat''getCurrAddrLng''getPermAddr''getEmmContact''getUsername''getEmail''getPassword',
  961.                                                 'getUserId''getJoiningDate''getEmpValidTill''getEmpStatus''getEmpType''getEmpCode''getEmpLabel''getTin',
  962.                                                 'getTinValidTill''getMedIns''getMedInsValidTill''getDocs''getNocApproval''getInst1''getYr1''getDur1',
  963.                                                 'getInst2''getYr2''getDur2''getInst3''getYr3''getDur3''getEinst1''getEyr1''getEdeg1''getEinst2',
  964.                                                 'getEyr2''getEdeg2''getEinst3''getEyr3''getEdeg3''getBankAcc''getBankAccType''getBankAccValidFrom',
  965.                                                 'getBankAccValidTo''getRoutingCode''getSwiftCode''getEar1''getEar2''getEar3''getEar4''getEar5''getEar6',
  966.                                                 'getEart''getDed1''getDed2''getDed3''getDed4''getDedt''getPayable''getHandCash''getBankTransfer',
  967.                                                 'getSecDep''getSecDepSpan''getSecDepRemMon''getSecDepRemAmount''getSlQty''getSlTkn''getSlFreq''getMlQty',
  968.                                                 'getMlTkn''getMlFreq''getElQty''getElTkn''getElFreq''getClQty''getClTkn''getClFreq''getLevt',
  969.                                                 'getWeeklyHoliday''getFiles''getSupervisor''getDept''getDesg''getBranch''getDivision''getCreatedAt',
  970.                                                 'getUpdatedAt''getEmployeeLevel''getSkill''getProbationaryPeriod''getDocBookedFlag''getTimeStampOfForm',
  971.                                                 'getIsConsultant''getConsultantLevel''getApplicationText''getCurrentEmployment''getEmergencyContactNumber',
  972.                                                 'getPostalCode''getCountry''getEducationData''getWorkExperienceData''getCertificateData''getLanguagesData',
  973.                                                 'getBeneficiaryName''getBankName''getBranchName''getClockedIn'
  974.                                             );
  975.                                             foreach ($employeeGetters as $getter) {
  976.                                                 if (!method_exists($EmployeeDetails$getter)) continue;
  977.                                                 try {
  978.                                                     $value $EmployeeDetails->{$getter}();
  979.                                                     if ($value instanceof \DateTime) {
  980.                                                         $userDataSingle[$getter] = $value->format('Y-m-d');
  981.                                                     } elseif (is_object($value)) {
  982.                                                         continue;
  983.                                                     } else {
  984.                                                         $userDataSingle[$getter] = $value;
  985.                                                     }
  986.                                                 } catch (\Exception $e) {
  987.                                                     continue;
  988.                                                 }
  989.                                             }
  990.                                             $userData[] = $userDataSingle;
  991.                                         }
  992.                                         $retDataDebug[$debugCount] = array(
  993.                                             'skipSend' => $skipSend
  994.                                         );
  995.                                         {
  996.                                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  997.                                             $userFiles['userData'] = json_encode($userData);
  998.                                             $curl curl_init();
  999.                                             curl_setopt_array($curl, array(
  1000.                                                 CURLOPT_RETURNTRANSFER => 1,
  1001.                                                 CURLOPT_POST => 1,
  1002.                                                 CURLOPT_URL => $urlToCall,
  1003.                                                 CURLOPT_CONNECTTIMEOUT => 10,
  1004.                                                 CURLOPT_SSL_VERIFYPEER => false,
  1005.                                                 CURLOPT_SSL_VERIFYHOST => false,
  1006.                                                 CURLOPT_HTTPHEADER => array(),
  1007.                                                 CURLOPT_POSTFIELDS => $userFiles
  1008.                                             ));
  1009.                                             $retData curl_exec($curl);
  1010.                                             $errData curl_error($curl);
  1011.                                             curl_close($curl);
  1012.                                             $retDataObj json_decode($retDatatrue);
  1013.                                             $retDataDebug[$debugCount] = $retDataObj;
  1014.                                             if (isset($retDataObj['globalIdsData']))
  1015.                                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1016.                                                     $connector $this->container->get('application_connector');
  1017.                                                     $connector->resetConnection(
  1018.                                                         'default',
  1019.                                                         $gocDataListByAppId[$app_id]['dbName'],
  1020.                                                         $gocDataListByAppId[$app_id]['dbUser'],
  1021.                                                         $gocDataListByAppId[$app_id]['dbPass'],
  1022.                                                         $gocDataListByAppId[$app_id]['dbHost'],
  1023.                                                         $reset true);
  1024.                                                     $em $this->getDoctrine()->getManager();
  1025.                                                     foreach ($usrList as $sys_id => $globaldata) {
  1026.                                                         $user $this->getDoctrine()
  1027.                                                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1028.                                                             ->findOneBy(
  1029.                                                                 array(
  1030.                                                                     'userId' => $sys_id
  1031.                                                                 )
  1032.                                                             );
  1033.                                                         if ($user) {
  1034.                                                             $user->setGlobalId($globaldata['gid']);
  1035.                                                             $em->flush();
  1036.                                                         }
  1037.                                                     }
  1038.                                                 }
  1039.                                         }
  1040.                                         $debugCount++;
  1041.                                     }
  1042.                                 }
  1043.                             }
  1044.                         } else {
  1045.                             $errorMsg $message['message'] ?? 'Unknown error occurred.';
  1046.                             $this->addFlash('error'$errorMsg);
  1047.                             return $this->redirectToRoute('add_employee');
  1048.                         }
  1049.                         $userType $data->getSession()->get(UserConstants::USER_TYPE);
  1050.                         $redirctUrl $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
  1051.                         if ($userType == 1) {
  1052.                             $redirctUrl $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
  1053.                         } else {
  1054.                             $redirctUrl $this->generateUrl('edit_employee', [], UrlGenerator::ABSOLUTE_URL) . '/my';
  1055.                         }
  1056.                         return new JsonResponse(array(
  1057.                             'employeeId' => $Employee->getEmployeeId(),
  1058.                             'redirectToNew' => 0,
  1059.                             'success' => true,
  1060.                             'redirectUrl' => $redirctUrl,
  1061.                         ));
  1062.                     }
  1063.                     else
  1064.                     {
  1065.                         $this->addFlash(
  1066.                             'error',
  1067.                             'User/Email not found. Please check the email and try again. If the problem persists, please contact support'
  1068.                         );
  1069.                         return $this->redirectToRoute('add_employee');
  1070.                     }
  1071.                 } else {
  1072.                     $this->addFlash(
  1073.                         'error',
  1074.                         'Invalid Approval Hash!'
  1075.                     );
  1076.                     return $this->redirectToRoute('add_employee');
  1077.                 }
  1078.             }
  1079.         }
  1080.         else {
  1081.             if ($data->isMethod('GET')) {
  1082.                 $TwigData HumanResource::TwigDataForAddEmployee($em0);
  1083.                 $existingRegionAssociations = [];
  1084.                 return $this->render(
  1085.                     '@Application/pages/human_resource/input_forms/add_employee.html.twig',
  1086.                     array(
  1087.                         'page_title' => 'Add Employee',
  1088.                         'ownOnly' => $ownOnly,
  1089.                         'deviceList' => $deviceList,
  1090.                         'heads' => Accounts::getLedgerHeadsWithParents($em),
  1091.                         'bankListObj' => $bankListObj,
  1092.                         'branches' => $TwigData['branches'],
  1093.                         'departments' => $TwigData['departments'],
  1094.                         'departmentPositions' => $TwigData['departmentPositions'],
  1095.                         'regions' => $TwigData['regions'],
  1096.                         'supervisors' => $TwigData['supervisors'],
  1097.                         'sysUsers' => $TwigData['sysUser'],
  1098.                         'EmploymentStatus' => $TwigData['EmploymentStatus'],
  1099.                         'AccountStatus' => $TwigData['AccountStatus'],
  1100.                         'sex' => $TwigData['sex'],
  1101.                         'skills' => $skills,
  1102.                         'id' => $id,
  1103.                         'consultancyLevel' => $consultancyLevel,
  1104.                         'existingSysUser' => null,
  1105.                         'BloodGroup' => $TwigData['BloodGroup'],
  1106.                         'days' => $TwigData['days'],
  1107.                         'AccountTypes' => $TwigData['AccountType'],
  1108.                         'module_data_array' => $TwigData['module_data_array'],
  1109.                         'user_type_data' => HumanResourceConstant::$userType,
  1110.                         'HasUpdateMode' => false,
  1111.                         'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($data)),
  1112.                         'leaveSettings' => $TwigData['leaveSettings'],
  1113.                         'employee' => [],
  1114.                         'positions' => $TwigData['positions'],
  1115.                         'existing_region_associations' => $existingRegionAssociations ?? [],
  1116.                         'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1117.                         'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1118.                     )
  1119.                 );
  1120.             }
  1121.             else {
  1122.                 try {
  1123.                     $approveHash $data->request->get('approvalHash');
  1124.                     $loginId $data->getSession()->get(UserConstants::USER_LOGIN_ID);
  1125.                     $CompanyId $this->getLoggedUserCompanyId($data);
  1126.                     $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1127.                     if (!$isSignatureOk) {
  1128.                         $this->addFlash('error''Invalid Approval Hash!');
  1129.                         return $this->redirectToRoute('add_employee');
  1130.                     }
  1131.                     // Strengthen: reject incomplete/invalid new employees before creating a user.
  1132.                     $vFirst trim((string) $data->request->get('firstname'));
  1133.                     $vEmail trim((string) $data->request->get('email'));
  1134.                     $vUser  trim((string) $data->request->get('username'));
  1135.                     $vErrors = [];
  1136.                     if ($vFirst === '') { $vErrors[] = 'First name is required.'; }
  1137.                     if ($vUser === '')  { $vErrors[] = 'Username is required.'; }
  1138.                     if ($vEmail === '' || !filter_var(explode(','$vEmail)[0], FILTER_VALIDATE_EMAIL)) { $vErrors[] = 'A valid email is required.'; }
  1139.                     if (!empty($vErrors)) {
  1140.                         $this->addFlash('error'implode(' '$vErrors));
  1141.                         return $this->redirectToRoute('add_employee');
  1142.                     }
  1143.                     $message $this->get('user_module')->addNewUser(
  1144.                         $data->request->get('firstname') . " " $data->request->get('lastname'),
  1145.                         $data->request->get('email'),
  1146.                         $data->request->get('username'),
  1147.                         $data->request->get('password'),
  1148.                         $data->request->get('desg'),
  1149.                         $this->getLoggedUserLoginId($data),
  1150.                         $data->request->get('company'),
  1151.                         $data->request->get('empStatus'),
  1152.                         $data->request->get('user_type'),
  1153.                         $data->request->get('companyIdList'),
  1154.                         $data->request->get('branch'),
  1155.                         $data->request->get('supervisor'),
  1156.                         $data->request->get('default_route'),
  1157.                         $data->request->has('access_module') ? 0,
  1158.                         "",
  1159.                         $data->files->get('img'),
  1160.                         '',
  1161.                         00,
  1162.                         ''''''0''0,
  1163.                         $data->request->get('global_user_id'null)
  1164.                     );
  1165.                     if ($message[0] === 'error') {
  1166.                         $this->addFlash('error''Invalid Approval Hash!');
  1167.                         return $this->redirectToRoute('add_employee');
  1168.                     }
  1169.                     $isSuccess HumanResource::StoreDataForAddEmployee($em$datafalse$CompanyId);
  1170.                     $Employee $isSuccess;
  1171.                     $EmployeeDetails $em->getRepository(EmployeeDetails::class)->findOneBy(['id' => $id]);
  1172.                     $Employee->setUserId($message[3]->getUserId());
  1173.                     $em->persist($Employee);
  1174.                     if ($EmployeeDetails) {
  1175.                         $EmployeeDetails->setUserId($message[3]->getUserId());
  1176.                         $em->persist($EmployeeDetails);
  1177.                     }
  1178.                     $em->flush();
  1179.                     $connection->commit();
  1180.                 } catch (Throwable $e) {
  1181.                     $connection->rollBack();
  1182.                     $em->close();
  1183.                     $this->addFlash('error''Failed to save employee: ' $e->getMessage());
  1184.                     return $this->redirectToRoute('add_employee');
  1185.                 }
  1186.                 if ($systemType !== '_CENTRAL_') {
  1187.                     $em_goc $this->getDoctrine()->getManager('company_group');
  1188.                     $em_goc->getConnection()->connect();
  1189.                     $connected $em_goc->getConnection()->isConnected();
  1190.                     if ($connected) {
  1191.                         $appIds $message[2]->getAppId();
  1192.                         $userIds $message[3]->getUserId();
  1193.                         $findByQuery = ['active' => 1];
  1194.                         if ($appIds !== '_UNSET_'$findByQuery['appId'] = $appIds;
  1195.                         $gocList $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")->findBy($findByQuery);
  1196.                         $gocDataList $gocDataListByAppId = [];
  1197.                         foreach ($gocList as $entry) {
  1198.                             $d = [
  1199.                                 'name' => $entry->getName(),
  1200.                                 'id' => $entry->getId(),
  1201.                                 'image' => $entry->getImage(),
  1202.                                 'companyGroupHash' => $entry->getCompanyGroupHash(),
  1203.                                 'dbName' => $entry->getDbName(),
  1204.                                 'dbUser' => $entry->getDbUser(),
  1205.                                 'dbPass' => $entry->getDbPass(),
  1206.                                 'dbHost' => $entry->getDbHost(),
  1207.                                 'appId' => $entry->getAppId(),
  1208.                                 'companyRemaining' => $entry->getCompanyRemaining(),
  1209.                                 'companyAllowed' => $entry->getCompanyAllowed(),
  1210.                             ];
  1211.                             $gocDataList[$entry->getId()] = $d;
  1212.                             $gocDataListByAppId[$entry->getAppId()] = $d;
  1213.                         }
  1214.                         $debugCount 0;
  1215.                         foreach ($gocDataList as $gocId => $entry) {
  1216.                             $skipSend 1;
  1217.                             $connector $this->container->get('application_connector');
  1218.                             $connector->resetConnection(
  1219.                                 'default',
  1220.                                 $entry['dbName'],
  1221.                                 $entry['dbUser'],
  1222.                                 $entry['dbPass'],
  1223.                                 $entry['dbHost'],
  1224.                                 $reset true
  1225.                             );
  1226.                             $em $this->getDoctrine()->getManager();
  1227.                             $users = ($userIds !== '_UNSET_')
  1228.                                 ? $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SysUser')->findBy(['userId' => $userIds])
  1229.                                 : $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SysUser')->findBy([]);
  1230.                             $userData $userFiles = [];
  1231.                             foreach ($users as $user) {
  1232.                                 $filePath $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1233.                                 if ($user->getImage() && file_exists($filePath)) {
  1234.                                     $mime mime_content_type($filePath);
  1235.                                     $info pathinfo($filePath);
  1236.                                     $name $info['basename'];
  1237.                                     if (strpos($mime'image') !== false) {
  1238.                                         $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = new \CURLFile($filePath$mime$name);
  1239.                                         $skipSend 0;
  1240.                                     }
  1241.                                 } else {
  1242.                                     $user->setImage(null);
  1243.                                     $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1244.                                     $em->flush();
  1245.                                 }
  1246.                                 $getters array_filter(get_class_methods($user), function ($m) {
  1247.                                     return substr($m03) === 'get';
  1248.                                 });
  1249.                                 $userDataSingle = [];
  1250.                                 foreach ($getters as $getter) {
  1251.                                     if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  1252.                                     $val $user->{$getter}();
  1253.                                     $userDataSingle[$getter] = $val instanceof \DateTime $val->format('Y-m-d') : $val;
  1254.                                 }
  1255.                                 $employeeGetters = [
  1256.                                     'getFirstname''getLastname''getImage''getIsImgLegal''getNid''getDob''getSex''getReligion',
  1257.                                     'getFather''getMother''getSpouse''getChild1''getChild2''getBlood''getPhone''getOfficailPhone',
  1258.                                     'getCurrAddr''getCurrAddrLat''getCurrAddrLng''getPermAddr''getEmmContact''getUsername''getEmail',
  1259.                                     'getPassword''getUserId''getJoiningDate''getEmpValidTill''getEmpStatus''getEmpType''getEmpCode',
  1260.                                     'getEmpLabel''getTin''getTinValidTill''getMedIns''getMedInsValidTill''getDocs''getNocApproval',
  1261.                                     'getInst1''getYr1''getDur1''getInst2''getYr2''getDur2''getInst3''getYr3''getDur3''getEinst1',
  1262.                                     'getEyr1''getEdeg1''getEinst2''getEyr2''getEdeg2''getEinst3''getEyr3''getEdeg3''getBankAcc',
  1263.                                     'getBankAccType''getBankAccValidFrom''getBankAccValidTo''getRoutingCode''getSwiftCode''getEar1',
  1264.                                     'getEar2''getEar3''getEar4''getEar5''getEar6''getEart''getDed1''getDed2''getDed3''getDed4',
  1265.                                     'getDedt''getPayable''getHandCash''getBankTransfer''getSecDep''getSecDepSpan''getSecDepRemMon',
  1266.                                     'getSecDepRemAmount''getSlQty''getSlTkn''getSlFreq''getMlQty''getMlTkn''getMlFreq''getElQty',
  1267.                                     'getElTkn''getElFreq''getClQty''getClTkn''getClFreq''getLevt''getWeeklyHoliday''getFiles',
  1268.                                     'getSupervisor''getDept''getDesg''getBranch''getDivision''getCreatedAt''getUpdatedAt',
  1269.                                     'getEmployeeLevel''getSkill''getProbationaryPeriod''getDocBookedFlag''getTimeStampOfForm',
  1270.                                     'getIsConsultant''getConsultantLevel''getApplicationText''getCurrentEmployment''getEmergencyContactNumber',
  1271.                                     'getPostalCode''getCountry''getEducationData''getWorkExperienceData''getCertificateData''getLanguagesData',
  1272.                                     'getBeneficiaryName''getBankName''getBranchName''getClockedIn'
  1273.                                 ];
  1274.                                 foreach ($employeeGetters as $getter) {
  1275.                                     if (!method_exists($EmployeeDetails$getter)) continue;
  1276.                                     $value $EmployeeDetails->{$getter}();
  1277.                                     if ($value instanceof \DateTime$userDataSingle[$getter] = $value->format('Y-m-d');
  1278.                                     elseif (!is_object($value)) $userDataSingle[$getter] = $value;
  1279.                                 }
  1280.                                 $userData[] = $userDataSingle;
  1281.                             }
  1282.                             $retDataDebug[$debugCount] = ['skipSend' => $skipSend];
  1283.                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1284.                             $userFiles['userData'] = json_encode($userData);
  1285.                             $curl curl_init();
  1286.                             curl_setopt_array($curl, [
  1287.                                 CURLOPT_RETURNTRANSFER => 1,
  1288.                                 CURLOPT_POST => 1,
  1289.                                 CURLOPT_URL => $urlToCall,
  1290.                                 CURLOPT_CONNECTTIMEOUT => 10,
  1291.                                 CURLOPT_SSL_VERIFYPEER => false,
  1292.                                 CURLOPT_SSL_VERIFYHOST => false,
  1293.                                 CURLOPT_POSTFIELDS => $userFiles
  1294.                             ]);
  1295.                             $retData curl_exec($curl);
  1296.                             $errData curl_error($curl);
  1297.                             curl_close($curl);
  1298.                             $retDataObj $errData ? ['status' => 'error''message' => 'cURL Error: ' $errData] : json_decode($retDatatrue);
  1299.                             $retDataDebug[$debugCount] = $retDataObj;
  1300.                             if (isset($retDataObj['globalIdsData'])) {
  1301.                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1302.                                     $connector->resetConnection(
  1303.                                         'default',
  1304.                                         $gocDataListByAppId[$app_id]['dbName'],
  1305.                                         $gocDataListByAppId[$app_id]['dbUser'],
  1306.                                         $gocDataListByAppId[$app_id]['dbPass'],
  1307.                                         $gocDataListByAppId[$app_id]['dbHost'],
  1308.                                         $reset true
  1309.                                     );
  1310.                                     $em $this->getDoctrine()->getManager();
  1311.                                     foreach ($usrList as $sys_id => $globaldata) {
  1312.                                         $user $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['userId' => $sys_id]);
  1313.                                         if ($user) {
  1314.                                             $user->setGlobalId($globaldata['gid']);
  1315.                                             $em->persist($user);
  1316.                                             $em->flush();
  1317.                                         }
  1318.                                     }
  1319.                                 }
  1320.                             }
  1321.                             $debugCount++;
  1322.                         }
  1323.                     }
  1324.                 }
  1325.                 $companyData $message[2];
  1326.                 if ($message[0] === 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  1327.                     $bodyTemplate '@Application/email/user/registration.html.twig';
  1328.                     $bodyData = [
  1329.                         'name' => $data->request->get('name'),
  1330.                         'companyData' => $companyData,
  1331.                         'userName' => $data->request->get('username'),
  1332.                         'password' => $data->request->get('password'),
  1333.                     ];
  1334.                     $new_mail $this->get('mail_module');
  1335.                     $new_mail->sendMyMail([
  1336.                         'senderHash' => '_CUSTOM_',
  1337.                         'forwardToMailAddress' => $data->request->get('email'),
  1338.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  1339.                         'fileName' => '',
  1340.                         'attachments' => [],
  1341.                         'toAddress' => $data->request->get('email'),
  1342.                         'fromAddress' => 'accounts@ourhoneybee.eu',
  1343.                         'userName' => 'accounts@ourhoneybee.eu',
  1344.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  1345.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  1346.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  1347.                         'mailTemplate' => $bodyTemplate,
  1348.                         'templateData' => $bodyData,
  1349.                         'embedCompanyImage' => 1,
  1350.                         'companyId' => $data->request->get('company'),
  1351.                         'companyImagePath' => $companyData->getImage()
  1352.                     ]);
  1353.                 }
  1354.                 $this->addFlash('success''New Employee Successfully Added!');
  1355.                 $userType $data->getSession()->get(UserConstants::USER_TYPE);
  1356.                 $redirectUrl $userType == 1
  1357.                     $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL)
  1358.                     : $this->generateUrl('add_employee', [], UrlGenerator::ABSOLUTE_URL);
  1359.                 return new JsonResponse([
  1360.                     'employeeId' => $Employee->getEmployeeId(),
  1361.                     'redirectToNew' => 1,
  1362.                     'success' => true,
  1363.                     'redirectUrl' => $redirectUrl,
  1364.                 ]);
  1365.             }
  1366.         }
  1367.     }
  1368.     /**
  1369.      * Redesigned cp-shell "Add Employee" form (calm, sectioned UX). GET only;
  1370.      * it POSTs to the existing `add_employee` handler (reusing the full save +
  1371.      * signature flow), so no backend duplication.
  1372.      */
  1373.     public function AddEmployeeCpAction(Request $data)
  1374.     {
  1375.         $em $this->getDoctrine()->getManager();
  1376.         $TwigData HumanResource::TwigDataForAddEmployee($em0);
  1377.         $banks $em->getRepository(BankList::class)->findAll();
  1378.         $bankListObj = [];
  1379.         foreach ($banks as $bank) { $bankListObj[$bank->getBankId()] = $bank->getName(); }
  1380.         return $this->render('@Application/pages/human_resource/input_forms/add_employee_cp.html.twig', [
  1381.             'page_title'          => 'Add Employee',
  1382.             'branches'            => $TwigData['branches'],
  1383.             'departments'         => $TwigData['departments'],
  1384.             'departmentPositions' => $TwigData['departmentPositions'],
  1385.             'supervisors'         => $TwigData['supervisors'],
  1386.             'EmploymentStatus'    => $TwigData['EmploymentStatus'],
  1387.             'AccountStatus'       => $TwigData['AccountStatus'],
  1388.             'sex'                 => $TwigData['sex'],
  1389.             'BloodGroup'          => $TwigData['BloodGroup'],
  1390.             'days'                => $TwigData['days'],
  1391.             'AccountTypes'        => $TwigData['AccountType'],
  1392.             'user_type_data'      => HumanResourceConstant::$userType,
  1393.             'skills'              => $em->getRepository(Skill::class)->findAll(),
  1394.             'bankListObj'         => $bankListObj,
  1395.             'heads'               => Accounts::getLedgerHeadsWithParents($em),
  1396.         ]);
  1397.     }
  1398.     public function AddNewEmployeeAction(Request $request$id)
  1399.     {
  1400.         $em $this->getDoctrine()->getManager();
  1401.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1402.         $approveHash $request->request->get('approvalHash');
  1403.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1404.         $CompanyId $this->getLoggedUserCompanyId($request);
  1405.         $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1406.         $employee HumanResource::StoreDataForAddEmployee($em$requestfalse$CompanyId);
  1407.         $isUserExist $em->getRepository(EmployeeDetails::class);
  1408.         if ($isSignatureOk) {
  1409.             if ($isUserExist) {
  1410.                 if ($employee) {
  1411.                     $message $this->get('user_module')->addNewUser(
  1412.                         $request->request->get('firstname') . " " $request->request->get('lastname'),
  1413.                         $request->request->get('email'),
  1414.                         $request->request->get('username'),
  1415.                         $request->request->get('password'),
  1416.                         $request->request->get('desg'),
  1417.                         $request->getLoggedUserLoginId($request),
  1418.                         $request->request->get('company'),
  1419.                         $request->request->get('user_type'),
  1420.                         $request->request->get('companyIdList'),
  1421.                         $request->request->get('branch'),
  1422.                         $request->request->get('supervisor'),
  1423.                         $request->request->get('default_route'),
  1424.                         $request->request->has('access_module') ? 0
  1425.                     );
  1426.                     if ($message[0] == 'success') {
  1427.                         $employee->setUserId($message[3]->getUserId());
  1428.                         $em->flush();
  1429.                         if ($systemType == '_CENTRAL_') {
  1430.                         } else {
  1431.                             $em_goc $this->getDoctrine()->getManager('company_group');
  1432.                             $em_goc->getConnection()->connect();
  1433.                             $connected $em_goc->getConnection()->isConnected();
  1434.                             $gocDataList = [];
  1435.                             $gocDataListByAppId = [];
  1436.                             $retDataDebug = array();
  1437.                             $appIds $message[2]->getAppId();
  1438.                             $userIds $message[3]->getUserId();
  1439.                             if ($connected) {
  1440.                                 $findByQuery = array(
  1441.                                     'active' => 1
  1442.                                 );
  1443.                                 if ($appIds !== '_UNSET_')
  1444.                                     $findByQuery['appId'] = $appIds;
  1445.                                 $gocList $this->getDoctrine()->getManager('company_group')
  1446.                                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1447.                                     ->findBy($findByQuery);
  1448.                                 foreach ($gocList as $entry) {
  1449.                                     $d = array(
  1450.                                         'name' => $entry->getName(),
  1451.                                         'id' => $entry->getId(),
  1452.                                         'image' => $entry->getImage(),
  1453.                                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  1454.                                         'dbName' => $entry->getDbName(),
  1455.                                         'dbUser' => $entry->getDbUser(),
  1456.                                         'dbPass' => $entry->getDbPass(),
  1457.                                         'dbHost' => $entry->getDbHost(),
  1458.                                         'appId' => $entry->getAppId(),
  1459.                                         'companyRemaining' => $entry->getCompanyRemaining(),
  1460.                                         'companyAllowed' => $entry->getCompanyAllowed(),
  1461.                                     );
  1462.                                     $gocDataList[$entry->getId()] = $d;
  1463.                                     $gocDataListByAppId[$entry->getAppId()] = $d;
  1464.                                 }
  1465.                                 $debugCount 0;
  1466.                                 foreach ($gocDataList as $gocId => $entry) {
  1467.                                     $skipSend 1;
  1468.                                     $connector $this->container->get('application_connector');
  1469.                                     $connector->resetConnection(
  1470.                                         'default',
  1471.                                         $gocDataList[$gocId]['dbName'],
  1472.                                         $gocDataList[$gocId]['dbUser'],
  1473.                                         $gocDataList[$gocId]['dbPass'],
  1474.                                         $gocDataList[$gocId]['dbHost'],
  1475.                                         $reset true);
  1476.                                     $em $this->getDoctrine()->getManager();
  1477.                                     if ($userIds !== '_UNSET_')
  1478.                                         $users $this->getDoctrine()
  1479.                                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1480.                                             ->findBy(
  1481.                                                 array(
  1482.                                                     'userId' => $userIds
  1483.                                                 )
  1484.                                             );
  1485.                                     else
  1486.                                         $users $this->getDoctrine()
  1487.                                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1488.                                             ->findBy(
  1489.                                                 array()
  1490.                                             );
  1491.                                     $output '';
  1492.                                     $userData = array();
  1493.                                     $userFiles = array();
  1494.                                     foreach ($users as $user) {
  1495.                                         $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1496.                                         if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  1497.                                             $mime mime_content_type($file);
  1498.                                             $info pathinfo($file);
  1499.                                             $name $info['basename'];
  1500.                                             if (strpos($mime'image') !== false) {
  1501.                                                 $output = new \CURLFile($file$mime$name);
  1502.                                             }
  1503.                                             $skipSend 0;
  1504.                                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  1505.                                         } else {
  1506.                                             $user->setImage(null);
  1507.                                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1508.                                             $em->flush();
  1509.                                         }
  1510.                                         $getters array_filter(get_class_methods($user), function ($method) {
  1511.                                             return 'get' === substr($method03);
  1512.                                         });
  1513.                                         $userDataSingle = array();
  1514.                                         foreach ($getters as $getter) {
  1515.                                             if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  1516.                                                 continue;
  1517. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  1518. //                                {
  1519. //                                    $userDataSingle[$getter]= $user->{$getter}();
  1520. //                                }
  1521.                                             if ($user->{$getter}() instanceof \DateTime) {
  1522.                                                 $ggtd $user->{$getter}();
  1523.                                                 $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  1524.                                             } else
  1525.                                                 $userDataSingle[$getter] = $user->{$getter}();
  1526.                                         }
  1527. //                                                    $userDataSingle['getNid']=$Employee->getNid();
  1528. //                                                    $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
  1529.                                         $userData[] = $userDataSingle;
  1530.                                     }
  1531.                                     $retDataDebug[$debugCount] = array(
  1532.                                         'skipSend' => $skipSend
  1533.                                     );
  1534.                                     {
  1535.                                         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1536.                                         $userFiles['userData'] = json_encode($userData);
  1537.                                         $curl curl_init();
  1538.                                         curl_setopt_array($curl, array(
  1539.                                             CURLOPT_RETURNTRANSFER => 1,
  1540.                                             CURLOPT_POST => 1,
  1541.                                             CURLOPT_URL => $urlToCall,
  1542.                                             CURLOPT_CONNECTTIMEOUT => 10,
  1543.                                             CURLOPT_SSL_VERIFYPEER => false,
  1544.                                             CURLOPT_SSL_VERIFYHOST => false,
  1545. //                            CURLOPT_SAFE_UPLOAD => false,
  1546.                                             CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  1547.                                             ),
  1548.                                             //                        CURLOPT_USERAGENT => 'InnoPM',
  1549. //                            CURLOPT_POSTFIELDS => array(
  1550. //                                'userData'=>json_encode($userData),
  1551. //                                'userFiles'=>$userFiles
  1552. //                            ),
  1553.                                             CURLOPT_POSTFIELDS => $userFiles
  1554.                                         ));
  1555.                                         $retData curl_exec($curl);
  1556.                                         $errData curl_error($curl);
  1557.                                         curl_close($curl);
  1558.                                         $response = [];
  1559.                                         if ($errData) {
  1560.                                             $response['status'] = 'error';
  1561.                                             $response['message'] = 'cURL Error: ' $errData;
  1562.                                         } else {
  1563.                                             $retDataObj json_decode($retDatatrue);
  1564.                                             if (!$retDataObj) {
  1565.                                                 $response['status'] = 'error';
  1566.                                                 $response['message'] = 'Invalid response from central server';
  1567.                                                 $response['raw_response'] = $retData;
  1568.                                             } else {
  1569.                                                 $response['status'] = 'success';
  1570.                                                 $response['data'] = $retDataObj;
  1571.                                             }
  1572.                                         }
  1573. // Return JSON response
  1574. //                                                    return new JsonResponse($response);
  1575.                                         $retDataDebug[$debugCount] = $retDataObj;
  1576.                                         if (isset($retDataObj['globalIdsData']))
  1577.                                             foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1578.                                                 $connector $this->container->get('application_connector');
  1579.                                                 $connector->resetConnection(
  1580.                                                     'default',
  1581.                                                     $gocDataListByAppId[$app_id]['dbName'],
  1582.                                                     $gocDataListByAppId[$app_id]['dbUser'],
  1583.                                                     $gocDataListByAppId[$app_id]['dbPass'],
  1584.                                                     $gocDataListByAppId[$app_id]['dbHost'],
  1585.                                                     $reset true);
  1586.                                                 $em $this->getDoctrine()->getManager();
  1587.                                                 foreach ($usrList as $sys_id => $globaldata) {
  1588.                                                     $user $this->getDoctrine()
  1589.                                                         ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1590.                                                         ->findOneBy(
  1591.                                                             array(
  1592.                                                                 'userId' => $sys_id
  1593.                                                             )
  1594.                                                         );
  1595.                                                     if ($user) {
  1596.                                                         $user->setGlobalId($globaldata['gid']);
  1597.                                                         $em->persist($user);
  1598.                                                         $em->flush();
  1599.                                                     }
  1600.                                                 }
  1601.                                             }
  1602.                                     }
  1603.                                     $debugCount++;
  1604.                                 }
  1605.                             }
  1606. //                    return new JsonResponse($retDataDebug);
  1607.                         }
  1608.                     }
  1609. //                                    if($message[0]=='success'){
  1610. //                                        $SysUserRepo = $em->getRepository('ApplicationBundle\\Entity\\SysUser');
  1611. //                                        $SysUser = $SysUserRepo->findOneBy([
  1612. //                                            'email' => $data->request->get('email')
  1613. //                                        ]);
  1614. //
  1615. //                                        if ($SysUser === null) {
  1616. //                                            throw new \Exception("User with email " . $data->request->get('email') . " not found.");
  1617. //                                        }
  1618. //
  1619. //                                        $isSuccess->setUserId($SysUser->getUserId());
  1620. //                                        $em->persist($isSuccess);
  1621. //                                        $em->flush();
  1622. //                                    }
  1623.                     $companyData $message[2];
  1624.                     if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  1625.                         $bodyHtml '';
  1626.                         $bodyTemplate '@Application/email/user/registration.html.twig';
  1627.                         $bodyData = array(
  1628.                             'name' => $request->request->get('name'),
  1629.                             'companyData' => $companyData,
  1630.                             'userName' => $request->request->get('username'),
  1631.                             'password' => $request->request->get('password'),
  1632.                         );
  1633.                         $attachments = [];
  1634.                         $new_mail $this->get('mail_module');
  1635.                         $new_mail->sendMyMail(array(
  1636.                             'senderHash' => '_CUSTOM_',
  1637.                             //                        'senderHash'=>'_CUSTOM_',
  1638.                             'forwardToMailAddress' => $request->request->get('email'),
  1639.                             'fromAddress' => 'accounts@ourhoneybee.eu',
  1640.                             'userName' => 'accounts@ourhoneybee.eu',
  1641.                             'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  1642.                             'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  1643.                             'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  1644.                             'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  1645.                             'fileName' => '',
  1646.                             'attachments' => $attachments,
  1647.                             'toAddress' => $request->request->get('email'),
  1648.                             'mailTemplate' => $bodyTemplate,
  1649.                             'templateData' => $bodyData,
  1650.                             'embedCompanyImage' => 1,
  1651.                             'companyId' => $request->request->get('company'),
  1652.                             'companyImagePath' => $companyData->getImage()
  1653.                         ));
  1654.                     }
  1655.                 }
  1656.                 $this->addFlash(
  1657.                     'success',
  1658.                     'New Employee Successfully Added!'
  1659.                 );
  1660.                 return $this->redirectToRoute('add_employee');
  1661.             } else {
  1662. //                        $requiredFields = [
  1663. //                            'email', 'username', 'password', 'firstname', 'lastname', 'nid', 'dob',
  1664. //                            'sex', 'blood', 'phone', 'perm_addr', 'dept', 'desg', 'branch',
  1665. //                            'emp_type', 'tin'
  1666. //                        ];
  1667. //
  1668. //                        $missingFields = [];
  1669. //
  1670. //                        foreach ($requiredFields as $field) {
  1671. //                            if (!$data->request->get($field)) {
  1672. //                                $missingFields[] = $field;
  1673. //                            }
  1674. //                        }
  1675. //                        if (!empty($missingFields)) {
  1676. //                            $this->addFlash('error', 'Missing fields: ' . implode(', ', $missingFields));
  1677. //                            return $this->redirectToRoute('add_employee');
  1678. //                        }
  1679. //                        $password = $data->request->get('password');
  1680. //                        $passwordPattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/';
  1681. //                        if (!preg_match($passwordPattern, $password)) {
  1682. //                            $this->addFlash('error', 'Password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one special character, and one number. ' . implode(', ', $missingFields));
  1683. //                            return $this->redirectToRoute('add_employee');
  1684. //                        }
  1685.                 $CompanyId $this->getLoggedUserCompanyId($request);
  1686.                 $isSuccess HumanResource::StoreDataForAddEmployee($em$requestfalse$CompanyId);
  1687.                 if ($isSuccess) {
  1688.                     if ($request->request->has('send_appointment')) {
  1689.                         $email $request->request->get('email');
  1690.                         $bodyHtml '';
  1691.                         $bodyTemplate '@Application/email/general/appointment_letter_test.html.twig';
  1692.                         $bodyData = [];
  1693.                         $attachments = [];
  1694.                         $forwardToMailAddress $email;
  1695.                         $new_mail $this->get('mail_module');
  1696.                         $new_mail->sendMyMail(array(
  1697.                             'senderHash' => '_CUSTOM_',
  1698.                             'forwardToMailAddress' => $forwardToMailAddress,
  1699.                             'subject' => 'Appointment Letter',
  1700.                             'attachments' => $attachments,
  1701.                             'toAddress' => $forwardToMailAddress,
  1702.                             'fromAddress' => 'accounts@ourhoneybee.eu',
  1703.                             'userName' => 'accounts@ourhoneybee.eu',
  1704.                             'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  1705.                             'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  1706.                             'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  1707.                             'emailBody' => $bodyHtml,
  1708.                             'mailTemplate' => $bodyTemplate,
  1709.                             'templateData' => $bodyData,
  1710.                         ));
  1711.                     }
  1712.                     // Mailer function
  1713.                     if ($request->get("send_mail") && empty($request->get('sys_user'))) {
  1714.                         $message $this->get('user_module')->addNewUser(
  1715.                             $request->request->get('firstname') . " " $request->request->get('lastname'),
  1716.                             $request->request->get('email'),
  1717.                             $request->request->get('username'),
  1718.                             $request->request->get('password'),
  1719.                             $request->request->get('desg'),
  1720.                             $request->getLoggedUserLoginId($request),
  1721.                             $request->request->get('company'),
  1722.                             $request->request->get('user_type'),
  1723.                             $request->request->get('companyIdList'),
  1724.                             $request->request->get('branch'),
  1725.                             $request->request->get('supervisor'),
  1726.                             $request->request->get('default_route'),
  1727.                             $request->request->has('access_module') ? 0
  1728.                         );
  1729.                         if ($message[0] == 'success') {
  1730.                             if ($systemType == '_CENTRAL_') {
  1731.                             } else {
  1732.                                 $em_goc $this->getDoctrine()->getManager('company_group');
  1733.                                 $em_goc->getConnection()->connect();
  1734.                                 $connected $em_goc->getConnection()->isConnected();
  1735.                                 $gocDataList = [];
  1736.                                 $gocDataListByAppId = [];
  1737.                                 $retDataDebug = array();
  1738.                                 $appIds $message[2]->getAppId();
  1739.                                 $userIds $message[3]->getUserId();
  1740.                                 if ($connected) {
  1741.                                     $findByQuery = array(
  1742.                                         'active' => 1
  1743.                                     );
  1744.                                     if ($appIds !== '_UNSET_')
  1745.                                         $findByQuery['appId'] = $appIds;
  1746.                                     $gocList $this->getDoctrine()->getManager('company_group')
  1747.                                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1748.                                         ->findBy($findByQuery);
  1749.                                     foreach ($gocList as $entry) {
  1750.                                         $d = array(
  1751.                                             'name' => $entry->getName(),
  1752.                                             'id' => $entry->getId(),
  1753.                                             'image' => $entry->getImage(),
  1754.                                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  1755.                                             'dbName' => $entry->getDbName(),
  1756.                                             'dbUser' => $entry->getDbUser(),
  1757.                                             'dbPass' => $entry->getDbPass(),
  1758.                                             'dbHost' => $entry->getDbHost(),
  1759.                                             'appId' => $entry->getAppId(),
  1760.                                             'companyRemaining' => $entry->getCompanyRemaining(),
  1761.                                             'companyAllowed' => $entry->getCompanyAllowed(),
  1762.                                         );
  1763.                                         $gocDataList[$entry->getId()] = $d;
  1764.                                         $gocDataListByAppId[$entry->getAppId()] = $d;
  1765.                                     }
  1766.                                     $debugCount 0;
  1767.                                     foreach ($gocDataList as $gocId => $entry) {
  1768.                                         $skipSend 1;
  1769.                                         $connector $this->container->get('application_connector');
  1770.                                         $connector->resetConnection(
  1771.                                             'default',
  1772.                                             $gocDataList[$gocId]['dbName'],
  1773.                                             $gocDataList[$gocId]['dbUser'],
  1774.                                             $gocDataList[$gocId]['dbPass'],
  1775.                                             $gocDataList[$gocId]['dbHost'],
  1776.                                             $reset true);
  1777.                                         $em $this->getDoctrine()->getManager();
  1778.                                         if ($userIds !== '_UNSET_')
  1779.                                             $users $this->getDoctrine()
  1780.                                                 ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1781.                                                 ->findBy(
  1782.                                                     array(
  1783.                                                         'userId' => $userIds
  1784.                                                     )
  1785.                                                 );
  1786.                                         else
  1787.                                             $users $this->getDoctrine()
  1788.                                                 ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1789.                                                 ->findBy(
  1790.                                                     array()
  1791.                                                 );
  1792.                                         $output '';
  1793.                                         $userData = array();
  1794.                                         $userFiles = array();
  1795.                                         foreach ($users as $user) {
  1796.                                             $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1797.                                             if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  1798.                                                 $mime mime_content_type($file);
  1799.                                                 $info pathinfo($file);
  1800.                                                 $name $info['basename'];
  1801.                                                 if (strpos($mime'image') !== false) {
  1802.                                                     $output = new \CURLFile($file$mime$name);
  1803.                                                 }
  1804.                                                 $skipSend 0;
  1805.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  1806.                                             } else {
  1807.                                                 $user->setImage(null);
  1808.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1809.                                                 $em->flush();
  1810.                                             }
  1811.                                             $getters array_filter(get_class_methods($user), function ($method) {
  1812.                                                 return 'get' === substr($method03);
  1813.                                             });
  1814.                                             $userDataSingle = array();
  1815.                                             foreach ($getters as $getter) {
  1816.                                                 if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  1817.                                                     continue;
  1818. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  1819. //                                {
  1820. //                                    $userDataSingle[$getter]= $user->{$getter}();
  1821. //                                }
  1822.                                                 if ($user->{$getter}() instanceof \DateTime) {
  1823.                                                     $ggtd $user->{$getter}();
  1824.                                                     $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  1825.                                                 } else
  1826.                                                     $userDataSingle[$getter] = $user->{$getter}();
  1827.                                             }
  1828. //                                                    $userDataSingle['getNid']=$Employee->getNid();
  1829. //                                                    $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
  1830.                                             $userData[] = $userDataSingle;
  1831.                                         }
  1832.                                         $retDataDebug[$debugCount] = array(
  1833.                                             'skipSend' => $skipSend
  1834.                                         );
  1835.                                         {
  1836.                                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1837.                                             $userFiles['userData'] = json_encode($userData);
  1838.                                             $curl curl_init();
  1839.                                             curl_setopt_array($curl, array(
  1840.                                                 CURLOPT_RETURNTRANSFER => 1,
  1841.                                                 CURLOPT_POST => 1,
  1842.                                                 CURLOPT_URL => $urlToCall,
  1843.                                                 CURLOPT_CONNECTTIMEOUT => 10,
  1844.                                                 CURLOPT_SSL_VERIFYPEER => false,
  1845.                                                 CURLOPT_SSL_VERIFYHOST => false,
  1846. //                            CURLOPT_SAFE_UPLOAD => false,
  1847.                                                 CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  1848.                                                 ),
  1849.                                                 //                        CURLOPT_USERAGENT => 'InnoPM',
  1850. //                            CURLOPT_POSTFIELDS => array(
  1851. //                                'userData'=>json_encode($userData),
  1852. //                                'userFiles'=>$userFiles
  1853. //                            ),
  1854.                                                 CURLOPT_POSTFIELDS => $userFiles
  1855.                                             ));
  1856.                                             $retData curl_exec($curl);
  1857.                                             $errData curl_error($curl);
  1858.                                             curl_close($curl);
  1859.                                             $response = [];
  1860.                                             if ($errData) {
  1861.                                                 $response['status'] = 'error';
  1862.                                                 $response['message'] = 'cURL Error: ' $errData;
  1863.                                             } else {
  1864.                                                 $retDataObj json_decode($retDatatrue);
  1865.                                                 if (!$retDataObj) {
  1866.                                                     $response['status'] = 'error';
  1867.                                                     $response['message'] = 'Invalid response from central server';
  1868.                                                     $response['raw_response'] = $retData;
  1869.                                                 } else {
  1870.                                                     $response['status'] = 'success';
  1871.                                                     $response['data'] = $retDataObj;
  1872.                                                 }
  1873.                                             }
  1874. // Return JSON response
  1875. //                                                    return new JsonResponse($response);
  1876.                                             $retDataDebug[$debugCount] = $retDataObj;
  1877.                                             if (isset($retDataObj['globalIdsData']))
  1878.                                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1879.                                                     $connector $this->container->get('application_connector');
  1880.                                                     $connector->resetConnection(
  1881.                                                         'default',
  1882.                                                         $gocDataListByAppId[$app_id]['dbName'],
  1883.                                                         $gocDataListByAppId[$app_id]['dbUser'],
  1884.                                                         $gocDataListByAppId[$app_id]['dbPass'],
  1885.                                                         $gocDataListByAppId[$app_id]['dbHost'],
  1886.                                                         $reset true);
  1887.                                                     $em $this->getDoctrine()->getManager();
  1888.                                                     foreach ($usrList as $sys_id => $globaldata) {
  1889.                                                         $user $this->getDoctrine()
  1890.                                                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  1891.                                                             ->findOneBy(
  1892.                                                                 array(
  1893.                                                                     'userId' => $sys_id
  1894.                                                                 )
  1895.                                                             );
  1896.                                                         if ($user) {
  1897.                                                             $user->setGlobalId($globaldata['gid']);
  1898.                                                             $em->persist($user);
  1899.                                                             $em->flush();
  1900.                                                         }
  1901.                                                     }
  1902.                                                 }
  1903.                                         }
  1904.                                         $debugCount++;
  1905.                                     }
  1906.                                 }
  1907. //                    return new JsonResponse($retDataDebug);
  1908.                             }
  1909.                         }
  1910.                         $SysUserRepo $em->getRepository(SysUser::class);
  1911.                         $SysUser $SysUserRepo->findOneBy(array(
  1912.                             'email' => $request->request->get('email')
  1913.                         ));
  1914.                         $isSuccess->setUserId($SysUser->getUserId());
  1915.                         $em->persist($isSuccess);
  1916.                         $em->flush();
  1917.                         $companyData $message[2];
  1918.                         if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  1919.                             $bodyHtml '';
  1920.                             $bodyTemplate '@Application/email/user/registration.html.twig';
  1921.                             $bodyData = array(
  1922.                                 'name' => $request->request->get('name'),
  1923.                                 'companyData' => $companyData,
  1924.                                 'userName' => $request->request->get('username'),
  1925.                                 'password' => $request->request->get('password'),
  1926.                             );
  1927.                             $attachments = [];
  1928. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  1929.                             $new_mail $this->get('mail_module');
  1930.                             $new_mail->sendMyMail(array(
  1931.                                 'senderHash' => '_CUSTOM_',
  1932.                                 //                        'senderHash'=>'_CUSTOM_',
  1933.                                 'forwardToMailAddress' => $request->request->get('email'),
  1934.                                 'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  1935.                                 'fileName' => '',
  1936.                                 'attachments' => $attachments,
  1937.                                 'toAddress' => $request->request->get('email'),
  1938.                                 'fromAddress' => 'accounts@ourhoneybee.eu',
  1939.                                 'userName' => 'accounts@ourhoneybee.eu',
  1940.                                 'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  1941.                                 'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  1942.                                 'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  1943. //                        'fromAddress'=>'sales@entity.innobd.com',
  1944. //                        'userName'=>'sales@entity.innobd.com',
  1945. //                        'password'=>'Y41dh8g0112',
  1946. //                        'smtpServer'=>'smtp.hostinger.com',
  1947. //                        'smtpPort'=>587,
  1948. //                        'emailBody'=>$bodyHtml,
  1949.                                 'mailTemplate' => $bodyTemplate,
  1950.                                 'templateData' => $bodyData,
  1951.                                 'embedCompanyImage' => 1,
  1952.                                 'companyId' => $request->request->get('company'),
  1953.                                 'companyImagePath' => $companyData->getImage()
  1954.                             ));
  1955. //                  $emailmessage = (new \Swift_Message('Registration to Entity'))
  1956. //                    ->setFrom('registration@entity.innobd.com')
  1957. //                    ->setTo($data->request->get('email'))
  1958. //                    ->setBody(
  1959. //                      $this->renderView(
  1960. //                        'ApplicationBundle:email/user:registration.html.twig',
  1961. //                        array(
  1962. //                          'name' => $data->request->get('name'),
  1963. //                          'companyData' => $companyData,
  1964. //                          'userName' => $data->request->get('email'),
  1965. //                          'password' => $data->request->get('password'),
  1966. //                        )
  1967. //                      ),
  1968. //                      'text/html'
  1969. //                    );
  1970. //                  $this->get('mailer')->send($emailmessage);
  1971.                         }
  1972.                     }
  1973.                     // End Mailer function
  1974.                     $this->addFlash(
  1975.                         'success',
  1976.                         'New Employee Successfully Added!'
  1977.                     );
  1978.                     return $this->redirectToRoute('employee_list');
  1979.                 } else {
  1980.                     $this->addFlash(
  1981.                         'error',
  1982.                         'Something Went Wrong!'
  1983.                     );
  1984.                     return $this->redirectToRoute('add_employee');
  1985.                 }
  1986.             }
  1987.         } else {
  1988.             $this->addFlash(
  1989.                 'error',
  1990.                 'Invalid Approval Hash!'
  1991.             );
  1992.             return $this->redirectToRoute('add_employee');
  1993.         }
  1994.     }
  1995.     public function UpdateEmployeeAction(Request $request$id)
  1996.     {
  1997.     }
  1998.     private function uploadImage($image$request)
  1999.     {
  2000.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
  2001.         $profileImage '';
  2002.         if ($image != null) {
  2003.             $fileName $request->request->get('firstname') . '.' $request->request->get('global_user_id') . '.' $image->guessExtension();
  2004.             $path $fileName;
  2005.             if (!file_exists($upl_dir)) {
  2006.                 mkdir($upl_dir0777true);
  2007.             }
  2008.             $image->move($upl_dir$path);
  2009.             $profileImage 'uploads/Users/' $path;
  2010.         }
  2011.         return $profileImage;
  2012.     }
  2013.     private function uploadMeetingFile($file$request)
  2014.     {
  2015.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/meeting/';
  2016.         $uploadedFilePath '';
  2017.         if ($file != null) {
  2018.             $fileName uniqid() . '.' $file->guessExtension();
  2019.             if (!file_exists($upl_dir)) {
  2020.                 mkdir($upl_dir0777true);
  2021.             }
  2022.             $file->move($upl_dir$fileName);
  2023.             $uploadedFilePath 'uploads/meeting/' $fileName;
  2024.         }
  2025.         return $uploadedFilePath;
  2026.     }
  2027.     public function OnboardEmployeeAction(Request $request)
  2028.     {
  2029.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2030.         $email $request->request->get('email');
  2031.         $applicantId $request->request->get('applicant_id');
  2032.         $em_goc $this->getDoctrine()->getManager('company_group');
  2033.         $em $this->getDoctrine()->getManager();
  2034.         $session $request->getSession();
  2035.         $companyId $session->get('userCompanyId');
  2036.         $appId $session->get('userAppId');
  2037.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/get_applicant_data_central';
  2038.         $applicantFiles = [
  2039.             'email' => $email,
  2040.             'applicantId' => $applicantId
  2041.         ];
  2042.         $entityToken $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  2043.             ->findOneBy(['userId' => $applicantId]);
  2044.         $curl curl_init();
  2045.         curl_setopt_array($curl, array(
  2046.             CURLOPT_RETURNTRANSFER => 1,
  2047.             CURLOPT_POST => 1,
  2048.             CURLOPT_URL => $urlToCall,
  2049.             CURLOPT_CONNECTTIMEOUT => 10,
  2050.             CURLOPT_SSL_VERIFYPEER => false,
  2051.             CURLOPT_SSL_VERIFYHOST => false,
  2052.             CURLOPT_HTTPHEADER => array(),
  2053.             CURLOPT_POSTFIELDS => $applicantFiles
  2054.         ));
  2055.         $retData curl_exec($curl);
  2056.         $errData curl_error($curl);
  2057.         curl_close($curl);
  2058.         $retDataObj json_decode($retDatatrue);
  2059.         if (!isset($retDataObj['status']) || $retDataObj['status'] !== 'success') {
  2060.             return new JsonResponse([
  2061.                 'status' => 'error',
  2062.                 'message' => 'Failed to get applicant data from central server',
  2063.                 'response' => $retDataObj
  2064.             ]);
  2065.         }
  2066.         $centralData $retDataObj['centralData'];
  2067.         $em $this->getDoctrine()->getManager();
  2068.         $existingUser $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy([
  2069.             'globalId' => $centralData['globalId']
  2070.         ]);
  2071.         if ($existingUser) {
  2072.             return new JsonResponse([
  2073.                 'status' => 'info',
  2074.                 'message' => 'User is already onboarded',
  2075.                 'userId' => $existingUser->getUserId(),
  2076.                 'redirectUrl' => 'dashboard'
  2077.             ]);
  2078.         }
  2079.         $sysUser = new SysUser();
  2080.         $sysUser->setGlobalId($centralData['globalId'] ?? '');
  2081.         $sysUser->setUsername($centralData['username'] ?? '');
  2082.         $sysUser->setEmail($centralData['email'] ?? '');
  2083.         $sysUser->setName($centralData['firstname'] ?? '');
  2084.         $sysUser->setUserType(1);
  2085.         $sysUser->setUserAppId($appId);
  2086.         $sysUser->setUserCompanyId($companyId);
  2087.         $sysUser->setStatus(1);
  2088.         $sysUser->setDefaultRoute('sales_dashboard');
  2089.         $em->persist($sysUser);
  2090.         $em->flush();
  2091.         $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')
  2092.             ->findOneBy(
  2093.                 array(
  2094.                     'userId' => $sysUser->getUserId(),
  2095.                 )
  2096.             );
  2097.         if (!$employee) {
  2098.             $employee = new Employee();
  2099.             if ($sysUser->getUserId()) {
  2100.                 $employee->setEmail($sysUser->getEmail());
  2101.                 $employee->setFirstName($sysUser->getUsername());
  2102.                 $employee->setLastName($sysUser->getName());
  2103.                 $employee->setCompanyId($sysUser->getUserCompanyId());
  2104.                 $employee->setStatus(1);
  2105.                 $employee->setUserId($sysUser->getUserId());
  2106.                 $em->persist($employee);
  2107.                 $em->flush();
  2108.             } else {
  2109.                 return new JsonResponse([
  2110.                     'status' => 'error',
  2111.                     'message' => 'Missing employee data',
  2112.                 ]);
  2113.             }
  2114.         }
  2115.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  2116.             ->findOneBy([
  2117.                 'userId' => $sysUser->getUserId(),
  2118.             ]);
  2119.         if (!$employeeDetails) {
  2120.             $employeeDetails = new EmployeeDetails();
  2121.             if ($sysUser->getUserId() && $employee->getEmployeeId()) {
  2122.                 $employeeDetails->setId($employee->getEmployeeId());
  2123.                 $employeeDetails->setEmail($sysUser->getEmail());
  2124.                 $employeeDetails->setFirstName($sysUser->getUsername());
  2125.                 $employeeDetails->setLastName($sysUser->getName());
  2126.                 $employeeDetails->setUsername($sysUser->getUsername());
  2127.                 $employeeDetails->setUserId($sysUser->getUserId());
  2128.                 $employeeDetails->setEmpStatus(1);
  2129.                 $em->persist($employeeDetails);
  2130.                 $em->flush();
  2131.             } else {
  2132.                 return new JsonResponse([
  2133.                     'status' => 'error',
  2134.                     'message' => 'Missing employee details data',
  2135.                 ]);
  2136.             }
  2137.         }
  2138.         $company $em->getRepository('ApplicationBundle\\Entity\\Company')->find($companyId);
  2139.         $companyName $company $company->getName() : '';
  2140.         $newAccess = [
  2141.             'userType' => 2,
  2142.             'userTypeName' => UserConstants::$userTypeName[2],
  2143.             'globalId' => $applicantId,
  2144.             'serverId' => 1,
  2145.             'serverUrl' => $request->getSchemeAndHttpHost(),
  2146.             'serverPort' => 80,
  2147.             'systemType' => '_ERP_',
  2148.             'companyId' => 1,
  2149.             'appId' => $appId,
  2150.             'companyLogoUrl' => '/uploads/CompanyImage/company_image' $request->request->get('appId') . '.png',
  2151.             'companyName' => $companyName,
  2152.             'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  2153.                     array(
  2154.                         'globalId' => $applicantId,
  2155.                         'appId' => $appId,
  2156.                         'authenticate' => 1,
  2157.                         'userType' => 2,
  2158.                         'userTypeName' => UserConstants::$userTypeName[2]
  2159.                     )
  2160.                 )
  2161.             ),
  2162.             'userCompanyList' => [],
  2163.         ];
  2164.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/update_token_storage';
  2165.         $curl curl_init();
  2166.         curl_setopt_array($curl, array(
  2167.             CURLOPT_RETURNTRANSFER => 1,
  2168.             CURLOPT_POST => 1,
  2169.             CURLOPT_URL => $urlToCall,
  2170.             CURLOPT_CONNECTTIMEOUT => 10,
  2171.             CURLOPT_SSL_VERIFYPEER => false,
  2172.             CURLOPT_SSL_VERIFYHOST => false,
  2173.             CURLOPT_HTTPHEADER => array(),
  2174.             CURLOPT_POSTFIELDS => json_encode($newAccess)
  2175.         ));
  2176.         $retData curl_exec($curl);
  2177.         $errData curl_error($curl);
  2178.         return new JsonResponse([
  2179.             'status' => 'success',
  2180.             'message' => 'User onboarded successfully',
  2181.             'redirectUlr' => 'dashboard',
  2182.             'returnData' => $retData,
  2183.             'errorData' => $errData
  2184.         ]);
  2185.     }
  2186.     public function UpdateTokenStorageAction(Request $request)
  2187.     {
  2188.         $em_goc $this->getDoctrine()->getManager('company_group');
  2189.         $newAccess $request->request->all();
  2190.         $appId = isset($newAccess['appId']) ? $newAccess['appId'] : null;
  2191.         $globalId = isset($newAccess['globalId']) ? $newAccess['globalId'] : null;
  2192.         $sesssionData MiscActions::UpdateCompanyListInSession(
  2193.             $em_goc,
  2194.             $globalId,
  2195.             1,
  2196.             1,
  2197.             1,
  2198.             $newAccess
  2199.         );
  2200.         return new JsonResponse([
  2201.             'status' => 'success',
  2202.             'message' => 'Token storage updated',
  2203.             'newaccess' => $newAccess
  2204.         ]);
  2205.     }
  2206.     /**
  2207.      * Authenticated launchers for the public HR letters (salary certificate / appointment letter).
  2208.      *
  2209.      * Security (IDOR fix): the public letter routes accept a RAW numeric employee id + appId query
  2210.      * param, so a plain link like /public/252?appId=9050 is enumerable and leaks salary/PII across
  2211.      * tenants without any auth. Instead of exposing that raw form from the employee list, the list
  2212.      * now links here â€” a SESSION-PROTECTED route (SessionCheckInterface). We mint the encrypted
  2213.      * token server-side from the CURRENT session's appId (so a user can only ever produce tokens for
  2214.      * their own tenant) and redirect to the public route with that opaque, non-guessable token. The
  2215.      * public action already decrypts the non-numeric id form.
  2216.      */
  2217.     public function SalaryCertificateLaunchAction(Request $request$id)
  2218.     {
  2219.         return $this->redirectToRoute('salary_certificate', array(
  2220.             'id' => $this->buildEncryptedEmployeeDocToken($request$id)
  2221.         ));
  2222.     }
  2223.     public function AppointmentLetterLaunchAction(Request $request$id)
  2224.     {
  2225.         return $this->redirectToRoute('appointment_letter', array(
  2226.             'id' => $this->buildEncryptedEmployeeDocToken($request$id)
  2227.         ));
  2228.     }
  2229.     /**
  2230.      * Encrypts {id, appId, dt} for a public employee-document link. appId comes from the session
  2231.      * (never the request) so the token is always scoped to the caller's own tenant.
  2232.      */
  2233.     private function buildEncryptedEmployeeDocToken(Request $request$id)
  2234.     {
  2235.         $payload = array(
  2236.             'id' => (int) $id,
  2237.             'appId' => (int) $this->getLoggedUserAppId($request),
  2238.             'dt' => (new \DateTime())->format('Y-m-d'),
  2239.         );
  2240.         return $this->get('url_encryptor')->encrypt(json_encode($payload));
  2241.     }
  2242.     public function EmployeeListAction(Request $data)
  2243.     {
  2244.         $em $this->getDoctrine()->getManager();
  2245.         if ($data->isMethod('GET')) {
  2246.             return $this->render("@Application/pages/human_resource/list/list_employee.html.twig", array(
  2247.                 'page_title' => 'Employee List',
  2248.             ));
  2249.         }
  2250.     }
  2251.     /**
  2252.      * Employee transaction profile â€” a single page (modelled on the Client Profile) that
  2253.      * surfaces, for one employee: their expense activity (approved + pending), the payments
  2254.      * they have taken (payslip disbursements), and their payslip history.
  2255.      * Data sources are all existing tables â€” no schema change:
  2256.      *   â€¢ employee_details            â†’ the person
  2257.      *   â€¢ expense_invoice.expense_of_employee_id (+ approved) â†’ expenses they did
  2258.      *   â€¢ payslip.sys_id = employee id â†’ payslips / salary paid
  2259.      */
  2260.     public function EmployeeProfileAction(Request $request$id)
  2261.     {
  2262.         $em $this->getDoctrine()->getManager();
  2263.         $employee $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findOneBy(
  2264.             array('id' => $id)
  2265.         );
  2266.         if (!$employee) {
  2267.             $this->addFlash('error''Employee not found.');
  2268.             return $this->redirect($this->generateUrl('hrm_cockpit'));
  2269.         }
  2270.         // â”€â”€ Expenses done by this employee â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  2271.         $expenses $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->findBy(
  2272.             array('expenseOfEmployeeId' => $id),
  2273.             array('expenseInvoiceDate' => 'DESC')
  2274.         );
  2275.         $expApprovedCount 0$expApprovedAmount 0.0;
  2276.         $expPendingCount  0$expPendingAmount  0.0;
  2277.         $expOtherCount    0$expOtherAmount    0.0;
  2278.         $advanceTaken     0.0;
  2279.         $expenseRows = array();
  2280.         foreach ($expenses as $e) {
  2281.             $status = (int) $e->getApproved();
  2282.             $amount = (float) $e->getInvoiceAmount();
  2283.             $advance = (float) $e->getAdvanceAmount();
  2284.             $advanceTaken += $advance;
  2285.             if ($status === GeneralConstant::APPROVED) {
  2286.                 $expApprovedCount++; $expApprovedAmount += $amount;
  2287.                 $statusLabel 'Approved'$statusClass 'approved';
  2288.             } elseif ($status === GeneralConstant::APPROVAL_STATUS_PENDING) {
  2289.                 $expPendingCount++; $expPendingAmount += $amount;
  2290.                 $statusLabel 'Pending'$statusClass 'pending';
  2291.             } else {
  2292.                 $expOtherCount++; $expOtherAmount += $amount;
  2293.                 $statusLabel = ($status === 0) ? 'Declined' 'Other'$statusClass 'other';
  2294.             }
  2295.             $expenseRows[] = array(
  2296.                 'id'          => $e->getExpenseInvoiceId(),
  2297.                 'documentHash'=> $e->getDocumentHash(),
  2298.                 'date'        => $e->getExpenseInvoiceDate(),
  2299.                 'amount'      => $amount,
  2300.                 'advance'     => $advance,
  2301.                 'statusLabel' => $statusLabel,
  2302.                 'statusClass' => $statusClass,
  2303.             );
  2304.         }
  2305.         // â”€â”€ Payslips / payments taken â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  2306.         $payslips $em->getRepository('ApplicationBundle\\Entity\\Payslip')->findBy(
  2307.             array('sysId' => $id),
  2308.             array('payslipId' => 'DESC')
  2309.         );
  2310.         $payslipCount 0$payslipTotalPaid 0.0;
  2311.         $payslipRows = array();
  2312.         foreach ($payslips as $p) {
  2313.             $net = (float) $p->getToTalSalary();
  2314.             $payslipCount++; $payslipTotalPaid += $net;
  2315.             $payslipRows[] = array(
  2316.                 'id'          => $p->getPayslipId(),
  2317.                 'documentHash'=> $p->getDocumentHash(),
  2318.                 'date'        => $p->getCreatedAt(),
  2319.                 'net'         => $net,
  2320.                 'status'      => $p->getStatus(),
  2321.             );
  2322.         }
  2323.         // â”€â”€ All vouchers touching this employee's ledger head(s) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  2324.         // employee.employee_id â†’ employee_details.id; that row carries the person's GL
  2325.         // account (accounts_head_id) and advance account (advance_head_id). Every voucher
  2326.         // leg posted to either head is "a voucher related to this employee".
  2327.         $conn $em->getConnection();
  2328.         $voucherRows = array();
  2329.         $voucherDebitTotal 0.0$voucherCreditTotal 0.0;
  2330.         try {
  2331.             $empLedger $conn->fetchAssociative(
  2332.                 "SELECT accounts_head_id, advance_head_id FROM employee WHERE employee_id = ? LIMIT 1",
  2333.                 array((int) $id)
  2334.             );
  2335.             $heads = array();
  2336.             if ($empLedger) {
  2337.                 if (!empty($empLedger['accounts_head_id'])) { $heads[] = (int) $empLedger['accounts_head_id']; }
  2338.                 if (!empty($empLedger['advance_head_id']))  { $heads[] = (int) $empLedger['advance_head_id']; }
  2339.             }
  2340.             if (!empty($heads)) {
  2341.                 $placeholders implode(','array_fill(0count($heads), '?'));
  2342.                 $sql "SELECT t.transaction_id, t.document_hash, t.transaction_date, t.description,
  2343.                                td.amount, td.position
  2344.                         FROM acc_transaction_details td
  2345.                         JOIN acc_transactions t ON t.transaction_id = td.transaction_id
  2346.                         WHERE td.accounts_head_id IN ($placeholders)
  2347.                           AND (t.status = 1 OR t.status IS NULL)
  2348.                         ORDER BY t.transaction_date DESC, t.transaction_id DESC";
  2349.                 $rows $conn->fetchAllAssociative($sql$heads);
  2350.                 foreach ($rows as $r) {
  2351.                     $amt = (float) $r['amount'];
  2352.                     $isDebit = ($r['position'] === 'dr' || $r['position'] === 'DR');
  2353.                     if ($isDebit) { $voucherDebitTotal += $amt; } else { $voucherCreditTotal += $amt; }
  2354.                     $voucherRows[] = array(
  2355.                         'id'          => $r['transaction_id'],
  2356.                         'documentHash'=> $r['document_hash'],
  2357.                         'date'        => $r['transaction_date'],
  2358.                         'description' => $r['description'],
  2359.                         'debit'       => $isDebit $amt 0.0,
  2360.                         'credit'      => $isDebit 0.0 $amt,
  2361.                     );
  2362.                 }
  2363.             }
  2364.         } catch (\Throwable $e) {
  2365.             // ledger lookup is best-effort â€” never break the profile page over it
  2366.             $voucherRows = array();
  2367.         }
  2368.         // Resolve department + designation ids to names (dept â†’ sys_department,
  2369.         // desg â†’ sys_department_position).
  2370.         $deptName '';
  2371.         $desgName '';
  2372.         try {
  2373.             $deptId = (int) $employee->getDept();
  2374.             $desgId = (int) $employee->getDesg();
  2375.             if ($deptId) {
  2376.                 $deptName = (string) $conn->fetchOne(
  2377.                     "SELECT department_name FROM sys_department WHERE department_id = ? LIMIT 1",
  2378.                     array($deptId)
  2379.                 );
  2380.             }
  2381.             if ($desgId) {
  2382.                 $desgName = (string) $conn->fetchOne(
  2383.                     "SELECT position_name FROM sys_department_position WHERE position_id = ? LIMIT 1",
  2384.                     array($desgId)
  2385.                 );
  2386.             }
  2387.         } catch (\Throwable $e) { /* names are best-effort */ }
  2388.         $data = array(
  2389.             'employee' => array(
  2390.                 'id'          => $employee->getId(),
  2391.                 'empCode'     => $employee->getEmpCode(),
  2392.                 'name'        => trim($employee->getFirstname() . ' ' $employee->getLastname()),
  2393.                 'department'  => $deptName,
  2394.                 'designation' => $desgName,
  2395.                 'image'       => $employee->getImage(),
  2396.                 'dept'        => $employee->getDept(),
  2397.                 'joiningDate' => $employee->getJoiningDate(),
  2398.                 'status'      => $employee->getEmpStatus(),
  2399.                 'phone'       => $employee->getPhone() ?: $employee->getOfficialPhone(),
  2400.                 'email'       => $employee->getEmail(),
  2401.             ),
  2402.             'kpi' => array(
  2403.                 'expenseTotalCount'   => count($expenses),
  2404.                 'expenseApprovedCount'=> $expApprovedCount,
  2405.                 'expenseApprovedAmount'=> $expApprovedAmount,
  2406.                 'expensePendingCount' => $expPendingCount,
  2407.                 'expensePendingAmount'=> $expPendingAmount,
  2408.                 'expenseOtherCount'   => $expOtherCount,
  2409.                 'expenseOtherAmount'  => $expOtherAmount,
  2410.                 'advanceTaken'        => $advanceTaken,
  2411.                 'payslipCount'        => $payslipCount,
  2412.                 'payslipTotalPaid'    => $payslipTotalPaid,
  2413.                 'voucherCount'        => count($voucherRows),
  2414.                 'voucherDebitTotal'   => $voucherDebitTotal,
  2415.                 'voucherCreditTotal'  => $voucherCreditTotal,
  2416.             ),
  2417.             'expenseRows' => $expenseRows,
  2418.             'payslipRows' => $payslipRows,
  2419.             'voucherRows' => $voucherRows,
  2420.         );
  2421.         return $this->render('@Application/pages/human_resource/views/employee_profile.html.twig', array(
  2422.             'page_title' => 'Employee Profile',
  2423.             'data'       => $data,
  2424.         ));
  2425.     }
  2426.     /**
  2427.      * Full read-only Employee View for the tenant â€” surfaces every field captured on the
  2428.      * employee-entry form, organised into sections (Personal, Employment, Payroll & Bank,
  2429.      * Leave, Skills/Education/Experience, Documents). Lookup ids are resolved to names.
  2430.      */
  2431.     public function EmployeeViewAction(Request $request$id)
  2432.     {
  2433.         $em $this->getDoctrine()->getManager();
  2434.         $conn $em->getConnection();
  2435.         $e $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findOneBy(array('id' => $id));
  2436.         if (!$e) {
  2437.             $this->addFlash('error''Employee not found.');
  2438.             return $this->redirect($this->generateUrl('hrm_cockpit'));
  2439.         }
  2440.         // best-effort single-value name lookup
  2441.         $lookup = function ($sql$val) use ($conn) {
  2442.             if ($val === null || $val === '' || $val == 0) return '';
  2443.             try { $v $conn->fetchOne($sql, array($val)); return $v === false '' : (string) $v; }
  2444.             catch (\Throwable $ex) { return ''; }
  2445.         };
  2446.         $jdec = function ($raw) {
  2447.             // Some fields are already cast to arrays by the ORM; others are raw JSON strings.
  2448.             if (is_array($raw)) return $raw;
  2449.             if ($raw === null || $raw === '' ) return array();
  2450.             $d json_decode($rawtrue);
  2451.             return is_array($d) ? $d : array();
  2452.         };
  2453.         // Resolve related names
  2454.         $deptName   $lookup("SELECT department_name FROM sys_department WHERE department_id = ? LIMIT 1"$e->getDept());
  2455.         $desgName   $lookup("SELECT position_name FROM sys_department_position WHERE position_id = ? LIMIT 1"$e->getDesg());
  2456.         $branchName $lookup("SELECT name FROM branch WHERE branch_id = ? LIMIT 1"$e->getBranch());
  2457.         $divName    $lookup("SELECT name FROM division WHERE division_id = ? LIMIT 1"$e->getDivision());
  2458.         $supRow     null;
  2459.         try {
  2460.             $supRow $conn->fetchAssociative("SELECT firstname, lastname FROM employee_details WHERE id = ? LIMIT 1", array((int) $e->getSupervisor()));
  2461.         } catch (\Throwable $ex) { $supRow null; }
  2462.         $supName $supRow trim(($supRow['firstname'] ?? '') . ' ' . ($supRow['lastname'] ?? '')) : '';
  2463.         $bankName $e->getBankName();
  2464.         if (!$bankName) { $bankName $lookup("SELECT bank_name FROM bank_list WHERE bank_id = ? LIMIT 1"$e->getBankId()); }
  2465.         // Skills (JSON array of skill ids â†’ names from tenant skill table)
  2466.         $skillIds $jdec($e->getSkill());
  2467.         $skillNames = array();
  2468.         if (!empty($skillIds)) {
  2469.             foreach ($skillIds as $sid) {
  2470.                 $n $lookup("SELECT name FROM skill WHERE skill_id = ? LIMIT 1", (int) $sid);
  2471.                 if ($n !== '') { $skillNames[] = $n; }
  2472.             }
  2473.         }
  2474.         $sexList   = \ApplicationBundle\Constants\EmployeeConstant::$sex;
  2475.         $bloodList = \ApplicationBundle\Constants\EmployeeConstant::$BloodGroup;
  2476.         $typeList  = \ApplicationBundle\Constants\EmployeeConstant::$employeeType;
  2477.         $fmtDate = function ($d) { return ($d instanceof \DateTimeInterface) ? $d->format('M d, Y') : ''; };
  2478.         $data = array(
  2479.             'id'    => $e->getId(),
  2480.             'name'  => trim($e->getFirstname() . ' ' $e->getLastname()),
  2481.             'image' => $e->getImage(),
  2482.             // Personal
  2483.             'personal' => array(
  2484.                 'First Name'        => $e->getFirstname(),
  2485.                 'Last Name'         => $e->getLastname(),
  2486.                 'Date of Birth'     => $fmtDate($e->getDob()),
  2487.                 'Gender'            => (isset($sexList[$e->getSex()]) ? $sexList[$e->getSex()] : $e->getSex()),
  2488.                 'Blood Group'       => (isset($bloodList[$e->getBlood()]) ? $bloodList[$e->getBlood()] : $e->getBlood()),
  2489.                 'Religion'          => $e->getReligion(),
  2490.                 'NID'               => $e->getNid(),
  2491.                 'TIN'               => $e->getTin(),
  2492.                 "Father's Name"     => $e->getFather(),
  2493.                 "Mother's Name"     => $e->getMother(),
  2494.                 'Spouse'            => $e->getSpouse(),
  2495.                 'Nationality/Country' => $e->getCountry(),
  2496.                 'Residency Status'  => $e->getResidencyStatus(),
  2497.             ),
  2498.             // Contact
  2499.             'contact' => array(
  2500.                 'Phone'             => $e->getPhone(),
  2501.                 'Official Phone'    => $e->getOfficialPhone(),
  2502.                 'Email'             => $e->getEmail(),
  2503.                 'Emergency Contact' => $e->getEmmContact() ?: $e->getEmergencyContactNumber(),
  2504.                 'Postal Code'       => $e->getPostalCode(),
  2505.                 'Current Address'   => $e->getCurrAddr(),
  2506.                 'Permanent Address' => $e->getPermAddr(),
  2507.             ),
  2508.             // Employment
  2509.             'employment' => array(
  2510.                 'Employee Code'      => $e->getEmpCode(),
  2511.                 'Username'           => $e->getUsername(),
  2512.                 'Designation'        => $desgName ?: $e->getDesg(),
  2513.                 'Department'         => $deptName ?: $e->getDept(),
  2514.                 'Branch'             => $branchName ?: $e->getBranch(),
  2515.                 'Division'           => $divName ?: $e->getDivision(),
  2516.                 'Supervisor'         => $supName,
  2517.                 'Employment Type'    => (isset($typeList[$e->getEmpType()]) ? $typeList[$e->getEmpType()] : $e->getEmpType()),
  2518.                 'Employee Level'     => $e->getEmployeeLevel(),
  2519.                 'Joining Date'       => $fmtDate($e->getJoiningDate()),
  2520.                 'Valid Till'         => $fmtDate($e->getEmpValidTill()),
  2521.                 'Status'             => ($e->getEmpStatus() == 'Active' 'Inactive'),
  2522.                 'Current Employment' => $e->getCurrentEmployment(),
  2523.             ),
  2524.             // Payroll & Bank
  2525.             'bank' => array(
  2526.                 'Beneficiary Name'  => $e->getBeneficiaryName(),
  2527.                 'Bank'              => $bankName,
  2528.                 'Branch Name'       => $e->getBranchName(),
  2529.                 'Account No'        => $e->getBankAcc(),
  2530.                 'Account Type'      => $e->getBankAccType(),
  2531.                 'Routing Code'      => $e->getRoutingCode(),
  2532.                 'SWIFT Code'        => $e->getSwiftCode(),
  2533.                 'Valid From'        => $fmtDate($e->getBankAccValidFrom()),
  2534.                 'Valid To'          => $fmtDate($e->getBankAccValidTo()),
  2535.             ),
  2536.             // Leave allocations
  2537.             'leave' => array(
  2538.                 'Sick (SL)'      => $e->getSlQty(),
  2539.                 'Casual (CL)'    => $e->getClQty(),
  2540.                 'Earned (EL)'    => $e->getElQty(),
  2541.                 'Maternity (ML)' => $e->getMlQty(),
  2542.                 'Weekly Holiday' => $e->getWeeklyHoliday(),
  2543.             ),
  2544.             'skills'         => $skillNames,
  2545.             'educationData'  => $jdec($e->getEducationData()),
  2546.             'experienceData' => $jdec($e->getWorkExperienceData()),
  2547.             'languagesData'  => $jdec($e->getLanguagesData()),
  2548.         );
  2549.         return $this->render('@Application/pages/human_resource/views/employee_view.html.twig', array(
  2550.             'page_title' => 'Employee View',
  2551.             'data'       => $data,
  2552.         ));
  2553.     }
  2554.     public function OrganizationChartAction()
  2555.     {
  2556.         $em $this->getDoctrine()->getManager();
  2557.         $Reponse HumanResource::TwigDataForOrgChart($em);
  2558.         return $this->render('@Application/pages/human_resource/views/org_chart.html.twig', array(
  2559.             'page_title' => 'Organization Chart',
  2560.             'supervisors' => $Reponse['TreantJsData'],
  2561.             'alluser' => $Reponse['TreantJsInitUser']
  2562.         ));
  2563.     }
  2564.     public function EmployeeListSelectizeAjaxAction(Request $request$str '_EMPTY_')
  2565.     {
  2566.         $em $this->getDoctrine()->getManager();
  2567.         $companyId $this->getLoggedUserCompanyId($request);
  2568.         $company_data Company::getCompanyData($em$companyId);
  2569.         $data = [];
  2570.         $html '';
  2571.         $qryStrs explode(' '$str);
  2572.         $qryStrAddedForSpacedName "";
  2573.         if ($str == '_EMPTY_') {
  2574.             $query "SELECT *
  2575. from  employee  order by employee_id asc limit 10";
  2576.         } else {
  2577.             foreach ($qryStrs as $qryStr) {
  2578.                 $qryStrAddedForSpacedName .= "or first_name like '%$qryStr%' or last_name like '%$qryStr%' ";
  2579.             }
  2580.             $query "SELECT  *
  2581. from  employee  where" . (is_numeric($str) ? " employee_id =$str " " 1=0 ") . $qryStrAddedForSpacedName " or `name` like '%$str%' or employee_code like '%$str%' order by employee_id asc limit 10";
  2582.         }
  2583.         $stmt $em->getConnection()->fetchAllAssociative($query);
  2584.         $res $stmt;
  2585. //    if(!empty($res)) {
  2586.         foreach ($res as $i => $r) {
  2587.             $res[$i]['id_padded'] = str_pad($r['employee_id'], 8'0'STR_PAD_LEFT);
  2588.         }
  2589. //    }
  2590.         return new JsonResponse(
  2591.             array(
  2592.                 'success' => true,
  2593.                 'data' => $res,
  2594.             )
  2595.         );
  2596.     }
  2597.     public function AttendanceAction(Request $data$remoteVerify 0)
  2598.     {
  2599.         $em $this->getDoctrine()->getManager();
  2600.         $em_goc $this->getDoctrine()->getManager('company_group');
  2601.         $session $data->getSession();
  2602. //        $token = $session->get(UserConstants::USER_TOKEN);
  2603. //        $providedToken = $data->headers->get('auth-token');
  2604. //
  2605. //        if (empty($providedToken) || $providedToken !== $token) {
  2606. //            return new JsonResponse([
  2607. //                'status' => 'error',
  2608. //                'message' => 'Token not match or missing',
  2609. //            ], 401);
  2610. //        }
  2611.         $workHourPolicy $em->getRepository('ApplicationBundle\\Entity\\WorkHourPolicy')->findAll();
  2612.         $options = array(
  2613.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2614.             'notification_server' => $this->container->getParameter('notification_server'),
  2615.         );
  2616.         if ($data->get('DataTable')) {
  2617.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  2618.             return new JsonResponse($response);
  2619.         }
  2620.         if ($data->request->get('getAttendanceStatus')) {
  2621.             $response HumanResource::getAttendanceStatus($em$data);
  2622.             return new JsonResponse($response);
  2623.         }
  2624. //        if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
  2625. //            return $this->redirectToRoute('permission_denied_page');
  2626.         // Auto attendance
  2627.         if ($data->get('autoAttendance') && $data->request->has('position_array')) {
  2628. //            $empId = $data->query->get('id');
  2629.             $empId $data->request->get('id'$session->get(UserConstants::USER_EMPLOYEE_ID));
  2630.             $positionsArray $data->request->get('position_array', []);
  2631.             if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  2632.             if ($positionsArray == null$positionsArray = [];
  2633.             $dataByAttId = [];
  2634.             $workPlaceType '_UNSET_';
  2635.             foreach ($positionsArray as $d) {
  2636.                 $sysUserId 0;
  2637.                 $userId 0;
  2638.                 $empId 0;
  2639.                 $dtTs 0;
  2640.                 $timeZoneStr '+0000';
  2641. //                $timeZoneStr = '+0600';
  2642.                 $token '_unset_';
  2643.                 if (isset($d['token'])) $token $d['token'];
  2644.                 if (isset($d['employeeId'])) $empId $d['employeeId'];
  2645.                 if (isset($d['userId'])) $userId $d['userId'];
  2646.                 if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  2647.                 if (isset($d['tsMilSec'])) {
  2648.                     $dtTs ceil(($d['tsMilSec']) / 1000);
  2649.                 }
  2650.                 if ($token != '_unset_') {
  2651.                     $sessionData MiscActions::GetSessionDataFromToken($em_goc$token)['sessionData'];
  2652.                     if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
  2653.                         $empId $sessionData[UserConstants::USER_EMPLOYEE_ID];
  2654.                 }
  2655.                 if ($sysUserId == 0)
  2656.                     $sysUserId $userId;
  2657.                 if ($sysUserId == 0)
  2658.                     $sysUserId $em->getRepository(Employee::class)
  2659.                         ->findOneBy(['employeeId' => $empId])->getUserId();
  2660.                 if ($dtTs == 0) {
  2661.                     $currTsTime = new \DateTime();
  2662.                     $dtTs $currTsTime->format('U');
  2663.                 } else {
  2664.                     $currTsTime = new \DateTime('@' $dtTs);
  2665.                 }
  2666.                 $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2667.                 $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2668.                 $EmployeeAttendance $this->getDoctrine()
  2669.                     ->getRepository(EmployeeAttendance::class)
  2670.                     ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  2671.                 if (!$EmployeeAttendance)
  2672.                     $EmployeeAttendance = new EmployeeAttendance;
  2673.                 $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  2674.                 if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  2675.                     if ($empId == 24)
  2676.                         $workPlaceType '_HYBRID_';
  2677.                     else
  2678.                         $workPlaceType '_STATIC_';
  2679.                 }
  2680.                 if (!isset($dataByAttId[$attendanceInfo->getId()]))
  2681.                     $dataByAttId[$attendanceInfo->getId()] = array(
  2682.                         'attendanceInfo' => $attendanceInfo,
  2683.                         'empId' => $empId,
  2684.                         'lat' => 0,
  2685.                         'lng' => 0,
  2686.                         'address' => 0,
  2687.                         'sysUserId' => $sysUserId,
  2688.                         'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  2689.                         'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  2690.                         'positionArray' => []
  2691.                     );
  2692.                 $posData = array(
  2693.                     'ts' => $dtTs,
  2694.                     'lat' => $d['lat'],
  2695.                     'lng' => $d['lng'],
  2696.                     'marker' => $d['markerId'],
  2697.                     'src' => 2,
  2698.                 );
  2699.                 $posDataArray = array(
  2700.                     $dtTs,
  2701.                     $d['lat'],
  2702.                     $d['lng'],
  2703.                     $d['markerId'],
  2704.                     2
  2705.                 );
  2706.                 $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  2707.                 //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  2708.                 $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  2709.                 $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  2710.                 $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  2711.                 $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  2712.                 if (isset($d['address']))
  2713.                     $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  2714. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  2715.             }
  2716.             $response = array(
  2717.                 'success' => true,
  2718.             );
  2719.             foreach ($dataByAttId as $attInfoId => $d) {
  2720.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  2721.                     $d['empId'],
  2722.                     $d['sysUserId'],
  2723.                     $d['companyId'],
  2724.                     $d['appId'],
  2725.                     $data,
  2726.                     $d['attendanceInfo'],
  2727.                     $options,
  2728.                     $d['positionArray'],
  2729.                     $d['lat'],
  2730.                     $d['lng'],
  2731.                     $d['address'],
  2732.                     $d['markerId']
  2733.                 );
  2734.             }
  2735.             if ($data->request->get('requestFromMobile')) {
  2736.                 $today = new \DateTime(date('y-m-d'));
  2737.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  2738.                 $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$empId$today);
  2739.                 return new JsonResponse(array(
  2740.                     'success' => $response['success'] == true true false,
  2741.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2742.                     'workPlaceType' => $workPlaceType,
  2743.                     'data' => $ActivitiesTemplate
  2744.                 ));
  2745.             }
  2746.             return new JsonResponse(
  2747.                 array(
  2748.                     'success' => true,
  2749.                     'msg' => 'Employee activities successfully updated.',
  2750.                     'workPlaceType' => $workPlaceType,
  2751.                 )
  2752.             );
  2753.         } else if ($data->get('autoAttendance')) {
  2754.             if ($data->request->get('requestFromMobile')) {
  2755.                 $empId $data->request->get('employeeId');
  2756.                 $userId $data->request->get('userId'0);
  2757.             } else {
  2758.                 $empId $data->request->get('employeeId'0);
  2759.                 $userId $data->request->get('userId'$data->request->get('id'0));
  2760.             }
  2761.             $dtTs $data->request->get('timeTs'0);
  2762.             $timeZoneStr '+0000';
  2763.             if ($dtTs == 0) {
  2764.                 $currTsTime = new \DateTime();
  2765.                 $dtTs $currTsTime->format('U');
  2766.             } else {
  2767.                 $currTsTime = new \DateTime('@' $dtTs);
  2768.             }
  2769.             $today = new \DateTime(date('y-m-d'));
  2770.             $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2771.             $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2772.             $appId $data->getSession()->get(UserConstants::USER_APP_ID);
  2773.             $geofenceContext = array(
  2774.                 'lat' => $data->request->get('lat'),
  2775.                 'lng' => $data->request->get('lng'),
  2776.                 'accuracy' => $data->request->get('accuracy'),
  2777.                 'locationAccuracy' => $data->request->get('locationAccuracy'),
  2778.                 'gpsAccuracy' => $data->request->get('gpsAccuracy'),
  2779.                 'isMockLocation' => $data->request->get('isMockLocation'),
  2780.                 'mock_location' => $data->request->get('mock_location'),
  2781.                 'isRemoteWork' => $data->request->get('isRemoteWork'),
  2782.                 'remote_work' => $data->request->get('remote_work'),
  2783.             );
  2784.             $response MiscActions::autoAttendanceGeneral($this->getDoctrine()->getManager(), $empId$userId$appId$dtTs$options$data->request->get('requestFromMobile'), HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED$geofenceContext);
  2785.             if ($data->request->get('requestFromMobile')) {
  2786.                 return new JsonResponse(array(
  2787.                     'success' => $response['success'] == true true false,
  2788.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2789.                 ));
  2790.             }
  2791.             return new JsonResponse(
  2792.                 array(
  2793.                     'success' => true,
  2794.                     'dtTs' => $dtTs,
  2795.                     'attDate' => $attDate->format(DATE_RFC822),
  2796.                     'currTsTime' => $currTsTime->format(DATE_RFC822),
  2797.                     'msg' => 'Employee activities successfully updated.',
  2798.                 )
  2799.             );
  2800.         } else {
  2801.             if ($data->get('manualAttendance')) {
  2802.                 return $this->render(
  2803.                     '@Application/pages/human_resource/input_forms/manual_attendance.html.twig',
  2804.                     array(
  2805.                         'page_title' => 'Manual Attendance',
  2806.                         'workPolicy' => $workHourPolicy,
  2807. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  2808. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  2809. //                        'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
  2810.                     )
  2811.                 );
  2812.             }
  2813.             // Show all matching employee list during ajax request
  2814.             // Show current location according to id
  2815.             if ($data->get('getCurrLocById')) {
  2816.                 $Id $data->get("id");
  2817.                 $options = array(
  2818.                     'employeeId' => $Id,
  2819.                     'entityDbaseName' => 'work_hour_policy',
  2820.                     'entityDbaseIdField' => 'id',
  2821.                     'entityDbaseEmployeeIdsField' => 'employeeIds',
  2822.                     'entityDesignationIdsField' => 'designationIds',
  2823.                     'entityDepartmentIdsField' => 'departmentIds',
  2824.                     'entityEmployeeTypeIdsField' => 'employee_types',
  2825.                     'limit' => 1,
  2826.                     'single' => 1,
  2827.                 );
  2828.                 $workHourPolicyData HumanResource::getApplicableSettingsDataForEmployee($em$options);
  2829.                 $today = new \DateTime(date('y-m-d'));
  2830.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  2831.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  2832.                 return new JsonResponse(["success" => true"workHourPolicyData" => $workHourPolicyData"template" => $ActivitiesTemplate]);
  2833.             }
  2834.         }
  2835.     }
  2836.     public function AttendanceForAppAction(Request $data$remoteVerify 0)
  2837.     {
  2838.         $em $this->getDoctrine()->getManager();
  2839.         $em_goc $this->getDoctrine()->getManager('company_group');
  2840.         $session $data->getSession();
  2841.         $token $session->get(UserConstants::USER_TOKEN);
  2842.         $providedToken $data->headers->get('auth-token');
  2843.         if (empty($providedToken) || $providedToken !== $token) {
  2844.             return new JsonResponse([
  2845.                 'status' => 'error',
  2846.                 'message' => 'Token not match or missing',
  2847.             ], 401);
  2848.         }
  2849.         $workHourPolicy $em->getRepository('ApplicationBundle\\Entity\\WorkHourPolicy')->findAll();
  2850.         $options = array(
  2851.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2852.             'notification_server' => $this->container->getParameter('notification_server'),
  2853.         );
  2854.         if ($data->get('DataTable')) {
  2855.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  2856.             return new JsonResponse($response);
  2857.         }
  2858.         if ($data->request->get('getAttendanceStatus')) {
  2859.             $response HumanResource::getAttendanceStatus($em$data);
  2860.             return new JsonResponse($response);
  2861.         }
  2862. //        if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
  2863. //            return $this->redirectToRoute('permission_denied_page');
  2864.         // Auto attendance
  2865.         if ($data->get('autoAttendance') && $data->request->has('position_array')) {
  2866. //            $empId = $data->query->get('id');
  2867.             $empId $data->request->get('id'$session->get(UserConstants::USER_EMPLOYEE_ID));
  2868.             $positionsArray $data->request->get('position_array', []);
  2869.             if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  2870.             if ($positionsArray == null$positionsArray = [];
  2871.             $dataByAttId = [];
  2872.             $workPlaceType '_UNSET_';
  2873.             foreach ($positionsArray as $d) {
  2874.                 $sysUserId 0;
  2875.                 $userId 0;
  2876.                 $empId 0;
  2877.                 $dtTs 0;
  2878.                 $timeZoneStr '+0000';
  2879. //                $timeZoneStr = '+0600';
  2880.                 $token '_unset_';
  2881.                 if (isset($d['token'])) $token $d['token'];
  2882.                 if (isset($d['employeeId'])) $empId $d['employeeId'];
  2883.                 if (isset($d['userId'])) $userId $d['userId'];
  2884.                 if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  2885.                 if (isset($d['tsMilSec'])) {
  2886.                     $dtTs ceil(($d['tsMilSec']) / 1000);
  2887.                 }
  2888.                 if ($token != '_unset_') {
  2889.                     $sessionData MiscActions::GetSessionDataFromToken($em_goc$token)['sessionData'];
  2890.                     if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
  2891.                         $empId $sessionData[UserConstants::USER_EMPLOYEE_ID];
  2892.                 }
  2893.                 if ($sysUserId == 0)
  2894.                     $sysUserId $userId;
  2895.                 if ($sysUserId == 0)
  2896.                     $sysUserId $em->getRepository(Employee::class)
  2897.                         ->findOneBy(['employeeId' => $empId])->getUserId();
  2898.                 if ($dtTs == 0) {
  2899.                     $currTsTime = new \DateTime();
  2900.                     $dtTs $currTsTime->format('U');
  2901.                 } else {
  2902.                     $currTsTime = new \DateTime('@' $dtTs);
  2903.                 }
  2904.                 $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2905.                 $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2906.                 $EmployeeAttendance $this->getDoctrine()
  2907.                     ->getRepository(EmployeeAttendance::class)
  2908.                     ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  2909.                 if (!$EmployeeAttendance)
  2910.                     $EmployeeAttendance = new EmployeeAttendance;
  2911.                 $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  2912.                 if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  2913.                     if ($empId == 24)
  2914.                         $workPlaceType '_HYBRID_';
  2915.                     else
  2916.                         $workPlaceType '_STATIC_';
  2917.                 }
  2918.                 if (!isset($dataByAttId[$attendanceInfo->getId()]))
  2919.                     $dataByAttId[$attendanceInfo->getId()] = array(
  2920.                         'attendanceInfo' => $attendanceInfo,
  2921.                         'empId' => $empId,
  2922.                         'lat' => 0,
  2923.                         'lng' => 0,
  2924.                         'address' => 0,
  2925.                         'sysUserId' => $sysUserId,
  2926.                         'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  2927.                         'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  2928.                         'positionArray' => []
  2929.                     );
  2930.                 $posData = array(
  2931.                     'ts' => $dtTs,
  2932.                     'lat' => $d['lat'],
  2933.                     'lng' => $d['lng'],
  2934.                     'marker' => $d['markerId'],
  2935.                     'src' => 2,
  2936.                 );
  2937.                 $posDataArray = array(
  2938.                     $dtTs,
  2939.                     $d['lat'],
  2940.                     $d['lng'],
  2941.                     $d['markerId'],
  2942.                     2
  2943.                 );
  2944.                 $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  2945.                 //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  2946.                 $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  2947.                 $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  2948.                 $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  2949.                 $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  2950.                 if (isset($d['address']))
  2951.                     $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  2952. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  2953.             }
  2954.             $response = array(
  2955.                 'success' => true,
  2956.             );
  2957.             foreach ($dataByAttId as $attInfoId => $d) {
  2958.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  2959.                     $d['empId'],
  2960.                     $d['sysUserId'],
  2961.                     $d['companyId'],
  2962.                     $d['appId'],
  2963.                     $data,
  2964.                     $d['attendanceInfo'],
  2965.                     $options,
  2966.                     $d['positionArray'],
  2967.                     $d['lat'],
  2968.                     $d['lng'],
  2969.                     $d['address'],
  2970.                     $d['markerId']
  2971.                 );
  2972.             }
  2973.             if ($data->request->get('requestFromMobile')) {
  2974.                 $today = new \DateTime(date('y-m-d'));
  2975.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  2976.                 $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$empId$today);
  2977.                 return new JsonResponse(array(
  2978.                     'success' => $response['success'] == true true false,
  2979.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2980.                     'workPlaceType' => $workPlaceType,
  2981.                     'data' => $ActivitiesTemplate
  2982.                 ));
  2983.             }
  2984.             return new JsonResponse(
  2985.                 array(
  2986.                     'success' => true,
  2987.                     'msg' => 'Employee activities successfully updated.',
  2988.                     'workPlaceType' => $workPlaceType,
  2989.                 )
  2990.             );
  2991.         } else if ($data->get('autoAttendance')) {
  2992.             $sysUserId 0;
  2993.             $userId 0;
  2994.             $empId 0;
  2995.             $dtTs 0;
  2996. //            $timeZoneStr = '+0600';
  2997.             $timeZoneStr '+0000';
  2998.             if ($data->request->get('requestFromMobile')) {
  2999.                 $empId $data->request->get('employeeId');
  3000.                 $userId $data->request->get('userId'0);
  3001.                 $sysUserId $data->request->get('id'0);
  3002. //        $empId = $em->getRepository(Employee::class)
  3003. //            ->findOneBy(['userId' => $userId])->getEmployeeId();
  3004.             } else {
  3005.                 $empId $data->request->get('employeeId'0);
  3006.                 $sysUserId $data->request->get('userId'0);
  3007.             }
  3008.             $dtTs $data->request->get('timeTs'0);
  3009.             if ($sysUserId == 0)
  3010.                 $sysUserId $userId;
  3011.             if ($sysUserId == 0)
  3012.                 $sysUserId $em->getRepository(Employee::class)
  3013.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3014.             if ($dtTs == 0) {
  3015.                 $currTsTime = new \DateTime();
  3016.                 $dtTs $currTsTime->format('U');
  3017.             } else {
  3018.                 $currTsTime = new \DateTime('@' $dtTs);
  3019.             }
  3020.             if ($sysUserId == 0)
  3021.                 $sysUserId $userId;
  3022.             if ($sysUserId == 0)
  3023.                 $sysUserId $em->getRepository(Employee::class)
  3024.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3025.             $today = new \DateTime(date('y-m-d'));
  3026.             $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  3027.             $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  3028.             $EmployeeAttendance $this->getDoctrine()
  3029.                 ->getRepository(EmployeeAttendance::class)
  3030.                 ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  3031.             if (!$EmployeeAttendance)
  3032.                 $EmployeeAttendance = new EmployeeAttendance;
  3033. //            return new JsonResponse(["success" => true, "data" => $ActivitiesTemplate]);
  3034. //            $attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $customTime);
  3035.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStrHumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED);
  3036.             if (!isset($dataByAttId[$attendanceInfo->getId()]))
  3037.                 $dataByAttId[$attendanceInfo->getId()] = array(
  3038.                     'attendanceInfo' => $attendanceInfo,
  3039.                     'empId' => $empId,
  3040.                     'lat' => 0,
  3041.                     'lng' => 0,
  3042.                     'address' => 0,
  3043.                     'sysUserId' => $sysUserId,
  3044.                     'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3045.                     'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  3046.                     'positionArray' => []
  3047.                 );
  3048.             $posData = array(
  3049.                 'ts' => $dtTs,
  3050.                 'lat' => 0,
  3051.                 'lng' => 0,
  3052.                 'marker' => HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  3053.                 'src' => 1,
  3054.             );
  3055.             $posDataArray = array(
  3056.                 $dtTs,
  3057.                 0,
  3058.                 0,
  3059.                 HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  3060.                 1
  3061.             );
  3062.             $dataByAttId[$attendanceInfo->getId()]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED;
  3063.             //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  3064.             $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  3065.             $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  3066.             $dataByAttId[$attendanceInfo->getId()]['lat'] = 0;  //for last lat lng etc
  3067.             $dataByAttId[$attendanceInfo->getId()]['lng'] = 0;  //for last lat lng etc
  3068.             if (isset($d['address']))
  3069.                 $dataByAttId[$attendanceInfo->getId()]['address'] = '';  //for last lat lng etc
  3070.             $response = array(
  3071.                 'success' => true
  3072.             );
  3073.             foreach ($dataByAttId as $attInfoId => $d) {
  3074.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  3075.                     $d['empId'],
  3076.                     $d['sysUserId'],
  3077.                     $d['companyId'],
  3078.                     $d['appId'],
  3079.                     $data,
  3080.                     $d['attendanceInfo'],
  3081.                     $options,
  3082.                     $d['positionArray'],
  3083.                     $d['lat'],
  3084.                     $d['lng'],
  3085.                     $d['address'],
  3086.                     $d['markerId']
  3087.                 );
  3088.             }
  3089.             if ($data->request->get('requestFromMobile')) {
  3090.                 return new JsonResponse(array(
  3091.                     'success' => $response['success'] == true true false,
  3092.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  3093.                 ));
  3094.             }
  3095.             return new JsonResponse(
  3096.                 array(
  3097.                     'success' => true,
  3098.                     'dtTs' => $dtTs,
  3099.                     'attDate' => $attDate->format(DATE_RFC822),
  3100.                     'currTsTime' => $currTsTime->format(DATE_RFC822),
  3101.                     'msg' => 'Employee activities successfully updated.',
  3102.                 )
  3103.             );
  3104. //
  3105. //
  3106. //            $response = HumanResource::setAttendanceLog($em, $empId, $sysUserId,
  3107. //                $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3108. //                $data->getSession()->get(UserConstants::USER_APP_ID),
  3109. //                $data, $attendanceInfo, $options);
  3110. //
  3111. //            if ($data->request->get('requestFromMobile')) {
  3112. //                return new JsonResponse($response);
  3113. //            }
  3114. //
  3115. //            return new JsonResponse(
  3116. //                array(
  3117. //                    'success' => true,
  3118. //                    'msg' => 'Employee activities successfully updated.'
  3119. //                )
  3120. //            );
  3121.             // }
  3122.             // else {
  3123.             //   return new JsonResponse(
  3124.             //     array(
  3125.             //       'success' => false,
  3126.             //       'msg' => "Invalid employee ID"
  3127.             //     )
  3128.             //   );
  3129.             // }
  3130.         } else {
  3131.             if ($data->get('manualAttendance')) {
  3132.                 return $this->render(
  3133.                     '@Application/pages/human_resource/input_forms/manual_attendance.html.twig',
  3134.                     array(
  3135.                         'page_title' => 'Manual Attendance',
  3136.                         'workPolicy' => $workHourPolicy,
  3137. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3138. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3139. //                        'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
  3140.                     )
  3141.                 );
  3142.             }
  3143.             // Show all matching employee list during ajax request
  3144.             // Show current location according to id
  3145.             if ($data->get('getCurrLocById')) {
  3146.                 $Id $data->get("id");
  3147.                 $options = array(
  3148.                     'employeeId' => $Id,
  3149.                     'entityDbaseName' => 'work_hour_policy',
  3150.                     'entityDbaseIdField' => 'id',
  3151.                     'entityDbaseEmployeeIdsField' => 'employeeIds',
  3152.                     'entityDesignationIdsField' => 'designationIds',
  3153.                     'entityDepartmentIdsField' => 'departmentIds',
  3154.                     'entityEmployeeTypeIdsField' => 'employee_types',
  3155.                     'limit' => 1,
  3156.                     'single' => 1,
  3157.                 );
  3158.                 $workHourPolicyData HumanResource::getApplicableSettingsDataForEmployee($em$options);
  3159.                 $today = new \DateTime(date('y-m-d'));
  3160.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3161.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3162.                 return new JsonResponse(["success" => true"workHourPolicyData" => $workHourPolicyData"template" => $ActivitiesTemplate]);
  3163.             }
  3164.         }
  3165.     }
  3166.     public function getCurrentStatusAction($id)
  3167.     {
  3168.         $today = new \DateTime(date('y-m-d'));
  3169.         $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3170.         $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$id$today);
  3171.         return new JsonResponse(["success" => true"data" => $ActivitiesTemplate]);
  3172.     }
  3173.     public function CurrentAttendanceAction(Request $data)
  3174.     {
  3175.         $em $this->getDoctrine()->getManager();
  3176.         $options = array(
  3177.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3178.             'notification_server' => $this->container->getParameter('notification_server'),
  3179.         );
  3180.         if ($data->get('DataTable')) {
  3181.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  3182.             return new JsonResponse($response);
  3183.         }
  3184.         if ($data->request->get('getAttendanceStatus')) {
  3185.             $response HumanResource::getAttendanceStatus($em$data);
  3186.             return new JsonResponse($response);
  3187.         }
  3188.         // Auto attendance
  3189.         if ($data->get('autoAttendance')) {
  3190.             $empId $data->query->get('id');
  3191.             $sysUserId 0;
  3192.             if ($data->get('requestFromMobile')) {
  3193.                 $sysUserId $data->request->get('id');
  3194.                 $empId $em->getRepository(Employee::class)
  3195.                     ->findOneBy(['userId' => $sysUserId])->getEmployeeId();
  3196.             } else {
  3197.                 $sysUserId $em->getRepository(Employee::class)
  3198.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3199.             }
  3200.             $customTime $data->get('time');
  3201.             $today = new \DateTime(date('y-m-d'));
  3202.             $EmployeeAttendance $this->getDoctrine()
  3203.                 ->getRepository(EmployeeAttendance::class)
  3204.                 ->findOneBy(array('employeeId' => $empId'date' => $today));
  3205.             if (!$EmployeeAttendance)
  3206.                 $EmployeeAttendance = new EmployeeAttendance;
  3207.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$customTime);
  3208.             $response HumanResource::setAttendanceLog($em$empId$sysUserId,
  3209.                 $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3210.                 $data->getSession()->get(UserConstants::USER_APP_ID),
  3211.                 $data$attendanceInfo$options);
  3212.             if ($data->get('requestFromMobile')) {
  3213.                 return new JsonResponse([$response]);
  3214.             }
  3215.             return new JsonResponse(
  3216.                 array(
  3217.                     'success' => true,
  3218.                     'msg' => 'Employee activities successfully updated.'
  3219.                 )
  3220.             );
  3221.             // }
  3222.             // else {
  3223.             //   return new JsonResponse(
  3224.             //     array(
  3225.             //       'success' => false,
  3226.             //       'msg' => "Invalid employee ID"
  3227.             //     )
  3228.             //   );
  3229.             // }
  3230.         } else {
  3231.             if ($data->get('manualAttendance')) {
  3232.                 return $this->render(
  3233.                     '@Application/pages/human_resource/report/current_attendance.html.twig',
  3234.                     array(
  3235.                         'page_title' => 'Current Attendance Status',
  3236.                     )
  3237.                 );
  3238.             }
  3239.             // Show all matching employee list during ajax request
  3240.             // Show current location according to id
  3241.             if ($data->get('getCurrLocById')) {
  3242.                 $Id $data->get("id");
  3243.                 $today = new \DateTime(date('y-m-d'));
  3244.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3245.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3246.                 return new JsonResponse(["success" => true"template" => $ActivitiesTemplate]);
  3247.             }
  3248.         }
  3249.     }
  3250.     public function EmployeeLeaveAction(Request $data$id 0)
  3251.     {
  3252.         $em $this->getDoctrine()->getManager();
  3253.         $request $data;
  3254.         if (!$id) {
  3255.             if ($data->isMethod('GET')) {
  3256.                 $EmpID $data->query->get('id');
  3257.                 $LeaveType $data->query->get('leaveType');
  3258.                 if ($data->query->has('id') && $data->query->has('leaveType')) {
  3259.                     $response HumanResource::HandelAjaxRequestForLeaveApp($em$EmpID$LeaveType);
  3260.                     return new JsonResponse($response);
  3261.                 }
  3262.                 if ($data->query->has('id')) {
  3263.                     $Response HumanResource::HandelAjaxRequestForLeaveApp($em$EmpID);
  3264.                     return new JsonResponse($Response);
  3265.                 }
  3266.                 $TemplateData HumanResource::TwigDataForLeaveApp($emFalse);
  3267.                 return $this->render(
  3268.                     '@Application/pages/human_resource/input_forms/employee_leave.html.twig',
  3269.                     array(
  3270.                         'page_title' => $TemplateData['Title'],
  3271.                         'EmployeeList' => $TemplateData['EmployeeList'],
  3272.                         'DesignationList' => $TemplateData['DesignationList'],
  3273.                         'HasUpdateMode' => false
  3274.                     )
  3275.                 );
  3276.             } else {
  3277.                 $CompanyId $this->getLoggedUserCompanyId($data);
  3278.                 $attachmentValidationError $this->validateLeaveAttachmentFiles($request->files);
  3279.                 if ($attachmentValidationError !== null) {
  3280.                     $this->addFlash('error'$attachmentValidationError);
  3281.                     if ($data->request->has('returnJson')) {
  3282.                         return new JsonResponse(array(
  3283.                             'success' => false,
  3284.                             'errorStr' => $attachmentValidationError,
  3285.                         ));
  3286.                     } else {
  3287.                         return $this->redirectToRoute('employee_leave');
  3288.                     }
  3289.                 }
  3290.                 $Response HumanResource::StoreDataForLeaveApplication($em$id$datafalse$CompanyId);
  3291.                 if ($Response['HasErr']) {
  3292.                     $this->addFlash('error'$Response['msg']);
  3293.                     if ($data->request->has('returnJson')) {
  3294.                         return new JsonResponse(array(
  3295.                             'success' => false,
  3296.                             'errorStr' => $Response['msg'],
  3297.                         ));
  3298.                     } else {
  3299.                         return $this->redirectToRoute('employee_leave');
  3300.                     }
  3301.                 }
  3302.                 $applicationId $Response['applicationId'];
  3303.                 $em_goc $this->getDoctrine()->getManager('company_group');
  3304.                 $file_path_list = [];
  3305.                 if ($applicationId != 0) {
  3306.                     if (!empty($request->files)) {
  3307.                         MiscActions::RemoveFilesForEntityDoc($em_goc'EmployeeLeaveApplication'$applicationId);
  3308.                         $storePath 'uploads/LeaveDoc/';
  3309.                         $path "";
  3310.                         $file_path "";
  3311.                         $session $request->getSession();
  3312.                         MiscActions::RemoveExpiredFiles($em_goc);
  3313.                         foreach ($this->getLeaveUploadedFiles($request->files) as $uploadedFile) {
  3314.                             //            if($uploadedFile->getImage())
  3315.                             //                var_dump($uploadedFile->getFile());
  3316.                             //                var_dump($uploadedFile);
  3317.                             if ($uploadedFile != null) {
  3318.                                 $extension $this->getLeaveAttachmentExtension($uploadedFile);
  3319.                                 $size $uploadedFile->getSize();
  3320.                                 $fileName 'LDOC_' $applicationId '_' . (md5(uniqid())) . '.' $extension;
  3321.                                 $path $fileName;
  3322.                                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  3323.                                 if (!file_exists($upl_dir)) {
  3324.                                     mkdir($upl_dir0777true);
  3325.                                 }
  3326.                                 if (file_exists($upl_dir '' $path)) {
  3327.                                     chmod($upl_dir '' $path0755);
  3328.                                     unlink($upl_dir '' $path);
  3329.                                 }
  3330.                                 $file $uploadedFile->move($upl_dir$path);
  3331.                                 $expireNever 1;
  3332.                                 $expireTs 0;
  3333.                                 $EntityFile = new EntityFile();
  3334.                                 $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  3335.                                 $EntityFile->setName($path);
  3336.                                 $EntityFile->setMarker('_GEN_');
  3337.                                 $EntityFile->setExtension($extension);
  3338.                                 $EntityFile->setExpireTs($expireTs);
  3339.                                 $EntityFile->setSize($size);
  3340.                                 $EntityFile->setRelativePath($storePath $path);
  3341.                                 $EntityFile->setEntityName('EmployeeLeaveApplication');
  3342.                                 $EntityFile->setEntityBundle('EmployeeLeaveApplication');
  3343.                                 $EntityFile->setEntityId($applicationId);
  3344.                                 $EntityFile->setEntityIdField('employeeLeaveApplicationId');
  3345.                                 $EntityFile->setModifyFieldSetter('setFiles');
  3346.                                 $EntityFile->setDocIdForApplicant(0);
  3347.                                 $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  3348.                                 $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  3349.                                 $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  3350.                                 $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  3351.                                 $em_goc->persist($EntityFile);
  3352.                                 $em_goc->flush();
  3353.                                 $EntityFileId $EntityFile->getId();
  3354.                             }
  3355.                             if ($path != "")
  3356.                                 $file_path_list[] = ($storePath $path);
  3357.                         }
  3358.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  3359.                         $v $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')->findOneBy(array(
  3360.                             'employeeLeaveApplicationId' => $applicationId,
  3361.                         ));
  3362.                         if ($v) {
  3363.                             $v->setFiles(implode(','$file_path_list));
  3364.                             $em->flush();
  3365.                         } else {
  3366.                         }
  3367.                     }
  3368.                 }
  3369.                 // $this->addFlash('success', 'Application submitted successfully!');
  3370.                 // return $this->redirectToRoute('leave_application_list');
  3371.                 if ($data->request->has('returnJson')) {
  3372.                     return new JsonResponse(array(
  3373.                         'success' => true,
  3374.                     ));
  3375.                 } else {
  3376.                     return $this->redirectToRoute('view_employee_leave_application', array('id' => $applicationId));
  3377.                 }
  3378.             }
  3379.         } else {
  3380.             if ($data->isMethod('GET')) {
  3381.                 $ApplicationRepo $em->getRepository(EmployeeLeaveApplication::class);
  3382.                 $OldData $ApplicationRepo->find(array('employeeLeaveApplicationId' => $id));
  3383.                 $TemplateData HumanResource::TwigDataForLeaveApp($em$OldData);
  3384.                 return $this->render(
  3385.                     '@Application/pages/human_resource/input_forms/employee_leave.html.twig',
  3386.                     array(
  3387.                         'page_title' => $TemplateData['Title'],
  3388.                         'EmployeeList' => $TemplateData['EmployeeList'],
  3389.                         'DesignationList' => $TemplateData['DesignationList'],
  3390.                         'OldData' => $TemplateData['OldData'],
  3391.                         'AvailableLeave' => $TemplateData['AvailableLeave'],
  3392.                         'HasUpdateMode' => true
  3393.                     )
  3394.                 );
  3395.             } else {
  3396.                 $CompanyId $this->getLoggedUserCompanyId($data);
  3397.                 $attachmentValidationError $this->validateLeaveAttachmentFiles($data->files);
  3398.                 if ($attachmentValidationError !== null) {
  3399.                     $this->addFlash('error'$attachmentValidationError);
  3400.                     return $this->redirectToRoute('employee_leave');
  3401.                 }
  3402.                 $Response HumanResource::StoreDataForLeaveApplication($em$id$datatrue$CompanyId);
  3403.                 if ($Response['HasErr']) {
  3404.                     $this->addFlash('error'$Response['msg']);
  3405.                     return $this->redirectToRoute('employee_leave');
  3406.                 }
  3407.                 $this->addFlash('success'"Application updated successfully!");
  3408.                 return $this->redirectToRoute('leave_application_list');
  3409.             }
  3410.         }
  3411.     }
  3412.     public function ViewLeaveApplicationAction(Request $request$id)
  3413.     {
  3414.         $em $this->getDoctrine()->getManager();
  3415.         if ($id) {
  3416.             $TwigData HumanResource::TwigDataForViewLeaveApplication($em$request$id);
  3417.             if ($TwigData['HasErr']) {
  3418.                 return new JsonResponse(array(
  3419.                     'success' => false,
  3420.                     'msg' => $TwigData['Msg']
  3421.                 ));
  3422.             }
  3423.             return $this->render(
  3424.                 '@Application/pages/human_resource/views/leave_application_view.html.twig',
  3425.                 array(
  3426.                     'page_title' => 'View Leave Application',
  3427.                     'Applicant' => $TwigData['Applicant'],
  3428.                     'Application' => $TwigData['Application'],
  3429.                     'LeaveType' => $TwigData['LeaveType'],
  3430.                     'LeaveCategory' => $TwigData['LeaveCategory'],
  3431.                     'leaveDataArray' => $TwigData['leaveDataArray'],
  3432.                     'FrwdEmp' => $TwigData['FrwdEmp'],
  3433.                     'ApplicantDesg' => $TwigData['ApplicantDesg'],
  3434.                     'approval_status' => $TwigData['approval_status'],
  3435.                     'approval_data' => $TwigData['approval_data'],
  3436.                     'document_log' => $TwigData['document_log'],
  3437.                     'auto_created' => 0,
  3438.                 )
  3439.             );
  3440.         }
  3441.         return new JsonResponse(array(
  3442.             'success' => false,
  3443.             'msg' => 'Wrong URL format! Please try with application ID'
  3444.         ));
  3445.     }
  3446.     public function PrintLeaveApplicationAction(Request $request$id)
  3447.     {
  3448.         if ($id) {
  3449.             $em $this->getDoctrine()->getManager();
  3450.             $company_data Company::getCompanyData($em1);
  3451.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['EmployeeLeaveApplication'], $id);
  3452.             $TwigData HumanResource::TwigDataForViewLeaveApplication($em$request$id);
  3453.             if ($TwigData['HasErr']) {
  3454.                 return new JsonResponse(array(
  3455.                     'success' => false,
  3456.                     'msg' => $TwigData['Msg']
  3457.                 ));
  3458.             }
  3459.             $ApplicationCategory $TwigData['Application']->getLeaveCategory();
  3460.             $ApplicationType = ($ApplicationCategory != && $ApplicationCategory != 2) ? $TwigData['LeaveType'] : '';
  3461.             return $this->render(
  3462.                 '@Application/pages/human_resource/print/leave_application_print.html.twig',
  3463.                 array(
  3464.                     'page_title' => 'Print Leave Application',
  3465.                     'export' => 'pdf,print',
  3466.                     'company_name' => $company_data->getName(),
  3467.                     'company_data' => $company_data,
  3468.                     'company_address' => $company_data->getAddress(),
  3469.                     'company_image' => $company_data->getImage(),
  3470.                     'Authorizations' => $Authorizations,
  3471.                     'ApplicationType' => $ApplicationType,
  3472.                     'ApplicationCategory' => $ApplicationCategory,
  3473.                     'Applicant' => $TwigData['Applicant'],
  3474.                     'Application' => $TwigData['Application'],
  3475.                     'LeaveType' => $TwigData['LeaveType'],
  3476.                     'LeaveCategory' => $TwigData['LeaveCategory'],
  3477.                     'leaveDataArray' => $TwigData['leaveDataArray'],
  3478.                     'FrwdEmp' => $TwigData['FrwdEmp'],
  3479.                     'ApplicantDesg' => $TwigData['ApplicantDesg'],
  3480.                     'approval_status' => $TwigData['approval_status'],
  3481.                     'approval_data' => $TwigData['approval_data'],
  3482.                     'document_log' => $TwigData['document_log'],
  3483.                     'red' => 0,
  3484.                     'invoice_footer' => 0
  3485.                 )
  3486.             );
  3487.         }
  3488.         return new JsonResponse(array(
  3489.             'success' => false,
  3490.             'msg' => 'Wrong URL format! Please try with application ID'
  3491.         ));
  3492.     }
  3493.     public function LeaveApplicationListAction(Request $request)
  3494.     {
  3495.         $em $this->getDoctrine()->getManager();
  3496.         $response HumanResource::GetEmployeeLeaveApplicationList($em$request);
  3497.         if ($request->isMethod('GET')) {
  3498.             return $this->render("@Application/pages/human_resource/list/leave_application_list.html.twig", array(
  3499.                 'page_title' => 'Leave Application List',
  3500.                 'application_data' => $response,
  3501.             ));
  3502.         }
  3503.     }
  3504.     public function PayrollPolicySettingsAction(Request $request$id)
  3505.     {
  3506.         $em $this->getDoctrine()->getManager();
  3507.         $CompanyId $this->getLoggedUserCompanyId($request);
  3508.         if ($id) {
  3509.             if ($request->isMethod('GET')) {
  3510.                 $Row $em->getRepository(PayrollPolicy::class)->find($id);
  3511.                 if (!$Row) {
  3512.                     $this->addFlash('error''Invalid Payroll Policy Id');
  3513.                     return $this->redirectToRoute('payroll_policy_settings');
  3514.                 }
  3515.                 $TwigData HumanResource::GetPayrollPolicyTwigData($em);
  3516.                 $OldData HumanResource::GetPayrollPolicyTwigData($em$id);
  3517.                 return $this->render('@Application/pages/human_resource/input_forms/payroll_policy_settings.html.twig', array(
  3518.                     'page_title' => 'Update Payroll Policy Settings',
  3519.                     'EmployeeIds' => $TwigData['EmployeeIds'],
  3520.                     'EmployeeType' => $TwigData['EmployeeType'],//
  3521.                     'department' => $TwigData['department'],
  3522.                     'Designation' => $TwigData['Designation'],
  3523.                     'WorkingDays' => $TwigData['WorkingDays'],
  3524.                     'OldData' => $OldData['Row'],
  3525.                     'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
  3526.                     'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
  3527.                     'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
  3528.                     'deductionAspects' => HumanResourceConstant::$deductionAspects,
  3529.                     'deductionCondition' => json_decode($Row->getDeductionCondition(), true),
  3530.                     'HasUpdateMode' => true,
  3531.                 ));
  3532.             } else {
  3533.                 $Response HumanResource::StorePayrollPolicyData($em$id$CompanyId$request);
  3534.                 if ($Response['HasErr']) {
  3535.                     $this->addFlash('error'$Response['msg']);
  3536.                     return $this->redirectToRoute('payroll_policy_settings');
  3537.                 }
  3538.                 return $this->redirectToRoute('payroll_policy_settings');
  3539. //        if ($Response['isSuccess']) {
  3540. //          return new JsonResponse(array('success' => true, 'msg' => 'don\'t forget to redirect'));
  3541. //        }
  3542. //        return new JsonResponse(array('success' => false, 'msg' => 'Sorry something went wrong'));
  3543.             }
  3544.         } else {
  3545.             if ($request->isMethod('GET')) {
  3546.                 if ($request->query->get('GetDocHash')) {
  3547.                     $Dochash HumanResource::GenerateDocHashForPayrollSettings($em$request);
  3548.                     return new JsonResponse($Dochash);
  3549.                 }
  3550.                 $TwigData HumanResource::GetPayrollPolicyTwigData($em);
  3551.                 return $this->render(
  3552.                     '@Application/pages/human_resource/input_forms/payroll_policy_settings.html.twig',
  3553.                     array(
  3554.                         'page_title' => 'Create Payroll Policy Settings',
  3555.                         'EmployeeIds' => $TwigData['EmployeeIds'],
  3556.                         'EmployeeType' => $TwigData['EmployeeType'],
  3557.                         'WorkingDays' => $TwigData['WorkingDays'],
  3558.                         'Designation' => $TwigData['Designation'],
  3559.                         'department' => $TwigData['department'],
  3560.                         'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
  3561.                         'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
  3562.                         'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
  3563.                         'deductionAspects' => HumanResourceConstant::$deductionAspects,
  3564.                         'HasUpdateMode' => false
  3565.                     )
  3566.                 );
  3567.             } else {
  3568.                 $Response HumanResource::StorePayrollPolicyData($em$id$CompanyId$request);
  3569.                 if ($Response['HasErr']) {
  3570.                     $this->addFlash('error'$Response['msg']);
  3571.                     return $this->redirectToRoute('payroll_policy_settings');
  3572.                 }
  3573.                 return $this->redirectToRoute('payroll_policy_settings');
  3574. //        return new JsonResponse(array("success" => true, 'msg' => 'Dont forget to redirect!'));
  3575.             }
  3576.         }
  3577.     }
  3578.     public function AttendanceReportAction(Request $request$apiKey 'impose')
  3579.     {
  3580.         $em $this->getDoctrine()->getManager();
  3581.         $attendanceSource HumanResourceConstant::$attendanceSources;
  3582.         $routeName $request->attributes->get('_route');
  3583.         if ($routeName == 'app_get_attendendance_data') {
  3584.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->get('considerCurrTsIfNoOut'1));
  3585.             $newReports = [];
  3586.             foreach ($ReportData['Reports'] as $gg) {
  3587.                 foreach ($gg as $d) {
  3588.                     $newReports[] = $d;
  3589. //                if(!isset($newReports[$d['id']]))
  3590. //                    $newReports[$d['id']]=array();
  3591. //                    $newReports[$d['id']][]=$d;
  3592.                 }
  3593.             }
  3594.             return new JsonResponse (array(
  3595.                 'attendanceSource' => $attendanceSource,
  3596. //                'Reports' => $ReportData['Reports'],
  3597.                 'Reports' => $newReports,
  3598.                 'from_date' => $ReportData['from_date'],
  3599.                 'to_date' => $ReportData['to_date'],
  3600.                 'report_for' => $ReportData['generated_for'],
  3601.                 'attendance' => $ReportData['attendance'],
  3602.             ));
  3603.         } else {
  3604.             $EmployeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  3605.             $Departments $em->getRepository(SysDepartment::class)->findAll();
  3606.             if ($request->isMethod('GET')) {
  3607.                 return $this->render('@Application/pages/human_resource/report/attendance_report.html.twig', array(
  3608.                     'page_title' => 'Attendance Report',
  3609.                     'employes' => $EmployeeIds,
  3610.                     'departments' => $Departments,
  3611.                     'isMethodGet' => true,
  3612.                     'from_date' => '',
  3613.                     'to_date' => '',
  3614.                     'report_for' => '',
  3615.                     'attendance' => [],
  3616.                     'Reports' => [],
  3617.                     'qry' => ''
  3618.                 ));
  3619.             }
  3620.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->request->get('considerCurrTsIfNoOut'0));
  3621.             if ($request->request->get('returnJson'0) == 1) {
  3622.                 return new JsonResponse($ReportData);
  3623.             }
  3624.             $Qry "start_date=" $ReportData['from_date'] . '&' "end_date=" $ReportData['to_date'] . '&' "period_type=" $ReportData['period_type'] . '&' "show_all=" $ReportData['show_all'] . '&' "department=" $request->get('department') . '&' "employes=" implode(',', ($request->get('employes') ? $request->get('employes') : []));
  3625.             return $this->render('@Application/pages/human_resource/report/attendance_report.html.twig', array(
  3626.                 'page_title' => 'Attendance Report',
  3627.                 'isMethodGet' => false,
  3628.                 'departments' => $Departments,
  3629.                 'employes' => $EmployeeIds,
  3630.                 'attendanceSource' => $attendanceSource,
  3631.                 'Reports' => $ReportData['Reports'],
  3632.                 'from_date' => $ReportData['from_date'],
  3633.                 'to_date' => $ReportData['to_date'],
  3634.                 'report_for' => $ReportData['generated_for'],
  3635.                 'attendance' => $ReportData['attendance'],
  3636.                 'qry' => $Qry
  3637.             ));
  3638.         }
  3639.     }
  3640.     public function AttendanceCustomReportAction(Request $request$apiKey 'impose')
  3641.     {
  3642.         $em $this->getDoctrine()->getManager();
  3643.         $attendanceSource HumanResourceConstant::$attendanceSources;
  3644.         $routeName $request->attributes->get('_route');
  3645.         if ($routeName == 'app_get_attendendance_data') {
  3646.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->get('considerCurrTsIfNoOut'1));
  3647.             $newReports = [];
  3648.             foreach ($ReportData['Reports'] as $gg) {
  3649.                 foreach ($gg as $d) {
  3650.                     $newReports[] = $d;
  3651. //                if(!isset($newReports[$d['id']]))
  3652. //                    $newReports[$d['id']]=array();
  3653. //                    $newReports[$d['id']][]=$d;
  3654.                 }
  3655.             }
  3656.             return new JsonResponse (array(
  3657.                 'attendanceSource' => $attendanceSource,
  3658. //                'Reports' => $ReportData['Reports'],
  3659.                 'Reports' => $newReports,
  3660.                 'from_date' => $ReportData['from_date'],
  3661.                 'to_date' => $ReportData['to_date'],
  3662.                 'report_for' => $ReportData['generated_for'],
  3663.                 'attendance' => $ReportData['attendance'],
  3664.             ));
  3665.         } else {
  3666.             $EmployeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  3667.             $Departments $em->getRepository(SysDepartment::class)->findAll();
  3668.             if ($request->isMethod('GET')) {
  3669.                 return $this->render('@Application/pages/human_resource/report/custom_attendance_report.html.twig', array(
  3670.                     'page_title' => 'Attendance Report',
  3671.                     'employes' => $EmployeeIds,
  3672.                     'departments' => $Departments,
  3673.                     'isMethodGet' => true,
  3674.                     'from_date' => '',
  3675.                     'to_date' => '',
  3676.                     'report_for' => '',
  3677.                     'attendance' => [],
  3678.                     'Reports' => [],
  3679.                     'qry' => ''
  3680.                 ));
  3681.             }
  3682.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->request->get('considerCurrTsIfNoOut'0));
  3683.             if ($request->request->get('returnJson'0) == 1) {
  3684.                 return new JsonResponse($ReportData);
  3685.             }
  3686.             $Qry "start_date=" $ReportData['from_date'] . '&' "end_date=" $ReportData['to_date'] . '&' "period_type=" $ReportData['period_type'] . '&' "show_all=" $ReportData['show_all'] . '&' "department=" $request->get('department') . '&' "employes=" implode(',', ($request->get('employes') ? $request->get('employes') : []));
  3687.             return $this->render('@Application/pages/human_resource/report/custom_attendance_report.html.twig', array(
  3688.                 'page_title' => 'Attendance Report',
  3689.                 'isMethodGet' => false,
  3690.                 'departments' => $Departments,
  3691.                 'employes' => $EmployeeIds,
  3692.                 'attendanceSource' => $attendanceSource,
  3693.                 'Reports' => $ReportData['Reports'],
  3694.                 'from_date' => $ReportData['from_date'],
  3695.                 'to_date' => $ReportData['to_date'],
  3696.                 'report_for' => $ReportData['generated_for'],
  3697.                 'attendance' => $ReportData['attendance'],
  3698.                 'qry' => $Qry
  3699.             ));
  3700.         }
  3701.     }
  3702.     public function PrintAttendanceReportAction(Request $request)
  3703.     {
  3704.         $em $this->getDoctrine()->getManager();
  3705.         $company_data Company::getCompanyData($em1);
  3706.         $ReportData HumanResource::GenerateAttendanceReport($em$request);
  3707.         return $this->render(
  3708.             '@Application/pages/human_resource/print/print_attendance_report.html.twig',
  3709.             array(
  3710.                 'page_title' => 'Print Attendance Report',
  3711.                 'export' => 'pdf,print',
  3712.                 'company_name' => $company_data->getName(),
  3713.                 'company_data' => $company_data,
  3714.                 'company_address' => $company_data->getAddress(),
  3715.                 'company_image' => $company_data->getImage(),
  3716.                 'Reports' => $ReportData['Reports'],
  3717.                 'from_date' => $ReportData['from_date'],
  3718.                 'to_date' => $ReportData['to_date'],
  3719.                 'report_for' => $ReportData['generated_for'],
  3720.                 'attendance' => $ReportData['attendance'],
  3721.                 'red' => 0
  3722.             )
  3723.         );
  3724.     }
  3725.     public function DisburseSalaryAction(Request $request)
  3726.     {
  3727.         $em $this->getDoctrine()->getManager();
  3728.         $EmployeeIds $em->getRepository(EmployeeDetails::class)->findBy(
  3729.             array(
  3730.                 'emp_status' => 1
  3731.             )
  3732.         );
  3733.         $startDate $request->get('salary_start_date''');
  3734.         $endDate $request->get('salary_till_date''');
  3735.         $filterType $request->get('filterType'1);
  3736.         $filterBranchIds $request->get('branchIds', []);
  3737.         $filterBankIds $request->get('bankIds', []);
  3738.         $filterDepartmentIds $request->get('departmentIds', []);
  3739.         $filterEmployeeIds $request->get('employeeIds', []);
  3740.         $Departments $em->getRepository(SysDepartment::class)->findAll();
  3741.         $attendance $em->getRepository(EmployeeAttendanceLog::class)->findAll();
  3742.         $banks $em->getRepository(BankList::class)->findAll();
  3743.         $branches $em->getRepository(Branch::class)->findAll();
  3744.         if ($request->isMethod('GET')) {
  3745.             return $this->render('@Application/pages/human_resource/report/disburse_salary.html.twig', array(
  3746.                 'page_title' => 'Disburse Salary',
  3747.                 'EmployeeIds' => $EmployeeIds,
  3748.                 'departments' => $Departments,
  3749.                 'attendance' => $attendance,
  3750.                 'branches' => $branches,
  3751.                 'banks' => $banks,
  3752.                 'SalaryReports' => [],
  3753.                 'from_date' => '',
  3754.                 'to_date' => '',
  3755.                 'Qry' => '',
  3756.                 'isMethodGet' => true,
  3757.                 'filterType' => $filterType,
  3758.                 'startDate' => $startDate,
  3759.                 'endDate' => $endDate,
  3760.                 'filterBranchIds' => $filterBranchIds,
  3761.                 'filterBankIds' => $filterBankIds,
  3762.                 'filterDepartmentIds' => $filterDepartmentIds,
  3763.                 'filterEmployeeIds' => $filterEmployeeIds,
  3764.             ));
  3765.         }
  3766.         $SalaryReports HumanResource::BasicDeduction($em$request);
  3767. //        $SalaryReportsNew = HumanResource::calculateSalary($em,
  3768. //            array(
  3769. //                'startDate' => $request->get('salary_start_date', ''),
  3770. //                'endDate' => $request->get('salary_end_date', ''),
  3771. //                'timeZone' => $request->get('time_zone', '+0600'),
  3772. //                'employeeIds' => $request->get('employeeIds', []),
  3773. //                'departmentIds' => $request->get('department', []),
  3774. //                'allFlag' => $request->get('show_all', 0),
  3775. //
  3776. //            )
  3777. //        );
  3778.         $Qry "salary_till_date=" $endDate '&' "departmentIds=" implode(','$filterDepartmentIds) . '&' "employeeIds=" implode(','$filterEmployeeIds) .
  3779.             '&' "salary_start_date=" $startDate .
  3780.             '&' "filterType=" $filterType .
  3781.             '&' "branchIds=" implode(','$filterBranchIds) .
  3782.             '&' "bankIds=" implode(','$filterBankIds);
  3783. //        if ($request->get('returnJson', 0) == 1) {
  3784.         if ($request->get('returnJson'0) == 1) {
  3785.             return new JsonResponse(array(
  3786.                 'SalaryReports' => $SalaryReports,
  3787.             ));
  3788.         } else {
  3789.             return $this->render('@Application/pages/human_resource/report/disburse_salary.html.twig', array(
  3790.                 'page_title' => 'Disburse Salary',
  3791.                 'EmployeeIds' => $EmployeeIds,
  3792.                 'departments' => $Departments,
  3793.                 'branches' => $branches,
  3794.                 'banks' => $banks,
  3795.                 'SalaryReports' => $SalaryReports,
  3796.                 'for_month' => $SalaryReports[0]['for_month'],
  3797.                 'from_date' => $SalaryReports[0]['from_date'],
  3798.                 'to_date' => $SalaryReports[0]['to_date'],
  3799.                 'Qry' => $Qry,
  3800.                 'isMethodGet' => false,
  3801.                 'startDate' => $startDate,
  3802.                 'endDate' => $endDate,
  3803.                 'filterType' => $filterType,
  3804.                 'filterBranchIds' => $filterBranchIds,
  3805.                 'filterBankIds' => $filterBankIds,
  3806.                 'filterDepartmentIds' => $filterDepartmentIds,
  3807.                 'filterEmployeeIds' => $filterEmployeeIds,
  3808.             ));
  3809.         }
  3810.     }
  3811.     public function PrintDisburseSalaryAction(Request $Req)
  3812.     {
  3813.         $em $this->getDoctrine()->getManager();
  3814.         $company_data Company::getCompanyData($em1);
  3815.         $SalaryReports HumanResource::BasicDeduction($em$Req);
  3816.         return $this->render(
  3817.             '@Application/pages/human_resource/print/print_disburse_salary.html.twig',
  3818.             array(
  3819.                 'page_title' => 'Print Disburse Salary',
  3820.                 'export' => 'pdf,print',
  3821.                 'company_name' => $company_data->getName(),
  3822.                 'company_data' => $company_data,
  3823.                 'company_address' => $company_data->getAddress(),
  3824.                 'company_image' => $company_data->getImage(),
  3825.                 'SalaryReports' => $SalaryReports,
  3826.                 'for_month' => $SalaryReports[0]['for_month'],
  3827.                 'from_date' => $SalaryReports[0]['from_date'],
  3828.                 'to_date' => $SalaryReports[0]['to_date'],
  3829.                 'red' => 0
  3830.             )
  3831.         );
  3832.     }
  3833.     public function SalaryReportAction(Request $request)
  3834.     {
  3835.         $em $this->getDoctrine()->getManager();
  3836.         $startDate $request->get('salary_start_date''');
  3837.         $endDate $request->get('salary_till_date''');
  3838.         $segregationType $request->get('segregationType'1);
  3839.         $filterBranchIds $request->get('branchIds', []);
  3840.         $filterBankIds $request->get('bankIds', []);
  3841.         $approvalFilterTypes $request->get('approvalFilterTypes', []);
  3842.         $filterDepartmentIds $request->get('departmentIds', []);
  3843.         $filterEmployeeIds $request->get('employeeIds', []);
  3844.         $Departments $em->getRepository(SysDepartment::class)->findAll();
  3845.         $attendance $em->getRepository(EmployeeAttendanceLog::class)->findAll();
  3846.         $banks $em->getRepository(BankList::class)->findAll();
  3847.         $branches $em->getRepository(Branch::class)->findAll();
  3848.         $SalaryReports HumanResource::GenerateSalaryReport($em$request);
  3849. //        dump($SalaryReports);
  3850.         $Qry "salary_till_date=" $endDate '&' "departmentIds=" implode(','$filterDepartmentIds) . '&' "employeeIds=" implode(','$filterEmployeeIds) .
  3851.             '&' "salary_start_date=" $startDate .
  3852.             '&' "segregationType=" $segregationType .
  3853.             '&' "branchIds=" implode(','$filterBranchIds) .
  3854.             '&' "bankIds=" implode(','$filterBankIds);
  3855. //        if ($request->get('returnJson', 0) == 1) {
  3856.         if ($request->get('returnJson'0) == 1) {
  3857.             return new JsonResponse(array(
  3858.                 'SalaryReports' => $SalaryReports,
  3859.             ));
  3860.         } else {
  3861.             return $this->render('@Application/pages/human_resource/report/salary_report.html.twig', array(
  3862.                 'page_title' => 'Salary Report',
  3863.                 'departments' => $Departments,
  3864.                 'branches' => $branches,
  3865.                 'banks' => $banks,
  3866.                 'approvalFilterTypes' => $approvalFilterTypes,
  3867.                 'salaryInfo' => $SalaryReports,
  3868.                 'SalaryReports' => $SalaryReports,
  3869.                 'for_month' => '',
  3870.                 'from_date' => $startDate,
  3871.                 'to_date' => $endDate,
  3872.                 'Qry' => $Qry,
  3873.                 'isMethodGet' => false,
  3874.                 'startDate' => $startDate,
  3875.                 'endDate' => $endDate,
  3876.                 'segregationType' => $segregationType,
  3877.                 'filterBranchIds' => $filterBranchIds,
  3878.                 'filterBankIds' => $filterBankIds,
  3879.                 'filterDepartmentIds' => $filterDepartmentIds,
  3880.                 'filterEmployeeIds' => $filterEmployeeIds,
  3881.             ));
  3882.         }
  3883.     }
  3884.     public function createJobRecruitmentAction(Request $request$id 0)
  3885.     {
  3886.         $data = [];
  3887.         $em_goc $this->getDoctrine()->getManager('company_group');
  3888.         $skillDetails $em_goc->getRepository(EntitySkill::class)->findAll();
  3889.         $em $this->getDoctrine()->getManager();
  3890.         $companyId $this->getLoggedUserCompanyId($request);
  3891.         if ($request->isMethod('POST')) {
  3892.             $em $this->getDoctrine()->getManager();
  3893.             $entity_id array_flip(GeneralConstant::$Entity_list)['JobRecruitment']; //change
  3894.             $dochash $request->request->get('docHash'); //change
  3895.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3896.             $approveRole $request->request->get('approvalRole');
  3897.             $approveHash $request->request->get('approvalHash');
  3898.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3899.                 $loginId$approveRole$approveHash$id)
  3900.             ) {
  3901.                 $this->addFlash(
  3902.                     'error',
  3903.                     'Sorry Could not insert Data.'
  3904.                 );
  3905.             } else {
  3906.                 $data $request->request;
  3907.                 $docId HumanResource::createJobRecruitment($em$loginId$id$data$companyId);
  3908.                 //now add Approval info
  3909.                 $approveRole $request->request->get('approvalRole');
  3910.                 $options = array(
  3911.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3912.                     'notification_server' => $this->container->getParameter('notification_server'),
  3913.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3914.                     'url' => $this->generateUrl(
  3915.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['JobRecruitment']]
  3916.                         ['entity_view_route_path_name']
  3917.                     )
  3918.                 );
  3919.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3920.                     array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  3921.                     $docId,
  3922.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  3923.                 );
  3924.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  3925.                     $docId,
  3926.                     $loginId,
  3927.                     $approveRole,
  3928.                     $request->request->get('approvalHash'));
  3929.                 $this->addFlash(
  3930.                     'success',
  3931.                     'New Recruitment Document Added.'
  3932.                 );
  3933.                 $url $this->generateUrl(
  3934.                     'view_job_recruitment'
  3935.                 );
  3936.                 return $this->redirect($url "/" $docId);
  3937.             }
  3938.         }
  3939.         if ($id == 0) {
  3940.         } else {
  3941.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')->findOneBy(
  3942.                 array(
  3943.                     'jobRecruitmentId' => $id///material
  3944.                 )
  3945.             );
  3946.             //now if its not editable, redirect to view
  3947.             if ($extDoc) {
  3948.                 if ($extDoc->getEditFlag() != 1) {
  3949.                     $url $this->generateUrl(
  3950.                         'view_job_recruitment'
  3951.                     );
  3952.                     return $this->redirect($url "/" $id);
  3953.                 }
  3954.             }
  3955.         }
  3956.         $jobType HumanResourceConstant::$employeeType;
  3957.         //$skillDetails = $em->getRepository(Skill::class)->findAll();
  3958.         $educationDetails $em->getRepository('ApplicationBundle\\Entity\\EducationQualification')->findAll();
  3959.         $employeeIds $em->getRepository('ApplicationBundle\\Entity\\Employee')->findAll();
  3960.         $location HumanResourceConstant::$location;
  3961.         $salaryPer HumanResourceConstant::$salaryPer;
  3962.         $workExperience HumanResourceConstant::$workExperience;
  3963.         $jobOpeningStatus HumanResourceConstant::$jobOpeningStatus;
  3964.         $compatibility HumanResourceConstant::$compatibility;
  3965.         return $this->render('@Application/pages/human_resource/input_forms/create_new_job_post.html.twig', [
  3966.             'page_title' => 'Create New Job Post',
  3967.             'jobType' => $jobType,
  3968.             'skillDetails' => $skillDetails,
  3969.             'educationDetails' => $educationDetails,
  3970.             'employeeIds' => $employeeIds,
  3971.             'location' => $location,
  3972.             'salaryPer' => $salaryPer,
  3973.             'workExperience' => $workExperience,
  3974.             'jobOpeningStatus' => $jobOpeningStatus,
  3975.             'compatibility' => $compatibility
  3976.         ]);
  3977.     }
  3978.     public function viewApplicantInfoAction(Request $request$id)
  3979.     {
  3980.         $em $this->getDoctrine()->getManager('company_group');
  3981.         //$session = $request->getSession();
  3982.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($id);
  3983.         $skillDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntitySkill')->findAll();
  3984.         //$companyId = $this->getLoggedUserCompanyId($request);
  3985.         $gender HumanResourceConstant::$sex;
  3986.         $blood HumanResourceConstant::$BloodGroup;
  3987.         //$userId = $session->get(UserConstants::USER_ID);
  3988.         return $this->render('@Application/pages/human_resource/views/view_applicant_info.html.twig', [
  3989.             'page_title' => 'Applicant Information',
  3990.             'gender' => $gender,
  3991.             'blood' => $blood,
  3992.             'consultantDetails' => $consultantDetails,
  3993.             'education' => json_decode($consultantDetails->getEducationData(), true),
  3994.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  3995.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  3996.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  3997.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  3998.             'skillDetails' => $skillDetails
  3999.         ]);
  4000.     }
  4001.     public function ListJobRecruitmentAction()
  4002.     {
  4003.         $em $this->getDoctrine()->getManager();
  4004.         $jobRecruitmentList = [];
  4005.         $jobRecruitments $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')->findAll();
  4006.         foreach ($jobRecruitments as $jobRecruitment) {
  4007.             $jobData = array(
  4008.                 'jobRecruitmentId' => $jobRecruitment->getJobRecruitmentId(),
  4009.                 'title' => $jobRecruitment->getTitle(),
  4010.                 'date' => $jobRecruitment->getDate(),
  4011.                 'jobOpeningStatus' => $jobRecruitment->getJobOpeningStatus(),
  4012.                 'applicationOpeningDate' => $jobRecruitment->getApplicationOpeningDate(),
  4013.                 'applicationClosingDate' => $jobRecruitment->getApplicationClosingDate(),
  4014.             );
  4015.             $jobRecruitmentList[] = $jobData;
  4016.         }
  4017.         return $this->render('@Application/pages/human_resource/list/job_recruitment_list.html.twig', [
  4018.             'page_title' => 'Job RecruitmentAction List',
  4019.             'jobRecruitments' => $jobRecruitmentList
  4020.         ]);
  4021.     }
  4022.     public function ViewJobRecruitmentAction(Request $request$id 0)
  4023.     {
  4024.         $em_goc $this->getDoctrine()->getManager('company_group');
  4025.         $skillDetails $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntitySkill')->findAll();
  4026.         $em $this->getDoctrine()->getManager();
  4027.         $companyId $this->getLoggedUserCompanyId($request);
  4028.         $company_data Company::getCompanyData($em$companyId);
  4029. //        return new JsonResponse($encryptedDataArray);
  4030.         $location HumanResourceConstant::$location;
  4031.         $salaryPer HumanResourceConstant::$salaryPer;
  4032.         $workExperience HumanResourceConstant::$workExperience;
  4033.         $jobOpeningStatus HumanResourceConstant::$jobOpeningStatus;
  4034.         $compatibility HumanResourceConstant::$compatibility;
  4035.         $jobType HumanResourceConstant::$employeeType;
  4036.         $educationDetail $em->getRepository(EducationQualification::class)->findAll();
  4037.         $jobRecruitments $em->getRepository('ApplicationBundle\\Entity\\JobRecruitment')->find($id);
  4038.         $em_goc $this->getDoctrine()->getManager('company_group');
  4039.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")->findBy(
  4040.             array(
  4041.                 'jobPostId' => $id,
  4042.                 'CompanyId' => $companyId,
  4043.                 'appId' => $company_data->getAppId()
  4044.             )
  4045.         );
  4046.         $applicantIdList = [];
  4047.         foreach ($applicantApplicationList as $dt) {
  4048.             $applicantIdList[] = $dt->getApplicantId();
  4049.         }
  4050.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4051.         $Approval_data = [
  4052.             'exists' => 0,
  4053.             'approvalId' => 0,
  4054.             'roleType' => 0,
  4055.             'required' => 0,
  4056.             'acted' => 0,
  4057.             'entity' => array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4058.             'entityId' => $id,
  4059.         ];
  4060.         if (in_array($request->getSession()->get(UserConstants::USER_TYPE), [125]))
  4061.             $Approval_data System::checkIfApprovalExists(
  4062.                 $em,
  4063.                 array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4064.                 $id,
  4065.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4066.             );
  4067.         return $this->render('@Application/pages/human_resource/views/view_job_recruitment.html.twig', [
  4068.             'page_title' => 'View Job RecruitmentAction',
  4069.             'jobRecruitments' => $jobRecruitments,
  4070.             'applicantApplicationList' => $applicantApplicationList,
  4071.             'applicantList' => $applicantList,
  4072. //            'encryptedData' => $encryptedData,
  4073.             'skills' => json_decode($jobRecruitments->getskills()),
  4074.             'skillDetails' => $skillDetails,
  4075.             'education' => json_decode($jobRecruitments->getEducations()),
  4076.             'educationDetails' => $educationDetail,
  4077.             'location' => $location,
  4078.             'salaryPer' => $salaryPer,
  4079.             'workExperience' => $workExperience,
  4080.             'jobType' => $jobType,
  4081.             'compatibility' => $compatibility,
  4082.             'approval_status' => $jobRecruitments->getApproved(),
  4083.             'jobOpeningStatus' => $jobOpeningStatus,
  4084.             'approval_data' => $Approval_data,
  4085.             'auto_created' => $jobRecruitments->getAutocreated(),
  4086.             'document_log' => $jobRecruitments->getAutocreated() == System::getDocumentLog(
  4087.                 $em,
  4088.                 array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4089.                 $id,
  4090.                 $jobRecruitments->getCreatedLoginId(),
  4091.                 $jobRecruitments->getEditedLoginId()
  4092.             ) : []
  4093.         ]);
  4094.     }
  4095.     public function ViewApplicantScheduleAction(Request $request$id 0)
  4096.     {
  4097.         $em $this->getDoctrine()->getManager();
  4098.         $companyId $this->getLoggedUserCompanyId($request);
  4099.         $company_data Company::getCompanyData($em$companyId);
  4100.         $em_goc $this->getDoctrine()->getManager('company_group');
  4101.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")->findBy(
  4102.             array(
  4103.                 'jobPostId' => $id,
  4104.                 'CompanyId' => $companyId,
  4105.                 'appId' => $company_data->getAppId()
  4106.             )
  4107.         );
  4108.         $applicantIdList = [];
  4109.         foreach ($applicantApplicationList as $dt) {
  4110.             $applicantIdList[] = $dt->getApplicantId();
  4111.         }
  4112.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4113.         return $this->render('@Application/pages/human_resource/views/view_applicant_scheduled.html.twig', [
  4114.             'page_title' => 'View Applicant Scheduled',
  4115.             'applicantApplicationList' => $applicantApplicationList,
  4116.             'applicantList' => $applicantList,
  4117.         ]);
  4118.     }
  4119.     public function ViewApplicantReportAction(Request $request$id 0)
  4120.     {
  4121.         $em $this->getDoctrine()->getManager();
  4122.         $companyId $this->getLoggedUserCompanyId($request);
  4123.         $company_data Company::getCompanyData($em$companyId);
  4124.         $em_goc $this->getDoctrine()->getManager('company_group');
  4125.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantApplicationList")->findBy(
  4126.             array(
  4127.                 'jobPostId' => $id,
  4128.                 'CompanyId' => $companyId,
  4129.                 'appId' => $company_data->getAppId()
  4130.             )
  4131.         );
  4132.         $applicantIdList = [];
  4133.         foreach ($applicantApplicationList as $dt) {
  4134.             $applicantIdList[] = $dt->getApplicantId();
  4135.         }
  4136.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4137.         return $this->render('@Application/pages/human_resource/views/view_applicant_report.html.twig', [
  4138.             'page_title' => 'View Applicant Report',
  4139.             'applicantApplicationList' => $applicantApplicationList,
  4140.             'applicantList' => $applicantList,
  4141.         ]);
  4142.     }
  4143.     public function createEmployeePerformanceEvaluationAction(Request $request$id 0)
  4144.     {
  4145.         $data = [];
  4146.         $em $this->getDoctrine()->getManager();
  4147.         $companyId $this->getLoggedUserCompanyId($request);
  4148.         if ($request->isMethod('POST')) {
  4149.             $em $this->getDoctrine()->getManager();
  4150.             $entity_id array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']; //change
  4151.             $dochash $request->request->get('docHash'); //change
  4152.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4153.             $approveRole $request->request->get('approvalRole');
  4154.             $approveHash $request->request->get('approvalHash');
  4155.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4156.                 $loginId$approveRole$approveHash$id)
  4157.             ) {
  4158.                 $this->addFlash(
  4159.                     'error',
  4160.                     'Sorry Could not insert Data.'
  4161.                 );
  4162.             } else {
  4163.                 $data $request->request;
  4164.                 $docId HumanResource::createEmployeePerformanceEvaluation($em$loginId$id$data$companyId);
  4165.                 //now add Approval info
  4166.                 $approveRole $request->request->get('approvalRole');
  4167.                 $options = array(
  4168.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4169.                     'notification_server' => $this->container->getParameter('notification_server'),
  4170.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4171.                     'url' => $this->generateUrl(
  4172.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
  4173.                         ['entity_view_route_path_name']
  4174.                     )
  4175.                 );
  4176. //                System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4177. //                    array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution'],
  4178. //                    $docId,
  4179. //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4180. //                );
  4181. //                System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution'],
  4182. //                    $docId,
  4183. //                    $loginId,
  4184. //                    $approveRole,
  4185. //                    $request->request->get('approvalHash'));
  4186. //                $this->addFlash(
  4187. //                    'success',
  4188. //                    'Document Added.'
  4189. //                );
  4190. //                $url = $this->generateUrl(
  4191. //                    'create_employee_performance_evaluation'
  4192. //                );
  4193. //                return $this->redirect($url);
  4194.             }
  4195.         }
  4196.         $skill $em->getRepository(Skill::class)->findAll();
  4197.         $educationDetail $em->getRepository(EducationQualification::class)->findAll();
  4198.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  4199.         $employeeType HumanResourceConstant::$employeeType;
  4200.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  4201.         $branch $em->getRepository(Branch::class)->findAll();
  4202.         $departments $em->getRepository(SysDepartment::class)->findAll();
  4203.         $department = [];
  4204.         foreach ($departments as $entry) {
  4205.             $department[$entry->getDepartmentId()] = array(
  4206.                 'id' => $entry->getDepartmentId(),
  4207.                 'name' => $entry->getDepartmentName(),
  4208.             );
  4209.         }
  4210.         return $this->render('@Application/pages/human_resource/input_forms/employee_performance_evolution.html.twig',
  4211.             array(
  4212.                 'page_title' => 'Create Employee Performance Evaluation',
  4213.                 'employeeIds' => $employeeIds,
  4214.                 'employeeType' => $employeeType,
  4215.                 'Designation' => $Designation,
  4216.                 'branch' => $branch,
  4217.                 'department' => $department,
  4218.                 'skill' => $skill,
  4219.                 'educationDetail' => $educationDetail
  4220.             )
  4221.         );
  4222.     }
  4223.     public function ViewIndividualReviewAction()
  4224.     {
  4225.         return $this->render('@Application/pages/human_resource/views/individual_review.html.twig',
  4226.             array(
  4227.                 'page_title' => 'Individual Performance View',
  4228.             )
  4229.         );
  4230.     }
  4231.     public function EmployeeListBySkillPerformanceAction()
  4232.     {
  4233.         $em $this->getDoctrine()->getManager();
  4234.         $employee $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findAll();
  4235.         $skill $em->getRepository('ApplicationBundle\\Entity\\Skill')->findAll();
  4236.         return $this->render('@Application/pages/human_resource/list/employee_performance_evolution_list.html.twig',
  4237.             array(
  4238.                 'page_title' => 'Employee Skill & Performance',
  4239.                 'employee' => $employee,
  4240.                 //'employeeSkill' => json_decode($employee->getSkill(),true),
  4241.                 'skill' => $skill,
  4242.             )
  4243.         );
  4244.     }
  4245.     public function setWorkPlaceAction(Request $req)
  4246.     {
  4247.         $em $this->getDoctrine()->getManager();
  4248.         $companyId $this->getLoggedUserCompanyId($req);
  4249.         $docHash '';
  4250.         if ($req->request->has('XHRreq')) {
  4251.             $docHash HumanResource::HandelXHRreqForEmpWorkplace($em$req);
  4252.             return new JsonResponse([$docHash]);
  4253.         }
  4254.         if ($req->isMethod('GET')) {
  4255.             $TwigData HumanResource::TwigDataForEmployeeWorkplace($em);
  4256.             return $this->render(
  4257.                 '@Application/pages/human_resource/input_forms/update_workplace.html.twig',
  4258.                 [
  4259.                     'page_title' => 'Set Workplace',
  4260.                     'employeeIds' => $TwigData['employeeIds']
  4261.                 ]
  4262.             );
  4263.         }
  4264.         if ($req->isMethod('POST')) {
  4265.             $approveHash $req->request->get('approvalHash');
  4266.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4267.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4268.             if ($isSignatureOk) {
  4269.                 $isSuccess HumanResource::CreateOrUpdateForEmpWorkplace($em$req$companyIdfalse$docHash);
  4270.                 if ($isSuccess) {
  4271.                     $this->addFlash(
  4272.                         'success',
  4273.                         'Workplace set!'
  4274.                     );
  4275.                     return $this->redirectToRoute('set_workplace');
  4276.                 }
  4277.             } else {
  4278.                 $this->addFlash(
  4279.                     'error',
  4280.                     'Invalid Approval Hash!'
  4281.                 );
  4282.                 return $this->redirectToRoute('set_workplace');
  4283.             }
  4284.         }
  4285.     }
  4286.     public function setWorkPlaceForAppAction(Request $req)
  4287.     {
  4288.         $em $this->getDoctrine()->getManager();
  4289.         $companyId $this->getLoggedUserCompanyId($req);
  4290.         $docHash HumanResource::HandelXHRreqForEmpWorkplace($em$req);
  4291.         if ($req->isMethod('GET')) {
  4292.             $TwigData HumanResource::TwigDataForEmployeeWorkplace($em);
  4293.             return $this->render(
  4294.                 '@Application/pages/human_resource/input_forms/update_workplace.html.twig',
  4295.                 [
  4296.                     'page_title' => 'Set Workplace',
  4297.                     'employeeIds' => $TwigData['employeeIds']
  4298.                 ]
  4299.             );
  4300.         }
  4301.         if ($req->isMethod('POST')) {
  4302.             $approveHash $req->request->get('approvalHash');
  4303.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4304.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4305.             if ($isSignatureOk) {
  4306.                 $isSuccess HumanResource::CreateOrUpdateForEmpWorkplace($em$req$companyIdfalse$docHash);
  4307.                 if ($isSuccess) {
  4308.                     $this->addFlash(
  4309.                         'success',
  4310.                         'Workplace set!'
  4311.                     );
  4312. //                    return $this->redirectToRoute('set_workplace');
  4313.                     return new JsonResponse(array(
  4314.                         "success" => true
  4315.                     ));
  4316.                 }
  4317.             } else {
  4318.                 $this->addFlash(
  4319.                     'error',
  4320.                     'Invalid Approval Hash!'
  4321.                 );
  4322. //                return $this->redirectToRoute('set_workplace');
  4323.             }
  4324.         }
  4325.     }
  4326.     public function ViewMeetingAction(Request $req$action 0$id 0)
  4327.     {
  4328.         $em $this->getDoctrine()->getManager();
  4329.         $companyId $this->getLoggedUserCompanyId($req);
  4330.         if ($req->request->has('XHRreq')) {
  4331.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4332.         }
  4333.         if ($action === 'view') {
  4334.             $response HumanResource::TwigDataForScheduledMeetingView($em$req$id);
  4335.             return $this->render(
  4336.                 '@Application/pages/human_resource/views/scheduled_meeting_view.html.twig',
  4337.                 [
  4338.                     'page_title' => 'View Scheduled Meeting',
  4339.                     'duration' => $response['duration'],
  4340.                     'appId' => $response['appId'],
  4341.                     'publicView' => 0,
  4342.                     'meeting_data' => $response['meeting_data'],
  4343.                     'agenda_list' => $response['agenda_list'],
  4344.                     'id' => $req->query->get('view_meeting'),
  4345.                     'approval_data' => $response['approval_data'],
  4346.                     'document_log' => $response['document_log'],
  4347.                     'approval_status' => $response['approval_status'],
  4348.                     'created_by' => $response['created_by'],
  4349.                     'updated_at' => $response['updated_at'],
  4350.                     'auto_created' => 0,
  4351.                 ]
  4352.             );
  4353.         }
  4354.         if ($action === 'print') {
  4355.             $response HumanResource::TwigDataForScheduledMeetingView($em$req$id);
  4356. //      $id = $req->query->get('print_meeting');
  4357.             $em $this->getDoctrine()->getManager();
  4358.             $company_data Company::getCompanyData($em1);
  4359.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'], $id);
  4360.             return $this->render(
  4361.                 '@Application/pages/human_resource/print/scheduled_meeting_print.html.twig',
  4362.                 array(
  4363.                     'page_title' => 'View Scheduled Meeting',
  4364.                     'duration' => $response['duration'],
  4365.                     'meeting_data' => $response['meeting_data'],
  4366.                     'agenda_list' => $response['agenda_list'],
  4367.                     'export' => 'pdf,print',
  4368.                     'company_name' => $company_data->getName(),
  4369.                     'company_data' => $company_data,
  4370.                     'company_address' => $company_data->getAddress(),
  4371.                     'company_image' => $company_data->getImage(),
  4372.                     'Authorizations' => $Authorizations,
  4373.                     'red' => 0
  4374.                 )
  4375.             );
  4376.         }
  4377.     }
  4378.     public function UpdateMeetingMinutesAction(Request $req$action 0$id 0)
  4379.     {
  4380.         $em $this->getDoctrine()->getManager();
  4381.         $companyId $this->getLoggedUserCompanyId($req);
  4382.         $scheduleId $req->request->get('scheduleId');
  4383.         $minuteText $req->request->get('minuteText');
  4384.         $agendaKey $req->request->get('key');
  4385.         $scheduledMeeting $em->getRepository(ScheduledMeeting::class)
  4386.             ->find($scheduleId);
  4387.         $agendaList json_decode($scheduledMeeting->getAgendaList(), true);
  4388.         foreach ($agendaList as $key => $item) {
  4389.             if ($key == $agendaKey)
  4390.                 $agendaList[$key]['minutes'] = $minuteText;
  4391.         }
  4392.         $scheduledMeeting->setAgendaList(json_encode($agendaList));
  4393.         $em->flush();
  4394.         return new JsonResponse(array(
  4395.             'success' => true
  4396.         ));
  4397.     }
  4398.     public function deleteLastAttendanceAction(Request $request)
  4399.     {
  4400.         $em $this->getDoctrine()->getManager();
  4401.         $lastAttendance $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance')
  4402.             ->createQueryBuilder('ea')
  4403.             ->orderBy('ea.id''DESC')
  4404.             ->setMaxResults(1)
  4405.             ->getQuery()
  4406.             ->getOneOrNullResult();
  4407.         $lastAttendanceLog $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')
  4408.             ->createQueryBuilder('eal')
  4409.             ->orderBy('eal.id''DESC')
  4410.             ->setMaxResults(1)
  4411.             ->getQuery()
  4412.             ->getOneOrNullResult();
  4413.         $deletedCount 0;
  4414.         if ($lastAttendance) {
  4415.             $em->remove($lastAttendance);
  4416.             $deletedCount++;
  4417.         }
  4418.         if ($lastAttendanceLog) {
  4419.             $em->remove($lastAttendanceLog);
  4420.             $deletedCount++;
  4421.         }
  4422.         $em->flush();
  4423.         return new JsonResponse(
  4424.             [
  4425.                 'success' => true,
  4426.                 'message' => "Deleted `$deletedCount` rows from attendance tables."
  4427.             ]
  4428.         );
  4429.     }
  4430.     public function SendMeetingUpdatesAction(Request $req$action 0$id 0)
  4431.     {
  4432.         $em $this->getDoctrine()->getManager();
  4433.         $companyId $this->getLoggedUserCompanyId($req);
  4434.         $session $req->getSession();
  4435.         $companyData Company::getCompanyData($em$companyId);
  4436.         $scheduleId $req->request->get('scheduleId');
  4437.         $minuteText $req->request->get('minuteText');
  4438.         $agendaKey $req->request->get('key');
  4439.         $scheduledMeeting $em->getRepository(ScheduledMeeting::class)
  4440.             ->find($scheduleId);
  4441.         $sendEmailInvitationTo json_decode($scheduledMeeting->getAllParticipantsNameEmail(), true);
  4442.         if ($sendEmailInvitationTo == null)
  4443.             $sendEmailInvitationTo = [];
  4444.         $agendaList json_decode($scheduledMeeting->getAgendaList(), true);
  4445.         if ($agendaList == null)
  4446.             $agendaList = [];
  4447.         $EmployeeList HumanResource::GetEmployeeList($em, []);
  4448.         // Same guard as HumanResource::TwigDataForScheduledMeetingView â€” an unmapped type must
  4449.         // not take the page down.
  4450.         $mtKey $scheduledMeeting->getMeetingType();
  4451.         $meetingType = isset(MeetingSchedulingConstant::$meetingType[$mtKey])
  4452.             ? MeetingSchedulingConstant::$meetingType[$mtKey]
  4453.             : ($mtKey === null || $mtKey === '' 'Meeting' 'Meeting (type ' $mtKey ')');
  4454.         foreach ($sendEmailInvitationTo as $key => $email) {
  4455.             $name ucWords(str_replace("_"" "$key));
  4456.             $bodyHtml '';
  4457.             $bodyTemplate '@Application/email/meeting_scheduling/scheduled_meeting_update.html.twig';
  4458.             $bodyData = array(
  4459.                 'name' => $name,
  4460.                 'gocId' => $session->get(UserConstants::USER_GOC_ID),
  4461.                 'appId' => $session->get(UserConstants::USER_APP_ID),
  4462.                 'email' => $email,
  4463.                 'meetingData' => $scheduledMeeting,
  4464.                 'meeting_type' => $meetingType,
  4465.                 'agenda_list' => $agendaList,
  4466.                 'companyData' => $companyData,
  4467.                 'employeeList' => $EmployeeList,
  4468.             );
  4469.             $attachments = [];
  4470.             $new_mail $this->get('mail_module');
  4471.             $new_mail->sendMyMail(array(
  4472.                 'senderHash' => '_MEETING_',
  4473.                 'forwardToMailAddress' => $email,
  4474.                 'subject' => "Meeting Updates Arranged By - " $companyData->getName() . " on " $scheduledMeeting->getTitle() . ". ",
  4475.                 'fileName' => '',
  4476.                 'attachments' => $attachments,
  4477.                 'toAddress' => $email,
  4478.                 'mailTemplate' => $bodyTemplate,
  4479.                 'templateData' => $bodyData,
  4480.                 'embedCompanyImage' => 1,
  4481.                 'companyId' => $companyId,
  4482.                 'companyImagePath' => $companyData->getImage()
  4483.             ));
  4484.         }
  4485.         return new JsonResponse(array(
  4486.             'success' => true
  4487.         ));
  4488.     }
  4489.     public function meetingSchedulingAction(Request $req$action 0)
  4490.     {
  4491.         $em $this->getDoctrine()->getManager();
  4492.         $companyId $this->getLoggedUserCompanyId($req);
  4493.         $session $req->getSession();
  4494.         if ($req->request->has('XHRreq')) {
  4495.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4496.         }
  4497.         if ($action === 'list') {
  4498.             $response HumanResource::TwigDataForScheduledMeetingList($em, [0null]);
  4499.             return $this->render(
  4500.                 '@Application/pages/human_resource/list/scheduled_meeting_list.html.twig',
  4501.                 [
  4502.                     'page_title' => 'Scheduled Meeting List',
  4503.                     'list' => $response
  4504.                 ]
  4505.             );
  4506.         }
  4507.         if ($req->isMethod('GET')) {
  4508.             $response HumanResource::twigDataForMeetingScheduling($em);
  4509.             return $this->render(
  4510.                 '@Application/pages/human_resource/input_forms/meeting_scheduling.html.twig',
  4511.                 [
  4512.                     'page_title' => 'Schedule a Meeting',
  4513.                     'employeeIds' => $response['employeeIds'],
  4514.                     'branches' => $response['branches'],
  4515.                     'asset' => $response['asset'],
  4516.                     'rooms' => $response['rooms'],
  4517.                     'sales_orders' => $response['salesOrders'],
  4518.                     'purchase_orders' => $response['purchaseOrders'],
  4519.                     'meeting_types' => $response['meetingType'],
  4520.                 ]
  4521.             );
  4522.         }
  4523.         if ($req->isMethod('POST')) {
  4524.             $approveHash $req->request->get('approvalHash');
  4525.             $approveRole $req->request->get('approvalRole');
  4526.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4527.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4528.             $companyData Company::getCompanyData($em$companyId);
  4529.             if ($isSignatureOk) {
  4530.                 $isSuccess HumanResource::createOrUpdateDataForMeetingScheduling($em$req);
  4531.                 if ($isSuccess) {
  4532.                     $options = array(
  4533.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4534.                         'notification_server' => $this->container->getParameter('notification_server'),
  4535.                         'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
  4536.                         'url' => $this->generateUrl(
  4537.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
  4538.                         )
  4539.                     );
  4540.                     $meetingId $isSuccess[1];
  4541.                     System::setApprovalInfo(
  4542.                         $this->getDoctrine()->getManager(),
  4543.                         $options,
  4544.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  4545.                         $meetingId,
  4546.                         $req->getSession()->get(UserConstants::USER_LOGIN_ID),
  4547.                         0//normal meeting
  4548.                         0,
  4549.                         $this->get('mail_module')
  4550.                     );
  4551.                     System::createEditSignatureHash(
  4552.                         $this->getDoctrine()->getManager(),
  4553.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  4554.                         $meetingId,
  4555.                         $loginId,
  4556.                         $approveRole,
  4557.                         $req->request->get('approvalHash')
  4558.                     );
  4559.                     $url $this->generateUrl(
  4560.                         'view_scheduled_meeting'
  4561.                     );
  4562.                     return $this->redirect($url "/" $meetingId);
  4563.                 } else {
  4564.                     return new JsonResponse(array(
  4565.                         'success' => false
  4566.                     ));
  4567.                 }
  4568.             } else {
  4569.                 $this->addFlash(
  4570.                     'error',
  4571.                     'Invalid Approval Hash!'
  4572.                 );
  4573.                 return $this->redirectToRoute('meeting_scheduling');
  4574.             }
  4575.         }
  4576.         return $this->redirectToRoute('meeting_scheduling');
  4577.     }
  4578.     public function MeetingSchedulingForAppAction(Request $request): JsonResponse
  4579.     {
  4580.         $em $this->getDoctrine()->getManager();
  4581.         $session $request->getSession();
  4582.         $mailer $this->get('mail_module');
  4583.         $helper = new HumanResourceHelper($em$mailer);
  4584.         try {
  4585.             $data $request->request->all();
  4586.             $files $request->files->all();
  4587.             $companyId $this->getLoggedUserCompanyId($request);
  4588.             $meeting $helper->prepareMeeting($data$session);
  4589.             $agendaList = [];
  4590.             if (!empty($data['agendaList']) && is_array($data['agendaList'])) {
  4591.                 foreach ($data['agendaList'] as $index => $agendaData) {
  4592.                     $agenda = [
  4593.                         'title' => $agendaData['title'] ?? null,
  4594.                         'desc' => $agendaData['desc'] ?? null,
  4595.                         'notes' => $agendaData['notes'] ?? null,
  4596.                         'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
  4597.                         'otherDocuments' => [],
  4598.                     ];
  4599.                     if (!empty($files['agendaList'][$index]['otherDocuments'])) {
  4600.                         foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
  4601.                             $uploadedFilePath $this->uploadMeetingFile($uploadedFile$request);
  4602.                             if ($uploadedFilePath) {
  4603.                                 $agenda['otherDocuments'][] = [
  4604.                                     'fileName' => basename($uploadedFilePath),
  4605.                                     'path' => $uploadedFilePath,
  4606.                                     'type' => $uploadedFile->getClientOriginalExtension(),
  4607.                                 ];
  4608.                             }
  4609.                         }
  4610.                     }
  4611.                     $agendaList[] = $agenda;
  4612.                 }
  4613.             }
  4614.             $meeting->setAgendaList(json_encode($agendaList));
  4615.             [$internalInfo$otherInfo$internalIds] = $helper->resolveParticipants(
  4616.                 $data['guests'] ?? [],
  4617.                 $session->get('userEmployeeId')
  4618.             );
  4619.             // Save **full participant objects** to DB
  4620.             $meeting->setInternalParticipantIds(!empty($internalInfo) ? json_encode($internalInfo) : null);
  4621.             $meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
  4622.             $meeting->setParticipantInfo(json_encode([
  4623.                 'internal' => $internalInfo,
  4624.                 'other' => $otherInfo,
  4625.             ]));
  4626.             // Persist the meeting
  4627.             $em->persist($meeting);
  4628.             $em->flush();
  4629.             // Send invitations
  4630.             $helper->sendInvitations($meeting$internalIds$otherInfo$companyId);
  4631.             return new JsonResponse([
  4632.                 'success' => true,
  4633.                 'message' => 'Meeting scheduled successfully',
  4634.                 'meetingId' => $meeting->getScheduleId(),
  4635.                 'documentHas' => $meeting->getDocumentHash(),
  4636.             ]);
  4637.         } catch (\Exception $e) {
  4638.             return new JsonResponse(['success' => false'error' => $e->getMessage()], 500);
  4639.         }
  4640.     }
  4641.     public function updateMeetingForAppAction(Request $requestint $meetingId): JsonResponse
  4642.     {
  4643.         $em $this->getDoctrine()->getManager();
  4644.         $session $request->getSession();
  4645.         $mailer $this->get('mail_module');
  4646.         $helper = new HumanResourceHelper($em$mailer);
  4647.         try {
  4648.             $data $request->request->all();
  4649.             $files $request->files->all();
  4650.             $meeting $em->getRepository(ScheduledMeeting::class)->find($meetingId);
  4651.             if (!$meeting) {
  4652.                 return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4653.             }
  4654.             $meeting->setTitle($data['title'] ?? $meeting->getTitle());
  4655.             $meeting->setSpecialType($data['specialType'] ?? $meeting->getSpecialType());
  4656.             $meeting->setStartAt(!empty($data['startAt']) ? new \DateTime($data['startAt']) : $meeting->getStartAt());
  4657.             $meeting->setEndAt(!empty($data['endAt']) ? new \DateTime($data['endAt']) : $meeting->getEndAt());
  4658.             $meeting->setMeetingType($data['meetingType'] ?? $meeting->getMeetingType());
  4659.             $meeting->setLocation($data['location'] ?? $meeting->getLocation());
  4660.             $meeting->setRoomId($data['roomId'] ?? $meeting->getRoomId());
  4661.             $meeting->setDesc($data['desc'] ?? $meeting->getDesc());
  4662.             $meeting->setLastModifiedDate(new \DateTime());
  4663.             if (isset($data['agendaList']) && is_array($data['agendaList'])) {
  4664.                 $agendaList = [];
  4665.                 foreach ($data['agendaList'] as $index => $agendaData) {
  4666.                     $agenda = [
  4667.                         'title' => $agendaData['title'] ?? null,
  4668.                         'desc' => $agendaData['desc'] ?? null,
  4669.                         'notes' => $agendaData['notes'] ?? null,
  4670.                         'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
  4671.                         'otherDocuments' => [],
  4672.                     ];
  4673.                     if (!empty($files['agendaList'][$index]['otherDocuments'])) {
  4674.                         foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
  4675.                             $uploadedFilePath $this->uploadMeetingFile($uploadedFile$request);
  4676.                             if ($uploadedFilePath) {
  4677.                                 $agenda['otherDocuments'][] = [
  4678.                                     'fileName' => basename($uploadedFilePath),
  4679.                                     'path' => $uploadedFilePath,
  4680.                                     'type' => $uploadedFile->getClientOriginalExtension(),
  4681.                                 ];
  4682.                             }
  4683.                         }
  4684.                     }
  4685.                     if (!empty($agendaData['otherDocumentsExisting'])) {
  4686.                         $agenda['otherDocuments'] = array_merge(
  4687.                             $agenda['otherDocuments'],
  4688.                             $agendaData['otherDocumentsExisting']
  4689.                         );
  4690.                     }
  4691.                     $agendaList[] = $agenda;
  4692.                 }
  4693.                 $meeting->setAgendaList(json_encode($agendaList));
  4694.             }
  4695.             if (isset($data['guests'])) {
  4696.                 [$internalIds$otherInfo] = $helper->resolveParticipants($data['guests'], $session->get('userEmployeeId'));
  4697.                 $meeting->setInternalParticipantIds(!empty($internalIds) ? json_encode($internalIds) : null);
  4698.                 $meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
  4699.             }
  4700.             $em->persist($meeting);
  4701.             $em->flush();
  4702.             if (isset($internalIds) || isset($otherInfo)) {
  4703.                 $helper->sendInvitations($meeting$internalIds ?? [], $otherInfo ?? [], $meeting->getCompanyId());
  4704.             }
  4705.             return new JsonResponse([
  4706.                 'success' => true,
  4707.                 'message' => 'Meeting updated successfully',
  4708.                 'meetingId' => $meeting->getScheduleId(),
  4709.                 'facilitator' => ['id' => $meeting->getFacilitatorId(), 'name' => $meeting->getFacilitatorName()],
  4710.                 'companyId' => $meeting->getCompanyId(),
  4711.                 'branchId' => $meeting->getBranchId(),
  4712.                 'internalParticipants' => json_decode($meeting->getInternalParticipantIds(), true) ?? [],
  4713.                 'otherParticipants' => json_decode($meeting->getOtherParticipantInfo(), true) ?? [],
  4714.                 'agendas' => json_decode($meeting->getAgendaList(), true) ?? [],
  4715.             ]);
  4716.         } catch (\Exception $e) {
  4717.             return new JsonResponse(['success' => false'error' => $e->getMessage()], 500);
  4718.         }
  4719.     }
  4720.     public function GetDocumentsForMeetingScheduleAppAction(Request $request): JsonResponse
  4721.     {
  4722.         $em $this->getDoctrine()->getManager();
  4723.         $hrHelper = new HumanResourceHelper($em);
  4724.         try {
  4725.             $documents $hrHelper->getAllDocumentsFromApproval($request);
  4726.             return ResponseStructure::success($documents'Documents fetched successfully');
  4727.         } catch (\Exception $e) {
  4728.             return ResponseStructure::error($e->getMessage());
  4729.         }
  4730.     }
  4731.     public function getMeetingsByDateAction(Request $request): JsonResponse
  4732.     {
  4733.         $em $this->getDoctrine()->getManager();
  4734.         $type $request->query->get('type'); // Day, Week, Month, Yearly, Custom
  4735.         $repo $em->getRepository(ScheduledMeeting::class);
  4736.         $today = new \DateTime();
  4737.         $fromDate null;
  4738.         $toDate = (clone $today)->setTime(235959);
  4739.         switch ($type) {
  4740.             case 'Day':
  4741.                 $fromDate = (clone $today)->setTime(000);
  4742.                 break;
  4743.             case 'Week':
  4744.                 $fromDate = (clone $today)->modify('-6 days')->setTime(000);
  4745.                 break;
  4746.             case 'Month':
  4747.                 $fromDate = (clone $today)->modify('-30 days')->setTime(000);
  4748.                 break;
  4749.             case 'Yearly':
  4750.                 $fromDate = (clone $today)->modify('-1 year')->setTime(000);
  4751.                 break;
  4752.             case 'Custom':
  4753.                 $start $request->query->get('start');
  4754.                 $end $request->query->get('end');
  4755.                 if (!$start || !$end) {
  4756.                     return new JsonResponse(['error' => 'Start and end date are required for Custom type'], 400);
  4757.                 }
  4758.                 $fromDate = new \DateTime($start " 00:00:00");
  4759.                 $toDate = new \DateTime($end " 23:59:59");
  4760.                 break;
  4761.             default:
  4762.                 return new JsonResponse(['error' => 'Invalid type parameter'], 400);
  4763.         }
  4764.         $meetings $repo->createQueryBuilder('pv')
  4765.             ->where('pv.startAt >= :fromDate')
  4766.             ->andWhere('pv.startAt <= :toDate')
  4767.             ->setParameter('fromDate'$fromDate)
  4768.             ->setParameter('toDate'$toDate)
  4769.             ->orderBy('pv.startAt''DESC')
  4770.             ->getQuery()
  4771.             ->getResult();
  4772.         $data = [];
  4773.         foreach ($meetings as $meeting) {
  4774.             $data[] = [
  4775.                 'id' => $meeting->getScheduleId(),
  4776.                 'title' => $meeting->getTitle(),
  4777.                 'desc' => $meeting->getDesc(),
  4778.                 'startAt' => $meeting->getStartAt()->format('Y-m-d H:i:s'),
  4779.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4780.                 'roomId' => $meeting->getRoomId(),
  4781.                 'meetingType' => $meetingType[$meeting->getMeetingType()] ?? null,
  4782.                 'location' => $meeting->getLocation(),
  4783.                 'participant' => json_decode($meeting->getParticipantInfo()),
  4784.                 'status' => $meeting->getStatus(),
  4785.                 'approved' => (bool)$meeting->getApproved(),
  4786.             ];
  4787.         }
  4788.         return new JsonResponse([
  4789.             'success' => true,
  4790.             'message' => 'Scheduled Meeting data retrieved successfully',
  4791.             'type' => $type,
  4792.             'fromDate' => $fromDate->format('Y-m-d'),
  4793.             'toDate' => $toDate->format('Y-m-d'),
  4794.             'count' => count($data),
  4795.             'data' => $data,
  4796.         ]);
  4797.     }
  4798.     public function getMeetingByYearlyAction(Request $request): JsonResponse
  4799.     {
  4800.         $em $this->getDoctrine()->getManager();
  4801.         $yearParam $request->query->get('year');
  4802.         try {
  4803.             $data HumanResourceHelper::GetMeetingByYearlyAction($em$yearParam);
  4804.             return new JsonResponse($data200);
  4805.         } catch (\Exception $e) {
  4806.             return new JsonResponse([
  4807.                 'success' => false,
  4808.                 'error' => $e->getMessage()
  4809.             ], 400);
  4810.         }
  4811.     }
  4812.     public function getMeetingByIdAction(Request $requestint $id): JsonResponse
  4813.     {
  4814.         $em $this->getDoctrine()->getManager();
  4815.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4816.         if (!$meeting) {
  4817.             return new JsonResponse([
  4818.                 'success' => false,
  4819.                 'error' => 'Meeting not found'
  4820.             ], 404);
  4821.         }
  4822.         return new JsonResponse([
  4823.             'success' => true,
  4824.             'meeting' => [
  4825.                 'id' => $meeting->getScheduleId(),
  4826.                 'docHash' => $meeting->getDocumentHash(),
  4827.                 'title' => $meeting->getTitle(),
  4828.                 'desc' => $meeting->getDesc(),
  4829.                 'specialType' => $meeting->getSpecialType(),
  4830.                 'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('Y-m-d H:i:s') : null,
  4831.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4832.                 'meetingType' => $meeting->getMeetingType(),
  4833.                 'location' => $meeting->getLocation(),
  4834.                 'roomId' => $meeting->getRoomId(),
  4835.                 'facilitator' => [
  4836.                     'id' => $meeting->getFacilitatorId(),
  4837.                     'name' => $meeting->getFacilitatorName()
  4838.                 ],
  4839.                 'companyId' => $meeting->getCompanyId(),
  4840.                 'branchId' => $meeting->getBranchId(),
  4841.                 'agendaList' => $meeting->getAgendaList() ? json_decode($meeting->getAgendaList(), true) : [],
  4842.                 'internalParticipants' => $meeting->getInternalParticipantIds() ? json_decode($meeting->getInternalParticipantIds(), true) : [],
  4843.                 'otherParticipants' => $meeting->getOtherParticipantInfo() ? json_decode($meeting->getOtherParticipantInfo(), true) : [],
  4844.                 'createdAt' => $meeting->getCreatedAt()->format('Y-m-d H:i:s'),
  4845.             ]
  4846.         ]);
  4847.     }
  4848.     public function updateMeetingAction(Request $requestint $id): JsonResponse
  4849.     {
  4850.         $em $this->getDoctrine()->getManager();
  4851.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4852.         if (!$meeting) {
  4853.             return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4854.         }
  4855.         $data json_decode($request->getContent(), true);
  4856.         if (!$data) {
  4857.             $data $request->request->all();
  4858.         }
  4859.         if (!$data) {
  4860.             return new JsonResponse(['success' => false'error' => 'Invalid data'], 400);
  4861.         }
  4862.         if (isset($data['title'])) $meeting->setTitle($data['title']);
  4863.         if (isset($data['desc'])) $meeting->setDesc($data['desc']);
  4864.         if (isset($data['startAt'])) $meeting->setStartAt(new \DateTime($data['startAt']));
  4865.         if (isset($data['endAt'])) $meeting->setEndAt(new \DateTime($data['endAt']));
  4866.         if (isset($data['location'])) $meeting->setLocation($data['location']);
  4867.         if (isset($data['meetingType'])) $meeting->setMeetingType($data['meetingType']);
  4868.         if (isset($data['roomId'])) $meeting->setRoomId($data['roomId']);
  4869.         if (isset($data['agendaList'])) {
  4870.             $agendaList is_array($data['agendaList']) ? $data['agendaList'] : json_decode($data['agendaList'], true);
  4871.             $meeting->setAgendaList(json_encode($agendaList));
  4872.         }
  4873.         $meeting->setLastModifiedDate(new \DateTime());
  4874.         $em->flush();
  4875.         return new JsonResponse([
  4876.             'success' => true,
  4877.             'message' => 'Meeting updated successfully',
  4878.             'meetingId' => $meeting->getScheduleId()
  4879.         ]);
  4880.     }
  4881.     public function deleteMeetingAction(Request $requestint $id): JsonResponse
  4882.     {
  4883.         $em $this->getDoctrine()->getManager();
  4884.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4885.         if (!$meeting) {
  4886.             return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4887.         }
  4888.         $em->remove($meeting);
  4889.         $em->flush();
  4890.         return new JsonResponse([
  4891.             'success' => true,
  4892.             'message' => 'Meeting deleted successfully',
  4893.             'deletedId' => $id
  4894.         ]);
  4895.     }
  4896.     public function searchParticipantByEmailAction(Request $request): JsonResponse
  4897.     {
  4898.         $em $this->getDoctrine()->getManager();
  4899.         $email trim($request->query->get('email'));
  4900.         if (empty($email)) {
  4901.             return new JsonResponse([
  4902.                 'success' => false,
  4903.                 'error' => 'Email is required'
  4904.             ], 400);
  4905.         }
  4906.         try {
  4907.             $companyId $this->getLoggedUserCompanyId($request);
  4908.             $client $em->getRepository(\ApplicationBundle\Entity\AccClients::class)
  4909.                 ->findOneBy(['email' => $email]);
  4910.             if ($client) {
  4911.                 return new JsonResponse([
  4912.                     'success' => true,
  4913.                     'type' => 'client',
  4914.                     'data' => [
  4915.                         'client_id' => $client->getClientId(),
  4916.                         'company_id' => $client->getCompanyId(),
  4917.                         'client_name' => $client->getClientName(),
  4918.                         'email' => $client->getEmail(),
  4919.                     ]
  4920.                 ]);
  4921.             }
  4922.             $employee $em->getRepository(\ApplicationBundle\Entity\Employee::class)
  4923.                 ->findOneBy(['email' => $email]);
  4924.             if ($employee) {
  4925.                 return new JsonResponse([
  4926.                     'success' => true,
  4927.                     'type' => 'employee',
  4928.                     'data' => [
  4929.                         'name' => $employee->getName(),
  4930.                         'email' => $employee->getEmail(),
  4931.                         'user_id' => $employee->getUserId(),
  4932.                         'address_contact' => $employee->getAddressContact(),
  4933.                     ]
  4934.                 ]);
  4935.             }
  4936.             return new JsonResponse([
  4937.                 'success' => false,
  4938.                 'error' => 'No client or employee found for this email'
  4939.             ], 404);
  4940.         } catch (\Exception $e) {
  4941.             return new JsonResponse([
  4942.                 'success' => false,
  4943.                 'error' => $e->getMessage()
  4944.             ], 500);
  4945.         }
  4946.     }
  4947.     public function GetRoomInformationForMeetingAction(Request $request): JsonResponse
  4948.     {
  4949.         $em $this->getDoctrine()->getManager();
  4950.         $onlyAvailable $request->query->getBoolean('onlyAvailable'false);
  4951.         $rooms HumanResourceHelper::getRooms($em$onlyAvailable);
  4952.         return new JsonResponse([
  4953.             'status' => 'success',
  4954.             'data' => $rooms
  4955.         ]);
  4956.     }
  4957.     public function MeetingTypeAction(Request $request)
  4958.     {
  4959.         return new JsonResponse([
  4960.             'success' => true,
  4961.             'data' => MeetingSchedulingConstant::$meetingType
  4962.         ]);
  4963.     }
  4964.     public function GetPriorityListAction()
  4965.     {
  4966.         $priority HumanResourceHelper::priorityList();
  4967.         return new JsonResponse([
  4968.             'success' => true,
  4969.             'data' => $priority
  4970.         ]);
  4971.     }
  4972.     public function CreateTrainingScheduleAction(Request $req$action 0)
  4973.     {
  4974.         $em $this->getDoctrine()->getManager();
  4975.         $companyId $this->getLoggedUserCompanyId($req);
  4976.         $session $req->getSession();
  4977.         if ($req->request->has('XHRreq')) {
  4978.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4979.         }
  4980.         if ($action === 'list') {
  4981.             $response HumanResource::TwigDataForScheduledMeetingList($em, [1]);
  4982.             return $this->render(
  4983.                 '@Application/pages/human_resource/list/scheduled_meeting_list.html.twig',
  4984.                 [
  4985.                     'page_title' => 'Training Schedule List',
  4986.                     'list' => $response
  4987.                 ]
  4988.             );
  4989.         }
  4990.         if ($req->isMethod('GET')) {
  4991.         }
  4992.         if ($req->isMethod('POST')) {
  4993.             $approveHash $req->request->get('approvalHash');
  4994.             $approveRole $req->request->get('approvalRole');
  4995.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4996.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4997.             $companyData Company::getCompanyData($em$companyId);
  4998.             if ($isSignatureOk) {
  4999.                 $isSuccess HumanResource::createOrUpdateDataForMeetingScheduling($em$req);
  5000.                 if ($isSuccess) {
  5001.                     $options = array(
  5002.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5003.                         'notification_server' => $this->container->getParameter('notification_server'),
  5004.                         'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
  5005.                         'url' => $this->generateUrl(
  5006.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
  5007.                         )
  5008.                     );
  5009.                     $meetingId $isSuccess[1];
  5010.                     System::setApprovalInfo(
  5011.                         $this->getDoctrine()->getManager(),
  5012.                         $options,
  5013.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  5014.                         $meetingId,
  5015.                         $req->getSession()->get(UserConstants::USER_LOGIN_ID),
  5016.                         '',
  5017.                         0,
  5018.                         $this->get('mail_module')
  5019.                     );
  5020.                     System::createEditSignatureHash(
  5021.                         $this->getDoctrine()->getManager(),
  5022.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  5023.                         $meetingId,
  5024.                         $loginId,
  5025.                         $approveRole,
  5026.                         $req->request->get('approvalHash')
  5027.                     );
  5028.                     $url $this->generateUrl(
  5029.                         'view_scheduled_meeting'
  5030.                     );
  5031.                     return $this->redirect($url "/" $meetingId);
  5032.                 } else {
  5033.                     return new JsonResponse(array(
  5034.                         'success' => false
  5035.                     ));
  5036.                 }
  5037.             } else {
  5038.                 $this->addFlash(
  5039.                     'error',
  5040.                     'Invalid Approval Hash!'
  5041.                 );
  5042.                 return $this->redirectToRoute('create_training_schedule');
  5043.             }
  5044.         }
  5045.         $response HumanResource::twigDataForTrainingScheduling($em);
  5046.         return $this->render(
  5047.             '@Application/pages/human_resource/input_forms/create_training_schedule.html.twig',
  5048.             [
  5049.                 'page_title' => 'Schedule a Training',
  5050.                 'employeeIds' => $response['employeeIds'],
  5051.                 'branches' => $response['branches'],
  5052.                 'asset' => $response['asset'],
  5053.                 'rooms' => $response['rooms'],
  5054.                 'courseList' => $response['courseList'],
  5055.                 'sales_orders' => $response['salesOrders'],
  5056.                 'purchase_orders' => $response['purchaseOrders'],
  5057.                 'meeting_types' => $response['meetingType'],
  5058.                 'skillList' => $response['skillList'],
  5059.             ]
  5060.         );
  5061.     }
  5062.     public function ScheduledTrainingListAction(Request $req$action 0)
  5063.     {
  5064.         $em $this->getDoctrine()->getManager();
  5065.         $companyId $this->getLoggedUserCompanyId($req);
  5066.         $session $req->getSession();
  5067.         $response HumanResource::TwigDataForScheduledMeetingList($em, [1]);
  5068.         return $this->render(
  5069.             '@Application/pages/human_resource/list/scheduled_training_list.html.twig',
  5070.             [
  5071.                 'page_title' => 'Scheduled Trainings ',
  5072.                 'list' => $response
  5073.             ]
  5074.         );
  5075.     }
  5076.     public function ScheduledInterviewListAction(Request $req$action 0)
  5077.     {
  5078.         $em $this->getDoctrine()->getManager();
  5079.         $companyId $this->getLoggedUserCompanyId($req);
  5080.         $session $req->getSession();
  5081.         $response HumanResource::TwigDataForScheduledMeetingList($em, [2]);
  5082.         return $this->render(
  5083.             '@Application/pages/human_resource/list/scheduled_interview_list.html.twig',
  5084.             [
  5085.                 'page_title' => 'Scheduled Interviews ',
  5086.                 'list' => $response
  5087.             ]
  5088.         );
  5089.     }
  5090.     public function GetFilteredQuestionsAction(Request $request$search '')
  5091.     {
  5092.         $em $this->getDoctrine()->getManager();
  5093.         $companyId $this->getLoggedUserCompanyId($request);
  5094.         if ($search == '' || $search == '_EMPTY_') {
  5095.             $stmt $em->getConnection()->fetchAllAssociative(
  5096.                 "SELECT * FROM questionnaire WHERE 1 LIMIT 10"
  5097.             );
  5098.         } else {
  5099.             $stmt $em->getConnection()->fetchAllAssociative(
  5100.                 "SELECT * FROM questionnaire WHERE question_text LIKE :search LIMIT 10",
  5101.                 ['search' => '%' $search '%']
  5102.             );
  5103.         }
  5104.         $queryResult $stmt;
  5105.         $parent_head_ids = [];
  5106.         $queryResultIndexed = [];
  5107.         foreach ($queryResult as $dt) {
  5108.             $queryResultIndexed[$dt['question_id']] = $dt;
  5109.         }
  5110.         return new JsonResponse(array(
  5111.             'data' => $queryResult,
  5112.             'queryResultIndexed' => $queryResultIndexed,
  5113.         ));
  5114.     }
  5115.     public function CreateTrainingCourseAction(Request $request$id 0)
  5116.     {
  5117.         $em $this->getDoctrine()->getManager();
  5118.         $companyId $this->getLoggedUserCompanyId($request);
  5119.         $skills $em->getRepository('ApplicationBundle\\Entity\\Skill')->findAll();
  5120.         $courses $em->getRepository('ApplicationBundle\\Entity\\TrainingCourse')->findAll();
  5121.         if ($request->isMethod('POST')) {
  5122.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5123.             $skill = new TrainingCourse;
  5124.             $skill->setTitle($request->request->get('name'));
  5125.             $skill->setCourseHash($request->request->get('coursehash'));
  5126.             $skill->setTrainingMaterialText($request->request->get('overview'));
  5127.             $skill->setTaggedSkillHashes(json_encode($request->request->get('skill')));
  5128.             $skill->setCompanyId($companyId);
  5129.             //$skill->setEditFlag(1); //editable usually
  5130.             $skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  5131.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  5132.             //$skill->setAutocreated(0);
  5133.             $em->persist($skill);
  5134.             $em->flush();
  5135.         }
  5136.         return $this->render(
  5137.             '@Application/pages/human_resource/input_forms/create_training_course.html.twig',
  5138.             [
  5139.                 'page_title' => 'Create Training Course',
  5140.                 'skills' => $skills,
  5141.                 'courses' => $courses
  5142.             ]
  5143.         );
  5144.     }
  5145.     public function CreateEmployeeExpenseAllowanceSettingsAction(Request $request$id 0)
  5146.     {
  5147.         $em $this->getDoctrine()->getManager();
  5148.         $companyId $this->getLoggedUserCompanyId($request);
  5149.         $extDocData = [];
  5150.         $extDetailsData = [];
  5151.         if ($request->isMethod('POST')) {
  5152.             //            Generic::debugMessage($_POST);
  5153.             $em $this->getDoctrine()->getManager();
  5154.             $entity_id array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']; //change
  5155.             $dochash $request->request->get('docHash'); //change
  5156.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5157.             $approveRole $request->request->get('approvalRole');
  5158.             $approveHash $request->request->get('approvalHash');
  5159.             if (!DocValidation::isInsertable(
  5160.                 $em,
  5161.                 $entity_id,
  5162.                 $dochash,
  5163.                 $loginId,
  5164.                 $approveRole,
  5165.                 $approveHash,
  5166.                 $id
  5167.             )
  5168.             ) {
  5169.                 $this->addFlash(
  5170.                     'error',
  5171.                     'Sorry Could not insert Data.'
  5172.                 );
  5173.             } else {
  5174.                 $funcname 'EmployeeExpenseAllowanceSettings';
  5175.                 DeleteDocument::$funcname($em$id0);
  5176.                 $docId HumanResource::CreateSalarySegregationPolicy($em$request$companyId0);
  5177.                 //now add Approval info
  5178.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5179.                 $approveRole $request->request->get('approvalRole');
  5180.                 $options = array(
  5181.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5182.                     'notification_server' => $this->container->getParameter('notification_server'),
  5183.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5184.                     'url' => $this->generateUrl(
  5185.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
  5186.                     )
  5187.                 );
  5188.                 System::setApprovalInfo(
  5189.                     $this->getDoctrine()->getManager(),
  5190.                     $options,
  5191.                     array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
  5192.                     $docId,
  5193.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5194.                 );
  5195.                 System::createEditSignatureHash(
  5196.                     $this->getDoctrine()->getManager(),
  5197.                     array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
  5198.                     $docId,
  5199.                     $loginId,
  5200.                     $approveRole,
  5201.                     $request->request->get('approvalHash')
  5202.                 );
  5203.                 $doc_here $this->getDoctrine()
  5204.                     ->getRepository('ApplicationBundle\\Entity\\EmployeeExpenseAllowanceSettings')
  5205.                     ->findOneBy(
  5206.                         array(
  5207.                             'id' => $docId
  5208.                         )
  5209.                     );
  5210.                 //notify
  5211.                 $this->addFlash(
  5212.                     'success',
  5213.                     'Settings Successfully Updated.'
  5214.                 );
  5215.                 $url $this->generateUrl(
  5216.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
  5217.                 );
  5218.                 System::AddNewNotification(
  5219.                     $this->container->getParameter('notification_enabled'),
  5220.                     $this->container->getParameter('notification_server'),
  5221.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  5222.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  5223.                     "Salary Segregation Policy : " $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  5224.                     'pos',
  5225.                     System::getPositionIdsByDepartment($emGeneralConstant::HRM_DEPARTMENT),
  5226.                     'success',
  5227.                     //                    $url . "/" . $TransID,
  5228.                     $url "/" $docId,
  5229.                     "Journal"
  5230.                 );
  5231.                 return $this->redirect($url "/" $docId);
  5232.             }
  5233.         }
  5234.         //for edits
  5235.         if ($id == 0) {
  5236.         } else {
  5237.             $extDocData $em->getRepository('ApplicationBundle\\Entity\\EmployeeExpenseAllowanceSettings')->findOneBy(
  5238.                 array(
  5239.                     'id' => $id///material
  5240.                 )
  5241.             );
  5242.             //now if its not editable, redirect to view
  5243.             if ($extDocData) {
  5244.                 if ($extDocData->getEditFlag() != 1) {
  5245. //          $url = $this->generateUrl(
  5246. ////              'view_salary_segregation_policy'
  5247. //              'salary_segregation_policy'
  5248. //          );
  5249. //          return $this->redirect($url . "/" . $id);
  5250.                 } else {
  5251. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  5252. //          $extDetailsData = $em->getRepository('ApplicationBundle\\Entity\\SalarySegregationPolicy')->findOneBy(
  5253. //              array(
  5254. //                  'transactionId' => $id, ///material
  5255. //
  5256. //              )
  5257. //          );
  5258.                 }
  5259.             } else {
  5260.             }
  5261.         }
  5262.         $employeeIds $em->getRepository("ApplicationBundle\\Entity\\Employee")->findAll();
  5263.         $employeeType HumanResourceConstant::$employeeType;
  5264.         $employeeExpenseAllowanceTypes HumanResourceConstant::$employeeExpenseAllowanceTypes;
  5265.         $Designation $em->getRepository("ApplicationBundle\\Entity\\SysDepartmentPosition")->findAll();
  5266.         $branch $em->getRepository("ApplicationBundle\\Entity\\Branch")->findAll();
  5267.         $departments $em->getRepository("ApplicationBundle\\Entity\\SysDepartment")->findAll();
  5268.         $department = [];
  5269.         foreach ($departments as $entry) {
  5270.             $department[$entry->getDepartmentId()] = array(
  5271.                 'id' => $entry->getDepartmentId(),
  5272.                 'name' => $entry->getDepartmentName(),
  5273.             );
  5274.         }
  5275.         return $this->render(
  5276.             '@Application/pages/human_resource/input_forms/create_employee_expense_allowance_settings.html.twig',
  5277.             [
  5278.                 'page_title' => 'Employee Expense Allowance Settings',
  5279.                 'employeeIds' => $employeeIds,
  5280.                 'extId' => $id,
  5281.                 'extDocData' => $extDocData,
  5282.                 'employeeType' => $employeeType,
  5283.                 'employeeExpenseAllowanceTypes' => $employeeExpenseAllowanceTypes,
  5284.                 'Designation' => $Designation,
  5285.                 'branch' => $branch,
  5286.                 'department' => $department,
  5287.             ]
  5288.         );
  5289.     }
  5290.     public function EmployeeExpenseAllowanceSettingsListAction(Request $request)
  5291.     {
  5292.         $em $this->getDoctrine()->getManager();
  5293.         $allowed_ids = [];
  5294.         $companyId $this->getLoggedUserCompanyId($request);
  5295.         $listData HumanResource::GetDataForEmployeeExpenseAllowanceSettingsListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5296.         if ($request->isMethod('POST')) {
  5297.             if ($request->query->has('dataTableQry')) {
  5298.                 return new JsonResponse(
  5299.                     $listData
  5300.                 );
  5301.             }
  5302.         }
  5303.         return $this->render('@Application/pages/human_resource/list/employee_expense_allowance_settings_list.html.twig',
  5304. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5305.             array(
  5306.                 'page_title' => 'Expense Allowance Settings List',
  5307. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5308. //            'client_types' => Client::GetClientType($em, $companyId),
  5309. //            'region_list' => Client::RegionList($em, $companyId),
  5310. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5311.             )
  5312.         );
  5313.     }
  5314.     public function salarySegAction(Request $request$id 0)
  5315.     {
  5316.         $em $this->getDoctrine()->getManager();
  5317.         $companyId $this->getLoggedUserCompanyId($request);
  5318.         $extDocData = [];
  5319.         $extDetailsData = [];
  5320.         if ($request->isMethod('POST')) {
  5321.             //            Generic::debugMessage($_POST);
  5322.             $em $this->getDoctrine()->getManager();
  5323.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']; //change
  5324.             $dochash $request->request->get('docHash'); //change
  5325.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5326.             $approveRole $request->request->get('approvalRole');
  5327.             $approveHash $request->request->get('approvalHash');
  5328.             if (!DocValidation::isInsertable(
  5329.                 $em,
  5330.                 $entity_id,
  5331.                 $dochash,
  5332.                 $loginId,
  5333.                 $approveRole,
  5334.                 $approveHash,
  5335.                 $id
  5336.             )
  5337.             ) {
  5338.                 $this->addFlash(
  5339.                     'error',
  5340.                     'Sorry Couldnot insert Data.'
  5341.                 );
  5342.             } else {
  5343.                 $funcname 'SalarySegregationPolicy';
  5344.                 DeleteDocument::$funcname($em$id0);
  5345.                 $docId HumanResource::CreateSalarySegregationPolicy($em$request$companyId0);
  5346.                 //now add Approval info
  5347.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5348.                 $approveRole $request->request->get('approvalRole');
  5349.                 $options = array(
  5350.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5351.                     'notification_server' => $this->container->getParameter('notification_server'),
  5352.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5353.                     'url' => $this->generateUrl(
  5354.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']]['entity_view_route_path_name']
  5355.                     )
  5356.                 );
  5357.                 System::setApprovalInfo(
  5358.                     $this->getDoctrine()->getManager(),
  5359.                     $options,
  5360.                     array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
  5361.                     $docId,
  5362.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5363.                     3    //journal voucher
  5364.                 );
  5365.                 System::createEditSignatureHash(
  5366.                     $this->getDoctrine()->getManager(),
  5367.                     array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
  5368.                     $docId,
  5369.                     $loginId,
  5370.                     $approveRole,
  5371.                     $request->request->get('approvalHash')
  5372.                 );
  5373.                 $doc_here $this->getDoctrine()
  5374.                     ->getRepository('ApplicationBundle\\Entity\\SalarySegregationPolicy')
  5375.                     ->findOneBy(
  5376.                         array(
  5377.                             'id' => $docId
  5378.                         )
  5379.                     );
  5380.                 //notify
  5381.                 $this->addFlash(
  5382.                     'success',
  5383.                     'Policy Successfully Updated.'
  5384.                 );
  5385.                 $url $this->generateUrl(
  5386.                     'salary_segregation_policy'
  5387.                 );
  5388.                 System::AddNewNotification(
  5389.                     $this->container->getParameter('notification_enabled'),
  5390.                     $this->container->getParameter('notification_server'),
  5391.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  5392.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  5393.                     "Salary Segregation Policy : " $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  5394.                     'pos',
  5395.                     System::getPositionIdsByDepartment($emGeneralConstant::HRM_DEPARTMENT),
  5396.                     'success',
  5397.                     //                    $url . "/" . $TransID,
  5398.                     $url "/" $docId,
  5399.                     "Journal"
  5400.                 );
  5401.                 return $this->redirect($url "/" $docId);
  5402.             }
  5403.         }
  5404.         //for edits
  5405.         if ($id == 0) {
  5406.         } else {
  5407.             $extDocData $em->getRepository('ApplicationBundle\\Entity\\SalarySegregationPolicy')->findOneBy(
  5408.                 array(
  5409.                     'id' => $id///material
  5410.                 )
  5411.             );
  5412.             //now if its not editable, redirect to view
  5413.             if ($extDocData) {
  5414.                 if ($extDocData->getEditFlag() != 1) {
  5415. //          $url = $this->generateUrl(
  5416. ////              'view_salary_segregation_policy'
  5417. //              'salary_segregation_policy'
  5418. //          );
  5419. //          return $this->redirect($url . "/" . $id);
  5420.                 } else {
  5421. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  5422. //          $extDetailsData = $em->getRepository('ApplicationBundle\\Entity\\SalarySegregationPolicy')->findOneBy(
  5423. //              array(
  5424. //                  'transactionId' => $id, ///material
  5425. //
  5426. //              )
  5427. //          );
  5428.                 }
  5429.             } else {
  5430.             }
  5431.         }
  5432.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  5433.         $employeeType HumanResourceConstant::$employeeType;
  5434.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  5435.         $branch $em->getRepository(Branch::class)->findAll();
  5436.         $departments $em->getRepository(SysDepartment::class)->findAll();
  5437.         $department = [];
  5438.         foreach ($departments as $entry) {
  5439.             $department[$entry->getDepartmentId()] = array(
  5440.                 'id' => $entry->getDepartmentId(),
  5441.                 'name' => $entry->getDepartmentName(),
  5442.             );
  5443.         }
  5444.         return $this->render(
  5445.             '@Application/pages/human_resource/input_forms/salary_segregation_policy.html.twig',
  5446.             [
  5447.                 'page_title' => 'Salary Segregation Policy',
  5448.                 'employeeIds' => $employeeIds,
  5449.                 'extId' => $id,
  5450.                 'extDocData' => $extDocData,
  5451.                 'employeeType' => $employeeType,
  5452.                 'Designation' => $Designation,
  5453.                 'branch' => $branch,
  5454.                 'department' => $department,
  5455.             ]
  5456.         );
  5457.     }
  5458.     public function GetSalarySegregationDataForEmployeeEntryAction(Request $request)
  5459.     {
  5460.         $em $this->getDoctrine()->getManager();
  5461.         $companyId $this->getLoggedUserCompanyId($request);
  5462.         if ($request->request->has('salSagDataReq')) {
  5463.             $ajaxData HumanResource::handelXhrForSalSeg($em$request);
  5464.             return new JsonResponse($ajaxData);
  5465.         }
  5466.         return new JsonResponse(array('success' => false));
  5467.     }
  5468.     public function WorkHourPolicyAction(Request $req$id 0)
  5469.     {
  5470.         $em $this->getDoctrine()->getManager();
  5471.         $companyId $this->getLoggedUserCompanyId($req);
  5472.         $extData = [];
  5473.         if ($id != 0) {
  5474.             $extData $em->getRepository('ApplicationBundle\\Entity\\WorkHourPolicy')
  5475.                 ->findOneBy(
  5476.                     array(
  5477.                         'id' => $id
  5478.                     )
  5479.                 );
  5480.         }
  5481.         if ($req->isMethod('POST')) {
  5482.             $storeDataRes HumanResource::checkSignature($em$req);
  5483.             if ($storeDataRes['hasErr']) {
  5484.                 $msg $storeDataRes['msg'];
  5485.                 $this->addFlash(
  5486.                     'error',
  5487.                     $msg
  5488.                 );
  5489.                 return $this->redirectToRoute('work_hour_policy');
  5490.             } else {
  5491.                 HumanResource::storeDataForWhPolicy($em$req$companyId);
  5492.                 $this->addFlash(
  5493.                     'success',
  5494.                     'Policy Successfully Created!'
  5495.                 );
  5496.                 return $this->redirectToRoute('work_hour_policy');
  5497.             }
  5498.         }
  5499.         $twigData HumanResource::twigDataForWorkHourPolicy($em);
  5500.         $timeZonesArray = array();
  5501.         return $this->render(
  5502.             '@Application/pages/human_resource/input_forms/work_hour_policy.html.twig',
  5503.             [
  5504.                 'page_title' => 'Work Hour Policy',
  5505.                 'extId' => $id,
  5506.                 'extData' => $extData,
  5507.                 'employeeIds' => $twigData['employeeIds'],
  5508.                 'employeeType' => $twigData['employeeType'],
  5509.                 'Designation' => $twigData['Designation'],
  5510.                 'branch' => $twigData['branch'],
  5511.                 'department' => $twigData['department'],
  5512.             ]
  5513.         );
  5514.     }
  5515.     public function WorkHourPolicyListAction(Request $request)
  5516.     {
  5517.         $em $this->getDoctrine()->getManager();
  5518.         $allowed_ids = [];
  5519.         $companyId $this->getLoggedUserCompanyId($request);
  5520.         $listData HumanResource::GetDataForWorkHourPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5521.         if ($request->isMethod('POST')) {
  5522.             if ($request->query->has('dataTableQry')) {
  5523.                 return new JsonResponse(
  5524.                     $listData
  5525.                 );
  5526.             }
  5527.         }
  5528.         return $this->render('@Application/pages/human_resource/list/work_hour_policy_list.html.twig',
  5529. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5530.             array(
  5531.                 'page_title' => 'Work Hour Policy List',
  5532. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5533. //            'client_types' => Client::GetClientType($em, $companyId),
  5534. //            'region_list' => Client::RegionList($em, $companyId),
  5535. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5536.             )
  5537.         );
  5538.     }
  5539.     public function WorkPlacePolicyListAction(Request $request)
  5540.     {
  5541.         $em $this->getDoctrine()->getManager();
  5542.         $workplacePolicyDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeWorkplace')->findAll();
  5543. //        $employee = $em->getRepository('ApplicationBundle\\Entity\\Employee')->findAll();
  5544.         return $this->render('@Application/pages/human_resource/list/work_place_policy_list.html.twig', array(
  5545.             'page_title' => 'Work Place Policy List',
  5546.             'workplacePolicyDetails' => $workplacePolicyDetails,
  5547. //            'employee'=>$employee
  5548.         ));
  5549.     }
  5550.     public function workPlacePolicyAction(Request $data$id)
  5551.     {
  5552.         $em $this->getDoctrine()->getManager();
  5553.         $workPlacePolicy $em->getRepository('ApplicationBundle\\Entity\\EmployeeWorkplace')->find($id);
  5554.         $employee $em->getRepository(Employee::class)->findAll();
  5555.         $Approval_data System::checkIfApprovalExists(
  5556.             $em,
  5557.             array_flip(GeneralConstant::$Entity_list)['EmployeeWorkplace'],
  5558.             $id,
  5559.             $data->getSession()->get(UserConstants::USER_LOGIN_ID)
  5560.         );
  5561.         $ApprovalStatus GeneralConstant::$approvalStatus;
  5562.         return $this->render('@Application/pages/human_resource/views/viewWorkPlacePolicy.html.twig', array(
  5563.             'page_title' => 'Work Place Policy  View',
  5564.             'workPlacePolicy' => $workPlacePolicy,
  5565.             'employee' => $employee,
  5566.             'approval_data' => $Approval_data,
  5567.             'approval_status' => $workPlacePolicy->getApproved(),
  5568.             'id' => $id,
  5569.         ));
  5570.     }
  5571.     public function SalarySegregationPolicyListAction(Request $request)
  5572.     {
  5573.         $em $this->getDoctrine()->getManager();
  5574.         $allowed_ids = [];
  5575.         $companyId $this->getLoggedUserCompanyId($request);
  5576.         $listData HumanResource::GetDataForSalarySegregationPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5577.         if ($request->isMethod('POST')) {
  5578.             if ($request->query->has('dataTableQry')) {
  5579.                 return new JsonResponse(
  5580.                     $listData
  5581.                 );
  5582.             }
  5583.         }
  5584.         return $this->render('@Application/pages/human_resource/list/salary_segregation_policy_list.html.twig',
  5585. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5586.             array(
  5587.                 'page_title' => 'Salary Segregation Policy List',
  5588. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5589. //            'client_types' => Client::GetClientType($em, $companyId),
  5590. //            'region_list' => Client::RegionList($em, $companyId),
  5591. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5592.             )
  5593.         );
  5594.     }
  5595.     public function HolidayCalendarListAction(Request $request)
  5596.     {
  5597.         $q $this->getDoctrine()
  5598.             ->getRepository('ApplicationBundle\\Entity\\HolidayCalendar')
  5599.             ->findBy(
  5600.                 array(
  5601. //                'status' => GeneralConstant::ACTIVE,
  5602.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5603. //                    'approved' =>  GeneralConstant::APPROVED,
  5604.                 )
  5605.             );
  5606.         $stage_list = array(
  5607.             => 'Pending',
  5608.             => 'Pending',
  5609.             => 'Complete',
  5610.             => 'Partial',
  5611.         );
  5612.         $data = [];
  5613.         foreach ($q as $entry) {
  5614.             $data[] = array(
  5615. //          'doc_date' => $entry->getSalesReplacementDate(),
  5616.                 'id' => $entry->getHolidayCalendarId(),
  5617.                 'title' => $entry->getHoliDayTitle(),
  5618.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5619. //          'stage' => $stage_list[$entry->getStage()]
  5620.             );
  5621.         }
  5622.         return $this->render('@Application/pages/human_resource/list/holiday_calendar_list.html.twig',
  5623.             array(
  5624.                 'page_title' => 'Holiday Calendar List',
  5625.                 'data' => $data
  5626.             )
  5627.         );
  5628.     }
  5629.     public function PayrollPolicyListAction(Request $request)
  5630.     {
  5631.         $em $this->getDoctrine()->getManager();
  5632.         $allowed_ids = [];
  5633.         $companyId $this->getLoggedUserCompanyId($request);
  5634.         $listData HumanResource::GetDataForPayrollPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5635.         if ($request->isMethod('POST')) {
  5636.             if ($request->query->has('dataTableQry')) {
  5637.                 return new JsonResponse(
  5638.                     $listData
  5639.                 );
  5640.             }
  5641.         }
  5642.         return $this->render('@Application/pages/human_resource/list/payroll_policy_list.html.twig',
  5643. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5644.             array(
  5645.                 'page_title' => 'Payroll Policy List',
  5646. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5647. //            'client_types' => Client::GetClientType($em, $companyId),
  5648. //            'region_list' => Client::RegionList($em, $companyId),
  5649. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5650.             )
  5651.         );
  5652.     }
  5653.     public function payslipAction(Request $req$action 0$id 0)
  5654.     {
  5655.         $em $this->getDoctrine()->getManager();
  5656.         $attendanceSource HumanResourceConstant::$attendanceSources;
  5657.         // The bare `payslip` route carries no action default, so a plain GET used to match none of
  5658.         // the branches below and fall out of the function returning null (a 500). It is reachable:
  5659.         // ModuleConstant registers it as the "Payslip" Spotlight module, and disburse_salary.html
  5660.         // POSTs to it to save signatures. Treat a bare GET as the list â€” what "Payslip" means â€”
  5661.         // and leave the POST path alone.
  5662.         if (!$action && !$req->isMethod('POST')) {
  5663.             $action 'list';
  5664.         }
  5665.         if ($action === 'list') {
  5666.             $response HumanResource::twigDataForPayslipList($em);
  5667.             $approval_status GeneralConstant::$approvalAction;
  5668.             return $this->render(
  5669.                 '@Application/pages/human_resource/list/payslip_list.html.twig',
  5670.                 [
  5671.                     'page_title' => 'Payslip List',
  5672.                     'reports' => $response,
  5673.                     'approval_status' => $approval_status
  5674.                 ]
  5675.             );
  5676.         }
  5677.         if ($action === 'view') {
  5678.             $response HumanResource::twigDataForPayslipViewAndPrint($em$req$id);
  5679.             return $this->render(
  5680.                 '@Application/pages/human_resource/views/payslip_view.html.twig',
  5681.                 [
  5682.                     'page_title' => 'View Payslip',
  5683.                     'approval_data' => $response['approval_data'],
  5684.                     'payslip' => $response['payslip'],
  5685.                     'bankAccount' => $response['bankAccount'],
  5686.                     'tin' => $response['tin'],
  5687.                     'employeeCode' => $response['employeeCode'],
  5688.                     'emp_code' => $response['employeeCode'],
  5689.                     'employee_code' => $response['employeeCode'],
  5690.                     'earningValues' => $response['earningValues'],
  5691.                     'facilityValues' => $response['facilityValues'],
  5692.                     'deductionValues' => $response['deductionValues'],
  5693.                     'document_log' => $response['document_log'],
  5694.                     'approval_status' => $response['approval_status'],
  5695.                     'created_by' => $response['created_by'],
  5696.                     'updated_at' => $response['updated_at'],
  5697.                     'employeeId' => $response['employeeId'],
  5698.                     'totalAttendance' => $response['totalPresent'],
  5699.                     'leaveList' => HumanResourceConstant::$LeaveType,
  5700.                     'AttReportData' => $response['AttReportData'],
  5701. //                    'attendanceLog' => $response['attendanceLog'],
  5702.                     'attendanceSource' => $attendanceSource,
  5703.                     'statutory_lines' => $response['statutory_lines'],
  5704.                     'statutory_total' => $response['statutory_total'],
  5705.                     'statutory_employer_total' => $response['statutory_employer_total'],
  5706.                     'statutory_country' => $response['statutory_country'],
  5707.                     'auto_created' => 0,
  5708.                 ]
  5709.             );
  5710.         }
  5711.         if ($action === 'print') {
  5712.             $em $this->getDoctrine()->getManager();
  5713.             $company_data Company::getCompanyData($em1);
  5714.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['Payslip'], $id);
  5715.             $response HumanResource::twigDataForPayslipViewAndPrint($em$req$id);
  5716.             return $this->render(
  5717.                 '@Application/pages/human_resource/print/payslip_print.html.twig',
  5718.                 array(
  5719.                     'page_title' => 'Print Payslip',
  5720.                     'export' => 'pdf,print',
  5721.                     'payslip' => $response['payslip'],
  5722.                     'bankAccount' => $response['bankAccount'],
  5723.                     'tin' => $response['tin'],
  5724.                     'employeeCode' => $response['employeeCode'],
  5725.                     'emp_code' => $response['employeeCode'],
  5726.                     'employee_code' => $response['employeeCode'],
  5727.                     'earningValues' => $response['earningValues'],
  5728.                     'facilityValues' => $response['facilityValues'],
  5729.                     'deductionValues' => $response['deductionValues'],
  5730.                     'company_name' => $company_data->getName(),
  5731.                     'company_data' => $company_data,
  5732.                     'company_address' => $company_data->getAddress(),
  5733.                     'company_image' => $company_data->getImage(),
  5734.                     'Authorizations' => $Authorizations,
  5735.                     'totalAttendance' => $response['totalPresent'],
  5736.                     'leaveList' => HumanResourceConstant::$LeaveType,
  5737.                     'AttReportData' => $response['AttReportData'],
  5738.                     'attendanceSource' => $attendanceSource,
  5739.                     'statutory_lines' => $response['statutory_lines'],
  5740.                     'statutory_total' => $response['statutory_total'],
  5741.                     'statutory_employer_total' => $response['statutory_employer_total'],
  5742.                     'statutory_country' => $response['statutory_country'],
  5743.                     'red' => 0
  5744.                 )
  5745.             );
  5746.         }
  5747.         if ($req->isMethod('POST')) {
  5748.             // TEMP DEBUG â€” capture the raw posted disburse payload (controller reloads reliably)
  5749.             @file_put_contents($this->get('kernel')->getLogDir() . '/payslip_post_dbg.log',
  5750.                 '[' date('H:i:s') . '] rowCount=' . (is_array($req->get('relevantEmployeeDataArray')) ? count($req->get('relevantEmployeeDataArray')) : 'not-array') .
  5751.                 ' | firstRow=' substr(json_encode($req->get('relevantEmployeeDataArray')[0] ?? 'MISSING'), 0600) . "\n"FILE_APPEND);
  5752.             $sigRes HumanResource::checkSignature($em$req);
  5753.             if ($sigRes['hasErr']) {
  5754.                 $msg $sigRes['msg'];
  5755.                 return new JsonResponse(['success' => false'msg' => $msg]);
  5756.             }
  5757.             HumanResource::storeDataForPayslip($em$req);
  5758.             return new JsonResponse(['success' => true]);
  5759.         }
  5760.         // Never fall through returning null â€” an unknown action is a 404, not a 500.
  5761.         throw $this->createNotFoundException('Unknown payslip action.');
  5762.     }
  5763.     public function applicantInfoAction(Request $request$id)
  5764.     {
  5765.         $em $this->getDoctrine()->getManager('company_group');
  5766.         $session $request->getSession();
  5767.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
  5768.         $skillDetails $em->getRepository(EntitySkill::class)->findAll();
  5769.         $companyId $this->getLoggedUserCompanyId($request);
  5770.         $gender HumanResourceConstant::$sex;
  5771.         $blood HumanResourceConstant::$BloodGroup;
  5772.         $userId $session->get(UserConstants::USER_ID);
  5773.         $encData $request->query->has('ref') ? $request->query->get('ref') : '';
  5774.         $education = array(
  5775.             'instituteName' => $request->get('instituteName'),
  5776.             'courseOfStudy' => $request->get('courseOfStudy'),
  5777.             'courseStartDate' => $request->get('courseStartDate'),
  5778.             'courseEndDate' => $request->get('courseEndDate'),
  5779.             'result' => $request->get('result'),
  5780.             'grade' => $request->get('grade'),
  5781.             'degree' => $request->get('degree'),
  5782.         );
  5783.         $workExperience = array(
  5784.             'title' => $request->get('title'),
  5785.             'companyName' => $request->get('companyName'),
  5786.             'jobStartDate' => $request->get('jobStartDate'),
  5787.             'jobEndDate' => $request->get('jobEndDate'),
  5788.             'description' => $request->get('description'),
  5789.         );
  5790.         $certificate = array(
  5791.             'certificatename' => $request->get('certificatename'),
  5792.             'issuedDate' => $request->get('issuedDate'),
  5793.         );
  5794.         $courses = array(
  5795.             'courseName' => $request->get('courseName'),
  5796.             'date' => $request->get('date'),
  5797.             'duration' => $request->get('duration')
  5798.         );
  5799.         $languages = array(
  5800.             'languageName' => $request->get('languageName'),
  5801.             'writtenSkill' => $request->get('writtenSkill'),
  5802.             'verbalSkill' => $request->get('verbalSkill'),
  5803.         );
  5804.         if ($request->isMethod('POST')) {
  5805.             if ($consultantDetails)
  5806.                 $consultant $consultantDetails;
  5807.             else
  5808.                 $consultant = new EntityApplicantDetails();
  5809.             $consultant->setApplicationText($request->request->get('applicationText'));
  5810.             $consultant->setFirstname($request->request->get('firstname'));
  5811.             $consultant->setLastname($request->request->get('lastname'));
  5812.             $consultant->setIsImgLegal($request->request->get('is_img_legal'));
  5813.             $consultant->setNid($request->request->get('nid'));
  5814.             $consultant->setDob(new \DateTime($request->get('dob')));
  5815.             $consultant->setSex($request->request->get('sex'));
  5816.             $consultant->setFather($request->request->get('father'));
  5817.             $consultant->setMother($request->request->get('mother'));
  5818.             $consultant->setBlood($request->request->get('blood'));
  5819.             $consultant->setPhone($request->request->get('phone'));
  5820.             $consultant->setCountry($request->request->get('country'));
  5821.             $consultant->setPostalCode($request->request->get('postalCode'));
  5822.             $consultant->setCurrAddr($request->request->get('curr_addr'));
  5823.             $consultant->setSkill(json_encode($request->request->get('skill')));
  5824.             $consultant->setEmergencyContactNumber($request->request->get('emm_contact'));
  5825.             $consultant->setCurrentEmployment($request->request->get('currentEmployment'));
  5826.             $consultant->setTin($request->request->get('tin'));
  5827.             $consultant->setEducationData(json_encode($education));
  5828.             $consultant->setWorkExperienceData(json_encode($workExperience));
  5829.             $consultant->setCertificateData(json_encode($certificate));
  5830.             $consultant->setCoursesData(json_encode($courses));
  5831.             $consultant->setLanguagesData(json_encode($languages));
  5832.             $consultant->setWorkExperienceYear($request->request->get('workExperienceYear'));
  5833.             //$consultant->setApplyForConsultant(1);
  5834.             $em->persist($consultant);
  5835.             $em->flush();
  5836.             $path "";
  5837.             $defaultProductImage '';
  5838.             $uploadedFile null;
  5839.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/applicantCv/';
  5840.             $uploadedFile $request->files->get('docUpload');
  5841.             if ($uploadedFile != null) {
  5842.                 $fileName 'cv' $consultantDetails->getApplicantId() . '.' $uploadedFile->guessExtension();
  5843.                 $path $fileName;
  5844. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  5845.                 if (!file_exists($upl_dir)) {
  5846.                     mkdir($upl_dir0777true);
  5847.                 }
  5848.                 $uploadedFile->move($upl_dir$path);
  5849.                 $defaultProductImage 'uploads/applicantCv/' $path;
  5850.                 $consultant->setDocImage($defaultProductImage);
  5851.                 $em->flush();
  5852.             }
  5853.             $this->addFlash(
  5854.                 'success',
  5855.                 'Data Updated.'
  5856.             );
  5857.             if ($encData != '') {
  5858.                 $url $this->generateUrl(
  5859.                     'applicant_job_recruitment_view'
  5860.                 );
  5861.                 return $this->redirect($url '?auto_apply=1&encData=' $encData);
  5862.             }
  5863.             $url $this->generateUrl(
  5864.                 'job_recruitment_list_applicant'
  5865.             );
  5866.             return $this->redirect($url);
  5867.         }
  5868.         return $this->render('@Application/pages/human_resource/input_forms/applicant_info.html.twig', array(
  5869.             'page_title' => 'My Information ',
  5870.             'gender' => $gender,
  5871.             'blood' => $blood,
  5872.             'consultantDetails' => $consultantDetails,
  5873.             'education' => json_decode($consultantDetails->getEducationData(), true),
  5874.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  5875.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  5876.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  5877.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  5878.             'skill' => json_decode($consultantDetails->getSkill(), true),
  5879.             'skillDetails' => $skillDetails
  5880.         ));
  5881. //        $em = $this->getDoctrine()->getManager('company_group');
  5882. //        $applicantRepo = $em->getRepository(EntityApplicantDetails::class);
  5883. //        $skillDetails = $em->getRepository(EntitySkill::class)->findAll();
  5884. //
  5885. //
  5886. //        if ($req->isMethod('POST')) {
  5887. //            $applicant = $applicantRepo->find($id);
  5888. //
  5889. //            if ($req->files->get('img')) {
  5890. //                $ImgName = HumanResource::StoreFiles($req->files->get('img'), 'Applicant');
  5891. //                $applicant->setImage($ImgName);
  5892. //            }
  5893. //
  5894. //            $applicant->setFirstname($req->request->get('firstname'));
  5895. //            $applicant->setLastname($req->request->get('lastname'));
  5896. //            $applicant->setIsImgLegal($req->request->get('is_img_legal'));
  5897. //            $applicant->setNid($req->request->get('nid'));
  5898. //            $applicant->setDob(HumanResource::StringToDate($req->request->get('dob')));
  5899. //            $applicant->setSex($req->request->get('sex'));
  5900. //            $applicant->setFather($req->request->get('father'));
  5901. //            $applicant->setMother($req->request->get('mother'));
  5902. //            $applicant->setSpouse($req->request->get('spouse'));
  5903. //            $applicant->setChild1($req->request->get('child_1'));
  5904. //            $applicant->setChild2($req->request->get('child_2'));
  5905. //            $applicant->setBlood($req->request->get('blood'));
  5906. //            $applicant->setPhone($req->request->get('phone'));
  5907. //            $applicant->setOAuthEmail($req->request->get('oauth_email'));
  5908. //            $applicant->setCurrAddr($req->request->get('curr_addr'));
  5909. //            $applicant->setPermAddr($req->request->get('perm_addr'));
  5910. //            $applicant->setEmmContact($req->request->get('emm_contact'));
  5911. //
  5912. //            $applicant->setInst1($req->request->get('inst1'));
  5913. //            $applicant->setYr1($req->request->get('yr1'));
  5914. //            $applicant->setDur1($req->request->get('dur1'));
  5915. //            $applicant->setInst2($req->request->get('inst2'));
  5916. //            $applicant->setYr2($req->request->get('yr2'));
  5917. //            $applicant->setDur2($req->request->get('dur2'));
  5918. //            $applicant->setInst3($req->request->get('inst3'));
  5919. //            $applicant->setYr3($req->request->get('yr3'));
  5920. //            $applicant->setDur3($req->request->get('dur3'));
  5921. //            $applicant->setEinst1($req->request->get('einst1'));
  5922. //            $applicant->setEyr1($req->request->get('eyr1'));
  5923. //            $applicant->setEdeg1($req->request->get('edeg1'));
  5924. //            $applicant->setEinst2($req->request->get('einst2'));
  5925. //            $applicant->setEyr2($req->request->get('eyr2'));
  5926. //            $applicant->setEdeg2($req->request->get('edeg2'));
  5927. //            $applicant->setEinst3($req->request->get('einst3'));
  5928. //            $applicant->setEyr3($req->request->get('eyr3'));
  5929. //            $applicant->setEdeg3($req->request->get('edeg3'));
  5930. //
  5931. //            $em->persist($applicant);
  5932. //            $em->flush();
  5933. //
  5934. //            return $this->render(
  5935. //                'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
  5936. //                [
  5937. //                    'page_title' => 'Applicant Info',
  5938. //                    'applicant_info' => $applicant,
  5939. //                    'blood' => HumanResourceConstant::$BloodGroup,
  5940. //                    'gender' => HumanResourceConstant::$sex,
  5941. //                    'skillDetails' => $skillDetails,
  5942. //                    'HasUpdateMode' => true,
  5943. //                ]
  5944. //            );
  5945. //        }
  5946. //
  5947. //        if ($id) {
  5948. //            $applicant = $applicantRepo->find($id);
  5949. //
  5950. //            return $this->render(
  5951. //                'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
  5952. //                [
  5953. //                    'page_title' => 'Applicant Info',
  5954. //                    'applicant_info' => $applicant,
  5955. //                    'blood' => HumanResourceConstant::$BloodGroup,
  5956. //                    'gender' => HumanResourceConstant::$sex,
  5957. //                    'skillDetails' => $skillDetails,
  5958. //                    'HasUpdateMode' => false,
  5959. //                ]
  5960. //            );
  5961. //        }
  5962. //
  5963. //        $google_client = new Google_Client();
  5964. //        $google_client->setClientId('916737688016-l2qfmb9p37cumudkaqpu8s7ndngq9una.apps.googleusercontent.com');
  5965. //        $google_client->setClientSecret('BEWpEBRvv3-hSoB4cGBrVB3z');
  5966. //        $google_client->setRedirectUri('http://localhost/applicant_info');
  5967. //        $google_client->addScope('email');
  5968. //        $google_client->addScope('profile');
  5969.     }
  5970.     public function applicantDashboardAction()
  5971.     {
  5972.         return new JsonResponse(['this is applicant dashboard']);
  5973.     }
  5974.     public function resignApplicationAction(Request $req$id)
  5975.     {
  5976.         $em $this->getDoctrine()->getManager();
  5977.         if ($req->request->has('xhrReq')) {
  5978.             $response HumanResource::HandelXhrForResignApplication($em$req);
  5979.             return new JsonResponse($response);
  5980.         }
  5981.         if ($req->isMethod('GET')) {
  5982.             $applicant $em->getRepository(EmployeeDetails::class)->findBy(['emp_status' => 1]);
  5983.             $resignReason HumanResourceConstant::$resignReason;
  5984.             return $this->render(
  5985.                 '@Application/pages/human_resource/input_forms/resign_application.html.twig',
  5986.                 [
  5987.                     'page_title' => 'Resign Application',
  5988.                     'employeeIds' => $applicant,
  5989.                     'resignReasons' => $resignReason,
  5990.                     'HasUpdateMode' => false,
  5991.                 ]
  5992.             );
  5993.         }
  5994.         if ($req->isMethod('POST')) {
  5995.             $approveHash $req->request->get('approvalHash');
  5996.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  5997.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  5998.             if ($isSignatureOk) {
  5999.                 $response HumanResource::storeResignApplicationData($em$req);
  6000.                 if ($response) {
  6001.                     return $this->redirectToRoute(
  6002.                         'view_resign_application',
  6003.                         array('id' => $response->getResignApplicationId()),
  6004.                         Response::HTTP_MOVED_PERMANENTLY
  6005.                     );
  6006.                 }
  6007.             } else {
  6008.                 $this->addFlash(
  6009.                     'error',
  6010.                     'Invalid Approval Hash!'
  6011.                 );
  6012.                 return $this->redirectToRoute('resign_application');
  6013.             }
  6014.         }
  6015.     }
  6016.     public function viewResignApplicationAction(Request $req$id 0)
  6017.     {
  6018.         $em $this->getDoctrine()->getManager();
  6019.         $response HumanResource::twigDataForResignApplicationView($em$req$id);
  6020.         return $this->render(
  6021.             '@Application/pages/human_resource/views/resign_application_view.html.twig',
  6022.             [
  6023.                 'page_title' => 'View Resign Application',
  6024.                 'approval_data' => $response['approval_data'],
  6025.                 'application' => $response['application'],
  6026.                 'applicant' => $response['applicant'],
  6027.                 'document_log' => $response['document_log'],
  6028.                 'approval_status' => $response['approval_status'],
  6029.                 'created_by' => $response['created_by'],
  6030.                 'updated_at' => $response['updated_at'],
  6031.                 'auto_created' => 0,
  6032.             ]
  6033.         );
  6034.     }
  6035.     public function printResignApplicationAction(Request $req$id)
  6036.     {
  6037.         if ($id) {
  6038.             $em $this->getDoctrine()->getManager();
  6039.             $company_data Company::getCompanyData($em1);
  6040.             $authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['ResignApplication'], $id);
  6041.             $response HumanResource::twigDataForResignApplicationView($em$req$id);
  6042.             return $this->render(
  6043.                 '@Application/pages/human_resource/print/resign_application_print.html.twig',
  6044.                 array(
  6045.                     'page_title' => 'Print Resign Application',
  6046.                     'export' => 'pdf,print',
  6047.                     'company_name' => $company_data->getName(),
  6048.                     'company_data' => $company_data,
  6049.                     'company_address' => $company_data->getAddress(),
  6050.                     'company_image' => $company_data->getImage(),
  6051.                     'application' => $response['application'],
  6052.                     'applicant' => $response['applicant'],
  6053.                     'Authorizations' => $authorizations,
  6054.                     'red' => 0
  6055.                 )
  6056.             );
  6057.         }
  6058.         return new JsonResponse(array(
  6059.             'success' => false,
  6060.             'msg' => 'Wrong URL format! Please try with application ID'
  6061.         ));
  6062.     }
  6063.     public function listResignApplicationAction(Request $req)
  6064.     {
  6065.         $em $this->getDoctrine()->getManager();
  6066.         $response HumanResource::getResignApplicationList($em$req);
  6067.         return $this->render("@Application/pages/human_resource/list/resign_application_list.html.twig", array(
  6068.             'page_title' => 'Resign Application List',
  6069.             'applications' => $response,
  6070.         ));
  6071.     }
  6072.     public function viewNocApprovalAction(Request $req$id)
  6073.     {
  6074.         $em $this->getDoctrine()->getManager();
  6075.         $response HumanResource::twigDataForNocView($em$req$id);
  6076.         return $this->render(
  6077.             '@Application/pages/human_resource/views/noc_view.html.twig',
  6078.             [
  6079.                 'page_title' => 'View NOC',
  6080.                 'approval_data' => $response['approval_data'],
  6081.                 'noc_application' => $response['noc_application'],
  6082.                 'resign_application' => $response['resign_application'],
  6083.                 'applicant' => $response['applicant'],
  6084.                 'document_log' => $response['document_log'],
  6085.                 'approval_status' => $response['approval_status'],
  6086.                 'created_by' => $response['created_by'],
  6087.                 'updated_at' => $response['updated_at'],
  6088.                 'auto_created' => 0,
  6089.             ]
  6090.         );
  6091.     }
  6092.     public function printNocApprovalAction(Request $req$id)
  6093.     {
  6094.         $em $this->getDoctrine()->getManager();
  6095.         $company_data Company::getCompanyData($em1);
  6096.         $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['NocApproval'], $id);
  6097.         $response HumanResource::twigDataForNocView($em$req$id);
  6098.         return $this->render(
  6099.             '@Application/pages/human_resource/print/noc_print.html.twig',
  6100.             [
  6101.                 'page_title' => 'Print NOC',
  6102.                 'noc_application' => $response['noc_application'],
  6103.                 'resign_application' => $response['resign_application'],
  6104.                 'applicant' => $response['applicant'],
  6105.                 'export' => 'pdf,print',
  6106.                 'company_name' => $company_data->getName(),
  6107.                 'company_data' => $company_data,
  6108.                 'company_address' => $company_data->getAddress(),
  6109.                 'company_image' => $company_data->getImage(),
  6110.                 'Authorizations' => $Authorizations,
  6111.                 'red' => 0
  6112.             ]
  6113.         );
  6114.     }
  6115.     public function createHolidayAction(Request $request$id)
  6116.     {
  6117.         $em $this->getDoctrine()->getManager();
  6118.         $companyId $this->getLoggedUserCompanyId($request);
  6119.         if ($request->isMethod('POST')) {
  6120.             $entity_id array_flip(GeneralConstant::$Entity_list)['HolidayCalendar']; //change
  6121.             $dochash $request->request->get('doc_hash'); //change
  6122.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6123.             $approveRole $request->request->get('approvalRole');
  6124.             $approveHash $request->request->get('approvalHash');
  6125.             if (!DocValidation::isInsertable(
  6126.                 $em,
  6127.                 $entity_id,
  6128.                 $dochash,
  6129.                 $loginId,
  6130.                 $approveRole,
  6131.                 $approveHash,
  6132.                 $id
  6133.             )
  6134.             ) {
  6135.                 $this->addFlash(
  6136.                     'error',
  6137.                     'Sorry Couldnot insert Data.'
  6138.                 );
  6139.             } else {
  6140.                 $funcname 'HolidayCalendar';
  6141.                 $doc_id $id;
  6142.                 DeleteDocument::$funcname($em$doc_id0);
  6143.                 if ($id != 0)
  6144.                     $HolidayCalender $em->getRepository(HolidayCalendar::class)->find($id);
  6145.                 else
  6146.                     $HolidayCalender = new HolidayCalendar;
  6147.                 $HolidayCalender->setDocumentHash($request->request->get('doc_hash'));
  6148.                 $HolidayCalender->setHoliDayTitle($request->request->get('holidayCalendarTitle'));
  6149.                 $HolidayCalender->setEmployeeIds(json_encode($request->request->get('employee')));
  6150.                 $HolidayCalender->setEmployeeTypeIds(json_encode($request->request->get('emp_status')));
  6151.                 $HolidayCalender->setDesignationIds(json_encode($request->request->get('desg', [])));
  6152.                 $HolidayCalender->setDepartmentIds(json_encode($request->request->get('dept', [])));
  6153.                 $HolidayCalender->setBranchIds(json_encode($request->request->get('branch', [])));
  6154.                 $HolidayCalender->setLevelSelectionStr($request->get('levelSelectionStr'''));
  6155.                 $HolidayCalender->setLevels(json_encode(HumanResource::getLevelsFromLevelSelectionStr($request->get('levelSelectionStr'''))));
  6156.                 $HolidayCalender->setCompanyId($companyId);
  6157.                 $HolidayCalender->setTypeHash('HD');
  6158.                 $HolidayCalender->setEditFlag(1); //editable usually
  6159.                 $HolidayCalender->setPrefixHash($request->request->get('prefix'));
  6160.                 $HolidayCalender->setAssocHash($request->request->get('assoc'));
  6161.                 $HolidayCalender->setNumberHash($request->request->get('number_hash'));
  6162.                 $HolidayCalender->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6163.                 $HolidayCalender->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6164.                 $HolidayCalender->setAutocreated(0);
  6165. //
  6166. //        $arr = [
  6167. //            'date' =>$request->request->get('start_date'),
  6168. //            'title' => $request->request->get('title'),
  6169. //        ];
  6170. //
  6171. //        $HolidayCalender->setData(json_encode($arr));
  6172.                 $em->persist($HolidayCalender);
  6173.                 $em->flush();
  6174.                 $indHolidays = [];
  6175.                 if ($request->request->has('start_date'))
  6176.                     $indHolidays $request->request->get('start_date');
  6177.                 foreach ($indHolidays as $ind => $dateRangeStr) {
  6178.                     $currRow $request->request->get('row')[$ind];//string
  6179.                     $holidayTitle $request->request->get('title')[$ind];//string
  6180.                     $currStartDate $request->request->get('start_date')[$ind];//string
  6181.                     $currEndDate $request->request->get('end_date')[$ind];//string
  6182.                     $HolidayDate = new HolidayCalendarDates();
  6183.                     $HolidayDate->setHolidayCalendarId($HolidayCalender->getHolidayCalendarId());
  6184.                     $HolidayDate->setDateRange($currStartDate '-' $currEndDate);//string
  6185.                     $HolidayDate->setStartDate(new \DateTime($currStartDate));//date
  6186.                     $HolidayDate->setEndDate(new \DateTime($currEndDate ' 23:59:59'));//date
  6187.                     $HolidayDate->setHolidayTitle($holidayTitle);
  6188. //          $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year',null));
  6189.                     $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year_' $currRownull));
  6190.                     $HolidayDate->setAllDayFlag($request->request->get('all_day_flag_' $currRow1));
  6191.                     $em->persist($HolidayDate);
  6192.                     $em->flush();
  6193.                 }
  6194.                 $options = [];
  6195.                 $entity array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'];
  6196.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6197.                 $approveRole $request->request->get('approvalRole');
  6198.                 System::setApprovalInfo(
  6199.                     $em,
  6200.                     $options,
  6201.                     $entity,
  6202.                     $HolidayCalender->getHolidayCalendarId(),
  6203.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6204.                 );
  6205.                 System::createEditSignatureHash(
  6206.                     $em,
  6207.                     $entity,
  6208.                     $HolidayCalender->getHolidayCalendarId(),
  6209.                     $loginId,
  6210.                     $approveRole,
  6211.                     $request->request->get('approvalHash')
  6212.                 );
  6213.                 $url $this->generateUrl(
  6214.                     'view_holiday_calendar'
  6215.                 );
  6216.                 return $this->redirect($url "/" $HolidayCalender->getHolidayCalendarId());
  6217.             }
  6218.         }
  6219.         $em $this->getDoctrine()->getManager();
  6220.         $branches $em->getRepository(Branch::class)->findAll();
  6221.         $employee $em->getRepository(Employee::class)->findAll();
  6222.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6223.         $departmentPositions $em->getRepository(SysDepartmentPosition::class)->findAll();
  6224.         $EmploymentStatus HumanResourceConstant::$employeeType;
  6225.         $em $this->getDoctrine()->getManager();
  6226.         $extDocData = [];
  6227.         if ($id != 0)
  6228.             $extDocData $em->getRepository(HolidayCalendar::class)->find($id);
  6229.         return $this->render(
  6230.             '@Application/pages/human_resource/input_forms/create_holiday.html.twig',
  6231.             [
  6232.                 'page_title' => 'Create Holiday',
  6233.                 'branches' => $branches,
  6234.                 'id' => $id,
  6235.                 'extDocData' => $extDocData,
  6236.                 'departments' => $departments,
  6237.                 'departmentPositions' => $departmentPositions,
  6238.                 'employeeStatus' => $EmploymentStatus,
  6239.                 'employeeIds' => $employee,
  6240.                 'holidayCalendarList' => $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendar')
  6241.                     ->findBy(array())
  6242.             ]
  6243.         );
  6244.     }
  6245.     public function HolidayViewAction(Request $request$id)
  6246.     {
  6247.         $em $this->getDoctrine()->getManager();
  6248.         $HolidaysCalendar $em->getRepository(HolidayCalendar::class)->find($id);
  6249.         $holidayCalendarDetails $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')
  6250.             ->findBy(array(
  6251.                 'holidayCalendarId' => $id
  6252.             ));
  6253.         $Approval_data System::checkIfApprovalExists(
  6254.             $em,
  6255.             array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
  6256.             $id,
  6257.             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6258.         );
  6259.         return $this->render('@Application/pages/human_resource/views/holidays_view.html.twig', array(
  6260.             'page_title' => 'View Holiday',
  6261.             'holidays' => $HolidaysCalendar,
  6262.             'holidayCalendarDetails' => $holidayCalendarDetails,
  6263.             'approval_status' => $HolidaysCalendar->getApproved(),
  6264.             'approval_data' => $Approval_data,
  6265.             'auto_created' => $HolidaysCalendar->getAutocreated(),
  6266.             'document_log' => $HolidaysCalendar->getAutocreated() == System::getDocumentLog(
  6267.                 $this->getDoctrine()->getManager(),
  6268.                 array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
  6269.                 $id,
  6270.                 $HolidaysCalendar->getCreatedLoginId(),
  6271.                 $HolidaysCalendar->getEditedLoginId()
  6272.             ) : []
  6273.         ));
  6274.     }
  6275.     public function GetHolidayDetailsAction(Request $request$id)
  6276.     {
  6277.         $em $this->getDoctrine()->getManager();
  6278.         $holidayCalendar $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendar')
  6279.             ->findOneBy(array(
  6280.                 'holidayCalendarId' => $id
  6281.             ));
  6282.         $holidayCalendarDetails $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')
  6283.             ->findBy(array(
  6284.                 'holidayCalendarId' => $id
  6285.             ));
  6286.         $holidayList = [];
  6287.         foreach ($holidayCalendarDetails as $det) {
  6288.             $dateDet = array(
  6289.                 'title' => $det->getHolidayTitle(),
  6290.                 'startDate' => $det->getStartDate()->format('Y-m-d'),
  6291.                 'endDate' => $det->getEndDate()->format('Y-m-d'),
  6292.             );
  6293.             $holidayList[] = $dateDet;
  6294.         }
  6295.         return new JsonResponse(
  6296.             array(
  6297.                 'success' => true,
  6298.                 'holidayList' => $holidayList
  6299.             )
  6300.         );
  6301.     }
  6302.     public function GetHolidayListByEmployeeIdAction(Request $request$id)
  6303.     {
  6304.         $em $this->getDoctrine()->getManager();
  6305.         $options = [];
  6306.         $options['employeeId'] = $id;
  6307.         HumanResource::getFilteredHolidaysSingle($em$options);
  6308.         $holidayCalendar $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendar')
  6309.             ->findOneBy(array(
  6310.                 'holidayCalendarId' => $id
  6311.             ));
  6312.         $holidayCalendarDetails $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')
  6313.             ->findBy(array(
  6314.                 'holidayCalendarId' => $id
  6315.             ));
  6316.         $holidayList = [];
  6317.         foreach ($holidayCalendarDetails as $det) {
  6318.             $dateDet = array(
  6319.                 'title' => $det->getHolidayTitle(),
  6320.                 'startDate' => $det->getStartDate()->format('Y-m-d'),
  6321.                 'endDate' => $det->getEndDate()->format('Y-m-d'),
  6322.             );
  6323.             $holidayList[] = $dateDet;
  6324.         }
  6325.         return new JsonResponse(
  6326.             array(
  6327.                 'success' => true,
  6328.                 'holidayList' => $holidayList
  6329.             )
  6330.         );
  6331.     }
  6332.     public function createQuestionAction(Request $request)
  6333.     {
  6334.         $em $this->getDoctrine()->getManager();
  6335.         $em_goc $this->getDoctrine()->getManager('company_group');
  6336.         $companyId $this->getLoggedUserCompanyId($request);
  6337.         if ($request->isMethod('POST')) {
  6338.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6339.             $question = new Questionnaire();
  6340.             $question->setQuestionTitle($request->request->get('questionTitle'''));
  6341.             $question->setQuestionText($request->request->get('questionText'''));
  6342.             $question->setIsForPlanningItem($request->request->has('forPlanningItem') ? 0);
  6343.             $question->setIsForInterview($request->request->has('forInterview') ? 0);
  6344.             $question->setIsForMock($request->request->has('forMock') ? 0);
  6345.             $question->setIsForTraining($request->request->has('forTraining') ? 0);
  6346.             $question->setTaggedSkillHashes($request->request->get('skillHash'));
  6347.             $question->setCorrectAnswers(json_encode($request->request->get('correctAns')));
  6348.             $question->setCompanyId($companyId);
  6349.             $optionData = [];
  6350.             foreach ($request->request->get('optionText') as $key => $val) {
  6351.                 $option = array(
  6352.                     'index' => $request->request->get('optionIndex')[$key],
  6353.                     'text' => $val,
  6354.                 );
  6355.                 $optionData[] = $option;
  6356.             }
  6357.             $question->setOptions(json_encode($optionData));
  6358.             $question->setQuestionValueWeight(1);
  6359.             $question->setQuestionText($request->request->get('questionText'));
  6360.             $question->setUniqueHash('_NONE_');
  6361.             $question->setType($request->request->get('type'0));
  6362.             //$skill->setEditFlag(1); //editable usually
  6363.             $question->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6364.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6365.             //$skill->setAutocreated(0);
  6366.             $em->persist($question);
  6367.             $em->flush();
  6368.             $questionId $question->getQuestionId();
  6369.             $file_path_list = [];
  6370.             if ($questionId != 0)
  6371.                 if (!empty($request->files)) {
  6372.                     MiscActions::RemoveFilesForEntityDoc($em_goc'Question'$questionId);
  6373.                     $storePath 'uploads/Questionnaire/';
  6374.                     $path "";
  6375.                     $file_path "";
  6376.                     $session $request->getSession();
  6377. //                    MiscActions::RemoveExpiredFiles($em_goc);
  6378.                     foreach ($request->files as $uploadedFileGG) {
  6379.                         //            if($uploadedFile->getImage())
  6380.                         //                var_dump($uploadedFile->getFile());
  6381.                         //                var_dump($uploadedFile);
  6382.                         $tempD $uploadedFileGG;
  6383.                         if (!is_array($uploadedFileGG)) {
  6384.                             $uploadedFileGG = array();
  6385.                             $uploadedFileGG[] = $tempD;
  6386.                         }
  6387.                         foreach ($uploadedFileGG as $uploadedFile) {
  6388.                             if ($uploadedFile != null) {
  6389.                                 $extension $uploadedFile->guessExtension();
  6390.                                 $size $uploadedFile->getSize();
  6391.                                 $fileName 'QUES_' $questionId '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  6392.                                 $path $fileName;
  6393.                                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  6394.                                 if (!file_exists($upl_dir)) {
  6395.                                     mkdir($upl_dir0777true);
  6396.                                 }
  6397.                                 if (file_exists($upl_dir '' $path)) {
  6398.                                     chmod($upl_dir '' $path0755);
  6399.                                     unlink($upl_dir '' $path);
  6400.                                 }
  6401.                                 $file $uploadedFile->move($upl_dir$path);
  6402.                                 $expireNever 1;
  6403.                                 $expireTs 0;
  6404.                                 $EntityFile = new EntityFile();
  6405.                                 $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  6406.                                 $EntityFile->setName($path);
  6407.                                 $EntityFile->setMarker('_GEN_');
  6408.                                 $EntityFile->setExtension($extension);
  6409.                                 $EntityFile->setExpireTs($expireTs);
  6410.                                 $EntityFile->setSize($size);
  6411.                                 $EntityFile->setRelativePath($storePath $path);
  6412.                                 $EntityFile->setEntityName('Questionnaire');
  6413.                                 $EntityFile->setEntityBundle('ApplicationBundle');
  6414.                                 $EntityFile->setEntityId($questionId);
  6415.                                 $EntityFile->setEntityIdField('questionId');
  6416.                                 $EntityFile->setModifyFieldSetter('setFiles');
  6417.                                 $EntityFile->setDocIdForApplicant(0);
  6418.                                 $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  6419.                                 $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  6420.                                 $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  6421.                                 $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  6422.                                 $em_goc->persist($EntityFile);
  6423.                                 $em_goc->flush();
  6424.                                 $EntityFileId $EntityFile->getId();
  6425.                             }
  6426.                             if ($path != "")
  6427.                                 $file_path_list[] = ($storePath $path);
  6428.                         }
  6429.                     }
  6430.                     $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  6431.                     $question->setFiles(implode(','$file_path_list));
  6432.                     $em->flush();
  6433.                 }
  6434.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  6435.                 if ($question)
  6436.                     return new JsonResponse(
  6437.                         array(
  6438.                             'id' => $questionId,
  6439.                             'value' => $questionId,
  6440.                             'question_id' => $questionId,
  6441.                             'text' => $question->getQuestionText(),
  6442.                             'question_text' => $question->getQuestionText(),
  6443.                             'question_title' => $question->getQuestionTitle(),
  6444.                             'files' => explode(','$question->getFiles()),
  6445.                             'options' => json_decode($question->getFiles(), true),
  6446.                             'answer_text' => '',
  6447.                             'success' => true
  6448.                         )
  6449.                     );
  6450.                 else
  6451.                     return new JsonResponse(
  6452.                         array(
  6453.                             'success' => false
  6454.                         )
  6455.                     );
  6456.             }
  6457.         }
  6458.         $skillDetails $em->getRepository(Skill::class)->findAll();
  6459.         $skillListObj = [];
  6460.         $skillListArray = [];
  6461.         foreach ($skillDetails as $skillDetail) {
  6462.             $dt = array(
  6463.                 'id' => $skillDetail->getSkillId(),
  6464.                 'name' => $skillDetail->getName(),
  6465.                 'hash' => $skillDetail->getUniqueHash(),
  6466.             );
  6467.             $skillListArray[] = $dt;
  6468.         }
  6469.         return $this->render('@Application/pages/human_resource/input_forms/createQuestion.html.twig', array(
  6470.             'page_title' => 'Create Question',
  6471.             'skiillDetails' => $skillDetails,
  6472.             'skillListArray' => $skillListArray,
  6473.         ));
  6474.     }
  6475.     public function createSkillAction(Request $request)
  6476.     {
  6477.         $em $this->getDoctrine()->getManager();
  6478.         $companyId $this->getLoggedUserCompanyId($request);
  6479.         if ($request->isMethod('POST')) {
  6480.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6481.             $skill = new Skill;
  6482.             $skill->setName($request->request->get('skillName'));
  6483.             $skill->setParentId($request->request->get('parentName'));
  6484.             $skill->setUniqueHash($request->request->get('uniqueHash'));
  6485.             $skill->setCompanyId($companyId);
  6486.             //$skill->setEditFlag(1); //editable usually
  6487.             $skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6488.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6489.             //$skill->setAutocreated(0);
  6490.             $em->persist($skill);
  6491.             $em->flush();
  6492.         }
  6493.         $skillDetails $em->getRepository(Skill::class)->findAll();
  6494.         return $this->render('@Application/pages/human_resource/input_forms/createSkill.html.twig', array(
  6495.             'page_title' => 'Create Skill',
  6496.             'skiillDetails' => $skillDetails,
  6497.         ));
  6498.     }
  6499.     public function createEducationQualificationAction(Request $request)
  6500.     {
  6501.         $em $this->getDoctrine()->getManager();
  6502.         $companyId $this->getLoggedUserCompanyId($request);
  6503.         if ($request->isMethod('POST')) {
  6504.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6505.             $new = new EducationQualification;
  6506.             $new->setName($request->request->get('educationName'));
  6507.             $new->setParentId($request->request->get('parentName'));
  6508.             $new->setUniqueHash($request->request->get('uniqueHash'));
  6509.             $new->setCompanyId($companyId);
  6510.             //$skill->setEditFlag(1); //editable usually
  6511.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6512.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6513.             //$skill->setAutocreated(0);
  6514.             $em->persist($new);
  6515.             $em->flush();
  6516.         }
  6517.         $educationDetails $em->getRepository(EducationQualification::class)->findAll();
  6518.         return $this->render('@Application/pages/human_resource/input_forms/create_education.html.twig', array(
  6519.             'page_title' => 'Create Education',
  6520.             'educationDetails' => $educationDetails,
  6521.         ));
  6522.     }
  6523.     public function createEvaluationCategoryAction(Request $request$id 0)
  6524.     {
  6525.         $em $this->getDoctrine()->getManager();
  6526.         $companyId $this->getLoggedUserCompanyId($request);
  6527.         if ($request->isMethod('POST')) {
  6528.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6529.             $new = new EvaluationCategory;
  6530.             $new->setName($request->request->get('name'));
  6531.             $new->setBranch($request->request->get('branch'));
  6532.             $new->setSelectionType($request->request->get('selection_type'));
  6533.             $new->setEmployeeIds($request->request->get('selected_employeeIds'));
  6534.             $new->setEmployeeTypeIds($request->request->get('employee_types'));
  6535.             $new->setDesignationIds($request->request->get('designation'));
  6536.             $new->setDesignationIds($request->request->get('designation'));
  6537.             $new->setmark($request->request->get('mark'));
  6538.             $new->setSkills(json_encode($request->request->get('skill')));
  6539.             $new->setLevelSelectionStr($request->request->get('levelSelectionStr'));
  6540.             $new->setCompanyId($companyId);
  6541.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6542.             $em->persist($new);
  6543.             $em->flush();
  6544.         }
  6545.         $skill $em->getRepository(Skill::class)->findAll();
  6546.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6547.         $employeeType HumanResourceConstant::$employeeType;
  6548.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6549.         $branch $em->getRepository(Branch::class)->findAll();
  6550.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6551.         $department = [];
  6552.         foreach ($departments as $entry) {
  6553.             $department[$entry->getDepartmentId()] = array(
  6554.                 'id' => $entry->getDepartmentId(),
  6555.                 'name' => $entry->getDepartmentName(),
  6556.             );
  6557.             return $this->render('@Application/pages/human_resource/input_forms/create_evaluation_category.html.twig', array(
  6558.                 'page_title' => 'Create Evaluation Category',
  6559.                 'employeeIds' => $employeeIds,
  6560.                 'employeeType' => $employeeType,
  6561.                 'Designation' => $Designation,
  6562.                 'branch' => $branch,
  6563.                 'department' => $department,
  6564.                 'skill' => $skill,
  6565.             ));
  6566.         }
  6567.     }
  6568.     public function createWorkplaceHarassmentAction(Request $request$id 0)
  6569.     {
  6570.         $em $this->getDoctrine()->getManager();
  6571.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6572.         //$employeeType = HumanResourceConstant::$employeeType;
  6573.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6574.         $branches $em->getRepository(Branch::class)->findAll();
  6575.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6576.         $harassmentType HumanResourceConstant::$harrasmentType;
  6577.         $department = [];
  6578.         foreach ($departments as $entry) {
  6579.             $department[$entry->getDepartmentId()] = array(
  6580.                 'id' => $entry->getDepartmentId(),
  6581.                 'name' => $entry->getDepartmentName(),
  6582.             );
  6583.         }
  6584.         return $this->render('@Application/pages/human_resource/input_forms/create_workplace_harrasment.html.twig', array(
  6585.             'page_title' => 'Create Workplace Harrasment',
  6586.             'employeeIds' => $employeeIds,
  6587.             'branches' => $branches,
  6588.             'harassmentType' => $harassmentType,
  6589.             'departments' => $department,
  6590.             'designationIds' => $Designation
  6591.         ));
  6592.     }
  6593.     public function ViewHarasssmentComplainAction()
  6594.     {
  6595.         return $this->render('@Application/pages/human_resource/views/view_harassment_compalin.html.twig', array(
  6596.             'page_title' => 'View Harassment Complain',
  6597.         ));
  6598.     }
  6599.     public function createWorkplaceViolenceAction(Request $request$id 0)
  6600.     {
  6601.         $em $this->getDoctrine()->getManager();
  6602.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6603.         //$employeeType = HumanResourceConstant::$employeeType;
  6604.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6605.         $branches $em->getRepository(Branch::class)->findAll();
  6606.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6607.         $harassmentType HumanResourceConstant::$harrasmentType;
  6608.         $department = [];
  6609.         foreach ($departments as $entry) {
  6610.             $department[$entry->getDepartmentId()] = array(
  6611.                 'id' => $entry->getDepartmentId(),
  6612.                 'name' => $entry->getDepartmentName(),
  6613.             );
  6614.         }
  6615.         return $this->render('@Application/pages/human_resource/input_forms/register_workplace_complaint.html.twig', array(
  6616.             'page_title' => 'Register Complaint',
  6617.             'employeeIds' => $employeeIds,
  6618.             'branches' => $branches,
  6619.             'harassmentType' => $harassmentType,
  6620.             'departments' => $department,
  6621.             'designationIds' => $Designation
  6622.         ));
  6623.     }
  6624.     public function createBonusPolicyAction(Request $request$id 0)
  6625.     {
  6626.         $em $this->getDoctrine()->getManager();
  6627.         $companyId $this->getLoggedUserCompanyId($request);
  6628.         $extDocData = [];
  6629.         $extDetailsData = [];
  6630.         if ($request->isMethod('POST')) {
  6631.             //            Generic::debugMessage($_POST);
  6632.             $em $this->getDoctrine()->getManager();
  6633.             $entity_id array_flip(GeneralConstant::$Entity_list)['BonusPolicy']; //change
  6634.             $dochash $request->request->get('docHash'); //change
  6635.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6636.             $approveRole $request->request->get('approvalRole');
  6637.             $approveHash $request->request->get('approvalHash');
  6638.             if (!DocValidation::isInsertable(
  6639.                 $em,
  6640.                 $entity_id,
  6641.                 $dochash,
  6642.                 $loginId,
  6643.                 $approveRole,
  6644.                 $approveHash,
  6645.                 $id
  6646.             )
  6647.             ) {
  6648.                 $this->addFlash(
  6649.                     'error',
  6650.                     'Sorry Couldnot insert Data.'
  6651.                 );
  6652.             } else {
  6653.                 $funcname 'BonusPolicy';
  6654.                 DeleteDocument::$funcname($em$id0);
  6655.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6656.                 $docId HumanResource::createBonusPolicy($em$request$companyId$loginId0);
  6657.                 //now add Approval info
  6658.                 $approveRole $request->request->get('approvalRole');
  6659.                 $options = array(
  6660.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6661.                     'notification_server' => $this->container->getParameter('notification_server'),
  6662.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6663.                     'url' => $this->generateUrl(
  6664.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['BonusPolicy']]['entity_view_route_path_name']
  6665.                     )
  6666.                 );
  6667.                 System::setApprovalInfo(
  6668.                     $this->getDoctrine()->getManager(),
  6669.                     $options,
  6670.                     array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
  6671.                     $docId,
  6672.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6673.                 );
  6674.                 System::createEditSignatureHash(
  6675.                     $this->getDoctrine()->getManager(),
  6676.                     array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
  6677.                     $docId,
  6678.                     $loginId,
  6679.                     $approveRole,
  6680.                     $request->request->get('approvalHash')
  6681.                 );
  6682.                 $doc_here $this->getDoctrine()
  6683.                     ->getRepository('ApplicationBundle\\Entity\\BonusPolicy')
  6684.                     ->findOneBy(
  6685.                         array(
  6686.                             'id' => $docId
  6687.                         )
  6688.                     );
  6689.                 //notify
  6690.                 $this->addFlash(
  6691.                     'success',
  6692.                     'Policy Successfully Updated.'
  6693.                 );
  6694.                 $url $this->generateUrl(
  6695.                     'bonus_policy_list'
  6696.                 );
  6697. //                System::AddNewNotification(
  6698. //                    $this->container->getParameter('notification_enabled'),
  6699. //                    $this->container->getParameter('notification_server'),
  6700. //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  6701. //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6702. //                    "Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6703. //                    'pos',
  6704. //                    System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
  6705. //                    'success',
  6706. //                    //                    $url . "/" . $TransID,
  6707. //                    $url . "/" . $docId,
  6708. //                    "Journal"
  6709. //
  6710. //                );
  6711.                 // bonus_policy_list has no {id} param â€” redirect to the list itself (appending
  6712.                 // /$docId produced an unmatched URL that fell back to the sales dashboard).
  6713.                 return $this->redirect($url);
  6714.             }
  6715.         }
  6716.         //for edits
  6717.         if ($id == 0) {
  6718.         } else {
  6719.             $extDocData $em->getRepository('ApplicationBundle\\Entity\\BonusPolicy')->findOneBy(
  6720.                 array(
  6721.                     'id' => $id///material
  6722.                 )
  6723.             );
  6724.             //now if its not editable, redirect to view
  6725.             if ($extDocData) {
  6726.                 if ($extDocData->getEditFlag() != 1) {
  6727. //          $url = $this->generateUrl(
  6728. ////              'view_salary_segregation_policy'
  6729. //              'salary_segregation_policy'
  6730. //          );
  6731. //          return $this->redirect($url . "/" . $id);
  6732.                 } else {
  6733. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  6734. //          $extDetailsData = $em->getRepository('ApplicationBundle\\Entity\\SalarySegregationPolicy')->findOneBy(
  6735. //              array(
  6736. //                  'transactionId' => $id, ///material
  6737. //
  6738. //              )
  6739. //          );
  6740.                 }
  6741.             } else {
  6742.             }
  6743.         }
  6744.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6745.         $employeeType HumanResourceConstant::$employeeType;
  6746.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6747.         $branch $em->getRepository(Branch::class)->findAll();
  6748.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6749.         $department = [];
  6750.         foreach ($departments as $entry) {
  6751.             $department[$entry->getDepartmentId()] = array(
  6752.                 'id' => $entry->getDepartmentId(),
  6753.                 'name' => $entry->getDepartmentName(),
  6754.             );
  6755.         }
  6756.         return $this->render('@Application/pages/human_resource/input_forms/create_bonus_policy.html.twig', array(
  6757.             'page_title' => (is_object($extDocData) ? 'Edit Bonus Policy' 'Create Bonus Policy'),
  6758.             'employeeIds' => $employeeIds,
  6759.             'employeeType' => $employeeType,
  6760.             'Designation' => $Designation,
  6761.             'branch' => $branch,
  6762.             'department' => $department,
  6763.             // Edit support: when an id was supplied, $extDocData holds the loaded BonusPolicy so the
  6764.             // form can pre-fill (docExists gates the edit bindings, same pattern as other forms).
  6765.             'docExists' => (is_object($extDocData) ? 0),
  6766.             'extDocData' => $extDocData,
  6767.         ));
  6768.     }
  6769.     public function BonusPolicyListAction()
  6770.     {
  6771.         $em $this->getDoctrine()->getManager();
  6772.         $bonusPolicy $em->getRepository(BonusPolicy::class)->findAll();
  6773.         return $this->render('@Application/pages/human_resource/list/bonus_policy_list.html.twig', array(
  6774.             'page_title' => 'Bonus Policy List',
  6775.             'bonusPolicy' => $bonusPolicy
  6776.         ));
  6777.     }
  6778.     /**
  6779.      * Festival Bonus disbursement. GET shows the run form (pick a Bonus Policy + festival label +
  6780.      * period); when a policy is selected it previews the eligible employees and their computed bonus
  6781.      * amounts (reusing the payroll policy math). POST action=disburse persists standalone bonus
  6782.      * payslips (payslipType=2) via BonusDisbursementService, which flow through the normal approval
  6783.      * funnel and then into the payslip -> payment-voucher pipeline. Money never moves automatically.
  6784.      */
  6785.     public function DisburseBonusAction(Request $request)
  6786.     {
  6787.         $em $this->getDoctrine()->getManager();
  6788.         $bonusPolicies $em->getRepository(BonusPolicy::class)->findBy(
  6789.             ['approved' => GeneralConstant::APPROVED],
  6790.             ['updatedAt' => 'DESC''createdAt' => 'DESC''id' => 'DESC']
  6791.         );
  6792.         $policyId = (int) $request->get('policyId'0);
  6793.         $festivalLabel trim((string) $request->get('festivalLabel'''));
  6794.         $fromStr $request->get('fromDate', (new \DateTime('first day of this month'))->format('Y-m-d'));
  6795.         $toStr $request->get('toDate', (new \DateTime('last day of this month'))->format('Y-m-d'));
  6796.         $from = new \DateTime($fromStr);
  6797.         $to = new \DateTime($toStr);
  6798.         $selectedPolicy $policyId $em->getRepository(BonusPolicy::class)->find($policyId) : null;
  6799.         $rows = [];
  6800.         $totalBonus 0;
  6801.         if ($selectedPolicy) {
  6802.             $rows = \ApplicationBundle\Modules\HumanResource\Service\BonusDisbursementService::computeBonusRows($em$selectedPolicy$from$to);
  6803.             foreach ($rows as $r) {
  6804.                 $totalBonus += ($r['gross']);
  6805.             }
  6806.         }
  6807.         // Disburse: persist the (optionally edited) bonus payslips.
  6808.         if ($request->isMethod('POST') && $request->request->get('action') === 'disburse' && $selectedPolicy) {
  6809.             $overrides $request->request->get('amount', []); // id => amount
  6810.             $overrideById = [];
  6811.             if (is_array($overrides)) {
  6812.                 foreach ($overrides as $eid => $amt) {
  6813.                     $overrideById[(int) $eid] = $amt;
  6814.                 }
  6815.             }
  6816.             $createdIds = \ApplicationBundle\Modules\HumanResource\Service\BonusDisbursementService::persistBonusPayslips(
  6817.                 $em$request$selectedPolicy$festivalLabel$from$to$rows$overrideById
  6818.             );
  6819.             $this->addFlash('success'count($createdIds) . ' bonus payslip(s) created for "' . ($festivalLabel ?: 'Festival Bonus') . '". Approve, then disburse against bank.');
  6820.             return $this->redirectToRoute('payslip');
  6821.         }
  6822.         return $this->render('@Application/pages/human_resource/report/disburse_bonus.html.twig', array(
  6823.             'page_title' => 'Bonus Disbursement',
  6824.             'bonusPolicies' => $bonusPolicies,
  6825.             'selectedPolicyId' => $policyId,
  6826.             'festivalLabel' => $festivalLabel,
  6827.             'fromDate' => $from->format('Y-m-d'),
  6828.             'toDate' => $to->format('Y-m-d'),
  6829.             'rows' => $rows,
  6830.             'totalBonus' => $totalBonus,
  6831.         ));
  6832.     }
  6833.     public function createIncrementPolicyAction(Request $request$id 0)
  6834.     {
  6835.         $em $this->getDoctrine()->getManager();
  6836.         $companyId $this->getLoggedUserCompanyId($request);
  6837.         $extDocData = [];
  6838.         $extDetailsData = [];
  6839.         if ($request->isMethod('POST')) {
  6840.             //            Generic::debugMessage($_POST);
  6841.             $em $this->getDoctrine()->getManager();
  6842.             $entity_id array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']; //change
  6843.             $dochash $request->request->get('docHash'); //change
  6844.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6845.             $approveRole $request->request->get('approvalRole');
  6846.             $approveHash $request->request->get('approvalHash');
  6847.             if (!DocValidation::isInsertable(
  6848.                 $em,
  6849.                 $entity_id,
  6850.                 $dochash,
  6851.                 $loginId,
  6852.                 $approveRole,
  6853.                 $approveHash,
  6854.                 $id
  6855.             )
  6856.             ) {
  6857.                 $this->addFlash(
  6858.                     'error',
  6859.                     'Sorry Couldnot insert Data.'
  6860.                 );
  6861.             } else {
  6862.                 $funcname 'IncrementPolicy';
  6863.                 DeleteDocument::$funcname($em$id0);
  6864.                 $docId HumanResource::createIncrementPolicy($em$request$companyId0);
  6865.                 //now add Approval info
  6866.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6867.                 $approveRole $request->request->get('approvalRole');
  6868.                 $options = array(
  6869.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6870.                     'notification_server' => $this->container->getParameter('notification_server'),
  6871.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6872.                     'url' => $this->generateUrl(
  6873.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']]
  6874.                         ['entity_view_route_path_name']
  6875.                     )
  6876.                 );
  6877.                 System::setApprovalInfo(
  6878.                     $this->getDoctrine()->getManager(),
  6879.                     $options,
  6880.                     array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6881.                     $docId,
  6882.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6883.                     3    //journal voucher
  6884.                 );
  6885.                 System::createEditSignatureHash(
  6886.                     $this->getDoctrine()->getManager(),
  6887.                     array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6888.                     $docId,
  6889.                     $loginId,
  6890.                     $approveRole,
  6891.                     $request->request->get('approvalHash')
  6892.                 );
  6893.                 $doc_here $this->getDoctrine()
  6894.                     ->getRepository('ApplicationBundle\\Entity\\IncrementPolicy')
  6895.                     ->findOneBy(
  6896.                         array(
  6897.                             'id' => $docId
  6898.                         )
  6899.                     );
  6900.                 //notify
  6901.                 $this->addFlash(
  6902.                     'success',
  6903.                     'Policy Successfully Updated.'
  6904.                 );
  6905.                 $url $this->generateUrl(
  6906.                     'view_increment_policy'
  6907.                 );
  6908.                 return $this->redirect($url "/" $docId);
  6909.             }
  6910.         }
  6911.         //for edits
  6912.         if ($id == 0) {
  6913.         } else {
  6914.             $extDocData $em->getRepository('ApplicationBundle\\Entity\\IncrementPolicy')->findOneBy(
  6915.                 array(
  6916.                     'id' => $id///material
  6917.                 )
  6918.             );
  6919.             //now if its not editable, redirect to view
  6920.             if ($extDocData) {
  6921.                 if ($extDocData->getEditFlag() != 1) {
  6922. //          $url = $this->generateUrl(
  6923. ////              'view_salary_segregation_policy'
  6924. //              'salary_segregation_policy'
  6925. //          );
  6926. //          return $this->redirect($url . "/" . $id);
  6927.                 } else {
  6928. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  6929. //          $extDetailsData = $em->getRepository('ApplicationBundle\\Entity\\SalarySegregationPolicy')->findOneBy(
  6930. //              array(
  6931. //                  'transactionId' => $id, ///material
  6932. //
  6933. //              )
  6934. //          );
  6935.                 }
  6936.             } else {
  6937.             }
  6938.         }
  6939.         //$em = $this->getDoctrine()->getManager();
  6940.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6941.         $employeeType HumanResourceConstant::$employeeType;
  6942.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6943.         $branch $em->getRepository(Branch::class)->findAll();
  6944.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6945.         $department = [];
  6946.         foreach ($departments as $entry) {
  6947.             $department[$entry->getDepartmentId()] = array(
  6948.                 'id' => $entry->getDepartmentId(),
  6949.                 'name' => $entry->getDepartmentName(),
  6950.             );
  6951.         }
  6952.         return $this->render('@Application/pages/human_resource/input_forms/create_increment_policy.html.twig', array(
  6953.             'page_title' => 'Create Increment Policy',
  6954.             'employeeIds' => $employeeIds,
  6955.             'employeeType' => $employeeType,
  6956.             'Designation' => $Designation,
  6957.             'branch' => $branch,
  6958.             'department' => $department,
  6959.         ));
  6960.     }
  6961.     public function IncrementPolicyListAction()
  6962.     {
  6963.         $em $this->getDoctrine()->getManager();
  6964.         $incrementPolicy $em->getRepository(IncrementPolicy::class)->findAll();
  6965.         return $this->render('@Application/pages/human_resource/list/increment_policy_list.html.twig', array(
  6966.             'page_title' => 'Increment Policy List',
  6967.             'incrementPolicy' => $incrementPolicy
  6968.         ));
  6969.     }
  6970.     public function ViewIncrementPolicyAction(Request $request$id)
  6971.     {
  6972.         $em $this->getDoctrine()->getManager();
  6973.         $incrementPolicy $em->getRepository(IncrementPolicy::class)->find($id);
  6974.         $Approval_data System::checkIfApprovalExists(
  6975.             $em,
  6976.             array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6977.             $id,
  6978.             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6979.         );
  6980.         return $this->render('@Application/pages/human_resource/views/view_increment_policy.html.twig', array(
  6981.             'page_title' => 'Increment Policy List',
  6982.             'incrementPolicy' => $incrementPolicy,
  6983.             'approval_status' => $incrementPolicy->getApproved(),
  6984.             'approval_data' => $Approval_data,
  6985.             'auto_created' => $incrementPolicy->getAutocreated(),
  6986.             'id' => $id,
  6987.             'document_log' => $incrementPolicy->getAutocreated() == System::getDocumentLog(
  6988.                 $this->getDoctrine()->getManager(),
  6989.                 array_flip(GeneralConstant::$Entity_list)['FundRequisition'],
  6990.                 $id,
  6991.                 $incrementPolicy->getCreatedLoginId(),
  6992.                 $incrementPolicy->getEditedLoginId()
  6993.             ) : []
  6994.         ));
  6995.     }
  6996.     public function createConsultancyTopicAction(Request $request$id 0)
  6997.     {
  6998.         $em $this->getDoctrine()->getManager();
  6999.         $companyId $this->getLoggedUserCompanyId($request);
  7000.         if ($request->isMethod('POST')) {
  7001.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7002.             $new = new ConsultancyTopic();
  7003.             $new->setTopicName($request->request->get('topicName'));
  7004.             $new->setParentTopicName($request->request->get('parentTopicName'));
  7005.             $new->setUniqueHash($request->request->get('uniqueHash'));
  7006.             $new->setCompanyId($companyId);
  7007.             $new->setTopicSlug($request->request->get('topicSlug'));
  7008.             $new->setTitle($request->request->get('title'));
  7009.             $new->setSubTitle($request->request->get('subTitle'));
  7010.             $new->setSummary($request->request->get('content'));
  7011.             $new->setVideo($request->request->get('video'));
  7012.             $new->setAuthor($request->request->get('author'));
  7013.             $new->setAuthorSummary($request->request->get('authorSummary'));
  7014.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7015. //            $arr = [
  7016. //                'requirement' => $request->request->get('requirement'),
  7017. //
  7018. //            ];
  7019. //            $new->setRequirementData(json_encode($arr));
  7020.             $em->persist($new);
  7021.             $em->flush();
  7022.         }
  7023. //            $data = [];
  7024. //            $em = $this->getDoctrine()->getManager();
  7025. //            $companyId = $this->getLoggedUserCompanyId($request);
  7026. //            if ($request->isMethod('POST')) {
  7027. //                $em = $this->getDoctrine()->getManager();
  7028. //                $entity_id = array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'];
  7029. //                //$dochash = $request->request->get('docHash');//change
  7030. //                $approveRole = $request->request->get('approvalRole');
  7031. //                $approveHash = $request->request->get('approvalHash');
  7032. //                $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7033. //                if (!DocValidation::isInsertable($em, $entity_id,
  7034. //                    $loginId, $approveRole, $approveHash, $id)
  7035. //                ) {
  7036. //                    $this->addFlash(
  7037. //                        'error',
  7038. //                        'Sorry Could not insert Data.'
  7039. //                    );
  7040. //                }  else {
  7041. //                    $data = $request->request;
  7042. //                    $docId = HumanResource::createConsultancyTopic($em, $loginId, $id, $data, $companyId);
  7043. ////                    now add Approval info
  7044. //
  7045. //                    $approveRole = $request->request->get('approvalRole');
  7046. //                    $options = array(
  7047. //                        'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7048. //                        'notification_server' => $this->container->getParameter('notification_server'),
  7049. //                        'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7050. ////                        'url' => $this->generateUrl(
  7051. ////                            GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
  7052. ////                            ['entity_view_route_path_name']
  7053. ////                        )
  7054. //                    );
  7055. //                    System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  7056. //                        array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
  7057. //                        $docId,
  7058. //                        $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  7059. //                    );
  7060. //                    System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
  7061. //                        $docId,
  7062. //                        $loginId,
  7063. //                        $request->request->get('approvalHash'));
  7064. //                    $this->addFlash(
  7065. //                        'success',
  7066. //                        'New Consultancy Topic Added.'
  7067. //                    );
  7068. ////                    $url = $this->generateUrl(
  7069. ////                        'create_consultancy_topic'
  7070. ////                    );
  7071. //                    //return $this->redirect($url);
  7072. //
  7073. //                }
  7074. //            }
  7075.         $consultancyDetails $em->getRepository('ApplicationBundle\\Entity\\ConsultancyTopic')->findAll();
  7076.         return $this->render('@Application/pages/human_resource/input_forms/create_consultancy.html.twig', array(
  7077.             'page_title' => 'Consultancy Topic',
  7078.             'consultancyDetails' => $consultancyDetails,
  7079. //                'requirement' => json_decode($consultancyDetails->getRequirementData())
  7080.         ));
  7081.     }
  7082.     public function createTopicAction(Request $request$id 0)
  7083.     {
  7084.         $em $this->getDoctrine()->getManager('company_group');
  7085.         $companyId $this->getLoggedUserCompanyId($request);
  7086.         $documentQRY $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findAll();
  7087.         $topicList $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findAll();
  7088.         $topic = [];
  7089.         $sessionName BuddybeeConstant::$sessionName;
  7090.         $document = [];
  7091.         foreach ($documentQRY as $d) {
  7092.             $document[$d->getId()] = array(
  7093.                 'id' => $d->getId(),
  7094.                 'documentName' => $d->getDocumentName(),
  7095.                 'text' => $d->getDocumentName(),
  7096.             );
  7097.         }
  7098.         $topicId $id;
  7099.         if ($topicId != 0)
  7100.             $topic $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(
  7101.                 array(
  7102.                     'id' => $topicId
  7103.                 )
  7104.             );
  7105.         if ($request->isMethod('POST')) {
  7106.             if ($request->request->has('topicId'))
  7107.                 $topicId $request->request->get('topicId');
  7108. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7109.             if ($topicId != 0)
  7110.                 $new $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(
  7111.                     array(
  7112.                         'id' => $topicId
  7113.                     )
  7114.                 );
  7115.             else
  7116.                 $new = new EntityCreateTopic();
  7117.             $new->setTopicName($request->request->get('topicName'));
  7118.             $new->setParentTopicId($request->request->get('parentTopic'));
  7119.             if ($request->request->get('countryId') != '')
  7120.                 $new->setCountryId($request->request->get('countryId'));
  7121.             else if ($request->request->get('parentTopic') != '') {
  7122.                 $parentTopic $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(
  7123.                     array(
  7124.                         'id' => $request->request->get('parentTopic')
  7125.                     )
  7126.                 );
  7127.                 if ($parentTopic)
  7128.                     $new->setCountryId($parentTopic->getCountryId());
  7129.             }
  7130.             $new->setTimeSlotMultipliers($request->request->get('timeSlotMultipliers'));
  7131.             $new->setOnlyBookableByAdmin($request->request->get('onlyBookableByAdmin'0));
  7132.             $new->setMeetingType($request->request->get('meetingType'0));
  7133.             $new->setConsultantCanUpload($request->request->get('consultantCanUpload'0));
  7134.             $new->setTopicMarker($request->request->get('topicMarker'));
  7135.             $new->setCoinMultiplierValue($request->request->get('coinMultiplierValue'1));
  7136.             $new->setMinLifetimeCoinsBalance($request->request->get('minLifetimeCoinsBalance'0));
  7137.             $new->setMapEmbedIframe($request->request->get('mapEmbedIframe'''));
  7138.             $new->setTopicSummary($request->request->get('topicSummary'));
  7139.             $new->setAddress($request->request->get('address'));
  7140.             $new->setLocationString($request->request->get('locationString'));
  7141.             $new->setLocationLat($request->request->get('locationLat'));
  7142.             $new->setLocationLong($request->request->get('locationLong'));
  7143.             $new->setUniversityRanking($request->request->get('universityRanking'));
  7144.             $new->setIsParent($request->request->get('isParent'));
  7145.             $new->setIsEvent($request->request->get('isEvent'));
  7146.             $new->setConsultancyEnabled($request->request->get('consultancyEnabled'0));
  7147.             $new->setEventExpired($request->request->get('eventExpired'0));
  7148.             $new->setEventDesc($request->request->get('eventDesc'0));
  7149.             $eventStartDate = new \DateTime($request->request->get('eventStartDate'));
  7150.             $eventEndDate = new \DateTime($request->request->get('eventStartDate'));
  7151.             $new->setEventStartDate($eventStartDate);
  7152.             $new->setEventStartDateTs($eventStartDate->format('U'));
  7153.             $new->setEventEndDate($eventEndDate);
  7154.             $new->setEventStartDateTs($eventEndDate->format('U'));
  7155.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7156.             $checkListStringArray = [];
  7157.             if ($request->request->has('checkList'))
  7158.                 foreach ($request->request->get('checkList') as $value) {
  7159.                     $checkListStringArray [] = explode(","$value);
  7160.                 }
  7161.             $docData = [];
  7162.             foreach ($request->request->get('document', []) as $key => $value)
  7163.                 $docData[] = [
  7164.                     'document' => $request->request->get('document')[$key],
  7165.                     'expDays' => $request->request->get('expDays')[$key],
  7166.                     'stage' => $request->request->get('stage')[$key],
  7167.                     'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
  7168.                     'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
  7169.                     'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
  7170.                     'checklist' => explode(","$request->request->get('checkList')[$key])
  7171.                 ];
  7172.             $coursePlanData = [];
  7173.             foreach ($request->request->get('coursePlanSessionNo', []) as $key => $value)
  7174.                 if ($request->request->get('coursePlanSessionNo')[$key] != '' and $request->request->get('coursePlanSessionNo')[$key] != null) {
  7175.                     if (!isset($coursePlanData[$request->request->get('coursePlanSessionNo')[$key]]))
  7176.                         $coursePlanData[$request->request->get('coursePlanSessionNo')[$key]] = [];
  7177.                     $coursePlanData[$request->request->get('coursePlanSessionNo')[$key]][] = [
  7178.                         'sessionNo' => $request->request->get('coursePlanSessionNo')[$key],
  7179.                         'subject' => $request->request->get('coursePlanSubject')[$key],
  7180.                         'details' => $request->request->get('coursePlanDetails')[$key],
  7181.                         'optimumMin' => $request->request->get('coursePlanOptimumMin')[$key],
  7182.                     ];
  7183.                 }
  7184.             $routineData = [];
  7185.             foreach ($request->request->get('routine_sequence', []) as $key => $value) {
  7186.                 $routineData[] = [
  7187.                     'sequence' => $request->request->get('routine_sequence')[$key],
  7188.                     'topicId' => $request->request->get('routine_topic_id')[$key],
  7189.                     'topicName' => $request->request->get('routine_topic_name')[$key],
  7190.                     'meetingType' => $request->request->get('routine_topic_meeting_type')[$key],
  7191.                     'duration' => $request->request->get('routine_duration')[$key],
  7192.                     'offset' => $request->request->get('routine_offset')[$key],
  7193.                     'coins' => $request->request->get('routine_coins')[$key],
  7194.                     'nextSequenceStart' => $request->request->has('routine_next_sequence_start_' $value) ? 0,
  7195.                     'modifiable' => $request->request->has('routine_modifiable_' $value) ? 0,
  7196.                 ];
  7197.             }
  7198.             $sessionData = [];
  7199.             foreach ($request->request->get('sessionId', []) as $key => $value)
  7200.                 $sessionData[] = [
  7201.                     'sessionId' => $request->request->get('sessionId')[$key],
  7202.                     'sessionYear' => $request->request->get('year')[$key],
  7203.                     'threshold' => $request->request->get('threshold')[$key],
  7204.                     'sessionStart' => $request->request->get('sessionStart')[$key],
  7205.                     'applicationStartDate' => $request->request->get('applicationStartDate')[$key],
  7206.                 ];
  7207.             $coursesData = [];
  7208.             foreach ($request->request->get('courseName', []) as $key => $value)
  7209.                 $coursesData[] = [
  7210.                     'courseName' => $request->request->get('courseName')[$key],
  7211.                 ];
  7212.             $departmentData = [];
  7213.             foreach ($request->request->get('departmentName', []) as $key => $value)
  7214.                 $departmentData[] = [
  7215.                     'departmentName' => $request->request->get('departmentName')[$key],
  7216.                 ];
  7217.             $benefitsData = [];
  7218.             foreach ($request->request->get('benefit', []) as $key => $value)
  7219.                 $benefitsData[] = [
  7220.                     'benefit' => $request->request->get('benefit')[$key],
  7221.                 ];
  7222.             $new->setRoutineData(json_encode($routineData));
  7223.             $new->setDocumentData(json_encode($docData));
  7224.             $new->setCoursePlanData(json_encode($coursePlanData));
  7225.             $new->setSessionData(json_encode($sessionData));
  7226.             $new->setCourses(json_encode($coursesData));
  7227.             $new->setDepartments(json_encode($departmentData));
  7228.             $new->setBenefits(json_encode($benefitsData));
  7229.             $otherDataObj = [];
  7230.             foreach (BuddybeeConstant::$otherDataByHash as $ohash => $otherDataGroup)
  7231.                 foreach ($otherDataGroup as $otherData) {
  7232.                     $fieldExists $request->request->has($ohash '_' $otherData['field']);
  7233.                     if ($fieldExists) {
  7234.                         $fieldValue $request->request->get($ohash '_' $otherData['field'], '');
  7235.                         $otherDataObj[$ohash '_' $otherData['field']] = $fieldValue;
  7236.                     }
  7237.                 }
  7238.             $new->setOtherData(json_encode($otherDataObj));
  7239.             $new->setBenefits(json_encode($benefitsData));
  7240.             $em->persist($new);
  7241.             $em->flush();
  7242.             $path "";
  7243.             $defaultProductImage '';
  7244.             $uploadedFile null;
  7245.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
  7246.             $uploadedFile $request->files->get('topicSummaryImage');
  7247.             if ($uploadedFile != null) {
  7248.                 $fileName 'TSI' $new->getId() . '.' $uploadedFile->guessExtension();
  7249.                 $path $fileName;
  7250. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7251.                 if (!file_exists($upl_dir)) {
  7252.                     mkdir($upl_dir0777true);
  7253.                 }
  7254.                 $uploadedFile->move($upl_dir$path);
  7255.                 $defaultProductImage 'uploads/topicImage/' $path;
  7256.                 $new->setTopicSummaryImage($defaultProductImage);
  7257.                 $em->flush();
  7258.             }
  7259.             $path "";
  7260.             $defaultProductImage '';
  7261.             $uploadedFile null;
  7262.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
  7263.             $uploadedFile $request->files->get('topicImage');
  7264.             if ($uploadedFile != null) {
  7265.                 $fileName 'TI' $new->getId() . '.' $uploadedFile->guessExtension();
  7266.                 $path $fileName;
  7267. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7268.                 if (!file_exists($upl_dir)) {
  7269.                     mkdir($upl_dir0777true);
  7270.                 }
  7271.                 $uploadedFile->move($upl_dir$path);
  7272.                 $defaultProductImage 'uploads/topicImage/' $path;
  7273.                 $new->setTopicImage($defaultProductImage);
  7274.                 $em->flush();
  7275.             }
  7276.             $this->addFlash(
  7277.                 'success',
  7278.                 'Topic Added.'
  7279.             );
  7280.         }
  7281.         return $this->render('@Application/pages/human_resource/input_forms/create_topic.html.twig', array(
  7282.             'page_title' => 'Create Topic',
  7283.             'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
  7284.             'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
  7285.             'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
  7286.             'document' => $document,
  7287.             'topic' => $topic,
  7288.             'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
  7289.             'topicId' => $topicId,
  7290.             'topicList' => $topicList,
  7291.             'topicMarker' => BuddybeeConstant::$topicMarkup,
  7292.             'sessionName' => $sessionName,
  7293.         ));
  7294.     }
  7295.     public function ConsultancyRequirementSettingsAction(Request $request$id 0)
  7296.     {
  7297.         $em $this->getDoctrine()->getManager('company_group');
  7298.         $entityList $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findAll();
  7299.         $documentQRY $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findAll();
  7300.         $entity = [];
  7301.         $sessionName BuddybeeConstant::$sessionName;
  7302.         $document = [];
  7303.         foreach ($documentQRY as $d) {
  7304.             $document[$d->getId()] = array(
  7305.                 'id' => $d->getId(),
  7306.                 'documentName' => $d->getDocumentName(),
  7307.                 'text' => $d->getDocumentName(),
  7308.             );
  7309.         }
  7310.         $countryId $id;
  7311.         if ($countryId != 0)
  7312.             $entity $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findOneBy(
  7313.                 array(
  7314.                     'countryId' => $countryId
  7315.                 )
  7316.             );
  7317.         if ($request->isMethod('POST')) {
  7318.             if ($request->request->has('countryId'))
  7319.                 $countryId $request->request->get('countryId');
  7320. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7321.             if ($countryId != 0) {
  7322.                 $new $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findOneBy(
  7323.                     array(
  7324.                         'countryId' => $countryId
  7325.                     )
  7326.                 );
  7327.                 if (!$new)
  7328.                     $new = new EntityCountryConsultantRequirements();
  7329.             } else
  7330.                 $new = new EntityCountryConsultantRequirements();
  7331.             $new->setCountryId($request->request->get('countryId'));
  7332.             $new->setContractLetterHtml($request->request->get('contractLetterHtml'));
  7333.             $new->setRequiredFields($request->request->get('requiredFields'));
  7334.             $new->setAllowedWorkingHoursPerDay($request->request->get('allowedWorkingHoursPerDay'));
  7335.             $new->setAllowedWorkingHoursPerMonth($request->request->get('allowedWorkingHoursPerMonth'));
  7336.             $new->setAllowedWorkingHoursPerWeek($request->request->get('allowedWorkingHoursPerWeek'));
  7337.             $new->setAllowedWorkingHoursPerYear($request->request->get('allowedWorkingHoursPerYear'));
  7338.             $new->setAllowedEarningPerDay($request->request->get('allowedEarningPerDay'));
  7339.             $new->setAllowedEarningPerMonth($request->request->get('allowedEarningPerMonth'));
  7340.             $new->setAllowedEarningPerWeek($request->request->get('allowedEarningPerWeek'));
  7341.             $new->setAllowedEarningPerYear($request->request->get('allowedEarningPerYear'));
  7342.             $new->setRevenuePercentagePerSession($request->request->get('revenuePercentagePerSession'));
  7343.             $docData = [];
  7344.             foreach ($request->request->get('document', []) as $key => $value)
  7345.                 $docData[] = [
  7346.                     'document' => $request->request->get('document')[$key],
  7347.                     'expDays' => $request->request->get('expDays')[$key],
  7348.                     'stage' => $request->request->get('stage')[$key],
  7349.                     'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
  7350.                     'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
  7351.                     'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
  7352.                     'checklist' => explode(","$request->request->get('checkList')[$key])
  7353.                 ];
  7354.             $new->setDocumentList(json_encode($docData));
  7355.             $em->persist($new);
  7356.             $em->flush();
  7357.             $this->addFlash(
  7358.                 'success',
  7359.                 'Restriction Updated.'
  7360.             );
  7361.         }
  7362.         return $this->render('@Buddybee/pages/create_consultancy_requirements.html.twig', array(
  7363.             'page_title' => 'Create Requirements',
  7364.             'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
  7365.             'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
  7366.             'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
  7367.             'document' => $document,
  7368.             'entity' => $entity,
  7369.             'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
  7370.             'countryId' => $countryId,
  7371.             'entityList' => $entityList,
  7372.             'topicMarker' => BuddybeeConstant::$topicMarkup,
  7373.             'sessionName' => $sessionName,
  7374.         ));
  7375.     }
  7376.     public function PromoCodeSettingsAction(Request $request$id 0)
  7377.     {
  7378.         $em $this->getDoctrine()->getManager('company_group');
  7379.         $entityList $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')->findAll();
  7380.         $applicantList $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
  7381.         $promoCodeId $id;
  7382.         $entity = [];
  7383.         if ($promoCodeId != 0)
  7384.             $entity $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')->findOneBy(
  7385.                 array(
  7386.                     'id' => $promoCodeId
  7387.                 )
  7388.             );
  7389.         if ($request->isMethod('POST')) {
  7390.             if ($request->request->has('promoCodeId'))
  7391.                 $promoCodeId $request->request->get('promoCodeId');
  7392. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7393.             if ($promoCodeId != 0) {
  7394.                 $new $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')->findOneBy(
  7395.                     array(
  7396.                         'id' => $promoCodeId
  7397.                     )
  7398.                 );
  7399.                 if (!$new)
  7400.                     $new = new PromoCode();
  7401.             } else
  7402.                 $new = new PromoCode();
  7403. //            $new->setCountryId($request->request->get('countryId'));
  7404.             $new->setCode($request->request->get('code'''));
  7405.             $new->setPromoType($request->request->get('promoType'1));
  7406.             $new->setPromoCodeType($request->request->get('promoCodeType'1));
  7407.             $new->setPromoValue($request->request->get('promoValue'0));
  7408.             $new->setPerpetual($request->request->get('perpetual'0));
  7409.             $new->setMaxDiscountAmount($request->request->get('maxDiscountAmount', -1));
  7410.             $new->setMaxCoinAddition($request->request->get('maxCoinAddition', -1));
  7411.             $new->setMinAmountForApplication($request->request->get('minAmountForApplication'0));
  7412.             $new->setMinCoinForApplication($request->request->get('minCoinForApplication'0));
  7413.             $new->setNextApplicationEachCoinCount($request->request->get('nextApplicationEachCoinCount', -1));
  7414.             $new->setMaxUseCount($request->request->get('maxUseCount', -1));
  7415.             $new->setMaxUseCountPerUser($request->request->get('maxUseCountPerUser', -1));
  7416.             $new->setUseCountBalance($request->request->get('useCountBalance', -1));
  7417.             $new->setReferralApplicantId($request->request->get('referralApplicantId'0));
  7418.             $new->setMaxReferralCommissionCount($request->request->get('maxReferralCommissionCount'0));
  7419.             $new->setReferralCommissionCountBalance($request->request->get('referralCommissionCountBalance'0));
  7420.             $new->setReferralCommissionType($request->request->get('referralCommissionType'1));
  7421.             $new->setReferralAmount($request->request->get('referralAmount'0));
  7422.             $startsAt = new \DateTime($request->request->get('startsAt'''));
  7423.             $expiresAt = new \DateTime($request->request->get('expiresAt'''));
  7424.             $new->setStartsAtTs($startsAt->format('U'));
  7425.             $new->setExpiresAtTs($expiresAt->format('U'));
  7426. //
  7427. //        startsAtTs:
  7428. //            type: integer
  7429. //            nullable: true
  7430. //        expiresAtTs:
  7431. //            type: integer
  7432. //            nullable: true
  7433.             $em->persist($new);
  7434.             $em->flush();
  7435.             $this->addFlash(
  7436.                 'success',
  7437.                 'Promo Code Updated.'
  7438.             );
  7439.         }
  7440.         return $this->render('@Buddybee/pages/buddybee_promo_code_settings.html.twig', array(
  7441.             'page_title' => 'Promo Codes',
  7442.             'entity' => $entity,
  7443.             'promoCodeId' => $promoCodeId,
  7444.             'entityList' => $entityList,
  7445.             'applicantList' => $applicantList,
  7446.         ));
  7447.     }
  7448.     public function createDocumentAction(Request $request$id 0)
  7449.     {
  7450.         $em $this->getDoctrine()->getManager('company_group');
  7451.         $companyId $this->getLoggedUserCompanyId($request);
  7452.         $document $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findAll();
  7453.         $thisDoc = [];
  7454.         if ($id != 0)
  7455.             $thisDoc $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findOneBy(
  7456.                 array(
  7457.                     'Id' => $id
  7458.                 )
  7459.             );
  7460.         if ($request->isMethod('POST')) {
  7461.             if ($id != 0)
  7462.                 $new $thisDoc;
  7463.             else
  7464.                 $new = new EntityCreateDocument();
  7465.             $new->setDocumentName($request->request->get('docName'));
  7466.             $new->setExpiryDays($request->request->get('expDays'));
  7467.             $new->setProcessingDays($request->request->get('processingDays'));
  7468.             $new->setEmergencyProcessingDays($request->request->get('emergencyProcessingDays'));
  7469.             $new->setDocVideo($request->request->get('docVideoLink'));
  7470.             $new->setRequiredDocument(json_encode($request->request->get('requiredDoc')));
  7471.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7472.             $arr = [
  7473.                 'checkListName' => $request->request->get('checkListName'),
  7474.             ];
  7475.             $new->setCheckList(json_encode($arr));
  7476.             $em->persist($new);
  7477.             $em->flush();
  7478.         }
  7479.         $this->addFlash(
  7480.             'Document Added',
  7481.             'Topic Added.'
  7482.         );
  7483.         return $this->render('@Application/pages/human_resource/input_forms/create_document.html.twig', array(
  7484.             'page_title' => 'Create Document',
  7485.             'document' => $document,
  7486.             'thisDoc' => $thisDoc
  7487.         ));
  7488.     }
  7489.     public function getIndividualDocumentAction(Request $request$id)
  7490.     {
  7491.         $em $this->getDoctrine()->getManager('company_group');
  7492.         if ($id == 0) {
  7493.             if ($request->request->has('documentId'))
  7494.                 $id $request->request->get('documentId');
  7495.         }
  7496.         $document $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->find($id);
  7497.         return new JsonResponse(
  7498.             array(
  7499.                 'success' => true,
  7500.                 'rowId' => $request->request->get('rowId'),
  7501.                 'expiryDays' => $document->getExpiryDays(),
  7502.                 'processingDays' => $document->getProcessingDays(),
  7503.                 'emergencyProcessing' => $document->getEmergencyProcessingDays(),
  7504.                 'checklist' => json_decode($document->getCheckList()),
  7505.             )
  7506.         );
  7507.     }
  7508.     public function createBlogAction(Request $request$id)
  7509.     {
  7510.         if (!$id) {
  7511.             if ($request->isMethod('POST')) {
  7512.                 $em $this->getDoctrine()->getManager('company_group');
  7513.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7514.                 $new = new EntityCreateBlog();
  7515.                 $new->setTopicId($request->request->get('topicId'));
  7516.                 $new->setTitle($request->request->get('title'));
  7517.                 $new->setSubtitle($request->request->get('subTitle'));
  7518.                 $new->setContent($request->request->get('content'));
  7519.                 $new->setVideoLink($request->request->get('videoLink'));
  7520.                 $new->setAuthorName($request->request->get('authorName'));
  7521.                 $new->setAuthorSummary($request->request->get('authorSummary'));
  7522.                 $new->setIsPrimaryBlog($request->request->get('checkPrimaryBlog'));
  7523.                 $em->persist($new);
  7524.                 $em->flush();
  7525.                 //$fileName = 'cv' . $consultantDetails->getApplicantId() . '.' . $uploadedFile->guessExtension();
  7526.                 $path "";
  7527.                 $defaultProductImage '';
  7528.                 $uploadedFile null;
  7529.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7530.                 $uploadedFile $request->files->get('authorImage');
  7531.                 if ($uploadedFile != null) {
  7532.                     $fileName 'authorImage' $new->getId() . '.' $uploadedFile->guessExtension();
  7533.                     $path $fileName;
  7534. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7535.                     if (!file_exists($upl_dir)) {
  7536.                         mkdir($upl_dir0777true);
  7537.                     }
  7538.                     $uploadedFile->move($upl_dir$path);
  7539.                     $defaultProductImage 'uploads/authorImage/' $path;
  7540.                     $new->setAuthorImage($defaultProductImage);
  7541.                     $em->flush();
  7542.                 }
  7543.                 $path "";
  7544.                 $defaultProductImage '';
  7545.                 $uploadedFile null;
  7546.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/mainImage/';
  7547.                 $uploadedFile $request->files->get('main_img');
  7548.                 if ($uploadedFile != null) {
  7549.                     $fileName 'mainImage' $new->getId() . '.' $uploadedFile->guessExtension();
  7550.                     $path $fileName;
  7551. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7552.                     if (!file_exists($upl_dir)) {
  7553.                         mkdir($upl_dir0777true);
  7554.                     }
  7555.                     $uploadedFile->move($upl_dir$path);
  7556.                     $defaultProductImage 'uploads/mainImage/' $path;
  7557.                     $new->setMainImage($defaultProductImage);
  7558.                     $em->flush();
  7559.                 }
  7560.                 $topicDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(
  7561.                     array(
  7562.                         'id' => $request->request->get('topicId')
  7563.                     )
  7564.                 );
  7565.                 if ($new->getIsPrimaryBlog() == 1) {
  7566.                     if ($topicDetails)
  7567.                         $topic $topicDetails;
  7568.                     else
  7569.                         $topic = new EntityCreateTopic();
  7570.                     $topic->setPrimaryBlogId($new->getId());
  7571.                     $em->flush();
  7572.                 }
  7573.                 $this->addFlash(
  7574.                     'success',
  7575.                     'Blog Added.'
  7576.                 );
  7577.             } else {
  7578.                 $em $this->getDoctrine()->getManager('company_group');
  7579.                 $topic $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findAll();
  7580.                 $applicant $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
  7581.                 $blogs $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateBlog')->findAll();
  7582.                 $topicIds = [];
  7583.                 foreach ($blogs as $blog) {
  7584.                     $topicIds [] = $blog->getTopicId();
  7585.                 }
  7586. //                $topic = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findBy(
  7587. //                    array(
  7588. //                        'id' => $topicIds
  7589. //                    )
  7590. //                );
  7591.                 return $this->render('@Application/pages/human_resource/input_forms/create_blog.html.twig', array(
  7592.                     'page_title' => 'Create Blog',
  7593.                     'topic' => $topic,
  7594.                     'applicant' => $applicant,
  7595.                     'blog' => $blogs,
  7596.                     'id' => $id,
  7597.                 ));
  7598.             }
  7599.         } else {
  7600.             if ($request->isMethod('GET')) {
  7601.                 $em $this->getDoctrine()->getManager('company_group');
  7602.                 $topic $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findAll();
  7603.                 $applicant $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
  7604.                 $blogs $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateBlog')->find($id);
  7605.                 return $this->render('@Application/pages/human_resource/input_forms/create_blog.html.twig', array(
  7606.                     'page_title' => 'Create Blog',
  7607.                     'topic' => $topic,
  7608.                     'applicant' => $applicant,
  7609.                     'blog' => $blogs,
  7610.                     'id' => $id,
  7611.                 ));
  7612.             } else {
  7613.                 $em $this->getDoctrine()->getManager('company_group');
  7614.                 $new = new EntityCreateBlog();
  7615.                 $new->setTopicId($request->request->get('topicId'));
  7616.                 $new->setTitle($request->request->get('title'));
  7617.                 $new->setSubtitle($request->request->get('subTitle'));
  7618.                 $new->setContent($request->request->get('content'));
  7619.                 $new->setVideoLink($request->request->get('videoLink'));
  7620.                 $new->setAuthorName($request->request->get('authorName'));
  7621.                 $new->setAuthorSummary($request->request->get('authorSummary'));
  7622.                 //$em->persist($new);
  7623.                 $em->flush();
  7624.                 $path "";
  7625.                 $defaultProductImage '';
  7626.                 $uploadedFile null;
  7627.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7628.                 $uploadedFile $request->files->get('authorImage');
  7629.                 if ($uploadedFile != null) {
  7630.                     $fileName 'authorImage' '.' $uploadedFile->guessExtension();
  7631.                     $path $fileName;
  7632. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7633.                     if (!file_exists($upl_dir)) {
  7634.                         mkdir($upl_dir0777true);
  7635.                     }
  7636.                     $uploadedFile->move($upl_dir$path);
  7637.                     $defaultProductImage 'uploads/authorImage/' $path;
  7638.                     $new->setAuthorImage($defaultProductImage);
  7639.                     $em->flush();
  7640.                 }
  7641.                 $this->addFlash(
  7642.                     'success',
  7643.                     'Blog Updated.'
  7644.                 );
  7645.             }
  7646.         }
  7647.         return new JsonResponse(
  7648.             array(
  7649.                 'success' => true,
  7650.             )
  7651.         );
  7652. //        if ($request->isMethod('POST')) {
  7653. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7654. //
  7655. //            $new = new EntityCreateBlog();
  7656. //
  7657. //            $new->setTopicId($request->request->get('topicId'));
  7658. //            $new->setTitle($request->request->get('title'));
  7659. //            $new->setSubtitle($request->request->get('subTitle'));
  7660. //            $new->setContent($request->request->get('content'));
  7661. //            $new->setVideoLink($request->request->get('videoLink'));
  7662. //            $new->setAuthorName($request->request->get('authorName'));
  7663. //            $new->setAuthorSummary($request->request->get('authorSummary'));
  7664. //
  7665. //            $em->persist($new);
  7666. //            $em->flush();
  7667. //
  7668. //
  7669. //            $path = "";
  7670. //            $defaultProductImage = '';
  7671. //            $uploadedFile = null;
  7672. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7673. //            $uploadedFile=  $request->files->get('authorImage');
  7674. //
  7675. //            if ($uploadedFile != null) {
  7676. //
  7677. //                $fileName = 'authorImage' .'.' . $uploadedFile->guessExtension();
  7678. //                $path = $fileName;
  7679. ////            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7680. //                if (!file_exists($upl_dir)) {
  7681. //                    mkdir($upl_dir, 0777, true);
  7682. //                }
  7683. //                $uploadedFile->move($upl_dir, $path);
  7684. //                $defaultProductImage = 'uploads/authorImage/' . $path;
  7685. //                $new->setAuthorImage($defaultProductImage);
  7686. //                $em->flush();
  7687. //
  7688. //            }
  7689. //            $this->addFlash(
  7690. //                'success',
  7691. //                'Blog Added.'
  7692. //            );
  7693. //        }
  7694. //        return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7695. //            'page_title' => 'Create Blog',
  7696. //            'topic'=> $topic,
  7697. //            'applicant' => $applicant,
  7698. //            'blog' => $blogs
  7699. //        ));
  7700.     }
  7701.     public function applicantConsultancyAction()
  7702.     {
  7703.         return $this->render('@Application/pages/human_resource/input_forms/consultancy.html.twig', array(
  7704.             'page_title' => 'Consultancy',
  7705.         ));
  7706.     }
  7707.     public function viewConsultantDetailsAction(Request $request$id 0)
  7708.     {
  7709.         $gocEnabled 1;
  7710.         $currAppId 4;
  7711.         $honeybeeAppId 1;
  7712.         $buddybeeAppId 4;
  7713.         $em_goc $this->getDoctrine()->getManager('company_group');
  7714.         $em $this->getDoctrine()->getManager();
  7715.         $option = [];
  7716.         $option['appId'] = $currAppId//honeybee
  7717.         $option['departmentId'] = 18//consultancy
  7718.         $option['designationId'] = 50;
  7719. //        $dataToConnect = System::changeDoctrineManagerByAppId(
  7720. //            $this->getDoctrine()->getManager('company_group'),
  7721. //            $gocEnabled,
  7722. //            $currAppId
  7723. //        );
  7724. //        if (!empty($dataToConnect)) {
  7725. //            $connector = $this->container->get('application_connector');
  7726. //            $connector->resetConnection(
  7727. //                'default',
  7728. //                $dataToConnect['dbName'],
  7729. //                $dataToConnect['dbUser'],
  7730. //                $dataToConnect['dbPass'],
  7731. //                $dataToConnect['dbHost'],
  7732. //                $reset = true
  7733. //            );
  7734. //            $em = $this->getDoctrine()->getManager();
  7735. //        } else {
  7736. //            $currAppId = $honeybeeAppId;
  7737. //            $dataToConnectAgain = System::changeDoctrineManagerByAppId(
  7738. //                $this->getDoctrine()->getManager('company_group'),
  7739. //                $gocEnabled,
  7740. //                $currAppId
  7741. //            );
  7742. //            if (!empty($dataToConnectAgain)) {
  7743. //                $connector = $this->container->get('application_connector');
  7744. //                $connector->resetConnection(
  7745. //                    'default',
  7746. //                    $dataToConnect['dbName'],
  7747. //                    $dataToConnect['dbUser'],
  7748. //                    $dataToConnect['dbPass'],
  7749. //                    $dataToConnect['dbHost'],
  7750. //                    $reset = true
  7751. //                );
  7752. //                $em = $this->getDoctrine()->getManager();
  7753. //            }
  7754. //
  7755. //        }
  7756.         $consultantDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($id);
  7757.         $skill $em_goc->getRepository(EntitySkill::class)->findAll();
  7758.         $gender HumanResourceConstant::$sex;
  7759.         $blood HumanResourceConstant::$BloodGroup;
  7760.         $consultantLevel HumanResourceConstant::$consultantLevel;
  7761.         $companyId $this->getLoggedUserCompanyId($request);
  7762.         $designation $em->getRepository("ApplicationBundle\\Entity\\SysDepartmentPosition")->findAll();
  7763.         $departments $em->getRepository("ApplicationBundle\\Entity\\SysDepartment")->findAll();
  7764.         $companyData Company::getCompanyData($em$companyId);
  7765.         $currDate = new \DateTime();
  7766.         if ($request->isMethod('POST')) {
  7767.             //for consultant only
  7768.             $convertToConsultant HumanResource::convertToConsultant($em_goc$em$id$option$request->request);
  7769.             if ($request->request->get('confirmStatus'0) == 1) {
  7770.                 $bodyTemplate '@Application/email/templates/consultantApprovalEmail.html.twig';
  7771.                 $contractLetterHtml '';
  7772.                 $bodyData = array(
  7773.                     'name' => $consultantDetails->getFirstname() . ' ' $consultantDetails->getLastname(),
  7774.                     'companyData' => $companyData,
  7775.                     'contractLetterHtml' => $contractLetterHtml,
  7776.                     'commentText' => $request->request->get('commentText'),
  7777.                 );
  7778.                 $new_mail $this->get('mail_module');
  7779.                 $new_mail->sendMyMail(array(
  7780.                     'senderHash' => '_CUSTOM_',
  7781.                     'encryptionMethod' => 'ssl',
  7782.                     'userName' => 'management@buddybee.eu',
  7783.                     'fromAddress' => 'management@buddybee.eu',
  7784.                     'password' => 'Eco@0112',
  7785.                     'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  7786.                     'smtpPort' => '465',
  7787.                     'forwardToMailAddress' => $consultantDetails->getEmail(),
  7788.                     'subject' => 'Consultant Contract Letter Of ' $consultantDetails->getFirstName(),
  7789.                     'fileName' => '',
  7790.                     //'attachments' => $attachments,
  7791.                     'toAddress' => $consultantDetails->getEmail(),
  7792.                     'mailTemplate' => $bodyTemplate,
  7793.                     'templateData' => $bodyData,
  7794.                     'embedCompanyImage' => 1,
  7795.                     'companyId' => $companyId,
  7796.                     'companyImagePath' => ""
  7797.                 ));
  7798.             }
  7799.             if ($request->request->get('confirmStatus'0) == 0) {
  7800.                 $bodyTemplate '@Application/email/templates/consultantRejectionEmail.html.twig';
  7801.                 $contractLetterHtml '';
  7802.                 $bodyData = array(
  7803.                     'name' => $consultantDetails->getFirstname() . ' ' $consultantDetails->getLastname(),
  7804.                     'companyData' => $companyData,
  7805.                     'contractLetterHtml' => $contractLetterHtml,
  7806.                     'commentText' => $request->request->get('commentText'),
  7807.                 );
  7808.                 $new_mail $this->get('mail_module');
  7809.                 $new_mail->sendMyMail(array(
  7810.                     'senderHash' => '_CUSTOM_',
  7811.                     'encryptionMethod' => 'ssl',
  7812.                     'userName' => 'management@buddybee.eu',
  7813.                     'fromAddress' => 'management@buddybee.eu',
  7814.                     'password' => 'Eco@0112',
  7815.                     'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  7816.                     'smtpPort' => '465',
  7817.                     'forwardToMailAddress' => $consultantDetails->getEmail(),
  7818.                     'subject' => 'Rejection Letter Of ' $consultantDetails->getFirstName(),
  7819.                     'fileName' => '',
  7820.                     //'attachments' => $attachments,
  7821.                     'toAddress' => $consultantDetails->getEmail(),
  7822.                     'mailTemplate' => $bodyTemplate,
  7823.                     'templateData' => $bodyData,
  7824.                     'embedCompanyImage' => 1,
  7825.                     'companyId' => $companyId,
  7826.                     'companyImagePath' => ""
  7827.                 ));
  7828.             }
  7829.         }
  7830.         $docList MiscActions::GetDocumentDataForBuddybeeConsultantApply($em_goc,
  7831.             $id,
  7832.             $consultantDetails->getCurrentCountryId()
  7833.         );
  7834.         return $this->render('@Application/pages/human_resource/views/viewConsultantDetails.html.twig', array(
  7835.             'page_title' => 'Consultant Details',
  7836.             'applicantId' => $id,
  7837.             'consultantDetails' => $consultantDetails,
  7838.             'education' => json_decode($consultantDetails->getEducationData(), true),
  7839.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  7840.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  7841.             'gender' => $gender,
  7842.             'blood' => $blood,
  7843.             'skill' => $skill,
  7844.             'docList' => $docList,
  7845.             'countryId' => $consultantDetails->getCurrentCountryId(),
  7846.             'consultantLevel' => $consultantLevel,
  7847.             'designation' => $designation,
  7848.             'department' => $departments
  7849.         ));
  7850.     }
  7851.     public function ApplicableEmployeSettingsAction()
  7852.     {
  7853.         $em $this->getDoctrine()->getManager();
  7854.         $employeeIds $em->getRepository(Employee::class)->findAll();
  7855.         return $this->render('@Application/pages/human_resource/input_forms/applicable_employee_settings.html.twig', array(
  7856.             'page_title' => 'Applicable Employee Settings',
  7857.             'employeeIds' => $employeeIds
  7858.         ));
  7859.     }
  7860.     public function GetApplicableSettingsForSingleEmployeeAction($id)
  7861.     {
  7862.         $em $this->getDoctrine()->getManager();
  7863.         $bankLists $em->getRepository(WorkHourPolicy::class)->findAll();
  7864.         if (json_decode($bankLists->getEmployeeIds()) == $id) {
  7865.             return new JsonResponse(
  7866.                 array(
  7867.                     'success' => true,
  7868.                     'msg' => 'employee found'
  7869.                 )
  7870.             );
  7871.         } else {
  7872.             return new JsonResponse(
  7873.                 array(
  7874.                     'success' => true,
  7875.                     'msg' => 'employee not found'
  7876.                 )
  7877.             );
  7878.         }
  7879.     }
  7880. //    public function  getEmployeeDataAction(){
  7881. //        $em = $this->getDoctrine()->getManager();
  7882. //        $emplyeeDetails =  $em->getRepository('ApplicationBundle\\Entity\\EmployeeDeatils')->findAll();
  7883. //        $days = HumanResourceConstant::$days;
  7884. //        $holidays = ;
  7885. //        $workHourPolicies = ;
  7886. //
  7887. //    }
  7888.     public function meetingSchedulingForTabAction()
  7889.     {
  7890.         $em $this->getDoctrine()->getManager();
  7891.         $date date('Y-m-d');
  7892.         $month date('m');
  7893.         $year date('Y');
  7894.         $monthName date("F"mktime(000$month));
  7895.         $totalDayOfMonth cal_days_in_month(CAL_GREGORIAN$month$year);
  7896.         $fromdt date('Y-m-01 'strtotime("First Day Of  $monthName $year"));
  7897. //        echo "Start Date : $fromdt" . "<br>";
  7898.         $todt date('Y-m-d 'strtotime("Last Day of $monthName $year"));
  7899. //        echo "End Date : $todt" . "<br>";
  7900.         $num_friday '';
  7901.         for ($i 0$i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
  7902.             if (date('l'strtotime($fromdt) + ($i 86400)) == 'Friday') {
  7903.                 $num_friday++;
  7904.             }
  7905.         }
  7906.         $num_saturday '';
  7907.         for ($i 0$i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
  7908.             if (date('l'strtotime($fromdt) + ($i 86400)) == 'Saturday') {
  7909.                 $num_saturday++;
  7910.             }
  7911.         }
  7912.         $totalWeekends $num_saturday $num_friday;
  7913.         $totalCompanyWorkingDay $totalDayOfMonth $totalWeekends;
  7914. //        $attendanceData=$em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')->findOneBy(
  7915. //            array(
  7916. //                'employeeId' => 3
  7917. //            )
  7918. //        );
  7919.         $DateRange = [];
  7920.         $holidayDates $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')->findAll();
  7921.         foreach ($holidayDates as $holiday) {
  7922.             $holidaayData = array(
  7923.                 'startDate' => $holiday->getStartDate(),
  7924.                 'endDate' => $holiday->getEndDate(),
  7925.             );
  7926.             $DateRange $holidaayData;
  7927.         }
  7928.         $employeeDataDetail = [];
  7929.         $employeeDetail $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findOneBy(
  7930.             array(
  7931.                 'id' => 3
  7932.             )
  7933.         );
  7934. //        foreach($employeeDetail as $employee){
  7935.         $employeeData = array(
  7936.             'firstName' => $employeeDetail->getFirstname(),
  7937.             'firstname' => $employeeDetail->getFirstname(),
  7938.             'lastName' => $employeeDetail->getLastname(),
  7939.             'lastname' => $employeeDetail->getLastname(),
  7940.             'name' => trim($employeeDetail->getFirstname() . ' ' $employeeDetail->getLastname()),
  7941.             'empCode' => $employeeDetail->getEmpCode(),
  7942.             'emp_code' => $employeeDetail->getEmpCode(),
  7943.             'employeeCode' => $employeeDetail->getEmpCode(),
  7944.             'basic' => $employeeDetail->getEar1(),
  7945.             'dearness' => $employeeDetail->getEar2(),
  7946.             'houseRent' => $employeeDetail->getEar3(),
  7947.             'medical' => $employeeDetail->getEar4(),
  7948.             'leaveTravel' => $employeeDetail->getEar5(),
  7949.             'childEducation' => $employeeDetail->getEar6(),
  7950.             'totalEarning' => $employeeDetail->getEart(),
  7951.         );
  7952.         $employeeDataDetail $employeeData;
  7953. //        }
  7954.         $attendanceData $em->getRepository(EmployeeAttendanceLog::class);
  7955. //        $employeeId = $attendanceData->getEmployeeId();
  7956. //        $countId = count($employeeId);
  7957.         $totalPresent $attendanceData->createQueryBuilder('a')
  7958.             // Filter by some parameter if you want
  7959.             ->where('a.employeeId = 3')
  7960.             ->andWhere('a.isPresent = 1')
  7961.             ->select('a.isPresent')
  7962.             ->getQuery()
  7963.             ->getResult();
  7964. //        $countAt = 0;
  7965.         $count count($totalPresent);
  7966. //        $count = $countAt+$count;
  7967.         //get holiday
  7968.         $holidayStartDate $DateRange['startDate']->format('Y-m-d');
  7969.         $holidayEndDate $DateRange['endDate']->format('Y-m-d');
  7970.         $dates HumanResource::getBetweenDates($holidayStartDate$holidayEndDate);
  7971.         $dateCount count($dates);
  7972.         $totalOffDay $totalWeekends $dateCount;
  7973.         $totalCompanyWorkingDay $totalDayOfMonth $totalOffDay;
  7974.         $totalAbsent $totalCompanyWorkingDay $count;
  7975. //        foreach($dates as $compDate ){
  7976. //
  7977. //
  7978. //
  7979. //            if($date == $compDate){
  7980. //                echo $date;
  7981. //                echo $compDate;
  7982. //                echo "holiday" ;
  7983. //
  7984. //            }
  7985. //            else{
  7986. //                echo "no holiday" ;
  7987. //            }
  7988. //        }
  7989.         $twigData HumanResource::twigDataForWorkHourPolicy($em);
  7990.         return $this->render('@Application/pages/human_resource/list/meeting_schedule_list_for_tab.html.twig', array(
  7991.             'page_title' => 'Meeting Schedule List',
  7992.             'date' => $date,
  7993.             'totalWeekends' => $totalWeekends,
  7994.             'totalCompanyWorkingDay' => $totalCompanyWorkingDay,
  7995. //            'attendanceData' => $attendanceData,
  7996. //            'employeeId' => $employeeId,
  7997.             'count' => $count,
  7998.             'totalAbsent' => $totalAbsent,
  7999.             'employeeDataDetail' => $employeeDataDetail,
  8000.             'holiday' => $DateRange,
  8001.             'holidayStartDate' => $holidayStartDate,
  8002.             'holidayEndDate' => $holidayEndDate,
  8003.             'holidayCount' => $dateCount,
  8004.             'totalOffDay' => $totalOffDay,
  8005.             'employeeIds' => $twigData['employeeIds'],
  8006.         ));
  8007.     }
  8008.     public function getEmployeeDataForDisburseAction($id)
  8009.     {
  8010.         $em $this->getDoctrine()->getManager();
  8011.         $employeeDetail $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->find($id);
  8012.         return new JsonResponse(
  8013.             array(
  8014.                 'success' => true,
  8015.                 'firstName' => $employeeDetail->getFirstName(),
  8016.                 'firstname' => $employeeDetail->getFirstName(),
  8017.                 'lastName' => $employeeDetail->getLastName(),
  8018.                 'lastname' => $employeeDetail->getLastName(),
  8019.                 'name' => trim($employeeDetail->getFirstName() . ' ' $employeeDetail->getLastName()),
  8020.                 'employeeCode' => $employeeDetail->getEmpCode(),
  8021.                 'emp_code' => $employeeDetail->getEmpCode(),
  8022.             )
  8023.         );
  8024.     }
  8025.     public function BulkAttendanceAction(Request $request)
  8026.     {
  8027.         $em $this->getDoctrine()->getManager();
  8028.         $companyId $this->getLoggedUserCompanyId($request);
  8029.         if ($request->isMethod('POST')) {
  8030.             $attendance = [];
  8031.             foreach ($request->request->get('date') as $key => $val) {
  8032.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8033.                 $bulkAttendance null;
  8034.                 if ($request->request->get('attId')[$key] != 0)
  8035.                     $bulkAttendance $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance')->findOneBy(array(
  8036.                         'id' => $request->request->get('attId')[$key],
  8037.                     ));
  8038.                 if (!$bulkAttendance)
  8039.                     $bulkAttendance = new EmployeeAttendance;
  8040.                 $theDate = new \DateTime($request->request->get('date')[$key]);
  8041.                 $bulkAttendance->setEmployeeId($request->request->get('employeeId'));
  8042.                 $bulkAttendance->setDate($theDate);
  8043.                 $bulkAttendance->setEntry(
  8044.                     ($request->request->get('startTimeTs')[$key] == '' ||
  8045.                         $request->request->get('startTimeTs')[$key] == 'NaN' ||
  8046.                         $request->request->get('startTimeTs')[$key] == 0) ? null :
  8047.                         new \DateTime('@' $request->request->get('startTimeTs')[$key])
  8048.                 );
  8049.                 $bulkAttendance->setLastOut(($request->request->get('endTimeTs')[$key] == '' ||
  8050.                     $request->request->get('endTimeTs')[$key] == 'NaN' ||
  8051.                     $request->request->get('endTimeTs')[$key] == 0) ? null :
  8052.                     new \DateTime('@' $request->request->get('endTimeTs')[$key]));
  8053.                 $bulkAttendance->setData(json_encode(
  8054.                     array(
  8055.                         "in" => json_decode($request->request->get('entryDataIn')[$key], true),
  8056.                         "out" => json_decode($request->request->get('entryDataOut')[$key], true)
  8057.                     )
  8058.                 ));
  8059. //                $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
  8060. //                $bulkAttendance->setIsPresent(1);
  8061.                 $bulkAttendance->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
  8062.                 $bulkAttendance->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
  8063. //                $bulkAttendance->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
  8064.                 $em->persist($bulkAttendance);
  8065.                 $em->flush();
  8066.                 $bulkAttendanceLog $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')->findOneBy(array(
  8067.                     'attendance_id' => $bulkAttendance->getId(),
  8068.                 ));
  8069.                 if (!$bulkAttendanceLog)
  8070.                     $bulkAttendanceLog = new EmployeeAttendanceLog;
  8071.                 $bulkAttendanceLog->setAttendanceId($bulkAttendance->getId());
  8072.                 $bulkAttendanceLog->setEmployeeId($request->request->get('employeeId'));
  8073.                 $bulkAttendanceLog->setLastStartTime(
  8074.                     ($request->request->get('startTimeTs')[$key] == '' ||
  8075.                         $request->request->get('startTimeTs')[$key] == 'NaN' ||
  8076.                         $request->request->get('startTimeTs')[$key] == 0) ? null :
  8077.                         new \DateTime('@' $request->request->get('startTimeTs')[$key])
  8078.                 );
  8079.                 $bulkAttendanceLog->setLastEndTime(($request->request->get('endTimeTs')[$key] == '' ||
  8080.                     $request->request->get('endTimeTs')[$key] == 'NaN' ||
  8081.                     $request->request->get('endTimeTs')[$key] == 0) ? null :
  8082.                     new \DateTime('@' $request->request->get('endTimeTs')[$key]));
  8083. //                $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
  8084.                 $bulkAttendanceLog->setIsPresent(1);
  8085.                 $bulkAttendanceLog->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
  8086.                 $bulkAttendanceLog->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
  8087.                 $bulkAttendanceLog->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
  8088. //                $bulkAttendanceLog->setPositionArray(json_encode($request->request->get('locations')[$key]));
  8089.                 $em->persist($bulkAttendanceLog);
  8090.                 $em->flush();
  8091.             }
  8092.         }
  8093.         $startDate $request->query->get('start_date''');
  8094.         $endDate $request->query->get('end_date''');
  8095.         $employeeId $request->query->get('employee_id'0);
  8096.         $existingData = [];
  8097.         $startDateTs 0;
  8098.         $endDateTs 0;
  8099.         $returnData = array(
  8100.             'page_title' => 'Bulk Attendance',
  8101.             'existingData' => $existingData,
  8102.             'startDateTs' => $startDateTs,
  8103.             'endDateTs' => $endDateTs,
  8104.         );
  8105.         if ($request->query->has('returnJson')) {
  8106.             if ($startDate != '' && $endDate != '' && $employeeId != 0) {
  8107.                 $startDateDt = new \DateTime($startDate);
  8108.                 $endDateDt = new \DateTime($endDate);
  8109.                 $startDateTs $startDateDt->format('U');
  8110.                 $endDateTs $endDateDt->format('U');
  8111.                 $attendanceQuery $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance')
  8112.                     ->createQueryBuilder('p')
  8113.                     ->where("p.employeeId = " $employeeId)
  8114. //                ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
  8115.                     ->andWhere("p.date <= :last")
  8116.                     ->andWhere("p.date >= :start")
  8117.                     ->setParameter('start'$startDateDt)
  8118.                     ->setParameter('last'$endDateDt);
  8119.                 $attendanceResults $attendanceQuery->getQuery()->getResult();
  8120.                 foreach ($attendanceResults as $att) {
  8121.                     $entryDateTime null;
  8122.                     $outDateTime null;
  8123.                     if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getEntry()->format('H:i:00 +0000'));
  8124.                     if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getLastOut()->format('H:i:00 +0000'));
  8125.                     $attData = array(
  8126.                         'id' => $att->getId(),
  8127.                         'date_str' => $att->getDate()->format('Y-m-d'),
  8128.                         'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
  8129.                         'in_time_full' => $entryDateTime $entryDateTime->format(DATE_RFC2822) : '',
  8130.                         'date_ts' => $att->getDate()->format('U'),
  8131.                         'in_time' => $entryDateTime $entryDateTime->format('H:i:s') : '',
  8132.                         'in_time_ts' => $entryDateTime $entryDateTime->format('U') : 0,
  8133.                         'last_out_time' => $outDateTime $outDateTime->format('H:i:s') : '',
  8134.                         'last_out_time_ts' => $outDateTime $outDateTime->format('U') : '',
  8135.                     );
  8136.                     $locations = [];
  8137.                     $locList = [];
  8138.                     $logHere $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')->findOneBy(array(
  8139.                         'attendance_id' => $att->getId(),
  8140.                     ));
  8141.                     if ($logHere)
  8142.                         $locList json_decode($logHere->getPositionArray(), true);
  8143.                     if ($locList == null)
  8144.                         $locList = [];
  8145.                     $entry_data json_decode($att->getData(), true);
  8146.                     if ($entry_data == null$entry_data = [];
  8147.                     $lastLat 0;
  8148.                     $lastLng 0;
  8149.                     foreach ($locList as $lg) {
  8150.                         $dist 0;
  8151.                         if (isset($lg['lat'])) {
  8152.                             if ($lastLat == 0) {
  8153.                                 $lastLat $lg['lat'];
  8154.                                 $lastLng $lg['lng'];
  8155.                             }
  8156.                             $theta $lastLng $lg['lng'];
  8157.                             $dist sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
  8158.                             $dist acos($dist);
  8159.                             $dist rad2deg($dist);
  8160.                             $miles $dist 60 1.1515;
  8161.                             $dist $miles 1609.344;
  8162.                             if (abs($dist) > 1000) {
  8163.                                 $locations[] = array(
  8164.                                     'ts' => $lg['ts'],
  8165.                                     'lat' => $lg['lat'],
  8166.                                     'lng' => $lg['lng'],
  8167.                                 );
  8168.                                 $lastLat $lg['lat'];
  8169.                                 $lastLng $lg['lng'];
  8170.                             }
  8171.                         }
  8172.                     }
  8173.                     $attData['locations'] = $locations;
  8174.                     $attData['entryData'] = $entry_data;
  8175.                     $existingData[$att->getDate()->format('U')] = $attData;
  8176.                 }
  8177.             }
  8178.             $returnData = array(
  8179.                 'page_title' => 'Bulk Attendance',
  8180.                 'existingData' => $existingData,
  8181.                 'startDateTs' => $startDateTs,
  8182.                 'endDateTs' => $endDateTs,
  8183.             );
  8184.             return new JsonResponse($returnData);
  8185.         } else
  8186.             return $this->render('@Application/pages/human_resource/attendance/bulk_attendance.html.twig'$returnData);
  8187.     }
  8188.     public function CreateAttendanceAmendmentAction(Request $request$id 0)
  8189.     {
  8190.         $em $this->getDoctrine()->getManager();
  8191.         $companyId $this->getLoggedUserCompanyId($request);
  8192.         $extDocData = [];
  8193.         if ($request->isMethod('POST')) {
  8194.             $em $this->getDoctrine()->getManager();
  8195.             $entity_id array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']; //change
  8196.             $dochash $request->request->get('docHash'); //change
  8197.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8198.             $approveRole $request->request->get('approvalRole');
  8199.             $approveHash $request->request->get('approvalHash');
  8200.             if ($dochash == '') {
  8201.                 $numberHash MiscActions::GetNumberHash($em'ATAM'$request->request->get('prefix_hash'$request->request->get('employeeId'0)), $request->request->get('assoc_hash'0));
  8202.                 $dochash 'ATAM' '/' $request->request->get('prefix_hash'$request->request->get('employeeId'0)) . '/' $request->request->get('assoc_hash'0) . '/' $numberHash;
  8203.             } else
  8204.                 $numberHash $request->request->get('number_hash');
  8205.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  8206.                 $loginId$approveRole$approveHash$id)
  8207.             ) {
  8208.                 if ($request->request->has('returnJson')) {
  8209.                     return new JsonResponse(array(
  8210.                         'success' => false,
  8211.                         'documentHash' => 0,
  8212.                         'documentId' => 0,
  8213.                     ));
  8214.                 } else
  8215.                     $this->addFlash(
  8216.                         'error',
  8217.                         'Sorry Could not insert Data.'
  8218.                     );
  8219.             } else {
  8220.                 $funcname 'AttendanceAmendment';
  8221.                 $doc_id $id;
  8222.                 DeleteDocument::$funcname($em$doc_id0);
  8223.                 $attendanceAmendment = new AttendanceAmendment();
  8224.                 $attendanceAmendment->setDocumentHash($dochash);
  8225.                 $attendanceAmendment->setAttendanceAmendmentDate(new \DateTime($request->request->get('docDate''')));
  8226.                 $attendanceAmendment->setStartDate(new \DateTime($request->request->get('startDate''')));
  8227.                 $attendanceAmendment->setEndDate(new \DateTime($request->request->get('endDate''')));
  8228.                 $attendanceAmendment->setTypeHash('ATAM');
  8229.                 $attendanceAmendment->setPrefixHash($request->request->get('prefix_hash'$request->request->get('employeeId'0)));
  8230.                 $attendanceAmendment->setAssocHash($request->request->get('assoc_hash'0));
  8231.                 $attendanceAmendment->setNumberHash($numberHash);
  8232.                 $attendanceAmendment->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  8233.                 $attendanceAmendment->setApproved(array_flip(GeneralConstant::$approvalStatus)['pending']);
  8234.                 $attendanceAmendment->setAutoCreated($request->request->get('fullApprove'0));
  8235.                 $attendanceAmendment->setEmployeeId($request->request->get('forcedEmployeeId'$request->request->get('employeeId'0)));
  8236. //                $attendanceAmendment->setAutocreated(0);
  8237.                 if ($request->request->has('dataArrayJson')) {
  8238.                     $attendanceAmendment->setData($request->request->get('dataArrayJson''[]'));
  8239.                 } else {
  8240.                     $arr = [
  8241.                     ];
  8242.                     //dump($arr);
  8243.                     foreach ($request->request->get('date', []) as $key => $val) {
  8244.                         if ($request->request->get('isChanged')[$key] == 1) {
  8245.                             $dt = array(
  8246.                                 'enabled' => 1,
  8247.                                 'attId' => $request->request->get('attId')[$key],
  8248.                                 'note' => $request->request->get('note')[$key],
  8249.                                 'startTimeTs' => $request->request->get('startTimeTs')[$key],
  8250.                                 'endTimeTs' => $request->request->get('endTimeTs')[$key],
  8251.                                 'totalWorkHour' => $request->request->get('totalWorkHour')[$key],
  8252.                                 'entryDataIn' => json_decode($request->request->get('entryDataIn')[$key], true),
  8253.                                 'entryDataOut' => json_decode($request->request->get('entryDataOut')[$key], true),
  8254.                             );
  8255.                             $arr[$val] = $dt;
  8256.                         }
  8257.                     }
  8258.                     $attendanceAmendment->setData(json_encode($arr));
  8259.                 }
  8260.                 $em->persist($attendanceAmendment);
  8261.                 $em->flush();
  8262.                 $ID $attendanceAmendment->getAttendanceAmendmentId();
  8263.                 //now add Approval info
  8264.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8265.                 $approveRole 1;  //created
  8266.                 $options = array(
  8267.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8268.                     'notification_server' => $this->container->getParameter('notification_server'),
  8269.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8270.                     'url' => $this->generateUrl(
  8271.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']]
  8272.                         ['entity_view_route_path_name']
  8273.                     )
  8274.                 );
  8275.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  8276.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8277.                     $ID,
  8278.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  8279.                 );
  8280.                 if ($request->request->get('fullApprove'0) == 1) {
  8281.                     DeleteDocument::AttendanceAmendment($em$ID);
  8282.                 } else {
  8283.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'], $ID,
  8284.                         $loginId,
  8285.                         $approveRole,
  8286.                         $request->request->get('approvalHash'));
  8287.                     $url $this->generateUrl(
  8288.                         'view_attendance_amendment'
  8289.                     );
  8290.                     if ($request->request->has('returnJson')) {
  8291.                         return new JsonResponse(array(
  8292.                             'success' => true,
  8293.                             'documentHash' => $dochash,
  8294.                             'documentId' => $ID,
  8295.                             'viewUrl' => $url "/" $ID,
  8296.                         ));
  8297.                     } else {
  8298.                         $this->addFlash(
  8299.                             'success',
  8300.                             'Attendance Amendment Note Added.'
  8301.                         );
  8302.                         return $this->redirect($url "/" $ID);
  8303.                     }
  8304.                 }
  8305.             }
  8306.         }
  8307.         if ($id == 0) {
  8308.         } else {
  8309.             $extDoc $em->getRepository('ApplicationBundle\\Entity\\AttendanceAmendment')->findOneBy(
  8310.                 array(
  8311.                     'salesOrderId' => $id///material
  8312.                 )
  8313.             );
  8314.             //now if its not editable, redirect to view
  8315.             if ($extDoc) {
  8316.                 if ($extDoc->getEditFlag() != 1) {
  8317.                     $url $this->generateUrl(
  8318.                         'view_attendance_amendment'
  8319.                     );
  8320.                     return $this->redirect($url "/" $id);
  8321.                 } else {
  8322.                     $extDocData $extDoc;
  8323.                 }
  8324.             } else {
  8325.             }
  8326.         }
  8327.         $startDate $request->query->get('start_date''');
  8328.         $endDate $request->query->get('end_date''');
  8329.         $employeeId $request->query->get('employee_id'0);
  8330.         $existingData = [];
  8331.         $startDateTs 0;
  8332.         $endDateTs 0;
  8333.         $returnData = array(
  8334.             'page_title' => 'Attendance Amendment',
  8335.             'existingData' => $existingData,
  8336.             'startDateTs' => $startDateTs,
  8337.             'extDocData' => $extDocData,
  8338.             'endDateTs' => $endDateTs,
  8339.         );
  8340.         if ($request->query->has('returnJson')) {
  8341.             if ($startDate != '' && $endDate != '' && $employeeId != 0) {
  8342.                 $startDateDt = new \DateTime($startDate);
  8343.                 $endDateDt = new \DateTime($endDate);
  8344.                 $startDateTs $startDateDt->format('U');
  8345.                 $endDateTs $endDateDt->format('U');
  8346.                 $attendanceQuery $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance')
  8347.                     ->createQueryBuilder('p')
  8348.                     ->where("p.employeeId = " $employeeId)
  8349. //                ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
  8350.                     ->andWhere("p.date <= :last")
  8351.                     ->andWhere("p.date >= :start")
  8352.                     ->setParameter('start'$startDateDt)
  8353.                     ->setParameter('last'$endDateDt);
  8354.                 $attendanceResults $attendanceQuery->getQuery()->getResult();
  8355.                 foreach ($attendanceResults as $att) {
  8356.                     $entryDateTime null;
  8357.                     $outDateTime null;
  8358.                     if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getEntry()->format('H:i:00 +0000'));
  8359.                     if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getLastOut()->format('H:i:00 +0000'));
  8360.                     $attData = array(
  8361.                         'id' => $att->getId(),
  8362.                         'date_str' => $att->getDate()->format('Y-m-d'),
  8363.                         'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
  8364.                         'in_time_full' => $entryDateTime $entryDateTime->format(DATE_RFC2822) : '',
  8365.                         'date_ts' => $att->getDate()->format('U'),
  8366.                         'in_time' => $entryDateTime $entryDateTime->format('H:i:s') : '',
  8367.                         'in_time_ts' => $entryDateTime $entryDateTime->format('U') : 0,
  8368.                         'last_out_time' => $outDateTime $outDateTime->format('H:i:s') : '',
  8369.                         'last_out_time_ts' => $outDateTime $outDateTime->format('U') : '',
  8370.                     );
  8371.                     $locations = [];
  8372.                     $locList = [];
  8373.                     $logHere $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')->findOneBy(array(
  8374.                         'attendance_id' => $att->getId(),
  8375.                     ));
  8376.                     if ($logHere)
  8377.                         $locList json_decode($logHere->getPositionArray(), true);
  8378.                     if ($locList == null)
  8379.                         $locList = [];
  8380.                     $entry_data json_decode($att->getData(), true);
  8381.                     if ($entry_data == null$entry_data = [];
  8382.                     $lastLat 0;
  8383.                     $lastLng 0;
  8384.                     foreach ($locList as $lg) {
  8385.                         $dist 0;
  8386.                         if (isset($lg['lat'])) {
  8387.                             if ($lastLat == 0) {
  8388.                                 $lastLat $lg['lat'];
  8389.                                 $lastLng $lg['lng'];
  8390.                             }
  8391.                             $theta $lastLng $lg['lng'];
  8392.                             $dist sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
  8393.                             $dist acos($dist);
  8394.                             $dist rad2deg($dist);
  8395.                             $miles $dist 60 1.1515;
  8396.                             $dist $miles 1609.344;
  8397.                             if (abs($dist) > 1000) {
  8398.                                 $locations[] = array(
  8399.                                     'ts' => $lg['ts'],
  8400.                                     'lat' => $lg['lat'],
  8401.                                     'lng' => $lg['lng'],
  8402.                                 );
  8403.                                 $lastLat $lg['lat'];
  8404.                                 $lastLng $lg['lng'];
  8405.                             }
  8406.                         }
  8407.                     }
  8408.                     $attData['locations'] = $locations;
  8409.                     $attData['entryData'] = $entry_data;
  8410.                     $existingData[$att->getDate()->format('U')] = $attData;
  8411.                 }
  8412.             }
  8413.             $returnData = array(
  8414.                 'page_title' => 'Attendance Amendment',
  8415.                 'existingData' => $existingData,
  8416.                 'startDateTs' => $startDateTs,
  8417.                 'extDocData' => $extDocData,
  8418.                 'endDateTs' => $endDateTs,
  8419.             );
  8420.             return new JsonResponse($returnData);
  8421.         } else
  8422.             return $this->render('@Application/pages/human_resource/attendance/create_attendance_amendment.html.twig'$returnData);
  8423.     }
  8424.     public function AttendanceAmendmentListAction(Request $request)
  8425.     {
  8426.         $data = [];
  8427.         return $this->render('@Application/pages/human_resource/list/attendance_amendment_list.html.twig',
  8428.             array(
  8429.                 'page_title' => 'Attendance Amendment List',
  8430.                 'data' => $data
  8431.             )
  8432.         );
  8433.     }
  8434.     public function ViewAttendanceAmendmentAction(Request $request$id)
  8435.     {
  8436.         $em $this->getDoctrine()->getManager();
  8437.         $dt HumanResource::GetAttendanceAmendmentDetails($em$id);
  8438.         return $this->render('@Application/pages/human_resource/views/view_attendance_amendment.html.twig',
  8439.             array(
  8440.                 'page_title' => 'Attendance Amendment',
  8441.                 'data' => $dt,
  8442.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8443.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8444.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8445.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8446.                     $id,
  8447.                     $dt['created_by'],
  8448.                     $dt['edited_by'])
  8449.             )
  8450.         );
  8451.     }
  8452.     public function PrintAttendanceAmendmentAction(Request $request$id)
  8453.     {
  8454.         $em $this->getDoctrine()->getManager();
  8455.         $dt HumanResource::GetAttendanceAmendmentDetails($em$id);
  8456.         $company_data Company::getCompanyData($em1);
  8457.         $document_mark = array(
  8458.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  8459.             'copy' => ''
  8460.         );
  8461.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  8462.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  8463.                 array(
  8464.                     //full array here
  8465.                     'pdf' => true,
  8466.                     'page_title' => 'Stock Received Note',
  8467.                     'export' => 'pdf,print',
  8468.                     'data' => $dt,
  8469.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8470.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8471.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8472.                         array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8473.                         $id,
  8474.                         $dt['created_by'],
  8475.                         $dt['edited_by']),
  8476.                     'document_mark_image' => $document_mark['original'],
  8477.                     'company_name' => $company_data->getName(),
  8478.                     'company_data' => $company_data,
  8479.                     'company_address' => $company_data->getAddress(),
  8480.                     'company_image' => $company_data->getImage(),
  8481.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  8482.                     'red' => 0
  8483.                 )
  8484.             );
  8485.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  8486. //                'orientation' => 'landscape',
  8487. //                'enable-javascript' => true,
  8488. //                'javascript-delay' => 1000,0
  8489.                 'no-stop-slow-scripts' => false,
  8490.                 'no-background' => false,
  8491.                 'lowquality' => false,
  8492.                 'encoding' => 'utf-8',
  8493. //            'images' => true,
  8494. //            'cookie' => array(),
  8495.                 'dpi' => 300,
  8496.                 'image-dpi' => 300,
  8497. //                'enable-external-links' => true,
  8498. //                'enable-internal-links' => true
  8499.             ));
  8500.             return new Response(
  8501.                 $pdf_response,
  8502.                 200,
  8503.                 array(
  8504.                     'Content-Type' => 'application/pdf',
  8505.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  8506.                 )
  8507.             );
  8508.         }
  8509.         return $this->render('@Application/pages/human_resource/views/view_attendance_amendment.html.twig',
  8510.             array(
  8511.                 'page_title' => 'Attendance Amendment',
  8512.                 'data' => $dt,
  8513.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8514.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8515.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8516.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8517.                     $id,
  8518.                     $dt['created_by'],
  8519.                     $dt['edited_by'])
  8520.             )
  8521.         );
  8522.     }
  8523.     public function createRoomAction(Request $request)
  8524.     {
  8525.         $em $this->getDoctrine()->getManager();
  8526.         $companyId $this->getLoggedUserCompanyId($request);
  8527.         if ($request->isMethod('POST')) {
  8528.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8529.             $room = new Room;
  8530.             $room->setRoomNo($request->request->get('RoomNo'));
  8531.             //$room->setRoomName($request->request->get('RoomName'));
  8532.             $room->setBuilding($request->request->get('buildingName'));
  8533.             $room->setFloor($request->request->get('floor'));
  8534.             $room->setCapacity($request->request->get('capacity'));
  8535.             $room->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  8536.             $em->persist($room);
  8537.             $em->flush();
  8538.         }
  8539.         return $this->render('@Application/pages/human_resource/input_forms/create_room.html.twig', array(
  8540.             'page_title' => 'Add Room',
  8541.         ));
  8542.     }
  8543.     public function ExpenseTypeAction()
  8544.     {
  8545.         $expenseType HumanResourceConstant::$employeeExpenseAllowanceTypes;
  8546.         $expenseTypeArray = [];
  8547.         foreach ($expenseType as $k => $dt) {
  8548.             $dt['id'] = $k;
  8549.             $newSegs = [];
  8550.             foreach ($dt['segregations'] as $l => $s) {
  8551.                 $newOptions = [];
  8552.                 foreach ($s['options'] as $l2 => $s2) {
  8553.                     $s3 = array(
  8554.                         'value' => $l2,
  8555.                         'text' => $s2,
  8556.                     );
  8557.                     $newOptions[] = $s3;
  8558.                 }
  8559.                 $s['options'] = $newOptions;
  8560.                 if (is_string($s['defaultVal'])) $s['defaultVal'] = [$s['defaultVal']];
  8561.                 $newSegs[] = $s;
  8562.             }
  8563.             $dt['segregations'] = $newSegs;
  8564.             $expenseTypeArray[] = $dt;
  8565.         }
  8566.         return new JsonResponse(
  8567.             array(
  8568.                 'success' => true,
  8569.                 'expenseType' => $expenseType,
  8570.                 'expenseTypeArray' => $expenseTypeArray,
  8571.             )
  8572.         );
  8573.     }
  8574.     public function DemoDataTableAction()
  8575.     {
  8576.         return $this->render('@Application/pages/human_resource/list/demo_data_table.html.twig', array(
  8577.             'page_title' => 'Add Room',
  8578.         ));
  8579.     }
  8580.     public function workEnrtyAction(Request $request)
  8581.     {
  8582. //        $em = $this->getDoctrine()->getManager();
  8583. //        $companyId = $this->getLoggedUserCompanyId($request);
  8584. //        if ($request->isMethod('POST')) {
  8585. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8586. //            $labour = new Labour();
  8587. //            $labour->setLabourName($request->request->get('labourName'));
  8588. //            $labour->setNidNumber($request->request->get('nidNumber'));
  8589. //            $em->persist($labour);
  8590. //            $em->flush();
  8591. //            $this->addFlash(
  8592. //                'success',
  8593. //                'Labour Added'
  8594. //            );
  8595. //        }
  8596.         return $this->render('@Application/pages/human_resource/input_forms/work_entry.html.twig', array(
  8597.             'page_title' => 'Work Entry',
  8598.         ));
  8599.     }
  8600.     public function ViewContractLetterAction(Request $request$id)
  8601.     {
  8602.         $em $this->getDoctrine()->getManager();
  8603.         $employeeDetail $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->find($id);
  8604. //        $employeeData = [];
  8605. //        foreach ($employeeDetails as $employeeDetail) {
  8606. //            $data = array(
  8607. //                'firstName' => $employeeDetail->getNid(),
  8608. //
  8609. //
  8610. //
  8611. //            );
  8612. //
  8613. //
  8614. //            $employeeData[] = $data;
  8615. //        }
  8616.         return $this->render('@Application/pages/human_resource/views/viewContractLetter.html.twig', array(
  8617.             'page_title' => 'Contract Letter',
  8618.             'employeeDetail' => $employeeDetail
  8619.         ));
  8620.     }
  8621.     public function getAttendanceReportForEmployeeAction(Request $request)
  8622.     {
  8623.         $em $this->getDoctrine()->getManager();
  8624.         $session $request->getSession();
  8625.         $fromDateRow = (new \DateTime($request->get('start_date''')));
  8626. //        $fromDate = $fromDateRow->format("M d, Y");
  8627.         $toDateRow = (new \DateTime($request->get('end_date'$fromDateRow) . ' 23:59:59'));
  8628. //        $toDate = $toDateRow->format("M d, Y");
  8629. //        $startDate = "2025-02-13";
  8630. //        $endDate = "2025-02-16";
  8631.         $userId $session->get(UserConstants::USER_ID);
  8632.         $attendanceDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance')->createQueryBuilder('A')
  8633. //            ->select('A.createdAt','A.data')
  8634.             ->where('A.sysId = :userId')
  8635.             ->andWhere('A.createdAt >=  :startDate')
  8636.             ->andWhere('A.createdAt <=  :endDate')
  8637.             ->setParameter('userId'$userId)
  8638.             ->setParameter('startDate'$fromDateRow)
  8639.             ->setParameter('endDate'$toDateRow)
  8640.             ->getQuery()
  8641.             ->getResult();
  8642.         $attendance = [];
  8643.         $dt = [];
  8644.         foreach ($attendanceDetails as $data) {
  8645.             $in_out_data json_decode($data->getData(), true);
  8646.             $new_in_data = [];
  8647.             $elapsed_data = [];
  8648.             $new_out_data = [];
  8649.             if ($in_out_data == null$in_out_data = [];
  8650.             if (isset($in_out_data['in'])) {
  8651.                 foreach ($in_out_data['in'] as $ind => $g) {
  8652.                     if (!isset($elapsed_data[$ind])) {
  8653.                         $elapsed_data[$ind] = 0;
  8654.                     }
  8655.                     $the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g ' +0000');
  8656.                     $new_in_data[] = $the_time->format('U');
  8657.                 }
  8658.             }
  8659.             if (isset($in_out_data['out'])) {
  8660.                 foreach ($in_out_data['out'] as $ind => $g) {
  8661.                     if (!isset($elapsed_data[$ind])) {
  8662.                         $elapsed_data[$ind] = 0;
  8663.                     }
  8664.                     $the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g ' +0000');
  8665.                     $new_out_data[] = $the_time->format('U');
  8666.                     if (isset($new_in_data[$ind])) {
  8667.                         $elapsed_data[$ind] = $new_out_data[$ind] - $new_in_data[$ind];
  8668.                     }
  8669.                 }
  8670.             }
  8671.             $list = array(
  8672.                 'date' => $data->getDate()->format('F d Y'),
  8673.                 'attendanceData' => [
  8674.                     'in' => $new_in_data,
  8675.                     'out' => $new_out_data,
  8676.                     'elapsedSec' => $elapsed_data,
  8677.                 ]
  8678.             );
  8679.             $dt[] = $list;
  8680.         }
  8681.         $count count($attendance);
  8682. //        for ($i=0;$i < $count; $i++){
  8683. //            $dt[] = $attendance[$i]['date'];
  8684. //            $dt[] = ($attendance[$i]['attendanceData']);
  8685. //        }
  8686. ////        $decodeData = json_decode($dt, true);
  8687. //
  8688. //        $work_hours = [];
  8689. //
  8690. //        foreach ($dt as $index => $entry) {
  8691. //            $in_times = $entry['in'];
  8692. //            $out_times = $entry['out'];
  8693. //
  8694. //
  8695. //            $count = min(count($in_times), count($out_times));
  8696. //
  8697. //            for ($i = 0; $i < $count; $i++) {
  8698. //                $time_in = new DateTime($in_times[$i]);
  8699. //                $time_out = new DateTime($out_times[$i]);
  8700. //
  8701. //
  8702. //                $interval = $time_in->diff($time_out);
  8703. //                $total_hours = $interval->format('%h');
  8704. //                $total_minutes = $interval->format('%i');
  8705. //
  8706. //
  8707. //                $work_hours[] = [
  8708. ////                    "set" => $index + 1,
  8709. //                    "in" => $in_times[$i],
  8710. //                    "out" => $out_times[$i],
  8711. //                    "worked" => "$total_hours hours, $total_minutes minutes"
  8712. //                ];
  8713. //            }
  8714. //        }
  8715. //
  8716. ////        foreach ($work_hours as $work) {
  8717. ////           return new  JsonResponse(
  8718. ////               array(
  8719. ////                   'in'=>$work['in'],
  8720. ////                   'out' => $work['out'],
  8721. ////                   'hour' => $work['worked']
  8722. ////               )
  8723. ////           ) ;
  8724. //////            echo "Set {$work['set']} - IN: {$work['in']} - OUT: {$work['out']} => Worked: {$work['worked']}\n";
  8725. ////        }
  8726.         return new JsonResponse($dt);
  8727.     }
  8728.     public function getTotalWorkHourAction(Request $request)
  8729.     {
  8730.         $em $this->getDoctrine()->getManager();
  8731.         $currentDate = new \DateTime(date('y-m-d'));
  8732.         $session $request->getSession();
  8733.         $token $session->get(UserConstants::USER_TOKEN);
  8734.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8735.         $planningItemId $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID);
  8736.         $attendanceData $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance');
  8737.         $currentStatus HumanResource::getCurrentStatusFromDb($attendanceData$employeeId$currentDate);
  8738.         $providedToken $request->headers->get('auth-token');
  8739.         if (empty($providedToken) || $providedToken !== $token) {
  8740.             return new JsonResponse([
  8741.                 'status' => 'error',
  8742.                 'message' => 'Token not match or missing',
  8743.             ], 401);
  8744.         }
  8745.         $planningItemDetails $em->getRepository(PlanningItem::class)->createQueryBuilder('p')
  8746.             ->select('p.itemAlias')
  8747.             ->where('p.id = :planningItemId')
  8748.             ->setParameter('planningItemId'$planningItemId)
  8749.             ->getQuery()
  8750.             ->getResult();
  8751.         // Check if "data" key exists and contains "in" times
  8752.         if (empty($currentStatus["data"]["in"])) {
  8753.             return new JsonResponse([
  8754. //                'message' => 'No attendance data available',
  8755.                 'currentStatus' => $currentStatus,
  8756.                 'totalWorkingTime' => '00:00:00'
  8757.             ]);
  8758.         }
  8759.         $totalSeconds 0;
  8760.         for ($i 0$i count($currentStatus["data"]["in"]); $i++) {
  8761.             $inTime $currentStatus["data"]["in"][$i];
  8762.             // Check if "out" time exists for this "in" time
  8763.             if (!isset($currentStatus["data"]["out"][$i])) {
  8764.                 continue; // Skip this entry if there is no out time
  8765.             }
  8766.             $outTime $currentStatus["data"]["out"][$i];
  8767.             // Calculate the difference
  8768.             $totalSeconds += ($outTime $inTime);
  8769.         }
  8770.         // If no valid time pairs were found, return 00:00:00
  8771. //        if ($totalSeconds == 0) {
  8772. //            return new JsonResponse([
  8773. //                'message' => 'No complete in-out records found',
  8774. //                'totalWorkingTime' => '00:00:00'
  8775. //            ]);
  8776. //        }
  8777.         // Convert total seconds to hours, minutes, and seconds
  8778.         $hours floor($totalSeconds 3600);
  8779.         $minutes floor(($totalSeconds 3600) / 60);
  8780.         $seconds $totalSeconds 60;
  8781.         $totalWorkingTime sprintf("%02d:%02d:%02d"$hours$minutes$seconds);
  8782.         return new JsonResponse([
  8783.             'taskName' => isset($planningItemDetails[0]) ? $planningItemDetails[0]['itemAlias'] : '',
  8784.             'currentStatus' => $currentStatus,
  8785.             'totalWorkingTime' => $totalWorkingTime,
  8786.         ]);
  8787.     }
  8788. //    public function getEmployeeDataAction(Request $request)
  8789. //    {
  8790. //        $em = $this->getDoctrine()->getManager();
  8791. //        $session = $request->getSession();
  8792. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8793. //
  8794. //
  8795. //        $employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->createQueryBuilder('E')
  8796. //            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin','E.image', 'P.positionName')
  8797. //            ->addSelect('A.current_balance')
  8798. //            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  8799. //            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  8800. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  8801. //            ->where('E.id = :employeeId')
  8802. //            ->setParameter('employeeId', $employeeId)
  8803. //            ->getQuery()
  8804. //            ->getResult();
  8805. //
  8806. //        return new JsonResponse($employeeDetails[0]);
  8807. //    }
  8808. //    public function getEmployeeDataAction(Request $request)
  8809. //    {
  8810. //        $em = $this->getDoctrine()->getManager();
  8811. //        $session = $request->getSession();
  8812. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8813. //        $image = $session->get(UserConstants::USER_IMAGE);
  8814. //        $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8815. //
  8816. //        $employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->createQueryBuilder('E')
  8817. //            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
  8818. //            ->addSelect('A.current_balance')
  8819. //            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  8820. //            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  8821. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  8822. //            ->where('E.id = :employeeId')
  8823. //            ->setParameter('employeeId', $employeeId)
  8824. //            ->getQuery()
  8825. //            ->getResult();
  8826. //
  8827. //        // If image is null or empty, assign empty string
  8828. //        if (empty($employeeDetails['image'])) {
  8829. //            $employeeDetails['image'] =  $image;
  8830. //        }
  8831. //
  8832. //        return new JsonResponse($employeeDetails);
  8833. //    }
  8834.     public function getEmployeeDataAction(Request $request)
  8835.     {
  8836.         $em $this->getDoctrine()->getManager();
  8837.         $session $request->getSession();
  8838.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8839.         $image $session->get(UserConstants::USER_IMAGE);
  8840.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8841.         $userImage $session->get(UserConstants::USER_IMAGE);
  8842.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->createQueryBuilder('E')
  8843.             ->select('E.firstname''E.lastname''E.nid''E.tin''E.image''P.positionName')
  8844.             ->addSelect('A.current_balance')
  8845.             ->leftJoin('ApplicationBundle:SysDepartmentPosition''P''WITH''E.desg = P.positionId')
  8846.             ->leftJoin('ApplicationBundle:Employee''EMP''WITH''EMP.employeeId = E.id')
  8847.             ->leftJoin('ApplicationBundle:AccAccountsHead''A''WITH''EMP.accountsHeadId = A.accountsHeadId')
  8848.             ->where('E.id = :employeeId')
  8849.             ->setParameter('employeeId'$employeeId)
  8850.             ->getQuery()
  8851.             ->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); // Only one employee expected
  8852.         if (!$employeeDetails) {
  8853.             return new JsonResponse(['error' => 'Employee not found'], 404);
  8854.         }
  8855.         // If image is missing, fallback to session image
  8856.         if (empty($employeeDetails['image'])) {
  8857.             $employeeDetails['image'] = $image;
  8858.         }
  8859.         // If image is still available, prefix it with absolute URL
  8860.         if (!empty($employeeDetails['image'])) {
  8861.             $employeeDetails['image_url'] = $absoluteUrl '' $userImage;
  8862.         } else {
  8863.             $employeeDetails['image_url'] = ''// no image
  8864.         }
  8865.         return new JsonResponse($employeeDetails);
  8866.     }
  8867.     public function updateEmployeeDataForAppAction(Request $request)
  8868.     {
  8869.         $em $this->getDoctrine()->getManager();
  8870.         $session $request->getSession();
  8871.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8872.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->find($employeeId);
  8873.         if ($request->isMethod('POST')) {
  8874.             $firstname $request->request->get('firstname');
  8875.             $lastname $request->request->get('lastname');
  8876.             $nid $request->request->get('nid');
  8877.             $tin $request->request->get('tin');
  8878.             if ($firstname !== null) {
  8879.                 $employeeDetails->setFirstName($firstname);
  8880.             }
  8881.             if ($lastname !== null) {
  8882.                 $employeeDetails->setLastName($lastname);
  8883.             }
  8884.             if ($nid !== null) {
  8885.                 $employeeDetails->setNid($nid);
  8886.             }
  8887.             if ($tin !== null) {
  8888.                 $employeeDetails->setTin($tin);
  8889.             }
  8890.             $em->flush();
  8891.             return new JsonResponse(['success' => true]);
  8892.         }
  8893.         return new JsonResponse(['success' => false'message' => 'Invalid request method']);
  8894.     }
  8895. //    public function updateEmployeeDataForAppAction(Request $request){
  8896. //        $em = $this->getDoctrine()->getManager();
  8897. //        $session = $request->getSession();
  8898. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8899. //        $employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->find($employeeId);
  8900. //
  8901. //        if ($request->isMethod('POST')) {
  8902. //            $employeeDetails->setFirstName(($request->request->get('firstname',$employeeDetails->getFirstName())));
  8903. //            $employeeDetails->setLastName($request->request->get('lastname',$employeeDetails->getLastName()));
  8904. //            $employeeDetails->setNid($request->request->get('nid'),$employeeDetails->getNid());
  8905. //            $employeeDetails->setTin($request->request->get('tin'),$employeeDetails->getTin());
  8906. //
  8907. //            $em->flush(); //
  8908. //
  8909. //            return new JsonResponse(['success' => true]);
  8910. //        }
  8911. //
  8912. //
  8913. //    }
  8914.     public function leaveApplicationListForAppAction(Request $request)
  8915.     {
  8916.         $em $this->getDoctrine()->getManager();
  8917.         $session $request->getSession();
  8918.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8919.         $leaveType HumanResourceConstant::$LeaveType;
  8920.         $approvalStatus GeneralConstant::$approvalAction;
  8921.         $leaveCategory HumanResourceConstant::$leavCategory;
  8922.         // Get page and limit from request (default: page=1, limit=10)
  8923.         $page max((int)$request->query->get('page'1), 1);
  8924.         $limit max((int)$request->query->get('limit'10), 1);
  8925.         $offset = ($page 1) * $limit;
  8926.         // Get total count
  8927.         $total $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  8928.             ->createQueryBuilder('L')
  8929.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8930.             ->where('L.employeeId = :employeeId')
  8931.             ->setParameter('employeeId'$employeeId)
  8932.             ->getQuery()
  8933.             ->getSingleScalarResult();
  8934.         // Get paginated results
  8935.         $leaveRecords $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  8936.             ->createQueryBuilder('L')
  8937.             ->select(
  8938.                 'L.documentHash',
  8939.                 'L.employeeLeaveApplicationId',
  8940.                 'L.leaveStartDate',
  8941.                 'L.leaveEndDate',
  8942.                 'L.leaveTypeId',
  8943.                 'L.leaveCategory',
  8944.                 'L.approved',
  8945.                 'L.createdAt',
  8946.                 'L.alternateDate',
  8947.                 'L.leaveComment',
  8948.                 'L.createdAt',
  8949.                 'L.approved_by'
  8950.             )
  8951.             ->where('L.employeeId = :employeeId')
  8952.             ->setParameter('employeeId'$employeeId)
  8953.             ->setFirstResult($offset)
  8954.             ->setMaxResults($limit)
  8955.             ->orderBy('L.employeeLeaveApplicationId''DESC')   //
  8956.             ->getQuery()
  8957.             ->getResult();
  8958.         // Count total approved (approved = 1)
  8959.         $totalApproved $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  8960.             ->createQueryBuilder('L')
  8961.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8962.             ->where('L.employeeId = :employeeId')
  8963.             ->andWhere('L.approved = 1')
  8964.             ->setParameter('employeeId'$employeeId)
  8965.             ->getQuery()
  8966.             ->getSingleScalarResult();
  8967. // Count total pending (approved = 3)
  8968.         $totalPending $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  8969.             ->createQueryBuilder('L')
  8970.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8971.             ->where('L.employeeId = :employeeId')
  8972.             ->andWhere('L.approved = 3')
  8973.             ->setParameter('employeeId'$employeeId)
  8974.             ->getQuery()
  8975.             ->getSingleScalarResult();
  8976. // Count total cancelled (approved = 0)
  8977.         $totalCancelled $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  8978.             ->createQueryBuilder('L')
  8979.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8980.             ->where('L.employeeId = :employeeId')
  8981.             ->andWhere('L.approved = 0')
  8982.             ->setParameter('employeeId'$employeeId)
  8983.             ->getQuery()
  8984.             ->getSingleScalarResult();
  8985.         // Format the results
  8986.         $formattedData = [];
  8987.         foreach ($leaveRecords as $leave) {
  8988.             $formattedData[] = [
  8989.                 'documentHash' => $leave['documentHash'],
  8990.                 'employeeLeaveApplicationId' => $leave['employeeLeaveApplicationId'],
  8991.                 'leaveStartDate' => $leave['leaveStartDate'] ? $leave['leaveStartDate']->getTimestamp() : 0,
  8992.                 'leaveEndDate' => $leave['leaveEndDate'] ? $leave['leaveEndDate']->getTimestamp() : 0,
  8993.                 'leaveType' => $leaveType[$leave['leaveTypeId']] ?? 'Unknown',
  8994.                 'leaveCategory' => $leaveCategory[$leave['leaveCategory']] ?? 'Unknown',
  8995.                 'approved' => $approvalStatus[$leave['approved']] ?? 'Unknown',
  8996.                 'createdAt' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
  8997.                 'alternateDate' => $leave['alternateDate'] ? $leave['alternateDate']->getTimestamp() : 0,
  8998.                 'note' => $leave['leaveComment'] ? $leave['leaveComment'] : '',
  8999.                 'appliedOn' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
  9000.                 'approvedBy' => $leave['approved_by'] ? $leave['approved_by'] : 'automatically approved',
  9001.             ];
  9002.         }
  9003.         $employee $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  9004.             ->find($employeeId);
  9005.         $totalLeaveBalance 0;
  9006.         for ($i 1$i <= 10$i++) {
  9007.             $getter "getLeave{$i}Tkn";
  9008.             $totalLeaveBalance += $employee->$getter();
  9009.         }
  9010.         // Final response with pagination meta
  9011.         return new JsonResponse([
  9012.             'success' => true,
  9013.             'message' => 'Leave application list fetched successfully',
  9014.             'totalLeaveBalance' => (int)($totalLeaveBalance ?? 0),
  9015.             'totalApproved' => (int)($totalApproved ?? 0),
  9016.             'totalPending' => (int)($totalPending ?? 0),
  9017.             'totalCancelled' => (int)($totalCancelled ?? 0),
  9018.             'data' => $formattedData,
  9019.             'CurrentPage' => $page,
  9020.             'limit' => $limit,
  9021.             'total' => $total,
  9022.         ]);
  9023.     }
  9024.     public function PublicProfilePageAction(Request $request)
  9025.     {
  9026.         return new JsonResponse(['success' => true]);
  9027.     }
  9028.     public function leaveSettingsAction(Request $request)
  9029.     {
  9030.         $em $this->getDoctrine()->getManager();
  9031.         if ($request->isMethod('POST')) {
  9032.             $ids $request->request->get('id', []);
  9033.             $leaveTitles $request->request->get('leaveTitle', []);
  9034.             $carryForwardTypes $request->request->get('carryForwardType', []);
  9035.             $carryForwardQtys $request->request->get('number', []);
  9036.             $totalLeaves $request->request->get('totalLeave', []);
  9037.             $resetFreqTypes $request->request->get('resetFrequencyType', []);
  9038.             $resetFreqQtys $request->request->get('resetFrequencyQty', []);
  9039.             $additionConditions $request->request->get('additionCondition', []);
  9040.             $additionDurations $request->request->get('additionConditionDuration', []);
  9041.             for ($i 0$i count($leaveTitles); $i++) {
  9042.                 if (
  9043.                     isset(
  9044.                         $carryForwardTypes[$i],
  9045.                         $carryForwardQtys[$i],
  9046.                         $totalLeaves[$i],
  9047.                         $resetFreqTypes[$i],
  9048.                         $resetFreqQtys[$i],
  9049.                         $additionConditions[$i],
  9050.                         $additionDurations[$i]
  9051.                     )
  9052.                 ) {
  9053.                     $id $ids[$i] ?? null;
  9054.                     $leaveSetting null;
  9055.                     if ($id) {
  9056.                         $leaveSetting $em->getRepository('ApplicationBundle\\Entity\\LeaveSettings')->find($id);
  9057.                     }
  9058.                     if (!$leaveSetting) {
  9059.                         $leaveSetting = new LeaveSettings();
  9060.                     }
  9061.                     $leaveSetting->setId($id);
  9062.                     $leaveSetting->setLeaveTitle($leaveTitles[$i]);
  9063.                     $leaveSetting->setCarryForwardType((int)$carryForwardTypes[$i]);
  9064.                     $leaveSetting->setCarryForwardQty((int)$carryForwardQtys[$i]);
  9065.                     $leaveSetting->setTotalLeave((int)$totalLeaves[$i]);
  9066.                     $leaveSetting->setResetFrequencyType((int)$resetFreqTypes[$i]);
  9067.                     $leaveSetting->setResetFrequencyQty((int)$resetFreqQtys[$i]);
  9068.                     $leaveSetting->setAdditionCondition((int)$additionConditions[$i]);
  9069.                     $leaveSetting->setAdditionConditionDuration((int)$additionDurations[$i]);
  9070.                     $em->persist($leaveSetting);
  9071.                 }
  9072.             }
  9073.             $em->flush();
  9074.             $this->addFlash('success''Leave settings saved successfully!');
  9075.             return $this->redirectToRoute('leave_settings_list');
  9076.         }
  9077.         $defaultLeaveType HumanResourceConstant::$defaultLeaveType;
  9078.         $savedLeaveSettings $em->getRepository('ApplicationBundle\\Entity\\LeaveSettings')->findAll();
  9079.         $useDefaultLeave count($savedLeaveSettings) === 0;
  9080.         $leaveSettings array_map(function ($setting) {
  9081.             return [
  9082.                 'id' => $setting->getId(),
  9083.                 'leaveTitle' => $setting->getLeaveTitle(),
  9084.                 'carryForwardType' => $setting->getCarryForwardType(),
  9085.                 'carryForwardQty' => $setting->getCarryForwardQty(),
  9086.                 'totalLeave' => $setting->getTotalLeave(),
  9087.                 'resetFrequencyType' => $setting->getResetFrequencyType(),
  9088.                 'resetFrequencyQty' => $setting->getResetFrequencyQty(),
  9089.                 'additionCondition' => $setting->getAdditionCondition(),
  9090.                 'additionConditionDuration' => $setting->getAdditionConditionDuration(),
  9091.             ];
  9092.         }, $savedLeaveSettings);
  9093.         return $this->render('@Application/pages/human_resource/input_forms/leave_settings.html.twig', [
  9094.             'page_title' => 'Leave Settings',
  9095.             'defaultLeaveType' => $defaultLeaveType,
  9096.             'leaveSettings' => $leaveSettings,
  9097.             'useDefaultLeave' => $useDefaultLeave,
  9098.         ]);
  9099.     }
  9100.     /**
  9101.      * HRM Command Center â€” a cp-shell, SaaS-style dashboard: live workforce,
  9102.      * attendance, leave/resignation queue and payroll cost trend at a glance.
  9103.      * Every KPI query is wrapped fail-safe so the page can never 500 on a
  9104.      * tenant whose schema/data differs.
  9105.      */
  9106.     public function HrmCockpitAction(Request $request): Response
  9107.     {
  9108.         $em $this->getDoctrine()->getManager();
  9109.         $conn $em->getConnection();
  9110.         $one = function ($sql$p = []) use ($conn) { try { $v $conn->fetchOne($sql$p); return $v === false null $v; } catch (\Throwable $e) { return null; } };
  9111.         $all = function ($sql$p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql$p); } catch (\Throwable $e) { return []; } };
  9112.         $activeHead = (int) $one("SELECT COUNT(*) FROM employee_details WHERE emp_status = 1");
  9113.         $totalHead  = (int) $one("SELECT COUNT(*) FROM employee_details");
  9114.         $joiners30  = (int) $one("SELECT COUNT(*) FROM employee_details WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
  9115.         // Composition by employment type (active only)
  9116.         $typeLabels = [=> 'Full-time'=> 'Part-time'=> 'Intern'=> 'Temporary'=> 'Contractual'];
  9117.         $byType = [];
  9118.         foreach ($all("SELECT emp_type t, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY emp_type") as $r) {
  9119.             $byType[$typeLabels[(int) $r['t']] ?? ('Type ' . (int) $r['t'])] = (int) $r['c'];
  9120.         }
  9121.         // Composition by gender (sex stored as varchar â€” normalise common encodings)
  9122.         $male 0$female 0$otherSex 0;
  9123.         foreach ($all("SELECT sex, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY sex") as $r) {
  9124.             $s strtolower(trim((string) $r['sex'])); $c = (int) $r['c'];
  9125.             if (in_array($s, ['1''m''male'], true)) { $male += $c; }
  9126.             elseif (in_array($s, ['2''f''female'], true)) { $female += $c; }
  9127.             else { $otherSex += $c; }
  9128.         }
  9129.         // Attendance today
  9130.         $presentToday = (int) $one("SELECT COUNT(DISTINCT employee_id) FROM employee_attendance WHERE DATE(created_at) = CURDATE()");
  9131.         $attRate $activeHead ? (int) round($presentToday 100 $activeHead) : 0;
  9132.         // Queues (approval convention: 3 = pending)
  9133.         $pendingLeave  = (int) $one("SELECT COUNT(*) FROM employee_leave_application WHERE (delete_flag IS NULL OR delete_flag = 0) AND approved = 3");
  9134.         $pendingResign = (int) $one("SELECT COUNT(*) FROM resign_application WHERE approved = 3");
  9135.         // Payroll cost trend (last 6 periods)
  9136.         $periods $all(
  9137.             "SELECT DATE_FORMAT(start_date, '%Y-%m') ym,
  9138.                     COUNT(*) slips, SUM(approved = 1) appr,
  9139.                     ROUND(SUM(payable_salary), 2) payable,
  9140.                     ROUND(SUM(CAST(eart AS DECIMAL(18,2))), 2) gross,
  9141.                     ROUND(SUM(CAST(dedt AS DECIMAL(18,2))), 2) ded
  9142.                FROM payslip WHERE start_date IS NOT NULL
  9143.               GROUP BY ym ORDER BY ym DESC LIMIT 6");
  9144.         $latest $periods[0] ?? null;
  9145.         $trend array_reverse($periods); // chronological for the bar chart
  9146.         $maxPayable 0.0;
  9147.         foreach ($trend as $t) { $maxPayable max($maxPayable, (float) $t['payable']); }
  9148.         // Recent joiners
  9149.         $recentJoiners $all(
  9150.             "SELECT firstname, lastname, emp_code, image, emp_type, joining_date
  9151.                FROM employee_details WHERE joining_date IS NOT NULL
  9152.               ORDER BY joining_date DESC LIMIT 6");
  9153.         // Statutory gate + currency
  9154.         $statutoryOn = ((string) $one("SELECT data FROM acc_setting WHERE name = 'payroll_statutory_enabled' LIMIT 1")) === '1';
  9155.         $cc strtoupper((string) $one("SELECT co.code FROM company c LEFT JOIN countries co ON co.country_id = c.country_id ORDER BY c.id LIMIT 1"));
  9156.         $currency = ['BD' => 'à§³''SG' => 'S$''DE' => '€'][$cc] ?? '';
  9157.         // â”€â”€ Intelligent helper â€” surface the most useful next action â”€â”€
  9158.         $pendingHr $pendingLeave $pendingResign;
  9159.         if ($pendingHr 0) {
  9160.             $bits = [];
  9161.             if ($pendingLeave 0)  { $bits[] = $pendingLeave ' leave'; }
  9162.             if ($pendingResign 0) { $bits[] = $pendingResign ' resignation'; }
  9163.             $hrHelper = ['type' => 'warn''text' => implode(' and '$bits) . ' request' . ($pendingHr == '' 's') . ' pending your approval.'];
  9164.         } elseif ($activeHead 0) {
  9165.             $hrHelper = ['type' => 'ok''text' => 'Attendance ' $attRate '% today (' $presentToday ' of ' $activeHead ' present) â€” no pending leave or resignation approvals.'];
  9166.         } else {
  9167.             $hrHelper null;
  9168.         }
  9169.         return $this->render('@Application/pages/human_resource/cockpit/hrm_cockpit.html.twig', [
  9170.             'page_title'     => 'HR Command Center',
  9171.             'hrHelper'       => $hrHelper,
  9172.             'activeHead'     => $activeHead,
  9173.             'totalHead'      => $totalHead,
  9174.             'joiners30'      => $joiners30,
  9175.             'byType'         => $byType,
  9176.             'male'           => $male'female' => $female'otherSex' => $otherSex,
  9177.             'presentToday'   => $presentToday'attRate' => $attRate,
  9178.             'pendingLeave'   => $pendingLeave'pendingResign' => $pendingResign,
  9179.             'latest'         => $latest'trend' => $trend'maxPayable' => $maxPayable,
  9180.             'recentJoiners'  => $recentJoiners'typeLabels' => $typeLabels,
  9181.             'statutoryOn'    => $statutoryOn'currency' => $currency'country' => $cc,
  9182.         ]);
  9183.     }
  9184.     /** Field Force Map page â€” who/where/what (Nectar attendance + task clock-in). */
  9185.     public function HrmFieldForceMapAction(Request $request): Response
  9186.     {
  9187.         $hours = (int) $request->query->get('hours'24);
  9188.         $d $this->fieldForceData($this->getDoctrine()->getManager()->getConnection(), $hours);
  9189.         return $this->render('@Application/pages/human_resource/cockpit/hrm_field_force.html.twig'array_merge(['page_title' => 'Field Force Map'], $d));
  9190.     }
  9191.     /** Live JSON feed powering the field-force map auto-refresh poll. */
  9192.     public function HrmFieldForceDataAction(Request $request): Response
  9193.     {
  9194.         return new \Symfony\Component\HttpFoundation\JsonResponse(
  9195.             $this->fieldForceData($this->getDoctrine()->getManager()->getConnection(), (int) $request->query->get('hours'24))
  9196.         );
  9197.     }
  9198.     /**
  9199.      * Build field-force data: latest GPS per employee (employee_attendance_log) +
  9200.      * active task (Nectar task_log) + planned visits. Shared by the page render
  9201.      * and the auto-refresh JSON feed.
  9202.      */
  9203.     private function fieldForceData($conn$hours 24): array
  9204.     {
  9205.         $hours max(1min(720, (int) $hours)); // trail window: 1h .. 30d
  9206.         $all = function ($sql$p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql$p); } catch (\Throwable $e) { return []; } };
  9207.         // Latest GPS log per ACTIVE employee (status<>0). The latest log's GPS is
  9208.         // the employee's last clock-in position (if clocked in) or last clock-out
  9209.         // position (if clocked out) â€” i.e. their current/last-known position.
  9210.         $rows $all(
  9211.             "SELECT l.employee_id, e.name AS emp_name,
  9212.                     l.current_lat, l.current_lng, l.current_address, l.current_work_status,
  9213.                     l.clocked_in, l.is_present, l.is_late, l.is_from_assigned_area,
  9214.                     l.last_start_time, l.total_work_hour, l.attendance_source
  9215.              FROM employee_attendance_log l
  9216.              JOIN (SELECT employee_id, MAX(id) AS mid FROM employee_attendance_log
  9217.                    WHERE current_lat IS NOT NULL AND current_lat <> 0 AND current_lat <> ''
  9218.                    GROUP BY employee_id) m ON m.mid = l.id
  9219.              JOIN employee e ON e.employee_id = l.employee_id
  9220.              WHERE (e.status IS NULL OR e.status <> 0)
  9221.              ORDER BY l.last_start_time DESC"
  9222.         );
  9223.         // Current active task per employee (Nectar task clock-in): started, not
  9224.         // ended. Gives "what they're doing" (task + project) and a task-level GPS
  9225.         // when the app captured one. InnoTracker is obsolete and not used here.
  9226.         $taskByEmp = [];
  9227.         foreach ($all(
  9228.             "SELECT tl.employee_id, pi.item_alias AS task_name, p.project_name,
  9229.                     tl.lat AS task_lat, tl.lng AS task_lng
  9230.              FROM task_log tl
  9231.              JOIN (SELECT employee_id, MAX(id) AS mid FROM task_log
  9232.                    WHERE employee_id IS NOT NULL AND actual_start_ts IS NOT NULL
  9233.                      AND (actual_end_ts IS NULL OR actual_end_ts = 0)
  9234.                    GROUP BY employee_id) m ON m.mid = tl.id
  9235.              LEFT JOIN planning_item pi ON pi.id = tl.planning_item_id
  9236.              LEFT JOIN project p ON p.project_id = tl.project_id"
  9237.         ) as $t) {
  9238.             $taskByEmp[(int) $t['employee_id']] = [
  9239.                 'task' => trim((string) $t['task_name']),
  9240.                 'project' => trim((string) $t['project_name']),
  9241.                 'lat' => (float) $t['task_lat'], 'lng' => (float) $t['task_lng'],
  9242.             ];
  9243.         }
  9244.         $now = new \DateTime();
  9245.         $people = []; $working 0$stale 0$offsite 0$seenEmp = [];
  9246.         foreach ($rows as $r) {
  9247.             $lat = (float) $r['current_lat']; $lng = (float) $r['current_lng'];
  9248.             if ($lat == 0.0 && $lng == 0.0) { continue; }
  9249.             $mins null$last trim((string) $r['last_start_time']);
  9250.             if ($last !== '' && $last !== '0000-00-00 00:00:00') {
  9251.                 try { $mins = (int) round(($now->getTimestamp() - (new \DateTime($last))->getTimestamp()) / 60); } catch (\Throwable $e) {}
  9252.             }
  9253.             $eid = (int) $r['employee_id'];
  9254.             $seenEmp[$eid] = true;
  9255.             $task $taskByEmp[$eid] ?? null;
  9256.             $hasTask $task && $task['task'] !== '';
  9257.             // Prefer task-level GPS (more precise / current) when the app captured one.
  9258.             if ($task && $task['lat'] != 0.0) { $lat $task['lat']; $lng $task['lng']; }
  9259.             $clockedIn = (int) $r['clocked_in'] === 1;
  9260.             // status: working (on a task or on the clock, fresh) / idle / stale (no fresh ping)
  9261.             $status 'idle';
  9262.             if ($mins !== null && $mins 180 && !$hasTask) { $status 'stale'$stale++; }
  9263.             elseif ($clockedIn || $hasTask) { $status 'working'$working++; }
  9264.             if (isset($r['is_from_assigned_area']) && (int) $r['is_from_assigned_area'] === && $clockedIn) { $offsite++; }
  9265.             $people[] = [
  9266.                 'id' => $eid,
  9267.                 'name' => trim((string) $r['emp_name']) ?: ('Employee #' $eid),
  9268.                 'lat' => $lat'lng' => $lng,
  9269.                 'address' => trim((string) $r['current_address']) ?: '',
  9270.                 'clockedIn' => $clockedIn,
  9271.                 'status' => $status,
  9272.                 'task' => $hasTask $task['task'] : '',
  9273.                 'project' => $hasTask $task['project'] : '',
  9274.                 'workHours' => (float) $r['total_work_hour'],
  9275.                 'isLate' => (int) $r['is_late'] === 1,
  9276.                 'offsite' => isset($r['is_from_assigned_area']) ? ((int) $r['is_from_assigned_area'] === 0) : null,
  9277.                 'lastSeen' => $last,
  9278.                 'minsAgo' => $mins,
  9279.                 'source' => (string) $r['attendance_source'],
  9280.             ];
  9281.         }
  9282.         // Employees on an active task with task-level GPS but no attendance ping
  9283.         // (located purely by the Nectar task clock-in).
  9284.         foreach ($taskByEmp as $eid => $t) {
  9285.             if (isset($seenEmp[$eid]) || $t['lat'] == 0.0 || $t['task'] === '') { continue; }
  9286.             $nm $all("SELECT name FROM employee WHERE employee_id = :id AND (status IS NULL OR status <> 0)", ['id' => $eid]);
  9287.             if (empty($nm)) { continue; } // inactive / unknown employee â†’ skip
  9288.             $working++;
  9289.             $people[] = [
  9290.                 'id' => $eid,
  9291.                 'name' => ($nm[0]['name'] ?? '') ?: ('Employee #' $eid),
  9292.                 'lat' => $t['lat'], 'lng' => $t['lng'], 'address' => '',
  9293.                 'clockedIn' => true'status' => 'working',
  9294.                 'task' => $t['task'], 'project' => $t['project'],
  9295.                 'workHours' => 0.0'isLate' => false'offsite' => null,
  9296.                 'lastSeen' => '''minsAgo' => null'source' => 'task',
  9297.             ];
  9298.         }
  9299.         // Planned visits (with coordinates) for context overlay.
  9300.         $visits $all(
  9301.             "SELECT v.latitude, v.longitude, v.location, v.start_date, v.priority_status
  9302.              FROM plan_visit v
  9303.              WHERE v.latitude IS NOT NULL AND v.latitude <> 0
  9304.                AND (v.delete_flag IS NULL OR v.delete_flag = 0)
  9305.              ORDER BY v.start_date DESC LIMIT 200"
  9306.         );
  9307.         $visitPins = [];
  9308.         foreach ($visits as $v) {
  9309.             $vlat = (float) $v['latitude']; $vlng = (float) $v['longitude'];
  9310.             if ($vlat == 0.0 && $vlng == 0.0) { continue; }
  9311.             $visitPins[] = ['lat' => $vlat'lng' => $vlng'location' => trim((string) $v['location']), 'date' => (string) $v['start_date']];
  9312.         }
  9313.         // Route-history trail: GPS pings within the selected window ($hours, default
  9314.         // 24h), chronological, capped to the most recent 60 points per employee.
  9315.         $trails = [];
  9316.         foreach ($all(
  9317.             "SELECT employee_id, current_lat, current_lng
  9318.              FROM employee_attendance_log
  9319.              WHERE current_lat IS NOT NULL AND current_lat <> 0 AND current_lat <> ''
  9320.                AND last_start_time >= DATE_SUB(NOW(), INTERVAL " . (int) $hours " HOUR)
  9321.              ORDER BY employee_id, id ASC"
  9322.         ) as $g) {
  9323.             $eid = (int) $g['employee_id'];
  9324.             $la = (float) $g['current_lat']; $ln = (float) $g['current_lng'];
  9325.             if ($la == 0.0 && $ln == 0.0) { continue; }
  9326.             if (!isset($trails[$eid])) { $trails[$eid] = []; }
  9327.             $trails[$eid][] = ['lat' => $la'lng' => $ln];
  9328.         }
  9329.         // Keep only trails for the active employees shown on the map; cap length.
  9330.         $personIds = [];
  9331.         foreach ($people as $p) { $personIds[$p['id']] = true; }
  9332.         foreach ($trails as $eid => $pts) {
  9333.             if (!isset($personIds[$eid])) { unset($trails[$eid]); continue; }
  9334.             if (count($pts) > 60) { $trails[$eid] = array_slice($pts, -60); }
  9335.         }
  9336.         return [
  9337.             'people' => $people,
  9338.             'visits' => $visitPins,
  9339.             'trails' => $trails,
  9340.             'hours'  => $hours,
  9341.             'kpi'    => ['total' => count($people), 'working' => $working'stale' => $stale'offsite' => $offsite],
  9342.         ];
  9343.     }
  9344.     /**
  9345.      * cp-shell Payroll Report â€” pick a period, see headline totals and a
  9346.      * by-employee breakdown (gross / deductions / net), with print. Fail-safe
  9347.      * DBAL; reads payslip header figures (consistent with the GL & return data).
  9348.      */
  9349.     public function HrmPayrollReportAction(Request $request): Response
  9350.     {
  9351.         $em $this->getDoctrine()->getManager();
  9352.         $conn $em->getConnection();
  9353.         $one = function ($sql$p = []) use ($conn) { try { $v $conn->fetchOne($sql$p); return $v === false null $v; } catch (\Throwable $e) { return null; } };
  9354.         $all = function ($sql$p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql$p); } catch (\Throwable $e) { return []; } };
  9355.         // Available periods (YYYY-MM) for the selector.
  9356.         $periodRows $all("SELECT DISTINCT DATE_FORMAT(start_date, '%Y-%m') ym FROM payslip WHERE start_date IS NOT NULL ORDER BY ym DESC");
  9357.         $periods array_map(function ($r) { return $r['ym']; }, $periodRows);
  9358.         $period = (string) $request->query->get('period''');
  9359.         if ($period === '' || !in_array($period$periodstrue)) {
  9360.             $period $periods[0] ?? date('Y-m');
  9361.         }
  9362.         // Per-employee breakdown for the chosen period.
  9363.         $rows $all(
  9364.             "SELECT p.sys_id,
  9365.                     COALESCE(NULLIF(TRIM(CONCAT(COALESCE(e.firstname,''),' ',COALESCE(e.lastname,''))),''), CONCAT('Emp #', p.sys_id)) AS name,
  9366.                     e.emp_code,
  9367.                     ROUND(SUM(CAST(NULLIF(p.eart,'') AS DECIMAL(18,2))),2) gross,
  9368.                     ROUND(SUM(CAST(NULLIF(p.dedt,'') AS DECIMAL(18,2))),2) ded,
  9369.                     ROUND(SUM(p.payable_salary),2) net,
  9370.                     MAX(p.approved) approved
  9371.                FROM payslip p
  9372.                LEFT JOIN employee_details e ON e.id = p.sys_id
  9373.               WHERE DATE_FORMAT(p.start_date, '%Y-%m') = :ym
  9374.               GROUP BY p.sys_id, name, e.emp_code
  9375.               ORDER BY net DESC",
  9376.             ['ym' => $period]
  9377.         );
  9378.         $totGross 0.0$totDed 0.0$totNet 0.0$approvedCount 0;
  9379.         foreach ($rows as $r) {
  9380.             $totGross += (float) $r['gross']; $totDed += (float) $r['ded']; $totNet += (float) $r['net'];
  9381.             if ((int) $r['approved'] === 1) { $approvedCount++; }
  9382.         }
  9383.         $cc strtoupper((string) $one("SELECT co.code FROM company c LEFT JOIN countries co ON co.country_id = c.country_id ORDER BY c.id LIMIT 1"));
  9384.         $currency = ['BD' => 'à§³''SG' => 'S$''DE' => '€'][$cc] ?? '';
  9385.         $statutoryOn = ((string) $one("SELECT data FROM acc_setting WHERE name = 'payroll_statutory_enabled' LIMIT 1")) === '1';
  9386.         return $this->render('@Application/pages/human_resource/cockpit/hrm_payroll_report.html.twig', [
  9387.             'page_title' => 'Payroll Report',
  9388.             'periods' => $periods'period' => $period'rows' => $rows,
  9389.             'totGross' => $totGross'totDed' => $totDed'totNet' => $totNet,
  9390.             'headcount' => count($rows), 'approvedCount' => $approvedCount,
  9391.             'currency' => $currency'country' => $cc'statutoryOn' => $statutoryOn,
  9392.         ]);
  9393.     }
  9394.     /**
  9395.      * cp-shell Headcount & Attrition report â€” joiners vs leavers over the last
  9396.      * 12 months, attrition rate, average tenure, and composition by type/branch.
  9397.      * Fail-safe DBAL.
  9398.      */
  9399.     public function HrmHeadcountReportAction(Request $request): Response
  9400.     {
  9401.         $em $this->getDoctrine()->getManager();
  9402.         $conn $em->getConnection();
  9403.         $one = function ($sql$p = []) use ($conn) { try { $v $conn->fetchOne($sql$p); return $v === false null $v; } catch (\Throwable $e) { return null; } };
  9404.         $all = function ($sql$p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql$p); } catch (\Throwable $e) { return []; } };
  9405.         $active = (int) $one("SELECT COUNT(*) FROM employee_details WHERE emp_status = 1");
  9406.         $total  = (int) $one("SELECT COUNT(*) FROM employee_details");
  9407.         $joiners12 = (int) $one("SELECT COUNT(*) FROM employee_details WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)");
  9408.         $leavers12 = (int) $one("SELECT COUNT(*) FROM resign_application WHERE approved = 1 AND COALESCE(resigned_from, created_at) >= DATE_SUB(NOW(), INTERVAL 12 MONTH)");
  9409.         $attrition $active round($leavers12 100 / ($active $leavers12), 1) : 0.0;
  9410.         $avgTenure = (float) $one("SELECT ROUND(AVG(DATEDIFF(NOW(), joining_date)) / 365.0, 1) FROM employee_details WHERE emp_status = 1 AND joining_date IS NOT NULL");
  9411.         // 12-month joiners vs leavers axis (built in PHP so empty months show as 0).
  9412.         $months = [];
  9413.         $cur = new \DateTime('first day of this month');
  9414.         for ($i 11$i >= 0$i--) {
  9415.             $k = (clone $cur)->modify("-$i month")->format('Y-m');
  9416.             $months[$k] = ['joiners' => 0'leavers' => 0];
  9417.         }
  9418.         foreach ($all("SELECT DATE_FORMAT(joining_date,'%Y-%m') m, COUNT(*) c FROM employee_details WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY m") as $r) {
  9419.             if (isset($months[$r['m']])) { $months[$r['m']]['joiners'] = (int) $r['c']; }
  9420.         }
  9421.         foreach ($all("SELECT DATE_FORMAT(COALESCE(resigned_from, created_at),'%Y-%m') m, COUNT(*) c FROM resign_application WHERE approved = 1 AND COALESCE(resigned_from, created_at) >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY m") as $r) {
  9422.             if (isset($months[$r['m']])) { $months[$r['m']]['leavers'] = (int) $r['c']; }
  9423.         }
  9424.         $maxFlow 1;
  9425.         foreach ($months as $v) { $maxFlow max($maxFlow$v['joiners'], $v['leavers']); }
  9426.         // Composition
  9427.         $typeLabels = [=> 'Full-time'=> 'Part-time'=> 'Intern'=> 'Temporary'=> 'Contractual'];
  9428.         $byType = [];
  9429.         foreach ($all("SELECT emp_type t, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY emp_type") as $r) {
  9430.             $byType[$typeLabels[(int) $r['t']] ?? ('Type ' . (int) $r['t'])] = (int) $r['c'];
  9431.         }
  9432.         $byBranch = [];
  9433.         foreach ($all("SELECT COALESCE(NULLIF(TRIM(branch_name),''),'Unassigned') b, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY b ORDER BY c DESC LIMIT 8") as $r) {
  9434.             $byBranch[$r['b']] = (int) $r['c'];
  9435.         }
  9436.         $recentLeavers $all(
  9437.             "SELECT COALESCE(NULLIF(TRIM(CONCAT(COALESCE(e.firstname,''),' ',COALESCE(e.lastname,''))),''), CONCAT('Emp #', r.employee_id)) AS name,
  9438.                     e.emp_code, e.branch_name, COALESCE(r.resigned_from, r.created_at) AS dt
  9439.                FROM resign_application r LEFT JOIN employee_details e ON e.id = r.employee_id
  9440.               WHERE r.approved = 1 ORDER BY dt DESC LIMIT 6");
  9441.         $cc strtoupper((string) $one("SELECT co.code FROM company c LEFT JOIN countries co ON co.country_id = c.country_id ORDER BY c.id LIMIT 1"));
  9442.         return $this->render('@Application/pages/human_resource/cockpit/hrm_headcount_report.html.twig', [
  9443.             'page_title' => 'Headcount & Attrition',
  9444.             'active' => $active'total' => $total'joiners12' => $joiners12'leavers12' => $leavers12,
  9445.             'attrition' => $attrition'avgTenure' => $avgTenure,
  9446.             'months' => $months'maxFlow' => $maxFlow,
  9447.             'byType' => $byType'byBranch' => $byBranch'recentLeavers' => $recentLeavers'country' => $cc,
  9448.         ]);
  9449.     }
  9450.     /**
  9451.      * Renders the Employee Dashboard with attendance, active clock status, and leave balances.
  9452.      */
  9453.     public function EmployeeDashboardAction(Request $request): Response
  9454.     {
  9455.         $em $this->getDoctrine()->getManager();
  9456.         $session $request->getSession();
  9457.         $empId $session->get(UserConstants::USER_EMPLOYEE_ID);
  9458.         $userId $session->get(UserConstants::USER_ID);
  9459.         if (!$empId || !$userId) {
  9460.             return $this->redirectToRoute('user_login');
  9461.         }
  9462.         $localTz = new \DateTimeZone('+0600');
  9463.         $utcTz = new \DateTimeZone('UTC');
  9464.         $today = new \DateTime('now'$localTz);
  9465.         $todayStr $today->format('Y-m-d');
  9466.         // â”€â”€ 1. Basic Info â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9467.         $employee $em->getRepository(Employee::class)->findOneBy(['employeeId' => $empId]);
  9468.         $employeeName $employee
  9469.             ? ($employee->getFirstName() . ' ' $employee->getLastName())
  9470.             : 'Employee';
  9471.         // â”€â”€ 2. Attendance Logic (today's clock-in/out) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9472.         $todayMidnight = new \DateTime($todayStr ' 00:00:00');
  9473.         $todayAttendance $em->getRepository(EmployeeAttendance::class)->findOneBy([
  9474.             'employeeId' => $empId,
  9475.             'date' => $todayMidnight,
  9476.         ]);
  9477.         $entryTime null;
  9478.         $lastOutTime null;
  9479.         $currentLocation 'none';
  9480.         $workedSeconds 0;
  9481.         if (
  9482.             $todayAttendance
  9483.             && method_exists($todayAttendance'getData')
  9484.             && $todayAttendance->getData()
  9485.         ) {
  9486.             $attData json_decode($todayAttendance->getData(), true);
  9487.             if (is_array($attData) && isset($attData['in'])) {
  9488.                 $inCount count($attData['in']);
  9489.                 $outCount = isset($attData['out']) ? count($attData['out']) : 0;
  9490.                 // Accumulate fully-completed in/out pairs
  9491.                 for ($i 0$i $outCount$i++) {
  9492.                     $inDt = new \DateTime($todayStr ' ' $attData['in'][$i], $utcTz);
  9493.                     $outDt = new \DateTime($todayStr ' ' $attData['out'][$i], $utcTz);
  9494.                     $workedSeconds += max(0$outDt->getTimestamp() - $inDt->getTimestamp());
  9495.                 }
  9496.                 if ($inCount $outCount) {
  9497.                     // Currently on-site
  9498.                     $currentLocation 'in';
  9499.                     $entryDt = new \DateTime($todayStr ' ' $attData['in'][$inCount 1], $utcTz);
  9500.                     $entryDt->setTimezone($localTz);
  9501.                     $entryTime $entryDt->format('Y-m-d H:i:s');
  9502.                 } elseif ($outCount 0) {
  9503.                     // Clocked out
  9504.                     $currentLocation 'out';
  9505.                     $outDt = new \DateTime($todayStr ' ' $attData['out'][$outCount 1], $utcTz);
  9506.                     $outDt->setTimezone($localTz);
  9507.                     $lastOutTime $outDt->format('Y-m-d H:i:s');
  9508.                 }
  9509.             }
  9510.         }
  9511.         // â”€â”€ Task Log: sync with attendance state â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9512.         // Only acts when attendance state and task-log state are out of sync.
  9513.         // Does NOT create duplicate logs on page refresh.
  9514.         $currTs = (new \DateTime())->format('U');
  9515.         $activeTaskLog $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  9516.             ->findOneBy(['userId' => $userId'workingStatus' => 1]);
  9517.         if ($currentLocation === 'in' && !$activeTaskLog) {
  9518.             // Clocked IN but no open task log â€” create one
  9519.             $planningItemId $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9520.             // Fall back to last known planning item if session has none
  9521.             if (!$planningItemId) {
  9522.                 $lastTask $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
  9523.                     ->findOneBy(['userId' => $userId], ['id' => 'DESC']);
  9524.                 $planningItemId $lastTask $lastTask->getPlanningItemId() : 0;
  9525.             }
  9526.             $taskLog = new \ApplicationBundle\Entity\TaskLog();
  9527.             $taskLog->setPlanningItemId($planningItemId);
  9528.             $taskLog->setUserId($userId);
  9529.             $taskLog->setLogType('session');
  9530.             $taskLog->setWorkingStatus(1);
  9531.             $taskLog->setActualStartTs($currTs);
  9532.             $em->persist($taskLog);
  9533.             $em->flush();
  9534.             $session->set(UserConstants::USER_CURRENT_TASK_ID$taskLog->getId());
  9535.             $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$planningItemId);
  9536.         } elseif (($currentLocation === 'out' || $currentLocation === 'none') && $activeTaskLog) {
  9537.             // Clocked OUT (or no attendance) but task log still open â€” close it
  9538.             $em->getConnection()->executeStatement(
  9539.                 'UPDATE task_log SET working_status=2, actual_end_ts=' $currTs .
  9540.                 ' WHERE working_status=1 AND user_id=' $userId
  9541.             );
  9542.             $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  9543.             $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  9544.         } elseif ($currentLocation === 'in' && $activeTaskLog) {
  9545.             // Already in sync â€” keep session aligned with DB record
  9546.             $session->set(UserConstants::USER_CURRENT_TASK_ID$activeTaskLog->getId());
  9547.             $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$activeTaskLog->getPlanningItemId());
  9548.         }
  9549.         // â”€â”€ 3. Leave Management â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9550.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->find($empId);
  9551.         $leaveBalanceList = [];
  9552.         $leaveNamesMap = [];
  9553.         $totalUsedDays 0;
  9554.         $totalAllowedLimit 0;
  9555.         if ($employeeDetails) {
  9556.             $leaveConfig json_decode($employeeDetails->getLeaveData(), true) ?? [];
  9557.             foreach ($leaveConfig as $config) {
  9558.                 $id $config['id'];
  9559.                 $title $config['title'];
  9560.                 $limit = (float)$config['total_leave'];
  9561.                 $leaveNamesMap[$id] = $title;
  9562.                 $getter "getLeave{$id}Tkn";
  9563.                 $taken method_exists($employeeDetails$getter)
  9564.                     ? (float)$employeeDetails->$getter()
  9565.                     : 0;
  9566.                 $totalUsedDays += $taken;
  9567.                 $totalAllowedLimit += $limit;
  9568.                 $leaveBalanceList[] = ['name' => $title'used' => $taken'limit' => $limit];
  9569.             }
  9570.         }
  9571.         // â”€â”€ 4. Upcoming Leaves â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9572.         $upcomingEntities $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  9573.             ->createQueryBuilder('L')
  9574.             ->where('L.employeeId = :empId AND L.approved = 1 AND L.leaveStartDate >= :today')
  9575.             ->setParameter('empId'$empId)
  9576.             ->setParameter('today'$todayMidnight)
  9577.             ->orderBy('L.leaveStartDate''ASC')
  9578.             ->setMaxResults(3)
  9579.             ->getQuery()->getResult();
  9580.         $upcomingLeaveFormatted = [];
  9581.         foreach ($upcomingEntities as $entity) {
  9582.             $upcomingLeaveFormatted[] = [
  9583.                 'leaveStartDate' => $entity->getLeaveStartDate(),
  9584.                 'leaveEndDate' => $entity->getLeaveEndDate(),
  9585.                 'leaveDaysCountable' => $entity->getLeaveDaysCountable(),
  9586.                 'leaveTypeName' => $leaveNamesMap[$entity->getLeaveTypeId()] ?? 'General Leave',
  9587.             ];
  9588.         }
  9589.         // â”€â”€ 5. Calendar year boundaries â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9590.         $yearStart = new \DateTime($today->format('Y') . '-01-01 00:00:00');
  9591.         $yearEnd = new \DateTime($today->format('Y') . '-12-31 23:59:59');
  9592.         // â”€â”€ 6a. Calendar: Leave dates (current year) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9593.         $calendarLeaveEntities $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
  9594.             ->createQueryBuilder('L')
  9595.             ->where('L.employeeId = :empId AND L.approved = 1')
  9596.             ->andWhere('L.leaveStartDate <= :yearEnd')
  9597.             ->andWhere('L.leaveEndDate   >= :yearStart')
  9598.             ->setParameter('empId'$empId)
  9599.             ->setParameter('yearStart'$yearStart)
  9600.             ->setParameter('yearEnd'$yearEnd)
  9601.             ->getQuery()->getResult();
  9602.         $calendarEvents = [];
  9603.         foreach ($calendarLeaveEntities as $lv) {
  9604.             $cursor = clone $lv->getLeaveStartDate();
  9605.             $end = clone $lv->getLeaveEndDate();
  9606.             $typeName $leaveNamesMap[$lv->getLeaveTypeId()] ?? 'Leave';
  9607.             while ($cursor <= $end) {
  9608.                 $calendarEvents[] = [
  9609.                     'date' => $cursor->format('Y-m-d'),
  9610.                     'type' => $typeName,
  9611.                     'kind' => 'leave',
  9612.                 ];
  9613.                 $cursor->modify('+1 day');
  9614.             }
  9615.         }
  9616.         // â”€â”€ 6b. Calendar: Holiday dates (current year) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9617.         $companyId $session->get(UserConstants::USER_COMPANY_ID) ?? 0;
  9618.         $approvedCalendarIds $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendar')
  9619.             ->createQueryBuilder('H')
  9620.             ->select('H.holidayCalendarId')
  9621.             ->where('H.approved = 1')
  9622.             ->andWhere('H.CompanyId = :cid')
  9623.             ->setParameter('cid'$companyId)
  9624.             ->getQuery()
  9625.             ->getSingleColumnResult();
  9626.         $calendarHolidayDates = [];
  9627.         if (!empty($approvedCalendarIds)) {
  9628.             $holidayDateRows $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')
  9629.                 ->createQueryBuilder('D')
  9630.                 ->where('D.holidayCalendarId IN (:calIds)')
  9631.                 ->andWhere('D.startDate <= :yearEnd')
  9632.                 ->andWhere('D.endDate   >= :yearStart')
  9633.                 ->setParameter('calIds'$approvedCalendarIds)
  9634.                 ->setParameter('yearStart'$yearStart)
  9635.                 ->setParameter('yearEnd'$yearEnd)
  9636.                 ->getQuery()->getResult();
  9637.             foreach ($holidayDateRows as $row) {
  9638.                 $cursor = clone $row->getStartDate();
  9639.                 $end = clone $row->getEndDate();
  9640.                 $title $row->getHolidayTitle() ?: 'Holiday';
  9641.                 while ($cursor <= $end) {
  9642.                     $calendarHolidayDates[] = [
  9643.                         'date' => $cursor->format('Y-m-d'),
  9644.                         'type' => $title,
  9645.                         'kind' => 'holiday',
  9646.                     ];
  9647.                     $cursor->modify('+1 day');
  9648.                 }
  9649.             }
  9650.         }
  9651.         // â”€â”€ 6c. Calendar: Present dates (current year) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9652.         // Uses EmployeeAttendanceLog where isPresent = 1.
  9653.         // NOTE: adjust the getter (getLastStartTime / getLastEndTime) to whichever
  9654.         //       column stores the working date in your entity.
  9655.         $attendanceLogs $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')
  9656.             ->createQueryBuilder('a')
  9657.             ->where('a.employeeId = :empId')
  9658.             ->andWhere('a.isPresent = 1')
  9659.             ->andWhere('a.last_end_time >= :yearStart')
  9660.             ->andWhere('a.last_end_time <= :yearEnd')
  9661.             ->setParameter('empId'$empId)
  9662.             ->setParameter('yearStart'$yearStart)
  9663.             ->setParameter('yearEnd'$yearEnd)
  9664.             ->getQuery()
  9665.             ->getResult();
  9666.         $calendarPresentDates = [];
  9667.         foreach ($attendanceLogs as $log) {
  9668.             // If your entity uses getLastStartTime() instead, change the line below
  9669.             $dt $log->getLastEndTime();
  9670.             if ($dt instanceof \DateTime) {
  9671.                 $calendarPresentDates[] = $dt->format('Y-m-d');
  9672.             }
  9673.         }
  9674.         $calendarPresentDates array_values(array_unique($calendarPresentDates));
  9675.         // Merge leave + holiday events for the calendar
  9676.         $calendarEvents array_merge($calendarEvents$calendarHolidayDates);
  9677.         // â”€â”€ 7. Planning Items (To-Do List) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9678.         $planningItems $em->getRepository('ApplicationBundle\\Entity\\PlanningItem')
  9679.             ->createQueryBuilder('P')
  9680.             ->where('P.status = 1')
  9681.             ->andWhere(
  9682.                 'P.assignedTo = :empId OR P.assignedToIds LIKE :empIdLike'
  9683.             )
  9684.             ->setParameter('empId'$empId)
  9685.             ->setParameter('empIdLike''%' $empId '%')
  9686.             ->orderBy('P.estimatedCompletionTimeTs''DESC')
  9687.             ->setMaxResults(10)
  9688.             ->getQuery()->getResult();
  9689.         $todoList = [];
  9690.         foreach ($planningItems as $item) {
  9691.             $dueTs $item->getEstimatedCompletionTimeTs();
  9692.             $todoList[] = [
  9693.                 'id' => $item->getId(),
  9694.                 'title' => $item->getItemAlias() ?: $item->getDescription() ?: 'Untitled Task',
  9695.                 'desc' => $item->getItemDesc() ?: '',
  9696.                 'stage' => (int)$item->getStage(),
  9697.                 'urgency' => (int)$item->getUrgency(),
  9698.                 'dueTs' => $dueTs,
  9699.                 'dueDate' => $dueTs date('d M Y'$dueTs) : null,
  9700.                 'isOverdue' => $dueTs && $dueTs time() && (int)$item->getStage() < 2,
  9701.                 'percentage' => (int)($item->getCompletionPercentage() ?? 0),
  9702.             ];
  9703.         }
  9704.         // â”€â”€ Render â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  9705.         return $this->render('@Application/pages/dashboard/employeeDashboard.html.twig', [
  9706.             'page_title' => 'My Dashboard',
  9707.             'employeeName' => $employeeName,
  9708.             'empId' => $empId,
  9709.             'userId' => $userId,
  9710.             'entryTime' => $entryTime,
  9711.             'lastOutTime' => $lastOutTime,
  9712.             'currentLocation' => $currentLocation,
  9713.             'workedSeconds' => $workedSeconds,
  9714.             'leaveBalance' => $leaveBalanceList,
  9715.             'totalLeaveQty' => $totalAllowedLimit,
  9716.             'totalUsedDays' => $totalUsedDays,
  9717.             'totalLeaveRemaining' => max(0$totalAllowedLimit $totalUsedDays),
  9718.             'upcomingLeave' => $upcomingLeaveFormatted,
  9719.             'calendarLeaveDates' => $calendarEvents,
  9720.             'calendarPresentDates' => $calendarPresentDates,
  9721.             'weekendDays' => [56],
  9722.             'todoList' => $todoList,
  9723.         ]);
  9724.     }
  9725.     public function leavePolicyListAction()
  9726.     {
  9727.         return $this->render("@Application/pages/human_resource/list/leaveApplicationSettingsList.html.twig", array(
  9728.             'page_title' => 'Leave PolicyList',
  9729.         ));
  9730.     }
  9731.     public function getEmployeeProfileDataAction(Request $request)
  9732.     {
  9733.         $em $this->getDoctrine()->getManager();
  9734.         $session $request->getSession();
  9735.         $userId $session->get(UserConstants::USER_ID);
  9736.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  9737.         $employeeData $em->getRepository('ApplicationBundle\\Entity\\Employee')
  9738.             ->findOneBy(
  9739.                 array(
  9740.                     'userId' => $userId
  9741.                 )
  9742.             );
  9743.         // The logged-in user may be known to this tenant without having an
  9744.         // Employee record here (e.g. an owner/admin who isn't an employee).
  9745.         // Return an empty-but-valid profile instead of dereferencing null,
  9746.         // which previously 500'd and broke the app dashboard.
  9747.         if (!$employeeData) {
  9748.             $data EmployeePayloadNormalizer::normalize([
  9749.                 'firstname' => '',
  9750.                 'lastname' => '',
  9751.                 'image' => '',
  9752.             ]);
  9753.             $data['userImage'] = '';
  9754.             return new JsonResponse([
  9755.                 'success' => true,
  9756.                 'data' => $data
  9757.             ]);
  9758.         }
  9759.         $data EmployeePayloadNormalizer::normalize([
  9760.             'firstname' => $employeeData->getFirstname(),
  9761.             'lastname' => $employeeData->getLastname(),
  9762.             'image' => $employeeData->getImage(),
  9763.         ]);
  9764.         $data['userImage'] = $absoluteUrl '' $employeeData->getImage();
  9765.         return new JsonResponse([
  9766.             'success' => true,
  9767.             'data' => $data
  9768.         ]);
  9769.     }
  9770. //    public function getMeetingSummaryAction(Request $request)
  9771. //    {
  9772. //        $em = $this->getDoctrine()->getManager();
  9773. //        $meetingId = $request->query->get('id');
  9774. //
  9775. //        $queryBuilder = $em->createQueryBuilder();
  9776. //        $queryBuilder
  9777. //            ->select('M', 'r.roomNo')
  9778. //            ->from('ApplicationBundle:ScheduledMeeting', 'M')
  9779. //            ->leftJoin('ApplicationBundle:Room', 'r', 'WITH', 'M.roomId = r.roomId')
  9780. //            ->where('M.scheduleId = :id')
  9781. //            ->setParameter('id', $meetingId);
  9782. //
  9783. //        $data = $queryBuilder->getQuery()->getResult();
  9784. //
  9785. //        $result = [];
  9786. //
  9787. //        foreach ($data as $row) {
  9788. //            $meeting = $row[0];
  9789. //
  9790. //            $result[] = [
  9791. //                'scheduleId'  => $meeting->getScheduleId(),
  9792. //                'title'       => $meeting->getTitle(),
  9793. //                'location'    => $meeting->getLocation(),
  9794. //                'roomId'      => $meeting->getRoomId(),
  9795. //                'startAt'     => $meeting->getStartAt() ? $meeting->getStartAt()->format('d-m-Y') : null,
  9796. //                'endAt'       => $meeting->getEndAt() ? $meeting->getEndAt()->format('d-m-Y') : null,
  9797. //                'agendaList'  => $meeting->getAgendaList(),
  9798. //                'roomNo'      => $row['roomNo']
  9799. //            ];
  9800. //        }
  9801. //
  9802. //        return new JsonResponse($result);
  9803. //    }
  9804.     public function getMeetingSummaryAction(Request $request)
  9805.     {
  9806.         $em $this->getDoctrine()->getManager();
  9807.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  9808.         $meetingId $request->query->get('id');
  9809.         $queryBuilder $em->createQueryBuilder();
  9810.         $queryBuilder
  9811.             ->select('M''r.roomNo')
  9812.             ->from('ApplicationBundle:ScheduledMeeting''M')
  9813.             ->leftJoin('ApplicationBundle:Room''r''WITH''M.roomId = r.roomId')
  9814.             ->where('M.scheduleId = :id')
  9815.             ->setParameter('id'$meetingId);
  9816.         $data $queryBuilder->getQuery()->getResult();
  9817.         $result = [];
  9818.         foreach ($data as $row) {
  9819.             $meeting $row[0];
  9820.             $participantIds json_decode($meeting->getInternalParticipantIds(), true) ?? [];
  9821.             $participants = [];
  9822.             if (!empty($participantIds)) {
  9823.                 $empQuery $em->createQueryBuilder()
  9824.                     ->select('e.employeeId''e.name''e.image')
  9825.                     ->from('ApplicationBundle:Employee''e')
  9826.                     ->where('e.employeeId IN (:ids)')
  9827.                     ->setParameter('ids'$participantIds)
  9828.                     ->getQuery()
  9829.                     ->getArrayResult();
  9830.                 foreach ($empQuery as $emp) {
  9831.                     $participants[] = [
  9832.                         'name' => $emp['name'],
  9833.                         'image' => rtrim($absoluteUrl'/') . '/' ltrim($emp['image'], '/')
  9834.                     ];
  9835.                 }
  9836.             }
  9837.             $result[] = [
  9838.                 'scheduleId' => $meeting->getScheduleId(),
  9839.                 'title' => $meeting->getTitle(),
  9840.                 'location' => $meeting->getLocation(),
  9841.                 'roomId' => $meeting->getRoomId(),
  9842.                 'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('d-m-Y') : null,
  9843.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('d-m-Y') : null,
  9844.                 'agendaList' => $meeting->getAgendaList(),
  9845.                 'roomNo' => $row['roomNo'],
  9846.                 'Participant' => $participants
  9847.             ];
  9848.         }
  9849.         return new JsonResponse([
  9850.             'status' => 'success',
  9851.             'message' => 'Meeting retrieved successfully',
  9852.             'data' => $result
  9853.         ], 200);
  9854.     }
  9855.     private function getLeaveUploadedFiles($files)
  9856.     {
  9857.         $uploadedFiles = array();
  9858.         foreach ($files as $uploadedFileGroup) {
  9859.             if (is_array($uploadedFileGroup)) {
  9860.                 foreach ($uploadedFileGroup as $uploadedFile) {
  9861.                     if ($uploadedFile !== null) {
  9862.                         $uploadedFiles[] = $uploadedFile;
  9863.                     }
  9864.                 }
  9865.             } elseif ($uploadedFileGroup !== null) {
  9866.                 $uploadedFiles[] = $uploadedFileGroup;
  9867.             }
  9868.         }
  9869.         return $uploadedFiles;
  9870.     }
  9871.     private function getLeaveAttachmentExtension($uploadedFile)
  9872.     {
  9873.         $extension strtolower((string)$uploadedFile->guessExtension());
  9874.         if ($extension === '') {
  9875.             $extension strtolower((string)$uploadedFile->getClientOriginalExtension());
  9876.         }
  9877.         return $extension;
  9878.     }
  9879.     private function validateLeaveAttachmentFiles($files)
  9880.     {
  9881.         $allowedExtensions = array('pdf''jpg''jpeg''png''doc''docx');
  9882.         $maxFileSize 1024 1024;
  9883.         foreach ($this->getLeaveUploadedFiles($files) as $uploadedFile) {
  9884.             $extension $this->getLeaveAttachmentExtension($uploadedFile);
  9885.             if (!in_array($extension$allowedExtensionstrue)) {
  9886.                 return "Only PDF, JPG, JPEG, PNG, DOC, and DOCX files are allowed for supporting documents.";
  9887.             }
  9888.             if ((int)$uploadedFile->getSize() > $maxFileSize) {
  9889.                 return "Each supporting document must be 5 MB or smaller.";
  9890.             }
  9891.         }
  9892.         return null;
  9893.     }
  9894. }