<?php
namespace ApplicationBundle\Controller;
use ApplicationBundle\Constants\BuddybeeConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\HumanResourceConstant;
use ApplicationBundle\Constants\MeetingSchedulingConstant;
use ApplicationBundle\Entity\AttendanceAmendment;
use ApplicationBundle\Entity\BankList;
use ApplicationBundle\Entity\BonusPolicy;
use ApplicationBundle\Entity\Branch;
use ApplicationBundle\Entity\ConsultancyTopic;
use ApplicationBundle\Entity\EducationQualification;
use ApplicationBundle\Entity\Employee;
use ApplicationBundle\Entity\EmployeeAttendance;
use ApplicationBundle\Entity\EmployeeAttendanceLog;
use ApplicationBundle\Entity\EmployeeDetails;
use ApplicationBundle\Entity\EmployeeLeaveApplication;
use ApplicationBundle\Entity\EvaluationCategory;
use ApplicationBundle\Entity\HolidayCalendar;
use ApplicationBundle\Entity\HolidayCalendarDates;
use ApplicationBundle\Entity\IncrementPolicy;
use ApplicationBundle\Entity\LeaveSettings;
use ApplicationBundle\Entity\PayrollPolicy;
use ApplicationBundle\Entity\PlanningItem;
use ApplicationBundle\Entity\Questionnaire;
use ApplicationBundle\Entity\ScheduledMeeting;
use ApplicationBundle\Entity\Skill;
use ApplicationBundle\Entity\SysDepartment;
use ApplicationBundle\Entity\SysDepartmentPosition;
use ApplicationBundle\Entity\SysUser;
use ApplicationBundle\Entity\TrainingCourse;
use ApplicationBundle\Entity\WorkHourPolicy;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\Buddybee\Buddybee;
use ApplicationBundle\Modules\HumanResource\HumanResource;
use ApplicationBundle\Modules\Inventory\Inventory;
use ApplicationBundle\Modules\Sales\Client;
use ApplicationBundle\Modules\System\DeleteDocument;
use ApplicationBundle\Modules\System\DocValidation;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Company;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use CompanyGroupBundle\Entity\EntityCountryConsultantRequirements;
use CompanyGroupBundle\Entity\EntityCreateBlog;
use CompanyGroupBundle\Entity\EntityCreateDocument;
use CompanyGroupBundle\Entity\EntityCreateTopic;
use CompanyGroupBundle\Entity\EntityFile;
use CompanyGroupBundle\Entity\EntityInvoice;
use CompanyGroupBundle\Entity\EntitySkill;
use CompanyGroupBundle\Entity\PromoCode;
use CompanyGroupBundle\Modules\ApplicantM;
use Ps\PdfBundle\Annotation\Pdf;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGenerator;
//use Symfony\Bundle\FrameworkBundle\Console\Application;
//use Symfony\Component\Console\Input\ArrayInput;
//use Symfony\Component\Console\Output\NullOutput;
class HumanResourceController extends GenericController implements SessionCheckInterface
{
//temporary for adding session
public function CheckoutPageAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$em_goc = $this->getDoctrine()->getManager('company_group');
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
if ($encData != "") {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
if (isset($encryptedData['invoiceId'])) $invoiceId = $encryptedData['invoiceId'];
}
$session = $request->getSession();
$currencyForGateway = 'eur';
$gatewayInvoice = null;
if ($invoiceId != 0)
$gatewayInvoice = $em->getRepository(EntityInvoice::class)->find($invoiceId);
$paymentGateway = $request->request->get('paymentGateway', 'stripe'); //aamarpay,bkash
$paymentType = $request->request->get('paymentType', 'credit');
$retailerId = $request->request->get('retailerId', 0);
if ($request->query->has('currency'))
$currencyForGateway = $request->query->get('currency');
else
$currencyForGateway = $request->request->get('currency', 'eur');
// {
// if ($request->query->has('meetingSessionId'))
// $id = $request->query->get('meetingSessionId');
// }
$currentUserBalance = 0;
$currentUserCoinBalance = 0;
$gatewayAmount = 0;
$redeemedAmount = 0;
$redeemedSessionCount = 0;
$toConsumeSessionCount = 0;
$invoiceSessionCount = 0;
$payableAmount = 0;
$promoClaimedAmount = 0;
$promoCodeId = 0;
$promoClaimedSession = 0;
$bookingExpireTime = null;
$bookingExpireTs = 0;
$imageBySessionCount = [
0 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
];
if (!$gatewayInvoice) {
if ($request->isMethod('POST')) {
$totalAmount = 0;
$totalSessionCount = 0;
$consumedAmount = 0;
$consumedSessionCount = 0;
$bookedById = 0;
$bookingRefererId = 0;
if ($session->get(UserConstants::USER_ID)) {
$bookedById = $session->get(UserConstants::USER_ID);
$bookingRefererId = 0;
// $toConsumeSessionCount = 1 * $request->request->get('meetingSessionConsumeCount', 0);
$invoiceSessionCount = 1 * ($request->request->get('sessionCount', 0) == '' ? 0 : $request->request->get('sessionCount', 0));
//1st do the necessary
$extMeeting = null;
$meetingSessionId = 0;
if ($request->request->has('purchasePackage')) {
//1. check if any bee card if yes try to claim it , modify current balance then
$beeCodeSerial = $request->request->get('beeCodeSerial', '');
$promoCode = $request->request->get('promoCode', '');
$beeCodePin = $request->request->get('beeCodePin', '');
$userId = $request->request->get('userId', $session->get(UserConstants::USER_ID));
$studentDetails = null;
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
}
if ($beeCodeSerial != '' && $beeCodePin != '') {
$claimData = MiscActions::ClaimBeeCode($em,
[
'claimFlag' => 1,
'pin' => $beeCodePin,
'serial' => $beeCodeSerial,
'userId' => $userId,
]);
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
$claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
}
$redeemedAmount = $claimData['data']['claimedAmount'];
$redeemedSessionCount = $claimData['data']['claimedCoin'];
} else
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
}
$payableAmount = round($request->request->get('payableAmount', 0), 0);
$totalAmountWoDiscount = round($request->request->get('totalAmountWoDiscount', 0), 0);
//now claim and process promocode
if ($promoCode != '') {
$claimData = MiscActions::ClaimPromoCode($em,
[
'claimFlag' => 1,
'promoCode' => $promoCode,
'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
'orderValue' => $totalAmountWoDiscount,
'currency' => $currencyForGateway,
'orderCoin' => $invoiceSessionCount,
'userId' => $userId,
]);
$promoClaimedAmount = 0;
// $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
$promoCodeId = $claimData['promoCodeId'];
$promoClaimedSession = $claimData['data']['claimedCoin'];
}
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$currentUserBalance = $session->get('BUDDYBEE_BALANCE');
$currentUserCoinBalance = $session->get('BUDDYBEE_COIN_BALANCE');
} else {
if ($bookingRefererId == 0)
$bookingRefererId = $session->get(UserConstants::USER_ID);
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
$currentUserCoinBalance = $studentDetails->getSessionCountBalance();
if ($bookingRefererId != $userId && $bookingRefererId != 0) {
$bookingReferer = $em_goc->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
if ($bookingReferer)
if ($bookingReferer->getIsAdmin()) {
$studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
$em_goc->flush();
}
}
}
}
//2. check if any promo code if yes add it to promo discount
//3. check if scheule is still temporarily booked if not return that you cannot book it
Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
// if ($request->request->get('autoAssignMeetingSession', 0) == 1
// && $request->request->get('consultancyScheduleId', 0) != 0
// && $request->request->get('consultancyScheduleId', 0) != ''
// )
{
//1st check if a meeting session exxists with same TS, student id , consultant id
// $scheduledStartTime = new \DateTime('@' . $request->request->get('consultancyScheduleId', ''));
// $extMeeting = $em->getRepository('CompanyGroupBundle:EntityMeetingSession')
// ->findOneBy(
// array(
// 'scheduledTimeTs' => $scheduledStartTime->format('U'),
// 'consultantId' => $request->request->get('consultantId', 0),
// 'studentId' => $request->request->get('studentId', 0),
// 'durationAllowedMin' => $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
// )
// );
// if ($extMeeting) {
// $new = $extMeeting;
// $meetingSessionId = $new->getSessionId();
// $periodMarker = $scheduledStartTime->format('Ym');
//
// }
// else {
//
//
// $scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
// $em,
// $request->request->get('consultantId', 0),
// $request->request->get('studentId', 0),
// $scheduledStartTime->format('U'),
// $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
// 1
// );
//
// if (!$scheduleValidity) {
// $url = $this->generateUrl(
// 'consultant_profile'
// );
// $output = [
//
// 'proceedToCheckout' => 0,
// 'message' => 'Session Booking Expired or not Found!',
// 'errorFlag' => 1,
// 'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
// ];
// return new JsonResponse($output);
// }
// $new = new EntityMeetingSession();
//
// $new->setTopicId($request->request->get('consultancyTopic', 0));
// $new->setConsultantId($request->request->get('consultantId', 0));
// $new->setStudentId($request->request->get('studentId', 0));
// $consultancyTopic = $em_goc->getRepository(EntityCreateTopic::class)->find($request->request->get('consultancyTopic', 0));
// $new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
// $new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
//
//
// $scheduledEndTime = new \DateTime($request->request->get('scheduledTime', ''));
// $scheduledEndTime = $scheduledEndTime->modify('+' . $request->request->get('meetingSessionScheduledDuration', 30) . ' minute');
//
// //$new->setScheduledTime($request->request->get('setScheduledTime'));
// $new->setScheduledTime($scheduledStartTime);
// $new->setDurationAllowedMin($request->request->get('meetingSessionScheduledDuration', 30));
// $new->setDurationLeftMin($request->request->get('meetingSessionScheduledDuration', 30));
// $new->setSessionExpireDate($scheduledEndTime);
// $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
// $new->setEquivalentSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setMeetingSpecificNote($request->request->get('meetingSpecificNote', ''));
//
// $new->setUsableSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setRedeemSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setMeetingActionFlag(0);// no action waiting for meeting
// $new->setScheduledTime($scheduledStartTime);
// $new->setScheduledTimeTs($scheduledStartTime->format('U'));
// $new->setPayableAmount($request->request->get('payableAmount', 0));
// $new->setDueAmount($request->request->get('dueAmount', 0));
// //$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
// //$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
// $new->setPackageName(($request->request->get('packageName', '')));
// $new->setPcakageDetails(($request->request->get('packageData', '')));
// $new->setScheduleId(($request->request->get('consultancyScheduleId', 0)));
// $currentUnixTime = new \DateTime();
// $currentUnixTimeStamp = $currentUnixTime->format('U');
// $studentId = $request->request->get('studentId', 0);
// $consultantId = $request->request->get('consultantId', 0);
// $new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
// $new->setSessionValue(($request->request->get('sessionValue', 0)));
//// $new->setIsPayment(0);
// $new->setConsultantIsPaidFull(0);
//
// if ($bookingExpireTs == 0) {
//
// $bookingExpireTime = new \DateTime();
// $currTime = new \DateTime();
// $currTimeTs = $currTime->format('U');
// $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (24 * 3600);
// if ($bookingExpireTs < $currTimeTs) {
// if ((1 * $scheduledStartTime->format('U')) - $currTimeTs > (12 * 3600))
// $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (2 * 3600);
// else
// $bookingExpireTs = (1 * $scheduledStartTime->format('U'));
// }
//
//// $bookingExpireTs = $bookingExpireTime->format('U');
// }
//
// $new->setPaidSessionCount(0);
// $new->setBookedById($bookedById);
// $new->setBookingRefererId($bookingRefererId);
// $new->setDueSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setExpireIfUnpaidTs($bookingExpireTs);
// $new->setBookingExpireTs($bookingExpireTs);
// $new->setConfirmationExpireTs($bookingExpireTs);
// $new->setIsPaidFull(0);
// $new->setIsExpired(0);
//
//
// $em_goc->persist($new);
// $em_goc->flush();
// $meetingSessionId = $new->getSessionId();
// $periodMarker = $scheduledStartTime->format('Ym');
// MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
// }
}
//4. if after all this stages passed then calcualte gateway payable
if ($request->request->get('isRecharge', 0) == 1) {
if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount - ($redeemedAmount + $promoClaimedAmount);
} else {
if ($toConsumeSessionCount <= $currentUserCoinBalance && $invoiceSessionCount <= $toConsumeSessionCount) {
$payableAmount = 0;
$gatewayAmount = 0;
} else if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount <= ($currentUserBalance + ($redeemedAmount + $promoClaimedAmount)) ? 0 : ($payableAmount - $currentUserBalance - ($redeemedAmount + $promoClaimedAmount));
}
$gatewayAmount = round($gatewayAmount, 2);
$dueAmount = round($request->request->get('dueAmount', $payableAmount), 0);
if ($request->request->has('gatewayProductData'))
$gatewayProductData = $request->request->get('gatewayProductData');
$gatewayProductData = [[
'price_data' => [
'currency' => $currencyForGateway,
'unit_amount' => $gatewayAmount != 0 ? ((100 * $gatewayAmount) / ($invoiceSessionCount != 0 ? $invoiceSessionCount : 1)) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => $invoiceSessionCount != 0 ? $invoiceSessionCount : 1,
]];
$new_invoice = null;
if ($extMeeting) {
$new_invoice = $em->getRepository('CompanyGroupBundle:EntityInvoice')
->findOneBy(
array(
'invoiceType' => $request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE),
'meetingId' => $extMeeting->getSessionId(),
)
);
}
if ($new_invoice) {
} else {
$new_invoice = new EntityInvoice();
$invoiceDate = new \DateTime();
$new_invoice->setInvoiceDate($invoiceDate);
$new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
$new_invoice->setStudentId($userId);
$new_invoice->setBillerId($retailerId == 0 ? 0 : $retailerId);
$new_invoice->setRetailerId($retailerId);
$new_invoice->setBillToId($userId);
$new_invoice->setAmountTransferGateWayHash($paymentGateway);
$new_invoice->setAmountCurrency($currencyForGateway);
$cardIds = $request->request->get('cardIds', []);
$new_invoice->setMeetingId($meetingSessionId);
$new_invoice->setGatewayBillAmount($gatewayAmount);
$new_invoice->setRedeemedAmount($redeemedAmount);
$new_invoice->setPromoDiscountAmount($promoClaimedAmount);
$new_invoice->setPromoCodeId($promoCodeId);
$new_invoice->setRedeemedSessionCount($redeemedSessionCount);
$new_invoice->setPaidAmount($payableAmount - $dueAmount);
$new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
$new_invoice->setDueAmount($dueAmount);
$new_invoice->setInvoiceType($request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
$new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' . microtime(true)));
$new_invoice->setCardIds(json_encode($cardIds));
$new_invoice->setAmountType($request->request->get('amountType', 1));
$new_invoice->setAmount($payableAmount);
$new_invoice->setConsumeAmount($payableAmount);
$new_invoice->setSessionCount($invoiceSessionCount);
$new_invoice->setConsumeSessionCount($toConsumeSessionCount);
$new_invoice->setIsPaidfull(0);
$new_invoice->setIsProcessed(0);
$new_invoice->setApplicantId($userId);
$new_invoice->setBookedById($bookedById);
$new_invoice->setBookingRefererId($bookingRefererId);
$new_invoice->setIsRecharge($request->request->get('isRecharge', 0));
$new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting', 0));
$new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting', 0));
$new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards', 0));
$new_invoice->setIsPayment(0); //0 means receive
$new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
$new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
if ($bookingExpireTs == 0) {
$bookingExpireTime = new \DateTime();
$bookingExpireTime->modify('+30 day');
$bookingExpireTs = $bookingExpireTime->format('U');
}
$new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
$new_invoice->setBookingExpireTs($bookingExpireTs);
$new_invoice->setConfirmationExpireTs($bookingExpireTs);
// $new_invoice->setStatus($request->request->get(0));
$em_goc->persist($new_invoice);
$em_goc->flush();
}
$invoiceId = $new_invoice->getId();
$gatewayInvoice = $new_invoice;
if ($request->request->get('isRecharge', 0) == 1) {
} else {
if ($gatewayAmount <= 0) {
$meetingId = 0;
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em_goc, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$meetingId = $retData['meetingId'];
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'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 ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'proceedToCheckout' => 0,
'redirectUrl' => $url . '/' . $meetingId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => 0,
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
}
return new JsonResponse($output);
// return $this->redirect($url);
} else {
}
// $url = $this->generateUrl(
// 'checkout_page'
// );
//
// return $this->redirect($url."?meetingSessionId=".$new->getSessionId().'&invoiceId='.$invoiceId);
}
}
} else {
$url = $this->generateUrl(
'user_login'
);
$session->set('LAST_REQUEST_URI_BEFORE_LOGIN', $this->generateUrl(
'pricing_plan_page', [
'autoRedirected' => 1
],
UrlGenerator::ABSOLUTE_URL
));
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url,
'clearLs' => 0
];
return new JsonResponse($output);
}
//now proceed to checkout page if the user has lower balance or recharging
//$invoiceDetails = $em->getRepository('CompanyGroupBundle:EntityInvoice')->
}
}
if ($gatewayInvoice) {
$gatewayProductData = json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
if ($gatewayProductData == null) $gatewayProductData = [];
if (empty($gatewayProductData))
$gatewayProductData = [
[
'price_data' => [
'currency' => 'eur',
'unit_amount' => $gatewayAmount != 0 ? (100 * $gatewayAmount) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => 1,
]
];
$productDescStr = '';
$productDescArr = [];
foreach ($gatewayProductData as $gpd) {
$productDescArr[] = $gpd['price_data']['product_data']['name'];
}
$productDescStr = implode(',', $productDescArr);
$paymentGatewayFromInvoice = $gatewayInvoice->getAmountTransferGateWayHash();
// return new JsonResponse(
// [
// 'paymentGateway' => $paymentGatewayFromInvoice,
// 'gateWayData' => $gatewayProductData[0]
// ]
// );
if ($paymentGateway == null) $paymentGatewayFromInvoice = 'stripe';
if ($paymentGatewayFromInvoice == 'stripe' || $paymentGatewayFromInvoice == 'aamarpay' || $paymentGatewayFromInvoice == 'bkash') {
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'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 ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
if ($paymentGatewayFromInvoice == 'stripe') {
$stripe = new \Stripe\Stripe();
\Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
$stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
{
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
$paymentIntent = [
"id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
"object" => "payment_intent",
"amount" => 3000,
"amount_capturable" => 0,
"amount_received" => 0,
"application" => null,
"application_fee_amount" => null,
"canceled_at" => null,
"cancellation_reason" => null,
"capture_method" => "automatic",
"charges" => [
"object" => "list",
"data" => [],
"has_more" => false,
"url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
],
"client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
"confirmation_method" => "automatic",
"created" => 1546523966,
"currency" => $currencyForGateway,
"customer" => null,
"description" => null,
"invoice" => null,
"last_payment_error" => null,
"livemode" => false,
"metadata" => [],
"next_action" => null,
"on_behalf_of" => null,
"payment_method" => null,
"payment_method_options" => [],
"payment_method_types" => [
"card"
],
"receipt_email" => null,
"review" => null,
"setup_future_usage" => null,
"shipping" => null,
"statement_descriptor" => null,
"statement_descriptor_suffix" => null,
"status" => "requires_payment_method",
"transfer_data" => null,
"transfer_group" => null
];
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => $gatewayProductData,
'mode' => 'payment',
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
]);
$output = [
'clientSecret' => $paymentIntent['client_secret'],
'id' => $checkout_session->id,
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
return new JsonResponse($output);
}
if ($paymentGatewayFromInvoice == 'aamarpay') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$url = $sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/request.php' : 'https://secure.aamarpay.com/request.php';
$fields = array(
// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'fail_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
// 'opt_a' => 'Reshad', //optional paramter
// 'opt_b' => 'Akil',
// 'opt_c' => 'Liza',
// 'opt_d' => 'Sohel',
// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
$fields_string = http_build_query($fields);
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
$output = [
//
// 'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
// 'fields'=>$fields,
// 'fields_string'=>$fields_string,
// 'redirectUrl' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1,
'data' => $fields
];
return new JsonResponse($output);
} else if ($paymentGatewayFromInvoice == 'bkash') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/grant');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$id_token = $tokenData['id_token'];
$goToBkashPage = 0;
if ($tokenData['statusCode'] == '0000') {
$auth = $id_token;
$requestbody = array(
"mode" => "0011",
// "payerReference" => "01723888888",
"payerReference" => $invoiceDate->format('U'),
"callbackURL" => $this->generateUrl(
'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
"amount" => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
"currency" => "BDT",
"intent" => "sale",
"merchantInvoiceNumber" => $invoiceId
);
$url = curl_init($baseUrl . '/tokenized/checkout/create');
$requestbodyJson = json_encode($requestbody);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $requestbodyJson);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
// curl_close($url);
// echo $resultdata;
$obj = json_decode($resultdata, true);
$goToBkashPage = 1;
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
$output = [
// 'redirectUrl' => $obj['bkashURL'],
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => $goToBkashPage,
'tokenData' => $tokenData,
'obj' => $obj,
'id_token' => $tokenData['id_token'],
'data' => [
'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
// 'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
]
];
return new JsonResponse($output);
}
// $fields = array(
//
// "mode" => "0011",
// "payerReference" => "01723888888",
// "callbackURL" => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
// "amount" => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),,
// "currency" => "BDT",
// "intent" => "sale",
// "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
//
// );
// $fields = array(
//// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'amount' => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),, //transaction amount
// 'payment_type' => 'VISA', //no need to change
// 'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
// 'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
// 'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
// 'cus_email' => $studentDetails->getEmail(), //customer email address
// 'cus_add1' => $studentDetails->getCurrAddr(), //customer address
// 'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
// 'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
// 'cus_state' => $studentDetails->getCurrAddrState(), //state
// 'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
// 'cus_country' => 'Bangladesh', //country
// 'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
// 'cus_fax' => '', //fax
// 'ship_name' => '', //ship name
// 'ship_add1' => '', //ship address
// 'ship_add2' => '',
// 'ship_city' => '',
// 'ship_state' => '',
// 'ship_postcode' => '',
// 'ship_country' => 'Bangladesh',
// 'desc' => $productDescStr,
// 'success_url' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'fail_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'cancel_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
//// 'opt_a' => 'Reshad', //optional paramter
//// 'opt_b' => 'Akil',
//// 'opt_c' => 'Liza',
//// 'opt_d' => 'Sohel',
//// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
// 'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
//
// ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
//
// $fields_string = http_build_query($fields);
//
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
} else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
$meetingId = 0;
if ($gatewayInvoice->getId() != 0) {
if ($gatewayInvoice->getDueAmount() <= 0) {
$retData = Buddybee::ProcessEntityInvoice($em_goc, $gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$meetingId = $retData['meetingId'];
}
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'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 ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'proceedToCheckout' => 0,
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'redirectUrl' => $url . '/' . $meetingId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'redirectUrl' => $url
];
}
return new JsonResponse($output);
}
}
$output = [
'clientSecret' => 0,
'id' => 0,
'proceedToCheckout' => 0
];
return new JsonResponse($output);
// return $this->render('ApplicationBundle:pages/stripe:checkout.html.twig', array(
// 'page_title' => 'Checkout',
//// 'stripe' => $stripe,
// 'stripe' => null,
//// 'PaymentIntent' => $paymentIntent,
//
//// 'consultantDetail' => $consultantDetail,
//// 'consultantDetails'=> $consultantDetails,
////
//// 'meetingSession' => $meetingSession,
//// 'packageDetails' => json_decode($meetingSession->getPcakageDetails(),true),
//// 'packageName' => json_decode($meetingSession->getPackageName(),true),
//// 'pay' => $payableAmount,
//// 'balance' => $currStudentBal
// ));
}
public function AddEmployeeAction(Request $data, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$skills = $em->getRepository(Skill::class)->findAll();
$session = $data->getSession();
$ownOnly = 0;
// $session=$data->getSession()->get(UserConstants::USER_LOGIN_ID);
$consultancyLevel = HumanResourceConstant::$consultantLevel;
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$banks = $em->getRepository(BankList::class)->findAll();
$bankListObj = [];
foreach ($banks as $bank) {
$bankListObj[$bank->getBankId()] = $bank->getName();
}
if ($id === "my") {
// return $this->redirectToRoute('permission_denied_page');
// return new JsonResponse([$id]);
$id = $session->get(UserConstants::USER_EMPLOYEE_ID);
$ownOnly = 1;
if ($id == 0 || $id == null) {
return $this->redirectToRoute('permission_denied_page');
}
}
if ($id) {
if ($data->isMethod('GET')) {
$Employee = $this->getDoctrine()->getRepository(EmployeeDetails::class)->find($id);
if (!$Employee) {
$this->addFlash(
'error',
'Invalid User ID!'
);
return $this->redirectToRoute('add_employee');
} else {
$EmployeeRes = HumanResource::TwigDataForAddEmployee($em, $id);
$Employee = $EmployeeRes['employee'];
$EmployeeMain = $EmployeeRes['employeeMain'];
$sysUserId = $EmployeeRes['sysId'];
$existingSysUser = $sysUserId ? $em->getRepository('ApplicationBundle:SysUser')->find($sysUserId) : [];
$regionIdsArray = json_decode($EmployeeMain->getRegionIds(), true) ?: [];
$regionLeaderFlagsArray = json_decode($EmployeeMain->getRegionLeaderFlags(), true) ?: [];
$existingRegionAssociations = [];
if (!empty($regionIdsArray)) {
$regionRepo = $this->getDoctrine()->getRepository('ApplicationBundle:Region');
$regions = $regionRepo->findBy(['id' => $regionIdsArray]);
$regionMap = [];
foreach ($regions as $region) {
$regionMap[$region->getId()] = $region;
}
foreach ($regionIdsArray as $index => $regionId) {
if (!isset($regionMap[$regionId])) continue;
$region = $regionMap[$regionId];
$existingRegionAssociations[] = [
'regionLevelId' => $region->getRegionLevelId(),
'regionId' => $region->getId(),
'isLeader' => isset($regionLeaderFlagsArray[$index]) ? (int)$regionLeaderFlagsArray[$index] : 0
];
}
}
$TwigData = HumanResource::TwigDataForAddEmployee($em, 0);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:add_employee.html.twig',
array(
'page_title' => 'Update Employee',
'ownOnly' => $ownOnly,
'branches' => $TwigData['branches'],
'bankListObj' => $bankListObj,
'heads' => Accounts::getLedgerHeadsWithParents($em),
'departments' => $TwigData['departments'],
'departmentPositions' => $TwigData['departmentPositions'],
'regions' => $TwigData['regions'],
'supervisors' => $TwigData['supervisors'],
'sysUsers' => $TwigData['sysUser'],
'EmploymentStatus' => $TwigData['EmploymentStatus'],
'sex' => $TwigData['sex'],
'BloodGroup' => $TwigData['BloodGroup'],
'days' => $TwigData['days'],
'employeeMain' => $EmployeeMain,
'employee' => $Employee,
'skills' => $skills,
'existingSysUser' => $existingSysUser,
'id' => $id,
'default_route' => $EmployeeRes['defaultRoute'],
'user_type' => $EmployeeRes['userType'],
'user_type_data' => HumanResourceConstant::$userType,
'AccountTypes' => $TwigData['AccountType'],
'weekends' => explode(',', $Employee->getWeeklyHoliday()),
'consultancyLevel' => $consultancyLevel,
'module_data_array' => $TwigData['module_data_array'],
'HasUpdateMode' => true,
'brand_list' => Inventory::GetBrandList($em, $this->getLoggedUserCompanyId($data)),
'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
'leaveData' => $EmployeeRes['leaveData'],
'positions' => $EmployeeRes['positions'],
'existing_region_associations' => $existingRegionAssociations
)
);
}
} else {
$approveHash = $data->request->get('approvalHash');
$loginId = $data->getSession()->get(UserConstants::USER_LOGIN_ID);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
$image = $data->files->get('img');
$profileImage = $this->uploadImage($image, $data);
$path = '';
if ($isSignatureOk) {
$CompanyId = $this->getLoggedUserCompanyId($data);
$isSuccess = HumanResource::StoreDataForAddEmployee($em, $data, $id, $CompanyId, $profileImage);
if ($isSuccess) {
// $EmployeeDetails = $em->getRepository(EmployeeDetails::class)->find($id);
$Employee = $em->getRepository(Employee::class)->find($id);
$EmployeeDetails = $em->getRepository(EmployeeDetails::class)->findOneBy(
array(
'id' => $id
)
);
$sysUserId = $isSuccess->getUserId();
$message = $this->get('user_module')->updateUser(
$sysUserId,
$data->request->get('firstname') . " " . $data->request->get('lastname'),
$data->request->has('email') ? $data->request->get('email') : '_UNCHANGED_',
$data->request->has('username') ? $data->request->get('username') : '_UNCHANGED_',
$data->request->get('password'),
1,
$data->request->get('user_type', '_UNCHANGED_'),
$data->request->get('supervisor'),
$data->request->get('default_route'),
$data->request->get('branch'),
$data->request->has('access_module') ? 1 : 0,
$data->getSession()->get(UserConstants::USER_LOGIN_ID),
$data->request->get('global_user_id', null),
$profileImage,
$upl_dir
);
if (isset($message[0]) && $message[0] === 'success') {
if ($systemType == '_CENTRAL_') {
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = $message[3]->getUserAppId();
$userIds = $message[3]->getUserId();
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds !== '_UNSET_')
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
// if($debugCount>0)
// continue;
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
if ($userIds !== '_UNSET_')
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage(); //<-- Path could be relative
// $output=$file;
if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
// $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = $output;
} else {
// unlink($this->container->getParameter('kernel.root_dir') . '/../web'. $centralUser->getImage());
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array(// 'file'=>$output
);
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($user->{$getter}() instanceof \DateTime) {
$ggtd = $user->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $user->{$getter}();
}
$employeeGetters = array(
'getFirstname', 'getLastname', 'getImage', 'getIsImgLegal', 'getNid', 'getDob', 'getSex', 'getReligion', 'getFather',
'getMother', 'getSpouse', 'getChild1', 'getChild2', 'getBlood', 'getPhone', 'getOfficailPhone', 'getCurrAddr',
'getCurrAddrLat', 'getCurrAddrLng', 'getPermAddr', 'getEmmContact', 'getUsername', 'getEmail', 'getPassword',
'getUserId', 'getJoiningDate', 'getEmpValidTill', 'getEmpStatus', 'getEmpType', 'getEmpCode', 'getEmpLabel', 'getTin',
'getTinValidTill', 'getMedIns', 'getMedInsValidTill', 'getDocs', 'getNocApproval', 'getInst1', 'getYr1', 'getDur1',
'getInst2', 'getYr2', 'getDur2', 'getInst3', 'getYr3', 'getDur3', 'getEinst1', 'getEyr1', 'getEdeg1', 'getEinst2',
'getEyr2', 'getEdeg2', 'getEinst3', 'getEyr3', 'getEdeg3', 'getBankAcc', 'getBankAccType', 'getBankAccValidFrom',
'getBankAccValidTo', 'getRoutingCode', 'getSwiftCode', 'getEar1', 'getEar2', 'getEar3', 'getEar4', 'getEar5', 'getEar6',
'getEart', 'getDed1', 'getDed2', 'getDed3', 'getDed4', 'getDedt', 'getPayable', 'getHandCash', 'getBankTransfer',
'getSecDep', 'getSecDepSpan', 'getSecDepRemMon', 'getSecDepRemAmount', 'getSlQty', 'getSlTkn', 'getSlFreq', 'getMlQty',
'getMlTkn', 'getMlFreq', 'getElQty', 'getElTkn', 'getElFreq', 'getClQty', 'getClTkn', 'getClFreq', 'getLevt',
'getWeeklyHoliday', 'getFiles', 'getSupervisor', 'getDept', 'getDesg', 'getBranch', 'getDivision', 'getCreatedAt',
'getUpdatedAt', 'getEmployeeLevel', 'getSkill', 'getProbationaryPeriod', 'getDocBookedFlag', 'getTimeStampOfForm',
'getIsConsultant', 'getConsultantLevel', 'getApplicationText', 'getCurrentEmployment', 'getEmergencyContactNumber',
'getPostalCode', 'getCountry', 'getEducationData', 'getWorkExperienceData', 'getCertificateData', 'getLanguagesData',
'getBeneficiaryName', 'getBankName', 'getBranchName', 'getClockedIn'
);
foreach ($employeeGetters as $getter) {
if (!method_exists($EmployeeDetails, $getter)) continue;
try {
$value = $EmployeeDetails->{$getter}();
if ($value instanceof \DateTime) {
$userDataSingle[$getter] = $value->format('Y-m-d');
} elseif (is_object($value)) {
continue; // skip non-scalar objects
} else {
$userDataSingle[$getter] = $value;
}
} catch (\Exception $e) {
continue;
}
}
// $userDataSingle['getNid']=$EmployeeDetails->getNid();
// $userDataSingle['getDob']=$EmployeeDetails->getDob();
// $userDataSingle['getSex']=$EmployeeDetails->getSex();
// $userDataSingle['getCurrAddr'] = $EmployeeDetails->getCurrAddr();
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend
);
// if ($skipSend == 0)
{
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HTTPHEADER => array(// "Accept: multipart/form-data",
),
// CURLOPT_USERAGENT => 'InnoPM',
// CURLOPT_POSTFIELDS => array(
// 'userData'=>json_encode($userData),
// 'userFiles'=>$userFiles
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = json_decode($retData, true);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData']))
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataListByAppId[$app_id]['dbName'],
$gocDataListByAppId[$app_id]['dbUser'],
$gocDataListByAppId[$app_id]['dbPass'],
$gocDataListByAppId[$app_id]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
foreach ($usrList as $sys_id => $globaldata) {
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->flush();
}
}
}
}
$debugCount++;
}
}
// return new JsonResponse($retDataDebug);
}
} else {
$errorMsg = $message['message'] ?? 'Unknown error occurred.';
$this->addFlash('error', $errorMsg);
return $this->redirectToRoute('add_employee');
}
// $SysUserRepo = $em->getRepository(SysUser::class);
// $SysUser = $SysUserRepo->findOneBy(array(
// 'email' => $data->request->get('email')
// ));
// $isSuccess->setUserId($SysUser->getUserId());
// $em->persist($isSuccess);
// $em->flush();
// $companyData = $message[2];
// $emailmessage = (new \Swift_Message('Update to Entity'))
// ->setFrom('registration@entity.innobd.com')
// ->setTo($data->request->get('email'))
// ->setBody(
// $this->renderView(
// 'ApplicationBundle:email/user:registration.html.twig',
// array(
// 'name' => $data->request->get('name'),
// 'companyData' => $companyData,
// 'userName' => $data->request->get('email'),
// 'password' => $data->request->get('password'),
// )
// ),
// 'text/html'
// );
// $this->get('mailer')->send($emailmessage);
$userType = $data->getSession()->get(UserConstants::USER_TYPE);
$redirctUrl = $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
if ($userType == 1) {
$redirctUrl = $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
} else {
$redirctUrl = $this->generateUrl('edit_employee', [], UrlGenerator::ABSOLUTE_URL) . '/my';
}
return new JsonResponse(array(
'employeeId' => $Employee->getEmployeeId(),
'redirectToNew' => 0,
'success' => true,
'redirectUrl' => $redirctUrl,
));
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('add_employee');
}
}
} else {
if ($data->isMethod('GET')) {
$TwigData = HumanResource::TwigDataForAddEmployee($em, 0);
$existingRegionAssociations = [];
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:add_employee.html.twig',
array(
'page_title' => 'Add Employee',
'ownOnly' => $ownOnly,
'heads' => Accounts::getLedgerHeadsWithParents($em),
'bankListObj' => $bankListObj,
'branches' => $TwigData['branches'],
'departments' => $TwigData['departments'],
'departmentPositions' => $TwigData['departmentPositions'],
'regions' => $TwigData['regions'],
'supervisors' => $TwigData['supervisors'],
'sysUsers' => $TwigData['sysUser'],
'EmploymentStatus' => $TwigData['EmploymentStatus'],
'sex' => $TwigData['sex'],
'skills' => $skills,
'consultancyLevel' => $consultancyLevel,
'existingSysUser' => null,
'BloodGroup' => $TwigData['BloodGroup'],
'days' => $TwigData['days'],
'AccountTypes' => $TwigData['AccountType'],
'module_data_array' => $TwigData['module_data_array'],
'user_type_data' => HumanResourceConstant::$userType,
'HasUpdateMode' => false,
'brand_list' => Inventory::GetBrandList($em, $this->getLoggedUserCompanyId($data)),
'employee' => [],
'positions' => $TwigData['positions'],
'existing_region_associations' => $existingRegionAssociations ?? [],
'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
)
);
} else {
$approveHash = $data->request->get('approvalHash');
$loginId = $data->getSession()->get(UserConstants::USER_LOGIN_ID);
$CompanyId = $this->getLoggedUserCompanyId($data);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
$isSuccess = HumanResource::StoreDataForAddEmployee($em, $data, false, $CompanyId);
$Employee = $isSuccess;
$EmployeeDetails = $em->getRepository(EmployeeDetails::class)->findOneBy(
array(
'id' => $id
)
);
$isUserExist = $em->getRepository(EmployeeDetails::class)
->findOneBy(array('email' => $data->request->get('email')));
if ($isSignatureOk) {
if ($isUserExist) {
if ($isSuccess) {
$message = $this->get('user_module')->addNewUser(
$data->request->get('firstname') . " " . $data->request->get('lastname'),
$data->request->get('email'),
$data->request->get('username'),
$data->request->get('password'),
$data->request->get('desg'),
$this->getLoggedUserLoginId($data),
$data->request->get('company'),
$data->request->get('user_type'),
$data->request->get('companyIdList'),
$data->request->get('branch'),
$data->request->get('supervisor'),
$data->request->get('default_route'),
$data->request->has('access_module') ? 1 : 0,
"",
$data->files->get('img'), '', 0, 0,
'', '', '', 0, '', 0, $data->request->get('global_user_id', null)
);
if ($message[0] == 'success') {
$Employee->setUserId($message[3]->getUserId());
$em->persist($Employee);
if ($EmployeeDetails) {
$EmployeeDetails->setUserId($message[3]->getUserId());
$em->persist($EmployeeDetails);
}
$em->flush();
if ($systemType == '_CENTRAL_') {
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = $message[2]->getAppId();
$userIds = $message[3]->getUserId();
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds !== '_UNSET_')
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
if ($userIds !== '_UNSET_')
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage();
if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = $output;
} else {
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array();
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($user->{$getter}() instanceof \DateTime) {
$ggtd = $user->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $user->{$getter}();
}
$employeeGetters = array(
'getFirstname', 'getLastname', 'getImage', 'getIsImgLegal', 'getNid', 'getDob', 'getSex', 'getReligion', 'getFather',
'getMother', 'getSpouse', 'getChild1', 'getChild2', 'getBlood', 'getPhone', 'getOfficailPhone', 'getCurrAddr',
'getCurrAddrLat', 'getCurrAddrLng', 'getPermAddr', 'getEmmContact', 'getUsername', 'getEmail', 'getPassword',
'getUserId', 'getJoiningDate', 'getEmpValidTill', 'getEmpStatus', 'getEmpType', 'getEmpCode', 'getEmpLabel', 'getTin',
'getTinValidTill', 'getMedIns', 'getMedInsValidTill', 'getDocs', 'getNocApproval', 'getInst1', 'getYr1', 'getDur1',
'getInst2', 'getYr2', 'getDur2', 'getInst3', 'getYr3', 'getDur3', 'getEinst1', 'getEyr1', 'getEdeg1', 'getEinst2',
'getEyr2', 'getEdeg2', 'getEinst3', 'getEyr3', 'getEdeg3', 'getBankAcc', 'getBankAccType', 'getBankAccValidFrom',
'getBankAccValidTo', 'getRoutingCode', 'getSwiftCode', 'getEar1', 'getEar2', 'getEar3', 'getEar4', 'getEar5', 'getEar6',
'getEart', 'getDed1', 'getDed2', 'getDed3', 'getDed4', 'getDedt', 'getPayable', 'getHandCash', 'getBankTransfer',
'getSecDep', 'getSecDepSpan', 'getSecDepRemMon', 'getSecDepRemAmount', 'getSlQty', 'getSlTkn', 'getSlFreq', 'getMlQty',
'getMlTkn', 'getMlFreq', 'getElQty', 'getElTkn', 'getElFreq', 'getClQty', 'getClTkn', 'getClFreq', 'getLevt',
'getWeeklyHoliday', 'getFiles', 'getSupervisor', 'getDept', 'getDesg', 'getBranch', 'getDivision', 'getCreatedAt',
'getUpdatedAt', 'getEmployeeLevel', 'getSkill', 'getProbationaryPeriod', 'getDocBookedFlag', 'getTimeStampOfForm',
'getIsConsultant', 'getConsultantLevel', 'getApplicationText', 'getCurrentEmployment', 'getEmergencyContactNumber',
'getPostalCode', 'getCountry', 'getEducationData', 'getWorkExperienceData', 'getCertificateData', 'getLanguagesData',
'getBeneficiaryName', 'getBankName', 'getBranchName', 'getClockedIn'
);
foreach ($employeeGetters as $getter) {
if (!method_exists($EmployeeDetails, $getter)) continue;
try {
$value = $EmployeeDetails->{$getter}();
if ($value instanceof \DateTime) {
$userDataSingle[$getter] = $value->format('Y-m-d');
} elseif (is_object($value)) {
continue; // skip non-scalar objects
} else {
$userDataSingle[$getter] = $value;
}
} catch (\Exception $e) {
continue;
}
}
// $userDataSingle['getNid']=$Employee->getNid();
// $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend
);
{
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HTTPHEADER => array(// "Accept: multipart/form-data",
),
// CURLOPT_USERAGENT => 'InnoPM',
// CURLOPT_POSTFIELDS => array(
// 'userData'=>json_encode($userData),
// 'userFiles'=>$userFiles
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$response = [];
if ($errData) {
$response['status'] = 'error';
$response['message'] = 'cURL Error: ' . $errData;
} else {
$retDataObj = json_decode($retData, true);
if (!$retDataObj) {
$response['status'] = 'error';
$response['message'] = 'Invalid response from central server';
$response['raw_response'] = $retData;
} else {
$response['status'] = 'success';
$response['data'] = $retDataObj;
}
}
// Return JSON response
// return new JsonResponse($response);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData']))
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataListByAppId[$app_id]['dbName'],
$gocDataListByAppId[$app_id]['dbUser'],
$gocDataListByAppId[$app_id]['dbPass'],
$gocDataListByAppId[$app_id]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
foreach ($usrList as $sys_id => $globaldata) {
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->persist($user);
$em->flush();
}
}
}
}
$debugCount++;
}
}
// return new JsonResponse($retDataDebug);
}
} else if ($message[0] == 'error') {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
}
// if($message[0]=='success'){
// $SysUserRepo = $em->getRepository('ApplicationBundle:SysUser');
// $SysUser = $SysUserRepo->findOneBy([
// 'email' => $data->request->get('email')
// ]);
//
// if ($SysUser === null) {
// throw new \Exception("User with email " . $data->request->get('email') . " not found.");
// }
//
// $isSuccess->setUserId($SysUser->getUserId());
// $em->persist($isSuccess);
// $em->flush();
// }
$companyData = $message[2];
if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/user:registration.html.twig';
$bodyData = array(
'name' => $data->request->get('name'),
'companyData' => $companyData,
'userName' => $data->request->get('username'),
'password' => $data->request->get('password'),
);
$attachments = [];
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $data->request->get('email'),
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' . $companyData->getName(),
'fileName' => '',
'attachments' => $attachments,
'toAddress' => $data->request->get('email'),
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $data->request->get('company'),
'companyImagePath' => $companyData->getImage()
));
}
}
$this->addFlash(
'success',
'New Employee Successfully Added!'
);
$userType = $data->getSession()->get(UserConstants::USER_TYPE);
$redirctUrl = $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
if ($userType == 1) {
$redirctUrl = $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
} else {
$redirctUrl = $this->generateUrl('add_employee', [], UrlGenerator::ABSOLUTE_URL);
}
return new JsonResponse(array(
'employeeId' => $Employee->getEmployeeId(),
'redirectToNew' => 1,
'success' => true,
'redirectUrl' => $redirctUrl,
));
// return $this->redirectToRoute('add_employee');
} else {
// $requiredFields = [
// 'email', 'username', 'password', 'firstname', 'lastname', 'nid', 'dob',
// 'sex', 'blood', 'phone', 'perm_addr', 'dept', 'desg', 'branch',
// 'emp_type', 'tin'
// ];
//
// $missingFields = [];
//
// foreach ($requiredFields as $field) {
// if (!$data->request->get($field)) {
// $missingFields[] = $field;
// }
// }
// if (!empty($missingFields)) {
// $this->addFlash('error', 'Missing fields: ' . implode(', ', $missingFields));
// return $this->redirectToRoute('add_employee');
// }
// $password = $data->request->get('password');
// $passwordPattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/';
// if (!preg_match($passwordPattern, $password)) {
// $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));
// return $this->redirectToRoute('add_employee');
// }
$CompanyId = $this->getLoggedUserCompanyId($data);
$isSuccess = HumanResource::StoreDataForAddEmployee($em, $data, false, $CompanyId);
if ($isSuccess) {
if ($data->request->has('send_appointment')) {
$email = $data->request->get('email');
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/general:appointment_letter_test.html.twig';
$bodyData = [];
$attachments = [];
$forwardToMailAddress = $email;
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Appointment Letter',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
));
}
// Mailer function
if ($data->get("send_mail") && empty($data->get('sys_user'))) {
$message = $this->get('user_module')->addNewUser(
$data->request->get('firstname') . " " . $data->request->get('lastname'),
$data->request->get('email'),
$data->request->get('username'),
$data->request->get('password'),
$data->request->get('desg'),
$this->getLoggedUserLoginId($data),
$data->request->get('company'),
$data->request->get('user_type'),
$data->request->get('companyIdList'),
$data->request->get('branch'),
$data->request->get('supervisor'),
$data->request->get('default_route'),
$data->request->has('access_module') ? 1 : 0
);
if ($message[0] == 'success') {
if ($systemType == '_CENTRAL_') {
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = $message[2]->getAppId();
$userIds = $message[3]->getUserId();
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds !== '_UNSET_')
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
if ($userIds !== '_UNSET_')
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage();
if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = $output;
} else {
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array();
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($user->{$getter}() instanceof \DateTime) {
$ggtd = $user->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $user->{$getter}();
}
// $userDataSingle['getNid']=$Employee->getNid();
// $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend
);
{
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HTTPHEADER => array(// "Accept: multipart/form-data",
),
// CURLOPT_USERAGENT => 'InnoPM',
// CURLOPT_POSTFIELDS => array(
// 'userData'=>json_encode($userData),
// 'userFiles'=>$userFiles
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$response = [];
if ($errData) {
$response['status'] = 'error';
$response['message'] = 'cURL Error: ' . $errData;
} else {
$retDataObj = json_decode($retData, true);
if (!$retDataObj) {
$response['status'] = 'error';
$response['message'] = 'Invalid response from central server';
$response['raw_response'] = $retData;
} else {
$response['status'] = 'success';
$response['data'] = $retDataObj;
}
}
// Return JSON response
// return new JsonResponse($response);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData']))
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataListByAppId[$app_id]['dbName'],
$gocDataListByAppId[$app_id]['dbUser'],
$gocDataListByAppId[$app_id]['dbPass'],
$gocDataListByAppId[$app_id]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
foreach ($usrList as $sys_id => $globaldata) {
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->persist($user);
$em->flush();
}
}
}
}
$debugCount++;
}
}
// return new JsonResponse($retDataDebug);
}
}
$SysUserRepo = $em->getRepository(SysUser::class);
$SysUser = $SysUserRepo->findOneBy(array(
'email' => $data->request->get('email')
));
$isSuccess->setUserId($SysUser->getUserId());
$em->persist($isSuccess);
$em->flush();
$companyData = $message[2];
if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/user:registration.html.twig';
$bodyData = array(
'name' => $data->request->get('name'),
'companyData' => $companyData,
'userName' => $data->request->get('username'),
'password' => $data->request->get('password'),
);
$attachments = [];
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $data->request->get('email'),
'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' . $companyData->getName(),
'fileName' => '',
'attachments' => $attachments,
'toAddress' => $data->request->get('email'),
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Y41dh8g0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'fromAddress'=>'sales@entity.innobd.com',
// 'userName'=>'sales@entity.innobd.com',
// 'password'=>'Y41dh8g0112',
// 'smtpServer'=>'smtp.hostinger.com',
// 'smtpPort'=>587,
// 'emailBody'=>$bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $data->request->get('company'),
'companyImagePath' => $companyData->getImage()
));
// $emailmessage = (new \Swift_Message('Registration to Entity'))
// ->setFrom('registration@entity.innobd.com')
// ->setTo($data->request->get('email'))
// ->setBody(
// $this->renderView(
// 'ApplicationBundle:email/user:registration.html.twig',
// array(
// 'name' => $data->request->get('name'),
// 'companyData' => $companyData,
// 'userName' => $data->request->get('email'),
// 'password' => $data->request->get('password'),
// )
// ),
// 'text/html'
// );
// $this->get('mailer')->send($emailmessage);
}
}
// End Mailer function
$this->addFlash(
'success',
'New Employee Successfully Added!'
);
$userType = HumanResourceConstant::$userType;
if ($userType == 1) {
return $this->redirectToRoute('employee_list');
} else {
return $this->redirectToRoute('edit_employee');
}
} else {
$this->addFlash(
'error',
'Something Went Wrong!'
);
$userType = HumanResourceConstant::$userType;
if ($userType == 1) {
return $this->redirectToRoute('employee_list');
} else {
return $this->redirectToRoute('edit_employee');
}
}
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('add_employee');
}
}
}
}
public function AddNewEmployeeAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$approveHash = $request->request->get('approvalHash');
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$CompanyId = $this->getLoggedUserCompanyId($request);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
$employee = HumanResource::StoreDataForAddEmployee($em, $request, false, $CompanyId);
$isUserExist = $em->getRepository(EmployeeDetails::class);
if ($isSignatureOk) {
if ($isUserExist) {
if ($employee) {
$message = $this->get('user_module')->addNewUser(
$request->request->get('firstname') . " " . $request->request->get('lastname'),
$request->request->get('email'),
$request->request->get('username'),
$request->request->get('password'),
$request->request->get('desg'),
$request->getLoggedUserLoginId($request),
$request->request->get('company'),
$request->request->get('user_type'),
$request->request->get('companyIdList'),
$request->request->get('branch'),
$request->request->get('supervisor'),
$request->request->get('default_route'),
$request->request->has('access_module') ? 1 : 0
);
if ($message[0] == 'success') {
$employee->setUserId($message[3]->getUserId());
$em->flush();
if ($systemType == '_CENTRAL_') {
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = $message[2]->getAppId();
$userIds = $message[3]->getUserId();
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds !== '_UNSET_')
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
if ($userIds !== '_UNSET_')
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage();
if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = $output;
} else {
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array();
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($user->{$getter}() instanceof \DateTime) {
$ggtd = $user->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $user->{$getter}();
}
// $userDataSingle['getNid']=$Employee->getNid();
// $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend
);
{
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HTTPHEADER => array(// "Accept: multipart/form-data",
),
// CURLOPT_USERAGENT => 'InnoPM',
// CURLOPT_POSTFIELDS => array(
// 'userData'=>json_encode($userData),
// 'userFiles'=>$userFiles
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$response = [];
if ($errData) {
$response['status'] = 'error';
$response['message'] = 'cURL Error: ' . $errData;
} else {
$retDataObj = json_decode($retData, true);
if (!$retDataObj) {
$response['status'] = 'error';
$response['message'] = 'Invalid response from central server';
$response['raw_response'] = $retData;
} else {
$response['status'] = 'success';
$response['data'] = $retDataObj;
}
}
// Return JSON response
// return new JsonResponse($response);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData']))
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataListByAppId[$app_id]['dbName'],
$gocDataListByAppId[$app_id]['dbUser'],
$gocDataListByAppId[$app_id]['dbPass'],
$gocDataListByAppId[$app_id]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
foreach ($usrList as $sys_id => $globaldata) {
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->persist($user);
$em->flush();
}
}
}
}
$debugCount++;
}
}
// return new JsonResponse($retDataDebug);
}
}
// if($message[0]=='success'){
// $SysUserRepo = $em->getRepository('ApplicationBundle:SysUser');
// $SysUser = $SysUserRepo->findOneBy([
// 'email' => $data->request->get('email')
// ]);
//
// if ($SysUser === null) {
// throw new \Exception("User with email " . $data->request->get('email') . " not found.");
// }
//
// $isSuccess->setUserId($SysUser->getUserId());
// $em->persist($isSuccess);
// $em->flush();
// }
$companyData = $message[2];
if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/user:registration.html.twig';
$bodyData = array(
'name' => $request->request->get('name'),
'companyData' => $companyData,
'userName' => $request->request->get('username'),
'password' => $request->request->get('password'),
);
$attachments = [];
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $request->request->get('email'),
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' . $companyData->getName(),
'fileName' => '',
'attachments' => $attachments,
'toAddress' => $request->request->get('email'),
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $request->request->get('company'),
'companyImagePath' => $companyData->getImage()
));
}
}
$this->addFlash(
'success',
'New Employee Successfully Added!'
);
return $this->redirectToRoute('add_employee');
} else {
// $requiredFields = [
// 'email', 'username', 'password', 'firstname', 'lastname', 'nid', 'dob',
// 'sex', 'blood', 'phone', 'perm_addr', 'dept', 'desg', 'branch',
// 'emp_type', 'tin'
// ];
//
// $missingFields = [];
//
// foreach ($requiredFields as $field) {
// if (!$data->request->get($field)) {
// $missingFields[] = $field;
// }
// }
// if (!empty($missingFields)) {
// $this->addFlash('error', 'Missing fields: ' . implode(', ', $missingFields));
// return $this->redirectToRoute('add_employee');
// }
// $password = $data->request->get('password');
// $passwordPattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/';
// if (!preg_match($passwordPattern, $password)) {
// $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));
// return $this->redirectToRoute('add_employee');
// }
$CompanyId = $this->getLoggedUserCompanyId($request);
$isSuccess = HumanResource::StoreDataForAddEmployee($em, $request, false, $CompanyId);
if ($isSuccess) {
if ($request->request->has('send_appointment')) {
$email = $request->request->get('email');
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/general:appointment_letter_test.html.twig';
$bodyData = [];
$attachments = [];
$forwardToMailAddress = $email;
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Appointment Letter',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
));
}
// Mailer function
if ($request->get("send_mail") && empty($request->get('sys_user'))) {
$message = $this->get('user_module')->addNewUser(
$request->request->get('firstname') . " " . $request->request->get('lastname'),
$request->request->get('email'),
$request->request->get('username'),
$request->request->get('password'),
$request->request->get('desg'),
$request->getLoggedUserLoginId($request),
$request->request->get('company'),
$request->request->get('user_type'),
$request->request->get('companyIdList'),
$request->request->get('branch'),
$request->request->get('supervisor'),
$request->request->get('default_route'),
$request->request->has('access_module') ? 1 : 0
);
if ($message[0] == 'success') {
if ($systemType == '_CENTRAL_') {
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = $message[2]->getAppId();
$userIds = $message[3]->getUserId();
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds !== '_UNSET_')
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
if ($userIds !== '_UNSET_')
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage();
if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = $output;
} else {
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array();
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($user->{$getter}() instanceof \DateTime) {
$ggtd = $user->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $user->{$getter}();
}
// $userDataSingle['getNid']=$Employee->getNid();
// $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend
);
{
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HTTPHEADER => array(// "Accept: multipart/form-data",
),
// CURLOPT_USERAGENT => 'InnoPM',
// CURLOPT_POSTFIELDS => array(
// 'userData'=>json_encode($userData),
// 'userFiles'=>$userFiles
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$response = [];
if ($errData) {
$response['status'] = 'error';
$response['message'] = 'cURL Error: ' . $errData;
} else {
$retDataObj = json_decode($retData, true);
if (!$retDataObj) {
$response['status'] = 'error';
$response['message'] = 'Invalid response from central server';
$response['raw_response'] = $retData;
} else {
$response['status'] = 'success';
$response['data'] = $retDataObj;
}
}
// Return JSON response
// return new JsonResponse($response);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData']))
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataListByAppId[$app_id]['dbName'],
$gocDataListByAppId[$app_id]['dbUser'],
$gocDataListByAppId[$app_id]['dbPass'],
$gocDataListByAppId[$app_id]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
foreach ($usrList as $sys_id => $globaldata) {
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->persist($user);
$em->flush();
}
}
}
}
$debugCount++;
}
}
// return new JsonResponse($retDataDebug);
}
}
$SysUserRepo = $em->getRepository(SysUser::class);
$SysUser = $SysUserRepo->findOneBy(array(
'email' => $request->request->get('email')
));
$isSuccess->setUserId($SysUser->getUserId());
$em->persist($isSuccess);
$em->flush();
$companyData = $message[2];
if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/user:registration.html.twig';
$bodyData = array(
'name' => $request->request->get('name'),
'companyData' => $companyData,
'userName' => $request->request->get('username'),
'password' => $request->request->get('password'),
);
$attachments = [];
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $request->request->get('email'),
'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' . $companyData->getName(),
'fileName' => '',
'attachments' => $attachments,
'toAddress' => $request->request->get('email'),
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Y41dh8g0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'fromAddress'=>'sales@entity.innobd.com',
// 'userName'=>'sales@entity.innobd.com',
// 'password'=>'Y41dh8g0112',
// 'smtpServer'=>'smtp.hostinger.com',
// 'smtpPort'=>587,
// 'emailBody'=>$bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $request->request->get('company'),
'companyImagePath' => $companyData->getImage()
));
// $emailmessage = (new \Swift_Message('Registration to Entity'))
// ->setFrom('registration@entity.innobd.com')
// ->setTo($data->request->get('email'))
// ->setBody(
// $this->renderView(
// 'ApplicationBundle:email/user:registration.html.twig',
// array(
// 'name' => $data->request->get('name'),
// 'companyData' => $companyData,
// 'userName' => $data->request->get('email'),
// 'password' => $data->request->get('password'),
// )
// ),
// 'text/html'
// );
// $this->get('mailer')->send($emailmessage);
}
}
// End Mailer function
$this->addFlash(
'success',
'New Employee Successfully Added!'
);
return $this->redirectToRoute('employee_list');
} else {
$this->addFlash(
'error',
'Something Went Wrong!'
);
return $this->redirectToRoute('add_employee');
}
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('add_employee');
}
}
public function UpdateEmployeeAction(Request $request, $id)
{
}
private function uploadImage($image, $request)
{
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
$profileImage = '';
if ($image != null) {
$fileName = $request->request->get('firstname') . '.' . $request->request->get('global_user_id') . '.' . $image->guessExtension();
$path = $fileName;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$image->move($upl_dir, $path);
$profileImage = 'uploads/Users/' . $path;
}
return $profileImage;
}
public function OnboardEmployeeAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$email = $request->request->get('email');
$applicantId = $request->request->get('applicant_id');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$companyId = $session->get('userCompanyId');
$appId = $session->get('userAppId');
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/get_applicant_data_central';
$applicantFiles = [
'email' => $email,
'applicantId' => $applicantId
];
$entityToken = $em->getRepository('ApplicationBundle:EntityTokenStorage')
->findOneBy(['userId' => $applicantId]);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array(),
CURLOPT_POSTFIELDS => $applicantFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = json_decode($retData, true);
if (!isset($retDataObj['status']) || $retDataObj['status'] !== 'success') {
return new JsonResponse([
'status' => 'error',
'message' => 'Failed to get applicant data from central server',
'response' => $retDataObj
]);
}
$centralData = $retDataObj['centralData'];
$em = $this->getDoctrine()->getManager();
$sysUser = new SysUser();
$sysUser->setGlobalId($centralData['globalId'] ?? '');
$sysUser->setUsername($centralData['username'] ?? '');
$sysUser->setEmail($centralData['email'] ?? '');
$sysUser->setName($centralData['firstname'] ?? '');
$sysUser->setUserType(1);
$sysUser->setUserAppId($appId);
$sysUser->setUserCompanyId($companyId);
$sysUser->setStatus(1);
$sysUser->setDefaultRoute('sales_dashboard');
$em->persist($sysUser);
$em->flush();
$employee = $em->getRepository('ApplicationBundle:Employee')
->findOneBy(
array(
'userId' => $sysUser->getUserId(),
)
);
if (!$employee) {
$employee = new Employee();
if ($sysUser->getUserId()) {
$employee->setEmail($sysUser->getEmail());
$employee->setFirstName($sysUser->getUsername());
$employee->setLastName($sysUser->getName());
$employee->setCompanyId($sysUser->getUserCompanyId());
$employee->setStatus(1);
$employee->setUserId($sysUser->getUserId());
$em->persist($employee);
$em->flush();
} else {
return new JsonResponse([
'status' => 'error',
'message' => 'Missing employee data',
]);
}
}
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')
->findOneBy([
'userId' => $sysUser->getUserId(),
]);
if (!$employeeDetails) {
$employeeDetails = new EmployeeDetails();
if ($sysUser->getUserId() && $employee->getEmployeeId()) {
$employeeDetails->setId($employee->getEmployeeId());
$employeeDetails->setEmail($sysUser->getEmail());
$employeeDetails->setFirstName($sysUser->getUsername());
$employeeDetails->setLastName($sysUser->getName());
$employeeDetails->setUsername($sysUser->getUsername());
$employeeDetails->setUserId($sysUser->getUserId());
$employeeDetails->setEmpStatus(1);
$em->persist($employeeDetails);
$em->flush();
} else {
return new JsonResponse([
'status' => 'error',
'message' => 'Missing employee details data',
]);
}
}
$company = $em->getRepository('ApplicationBundle:Company')->find($companyId);
$companyName = $company ? $company->getName() : '';
$currentAccessList = $session->get('userAccessList', []);
$newAccess = [
'userType' => 1,
'userTypeName' => 'Admin',
'globalId' => $sysUser->getGlobalId(),
'serverId' => 1,
'serverUrl' => $request->getSchemeAndHttpHost(),
'serverPort' => 80,
'systemType' => $systemType,
'companyId' => $companyId,
'appId' => $appId,
'companyLogoUrl' => '/uploads/CompanyImage/company_image' . $appId . '.png',
'companyName' => $companyName,
'authenticationStr' => base64_encode(bin2hex(random_bytes(32))),
'userCompanyList' => [],
];
$exists = false;
foreach ($currentAccessList as $access) {
if ($access['companyId'] == $companyId && $access['appId'] == $appId) {
$exists = true;
break;
}
}
if (!$exists) {
$currentAccessList[] = $newAccess;
$session->set('userAccessList', $currentAccessList);
}
if ($entityToken) {
$entityToken->setSessionData($currentAccessList);
$entityToken->setUpdatedAt(new \DateTime());
$em->persist($entityToken);
$em->flush();
return new JsonResponse([
'status' => 'success',
'message' => 'Token session updated successfully'
]);
}
return new JsonResponse([
'status' => 'success',
'message' => 'User onboarded successfully',
'redirectUlr' => 'dashboard'
]);
}
public function DecodeQrAction(Request $request)
{
$applicantId = $request->request->get('applicant_id');
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/get_applicant_data_central';
$applicantFiles = [
'applicantId' => $applicantId
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array(),
CURLOPT_POSTFIELDS => $applicantFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = json_decode($retData, true);
return new JsonResponse($retDataObj['centralData']);
}
public function GetApplicantDataForErpAction(Request $request)
{
$applicantId = $request->request->get('applicantId');
if (!$applicantId) {
return new JsonResponse([
'status' => 'error',
'message' => 'Missing applicantId in request.'
]);
}
$em_goc = $this->getDoctrine()->getManager('company_group');
$entityApplicant = $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")
->findOneBy(['applicantId' => $applicantId]);
if (!$entityApplicant) {
return new JsonResponse([
'status' => 'error',
'message' => 'Applicant not found.'
]);
}
return new JsonResponse([
'status' => 'success',
'centralData' => [
'globalId' => $entityApplicant->getApplicantId(),
'username' => $entityApplicant->getUsername(),
'email' => $entityApplicant->getEmail(),
'firstname' => $entityApplicant->getFirstname(),
'lastname' => $entityApplicant->getLastname(),
'image' => $entityApplicant->getImage(),
'phone' => $entityApplicant->getPhone(),
'address' => $entityApplicant->getPermAddr()
]
]);
}
public function EmployeeListAction(Request $data)
{
$em = $this->getDoctrine()->getManager();
if ($data->isMethod('GET')) {
return $this->render("ApplicationBundle:pages/human_resource/list:list_employee.html.twig", array(
'page_title' => 'Employee List',
));
}
}
public function OrganizationChartAction()
{
$em = $this->getDoctrine()->getManager();
$Reponse = HumanResource::TwigDataForOrgChart($em);
return $this->render('ApplicationBundle:pages/human_resource/views:org_chart.html.twig', array(
'page_title' => 'Organization Chart',
'supervisors' => $Reponse['TreantJsData'],
'alluser' => $Reponse['TreantJsInitUser']
));
}
public function EmployeeListSelectizeAjaxAction(Request $request, $str = '_EMPTY_')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$html = '';
$qryStrs = explode(' ', $str);
$qryStrAddedForSpacedName = "";
if ($str == '_EMPTY_') {
$query = "SELECT *
from employee order by employee_id asc limit 10";
} else {
foreach ($qryStrs as $qryStr) {
$qryStrAddedForSpacedName .= "or first_name like '%$qryStr%' or last_name like '%$qryStr%' ";
}
$query = "SELECT *
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";
}
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$res = $stmt->fetchAll();
// if(!empty($res)) {
foreach ($res as $i => $r) {
$res[$i]['id_padded'] = str_pad($r['employee_id'], 8, '0', STR_PAD_LEFT);
}
// }
return new JsonResponse(
array(
'success' => true,
'data' => $res,
)
);
}
public function AttendanceAction(Request $data, $remoteVerify = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$workHourPolicy = $em->getRepository('ApplicationBundle:WorkHourPolicy')->findAll();
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
);
if ($data->get('DataTable')) {
$response = HumanResource::HandelAjaxRequestForManualAttendance($em, $data);
return new JsonResponse($response);
}
if ($data->request->get('getAttendanceStatus')) {
$response = HumanResource::getAttendanceStatus($em, $data);
return new JsonResponse($response);
}
$session = $data->getSession();
// if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
// return $this->redirectToRoute('permission_denied_page');
// Auto attendance
if ($data->get('autoAttendance') && $data->request->has('position_array')) {
// $empId = $data->query->get('id');
$empId = $data->request->get('id', $session->get(UserConstants::USER_EMPLOYEE_ID));
$positionsArray = $data->request->get('position_array', []);
if (is_string($positionsArray)) $positionsArray = json_decode($positionsArray, true);
if ($positionsArray == null) $positionsArray = [];
$dataByAttId = [];
$workPlaceType = '_UNSET_';
foreach ($positionsArray as $d) {
$sysUserId = 0;
$userId = 0;
$empId = 0;
$dtTs = 0;
$timeZoneStr = '+0000';
// $timeZoneStr = '+0600';
$token = '_unset_';
if (isset($d['token'])) $token = $d['token'];
if (isset($d['employeeId'])) $empId = $d['employeeId'];
if (isset($d['userId'])) $userId = $d['userId'];
if (isset($d['sysUserId'])) $sysUserId = $d['sysUserId'];
if (isset($d['tsMilSec'])) {
$dtTs = ceil((1 * $d['tsMilSec']) / 1000);
}
if ($token != '_unset_') {
$sessionData = MiscActions::GetSessionDataFromToken($em_goc, $token)['sessionData'];
if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
$empId = $sessionData[UserConstants::USER_EMPLOYEE_ID];
}
if ($sysUserId == 0)
$sysUserId = $userId;
if ($sysUserId == 0)
$sysUserId = $em->getRepository(Employee::class)
->findOneBy(['employeeId' => $empId])->getUserId();
if ($dtTs == 0) {
$currTsTime = new \DateTime();
$dtTs = $currTsTime->format('U');
} else {
$currTsTime = new \DateTime('@' . $dtTs);
}
$currTsTime->setTimezone(new \DateTimeZone('UTC'));
$attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' . $timeZoneStr);
$EmployeeAttendance = $this->getDoctrine()
->getRepository(EmployeeAttendance::class)
->findOneBy(array('employeeId' => $empId, 'date' => $attDate));
if (!$EmployeeAttendance)
$EmployeeAttendance = new EmployeeAttendance;
$attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $attDate, $dtTs, $timeZoneStr, $d['markerId']);
if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
if ($empId == 24)
$workPlaceType = '_HYBRID_';
else
$workPlaceType = '_STATIC_';
}
if (!isset($dataByAttId[$attendanceInfo->getId()]))
$dataByAttId[$attendanceInfo->getId()] = array(
'attendanceInfo' => $attendanceInfo,
'empId' => $empId,
'lat' => 0,
'lng' => 0,
'address' => 0,
'sysUserId' => $sysUserId,
'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
'positionArray' => []
);
$posData = array(
'ts' => $dtTs,
'lat' => $d['lat'],
'lng' => $d['lng'],
'marker' => $d['markerId'],
'src' => 2,
);
$posDataArray = array(
$dtTs,
$d['lat'],
$d['lng'],
$d['markerId'],
2
);
$dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
//this markerId will be calclulted and modified to check if user is in our out of office/workplace later
$dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
$dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
$dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat']; //for last lat lng etc
$dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng']; //for last lat lng etc
if (isset($d['address']))
$dataByAttId[$attendanceInfo->getId()]['address'] = $d['address']; //for last lat lng etc
// $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
}
$response = array(
'success' => true,
);
foreach ($dataByAttId as $attInfoId => $d) {
$response = HumanResource::setAttendanceLogFlutterApp($em,
$d['empId'],
$d['sysUserId'],
$d['companyId'],
$d['appId'],
$data,
$d['attendanceInfo'],
$options,
$d['positionArray'],
$d['lat'],
$d['lng'],
$d['address'],
$d['markerId']
);
}
if ($data->request->get('requestFromMobile')) {
$today = new \DateTime(date('y-m-d'));
$repository = $this->getDoctrine()->getRepository(EmployeeAttendance::class);
$ActivitiesTemplate = HumanResource::getCurrentStatusFromDb($repository, $empId, $today);
return new JsonResponse(array(
'success' => $response['success'] == true ? true : false,
'msg' => $response['success'] == true ? 'Employee activities successfully updated.' : 'Action Failed',
'workPlaceType' => $workPlaceType,
'data' => $ActivitiesTemplate
));
}
return new JsonResponse(
array(
'success' => true,
'msg' => 'Employee activities successfully updated.',
'workPlaceType' => $workPlaceType,
)
);
} else if ($data->get('autoAttendance')) {
$sysUserId = 0;
$userId = 0;
$empId = 0;
$dtTs = 0;
// $timeZoneStr = '+0600';
$timeZoneStr = '+0000';
if ($data->request->get('requestFromMobile')) {
$empId = $data->request->get('employeeId');
$userId = $data->request->get('userId', 0);
$sysUserId = $data->request->get('id', 0);
// $empId = $em->getRepository(Employee::class)
// ->findOneBy(['userId' => $userId])->getEmployeeId();
} else {
$empId = $data->request->get('employeeId', 0);
$sysUserId = $data->request->get('userId', 0);
}
$dtTs = $data->request->get('timeTs', 0);
if ($sysUserId == 0)
$sysUserId = $userId;
if ($sysUserId == 0)
$sysUserId = $em->getRepository(Employee::class)
->findOneBy(['employeeId' => $empId])->getUserId();
if ($dtTs == 0) {
$currTsTime = new \DateTime();
$dtTs = $currTsTime->format('U');
} else {
$currTsTime = new \DateTime('@' . $dtTs);
}
if ($sysUserId == 0)
$sysUserId = $userId;
if ($sysUserId == 0)
$sysUserId = $em->getRepository(Employee::class)
->findOneBy(['employeeId' => $empId])->getUserId();
$today = new \DateTime(date('y-m-d'));
$currTsTime->setTimezone(new \DateTimeZone('UTC'));
$attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' . $timeZoneStr);
$EmployeeAttendance = $this->getDoctrine()
->getRepository(EmployeeAttendance::class)
->findOneBy(array('employeeId' => $empId, 'date' => $attDate));
if (!$EmployeeAttendance)
$EmployeeAttendance = new EmployeeAttendance;
// return new JsonResponse(["success" => true, "data" => $ActivitiesTemplate]);
// $attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $customTime);
$attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $attDate, $dtTs, $timeZoneStr, HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED);
if (!isset($dataByAttId[$attendanceInfo->getId()]))
$dataByAttId[$attendanceInfo->getId()] = array(
'attendanceInfo' => $attendanceInfo,
'empId' => $empId,
'lat' => 0,
'lng' => 0,
'address' => 0,
'sysUserId' => $sysUserId,
'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
'positionArray' => []
);
$posData = array(
'ts' => $dtTs,
'lat' => 0,
'lng' => 0,
'marker' => HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
'src' => 1,
);
$posDataArray = array(
$dtTs,
0,
0,
HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
1
);
$dataByAttId[$attendanceInfo->getId()]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED;
//this markerId will be calclulted and modified to check if user is in our out of office/workplace later
$dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
$dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
$dataByAttId[$attendanceInfo->getId()]['lat'] = 0; //for last lat lng etc
$dataByAttId[$attendanceInfo->getId()]['lng'] = 0; //for last lat lng etc
if (isset($d['address']))
$dataByAttId[$attendanceInfo->getId()]['address'] = ''; //for last lat lng etc
$response = array(
'success' => true
);
foreach ($dataByAttId as $attInfoId => $d) {
$response = HumanResource::setAttendanceLogFlutterApp($em,
$d['empId'],
$d['sysUserId'],
$d['companyId'],
$d['appId'],
$data,
$d['attendanceInfo'],
$options,
$d['positionArray'],
$d['lat'],
$d['lng'],
$d['address'],
$d['markerId']
);
}
if ($data->request->get('requestFromMobile')) {
return new JsonResponse(array(
'success' => $response['success'] == true ? true : false,
'msg' => $response['success'] == true ? 'Employee activities successfully updated.' : 'Action Failed',
));
}
return new JsonResponse(
array(
'success' => true,
'dtTs' => $dtTs,
'attDate' => $attDate->format(DATE_RFC822),
'currTsTime' => $currTsTime->format(DATE_RFC822),
'msg' => 'Employee activities successfully updated.',
)
);
//
//
// $response = HumanResource::setAttendanceLog($em, $empId, $sysUserId,
// $data->getSession()->get(UserConstants::USER_COMPANY_ID),
// $data->getSession()->get(UserConstants::USER_APP_ID),
// $data, $attendanceInfo, $options);
//
// if ($data->request->get('requestFromMobile')) {
// return new JsonResponse($response);
// }
//
// return new JsonResponse(
// array(
// 'success' => true,
// 'msg' => 'Employee activities successfully updated.'
// )
// );
// }
// else {
// return new JsonResponse(
// array(
// 'success' => false,
// 'msg' => "Invalid employee ID"
// )
// );
// }
} else {
if ($data->get('manualAttendance')) {
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:manual_attendance.html.twig',
array(
'page_title' => 'Manual Attendance',
'workPolicy' => $workHourPolicy,
// 'workTime' => json_decode($workHourPolicy->getRepeatationData()),
// 'workTime' => json_decode($workHourPolicy->getRepeatationData()),
// 'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
)
);
}
// Show all matching employee list during ajax request
// Show current location according to id
if ($data->get('getCurrLocById')) {
$Id = $data->get("id");
$options = array(
'employeeId' => $Id,
'entityDbaseName' => 'work_hour_policy',
'entityDbaseIdField' => 'id',
'entityDbaseEmployeeIdsField' => 'employeeIds',
'entityDesignationIdsField' => 'designationIds',
'entityDepartmentIdsField' => 'departmentIds',
'entityEmployeeTypeIdsField' => 'employee_types',
'limit' => 1,
'single' => 1,
);
$workHourPolicyData = HumanResource::getApplicableSettingsDataForEmployee($em, $options);
$today = new \DateTime(date('y-m-d'));
$repository = $this->getDoctrine()->getRepository(EmployeeAttendance::class);
$ActivitiesTemplate = HumanResource::getActivitiesTemplate($repository, $Id, $today);
return new JsonResponse(["success" => true, "workHourPolicyData" => $workHourPolicyData, "template" => $ActivitiesTemplate]);
}
}
}
public function getCurrentStatusAction($id)
{
$today = new \DateTime(date('y-m-d'));
$repository = $this->getDoctrine()->getRepository(EmployeeAttendance::class);
$ActivitiesTemplate = HumanResource::getCurrentStatusFromDb($repository, $id, $today);
return new JsonResponse(["success" => true, "data" => $ActivitiesTemplate]);
}
public function CurrentAttendanceAction(Request $data)
{
$em = $this->getDoctrine()->getManager();
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
);
if ($data->get('DataTable')) {
$response = HumanResource::HandelAjaxRequestForManualAttendance($em, $data);
return new JsonResponse($response);
}
if ($data->request->get('getAttendanceStatus')) {
$response = HumanResource::getAttendanceStatus($em, $data);
return new JsonResponse($response);
}
// Auto attendance
if ($data->get('autoAttendance')) {
$empId = $data->query->get('id');
$sysUserId = 0;
if ($data->get('requestFromMobile')) {
$sysUserId = $data->request->get('id');
$empId = $em->getRepository(Employee::class)
->findOneBy(['userId' => $sysUserId])->getEmployeeId();
} else {
$sysUserId = $em->getRepository(Employee::class)
->findOneBy(['employeeId' => $empId])->getUserId();
}
$customTime = $data->get('time');
$today = new \DateTime(date('y-m-d'));
$EmployeeAttendance = $this->getDoctrine()
->getRepository(EmployeeAttendance::class)
->findOneBy(array('employeeId' => $empId, 'date' => $today));
if (!$EmployeeAttendance)
$EmployeeAttendance = new EmployeeAttendance;
$attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $customTime);
$response = HumanResource::setAttendanceLog($em, $empId, $sysUserId,
$data->getSession()->get(UserConstants::USER_COMPANY_ID),
$data->getSession()->get(UserConstants::USER_APP_ID),
$data, $attendanceInfo, $options);
if ($data->get('requestFromMobile')) {
return new JsonResponse([$response]);
}
return new JsonResponse(
array(
'success' => true,
'msg' => 'Employee activities successfully updated.'
)
);
// }
// else {
// return new JsonResponse(
// array(
// 'success' => false,
// 'msg' => "Invalid employee ID"
// )
// );
// }
} else {
if ($data->get('manualAttendance')) {
return $this->render(
'ApplicationBundle:pages/human_resource/report:current_attendance.html.twig',
array(
'page_title' => 'Current Attendance Status',
)
);
}
// Show all matching employee list during ajax request
// Show current location according to id
if ($data->get('getCurrLocById')) {
$Id = $data->get("id");
$today = new \DateTime(date('y-m-d'));
$repository = $this->getDoctrine()->getRepository(EmployeeAttendance::class);
$ActivitiesTemplate = HumanResource::getActivitiesTemplate($repository, $Id, $today);
return new JsonResponse(["success" => true, "template" => $ActivitiesTemplate]);
}
}
}
public function EmployeeLeaveAction(Request $data, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$request = $data;
if (!$id) {
if ($data->isMethod('GET')) {
$EmpID = $data->query->get('id');
$LeaveType = $data->query->get('leaveType');
if ($data->query->has('id') && $data->query->has('leaveType')) {
$response = HumanResource::HandelAjaxRequestForLeaveApp($em, $EmpID, $LeaveType);
return new JsonResponse($response);
}
if ($data->query->has('id')) {
$Response = HumanResource::HandelAjaxRequestForLeaveApp($em, $EmpID);
return new JsonResponse($Response);
}
$TemplateData = HumanResource::TwigDataForLeaveApp($em, False);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:employee_leave.html.twig',
array(
'page_title' => $TemplateData['Title'],
'EmployeeList' => $TemplateData['EmployeeList'],
'DesignationList' => $TemplateData['DesignationList'],
'HasUpdateMode' => false
)
);
} else {
$CompanyId = $this->getLoggedUserCompanyId($data);
$Response = HumanResource::StoreDataForLeaveApplication($em, $id, $data, false, $CompanyId);
if ($Response['HasErr']) {
$this->addFlash('error', $Response['msg']);
if ($data->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'errorStr' => $Response['msg'],
));
} else {
return $this->redirectToRoute('employee_leave');
}
}
$applicationId = $Response['applicationId'];
$em_goc = $this->getDoctrine()->getManager('company_group');
$file_path_list = [];
if ($applicationId != 0) {
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'EmployeeLeaveApplication', $applicationId);
$storePath = 'uploads/LeaveDoc/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'LDOC_' . $applicationId . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('EmployeeLeaveApplication');
$EntityFile->setEntityBundle('EmployeeLeaveApplication');
$EntityFile->setEntityId($applicationId);
$EntityFile->setEntityIdField('employeeLeaveApplicationId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$v = $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')->findOneBy(array(
'employeeLeaveApplicationId' => $applicationId,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
}
// $this->addFlash('success', 'Application submitted successfully!');
// return $this->redirectToRoute('leave_application_list');
if ($data->request->has('returnJson')) {
return new JsonResponse(array(
'success' => true,
));
} else {
return $this->redirectToRoute('view_employee_leave_application', array('id' => $applicationId));
}
}
} else {
if ($data->isMethod('GET')) {
$ApplicationRepo = $em->getRepository(EmployeeLeaveApplication::class);
$OldData = $ApplicationRepo->find(array('employeeLeaveApplicationId' => $id));
$TemplateData = HumanResource::TwigDataForLeaveApp($em, $OldData);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:employee_leave.html.twig',
array(
'page_title' => $TemplateData['Title'],
'EmployeeList' => $TemplateData['EmployeeList'],
'DesignationList' => $TemplateData['DesignationList'],
'OldData' => $TemplateData['OldData'],
'AvailableLeave' => $TemplateData['AvailableLeave'],
'HasUpdateMode' => true
)
);
} else {
$CompanyId = $this->getLoggedUserCompanyId($data);
$Response = HumanResource::StoreDataForLeaveApplication($em, $id, $data, true, $CompanyId);
if ($Response['HasErr']) {
$this->addFlash('error', $Response['msg']);
return $this->redirectToRoute('employee_leave');
}
$this->addFlash('success', "Application updated successfully!");
return $this->redirectToRoute('leave_application_list');
}
}
}
public function ViewLeaveApplicationAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
if ($id) {
$TwigData = HumanResource::TwigDataForViewLeaveApplication($em, $request, $id);
if ($TwigData['HasErr']) {
return new JsonResponse(array(
'success' => false,
'msg' => $TwigData['Msg']
));
}
return $this->render(
'ApplicationBundle:pages/human_resource/views:leave_application_view.html.twig',
array(
'page_title' => 'View Leave Application',
'Applicant' => $TwigData['Applicant'],
'Application' => $TwigData['Application'],
'LeaveType' => $TwigData['LeaveType'],
'leaveDataArray' => $TwigData['leaveDataArray'],
'LeaveCategory' => $TwigData['LeaveCategory'],
'FrwdEmp' => $TwigData['FrwdEmp'],
'ApplicantDesg' => $TwigData['ApplicantDesg'],
'approval_status' => $TwigData['approval_status'],
'approval_data' => $TwigData['approval_data'],
'document_log' => $TwigData['document_log'],
'auto_created' => 0,
)
);
}
return new JsonResponse(array(
'success' => false,
'msg' => 'Wrong URL format! Please try with application ID'
));
}
public function PrintLeaveApplicationAction(Request $request, $id)
{
if ($id) {
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$Application = $em->getRepository(EmployeeLeaveApplication::class)->find($id);
$Authorizations = System::getSignatureListForDocumentPrint($em, array_flip(GeneralConstant::$Entity_list)['EmployeeLeaveApplication'], $id);
$ApplicationCategory = $Application->getLeaveCategory();
$ApplicationType = '';
if (($ApplicationCategory != 1 && $ApplicationCategory != 2))
if (isset($leaveDataArray[$Application->getLeaveTypeId() - 1]))
$ApplicationType = $leaveDataArray[$Application->getLeaveTypeId() - 1]['name'];
$Applicant = $em->getRepository(EmployeeDetails::class)
->find($Application->getEmployeeId());
return $this->render(
'ApplicationBundle:pages/human_resource/print:leave_application_print.html.twig',
array(
'page_title' => 'Print Leave Application',
'export' => 'pdf,print',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'Application' => $Application,
'Applicant' => $Applicant,
'Authorizations' => $Authorizations,
'ApplicationType' => $ApplicationType,
'ApplicationCategory' => $ApplicationCategory,
'red' => 0
)
);
}
return new JsonResponse(array(
'success' => false,
'msg' => 'Wrong URL format! Please try with application ID'
));
}
public function LeaveApplicationListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response = HumanResource::GetEmployeeLeaveApplicationList($em, $request);
if ($request->isMethod('GET')) {
return $this->render("ApplicationBundle:pages/human_resource/list:leave_application_list.html.twig", array(
'page_title' => 'Leave Application List',
'application_data' => $response,
));
}
}
public function PayrollPolicySettingsAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$CompanyId = $this->getLoggedUserCompanyId($request);
if ($id) {
if ($request->isMethod('GET')) {
$Row = $em->getRepository(PayrollPolicy::class)->find($id);
if (!$Row) {
$this->addFlash('error', 'Invalid Payroll Policy Id');
return $this->redirectToRoute('payroll_policy_settings');
}
$TwigData = HumanResource::GetPayrollPolicyTwigData($em);
$OldData = HumanResource::GetPayrollPolicyTwigData($em, $id);
return $this->render('ApplicationBundle:pages/human_resource/input_forms:payroll_policy_settings.html.twig', array(
'page_title' => 'Update Payroll Policy Settings',
'EmployeeIds' => $TwigData['EmployeeIds'],
'EmployeeType' => $TwigData['EmployeeType'],
'department' => $TwigData['department'],
'Designation' => $TwigData['Designation'],
'WorkingDays' => $TwigData['WorkingDays'],
'OldData' => $OldData['Row'],
'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
'deductionAspects' => HumanResourceConstant::$deductionAspects,
'deductionCondition' => json_decode($Row->getDeductionCondition(), true),
'HasUpdateMode' => true,
));
} else {
$Response = HumanResource::StorePayrollPolicyData($em, $id, $CompanyId, $request);
if ($Response['HasErr']) {
$this->addFlash('error', $Response['msg']);
return $this->redirectToRoute('payroll_policy_settings');
}
return $this->redirectToRoute('payroll_policy_settings');
// if ($Response['isSuccess']) {
// return new JsonResponse(array('success' => true, 'msg' => 'don\'t forget to redirect'));
// }
// return new JsonResponse(array('success' => false, 'msg' => 'Sorry something went wrong'));
}
} else {
if ($request->isMethod('GET')) {
if ($request->query->get('GetDocHash')) {
$Dochash = HumanResource::GenerateDocHashForPayrollSettings($em, $request);
return new JsonResponse($Dochash);
}
$TwigData = HumanResource::GetPayrollPolicyTwigData($em);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:payroll_policy_settings.html.twig',
array(
'page_title' => 'Create Payroll Policy Settings',
'EmployeeIds' => $TwigData['EmployeeIds'],
'EmployeeType' => $TwigData['EmployeeType'],
'WorkingDays' => $TwigData['WorkingDays'],
'Designation' => $TwigData['Designation'],
'department' => $TwigData['department'],
'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
'deductionAspects' => HumanResourceConstant::$deductionAspects,
'HasUpdateMode' => false
)
);
} else {
$Response = HumanResource::StorePayrollPolicyData($em, $id, $CompanyId, $request);
if ($Response['HasErr']) {
$this->addFlash('error', $Response['msg']);
return $this->redirectToRoute('payroll_policy_settings');
}
return $this->redirectToRoute('payroll_policy_settings');
// return new JsonResponse(array("success" => true, 'msg' => 'Dont forget to redirect!'));
}
}
}
public function AttendanceReportAction(Request $request, $apiKey = 'impose')
{
$em = $this->getDoctrine()->getManager();
$attendanceSource = HumanResourceConstant::$attendanceSources;
$routeName = $request->attributes->get('_route');
if ($routeName == 'app_get_attendendance_data') {
$ReportData = HumanResource::GenerateAttendanceReport($em, $request, $request->get('considerCurrTsIfNoOut', 1));
$newReports = [];
foreach ($ReportData['Reports'] as $gg) {
foreach ($gg as $d) {
$newReports[] = $d;
// if(!isset($newReports[$d['id']]))
// $newReports[$d['id']]=array();
// $newReports[$d['id']][]=$d;
}
}
return new JsonResponse (array(
'attendanceSource' => $attendanceSource,
// 'Reports' => $ReportData['Reports'],
'Reports' => $newReports,
'from_date' => $ReportData['from_date'],
'to_date' => $ReportData['to_date'],
'report_for' => $ReportData['generated_for'],
'attendance' => $ReportData['attendance'],
));
} else {
$EmployeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
$Departments = $em->getRepository(SysDepartment::class)->findAll();
if ($request->isMethod('GET')) {
return $this->render('ApplicationBundle:pages/human_resource/report:attendance_report.html.twig', array(
'page_title' => 'Attendance Report',
'employes' => $EmployeeIds,
'departments' => $Departments,
'isMethodGet' => true,
'from_date' => '',
'to_date' => '',
'report_for' => '',
'attendance' => [],
'Reports' => [],
'qry' => ''
));
}
$ReportData = HumanResource::GenerateAttendanceReport($em, $request, $request->request->get('considerCurrTsIfNoOut', 0));
if ($request->request->get('returnJson', 0) == 1) {
return new JsonResponse($ReportData);
}
$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') : []));
return $this->render('ApplicationBundle:pages/human_resource/report:attendance_report.html.twig', array(
'page_title' => 'Attendance Report',
'isMethodGet' => false,
'departments' => $Departments,
'employes' => $EmployeeIds,
'attendanceSource' => $attendanceSource,
'Reports' => $ReportData['Reports'],
'from_date' => $ReportData['from_date'],
'to_date' => $ReportData['to_date'],
'report_for' => $ReportData['generated_for'],
'attendance' => $ReportData['attendance'],
'qry' => $Qry
));
}
}
public function PrintAttendanceReportAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$ReportData = HumanResource::GenerateAttendanceReport($em, $request);
return $this->render(
'ApplicationBundle:pages/human_resource/print:print_attendance_report.html.twig',
array(
'page_title' => 'Print Attendance Report',
'export' => 'pdf,print',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'Reports' => $ReportData['Reports'],
'from_date' => $ReportData['from_date'],
'to_date' => $ReportData['to_date'],
'report_for' => $ReportData['generated_for'],
'attendance' => $ReportData['attendance'],
'red' => 0
)
);
}
public function SalaryReportAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$startDate = $request->get('salary_start_date', '');
$endDate = $request->get('salary_till_date', '');
$segregationType = $request->get('segregationType', 1);
$filterBranchIds = $request->get('branchIds', []);
$filterBankIds = $request->get('bankIds', []);
$approvalFilterTypes = $request->get('approvalFilterTypes', []);
$filterDepartmentIds = $request->get('departmentIds', []);
$filterEmployeeIds = $request->get('employeeIds', []);
$Departments = $em->getRepository(SysDepartment::class)->findAll();
$attendance = $em->getRepository(EmployeeAttendanceLog::class)->findAll();
$banks = $em->getRepository(BankList::class)->findAll();
$branches = $em->getRepository(Branch::class)->findAll();
$SalaryReports = HumanResource::GenerateSalaryReport($em, $request);
// dump($SalaryReports);
$Qry = "salary_till_date=" . $endDate . '&' . "departmentIds=" . implode(',', $filterDepartmentIds) . '&' . "employeeIds=" . implode(',', $filterEmployeeIds) .
'&' . "salary_start_date=" . $startDate .
'&' . "segregationType=" . $segregationType .
'&' . "branchIds=" . implode(',', $filterBranchIds) .
'&' . "bankIds=" . implode(',', $filterBankIds);
// if ($request->get('returnJson', 0) == 1) {
if ($request->get('returnJson', 0) == 1) {
return new JsonResponse(array(
'SalaryReports' => $SalaryReports,
));
} else {
return $this->render('ApplicationBundle:pages/human_resource/report:salary_report.html.twig', array(
'page_title' => 'Salary Report',
'departments' => $Departments,
'branches' => $branches,
'banks' => $banks,
'approvalFilterTypes' => $approvalFilterTypes,
'salaryInfo' => $SalaryReports,
'SalaryReports' => $SalaryReports,
'for_month' => '',
'from_date' => $startDate,
'to_date' => $endDate,
'Qry' => $Qry,
'isMethodGet' => false,
'startDate' => $startDate,
'endDate' => $endDate,
'segregationType' => $segregationType,
'filterBranchIds' => $filterBranchIds,
'filterBankIds' => $filterBankIds,
'filterDepartmentIds' => $filterDepartmentIds,
'filterEmployeeIds' => $filterEmployeeIds,
));
}
}
public function DisburseSalaryAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$EmployeeIds = $em->getRepository(EmployeeDetails::class)->findBy(
array(
'emp_status' => 1
)
);
$startDate = $request->get('salary_start_date', '');
$endDate = $request->get('salary_till_date', '');
$filterType = $request->get('filterType', 1);
$filterBranchIds = $request->get('branchIds', []);
$filterBankIds = $request->get('bankIds', []);
$filterDepartmentIds = $request->get('departmentIds', []);
$filterEmployeeIds = $request->get('employeeIds', []);
$Departments = $em->getRepository(SysDepartment::class)->findAll();
$attendance = $em->getRepository(EmployeeAttendanceLog::class)->findAll();
$banks = $em->getRepository(BankList::class)->findAll();
$branches = $em->getRepository(Branch::class)->findAll();
if ($request->isMethod('GET')) {
return $this->render('ApplicationBundle:pages/human_resource/report:disburse_salary.html.twig', array(
'page_title' => 'Disburse Salary',
'EmployeeIds' => $EmployeeIds,
'departments' => $Departments,
'attendance' => $attendance,
'branches' => $branches,
'banks' => $banks,
'SalaryReports' => [],
'from_date' => '',
'to_date' => '',
'Qry' => '',
'isMethodGet' => true,
'filterType' => $filterType,
'startDate' => $startDate,
'endDate' => $endDate,
'filterBranchIds' => $filterBranchIds,
'filterBankIds' => $filterBankIds,
'filterDepartmentIds' => $filterDepartmentIds,
'filterEmployeeIds' => $filterEmployeeIds,
));
}
$SalaryReports = HumanResource::BasicDeduction($em, $request);
// $SalaryReportsNew = HumanResource::calculateSalary($em,
// array(
// 'startDate' => $request->get('salary_start_date', ''),
// 'endDate' => $request->get('salary_end_date', ''),
// 'timeZone' => $request->get('time_zone', '+0600'),
// 'employeeIds' => $request->get('employeeIds', []),
// 'departmentIds' => $request->get('department', []),
// 'allFlag' => $request->get('show_all', 0),
//
// )
// );
$Qry = "salary_till_date=" . $endDate . '&' . "departmentIds=" . implode(',', $filterDepartmentIds) . '&' . "employeeIds=" . implode(',', $filterEmployeeIds) .
'&' . "salary_start_date=" . $startDate .
'&' . "filterType=" . $filterType .
'&' . "branchIds=" . implode(',', $filterBranchIds) .
'&' . "bankIds=" . implode(',', $filterBankIds);
// if ($request->get('returnJson', 0) == 1) {
if ($request->get('returnJson', 0) == 1) {
return new JsonResponse(array(
'SalaryReports' => $SalaryReports,
));
} else {
return $this->render('ApplicationBundle:pages/human_resource/report:disburse_salary.html.twig', array(
'page_title' => 'Disburse Salary',
'EmployeeIds' => $EmployeeIds,
'departments' => $Departments,
'branches' => $branches,
'banks' => $banks,
'SalaryReports' => $SalaryReports,
'for_month' => $SalaryReports[0]['for_month'],
'from_date' => $SalaryReports[0]['from_date'],
'to_date' => $SalaryReports[0]['to_date'],
'Qry' => $Qry,
'isMethodGet' => false,
'startDate' => $startDate,
'endDate' => $endDate,
'filterType' => $filterType,
'filterBranchIds' => $filterBranchIds,
'filterBankIds' => $filterBankIds,
'filterDepartmentIds' => $filterDepartmentIds,
'filterEmployeeIds' => $filterEmployeeIds,
));
}
}
public function PrintDisburseSalaryAction(Request $Req)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$SalaryReports = HumanResource::BasicDeduction($em, $Req);
return $this->render(
'ApplicationBundle:pages/human_resource/print:print_disburse_salary.html.twig',
array(
'page_title' => 'Print Disburse Salary',
'export' => 'pdf,print',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'SalaryReports' => $SalaryReports,
'for_month' => $SalaryReports[0]['for_month'],
'from_date' => $SalaryReports[0]['from_date'],
'to_date' => $SalaryReports[0]['to_date'],
'red' => 0
)
);
}
public function createJobRecruitmentAction(Request $request, $id = 0)
{
$data = [];
$em_goc = $this->getDoctrine()->getManager('company_group');
$skillDetails = $em_goc->getRepository(EntitySkill::class)->findAll();
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['JobRecruitment']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable($em, $entity_id, $dochash,
$loginId, $approveRole, $approveHash, $id)
) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$data = $request->request;
$docId = HumanResource::createJobRecruitment($em, $loginId, $id, $data, $companyId);
//now add Approval info
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['JobRecruitment']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'New Recruitment Document Added.'
);
$url = $this->generateUrl(
'view_job_recruitment'
);
return $this->redirect($url . "/" . $docId);
}
}
if ($id == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:JobRecruitment')->findOneBy(
array(
'jobRecruitmentId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_job_recruitment'
);
return $this->redirect($url . "/" . $id);
}
}
}
$jobType = HumanResourceConstant::$employeeType;
//$skillDetails = $em->getRepository(Skill::class)->findAll();
$educationDetails = $em->getRepository('ApplicationBundle:EducationQualification')->findAll();
$employeeIds = $em->getRepository('ApplicationBundle:Employee')->findAll();
$location = HumanResourceConstant::$location;
$salaryPer = HumanResourceConstant::$salaryPer;
$workExperience = HumanResourceConstant::$workExperience;
$jobOpeningStatus = HumanResourceConstant::$jobOpeningStatus;
$compatibility = HumanResourceConstant::$compatibility;
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_new_job_post.html.twig', [
'page_title' => 'Create New Job Post',
'jobType' => $jobType,
'skillDetails' => $skillDetails,
'educationDetails' => $educationDetails,
'employeeIds' => $employeeIds,
'location' => $location,
'salaryPer' => $salaryPer,
'workExperience' => $workExperience,
'jobOpeningStatus' => $jobOpeningStatus,
'compatibility' => $compatibility
]);
}
public function viewApplicantInfoAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager('company_group');
//$session = $request->getSession();
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($id);
$skillDetails = $em->getRepository('CompanyGroupBundle:EntitySkill')->findAll();
//$companyId = $this->getLoggedUserCompanyId($request);
$gender = HumanResourceConstant::$sex;
$blood = HumanResourceConstant::$BloodGroup;
//$userId = $session->get(UserConstants::USER_ID);
return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_info.html.twig', [
'page_title' => 'Applicant Information',
'gender' => $gender,
'blood' => $blood,
'consultantDetails' => $consultantDetails,
'education' => json_decode($consultantDetails->getEducationData(), true),
'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
'certificate' => json_decode($consultantDetails->getCertificateData(), true),
'courses' => json_decode($consultantDetails->getCoursesData(), true),
'languages' => json_decode($consultantDetails->getLanguagesData(), true),
'skillDetails' => $skillDetails
]);
}
public function ListJobRecruitmentAction()
{
$em = $this->getDoctrine()->getManager();
$jobRecruitmentList = [];
$jobRecruitments = $em->getRepository('ApplicationBundle:JobRecruitment')->findAll();
foreach ($jobRecruitments as $jobRecruitment) {
$jobData = array(
'jobRecruitmentId' => $jobRecruitment->getJobRecruitmentId(),
'title' => $jobRecruitment->getTitle(),
'date' => $jobRecruitment->getDate(),
'jobOpeningStatus' => $jobRecruitment->getJobOpeningStatus(),
'applicationOpeningDate' => $jobRecruitment->getApplicationOpeningDate(),
'applicationClosingDate' => $jobRecruitment->getApplicationClosingDate(),
);
$jobRecruitmentList[] = $jobData;
}
return $this->render('ApplicationBundle:pages/human_resource/list:job_recruitment_list.html.twig', [
'page_title' => 'Job RecruitmentAction List',
'jobRecruitments' => $jobRecruitmentList
]);
}
public function ViewJobRecruitmentAction(Request $request, $id = 0)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$skillDetails = $em_goc->getRepository('CompanyGroupBundle:EntitySkill')->findAll();
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
// return new JsonResponse($encryptedDataArray);
$location = HumanResourceConstant::$location;
$salaryPer = HumanResourceConstant::$salaryPer;
$workExperience = HumanResourceConstant::$workExperience;
$jobOpeningStatus = HumanResourceConstant::$jobOpeningStatus;
$compatibility = HumanResourceConstant::$compatibility;
$jobType = HumanResourceConstant::$employeeType;
$educationDetail = $em->getRepository(EducationQualification::class)->findAll();
$jobRecruitments = $em->getRepository('ApplicationBundle:JobRecruitment')->find($id);
$em_goc = $this->getDoctrine()->getManager('company_group');
$applicantApplicationList = $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
array(
'jobPostId' => $id,
'CompanyId' => $companyId,
'appId' => $company_data->getAppId()
)
);
$applicantIdList = [];
foreach ($applicantApplicationList as $dt) {
$applicantIdList[] = $dt->getApplicantId();
}
$applicantList = ApplicantM::getApplicantList($em_goc, $applicantIdList);
$Approval_data = [
'exists' => 0,
'approvalId' => 0,
'roleType' => 0,
'required' => 0,
'acted' => 0,
'entity' => array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
'entityId' => $id,
];
if (in_array($request->getSession()->get(UserConstants::USER_TYPE), [1, 2, 5]))
$Approval_data = System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
return $this->render('ApplicationBundle:pages/human_resource/views:view_job_recruitment.html.twig', [
'page_title' => 'View Job RecruitmentAction',
'jobRecruitments' => $jobRecruitments,
'applicantApplicationList' => $applicantApplicationList,
'applicantList' => $applicantList,
// 'encryptedData' => $encryptedData,
'skills' => json_decode($jobRecruitments->getskills()),
'skillDetails' => $skillDetails,
'education' => json_decode($jobRecruitments->getEducations()),
'educationDetails' => $educationDetail,
'location' => $location,
'salaryPer' => $salaryPer,
'workExperience' => $workExperience,
'jobType' => $jobType,
'compatibility' => $compatibility,
'approval_status' => $jobRecruitments->getApproved(),
'jobOpeningStatus' => $jobOpeningStatus,
'approval_data' => $Approval_data,
'auto_created' => $jobRecruitments->getAutocreated(),
'document_log' => $jobRecruitments->getAutocreated() == 0 ? System::getDocumentLog(
$em,
array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
$id,
$jobRecruitments->getCreatedLoginId(),
$jobRecruitments->getEditedLoginId()
) : []
]);
}
public function ViewApplicantScheduleAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$em_goc = $this->getDoctrine()->getManager('company_group');
$applicantApplicationList = $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
array(
'jobPostId' => $id,
'CompanyId' => $companyId,
'appId' => $company_data->getAppId()
)
);
$applicantIdList = [];
foreach ($applicantApplicationList as $dt) {
$applicantIdList[] = $dt->getApplicantId();
}
$applicantList = ApplicantM::getApplicantList($em_goc, $applicantIdList);
return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_scheduled.html.twig', [
'page_title' => 'View Applicant Scheduled',
'applicantApplicationList' => $applicantApplicationList,
'applicantList' => $applicantList,
]);
}
public function ViewApplicantReportAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$em_goc = $this->getDoctrine()->getManager('company_group');
$applicantApplicationList = $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
array(
'jobPostId' => $id,
'CompanyId' => $companyId,
'appId' => $company_data->getAppId()
)
);
$applicantIdList = [];
foreach ($applicantApplicationList as $dt) {
$applicantIdList[] = $dt->getApplicantId();
}
$applicantList = ApplicantM::getApplicantList($em_goc, $applicantIdList);
return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_report.html.twig', [
'page_title' => 'View Applicant Report',
'applicantApplicationList' => $applicantApplicationList,
'applicantList' => $applicantList,
]);
}
public function createEmployeePerformanceEvaluationAction(Request $request, $id = 0)
{
$data = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable($em, $entity_id, $dochash,
$loginId, $approveRole, $approveHash, $id)
) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$data = $request->request;
$docId = HumanResource::createEmployeePerformanceEvaluation($em, $loginId, $id, $data, $companyId);
//now add Approval info
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'New Recruitment Document Added.'
);
$url = $this->generateUrl(
'view_employee_performance_evolution'
);
return $this->redirect($url . "/" . $docId);
}
}
$skill = $em->getRepository(Skill::class)->findAll();
$educationDetail = $em->getRepository(EducationQualification::class)->findAll();
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branch = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:employee_performance_evolution.html.twig',
array(
'page_title' => 'Create Employee Performance Evaluation',
'employeeIds' => $employeeIds,
'employeeType' => $employeeType,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
'skill' => $skill,
'educationDetail' => $educationDetail
)
);
}
public function ViewIndividualReviewAction()
{
return $this->render('ApplicationBundle:pages/human_resource/views:individual_review.html.twig',
array(
'page_title' => 'Individual Performance View',
)
);
}
public function EmployeeListBySkillPerformanceAction()
{
$em = $this->getDoctrine()->getManager();
$employee = $em->getRepository('ApplicationBundle:EmployeeDetails')->findAll();
$skill = $em->getRepository('ApplicationBundle:Skill')->findAll();
return $this->render('ApplicationBundle:pages/human_resource/list:employee_performance_evolution_list.html.twig',
array(
'page_title' => 'Employee Skill & Performance',
'employee' => $employee,
//'employeeSkill' => json_decode($employee->getSkill(),true),
'skill' => $skill,
)
);
}
public function setWorkPlaceAction(Request $req)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$docHash = '';
if ($req->request->has('XHRreq')) {
$docHash = HumanResource::HandelXHRreqForEmpWorkplace($em, $req);
return new JsonResponse([$docHash]);
}
if ($req->isMethod('GET')) {
$TwigData = HumanResource::TwigDataForEmployeeWorkplace($em);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:update_workplace.html.twig',
[
'page_title' => 'Set Workplace',
'employeeIds' => $TwigData['employeeIds']
]
);
}
if ($req->isMethod('POST')) {
$approveHash = $req->request->get('approvalHash');
$loginId = $req->getSession()->get(UserConstants::USER_LOGIN_ID);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
if ($isSignatureOk) {
$isSuccess = HumanResource::CreateOrUpdateForEmpWorkplace($em, $req, $companyId, false, $docHash);
if ($isSuccess) {
$this->addFlash(
'success',
'Workplace set!'
);
return $this->redirectToRoute('set_workplace');
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('set_workplace');
}
}
}
public function setWorkPlaceForAppAction(Request $req)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$docHash = HumanResource::HandelXHRreqForEmpWorkplace($em, $req);
if ($req->isMethod('GET')) {
$TwigData = HumanResource::TwigDataForEmployeeWorkplace($em);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:update_workplace.html.twig',
[
'page_title' => 'Set Workplace',
'employeeIds' => $TwigData['employeeIds']
]
);
}
if ($req->isMethod('POST')) {
$approveHash = $req->request->get('approvalHash');
$loginId = $req->getSession()->get(UserConstants::USER_LOGIN_ID);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
if ($isSignatureOk) {
$isSuccess = HumanResource::CreateOrUpdateForEmpWorkplace($em, $req, $companyId, false, $docHash);
if ($isSuccess) {
$this->addFlash(
'success',
'Workplace set!'
);
// return $this->redirectToRoute('set_workplace');
return new JsonResponse(array(
"success" => true
));
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
// return $this->redirectToRoute('set_workplace');
}
}
}
public function ViewMeetingAction(Request $req, $action = 0, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
if ($req->request->has('XHRreq')) {
return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em, $req)]);
}
if ($action === 'view') {
$response = HumanResource::TwigDataForScheduledMeetingView($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/views:scheduled_meeting_view.html.twig',
[
'page_title' => 'View Scheduled Meeting',
'duration' => $response['duration'],
'appId' => $response['appId'],
'publicView' => 0,
'meeting_data' => $response['meeting_data'],
'agenda_list' => $response['agenda_list'],
'id' => $req->query->get('view_meeting'),
'approval_data' => $response['approval_data'],
'document_log' => $response['document_log'],
'approval_status' => $response['approval_status'],
'created_by' => $response['created_by'],
'updated_at' => $response['updated_at'],
'auto_created' => 0,
]
);
}
if ($action === 'print') {
$response = HumanResource::TwigDataForScheduledMeetingView($em, $req, $id);
// $id = $req->query->get('print_meeting');
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$Authorizations = System::getSignatureListForDocumentPrint($em, array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'], $id);
return $this->render(
'ApplicationBundle:pages/human_resource/print:scheduled_meeting_print.html.twig',
array(
'page_title' => 'View Scheduled Meeting',
'duration' => $response['duration'],
'meeting_data' => $response['meeting_data'],
'agenda_list' => $response['agenda_list'],
'export' => 'pdf,print',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'Authorizations' => $Authorizations,
'red' => 0
)
);
}
}
public function UpdateMeetingMinutesAction(Request $req, $action = 0, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$scheduleId = $req->request->get('scheduleId');
$minuteText = $req->request->get('minuteText');
$agendaKey = $req->request->get('key');
$scheduledMeeting = $em->getRepository(ScheduledMeeting::class)
->find($scheduleId);
$agendaList = json_decode($scheduledMeeting->getAgendaList(), true);
foreach ($agendaList as $key => $item) {
if ($key == $agendaKey)
$agendaList[$key]['minutes'] = $minuteText;
}
$scheduledMeeting->setAgendaList(json_encode($agendaList));
$em->flush();
return new JsonResponse(array(
'success' => true
));
}
public function SendMeetingUpdatesAction(Request $req, $action = 0, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$session = $req->getSession();
$companyData = Company::getCompanyData($em, $companyId);
$scheduleId = $req->request->get('scheduleId');
$minuteText = $req->request->get('minuteText');
$agendaKey = $req->request->get('key');
$scheduledMeeting = $em->getRepository(ScheduledMeeting::class)
->find($scheduleId);
$sendEmailInvitationTo = json_decode($scheduledMeeting->getAllParticipantsNameEmail(), true);
if ($sendEmailInvitationTo == null)
$sendEmailInvitationTo = [];
$agendaList = json_decode($scheduledMeeting->getAgendaList(), true);
if ($agendaList == null)
$agendaList = [];
$EmployeeList = HumanResource::GetEmployeeList($em, []);
$meetingType = MeetingSchedulingConstant::$meetingType[$scheduledMeeting->getMeetingType()];
foreach ($sendEmailInvitationTo as $key => $email) {
$name = ucWords(str_replace("_", " ", $key));
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/meeting_scheduling:scheduled_meeting_update.html.twig';
$bodyData = array(
'name' => $name,
'gocId' => $session->get(UserConstants::USER_GOC_ID),
'appId' => $session->get(UserConstants::USER_APP_ID),
'email' => $email,
'meetingData' => $scheduledMeeting,
'meeting_type' => $meetingType,
'agenda_list' => $agendaList,
'companyData' => $companyData,
'employeeList' => $EmployeeList,
);
$attachments = [];
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_MEETING_',
'forwardToMailAddress' => $email,
'subject' => "Meeting Updates Arranged By - " . $companyData->getName() . " on " . $scheduledMeeting->getTitle() . ". ",
'fileName' => '',
'attachments' => $attachments,
'toAddress' => $email,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $companyId,
'companyImagePath' => $companyData->getImage()
));
}
return new JsonResponse(array(
'success' => true
));
}
public function meetingSchedulingAction(Request $req, $action = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$session = $req->getSession();
if ($req->request->has('XHRreq')) {
return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em, $req)]);
}
if ($action === 'list') {
$response = HumanResource::TwigDataForScheduledMeetingList($em, [0, null]);
return $this->render(
'ApplicationBundle:pages/human_resource/list:scheduled_meeting_list.html.twig',
[
'page_title' => 'Scheduled Meeting List',
'list' => $response
]
);
}
if ($req->isMethod('GET')) {
$response = HumanResource::twigDataForMeetingScheduling($em);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:meeting_scheduling.html.twig',
[
'page_title' => 'Schedule a Meeting',
'employeeIds' => $response['employeeIds'],
'branches' => $response['branches'],
'asset' => $response['asset'],
'rooms' => $response['rooms'],
'sales_orders' => $response['salesOrders'],
'purchase_orders' => $response['purchaseOrders'],
'meeting_types' => $response['meetingType'],
]
);
}
if ($req->isMethod('POST')) {
$approveHash = $req->request->get('approvalHash');
$approveRole = $req->request->get('approvalRole');
$loginId = $req->getSession()->get(UserConstants::USER_LOGIN_ID);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
$companyData = Company::getCompanyData($em, $companyId);
if ($isSignatureOk) {
$isSuccess = HumanResource::createOrUpdateDataForMeetingScheduling($em, $req);
if ($isSuccess) {
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
)
);
$meetingId = $isSuccess[1];
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
$meetingId,
$req->getSession()->get(UserConstants::USER_LOGIN_ID),
0, //normal meeting
0,
$this->get('mail_module')
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
$meetingId,
$loginId,
$approveRole,
$req->request->get('approvalHash')
);
$url = $this->generateUrl(
'view_scheduled_meeting'
);
return $this->redirect($url . "/" . $meetingId);
} else {
return new JsonResponse(array(
'success' => false
));
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('meeting_scheduling');
}
}
return $this->redirectToRoute('meeting_scheduling');
}
public function CreateTrainingScheduleAction(Request $req, $action = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$session = $req->getSession();
if ($req->request->has('XHRreq')) {
return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em, $req)]);
}
if ($action === 'list') {
$response = HumanResource::TwigDataForScheduledMeetingList($em, [1]);
return $this->render(
'ApplicationBundle:pages/human_resource/list:scheduled_meeting_list.html.twig',
[
'page_title' => 'Training Schedule List',
'list' => $response
]
);
}
if ($req->isMethod('GET')) {
}
if ($req->isMethod('POST')) {
$approveHash = $req->request->get('approvalHash');
$approveRole = $req->request->get('approvalRole');
$loginId = $req->getSession()->get(UserConstants::USER_LOGIN_ID);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
$companyData = Company::getCompanyData($em, $companyId);
if ($isSignatureOk) {
$isSuccess = HumanResource::createOrUpdateDataForMeetingScheduling($em, $req);
if ($isSuccess) {
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
)
);
$meetingId = $isSuccess[1];
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
$meetingId,
$req->getSession()->get(UserConstants::USER_LOGIN_ID),
'',
0,
$this->get('mail_module')
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
$meetingId,
$loginId,
$approveRole,
$req->request->get('approvalHash')
);
$url = $this->generateUrl(
'view_scheduled_meeting'
);
return $this->redirect($url . "/" . $meetingId);
} else {
return new JsonResponse(array(
'success' => false
));
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('create_training_schedule');
}
}
$response = HumanResource::twigDataForTrainingScheduling($em);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:create_training_schedule.html.twig',
[
'page_title' => 'Schedule a Training',
'employeeIds' => $response['employeeIds'],
'branches' => $response['branches'],
'asset' => $response['asset'],
'rooms' => $response['rooms'],
'courseList' => $response['courseList'],
'sales_orders' => $response['salesOrders'],
'purchase_orders' => $response['purchaseOrders'],
'meeting_types' => $response['meetingType'],
'skillList' => $response['skillList'],
]
);
}
public function ScheduledTrainingListAction(Request $req, $action = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$session = $req->getSession();
$response = HumanResource::TwigDataForScheduledMeetingList($em, [1]);
return $this->render(
'ApplicationBundle:pages/human_resource/list:scheduled_training_list.html.twig',
[
'page_title' => 'Scheduled Trainings ',
'list' => $response
]
);
}
public function ScheduledInterviewListAction(Request $req, $action = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$session = $req->getSession();
$response = HumanResource::TwigDataForScheduledMeetingList($em, [2]);
return $this->render(
'ApplicationBundle:pages/human_resource/list:scheduled_interview_list.html.twig',
[
'page_title' => 'Scheduled Interviews ',
'list' => $response
]
);
}
public function GetFilteredQuestionsAction(Request $request, $search = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($search == '' || $search == '_EMPTY_')
$Query = "SELECT * FROM questionnaire WHERE 1 limit 10;";
else
$Query = "SELECT * FROM questionnaire WHERE question_text like '%$search%' limit 10;";
$stmt = $em->getConnection()->prepare($Query);
$stmt->execute();
$queryResult = $stmt->fetchAll();
$parent_head_ids = [];
$queryResultIndexed = [];
foreach ($queryResult as $dt) {
$queryResultIndexed[$dt['question_id']] = $dt;
}
return new JsonResponse(array(
'data' => $queryResult,
'queryResultIndexed' => $queryResultIndexed,
));
}
public function CreateTrainingCourseAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$skills = $em->getRepository('ApplicationBundle:Skill')->findAll();
$courses = $em->getRepository('ApplicationBundle:TrainingCourse')->findAll();
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$skill = new TrainingCourse;
$skill->setTitle($request->request->get('name'));
$skill->setCourseHash($request->request->get('coursehash'));
$skill->setTrainingMaterialText($request->request->get('overview'));
$skill->setTaggedSkillHashes(json_encode($request->request->get('skill')));
$skill->setCompanyId($companyId);
//$skill->setEditFlag(1); //editable usually
$skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
//$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
//$skill->setAutocreated(0);
$em->persist($skill);
$em->flush();
}
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:create_training_course.html.twig',
[
'page_title' => 'Create Training Course',
'skills' => $skills,
'courses' => $courses
]
);
}
public function CreateEmployeeExpenseAllowanceSettingsAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extDocData = [];
$extDetailsData = [];
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)
) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'EmployeeExpenseAllowanceSettings';
DeleteDocument::$funcname($em, $id, 0);
$docId = HumanResource::CreateSalarySegregationPolicy($em, $request, $companyId, 0);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$doc_here = $this->getDoctrine()
->getRepository('ApplicationBundle:EmployeeExpenseAllowanceSettings')
->findOneBy(
array(
'id' => $docId
)
);
//notify
$this->addFlash(
'success',
'Settings Successfully Updated.'
);
$url = $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
'success',
// $url . "/" . $TransID,
$url . "/" . $docId,
"Journal"
);
return $this->redirect($url . "/" . $docId);
}
}
//for edits
if ($id == 0) {
} else {
$extDocData = $em->getRepository('ApplicationBundle:EmployeeExpenseAllowanceSettings')->findOneBy(
array(
'id' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDocData) {
if ($extDocData->getEditFlag() != 1) {
// $url = $this->generateUrl(
//// 'view_salary_segregation_policy'
// 'salary_segregation_policy'
// );
// return $this->redirect($url . "/" . $id);
} else {
// $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
// $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
// array(
// 'transactionId' => $id, ///material
//
// )
// );
}
} else {
}
}
$employeeIds = $em->getRepository("ApplicationBundle:Employee")->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$employeeExpenseAllowanceTypes = HumanResourceConstant::$employeeExpenseAllowanceTypes;
$Designation = $em->getRepository("ApplicationBundle:SysDepartmentPosition")->findAll();
$branch = $em->getRepository("ApplicationBundle:Branch")->findAll();
$departments = $em->getRepository("ApplicationBundle:SysDepartment")->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:create_employee_expense_allowance_settings.html.twig',
[
'page_title' => 'Employee Expense Allowance Settings',
'employeeIds' => $employeeIds,
'extId' => $id,
'extDocData' => $extDocData,
'employeeType' => $employeeType,
'employeeExpenseAllowanceTypes' => $employeeExpenseAllowanceTypes,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
]
);
}
public function EmployeeExpenseAllowanceSettingsListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$listData = HumanResource::GetDataForEmployeeExpenseAllowanceSettingsListAction($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render('ApplicationBundle:pages/human_resource/list:employee_expense_allowance_settings_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Expense Allowance Settings List',
// 'data' => SalesOrderM::GetClientList($em, [], $companyId),
// 'client_types' => Client::GetClientType($em, $companyId),
// 'region_list' => Client::RegionList($em, $companyId),
// 'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function salarySegAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extDocData = [];
$extDetailsData = [];
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'SalarySegregationPolicy';
DeleteDocument::$funcname($em, $id, 0);
$docId = HumanResource::CreateSalarySegregationPolicy($em, $request, $companyId, 0);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
3 //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$doc_here = $this->getDoctrine()
->getRepository('ApplicationBundle:SalarySegregationPolicy')
->findOneBy(
array(
'id' => $docId
)
);
//notify
$this->addFlash(
'success',
'Policy Successfully Updated.'
);
$url = $this->generateUrl(
'salary_segregation_policy'
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
'success',
// $url . "/" . $TransID,
$url . "/" . $docId,
"Journal"
);
return $this->redirect($url . "/" . $docId);
}
}
//for edits
if ($id == 0) {
} else {
$extDocData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
array(
'id' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDocData) {
if ($extDocData->getEditFlag() != 1) {
// $url = $this->generateUrl(
//// 'view_salary_segregation_policy'
// 'salary_segregation_policy'
// );
// return $this->redirect($url . "/" . $id);
} else {
// $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
// $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
// array(
// 'transactionId' => $id, ///material
//
// )
// );
}
} else {
}
}
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branch = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:salary_segregation_policy.html.twig',
[
'page_title' => 'Salary Segregation Policy',
'employeeIds' => $employeeIds,
'extId' => $id,
'extDocData' => $extDocData,
'employeeType' => $employeeType,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
]
);
}
public function GetSalarySegregationDataForEmployeeEntryAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->request->has('salSagDataReq')) {
$ajaxData = HumanResource::handelXhrForSalSeg($em, $request);
return new JsonResponse($ajaxData);
}
return new JsonResponse(array('success' => false));
}
public function WorkHourPolicyAction(Request $req, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($req);
$extData = [];
if ($id != 0) {
$extData = $em->getRepository('ApplicationBundle:WorkHourPolicy')
->findOneBy(
array(
'id' => $id
)
);
}
if ($req->isMethod('POST')) {
$storeDataRes = HumanResource::checkSignature($em, $req);
if ($storeDataRes['hasErr']) {
$msg = $storeDataRes['msg'];
$this->addFlash(
'error',
$msg
);
return $this->redirectToRoute('work_hour_policy');
} else {
HumanResource::storeDataForWhPolicy($em, $req, $companyId);
$this->addFlash(
'success',
'Policy Successfully Created!'
);
return $this->redirectToRoute('work_hour_policy');
}
}
$twigData = HumanResource::twigDataForWorkHourPolicy($em);
$timeZonesArray = array();
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:work_hour_policy.html.twig',
[
'page_title' => 'Work Hour Policy',
'extId' => $id,
'extData' => $extData,
'employeeIds' => $twigData['employeeIds'],
'employeeType' => $twigData['employeeType'],
'Designation' => $twigData['Designation'],
'branch' => $twigData['branch'],
'department' => $twigData['department'],
]
);
}
public function WorkHourPolicyListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$listData = HumanResource::GetDataForWorkHourPolicyListAction($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render('ApplicationBundle:pages/human_resource/list:work_hour_policy_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Work Hour Policy List',
// 'data' => SalesOrderM::GetClientList($em, [], $companyId),
// 'client_types' => Client::GetClientType($em, $companyId),
// 'region_list' => Client::RegionList($em, $companyId),
// 'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function WorkPlacePolicyListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$workplacePolicyDetails = $em->getRepository('ApplicationBundle:EmployeeWorkplace')->findAll();
// $employee = $em->getRepository('ApplicationBundle:Employee')->findAll();
return $this->render('ApplicationBundle:pages/human_resource/list:work_place_policy_list.html.twig', array(
'page_title' => 'Work Place Policy List',
'workplacePolicyDetails' => $workplacePolicyDetails,
// 'employee'=>$employee
));
}
public function workPlacePolicyAction(Request $data, $id)
{
$em = $this->getDoctrine()->getManager();
$workPlacePolicy = $em->getRepository('ApplicationBundle:EmployeeWorkplace')->find($id);
$employee = $em->getRepository(Employee::class)->findAll();
$Approval_data = System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['EmployeeWorkplace'],
$id,
$data->getSession()->get(UserConstants::USER_LOGIN_ID)
);
$ApprovalStatus = GeneralConstant::$approvalStatus;
return $this->render('ApplicationBundle:pages/human_resource/views:viewWorkPlacePolicy.html.twig', array(
'page_title' => 'Work Place Policy View',
'workPlacePolicy' => $workPlacePolicy,
'employee' => $employee,
'approval_data' => $Approval_data,
'approval_status' => $workPlacePolicy->getApproved(),
'id' => $id,
));
}
public function SalarySegregationPolicyListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$listData = HumanResource::GetDataForSalarySegregationPolicyListAction($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render('ApplicationBundle:pages/human_resource/list:salary_segregation_policy_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Salary Segregation Policy List',
// 'data' => SalesOrderM::GetClientList($em, [], $companyId),
// 'client_types' => Client::GetClientType($em, $companyId),
// 'region_list' => Client::RegionList($em, $companyId),
// 'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function HolidayCalendarListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:HolidayCalendar')
->findBy(
array(
// 'status' => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request)
// 'approved' => GeneralConstant::APPROVED,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
// 'doc_date' => $entry->getSalesReplacementDate(),
'id' => $entry->getHolidayCalendarId(),
'title' => $entry->getHoliDayTitle(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
// 'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render('ApplicationBundle:pages/human_resource/list:holiday_calendar_list.html.twig',
array(
'page_title' => 'Holiday Calendar List',
'data' => $data
)
);
}
public function PayrollPolicyListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$listData = HumanResource::GetDataForPayrollPolicyListAction($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render('ApplicationBundle:pages/human_resource/list:payroll_policy_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Payroll Policy List',
// 'data' => SalesOrderM::GetClientList($em, [], $companyId),
// 'client_types' => Client::GetClientType($em, $companyId),
// 'region_list' => Client::RegionList($em, $companyId),
// 'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function payslipAction(Request $req, $action = 0, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$attendanceSource = HumanResourceConstant::$attendanceSources;
if ($action === 'list') {
$response = HumanResource::twigDataForPayslipList($em);
$approval_status = GeneralConstant::$approvalAction;
return $this->render(
'ApplicationBundle:pages/human_resource/list:payslip_list.html.twig',
[
'page_title' => 'Payslip List',
'reports' => $response,
'approval_status' => $approval_status
]
);
}
if ($action === 'view') {
$response = HumanResource::twigDataForPayslipViewAndPrint($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/views:payslip_view.html.twig',
[
'page_title' => 'View Payslip',
'approval_data' => $response['approval_data'],
'payslip' => $response['payslip'],
'bankAccount' => $response['bankAccount'],
'tin' => $response['tin'],
'employeeCode' => $response['employeeCode'],
'earningValues' => $response['earningValues'],
'facilityValues' => $response['facilityValues'],
'deductionValues' => $response['deductionValues'],
'document_log' => $response['document_log'],
'approval_status' => $response['approval_status'],
'created_by' => $response['created_by'],
'updated_at' => $response['updated_at'],
'employeeId' => $response['employeeId'],
'totalAttendance' => $response['totalPresent'],
'leaveList' => HumanResourceConstant::$LeaveType,
'AttReportData' => $response['AttReportData'],
// 'attendanceLog' => $response['attendanceLog'],
'attendanceSource' => $attendanceSource,
'auto_created' => 0,
]
);
}
if ($action === 'print') {
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$Authorizations = System::getSignatureListForDocumentPrint($em, array_flip(GeneralConstant::$Entity_list)['Payslip'], $id);
$response = HumanResource::twigDataForPayslipViewAndPrint($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/print:payslip_print.html.twig',
array(
'page_title' => 'Print Payslip',
'export' => 'pdf,print',
'payslip' => $response['payslip'],
'bankAccount' => $response['bankAccount'],
'tin' => $response['tin'],
'employeeCode' => $response['employeeCode'],
'earningValues' => $response['earningValues'],
'facilityValues' => $response['facilityValues'],
'deductionValues' => $response['deductionValues'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'Authorizations' => $Authorizations,
'totalAttendance' => $response['totalPresent'],
'leaveList' => HumanResourceConstant::$LeaveType,
'AttReportData' => $response['AttReportData'],
'attendanceSource' => $attendanceSource,
'red' => 0
)
);
}
if ($req->isMethod('POST')) {
$sigRes = HumanResource::checkSignature($em, $req);
if ($sigRes['hasErr']) {
$msg = $sigRes['msg'];
return new JsonResponse(['success' => false, 'msg' => $msg]);
}
HumanResource::storeDataForPayslip($em, $req);
return new JsonResponse(['success' => true]);
}
}
public function applicantInfoAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$skillDetails = $em->getRepository(EntitySkill::class)->findAll();
$companyId = $this->getLoggedUserCompanyId($request);
$gender = HumanResourceConstant::$sex;
$blood = HumanResourceConstant::$BloodGroup;
$userId = $session->get(UserConstants::USER_ID);
$encData = $request->query->has('ref') ? $request->query->get('ref') : '';
$education = array(
'instituteName' => $request->get('instituteName'),
'courseOfStudy' => $request->get('courseOfStudy'),
'courseStartDate' => $request->get('courseStartDate'),
'courseEndDate' => $request->get('courseEndDate'),
'result' => $request->get('result'),
'grade' => $request->get('grade'),
'degree' => $request->get('degree'),
);
$workExperience = array(
'title' => $request->get('title'),
'companyName' => $request->get('companyName'),
'jobStartDate' => $request->get('jobStartDate'),
'jobEndDate' => $request->get('jobEndDate'),
'description' => $request->get('description'),
);
$certificate = array(
'certificatename' => $request->get('certificatename'),
'issuedDate' => $request->get('issuedDate'),
);
$courses = array(
'courseName' => $request->get('courseName'),
'date' => $request->get('date'),
'duration' => $request->get('duration')
);
$languages = array(
'languageName' => $request->get('languageName'),
'writtenSkill' => $request->get('writtenSkill'),
'verbalSkill' => $request->get('verbalSkill'),
);
if ($request->isMethod('POST')) {
if ($consultantDetails)
$consultant = $consultantDetails;
else
$consultant = new EntityApplicantDetails();
$consultant->setApplicationText($request->request->get('applicationText'));
$consultant->setFirstname($request->request->get('firstname'));
$consultant->setLastname($request->request->get('lastname'));
$consultant->setIsImgLegal($request->request->get('is_img_legal'));
$consultant->setNid($request->request->get('nid'));
$consultant->setDob(new \DateTime($request->get('dob')));
$consultant->setSex($request->request->get('sex'));
$consultant->setFather($request->request->get('father'));
$consultant->setMother($request->request->get('mother'));
$consultant->setBlood($request->request->get('blood'));
$consultant->setPhone($request->request->get('phone'));
$consultant->setCountry($request->request->get('country'));
$consultant->setPostalCode($request->request->get('postalCode'));
$consultant->setCurrAddr($request->request->get('curr_addr'));
$consultant->setSkill(json_encode($request->request->get('skill')));
$consultant->setEmergencyContactNumber($request->request->get('emm_contact'));
$consultant->setCurrentEmployment($request->request->get('currentEmployment'));
$consultant->setTin($request->request->get('tin'));
$consultant->setEducationData(json_encode($education));
$consultant->setWorkExperienceData(json_encode($workExperience));
$consultant->setCertificateData(json_encode($certificate));
$consultant->setCoursesData(json_encode($courses));
$consultant->setLanguagesData(json_encode($languages));
$consultant->setWorkExperienceYear($request->request->get('workExperienceYear'));
//$consultant->setApplyForConsultant(1);
$em->persist($consultant);
$em->flush();
$path = "";
$defaultProductImage = '';
$uploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/applicantCv/';
$uploadedFile = $request->files->get('docUpload');
if ($uploadedFile != null) {
$fileName = 'cv' . $consultantDetails->getApplicantId() . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$uploadedFile->move($upl_dir, $path);
$defaultProductImage = 'uploads/applicantCv/' . $path;
$consultant->setDocImage($defaultProductImage);
$em->flush();
}
$this->addFlash(
'success',
'Data Updated.'
);
if ($encData != '') {
$url = $this->generateUrl(
'applicant_job_recruitment_view'
);
return $this->redirect($url . '?auto_apply=1&encData=' . $encData);
}
$url = $this->generateUrl(
'job_recruitment_list_applicant'
);
return $this->redirect($url);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig', array(
'page_title' => 'My Information ',
'gender' => $gender,
'blood' => $blood,
'consultantDetails' => $consultantDetails,
'education' => json_decode($consultantDetails->getEducationData(), true),
'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
'certificate' => json_decode($consultantDetails->getCertificateData(), true),
'courses' => json_decode($consultantDetails->getCoursesData(), true),
'languages' => json_decode($consultantDetails->getLanguagesData(), true),
'skill' => json_decode($consultantDetails->getSkill(), true),
'skillDetails' => $skillDetails
));
// $em = $this->getDoctrine()->getManager('company_group');
// $applicantRepo = $em->getRepository(EntityApplicantDetails::class);
// $skillDetails = $em->getRepository(EntitySkill::class)->findAll();
//
//
// if ($req->isMethod('POST')) {
// $applicant = $applicantRepo->find($id);
//
// if ($req->files->get('img')) {
// $ImgName = HumanResource::StoreFiles($req->files->get('img'), 'Applicant');
// $applicant->setImage($ImgName);
// }
//
// $applicant->setFirstname($req->request->get('firstname'));
// $applicant->setLastname($req->request->get('lastname'));
// $applicant->setIsImgLegal($req->request->get('is_img_legal'));
// $applicant->setNid($req->request->get('nid'));
// $applicant->setDob(HumanResource::StringToDate($req->request->get('dob')));
// $applicant->setSex($req->request->get('sex'));
// $applicant->setFather($req->request->get('father'));
// $applicant->setMother($req->request->get('mother'));
// $applicant->setSpouse($req->request->get('spouse'));
// $applicant->setChild1($req->request->get('child_1'));
// $applicant->setChild2($req->request->get('child_2'));
// $applicant->setBlood($req->request->get('blood'));
// $applicant->setPhone($req->request->get('phone'));
// $applicant->setOAuthEmail($req->request->get('oauth_email'));
// $applicant->setCurrAddr($req->request->get('curr_addr'));
// $applicant->setPermAddr($req->request->get('perm_addr'));
// $applicant->setEmmContact($req->request->get('emm_contact'));
//
// $applicant->setInst1($req->request->get('inst1'));
// $applicant->setYr1($req->request->get('yr1'));
// $applicant->setDur1($req->request->get('dur1'));
// $applicant->setInst2($req->request->get('inst2'));
// $applicant->setYr2($req->request->get('yr2'));
// $applicant->setDur2($req->request->get('dur2'));
// $applicant->setInst3($req->request->get('inst3'));
// $applicant->setYr3($req->request->get('yr3'));
// $applicant->setDur3($req->request->get('dur3'));
// $applicant->setEinst1($req->request->get('einst1'));
// $applicant->setEyr1($req->request->get('eyr1'));
// $applicant->setEdeg1($req->request->get('edeg1'));
// $applicant->setEinst2($req->request->get('einst2'));
// $applicant->setEyr2($req->request->get('eyr2'));
// $applicant->setEdeg2($req->request->get('edeg2'));
// $applicant->setEinst3($req->request->get('einst3'));
// $applicant->setEyr3($req->request->get('eyr3'));
// $applicant->setEdeg3($req->request->get('edeg3'));
//
// $em->persist($applicant);
// $em->flush();
//
// return $this->render(
// 'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
// [
// 'page_title' => 'Applicant Info',
// 'applicant_info' => $applicant,
// 'blood' => HumanResourceConstant::$BloodGroup,
// 'gender' => HumanResourceConstant::$sex,
// 'skillDetails' => $skillDetails,
// 'HasUpdateMode' => true,
// ]
// );
// }
//
// if ($id) {
// $applicant = $applicantRepo->find($id);
//
// return $this->render(
// 'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
// [
// 'page_title' => 'Applicant Info',
// 'applicant_info' => $applicant,
// 'blood' => HumanResourceConstant::$BloodGroup,
// 'gender' => HumanResourceConstant::$sex,
// 'skillDetails' => $skillDetails,
// 'HasUpdateMode' => false,
// ]
// );
// }
//
// $google_client = new Google_Client();
// $google_client->setClientId('916737688016-l2qfmb9p37cumudkaqpu8s7ndngq9una.apps.googleusercontent.com');
// $google_client->setClientSecret('BEWpEBRvv3-hSoB4cGBrVB3z');
// $google_client->setRedirectUri('http://localhost/applicant_info');
// $google_client->addScope('email');
// $google_client->addScope('profile');
}
public function applicantDashboardAction()
{
return new JsonResponse(['this is applicant dashboard']);
}
public function resignApplicationAction(Request $req, $id)
{
$em = $this->getDoctrine()->getManager();
if ($req->request->has('xhrReq')) {
$response = HumanResource::HandelXhrForResignApplication($em, $req);
return new JsonResponse($response);
}
if ($req->isMethod('GET')) {
$applicant = $em->getRepository(EmployeeDetails::class)->findBy(['emp_status' => 1]);
$resignReason = HumanResourceConstant::$resignReason;
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:resign_application.html.twig',
[
'page_title' => 'Resign Application',
'employeeIds' => $applicant,
'resignReasons' => $resignReason,
'HasUpdateMode' => false,
]
);
}
if ($req->isMethod('POST')) {
$approveHash = $req->request->get('approvalHash');
$loginId = $req->getSession()->get(UserConstants::USER_LOGIN_ID);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
if ($isSignatureOk) {
$response = HumanResource::storeResignApplicationData($em, $req);
if ($response) {
return $this->redirectToRoute(
'view_resign_application',
array('id' => $response->getResignApplicationId()),
Response::HTTP_MOVED_PERMANENTLY
);
}
} else {
$this->addFlash(
'error',
'Invalid Approval Hash!'
);
return $this->redirectToRoute('resign_application');
}
}
}
public function viewResignApplicationAction(Request $req, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$response = HumanResource::twigDataForResignApplicationView($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/views:resign_application_view.html.twig',
[
'page_title' => 'View Resign Application',
'approval_data' => $response['approval_data'],
'application' => $response['application'],
'applicant' => $response['applicant'],
'document_log' => $response['document_log'],
'approval_status' => $response['approval_status'],
'created_by' => $response['created_by'],
'updated_at' => $response['updated_at'],
'auto_created' => 0,
]
);
}
public function printResignApplicationAction(Request $req, $id)
{
if ($id) {
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$authorizations = System::getSignatureListForDocumentPrint($em, array_flip(GeneralConstant::$Entity_list)['ResignApplication'], $id);
$response = HumanResource::twigDataForResignApplicationView($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/print:resign_application_print.html.twig',
array(
'page_title' => 'Print Resign Application',
'export' => 'pdf,print',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'application' => $response['application'],
'applicant' => $response['applicant'],
'Authorizations' => $authorizations,
'red' => 0
)
);
}
return new JsonResponse(array(
'success' => false,
'msg' => 'Wrong URL format! Please try with application ID'
));
}
public function listResignApplicationAction(Request $req)
{
$em = $this->getDoctrine()->getManager();
$response = HumanResource::getResignApplicationList($em, $req);
return $this->render("ApplicationBundle:pages/human_resource/list:resign_application_list.html.twig", array(
'page_title' => 'Resign Application List',
'applications' => $response,
));
}
public function viewNocApprovalAction(Request $req, $id)
{
$em = $this->getDoctrine()->getManager();
$response = HumanResource::twigDataForNocView($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/views:noc_view.html.twig',
[
'page_title' => 'View NOC',
'approval_data' => $response['approval_data'],
'noc_application' => $response['noc_application'],
'resign_application' => $response['resign_application'],
'applicant' => $response['applicant'],
'document_log' => $response['document_log'],
'approval_status' => $response['approval_status'],
'created_by' => $response['created_by'],
'updated_at' => $response['updated_at'],
'auto_created' => 0,
]
);
}
public function printNocApprovalAction(Request $req, $id)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$Authorizations = System::getSignatureListForDocumentPrint($em, array_flip(GeneralConstant::$Entity_list)['NocApproval'], $id);
$response = HumanResource::twigDataForNocView($em, $req, $id);
return $this->render(
'ApplicationBundle:pages/human_resource/print:noc_print.html.twig',
[
'page_title' => 'Print NOC',
'noc_application' => $response['noc_application'],
'resign_application' => $response['resign_application'],
'applicant' => $response['applicant'],
'export' => 'pdf,print',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'Authorizations' => $Authorizations,
'red' => 0
]
);
}
public function createHolidayAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$entity_id = array_flip(GeneralConstant::$Entity_list)['HolidayCalendar']; //change
$dochash = $request->request->get('doc_hash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'HolidayCalendar';
$doc_id = $id;
DeleteDocument::$funcname($em, $doc_id, 0);
if ($id != 0)
$HolidayCalender = $em->getRepository(HolidayCalendar::class)->find($id);
else
$HolidayCalender = new HolidayCalendar;
$HolidayCalender->setDocumentHash($request->request->get('doc_hash'));
$HolidayCalender->setHoliDayTitle($request->request->get('holidayCalendarTitle'));
$HolidayCalender->setEmployeeIds(json_encode($request->request->get('employee')));
$HolidayCalender->setEmployeeTypeIds(json_encode($request->request->get('emp_status')));
$HolidayCalender->setDesignationIds(json_encode($request->request->get('desg', [])));
$HolidayCalender->setDepartmentIds(json_encode($request->request->get('dept', [])));
$HolidayCalender->setBranchIds(json_encode($request->request->get('branch', [])));
$HolidayCalender->setLevelSelectionStr($request->get('levelSelectionStr', ''));
$HolidayCalender->setLevels(json_encode(HumanResource::getLevelsFromLevelSelectionStr($request->get('levelSelectionStr', ''))));
$HolidayCalender->setCompanyId($companyId);
$HolidayCalender->setTypeHash('HD');
$HolidayCalender->setEditFlag(1); //editable usually
$HolidayCalender->setPrefixHash($request->request->get('prefix'));
$HolidayCalender->setAssocHash($request->request->get('assoc'));
$HolidayCalender->setNumberHash($request->request->get('number_hash'));
$HolidayCalender->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$HolidayCalender->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
$HolidayCalender->setAutocreated(0);
//
// $arr = [
// 'date' =>$request->request->get('start_date'),
// 'title' => $request->request->get('title'),
// ];
//
// $HolidayCalender->setData(json_encode($arr));
$em->persist($HolidayCalender);
$em->flush();
$indHolidays = [];
if ($request->request->has('start_date'))
$indHolidays = $request->request->get('start_date');
foreach ($indHolidays as $ind => $dateRangeStr) {
$currRow = $request->request->get('row')[$ind];//string
$holidayTitle = $request->request->get('title')[$ind];//string
$currStartDate = $request->request->get('start_date')[$ind];//string
$currEndDate = $request->request->get('end_date')[$ind];//string
$HolidayDate = new HolidayCalendarDates();
$HolidayDate->setHolidayCalendarId($HolidayCalender->getHolidayCalendarId());
$HolidayDate->setDateRange($currStartDate . '-' . $currEndDate);//string
$HolidayDate->setStartDate(new \DateTime($currStartDate));//date
$HolidayDate->setEndDate(new \DateTime($currEndDate . ' 23:59:59'));//date
$HolidayDate->setHolidayTitle($holidayTitle);
// $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year',null));
$HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year_' . $currRow, null));
$HolidayDate->setAllDayFlag($request->request->get('all_day_flag_' . $currRow, 1));
$em->persist($HolidayDate);
$em->flush();
}
$options = [];
$entity = array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'];
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
System::setApprovalInfo(
$em,
$options,
$entity,
$HolidayCalender->getHolidayCalendarId(),
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$em,
$entity,
$HolidayCalender->getHolidayCalendarId(),
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$url = $this->generateUrl(
'view_holiday_calendar'
);
return $this->redirect($url . "/" . $HolidayCalender->getHolidayCalendarId());
}
}
$em = $this->getDoctrine()->getManager();
$branches = $em->getRepository(Branch::class)->findAll();
$employee = $em->getRepository(Employee::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$departmentPositions = $em->getRepository(SysDepartmentPosition::class)->findAll();
$EmploymentStatus = HumanResourceConstant::$employeeType;
$em = $this->getDoctrine()->getManager();
$extDocData = [];
if ($id != 0)
$extDocData = $em->getRepository(HolidayCalendar::class)->find($id);
return $this->render(
'ApplicationBundle:pages/human_resource/input_forms:create_holiday.html.twig',
[
'page_title' => 'Create Holiday',
'branches' => $branches,
'id' => $id,
'extDocData' => $extDocData,
'departments' => $departments,
'departmentPositions' => $departmentPositions,
'employeeStatus' => $EmploymentStatus,
'employeeIds' => $employee,
'holidayCalendarList' => $em->getRepository('ApplicationBundle:HolidayCalendar')
->findBy(array())
]
);
}
public function HolidayViewAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$HolidaysCalendar = $em->getRepository(HolidayCalendar::class)->find($id);
$holidayCalendarDetails = $em->getRepository('ApplicationBundle:HolidayCalendarDates')
->findBy(array(
'holidayCalendarId' => $id
));
$Approval_data = System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
return $this->render('ApplicationBundle:pages/human_resource/views:holidays_view.html.twig', array(
'page_title' => 'View Holiday',
'holidays' => $HolidaysCalendar,
'holidayCalendarDetails' => $holidayCalendarDetails,
'approval_status' => $HolidaysCalendar->getApproved(),
'approval_data' => $Approval_data,
'auto_created' => $HolidaysCalendar->getAutocreated(),
'document_log' => $HolidaysCalendar->getAutocreated() == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
$id,
$HolidaysCalendar->getCreatedLoginId(),
$HolidaysCalendar->getEditedLoginId()
) : []
));
}
public function GetHolidayDetailsAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$holidayCalendar = $em->getRepository('ApplicationBundle:HolidayCalendar')
->findOneBy(array(
'holidayCalendarId' => $id
));
$holidayCalendarDetails = $em->getRepository('ApplicationBundle:HolidayCalendarDates')
->findBy(array(
'holidayCalendarId' => $id
));
$holidayList = [];
foreach ($holidayCalendarDetails as $det) {
$dateDet = array(
'title' => $det->getHolidayTitle(),
'startDate' => $det->getStartDate()->format('Y-m-d'),
'endDate' => $det->getEndDate()->format('Y-m-d'),
);
$holidayList[] = $dateDet;
}
return new JsonResponse(
array(
'success' => true,
'holidayList' => $holidayList
)
);
}
public function GetHolidayListByEmployeeIdAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$options = [];
$options['employeeId'] = $id;
HumanResource::getFilteredHolidaysSingle($em, $options);
$holidayCalendar = $em->getRepository('ApplicationBundle:HolidayCalendar')
->findOneBy(array(
'holidayCalendarId' => $id
));
$holidayCalendarDetails = $em->getRepository('ApplicationBundle:HolidayCalendarDates')
->findBy(array(
'holidayCalendarId' => $id
));
$holidayList = [];
foreach ($holidayCalendarDetails as $det) {
$dateDet = array(
'title' => $det->getHolidayTitle(),
'startDate' => $det->getStartDate()->format('Y-m-d'),
'endDate' => $det->getEndDate()->format('Y-m-d'),
);
$holidayList[] = $dateDet;
}
return new JsonResponse(
array(
'success' => true,
'holidayList' => $holidayList
)
);
}
public function createQuestionAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$question = new Questionnaire();
$question->setQuestionTitle($request->request->get('questionTitle', ''));
$question->setQuestionText($request->request->get('questionText', ''));
$question->setIsForPlanningItem($request->request->has('forPlanningItem') ? 1 : 0);
$question->setIsForInterview($request->request->has('forInterview') ? 1 : 0);
$question->setIsForMock($request->request->has('forMock') ? 1 : 0);
$question->setIsForTraining($request->request->has('forTraining') ? 1 : 0);
$question->setTaggedSkillHashes($request->request->get('skillHash'));
$question->setCorrectAnswers(json_encode($request->request->get('correctAns')));
$question->setCompanyId($companyId);
$optionData = [];
foreach ($request->request->get('optionText') as $key => $val) {
$option = array(
'index' => $request->request->get('optionIndex')[$key],
'text' => $val,
);
$optionData[] = $option;
}
$question->setOptions(json_encode($optionData));
$question->setQuestionValueWeight(1);
$question->setQuestionText($request->request->get('questionText'));
$question->setUniqueHash('_NONE_');
$question->setType($request->request->get('type', 0));
//$skill->setEditFlag(1); //editable usually
$question->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
//$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
//$skill->setAutocreated(0);
$em->persist($question);
$em->flush();
$questionId = $question->getQuestionId();
$file_path_list = [];
if ($questionId != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'Question', $questionId);
$storePath = 'uploads/Questionnaire/';
$path = "";
$file_path = "";
$session = $request->getSession();
// MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'QUES_' . $questionId . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('Questionnaire');
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($questionId);
$EntityFile->setEntityIdField('questionId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$question->setFiles(implode(',', $file_path_list));
$em->flush();
}
if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
if ($question)
return new JsonResponse(
array(
'id' => $questionId,
'value' => $questionId,
'question_id' => $questionId,
'text' => $question->getQuestionText(),
'question_text' => $question->getQuestionText(),
'question_title' => $question->getQuestionTitle(),
'files' => explode(',', $question->getFiles()),
'options' => json_decode($question->getFiles(), true),
'answer_text' => '',
'success' => true
)
);
else
return new JsonResponse(
array(
'success' => false
)
);
}
}
$skillDetails = $em->getRepository(Skill::class)->findAll();
$skillListObj = [];
$skillListArray = [];
foreach ($skillDetails as $skillDetail) {
$dt = array(
'id' => $skillDetail->getSkillId(),
'name' => $skillDetail->getName(),
'hash' => $skillDetail->getUniqueHash(),
);
$skillListArray[] = $dt;
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:createQuestion.html.twig', array(
'page_title' => 'Create Question',
'skiillDetails' => $skillDetails,
'skillListArray' => $skillListArray,
));
}
public function createSkillAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$skill = new Skill;
$skill->setName($request->request->get('skillName'));
$skill->setParentId($request->request->get('parentName'));
$skill->setUniqueHash($request->request->get('uniqueHash'));
$skill->setCompanyId($companyId);
//$skill->setEditFlag(1); //editable usually
$skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
//$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
//$skill->setAutocreated(0);
$em->persist($skill);
$em->flush();
}
$skillDetails = $em->getRepository(Skill::class)->findAll();
return $this->render('ApplicationBundle:pages/human_resource/input_forms:createSkill.html.twig', array(
'page_title' => 'Create Skill',
'skiillDetails' => $skillDetails,
));
}
public function createEducationQualificationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$new = new EducationQualification;
$new->setName($request->request->get('educationName'));
$new->setParentId($request->request->get('parentName'));
$new->setUniqueHash($request->request->get('uniqueHash'));
$new->setCompanyId($companyId);
//$skill->setEditFlag(1); //editable usually
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
//$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
//$skill->setAutocreated(0);
$em->persist($new);
$em->flush();
}
$educationDetails = $em->getRepository(EducationQualification::class)->findAll();
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_education.html.twig', array(
'page_title' => 'Create Education',
'educationDetails' => $educationDetails,
));
}
public function createEvaluationCategoryAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$new = new EvaluationCategory;
$new->setName($request->request->get('name'));
$new->setBranch($request->request->get('branch'));
$new->setSelectionType($request->request->get('selection_type'));
$new->setEmployeeIds($request->request->get('selected_employeeIds'));
$new->setEmployeeTypeIds($request->request->get('employee_types'));
$new->setDesignationIds($request->request->get('designation'));
$new->setDesignationIds($request->request->get('designation'));
$new->setmark($request->request->get('mark'));
$new->setSkills(json_encode($request->request->get('skill')));
$new->setLevelSelectionStr($request->request->get('levelSelectionStr'));
$new->setCompanyId($companyId);
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$em->persist($new);
$em->flush();
}
$skill = $em->getRepository(Skill::class)->findAll();
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branch = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_evaluation_category.html.twig', array(
'page_title' => 'Create Evaluation Category',
'employeeIds' => $employeeIds,
'employeeType' => $employeeType,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
'skill' => $skill,
));
}
}
public function createWorkplaceHarassmentAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
//$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branches = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$harassmentType = HumanResourceConstant::$harrasmentType;
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_workplace_harrasment.html.twig', array(
'page_title' => 'Create Workplace Harrasment',
'employeeIds' => $employeeIds,
'branches' => $branches,
'harassmentType' => $harassmentType,
'departments' => $department,
'designationIds' => $Designation
));
}
public function ViewHarasssmentComplainAction()
{
return $this->render('ApplicationBundle:pages/human_resource/views:view_harassment_compalin.html.twig', array(
'page_title' => 'View Harassment Complain',
));
}
public function createWorkplaceViolenceAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
//$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branches = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$harassmentType = HumanResourceConstant::$harrasmentType;
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:register_workplace_complaint.html.twig', array(
'page_title' => 'Register Complaint',
'employeeIds' => $employeeIds,
'branches' => $branches,
'harassmentType' => $harassmentType,
'departments' => $department,
'designationIds' => $Designation
));
}
public function createBonusPolicyAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extDocData = [];
$extDetailsData = [];
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['BonusPolicy']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'BonusPolicy';
DeleteDocument::$funcname($em, $id, 0);
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$docId = HumanResource::createBonusPolicy($em, $request, $companyId, $loginId, 0);
//now add Approval info
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['BonusPolicy']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$doc_here = $this->getDoctrine()
->getRepository('ApplicationBundle:BonusPolicy')
->findOneBy(
array(
'id' => $docId
)
);
//notify
$this->addFlash(
'success',
'Policy Successfully Updated.'
);
$url = $this->generateUrl(
'view_bonus_policy'
);
// System::AddNewNotification(
// $this->container->getParameter('notification_enabled'),
// $this->container->getParameter('notification_server'),
// $request->getSession()->get(UserConstants::USER_APP_ID),
// $request->getSession()->get(UserConstants::USER_COMPANY_ID),
// "Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
// 'pos',
// System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
// 'success',
// // $url . "/" . $TransID,
// $url . "/" . $docId,
// "Journal"
//
// );
return $this->redirect($url . "/" . $docId);
}
}
//for edits
if ($id == 0) {
} else {
$extDocData = $em->getRepository('ApplicationBundle:BonusPolicy')->findOneBy(
array(
'id' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDocData) {
if ($extDocData->getEditFlag() != 1) {
// $url = $this->generateUrl(
//// 'view_salary_segregation_policy'
// 'salary_segregation_policy'
// );
// return $this->redirect($url . "/" . $id);
} else {
// $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
// $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
// array(
// 'transactionId' => $id, ///material
//
// )
// );
}
} else {
}
}
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branch = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_bonus_policy.html.twig', array(
'page_title' => 'Create Bonus Policy',
'employeeIds' => $employeeIds,
'employeeType' => $employeeType,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
));
}
public function BonusPolicyListAction()
{
$em = $this->getDoctrine()->getManager();
$bonusPolicy = $em->getRepository(BonusPolicy::class)->findAll();
return $this->render('ApplicationBundle:pages/human_resource/list:bonus_policy_list.html.twig', array(
'page_title' => 'Increment Policy List',
'bonusPolicy' => $bonusPolicy
));
}
public function createIncrementPolicyAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extDocData = [];
$extDetailsData = [];
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'IncrementPolicy';
DeleteDocument::$funcname($em, $id, 0);
$docId = HumanResource::createIncrementPolicy($em, $request, $companyId, 0);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']]['view_increment_policy']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
3 //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$doc_here = $this->getDoctrine()
->getRepository('ApplicationBundle:IncrementPolicy')
->findOneBy(
array(
'id' => $docId
)
);
//notify
$this->addFlash(
'success',
'Policy Successfully Updated.'
);
$url = $this->generateUrl(
'view_increment_policy'
);
// System::AddNewNotification(
// $this->container->getParameter('notification_enabled'),
// $this->container->getParameter('notification_server'),
// $request->getSession()->get(UserConstants::USER_APP_ID),
// $request->getSession()->get(UserConstants::USER_COMPANY_ID),
// "Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
// 'pos',
// System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
// 'success',
// // $url . "/" . $TransID,
// $url . "/" . $docId,
// "Journal"
//
// );
return $this->redirect($url . "/" . $docId);
}
}
//for edits
if ($id == 0) {
} else {
$extDocData = $em->getRepository('ApplicationBundle:IncrementPolicy')->findOneBy(
array(
'id' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDocData) {
if ($extDocData->getEditFlag() != 1) {
// $url = $this->generateUrl(
//// 'view_salary_segregation_policy'
// 'salary_segregation_policy'
// );
// return $this->redirect($url . "/" . $id);
} else {
// $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
// $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
// array(
// 'transactionId' => $id, ///material
//
// )
// );
}
} else {
}
}
//$em = $this->getDoctrine()->getManager();
$employeeIds = $em->getRepository(EmployeeDetails::class)->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$Designation = $em->getRepository(SysDepartmentPosition::class)->findAll();
$branch = $em->getRepository(Branch::class)->findAll();
$departments = $em->getRepository(SysDepartment::class)->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_increment_policy.html.twig', array(
'page_title' => 'Create Increment Policy',
'employeeIds' => $employeeIds,
'employeeType' => $employeeType,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
));
}
public function IncrementPolicyListAction()
{
$em = $this->getDoctrine()->getManager();
$incrementPolicy = $em->getRepository(IncrementPolicy::class)->findAll();
return $this->render('ApplicationBundle:pages/human_resource/list:increment_policy_list.html.twig', array(
'page_title' => 'Increment Policy List',
'incrementPolicy' => $incrementPolicy
));
}
public function ViewIncrementPolicyAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$incrementPolicy = $em->getRepository(IncrementPolicy::class)->find($id);
$Approval_data = System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
return $this->render('ApplicationBundle:pages/human_resource/views:view_increment_policy.html.twig', array(
'page_title' => 'Increment Policy List',
'incrementPolicy' => $incrementPolicy,
'approval_status' => $incrementPolicy->getApproved(),
'approval_data' => $Approval_data,
'auto_created' => $incrementPolicy->getAutocreated(),
'id' => $id,
'document_log' => $incrementPolicy->getAutocreated() == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['FundRequisition'],
$id,
$incrementPolicy->getCreatedLoginId(),
$incrementPolicy->getEditedLoginId()
) : []
));
}
public function createConsultancyTopicAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$new = new ConsultancyTopic();
$new->setTopicName($request->request->get('topicName'));
$new->setParentTopicName($request->request->get('parentTopicName'));
$new->setUniqueHash($request->request->get('uniqueHash'));
$new->setCompanyId($companyId);
$new->setTopicSlug($request->request->get('topicSlug'));
$new->setTitle($request->request->get('title'));
$new->setSubTitle($request->request->get('subTitle'));
$new->setSummary($request->request->get('content'));
$new->setVideo($request->request->get('video'));
$new->setAuthor($request->request->get('author'));
$new->setAuthorSummary($request->request->get('authorSummary'));
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
// $arr = [
// 'requirement' => $request->request->get('requirement'),
//
// ];
// $new->setRequirementData(json_encode($arr));
$em->persist($new);
$em->flush();
}
// $data = [];
// $em = $this->getDoctrine()->getManager();
// $companyId = $this->getLoggedUserCompanyId($request);
// if ($request->isMethod('POST')) {
// $em = $this->getDoctrine()->getManager();
// $entity_id = array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'];
// //$dochash = $request->request->get('docHash');//change
// $approveRole = $request->request->get('approvalRole');
// $approveHash = $request->request->get('approvalHash');
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
// if (!DocValidation::isInsertable($em, $entity_id,
// $loginId, $approveRole, $approveHash, $id)
// ) {
// $this->addFlash(
// 'error',
// 'Sorry Could not insert Data.'
// );
// } else {
// $data = $request->request;
// $docId = HumanResource::createConsultancyTopic($em, $loginId, $id, $data, $companyId);
//// now add Approval info
//
// $approveRole = $request->request->get('approvalRole');
// $options = array(
// 'notification_enabled' => $this->container->getParameter('notification_enabled'),
// 'notification_server' => $this->container->getParameter('notification_server'),
// 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
//// 'url' => $this->generateUrl(
//// GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
//// ['entity_view_route_path_name']
//// )
// );
// System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
// array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
// $docId,
// $request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
// );
// System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
// $docId,
// $loginId,
// $request->request->get('approvalHash'));
// $this->addFlash(
// 'success',
// 'New Consultancy Topic Added.'
// );
//// $url = $this->generateUrl(
//// 'create_consultancy_topic'
//// );
// //return $this->redirect($url);
//
// }
// }
$consultancyDetails = $em->getRepository('ApplicationBundle:ConsultancyTopic')->findAll();
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_consultancy.html.twig', array(
'page_title' => 'Consultancy Topic',
'consultancyDetails' => $consultancyDetails,
// 'requirement' => json_decode($consultancyDetails->getRequirementData())
));
}
public function createTopicAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$companyId = $this->getLoggedUserCompanyId($request);
$documentQRY = $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
$topicList = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
$topic = [];
$sessionName = BuddybeeConstant::$sessionName;
$document = [];
foreach ($documentQRY as $d) {
$document[$d->getId()] = array(
'id' => $d->getId(),
'documentName' => $d->getDocumentName(),
'text' => $d->getDocumentName(),
);
}
$topicId = $id;
if ($topicId != 0)
$topic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
array(
'id' => $topicId
)
);
if ($request->isMethod('POST')) {
if ($request->request->has('topicId'))
$topicId = $request->request->get('topicId');
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($topicId != 0)
$new = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
array(
'id' => $topicId
)
);
else
$new = new EntityCreateTopic();
$new->setTopicName($request->request->get('topicName'));
$new->setParentTopicId($request->request->get('parentTopic'));
if ($request->request->get('countryId') != '')
$new->setCountryId($request->request->get('countryId'));
else if ($request->request->get('parentTopic') != '') {
$parentTopic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
array(
'id' => $request->request->get('parentTopic')
)
);
if ($parentTopic)
$new->setCountryId($parentTopic->getCountryId());
}
$new->setTimeSlotMultipliers($request->request->get('timeSlotMultipliers'));
$new->setOnlyBookableByAdmin($request->request->get('onlyBookableByAdmin', 0));
$new->setMeetingType($request->request->get('meetingType', 0));
$new->setConsultantCanUpload($request->request->get('consultantCanUpload', 0));
$new->setTopicMarker($request->request->get('topicMarker'));
$new->setCoinMultiplierValue($request->request->get('coinMultiplierValue', 1));
$new->setMinLifetimeCoinsBalance($request->request->get('minLifetimeCoinsBalance', 0));
$new->setMapEmbedIframe($request->request->get('mapEmbedIframe', ''));
$new->setTopicSummary($request->request->get('topicSummary'));
$new->setAddress($request->request->get('address'));
$new->setLocationString($request->request->get('locationString'));
$new->setLocationLat($request->request->get('locationLat'));
$new->setLocationLong($request->request->get('locationLong'));
$new->setUniversityRanking($request->request->get('universityRanking'));
$new->setIsParent($request->request->get('isParent'));
$new->setIsEvent($request->request->get('isEvent'));
$new->setConsultancyEnabled($request->request->get('consultancyEnabled', 0));
$new->setEventExpired($request->request->get('eventExpired', 0));
$new->setEventDesc($request->request->get('eventDesc', 0));
$eventStartDate = new \DateTime($request->request->get('eventStartDate'));
$eventEndDate = new \DateTime($request->request->get('eventStartDate'));
$new->setEventStartDate($eventStartDate);
$new->setEventStartDateTs($eventStartDate->format('U'));
$new->setEventEndDate($eventEndDate);
$new->setEventStartDateTs($eventEndDate->format('U'));
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$checkListStringArray = [];
if ($request->request->has('checkList'))
foreach ($request->request->get('checkList') as $value) {
$checkListStringArray [] = explode(",", $value);
}
$docData = [];
foreach ($request->request->get('document', []) as $key => $value)
$docData[] = [
'document' => $request->request->get('document')[$key],
'expDays' => $request->request->get('expDays')[$key],
'stage' => $request->request->get('stage')[$key],
'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
'checklist' => explode(",", $request->request->get('checkList')[$key])
];
$coursePlanData = [];
foreach ($request->request->get('coursePlanSessionNo', []) as $key => $value)
if ($request->request->get('coursePlanSessionNo')[$key] != '' and $request->request->get('coursePlanSessionNo')[$key] != null) {
if (!isset($coursePlanData[$request->request->get('coursePlanSessionNo')[$key]]))
$coursePlanData[$request->request->get('coursePlanSessionNo')[$key]] = [];
$coursePlanData[$request->request->get('coursePlanSessionNo')[$key]][] = [
'sessionNo' => $request->request->get('coursePlanSessionNo')[$key],
'subject' => $request->request->get('coursePlanSubject')[$key],
'details' => $request->request->get('coursePlanDetails')[$key],
'optimumMin' => $request->request->get('coursePlanOptimumMin')[$key],
];
}
$routineData = [];
foreach ($request->request->get('routine_sequence', []) as $key => $value) {
$routineData[] = [
'sequence' => $request->request->get('routine_sequence')[$key],
'topicId' => $request->request->get('routine_topic_id')[$key],
'topicName' => $request->request->get('routine_topic_name')[$key],
'meetingType' => $request->request->get('routine_topic_meeting_type')[$key],
'duration' => $request->request->get('routine_duration')[$key],
'offset' => $request->request->get('routine_offset')[$key],
'coins' => $request->request->get('routine_coins')[$key],
'nextSequenceStart' => $request->request->has('routine_next_sequence_start_' . $value) ? 1 : 0,
'modifiable' => $request->request->has('routine_modifiable_' . $value) ? 1 : 0,
];
}
$sessionData = [];
foreach ($request->request->get('sessionId', []) as $key => $value)
$sessionData[] = [
'sessionId' => $request->request->get('sessionId')[$key],
'sessionYear' => $request->request->get('year')[$key],
'threshold' => $request->request->get('threshold')[$key],
'sessionStart' => $request->request->get('sessionStart')[$key],
'applicationStartDate' => $request->request->get('applicationStartDate')[$key],
];
$coursesData = [];
foreach ($request->request->get('courseName', []) as $key => $value)
$coursesData[] = [
'courseName' => $request->request->get('courseName')[$key],
];
$departmentData = [];
foreach ($request->request->get('departmentName', []) as $key => $value)
$departmentData[] = [
'departmentName' => $request->request->get('departmentName')[$key],
];
$benefitsData = [];
foreach ($request->request->get('benefit', []) as $key => $value)
$benefitsData[] = [
'benefit' => $request->request->get('benefit')[$key],
];
$new->setRoutineData(json_encode($routineData));
$new->setDocumentData(json_encode($docData));
$new->setCoursePlanData(json_encode($coursePlanData));
$new->setSessionData(json_encode($sessionData));
$new->setCourses(json_encode($coursesData));
$new->setDepartments(json_encode($departmentData));
$new->setBenefits(json_encode($benefitsData));
$otherDataObj = [];
foreach (BuddybeeConstant::$otherDataByHash as $ohash => $otherDataGroup)
foreach ($otherDataGroup as $otherData) {
$fieldExists = $request->request->has($ohash . '_' . $otherData['field']);
if ($fieldExists) {
$fieldValue = $request->request->get($ohash . '_' . $otherData['field'], '');
$otherDataObj[$ohash . '_' . $otherData['field']] = $fieldValue;
}
}
$new->setOtherData(json_encode($otherDataObj));
$new->setBenefits(json_encode($benefitsData));
$em->persist($new);
$em->flush();
$path = "";
$defaultProductImage = '';
$uploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
$uploadedFile = $request->files->get('topicSummaryImage');
if ($uploadedFile != null) {
$fileName = 'TSI' . $new->getId() . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$uploadedFile->move($upl_dir, $path);
$defaultProductImage = 'uploads/topicImage/' . $path;
$new->setTopicSummaryImage($defaultProductImage);
$em->flush();
}
$path = "";
$defaultProductImage = '';
$uploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
$uploadedFile = $request->files->get('topicImage');
if ($uploadedFile != null) {
$fileName = 'TI' . $new->getId() . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$uploadedFile->move($upl_dir, $path);
$defaultProductImage = 'uploads/topicImage/' . $path;
$new->setTopicImage($defaultProductImage);
$em->flush();
}
$this->addFlash(
'success',
'Topic Added.'
);
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_topic.html.twig', array(
'page_title' => 'Create Topic',
'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
'document' => $document,
'topic' => $topic,
'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
'topicId' => $topicId,
'topicList' => $topicList,
'topicMarker' => BuddybeeConstant::$topicMarkup,
'sessionName' => $sessionName,
));
}
public function ConsultancyRequirementSettingsAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$entityList = $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findAll();
$documentQRY = $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
$entity = [];
$sessionName = BuddybeeConstant::$sessionName;
$document = [];
foreach ($documentQRY as $d) {
$document[$d->getId()] = array(
'id' => $d->getId(),
'documentName' => $d->getDocumentName(),
'text' => $d->getDocumentName(),
);
}
$countryId = $id;
if ($countryId != 0)
$entity = $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findOneBy(
array(
'countryId' => $countryId
)
);
if ($request->isMethod('POST')) {
if ($request->request->has('countryId'))
$countryId = $request->request->get('countryId');
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($countryId != 0) {
$new = $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findOneBy(
array(
'countryId' => $countryId
)
);
if (!$new)
$new = new EntityCountryConsultantRequirements();
} else
$new = new EntityCountryConsultantRequirements();
$new->setCountryId($request->request->get('countryId'));
$new->setContractLetterHtml($request->request->get('contractLetterHtml'));
$new->setRequiredFields($request->request->get('requiredFields'));
$new->setAllowedWorkingHoursPerDay($request->request->get('allowedWorkingHoursPerDay'));
$new->setAllowedWorkingHoursPerMonth($request->request->get('allowedWorkingHoursPerMonth'));
$new->setAllowedWorkingHoursPerWeek($request->request->get('allowedWorkingHoursPerWeek'));
$new->setAllowedWorkingHoursPerYear($request->request->get('allowedWorkingHoursPerYear'));
$new->setAllowedEarningPerDay($request->request->get('allowedEarningPerDay'));
$new->setAllowedEarningPerMonth($request->request->get('allowedEarningPerMonth'));
$new->setAllowedEarningPerWeek($request->request->get('allowedEarningPerWeek'));
$new->setAllowedEarningPerYear($request->request->get('allowedEarningPerYear'));
$new->setRevenuePercentagePerSession($request->request->get('revenuePercentagePerSession'));
$docData = [];
foreach ($request->request->get('document', []) as $key => $value)
$docData[] = [
'document' => $request->request->get('document')[$key],
'expDays' => $request->request->get('expDays')[$key],
'stage' => $request->request->get('stage')[$key],
'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
'checklist' => explode(",", $request->request->get('checkList')[$key])
];
$new->setDocumentList(json_encode($docData));
$em->persist($new);
$em->flush();
$this->addFlash(
'success',
'Restriction Updated.'
);
}
return $this->render('@Buddybee/pages/create_consultancy_requirements.html.twig', array(
'page_title' => 'Create Requirements',
'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
'document' => $document,
'entity' => $entity,
'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
'countryId' => $countryId,
'entityList' => $entityList,
'topicMarker' => BuddybeeConstant::$topicMarkup,
'sessionName' => $sessionName,
));
}
public function PromoCodeSettingsAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$entityList = $em->getRepository('CompanyGroupBundle:PromoCode')->findAll();
$applicantList = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
$promoCodeId = $id;
$entity = [];
if ($promoCodeId != 0)
$entity = $em->getRepository('CompanyGroupBundle:PromoCode')->findOneBy(
array(
'id' => $promoCodeId
)
);
if ($request->isMethod('POST')) {
if ($request->request->has('promoCodeId'))
$promoCodeId = $request->request->get('promoCodeId');
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($promoCodeId != 0) {
$new = $em->getRepository('CompanyGroupBundle:PromoCode')->findOneBy(
array(
'id' => $promoCodeId
)
);
if (!$new)
$new = new PromoCode();
} else
$new = new PromoCode();
// $new->setCountryId($request->request->get('countryId'));
$new->setCode($request->request->get('code', ''));
$new->setPromoType($request->request->get('promoType', 1));
$new->setPromoCodeType($request->request->get('promoCodeType', 1));
$new->setPromoValue($request->request->get('promoValue', 0));
$new->setPerpetual($request->request->get('perpetual', 0));
$new->setMaxDiscountAmount($request->request->get('maxDiscountAmount', -1));
$new->setMaxCoinAddition($request->request->get('maxCoinAddition', -1));
$new->setMinAmountForApplication($request->request->get('minAmountForApplication', 0));
$new->setMinCoinForApplication($request->request->get('minCoinForApplication', 0));
$new->setNextApplicationEachCoinCount($request->request->get('nextApplicationEachCoinCount', -1));
$new->setMaxUseCount($request->request->get('maxUseCount', -1));
$new->setMaxUseCountPerUser($request->request->get('maxUseCountPerUser', -1));
$new->setUseCountBalance($request->request->get('useCountBalance', -1));
$new->setReferralApplicantId($request->request->get('referralApplicantId', 0));
$new->setMaxReferralCommissionCount($request->request->get('maxReferralCommissionCount', 0));
$new->setReferralCommissionCountBalance($request->request->get('referralCommissionCountBalance', 0));
$new->setReferralCommissionType($request->request->get('referralCommissionType', 1));
$new->setReferralAmount($request->request->get('referralAmount', 0));
$startsAt = new \DateTime($request->request->get('startsAt', ''));
$expiresAt = new \DateTime($request->request->get('expiresAt', ''));
$new->setStartsAtTs($startsAt->format('U'));
$new->setExpiresAtTs($expiresAt->format('U'));
//
// startsAtTs:
// type: integer
// nullable: true
// expiresAtTs:
// type: integer
// nullable: true
$em->persist($new);
$em->flush();
$this->addFlash(
'success',
'Promo Code Updated.'
);
}
return $this->render('@Buddybee/pages/buddybee_promo_code_settings.html.twig', array(
'page_title' => 'Promo Codes',
'entity' => $entity,
'promoCodeId' => $promoCodeId,
'entityList' => $entityList,
'applicantList' => $applicantList,
));
}
public function createDocumentAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$companyId = $this->getLoggedUserCompanyId($request);
$document = $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
$thisDoc = [];
if ($id != 0)
$thisDoc = $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findOneBy(
array(
'Id' => $id
)
);
if ($request->isMethod('POST')) {
if ($id != 0)
$new = $thisDoc;
else
$new = new EntityCreateDocument();
$new->setDocumentName($request->request->get('docName'));
$new->setExpiryDays($request->request->get('expDays'));
$new->setProcessingDays($request->request->get('processingDays'));
$new->setEmergencyProcessingDays($request->request->get('emergencyProcessingDays'));
$new->setDocVideo($request->request->get('docVideoLink'));
$new->setRequiredDocument(json_encode($request->request->get('requiredDoc')));
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$arr = [
'checkListName' => $request->request->get('checkListName'),
];
$new->setCheckList(json_encode($arr));
$em->persist($new);
$em->flush();
}
$this->addFlash(
'Document Added',
'Topic Added.'
);
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_document.html.twig', array(
'page_title' => 'Create Document',
'document' => $document,
'thisDoc' => $thisDoc
));
}
public function getIndividualDocumentAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager('company_group');
if ($id == 0) {
if ($request->request->has('documentId'))
$id = $request->request->get('documentId');
}
$document = $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->find($id);
return new JsonResponse(
array(
'success' => true,
'rowId' => $request->request->get('rowId'),
'expiryDays' => $document->getExpiryDays(),
'processingDays' => $document->getProcessingDays(),
'emergencyProcessing' => $document->getEmergencyProcessingDays(),
'checklist' => json_decode($document->getCheckList()),
)
);
}
public function createBlogAction(Request $request, $id)
{
if (!$id) {
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager('company_group');
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$new = new EntityCreateBlog();
$new->setTopicId($request->request->get('topicId'));
$new->setTitle($request->request->get('title'));
$new->setSubtitle($request->request->get('subTitle'));
$new->setContent($request->request->get('content'));
$new->setVideoLink($request->request->get('videoLink'));
$new->setAuthorName($request->request->get('authorName'));
$new->setAuthorSummary($request->request->get('authorSummary'));
$new->setIsPrimaryBlog($request->request->get('checkPrimaryBlog'));
$em->persist($new);
$em->flush();
//$fileName = 'cv' . $consultantDetails->getApplicantId() . '.' . $uploadedFile->guessExtension();
$path = "";
$defaultProductImage = '';
$uploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
$uploadedFile = $request->files->get('authorImage');
if ($uploadedFile != null) {
$fileName = 'authorImage' . $new->getId() . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$uploadedFile->move($upl_dir, $path);
$defaultProductImage = 'uploads/authorImage/' . $path;
$new->setAuthorImage($defaultProductImage);
$em->flush();
}
$path = "";
$defaultProductImage = '';
$uploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/mainImage/';
$uploadedFile = $request->files->get('main_img');
if ($uploadedFile != null) {
$fileName = 'mainImage' . $new->getId() . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$uploadedFile->move($upl_dir, $path);
$defaultProductImage = 'uploads/mainImage/' . $path;
$new->setMainImage($defaultProductImage);
$em->flush();
}
$topicDetails = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
array(
'id' => $request->request->get('topicId')
)
);
if ($new->getIsPrimaryBlog() == 1) {
if ($topicDetails)
$topic = $topicDetails;
else
$topic = new EntityCreateTopic();
$topic->setPrimaryBlogId($new->getId());
$em->flush();
}
$this->addFlash(
'success',
'Blog Added.'
);
} else {
$em = $this->getDoctrine()->getManager('company_group');
$topic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
$applicant = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
$blogs = $em->getRepository('CompanyGroupBundle:EntityCreateBlog')->findAll();
$topicIds = [];
foreach ($blogs as $blog) {
$topicIds [] = $blog->getTopicId();
}
// $topic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findBy(
// array(
// 'id' => $topicIds
// )
// );
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
'page_title' => 'Create Blog',
'topic' => $topic,
'applicant' => $applicant,
'blog' => $blogs,
'id' => $id,
));
}
} else {
if ($request->isMethod('GET')) {
$em = $this->getDoctrine()->getManager('company_group');
$topic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
$applicant = $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
$blogs = $em->getRepository('CompanyGroupBundle:EntityCreateBlog')->find($id);
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
'page_title' => 'Create Blog',
'topic' => $topic,
'applicant' => $applicant,
'blog' => $blogs,
'id' => $id,
));
} else {
$em = $this->getDoctrine()->getManager('company_group');
$new = new EntityCreateBlog();
$new->setTopicId($request->request->get('topicId'));
$new->setTitle($request->request->get('title'));
$new->setSubtitle($request->request->get('subTitle'));
$new->setContent($request->request->get('content'));
$new->setVideoLink($request->request->get('videoLink'));
$new->setAuthorName($request->request->get('authorName'));
$new->setAuthorSummary($request->request->get('authorSummary'));
//$em->persist($new);
$em->flush();
$path = "";
$defaultProductImage = '';
$uploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
$uploadedFile = $request->files->get('authorImage');
if ($uploadedFile != null) {
$fileName = 'authorImage' . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$uploadedFile->move($upl_dir, $path);
$defaultProductImage = 'uploads/authorImage/' . $path;
$new->setAuthorImage($defaultProductImage);
$em->flush();
}
$this->addFlash(
'success',
'Blog Updated.'
);
}
}
return new JsonResponse(
array(
'success' => true,
)
);
// if ($request->isMethod('POST')) {
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
//
// $new = new EntityCreateBlog();
//
// $new->setTopicId($request->request->get('topicId'));
// $new->setTitle($request->request->get('title'));
// $new->setSubtitle($request->request->get('subTitle'));
// $new->setContent($request->request->get('content'));
// $new->setVideoLink($request->request->get('videoLink'));
// $new->setAuthorName($request->request->get('authorName'));
// $new->setAuthorSummary($request->request->get('authorSummary'));
//
// $em->persist($new);
// $em->flush();
//
//
// $path = "";
// $defaultProductImage = '';
// $uploadedFile = null;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
// $uploadedFile= $request->files->get('authorImage');
//
// if ($uploadedFile != null) {
//
// $fileName = 'authorImage' .'.' . $uploadedFile->guessExtension();
// $path = $fileName;
//// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $uploadedFile->move($upl_dir, $path);
// $defaultProductImage = 'uploads/authorImage/' . $path;
// $new->setAuthorImage($defaultProductImage);
// $em->flush();
//
// }
// $this->addFlash(
// 'success',
// 'Blog Added.'
// );
// }
// return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
// 'page_title' => 'Create Blog',
// 'topic'=> $topic,
// 'applicant' => $applicant,
// 'blog' => $blogs
// ));
}
public function applicantConsultancyAction()
{
return $this->render('ApplicationBundle:pages/human_resource/input_forms:consultancy.html.twig', array(
'page_title' => 'Consultancy',
));
}
public function viewConsultantDetailsAction(Request $request, $id = 0)
{
$gocEnabled = 1;
$currAppId = 4;
$honeybeeAppId = 1;
$buddybeeAppId = 4;
$em_goc = $this->getDoctrine()->getManager('company_group');
$em = $this->getDoctrine()->getManager();
$option = [];
$option['appId'] = $currAppId; //honeybee
$option['departmentId'] = 18; //consultancy
$option['designationId'] = 50;
// $dataToConnect = System::changeDoctrineManagerByAppId(
// $this->getDoctrine()->getManager('company_group'),
// $gocEnabled,
// $currAppId
// );
// if (!empty($dataToConnect)) {
// $connector = $this->container->get('application_connector');
// $connector->resetConnection(
// 'default',
// $dataToConnect['dbName'],
// $dataToConnect['dbUser'],
// $dataToConnect['dbPass'],
// $dataToConnect['dbHost'],
// $reset = true
// );
// $em = $this->getDoctrine()->getManager();
// } else {
// $currAppId = $honeybeeAppId;
// $dataToConnectAgain = System::changeDoctrineManagerByAppId(
// $this->getDoctrine()->getManager('company_group'),
// $gocEnabled,
// $currAppId
// );
// if (!empty($dataToConnectAgain)) {
// $connector = $this->container->get('application_connector');
// $connector->resetConnection(
// 'default',
// $dataToConnect['dbName'],
// $dataToConnect['dbUser'],
// $dataToConnect['dbPass'],
// $dataToConnect['dbHost'],
// $reset = true
// );
// $em = $this->getDoctrine()->getManager();
// }
//
// }
$consultantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($id);
$skill = $em_goc->getRepository(EntitySkill::class)->findAll();
$gender = HumanResourceConstant::$sex;
$blood = HumanResourceConstant::$BloodGroup;
$consultantLevel = HumanResourceConstant::$consultantLevel;
$companyId = $this->getLoggedUserCompanyId($request);
$designation = $em->getRepository("ApplicationBundle:SysDepartmentPosition")->findAll();
$departments = $em->getRepository("ApplicationBundle:SysDepartment")->findAll();
$companyData = Company::getCompanyData($em, $companyId);
$currDate = new \DateTime();
if ($request->isMethod('POST')) {
//for consultant only
$convertToConsultant = HumanResource::convertToConsultant($em_goc, $em, $id, $option, $request->request);
if ($request->request->get('confirmStatus', 0) == 1) {
$bodyTemplate = 'ApplicationBundle:email/templates:consultantApprovalEmail.html.twig';
$contractLetterHtml = '';
$bodyData = array(
'name' => $consultantDetails->getFirstname() . ' ' . $consultantDetails->getLastname(),
'companyData' => $companyData,
'contractLetterHtml' => $contractLetterHtml,
'commentText' => $request->request->get('commentText'),
);
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
'encryptionMethod' => 'ssl',
'userName' => 'management@buddybee.eu',
'fromAddress' => 'management@buddybee.eu',
'password' => 'Eco@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => '465',
'forwardToMailAddress' => $consultantDetails->getEmail(),
'subject' => 'Consultant Contract Letter Of ' . $consultantDetails->getFirstName(),
'fileName' => '',
//'attachments' => $attachments,
'toAddress' => $consultantDetails->getEmail(),
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $companyId,
'companyImagePath' => ""
));
}
if ($request->request->get('confirmStatus', 0) == 0) {
$bodyTemplate = 'ApplicationBundle:email/templates:consultantRejectionEmail.html.twig';
$contractLetterHtml = '';
$bodyData = array(
'name' => $consultantDetails->getFirstname() . ' ' . $consultantDetails->getLastname(),
'companyData' => $companyData,
'contractLetterHtml' => $contractLetterHtml,
'commentText' => $request->request->get('commentText'),
);
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
'encryptionMethod' => 'ssl',
'userName' => 'management@buddybee.eu',
'fromAddress' => 'management@buddybee.eu',
'password' => 'Eco@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => '465',
'forwardToMailAddress' => $consultantDetails->getEmail(),
'subject' => 'Rejection Letter Of ' . $consultantDetails->getFirstName(),
'fileName' => '',
//'attachments' => $attachments,
'toAddress' => $consultantDetails->getEmail(),
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $companyId,
'companyImagePath' => ""
));
}
}
$docList = MiscActions::GetDocumentDataForBuddybeeConsultantApply($em_goc,
$id,
$consultantDetails->getCurrentCountryId()
);
return $this->render('ApplicationBundle:pages/human_resource/views:viewConsultantDetails.html.twig', array(
'page_title' => 'Consultant Details',
'applicantId' => $id,
'consultantDetails' => $consultantDetails,
'education' => json_decode($consultantDetails->getEducationData(), true),
'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
'certificate' => json_decode($consultantDetails->getCertificateData(), true),
'gender' => $gender,
'blood' => $blood,
'skill' => $skill,
'docList' => $docList,
'countryId' => $consultantDetails->getCurrentCountryId(),
'consultantLevel' => $consultantLevel,
'designation' => $designation,
'department' => $departments
));
}
public function ApplicableEmployeSettingsAction()
{
$em = $this->getDoctrine()->getManager();
$employeeIds = $em->getRepository(Employee::class)->findAll();
return $this->render('ApplicationBundle:pages/human_resource/input_forms:applicable_employee_settings.html.twig', array(
'page_title' => 'Applicable Employee Settings',
'employeeIds' => $employeeIds
));
}
public function GetApplicableSettingsForSingleEmployeeAction($id)
{
$em = $this->getDoctrine()->getManager();
$bankLists = $em->getRepository(WorkHourPolicy::class)->findAll();
if (json_decode($bankLists->getEmployeeIds()) == $id) {
return new JsonResponse(
array(
'success' => true,
'msg' => 'employee found'
)
);
} else {
return new JsonResponse(
array(
'success' => true,
'msg' => 'employee not found'
)
);
}
}
// public function getEmployeeDataAction(){
// $em = $this->getDoctrine()->getManager();
// $emplyeeDetails = $em->getRepository('ApplicationBundle:EmployeeDeatils')->findAll();
// $days = HumanResourceConstant::$days;
// $holidays = ;
// $workHourPolicies = ;
//
// }
public function meetingSchedulingForTabAction()
{
$em = $this->getDoctrine()->getManager();
$date = date('Y-m-d');
$month = date('m');
$year = date('Y');
$monthName = date("F", mktime(0, 0, 0, $month));
$totalDayOfMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$fromdt = date('Y-m-01 ', strtotime("First Day Of $monthName $year"));
// echo "Start Date : $fromdt" . "<br>";
$todt = date('Y-m-d ', strtotime("Last Day of $monthName $year"));
// echo "End Date : $todt" . "<br>";
$num_friday = '';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
if (date('l', strtotime($fromdt) + ($i * 86400)) == 'Friday') {
$num_friday++;
}
}
$num_saturday = '';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
if (date('l', strtotime($fromdt) + ($i * 86400)) == 'Saturday') {
$num_saturday++;
}
}
$totalWeekends = $num_saturday + $num_friday;
$totalCompanyWorkingDay = $totalDayOfMonth - $totalWeekends;
// $attendanceData=$em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(
// array(
// 'employeeId' => 3
// )
// );
$DateRange = [];
$holidayDates = $em->getRepository('ApplicationBundle:HolidayCalendarDates')->findAll();
foreach ($holidayDates as $holiday) {
$holidaayData = array(
'startDate' => $holiday->getStartDate(),
'endDate' => $holiday->getEndDate(),
);
$DateRange = $holidaayData;
}
$employeeDataDetail = [];
$employeeDetail = $em->getRepository('ApplicationBundle:EmployeeDetails')->findOneBy(
array(
'id' => 3
)
);
// foreach($employeeDetail as $employee){
$employeeData = array(
'firstName' => $employeeDetail->getFirstname(),
'basic' => $employeeDetail->getEar1(),
'dearness' => $employeeDetail->getEar2(),
'houseRent' => $employeeDetail->getEar3(),
'medical' => $employeeDetail->getEar4(),
'leaveTravel' => $employeeDetail->getEar5(),
'childEducation' => $employeeDetail->getEar6(),
'totalEarning' => $employeeDetail->getEart(),
);
$employeeDataDetail = $employeeData;
// }
$attendanceData = $em->getRepository(EmployeeAttendanceLog::class);
// $employeeId = $attendanceData->getEmployeeId();
// $countId = count($employeeId);
$totalPresent = $attendanceData->createQueryBuilder('a')
// Filter by some parameter if you want
->where('a.employeeId = 3')
->andWhere('a.isPresent = 1')
->select('a.isPresent')
->getQuery()
->getResult();
// $countAt = 0;
$count = count($totalPresent);
// $count = $countAt+$count;
//get holiday
$holidayStartDate = $DateRange['startDate']->format('Y-m-d');
$holidayEndDate = $DateRange['endDate']->format('Y-m-d');
$dates = HumanResource::getBetweenDates($holidayStartDate, $holidayEndDate);
$dateCount = count($dates);
$totalOffDay = $totalWeekends + $dateCount;
$totalCompanyWorkingDay = $totalDayOfMonth - $totalOffDay;
$totalAbsent = $totalCompanyWorkingDay - $count;
// foreach($dates as $compDate ){
//
//
//
// if($date == $compDate){
// echo $date;
// echo $compDate;
// echo "holiday" ;
//
// }
// else{
// echo "no holiday" ;
// }
// }
$twigData = HumanResource::twigDataForWorkHourPolicy($em);
return $this->render('ApplicationBundle:pages/human_resource/list:meeting_schedule_list_for_tab.html.twig', array(
'page_title' => 'Meeting Schedule List',
'date' => $date,
'totalWeekends' => $totalWeekends,
'totalCompanyWorkingDay' => $totalCompanyWorkingDay,
// 'attendanceData' => $attendanceData,
// 'employeeId' => $employeeId,
'count' => $count,
'totalAbsent' => $totalAbsent,
'employeeDataDetail' => $employeeDataDetail,
'holiday' => $DateRange,
'holidayStartDate' => $holidayStartDate,
'holidayEndDate' => $holidayEndDate,
'holidayCount' => $dateCount,
'totalOffDay' => $totalOffDay,
'employeeIds' => $twigData['employeeIds'],
));
}
public function getEmployeeDataForDisburseAction($id)
{
$em = $this->getDoctrine()->getManager();
$employeeDetail = $em->getRepository('ApplicationBundle:EmployeeDetails')->find($id);
return new JsonResponse(
array(
'success' => true,
'firstName' => $employeeDetail->getFirstName(),
)
);
}
public function BulkAttendanceAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$attendance = [];
foreach ($request->request->get('date') as $key => $val) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$bulkAttendance = null;
if ($request->request->get('attId')[$key] != 0)
$bulkAttendance = $em->getRepository('ApplicationBundle:EmployeeAttendance')->findOneBy(array(
'id' => $request->request->get('attId')[$key],
));
if (!$bulkAttendance)
$bulkAttendance = new EmployeeAttendance;
$theDate = new \DateTime($request->request->get('date')[$key]);
$bulkAttendance->setEmployeeId($request->request->get('employeeId'));
$bulkAttendance->setDate($theDate);
$bulkAttendance->setEntry(
($request->request->get('startTimeTs')[$key] == '' ||
$request->request->get('startTimeTs')[$key] == 'NaN' ||
$request->request->get('startTimeTs')[$key] == 0) ? null :
new \DateTime('@' . $request->request->get('startTimeTs')[$key])
);
$bulkAttendance->setLastOut(($request->request->get('endTimeTs')[$key] == '' ||
$request->request->get('endTimeTs')[$key] == 'NaN' ||
$request->request->get('endTimeTs')[$key] == 0) ? null :
new \DateTime('@' . $request->request->get('endTimeTs')[$key]));
$bulkAttendance->setData(json_encode(
array(
"in" => json_decode($request->request->get('entryDataIn')[$key], true),
"out" => json_decode($request->request->get('entryDataOut')[$key], true)
)
));
// $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
// $bulkAttendance->setIsPresent(1);
$bulkAttendance->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
$bulkAttendance->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
// $bulkAttendance->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
$em->persist($bulkAttendance);
$em->flush();
$bulkAttendanceLog = $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
'attendance_id' => $bulkAttendance->getId(),
));
if (!$bulkAttendanceLog)
$bulkAttendanceLog = new EmployeeAttendanceLog;
$bulkAttendanceLog->setAttendanceId($bulkAttendance->getId());
$bulkAttendanceLog->setEmployeeId($request->request->get('employeeId'));
$bulkAttendanceLog->setLastStartTime(
($request->request->get('startTimeTs')[$key] == '' ||
$request->request->get('startTimeTs')[$key] == 'NaN' ||
$request->request->get('startTimeTs')[$key] == 0) ? null :
new \DateTime('@' . $request->request->get('startTimeTs')[$key])
);
$bulkAttendanceLog->setLastEndTime(($request->request->get('endTimeTs')[$key] == '' ||
$request->request->get('endTimeTs')[$key] == 'NaN' ||
$request->request->get('endTimeTs')[$key] == 0) ? null :
new \DateTime('@' . $request->request->get('endTimeTs')[$key]));
// $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
$bulkAttendanceLog->setIsPresent(1);
$bulkAttendanceLog->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
$bulkAttendanceLog->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
$bulkAttendanceLog->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
// $bulkAttendanceLog->setPositionArray(json_encode($request->request->get('locations')[$key]));
$em->persist($bulkAttendanceLog);
$em->flush();
}
}
$startDate = $request->query->get('start_date', '');
$endDate = $request->query->get('end_date', '');
$employeeId = $request->query->get('employee_id', 0);
$existingData = [];
$startDateTs = 0;
$endDateTs = 0;
$returnData = array(
'page_title' => 'Bulk Attendance',
'existingData' => $existingData,
'startDateTs' => $startDateTs,
'endDateTs' => $endDateTs,
);
if ($request->query->has('returnJson')) {
if ($startDate != '' && $endDate != '' && $employeeId != 0) {
$startDateDt = new \DateTime($startDate);
$endDateDt = new \DateTime($endDate);
$startDateTs = $startDateDt->format('U');
$endDateTs = $endDateDt->format('U');
$attendanceQuery = $em->getRepository('ApplicationBundle:EmployeeAttendance')
->createQueryBuilder('p')
->where("p.employeeId = " . $employeeId)
// ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
->andWhere("p.date <= :last")
->andWhere("p.date >= :start")
->setParameter('start', $startDateDt)
->setParameter('last', $endDateDt);
$attendanceResults = $attendanceQuery->getQuery()->getResult();
foreach ($attendanceResults as $att) {
$entryDateTime = null;
$outDateTime = null;
if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' . $att->getEntry()->format('H:i:00 +0000'));
if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' . $att->getLastOut()->format('H:i:00 +0000'));
$attData = array(
'id' => $att->getId(),
'date_str' => $att->getDate()->format('Y-m-d'),
'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
'in_time_full' => $entryDateTime ? $entryDateTime->format(DATE_RFC2822) : '',
'date_ts' => $att->getDate()->format('U'),
'in_time' => $entryDateTime ? $entryDateTime->format('H:i:s') : '',
'in_time_ts' => $entryDateTime ? $entryDateTime->format('U') : 0,
'last_out_time' => $outDateTime ? $outDateTime->format('H:i:s') : '',
'last_out_time_ts' => $outDateTime ? $outDateTime->format('U') : '',
);
$locations = [];
$locList = [];
$logHere = $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
'attendance_id' => $att->getId(),
));
if ($logHere)
$locList = json_decode($logHere->getPositionArray(), true);
if ($locList == null)
$locList = [];
$entry_data = json_decode($att->getData(), true);
if ($entry_data == null) $entry_data = [];
$lastLat = 0;
$lastLng = 0;
foreach ($locList as $lg) {
$dist = 0;
if (isset($lg['lat'])) {
if ($lastLat == 0) {
$lastLat = $lg['lat'];
$lastLng = $lg['lng'];
}
$theta = $lastLng - $lg['lng'];
$dist = sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$dist = $miles * 1609.344;
if (abs($dist) > 1000) {
$locations[] = array(
'ts' => $lg['ts'],
'lat' => $lg['lat'],
'lng' => $lg['lng'],
);
$lastLat = $lg['lat'];
$lastLng = $lg['lng'];
}
}
}
$attData['locations'] = $locations;
$attData['entryData'] = $entry_data;
$existingData[$att->getDate()->format('U')] = $attData;
}
}
$returnData = array(
'page_title' => 'Bulk Attendance',
'existingData' => $existingData,
'startDateTs' => $startDateTs,
'endDateTs' => $endDateTs,
);
return new JsonResponse($returnData);
} else
return $this->render('ApplicationBundle:pages/human_resource/attendance:bulk_attendance.html.twig', $returnData);
}
public function CreateAttendanceAmendmentAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extDocData = [];
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if ($dochash == '') {
$numberHash = MiscActions::GetNumberHash($em, 'ATAM', $request->request->get('prefix_hash', $request->request->get('employeeId', 0)), $request->request->get('assoc_hash', 0), '', 1);
$dochash = 'ATAM' . '/' . $request->request->get('prefix_hash', $request->request->get('employeeId', 0)) . '/' . $request->request->get('assoc_hash', 0) . '/' . $numberHash;
} else
$numberHash = $request->request->get('number_hash');
if (!DocValidation::isInsertable($em, $entity_id, $dochash,
$loginId, $approveRole, $approveHash, $id)
) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'documentHash' => 0,
'documentId' => 0,
));
} else
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'AttendanceAmendment';
$doc_id = $id;
DeleteDocument::$funcname($em, $doc_id, 0);
$attendanceAmendment = new AttendanceAmendment();
$attendanceAmendment->setDocumentHash($dochash);
$attendanceAmendment->setAttendanceAmendmentDate(new \DateTime($request->request->get('docDate', '')));
$attendanceAmendment->setStartDate(new \DateTime($request->request->get('startDate', '')));
$attendanceAmendment->setEndDate(new \DateTime($request->request->get('endDate', '')));
$attendanceAmendment->setTypeHash('ATAM');
$attendanceAmendment->setPrefixHash($request->request->get('prefix_hash', 0));
$attendanceAmendment->setAssocHash($request->request->get('assoc_hash', 0));
$attendanceAmendment->setNumberHash($numberHash);
$attendanceAmendment->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$attendanceAmendment->setApproved(array_flip(GeneralConstant::$approvalStatus)['pending']);
$attendanceAmendment->setAutoCreated($request->request->get('fullApprove', 0));
$attendanceAmendment->setEmployeeId($request->request->get('forcedEmployeeId', $request->request->get('employeeId', 0)));
// $attendanceAmendment->setAutocreated(0);
if ($request->request->has('dataArrayJson')) {
$attendanceAmendment->setData($request->request->get('dataArrayJson', '[]'));
} else {
$arr = [
];
//dump($arr);
foreach ($request->request->get('date', []) as $key => $val) {
if ($request->request->get('isChanged')[$key] == 1) {
$dt = array(
'enabled' => 1,
'attId' => $request->request->get('attId')[$key],
'note' => $request->request->get('note')[$key],
'startTimeTs' => $request->request->get('startTimeTs')[$key],
'endTimeTs' => $request->request->get('endTimeTs')[$key],
'totalWorkHour' => $request->request->get('totalWorkHour')[$key],
'entryDataIn' => json_decode($request->request->get('entryDataIn')[$key], true),
'entryDataOut' => json_decode($request->request->get('entryDataOut')[$key], true),
);
$arr[$val] = $dt;
}
}
$attendanceAmendment->setData(json_encode($arr));
}
$em->persist($attendanceAmendment);
$em->flush();
$ID = $attendanceAmendment->getAttendanceAmendmentId();
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$ID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
if ($request->request->get('fullApprove', 0) == 1) {
DeleteDocument::AttendanceAmendment($em, $ID);
} else {
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'], $ID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$url = $this->generateUrl(
'view_attendance_amendment'
);
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => true,
'documentHash' => $dochash,
'documentId' => $ID,
'viewUrl' => $url . "/" . $ID,
));
} else {
$this->addFlash(
'success',
'Attendance Amendment Note Added.'
);
return $this->redirect($url . "/" . $ID);
}
}
}
}
if ($id == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:AttendanceAmendment')->findOneBy(
array(
'salesOrderId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_attendance_amendment'
);
return $this->redirect($url . "/" . $id);
} else {
$extDocData = $extDoc;
}
} else {
}
}
$startDate = $request->query->get('start_date', '');
$endDate = $request->query->get('end_date', '');
$employeeId = $request->query->get('employee_id', 0);
$existingData = [];
$startDateTs = 0;
$endDateTs = 0;
$returnData = array(
'page_title' => 'Attendance Amendment',
'existingData' => $existingData,
'startDateTs' => $startDateTs,
'extDocData' => $extDocData,
'endDateTs' => $endDateTs,
);
if ($request->query->has('returnJson')) {
if ($startDate != '' && $endDate != '' && $employeeId != 0) {
$startDateDt = new \DateTime($startDate);
$endDateDt = new \DateTime($endDate);
$startDateTs = $startDateDt->format('U');
$endDateTs = $endDateDt->format('U');
$attendanceQuery = $em->getRepository('ApplicationBundle:EmployeeAttendance')
->createQueryBuilder('p')
->where("p.employeeId = " . $employeeId)
// ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
->andWhere("p.date <= :last")
->andWhere("p.date >= :start")
->setParameter('start', $startDateDt)
->setParameter('last', $endDateDt);
$attendanceResults = $attendanceQuery->getQuery()->getResult();
foreach ($attendanceResults as $att) {
$entryDateTime = null;
$outDateTime = null;
if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' . $att->getEntry()->format('H:i:00 +0000'));
if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' . $att->getLastOut()->format('H:i:00 +0000'));
$attData = array(
'id' => $att->getId(),
'date_str' => $att->getDate()->format('Y-m-d'),
'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
'in_time_full' => $entryDateTime ? $entryDateTime->format(DATE_RFC2822) : '',
'date_ts' => $att->getDate()->format('U'),
'in_time' => $entryDateTime ? $entryDateTime->format('H:i:s') : '',
'in_time_ts' => $entryDateTime ? $entryDateTime->format('U') : 0,
'last_out_time' => $outDateTime ? $outDateTime->format('H:i:s') : '',
'last_out_time_ts' => $outDateTime ? $outDateTime->format('U') : '',
);
$locations = [];
$locList = [];
$logHere = $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
'attendance_id' => $att->getId(),
));
if ($logHere)
$locList = json_decode($logHere->getPositionArray(), true);
if ($locList == null)
$locList = [];
$entry_data = json_decode($att->getData(), true);
if ($entry_data == null) $entry_data = [];
$lastLat = 0;
$lastLng = 0;
foreach ($locList as $lg) {
$dist = 0;
if (isset($lg['lat'])) {
if ($lastLat == 0) {
$lastLat = $lg['lat'];
$lastLng = $lg['lng'];
}
$theta = $lastLng - $lg['lng'];
$dist = sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$dist = $miles * 1609.344;
if (abs($dist) > 1000) {
$locations[] = array(
'ts' => $lg['ts'],
'lat' => $lg['lat'],
'lng' => $lg['lng'],
);
$lastLat = $lg['lat'];
$lastLng = $lg['lng'];
}
}
}
$attData['locations'] = $locations;
$attData['entryData'] = $entry_data;
$existingData[$att->getDate()->format('U')] = $attData;
}
}
$returnData = array(
'page_title' => 'Attendance Amendment',
'existingData' => $existingData,
'startDateTs' => $startDateTs,
'extDocData' => $extDocData,
'endDateTs' => $endDateTs,
);
return new JsonResponse($returnData);
} else
return $this->render('ApplicationBundle:pages/human_resource/attendance:create_attendance_amendment.html.twig', $returnData);
}
public function AttendanceAmendmentListAction(Request $request)
{
$data = [];
return $this->render('ApplicationBundle:pages/human_resource/list:attendance_amendment_list.html.twig',
array(
'page_title' => 'Attendance Amendment List',
'data' => $data
)
);
}
public function ViewAttendanceAmendmentAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = HumanResource::GetAttendanceAmendmentDetails($em, $id);
return $this->render('ApplicationBundle:pages/human_resource/views:view_attendance_amendment.html.twig',
array(
'page_title' => 'Attendance Amendment',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public function PrintAttendanceAmendmentAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = HumanResource::GetAttendanceAmendmentDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Stock Received Note',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$id,
$dt['created_by'],
$dt['edited_by']),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,0
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="stock_received_note_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/human_resource/views:view_attendance_amendment.html.twig',
array(
'page_title' => 'Attendance Amendment',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public function createRoomAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$room = new Room;
$room->setRoomNo($request->request->get('RoomNo'));
//$room->setRoomName($request->request->get('RoomName'));
$room->setBuilding($request->request->get('buildingName'));
$room->setFloor($request->request->get('floor'));
$room->setCapacity($request->request->get('capacity'));
$room->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$em->persist($room);
$em->flush();
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_room.html.twig', array(
'page_title' => 'Add Room',
));
}
public function ExpenseTypeAction()
{
$expenseType = HumanResourceConstant::$employeeExpenseAllowanceTypes;
$expenseTypeArray = [];
foreach ($expenseType as $k => $dt) {
$dt['id'] = $k;
$newSegs = [];
foreach ($dt['segregations'] as $l => $s) {
$newOptions = [];
foreach ($s['options'] as $l2 => $s2) {
$s3 = array(
'value' => $l2,
'text' => $s2,
);
$newOptions[] = $s3;
}
$s['options'] = $newOptions;
if (is_string($s['defaultVal'])) $s['defaultVal'] = [$s['defaultVal']];
$newSegs[] = $s;
}
$dt['segregations'] = $newSegs;
$expenseTypeArray[] = $dt;
}
return new JsonResponse(
array(
'success' => true,
'expenseType' => $expenseType,
'expenseTypeArray' => $expenseTypeArray,
)
);
}
public function DemoDataTableAction()
{
return $this->render('ApplicationBundle:pages/human_resource/list:demo_data_table.html.twig', array(
'page_title' => 'Add Room',
));
}
public function workEnrtyAction(Request $request)
{
// $em = $this->getDoctrine()->getManager();
// $companyId = $this->getLoggedUserCompanyId($request);
// if ($request->isMethod('POST')) {
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
// $labour = new Labour();
// $labour->setLabourName($request->request->get('labourName'));
// $labour->setNidNumber($request->request->get('nidNumber'));
// $em->persist($labour);
// $em->flush();
// $this->addFlash(
// 'success',
// 'Labour Added'
// );
// }
return $this->render('ApplicationBundle:pages/human_resource/input_forms:work_entry.html.twig', array(
'page_title' => 'Work Entry',
));
}
public function ViewContractLetterAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$employeeDetail = $em->getRepository('ApplicationBundle:EmployeeDetails')->find($id);
// $employeeData = [];
// foreach ($employeeDetails as $employeeDetail) {
// $data = array(
// 'firstName' => $employeeDetail->getNid(),
//
//
//
// );
//
//
// $employeeData[] = $data;
// }
return $this->render('ApplicationBundle:pages/human_resource/views:viewContractLetter.html.twig', array(
'page_title' => 'Contract Letter',
'employeeDetail' => $employeeDetail
));
}
public function getAttendanceReportForEmployeeAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$fromDateRow = (new \DateTime($request->get('start_date', '')));
// $fromDate = $fromDateRow->format("M d, Y");
$toDateRow = (new \DateTime($request->get('end_date', $fromDateRow) . ' 23:59:59'));
// $toDate = $toDateRow->format("M d, Y");
// $startDate = "2025-02-13";
// $endDate = "2025-02-16";
$userId = $session->get(UserConstants::USER_ID);
$attendanceDetails = $em->getRepository('ApplicationBundle:EmployeeAttendance')->createQueryBuilder('A')
// ->select('A.createdAt','A.data')
->where('A.sysId = :userId')
->andWhere('A.createdAt >= :startDate')
->andWhere('A.createdAt <= :endDate')
->setParameter('userId', $userId)
->setParameter('startDate', $fromDateRow)
->setParameter('endDate', $toDateRow)
->getQuery()
->getResult();
$attendance = [];
$dt = [];
foreach ($attendanceDetails as $data) {
$in_out_data = json_decode($data->getData(), true);
$new_in_data = [];
$elapsed_data = [];
$new_out_data = [];
if ($in_out_data == null) $in_out_data = [];
if (isset($in_out_data['in'])) {
foreach ($in_out_data['in'] as $ind => $g) {
if (!isset($elapsed_data[$ind])) {
$elapsed_data[$ind] = 0;
}
$the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g . ' +0000');
$new_in_data[] = $the_time->format('U');
}
}
if (isset($in_out_data['out'])) {
foreach ($in_out_data['out'] as $ind => $g) {
if (!isset($elapsed_data[$ind])) {
$elapsed_data[$ind] = 0;
}
$the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g . ' +0000');
$new_out_data[] = $the_time->format('U');
if (isset($new_in_data[$ind])) {
$elapsed_data[$ind] = $new_out_data[$ind] - $new_in_data[$ind];
}
}
}
$list = array(
'date' => $data->getDate()->format('F d Y'),
'attendanceData' => [
'in' => $new_in_data,
'out' => $new_out_data,
'elapsedSec' => $elapsed_data,
]
);
$dt[] = $list;
}
$count = count($attendance);
// for ($i=0;$i < $count; $i++){
// $dt[] = $attendance[$i]['date'];
// $dt[] = ($attendance[$i]['attendanceData']);
// }
//// $decodeData = json_decode($dt, true);
//
// $work_hours = [];
//
// foreach ($dt as $index => $entry) {
// $in_times = $entry['in'];
// $out_times = $entry['out'];
//
//
// $count = min(count($in_times), count($out_times));
//
// for ($i = 0; $i < $count; $i++) {
// $time_in = new DateTime($in_times[$i]);
// $time_out = new DateTime($out_times[$i]);
//
//
// $interval = $time_in->diff($time_out);
// $total_hours = $interval->format('%h');
// $total_minutes = $interval->format('%i');
//
//
// $work_hours[] = [
//// "set" => $index + 1,
// "in" => $in_times[$i],
// "out" => $out_times[$i],
// "worked" => "$total_hours hours, $total_minutes minutes"
// ];
// }
// }
//
//// foreach ($work_hours as $work) {
//// return new JsonResponse(
//// array(
//// 'in'=>$work['in'],
//// 'out' => $work['out'],
//// 'hour' => $work['worked']
//// )
//// ) ;
////// echo "Set {$work['set']} - IN: {$work['in']} - OUT: {$work['out']} => Worked: {$work['worked']}\n";
//// }
return new JsonResponse($dt);
}
public function getTotalWorkHourAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$currentDate = new \DateTime(date('y-m-d'));
$session = $request->getSession();
$employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$planningItemId = $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID);
$attendanceData = $em->getRepository('ApplicationBundle:EmployeeAttendance');
$currentStatus = HumanResource::getCurrentStatusFromDb($attendanceData, $employeeId, $currentDate);
$planningItemDetails = $em->getRepository(PlanningItem::class)->createQueryBuilder('p')
->select('p.itemAlias')
->where('p.id = :planningItemId')
->setParameter('planningItemId', $planningItemId)
->getQuery()
->getResult();
// Check if "data" key exists and contains "in" times
if (empty($currentStatus["data"]["in"])) {
return new JsonResponse([
// 'message' => 'No attendance data available',
'currentStatus' => $currentStatus,
'totalWorkingTime' => '00:00:00'
]);
}
$totalSeconds = 0;
for ($i = 0; $i < count($currentStatus["data"]["in"]); $i++) {
$inTime = $currentStatus["data"]["in"][$i];
// Check if "out" time exists for this "in" time
if (!isset($currentStatus["data"]["out"][$i])) {
continue; // Skip this entry if there is no out time
}
$outTime = $currentStatus["data"]["out"][$i];
// Calculate the difference
$totalSeconds += ($outTime - $inTime);
}
// If no valid time pairs were found, return 00:00:00
// if ($totalSeconds == 0) {
// return new JsonResponse([
// 'message' => 'No complete in-out records found',
// 'totalWorkingTime' => '00:00:00'
// ]);
// }
// Convert total seconds to hours, minutes, and seconds
$hours = floor($totalSeconds / 3600);
$minutes = floor(($totalSeconds % 3600) / 60);
$seconds = $totalSeconds % 60;
$totalWorkingTime = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
return new JsonResponse([
'taskName' => isset($planningItemDetails[0]) ? $planningItemDetails[0]['itemAlias'] : '',
'currentStatus' => $currentStatus,
'totalWorkingTime' => $totalWorkingTime
]);
}
// public function getEmployeeDataAction(Request $request)
// {
// $em = $this->getDoctrine()->getManager();
// $session = $request->getSession();
// $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
//
//
// $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
// ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin','E.image', 'P.positionName')
// ->addSelect('A.current_balance')
// ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
// ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
// ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
// ->where('E.id = :employeeId')
// ->setParameter('employeeId', $employeeId)
// ->getQuery()
// ->getResult();
//
// return new JsonResponse($employeeDetails[0]);
// }
// public function getEmployeeDataAction(Request $request)
// {
// $em = $this->getDoctrine()->getManager();
// $session = $request->getSession();
// $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
// $image = $session->get(UserConstants::USER_IMAGE);
// $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
//
// $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
// ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
// ->addSelect('A.current_balance')
// ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
// ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
// ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
// ->where('E.id = :employeeId')
// ->setParameter('employeeId', $employeeId)
// ->getQuery()
// ->getResult();
//
// // If image is null or empty, assign empty string
// if (empty($employeeDetails['image'])) {
// $employeeDetails['image'] = $image;
// }
//
// return new JsonResponse($employeeDetails);
// }
public function getEmployeeDataAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$image = $session->get(UserConstants::USER_IMAGE);
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$userImage = $session->get(UserConstants::USER_IMAGE);
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
->addSelect('A.current_balance')
->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
->where('E.id = :employeeId')
->setParameter('employeeId', $employeeId)
->getQuery()
->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); // Only one employee expected
if (!$employeeDetails) {
return new JsonResponse(['error' => 'Employee not found'], 404);
}
// If image is missing, fallback to session image
if (empty($employeeDetails['image'])) {
$employeeDetails['image'] = $image;
}
// If image is still available, prefix it with absolute URL
if (!empty($employeeDetails['image'])) {
$employeeDetails['image_url'] = $absoluteUrl . '' . $userImage;
} else {
$employeeDetails['image_url'] = ''; // no image
}
return new JsonResponse($employeeDetails);
}
public function updateEmployeeDataForAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->find($employeeId);
if ($request->isMethod('POST')) {
$firstname = $request->request->get('firstname');
$lastname = $request->request->get('lastname');
$nid = $request->request->get('nid');
$tin = $request->request->get('tin');
if ($firstname !== null) {
$employeeDetails->setFirstName($firstname);
}
if ($lastname !== null) {
$employeeDetails->setLastName($lastname);
}
if ($nid !== null) {
$employeeDetails->setNid($nid);
}
if ($tin !== null) {
$employeeDetails->setTin($tin);
}
$em->flush();
return new JsonResponse(['success' => true]);
}
return new JsonResponse(['success' => false, 'message' => 'Invalid request method']);
}
// public function updateEmployeeDataForAppAction(Request $request){
// $em = $this->getDoctrine()->getManager();
// $session = $request->getSession();
// $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
// $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->find($employeeId);
//
// if ($request->isMethod('POST')) {
// $employeeDetails->setFirstName(($request->request->get('firstname',$employeeDetails->getFirstName())));
// $employeeDetails->setLastName($request->request->get('lastname',$employeeDetails->getLastName()));
// $employeeDetails->setNid($request->request->get('nid'),$employeeDetails->getNid());
// $employeeDetails->setTin($request->request->get('tin'),$employeeDetails->getTin());
//
// $em->flush(); //
//
// return new JsonResponse(['success' => true]);
// }
//
//
// }
public function leaveApplicationListForAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$leaveType = HumanResourceConstant::$LeaveType;
$approvalStatus = GeneralConstant::$approvalAction;
$leaveCategory = HumanResourceConstant::$leavCategory;
// Get page and limit from request (default: page=1, limit=10)
$page = max((int)$request->query->get('page', 1), 1);
$limit = max((int)$request->query->get('limit', 10), 1);
$offset = ($page - 1) * $limit;
// Get total count
$total = $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
->createQueryBuilder('L')
->select('COUNT(L.employeeLeaveApplicationId)')
->where('L.employeeId = :employeeId')
->setParameter('employeeId', $employeeId)
->getQuery()
->getSingleScalarResult();
// Get paginated results
$leaveRecords = $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
->createQueryBuilder('L')
->select(
'L.documentHash',
'L.employeeLeaveApplicationId',
'L.leaveStartDate',
'L.leaveEndDate',
'L.leaveTypeId',
'L.leaveCategory',
'L.approved',
'L.createdAt',
'L.alternateDate',
'L.leaveComment',
'L.createdAt',
'L.approved_by'
)
->where('L.employeeId = :employeeId')
->setParameter('employeeId', $employeeId)
->setFirstResult($offset)
->setMaxResults($limit)
->getQuery()
->getResult();
// Format the results
$formattedData = [];
foreach ($leaveRecords as $leave) {
$formattedData[] = [
'documentHash' => $leave['documentHash'],
'employeeLeaveApplicationId' => $leave['employeeLeaveApplicationId'],
'leaveStartDate' => $leave['leaveStartDate'] ? $leave['leaveStartDate']->getTimestamp() : 0,
'leaveEndDate' => $leave['leaveEndDate'] ? $leave['leaveEndDate']->getTimestamp() : 0,
'leaveType' => $leaveType[$leave['leaveTypeId']] ?? 'Unknown',
'leaveCategory' => $leaveCategory[$leave['leaveCategory']] ?? 'Unknown',
'approved' => $approvalStatus[$leave['approved']] ?? 'Unknown',
'createdAt' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
'alternateDate' => $leave['alternateDate'] ? $leave['alternateDate']->getTimestamp() : 0,
'note' => $leave['leaveComment'] ? $leave['leaveComment'] : '',
'appliedOn' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
'approvedBy' => $leave['approved_by'] ? $leave['approved_by'] : 'automatically approved',
];
}
// Final response with pagination meta
return new JsonResponse([
'CurrentPage' => $page,
'limit' => $limit,
'total' => (int)$total,
'data' => $formattedData,
]);
}
public function PublicProfilePageAction(Request $request)
{
return new JsonResponse(['success' => true]);
}
public function leaveSettingsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$ids = $request->request->get('id', []);
$leaveTitles = $request->request->get('leaveTitle', []);
$carryForwardTypes = $request->request->get('carryForwardType', []);
$carryForwardQtys = $request->request->get('number', []);
$totalLeaves = $request->request->get('totalLeave', []);
$resetFreqTypes = $request->request->get('resetFrequencyType', []);
$resetFreqQtys = $request->request->get('resetFrequencyQty', []);
$additionConditions = $request->request->get('additionCondition', []);
$additionDurations = $request->request->get('additionConditionDuration', []);
for ($i = 0; $i < count($leaveTitles); $i++) {
if (
isset(
$carryForwardTypes[$i],
$carryForwardQtys[$i],
$totalLeaves[$i],
$resetFreqTypes[$i],
$resetFreqQtys[$i],
$additionConditions[$i],
$additionDurations[$i]
)
) {
$id = $ids[$i] ?? null;
$leaveSetting = null;
$existingLeaveSettings = $em->getRepository('ApplicationBundle:LeaveSettings')->findAll();
foreach ($existingLeaveSettings as $extLv) {
$em->remove($extLv);
$em->flush();
}
// if ($id) {
// $leaveSettings = $em->getRepository('ApplicationBundle:LeaveSettings')->find($id);
// }
// if (!$leaveSetting) {
$leaveSetting = new LeaveSettings();
// }
$leaveSetting->setId($i+1);
$leaveSetting->setLeaveTitle($leaveTitles[$i]);
$leaveSetting->setCarryForwardType((int)$carryForwardTypes[$i]);
$leaveSetting->setCarryForwardQty((int)$carryForwardQtys[$i]);
$leaveSetting->setTotalLeave((int)$totalLeaves[$i]);
$leaveSetting->setResetFrequencyType((int)$resetFreqTypes[$i]);
$leaveSetting->setResetFrequencyQty((int)$resetFreqQtys[$i]);
$leaveSetting->setAdditionCondition((int)$additionConditions[$i]);
$leaveSetting->setAdditionConditionDuration((int)$additionDurations[$i]);
$em->persist($leaveSetting);
}
}
$em->flush();
$this->addFlash('success', 'Leave settings saved successfully!');
return $this->redirectToRoute('leave_settings_list');
}
return $this->render('ApplicationBundle:pages/human_resource/input_forms:leave_settings.html.twig', [
'page_title' => 'Leave Settings',
]);
}
public function leavePolicyListAction()
{
return $this->render("ApplicationBundle:pages/human_resource/list:leaveApplicationSettingsList.html.twig", array(
'page_title' => 'Leave PolicyList',
));
}
}