<?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\Helper\EmployeePayloadNormalizer;
use ApplicationBundle\Helper\ResponseStructure;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\Buddybee\Buddybee;
use ApplicationBundle\Modules\HumanResource\HumanResource;
use ApplicationBundle\Modules\HumanResource\HumanResourceHelper;
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 DateTime;
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 Throwable;
//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 = $em;
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$systemType = $this->container->getParameter('system_type') ?: '_CENTRAL_';
$stripe_secret_key = $this->container->getParameter('stripe_secret_key_live');
$paymentService = $this->container->get('eco_system_payment_service');
$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
$retailerId = $request->request->get('retailerId', 0);
if ($request->query->has('currency'))
$currencyForGateway = $request->query->get('currency');
else
$currencyForGateway = $request->request->get('currency', 'eur');
$setupOnlyCheckout = (int)$request->request->get('setupOnly', $request->query->get('setupOnly', 0)) === 1;
$checkoutFlow = $request->request->get('flow', $request->query->get('flow', 'payment'));
$isCompanySetupCheckout = $setupOnlyCheckout && $checkoutFlow === 'company_setup';
$isSaasSubscriptionCheckout = (int)$request->request->get('saasSubscription', $request->query->get('saasSubscription', 0)) === 1;
$companySetupRedirectUrl = $request->request->get('companySetupRedirectUrl', $request->query->get('companySetupRedirectUrl', ''));
$ownerId = (int)$request->request->get('ownerId', $request->query->get('ownerId', 0));
$currentUserBalance = 0;
$gatewayAmount = 0;
$redeemedAmount = 0;
$redeemedSessionCount = 0;
$toConsumeSessionCount = 0;
$invoiceSessionCount = 0;
$payableAmount = 0;
$promoClaimedAmount = 0;
$promoCodeId = 0;
$promoClaimedSession = 0;
$bookingExpireTs = 0;
$imageBypackageId = [
0 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
4 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
5 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
];
$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')) {
$bookedById = 0;
$bookingRefererId = 0;
if ($session->get(UserConstants::USER_ID)) {
$bookedById = $session->get(UserConstants::USER_ID);
$bookingRefererId = 0;
$invoiceSessionCount = 1 * ($request->request->get('sessionCount', 0) == '' ? 0 : $request->request->get('sessionCount', 0));
$dataAppId = $request->request->get('appId', $session->get(UserConstants::USER_APP_ID));
$expireTsAddition = $request->request->get('expireTsAddition',
$request->request->get('billingFrequency', 2) == 1 ? 30 * 24 * 3600 : 365 * 24 * 2600
);
$expireTsModification = $request->request->get('expireTsModification', 0);
$userAddition = $request->request->get('userAddition', 0);
$userModification = $request->request->get('userModification', 0);
$adminAddition = $request->request->get('adminAddition', 0);
$adminModification = $request->request->get('adminModification', 0);
$packageId = $request->request->get('packageId', 1);
if($packageId == 0)
$packageId=1;
$successActionData = [
'appId' => $dataAppId,
'packageId' => $packageId,
'expireTsAddition' => $expireTsAddition,/// can also be - if needed
'expireTsModification' => $expireTsModification,/// can also be - if needed
'userAddition' => $userAddition,/// can also be - if needed
'userModification' => $userModification,/// can also be - if needed
'adminAddition' => $adminAddition,/// can also be - if needed
'adminModification' => $adminModification,/// can also be - if needed
];
if ($request->request->has('purchasePackage')) {
$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->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');
} else {
if ($bookingRefererId == 0)
$bookingRefererId = $session->get(UserConstants::USER_ID);
$studentDetails = $em->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
if ($bookingRefererId != $userId && $bookingRefererId != 0) {
$bookingReferer = $em->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
if ($bookingReferer)
if ($bookingReferer->getIsAdmin()) {
$studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
$em->flush();
}
}
}
}
Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
if ($request->request->get('isRecharge', 0) == 1) {
if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount - ($redeemedAmount + $promoClaimedAmount);
} else if ($isSaasSubscriptionCheckout) {
$gatewayAmount = max(0, round($payableAmount - ($redeemedAmount + $promoClaimedAmount), 2));
} 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) / 1) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'HoneyBee Hive Subscription- ' . GeneralConstant::$packageDetails[$packageId]['packageName'],
'images' => [$imageBypackageId[$packageId]],
],
],
'quantity' => 1,
]];
$new_invoice = null;
if (!$new_invoice) {
$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(0);
$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->setAppId($dataAppId);
$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
$new_invoice->setSuccessActionData(json_encode($successActionData)); //0 means receive
if ($bookingExpireTs == 0) {
$bookingExpireTs = (new \DateTime('+30 day'))->format('U');
}
$new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
$new_invoice->setBookingExpireTs($bookingExpireTs);
$new_invoice->setConfirmationExpireTs($bookingExpireTs);
$em->persist($new_invoice);
$em->flush();
}
$invoiceId = $new_invoice->getId();
$gatewayInvoice = $new_invoice;
if ($request->request->get('isRecharge', 0) != 1) {
}
}
} 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\\Entity\\EntityInvoice')->
}
}
if ($gatewayInvoice) {
$stripeCustomerId = null;
if ($gatewayInvoice->getInvoiceType() == BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE) {
$companyGroup = $em_goc
->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy(
array(
'appId' => $gatewayInvoice->getAppId(),
)
);
if ($companyGroup)
$stripeCustomerId = $companyGroup->getStripeCustomerId();
} else
$stripeCustomerId = $gatewayInvoice->getStripeCustomerId();
$route = $request->attributes->get('_route');
if ($gatewayAmount > 0) {
$processType = ($route == 'app_checkout_page_api') ? 'intent' : 'session';
} else if ($isCompanySetupCheckout) {
$processType = 'session';
} else if (!$stripeCustomerId) {
$processType = 'setup';
} else if ($gatewayAmount <= 0) {
$meetingId = 0;
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
$this->container->getParameter('kernel.root_dir'),
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\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'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 ',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
$url = $this->generateUrl(
$systemType == '_BUDDYBEE_' ? 'buddybee_dashboard' : 'central_landing'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => 0,
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
return new JsonResponse($output);
} else {
}
$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();
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/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' => \ApplicationBundle\Helper\MailerConfig::address(),
'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
if ($paymentGatewayFromInvoice == 'bkash' || $paymentGatewayFromInvoice == 'stripe') {
$successPayload = [
'invoiceId' => $gatewayInvoice->getId(),
'autoRedirect' => $request->request->get('autoRedirect', $request->query->get('autoRedirect', 1)),
];
$successMetadata = [];
if ($setupOnlyCheckout || $isCompanySetupCheckout) {
$successPayload['setupOnly'] = 1;
$successPayload['appId'] = (int)$gatewayInvoice->getAppId();
$successPayload['ownerId'] = $ownerId;
if ($companySetupRedirectUrl !== '') {
$successPayload['redirectUrl'] = $companySetupRedirectUrl;
}
$successMetadata = [
'app_id' => (string)((int)$gatewayInvoice->getAppId()),
'owner_id' => (string)$ownerId,
'redirect_url' => (string)$companySetupRedirectUrl,
];
}
$successUrl = $this->generateUrl(
'payment_gateway_success',
[
'encData' => $this->get('url_encryptor')->encrypt(json_encode($successPayload)),
'hbeeSessionToken' => $session->get('token', 0),
],
UrlGenerator::ABSOLUTE_URL
);
$successUrl .= (strpos($successUrl, '?') !== false ? '&' : '?') . 'session_id={CHECKOUT_SESSION_ID}';
$cancelUrl = $this->generateUrl(
'payment_gateway_cancel',
[
'invoiceId' => $gatewayInvoice->getId(),
'autoRedirect' => $request->request->get('autoRedirect', $request->query->get('autoRedirect', 1)),
'hbeeSessionToken' => $session->get('token', 0),
],
UrlGenerator::ABSOLUTE_URL
);
$result = $paymentService->processPayment(
$gatewayInvoice,
null,
$processType,
$paymentGatewayFromInvoice,
[
'setupOnly' => $setupOnlyCheckout ? 1 : 0,
'success_url' => $successUrl,
'cancel_url' => $cancelUrl,
'metadata' => $successMetadata,
]
);
$output = [
'clientSecret' => $result['client_secret'] ?? '',
'type' => $processType,
'id' => $result['id'] ?? '',
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => $result['success'] ? 1 : 0,
'error' => $result['error'] ?? null,
'mode' => $result['mode'] ?? null,
'paymentIntentId' => $processType == 'intent' ? $result['id'] : ''
];
return new JsonResponse($output);
} 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], $this->container->getParameter('kernel.root_dir'), 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\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/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' => \ApplicationBundle\Helper\MailerConfig::address(),
'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
// '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);
}
//changes dev
public function AddEmployeeAction(Request $data, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$connection = $em->getConnection();
$connection->beginTransaction();
$skills = $em->getRepository(Skill::class)->findAll();
$session = $data->getSession();
$ownOnly = 0;
$consultancyLevel = HumanResourceConstant::$consultantLevel;
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$banks = $em->getRepository(BankList::class)->findAll();
$bankListObj = [];
$deviceList = $em_goc->getRepository('CompanyGroupBundle\\Entity\\Device')->findBy([
'appId' => $session->get(UserConstants::USER_APP_ID)
]);
$id = $data->request->get('employeeId', $id);
foreach ($banks as $bank) {
$bankListObj[$bank->getBankId()] = $bank->getName();
}
if ($id === "my") {
$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\\Entity\\SysUser')->find($sysUserId) : [];
$regionIdsArray = json_decode($EmployeeMain->getRegionIds(), true) ?: [];
$regionLeaderFlagsArray = json_decode($EmployeeMain->getRegionLeaderFlags(), true) ?: [];
$existingRegionAssociations = [];
if (!empty($regionIdsArray)) {
$regionRepo = $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\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(
'@Application/pages/human_resource/input_forms/add_employee.html.twig',
array(
'page_title' => 'Update Employee',
'ownOnly' => $ownOnly,
'deviceList' => $deviceList,
'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'],
'AccountStatus' => $TwigData['AccountStatus'],
'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)),
'leaveSettings' => $TwigData['leaveSettings'],
'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 = 1;
$emailQryStr=" 1=0 ";
$emails=explode(',',$data->get('email'));
foreach ($emails as $emailSingle) {
$emailQryStr.=" or m.email like '%" . $emailSingle . "%' or m.oAuthEmail like '%" . $emailSingle . "%'";
}
$user=null;
$users = $em->getRepository('ApplicationBundle\\Entity\\SysUser')
->createQueryBuilder('m')
->where(" ( ".$emailQryStr." )")
->getQuery()
->setMaxResults(1)
->getResult();
if(!empty($users)) {
$user = $users[0];
}
if ($user) {
$sysUserId = $user->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'),
$data->request->get('empStatus'),
$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') {
HumanResource::StoreDataForAddEmployee($em, $data, $id, $CompanyId, $profileImage);
$connection->commit();
if ($systemType == '_CENTRAL_') {
} else {
$Employee = $em->getRepository(Employee::class)->find($id);
$EmployeeDetails = $em->getRepository(EmployeeDetails::class)->findOneBy(
array(
'id' => $id
)
);
$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\\Entity\\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\\Entity\\SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\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 ($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;
} else {
$userDataSingle[$getter] = $value;
}
} catch (\Exception $e) {
continue;
}
}
$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_HTTPHEADER => array(),
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\\Entity\\SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->flush();
}
}
}
}
$debugCount++;
}
}
}
} else {
$errorMsg = $message['message'] ?? 'Unknown error occurred.';
$this->addFlash('error', $errorMsg);
return $this->redirectToRoute('add_employee');
}
$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',
'User/Email not found. Please check the email and try again. If the problem persists, please contact support'
);
return $this->redirectToRoute('add_employee');
}
} 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(
'@Application/pages/human_resource/input_forms/add_employee.html.twig',
array(
'page_title' => 'Add Employee',
'ownOnly' => $ownOnly,
'deviceList' => $deviceList,
'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'],
'AccountStatus' => $TwigData['AccountStatus'],
'sex' => $TwigData['sex'],
'skills' => $skills,
'id' => $id,
'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)),
'leaveSettings' => $TwigData['leaveSettings'],
'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 {
try {
$approveHash = $data->request->get('approvalHash');
$loginId = $data->getSession()->get(UserConstants::USER_LOGIN_ID);
$CompanyId = $this->getLoggedUserCompanyId($data);
$isSignatureOk = DocValidation::isSignatureOk($em, $loginId, $approveHash);
if (!$isSignatureOk) {
$this->addFlash('error', 'Invalid Approval Hash!');
return $this->redirectToRoute('add_employee');
}
// Strengthen: reject incomplete/invalid new employees before creating a user.
$vFirst = trim((string) $data->request->get('firstname'));
$vEmail = trim((string) $data->request->get('email'));
$vUser = trim((string) $data->request->get('username'));
$vErrors = [];
if ($vFirst === '') { $vErrors[] = 'First name is required.'; }
if ($vUser === '') { $vErrors[] = 'Username is required.'; }
if ($vEmail === '' || !filter_var(explode(',', $vEmail)[0], FILTER_VALIDATE_EMAIL)) { $vErrors[] = 'A valid email is required.'; }
if (!empty($vErrors)) {
$this->addFlash('error', implode(' ', $vErrors));
return $this->redirectToRoute('add_employee');
}
$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('empStatus'),
$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] === 'error') {
$this->addFlash('error', 'Invalid Approval Hash!');
return $this->redirectToRoute('add_employee');
}
$isSuccess = HumanResource::StoreDataForAddEmployee($em, $data, false, $CompanyId);
$Employee = $isSuccess;
$EmployeeDetails = $em->getRepository(EmployeeDetails::class)->findOneBy(['id' => $id]);
$Employee->setUserId($message[3]->getUserId());
$em->persist($Employee);
if ($EmployeeDetails) {
$EmployeeDetails->setUserId($message[3]->getUserId());
$em->persist($EmployeeDetails);
}
$em->flush();
$connection->commit();
} catch (Throwable $e) {
$connection->rollBack();
$em->close();
$this->addFlash('error', 'Failed to save employee: ' . $e->getMessage());
return $this->redirectToRoute('add_employee');
}
if ($systemType !== '_CENTRAL_') {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
if ($connected) {
$appIds = $message[2]->getAppId();
$userIds = $message[3]->getUserId();
$findByQuery = ['active' => 1];
if ($appIds !== '_UNSET_') $findByQuery['appId'] = $appIds;
$gocList = $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")->findBy($findByQuery);
$gocDataList = $gocDataListByAppId = [];
foreach ($gocList as $entry) {
$d = [
'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',
$entry['dbName'],
$entry['dbUser'],
$entry['dbPass'],
$entry['dbHost'],
$reset = true
);
$em = $this->getDoctrine()->getManager();
$users = ($userIds !== '_UNSET_')
? $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SysUser')->findBy(['userId' => $userIds])
: $this->getDoctrine()->getRepository('ApplicationBundle\\Entity\\SysUser')->findBy([]);
$userData = $userFiles = [];
foreach ($users as $user) {
$filePath = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage();
if ($user->getImage() && file_exists($filePath)) {
$mime = mime_content_type($filePath);
$info = pathinfo($filePath);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = new \CURLFile($filePath, $mime, $name);
$skipSend = 0;
}
} else {
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($m) {
return substr($m, 0, 3) === 'get';
});
$userDataSingle = [];
foreach ($getters as $getter) {
if (in_array($getter, ['getCreatedAt', 'getUpdatedAt', 'getImage'])) continue;
$val = $user->{$getter}();
$userDataSingle[$getter] = $val instanceof \DateTime ? $val->format('Y-m-d') : $val;
}
$employeeGetters = [
'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;
$value = $EmployeeDetails->{$getter}();
if ($value instanceof \DateTime) $userDataSingle[$getter] = $value->format('Y-m-d');
elseif (!is_object($value)) $userDataSingle[$getter] = $value;
}
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = ['skipSend' => $skipSend];
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_POSTFIELDS => $userFiles
]);
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = $errData ? ['status' => 'error', 'message' => 'cURL Error: ' . $errData] : json_decode($retData, true);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData'])) {
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$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\\Entity\\SysUser')->findOneBy(['userId' => $sys_id]);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->persist($user);
$em->flush();
}
}
}
}
$debugCount++;
}
}
}
$companyData = $message[2];
if ($message[0] === 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
$bodyTemplate = '@Application/email/user/registration.html.twig';
$bodyData = [
'name' => $data->request->get('name'),
'companyData' => $companyData,
'userName' => $data->request->get('username'),
'password' => $data->request->get('password'),
];
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail([
'senderHash' => '_CUSTOM_',
'forwardToMailAddress' => $data->request->get('email'),
'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' . $companyData->getName(),
'fileName' => '',
'attachments' => [],
'toAddress' => $data->request->get('email'),
'fromAddress' => 'accounts@ourhoneybee.eu',
'userName' => 'accounts@ourhoneybee.eu',
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
'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);
$redirectUrl = $userType == 1
? $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL)
: $this->generateUrl('add_employee', [], UrlGenerator::ABSOLUTE_URL);
return new JsonResponse([
'employeeId' => $Employee->getEmployeeId(),
'redirectToNew' => 1,
'success' => true,
'redirectUrl' => $redirectUrl,
]);
}
}
}
/**
* Redesigned cp-shell "Add Employee" form (calm, sectioned UX). GET only;
* it POSTs to the existing `add_employee` handler (reusing the full save +
* signature flow), so no backend duplication.
*/
public function AddEmployeeCpAction(Request $data)
{
$em = $this->getDoctrine()->getManager();
$TwigData = HumanResource::TwigDataForAddEmployee($em, 0);
$banks = $em->getRepository(BankList::class)->findAll();
$bankListObj = [];
foreach ($banks as $bank) { $bankListObj[$bank->getBankId()] = $bank->getName(); }
return $this->render('@Application/pages/human_resource/input_forms/add_employee_cp.html.twig', [
'page_title' => 'Add Employee',
'branches' => $TwigData['branches'],
'departments' => $TwigData['departments'],
'departmentPositions' => $TwigData['departmentPositions'],
'supervisors' => $TwigData['supervisors'],
'EmploymentStatus' => $TwigData['EmploymentStatus'],
'AccountStatus' => $TwigData['AccountStatus'],
'sex' => $TwigData['sex'],
'BloodGroup' => $TwigData['BloodGroup'],
'days' => $TwigData['days'],
'AccountTypes' => $TwigData['AccountType'],
'user_type_data' => HumanResourceConstant::$userType,
'skills' => $em->getRepository(Skill::class)->findAll(),
'bankListObj' => $bankListObj,
'heads' => Accounts::getLedgerHeadsWithParents($em),
]);
}
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\\Entity\\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\\Entity\\SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\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\\Entity\\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\\Entity\\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 = '@Application/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' => 'accounts@ourhoneybee.eu',
'userName' => 'accounts@ourhoneybee.eu',
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
'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 = '@Application/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' => 'accounts@ourhoneybee.eu',
'userName' => 'accounts@ourhoneybee.eu',
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
'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\\Entity\\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\\Entity\\SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\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\\Entity\\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 = '@Application/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' => 'accounts@ourhoneybee.eu',
'userName' => 'accounts@ourhoneybee.eu',
'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
// '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;
}
private function uploadMeetingFile($file, $request)
{
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/meeting/';
$uploadedFilePath = '';
if ($file != null) {
$fileName = uniqid() . '.' . $file->guessExtension();
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file->move($upl_dir, $fileName);
$uploadedFilePath = 'uploads/meeting/' . $fileName;
}
return $uploadedFilePath;
}
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_goc = $this->getDoctrine()->getManager('company_group');
$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_goc->getRepository('CompanyGroupBundle\\Entity\\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();
$existingUser = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy([
'globalId' => $centralData['globalId']
]);
if ($existingUser) {
return new JsonResponse([
'status' => 'info',
'message' => 'User is already onboarded',
'userId' => $existingUser->getUserId(),
'redirectUrl' => 'dashboard'
]);
}
$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\\Entity\\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\\Entity\\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\\Entity\\Company')->find($companyId);
$companyName = $company ? $company->getName() : '';
$newAccess = [
'userType' => 2,
'userTypeName' => UserConstants::$userTypeName[2],
'globalId' => $applicantId,
'serverId' => 1,
'serverUrl' => $request->getSchemeAndHttpHost(),
'serverPort' => 80,
'systemType' => '_ERP_',
'companyId' => 1,
'appId' => $appId,
'companyLogoUrl' => '/uploads/CompanyImage/company_image' . $request->request->get('appId') . '.png',
'companyName' => $companyName,
'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
array(
'globalId' => $applicantId,
'appId' => $appId,
'authenticate' => 1,
'userType' => 2,
'userTypeName' => UserConstants::$userTypeName[2]
)
)
),
'userCompanyList' => [],
];
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/update_token_storage';
$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 => json_encode($newAccess)
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
return new JsonResponse([
'status' => 'success',
'message' => 'User onboarded successfully',
'redirectUlr' => 'dashboard',
'returnData' => $retData,
'errorData' => $errData
]);
}
public function UpdateTokenStorageAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$newAccess = $request->request->all();
$appId = isset($newAccess['appId']) ? $newAccess['appId'] : null;
$globalId = isset($newAccess['globalId']) ? $newAccess['globalId'] : null;
$sesssionData = MiscActions::UpdateCompanyListInSession(
$em_goc,
$globalId,
1,
1,
1,
$newAccess
);
return new JsonResponse([
'status' => 'success',
'message' => 'Token storage updated',
'newaccess' => $newAccess
]);
}
/**
* Authenticated launchers for the public HR letters (salary certificate / appointment letter).
*
* Security (IDOR fix): the public letter routes accept a RAW numeric employee id + appId query
* param, so a plain link like /public/252?appId=9050 is enumerable and leaks salary/PII across
* tenants without any auth. Instead of exposing that raw form from the employee list, the list
* now links here — a SESSION-PROTECTED route (SessionCheckInterface). We mint the encrypted
* token server-side from the CURRENT session's appId (so a user can only ever produce tokens for
* their own tenant) and redirect to the public route with that opaque, non-guessable token. The
* public action already decrypts the non-numeric id form.
*/
public function SalaryCertificateLaunchAction(Request $request, $id)
{
return $this->redirectToRoute('salary_certificate', array(
'id' => $this->buildEncryptedEmployeeDocToken($request, $id)
));
}
public function AppointmentLetterLaunchAction(Request $request, $id)
{
return $this->redirectToRoute('appointment_letter', array(
'id' => $this->buildEncryptedEmployeeDocToken($request, $id)
));
}
/**
* Encrypts {id, appId, dt} for a public employee-document link. appId comes from the session
* (never the request) so the token is always scoped to the caller's own tenant.
*/
private function buildEncryptedEmployeeDocToken(Request $request, $id)
{
$payload = array(
'id' => (int) $id,
'appId' => (int) $this->getLoggedUserAppId($request),
'dt' => (new \DateTime())->format('Y-m-d'),
);
return $this->get('url_encryptor')->encrypt(json_encode($payload));
}
public function EmployeeListAction(Request $data)
{
$em = $this->getDoctrine()->getManager();
if ($data->isMethod('GET')) {
return $this->render("@Application/pages/human_resource/list/list_employee.html.twig", array(
'page_title' => 'Employee List',
));
}
}
/**
* Employee transaction profile — a single page (modelled on the Client Profile) that
* surfaces, for one employee: their expense activity (approved + pending), the payments
* they have taken (payslip disbursements), and their payslip history.
* Data sources are all existing tables — no schema change:
* • employee_details → the person
* • expense_invoice.expense_of_employee_id (+ approved) → expenses they did
* • payslip.sys_id = employee id → payslips / salary paid
*/
public function EmployeeProfileAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$employee = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findOneBy(
array('id' => $id)
);
if (!$employee) {
$this->addFlash('error', 'Employee not found.');
return $this->redirect($this->generateUrl('hrm_cockpit'));
}
// ── Expenses done by this employee ─────────────────────────────────────────────
$expenses = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->findBy(
array('expenseOfEmployeeId' => $id),
array('expenseInvoiceDate' => 'DESC')
);
$expApprovedCount = 0; $expApprovedAmount = 0.0;
$expPendingCount = 0; $expPendingAmount = 0.0;
$expOtherCount = 0; $expOtherAmount = 0.0;
$advanceTaken = 0.0;
$expenseRows = array();
foreach ($expenses as $e) {
$status = (int) $e->getApproved();
$amount = (float) $e->getInvoiceAmount();
$advance = (float) $e->getAdvanceAmount();
$advanceTaken += $advance;
if ($status === GeneralConstant::APPROVED) {
$expApprovedCount++; $expApprovedAmount += $amount;
$statusLabel = 'Approved'; $statusClass = 'approved';
} elseif ($status === GeneralConstant::APPROVAL_STATUS_PENDING) {
$expPendingCount++; $expPendingAmount += $amount;
$statusLabel = 'Pending'; $statusClass = 'pending';
} else {
$expOtherCount++; $expOtherAmount += $amount;
$statusLabel = ($status === 0) ? 'Declined' : 'Other'; $statusClass = 'other';
}
$expenseRows[] = array(
'id' => $e->getExpenseInvoiceId(),
'documentHash'=> $e->getDocumentHash(),
'date' => $e->getExpenseInvoiceDate(),
'amount' => $amount,
'advance' => $advance,
'statusLabel' => $statusLabel,
'statusClass' => $statusClass,
);
}
// ── Payslips / payments taken ──────────────────────────────────────────────────
$payslips = $em->getRepository('ApplicationBundle\\Entity\\Payslip')->findBy(
array('sysId' => $id),
array('payslipId' => 'DESC')
);
$payslipCount = 0; $payslipTotalPaid = 0.0;
$payslipRows = array();
foreach ($payslips as $p) {
$net = (float) $p->getToTalSalary();
$payslipCount++; $payslipTotalPaid += $net;
$payslipRows[] = array(
'id' => $p->getPayslipId(),
'documentHash'=> $p->getDocumentHash(),
'date' => $p->getCreatedAt(),
'net' => $net,
'status' => $p->getStatus(),
);
}
// ── All vouchers touching this employee's ledger head(s) ───────────────────────
// employee.employee_id → employee_details.id; that row carries the person's GL
// account (accounts_head_id) and advance account (advance_head_id). Every voucher
// leg posted to either head is "a voucher related to this employee".
$conn = $em->getConnection();
$voucherRows = array();
$voucherDebitTotal = 0.0; $voucherCreditTotal = 0.0;
try {
$empLedger = $conn->fetchAssociative(
"SELECT accounts_head_id, advance_head_id FROM employee WHERE employee_id = ? LIMIT 1",
array((int) $id)
);
$heads = array();
if ($empLedger) {
if (!empty($empLedger['accounts_head_id'])) { $heads[] = (int) $empLedger['accounts_head_id']; }
if (!empty($empLedger['advance_head_id'])) { $heads[] = (int) $empLedger['advance_head_id']; }
}
if (!empty($heads)) {
$placeholders = implode(',', array_fill(0, count($heads), '?'));
$sql = "SELECT t.transaction_id, t.document_hash, t.transaction_date, t.description,
td.amount, td.position
FROM acc_transaction_details td
JOIN acc_transactions t ON t.transaction_id = td.transaction_id
WHERE td.accounts_head_id IN ($placeholders)
AND (t.status = 1 OR t.status IS NULL)
ORDER BY t.transaction_date DESC, t.transaction_id DESC";
$rows = $conn->fetchAllAssociative($sql, $heads);
foreach ($rows as $r) {
$amt = (float) $r['amount'];
$isDebit = ($r['position'] === 'dr' || $r['position'] === 'DR');
if ($isDebit) { $voucherDebitTotal += $amt; } else { $voucherCreditTotal += $amt; }
$voucherRows[] = array(
'id' => $r['transaction_id'],
'documentHash'=> $r['document_hash'],
'date' => $r['transaction_date'],
'description' => $r['description'],
'debit' => $isDebit ? $amt : 0.0,
'credit' => $isDebit ? 0.0 : $amt,
);
}
}
} catch (\Throwable $e) {
// ledger lookup is best-effort — never break the profile page over it
$voucherRows = array();
}
// Resolve department + designation ids to names (dept → sys_department,
// desg → sys_department_position).
$deptName = '';
$desgName = '';
try {
$deptId = (int) $employee->getDept();
$desgId = (int) $employee->getDesg();
if ($deptId) {
$deptName = (string) $conn->fetchOne(
"SELECT department_name FROM sys_department WHERE department_id = ? LIMIT 1",
array($deptId)
);
}
if ($desgId) {
$desgName = (string) $conn->fetchOne(
"SELECT position_name FROM sys_department_position WHERE position_id = ? LIMIT 1",
array($desgId)
);
}
} catch (\Throwable $e) { /* names are best-effort */ }
$data = array(
'employee' => array(
'id' => $employee->getId(),
'empCode' => $employee->getEmpCode(),
'name' => trim($employee->getFirstname() . ' ' . $employee->getLastname()),
'department' => $deptName,
'designation' => $desgName,
'image' => $employee->getImage(),
'dept' => $employee->getDept(),
'joiningDate' => $employee->getJoiningDate(),
'status' => $employee->getEmpStatus(),
'phone' => $employee->getPhone() ?: $employee->getOfficialPhone(),
'email' => $employee->getEmail(),
),
'kpi' => array(
'expenseTotalCount' => count($expenses),
'expenseApprovedCount'=> $expApprovedCount,
'expenseApprovedAmount'=> $expApprovedAmount,
'expensePendingCount' => $expPendingCount,
'expensePendingAmount'=> $expPendingAmount,
'expenseOtherCount' => $expOtherCount,
'expenseOtherAmount' => $expOtherAmount,
'advanceTaken' => $advanceTaken,
'payslipCount' => $payslipCount,
'payslipTotalPaid' => $payslipTotalPaid,
'voucherCount' => count($voucherRows),
'voucherDebitTotal' => $voucherDebitTotal,
'voucherCreditTotal' => $voucherCreditTotal,
),
'expenseRows' => $expenseRows,
'payslipRows' => $payslipRows,
'voucherRows' => $voucherRows,
);
return $this->render('@Application/pages/human_resource/views/employee_profile.html.twig', array(
'page_title' => 'Employee Profile',
'data' => $data,
));
}
/**
* Full read-only Employee View for the tenant — surfaces every field captured on the
* employee-entry form, organised into sections (Personal, Employment, Payroll & Bank,
* Leave, Skills/Education/Experience, Documents). Lookup ids are resolved to names.
*/
public function EmployeeViewAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$e = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findOneBy(array('id' => $id));
if (!$e) {
$this->addFlash('error', 'Employee not found.');
return $this->redirect($this->generateUrl('hrm_cockpit'));
}
// best-effort single-value name lookup
$lookup = function ($sql, $val) use ($conn) {
if ($val === null || $val === '' || $val == 0) return '';
try { $v = $conn->fetchOne($sql, array($val)); return $v === false ? '' : (string) $v; }
catch (\Throwable $ex) { return ''; }
};
$jdec = function ($raw) {
// Some fields are already cast to arrays by the ORM; others are raw JSON strings.
if (is_array($raw)) return $raw;
if ($raw === null || $raw === '' ) return array();
$d = json_decode($raw, true);
return is_array($d) ? $d : array();
};
// Resolve related names
$deptName = $lookup("SELECT department_name FROM sys_department WHERE department_id = ? LIMIT 1", $e->getDept());
$desgName = $lookup("SELECT position_name FROM sys_department_position WHERE position_id = ? LIMIT 1", $e->getDesg());
$branchName = $lookup("SELECT name FROM branch WHERE branch_id = ? LIMIT 1", $e->getBranch());
$divName = $lookup("SELECT name FROM division WHERE division_id = ? LIMIT 1", $e->getDivision());
$supRow = null;
try {
$supRow = $conn->fetchAssociative("SELECT firstname, lastname FROM employee_details WHERE id = ? LIMIT 1", array((int) $e->getSupervisor()));
} catch (\Throwable $ex) { $supRow = null; }
$supName = $supRow ? trim(($supRow['firstname'] ?? '') . ' ' . ($supRow['lastname'] ?? '')) : '';
$bankName = $e->getBankName();
if (!$bankName) { $bankName = $lookup("SELECT bank_name FROM bank_list WHERE bank_id = ? LIMIT 1", $e->getBankId()); }
// Skills (JSON array of skill ids → names from tenant skill table)
$skillIds = $jdec($e->getSkill());
$skillNames = array();
if (!empty($skillIds)) {
foreach ($skillIds as $sid) {
$n = $lookup("SELECT name FROM skill WHERE skill_id = ? LIMIT 1", (int) $sid);
if ($n !== '') { $skillNames[] = $n; }
}
}
$sexList = \ApplicationBundle\Constants\EmployeeConstant::$sex;
$bloodList = \ApplicationBundle\Constants\EmployeeConstant::$BloodGroup;
$typeList = \ApplicationBundle\Constants\EmployeeConstant::$employeeType;
$fmtDate = function ($d) { return ($d instanceof \DateTimeInterface) ? $d->format('M d, Y') : ''; };
$data = array(
'id' => $e->getId(),
'name' => trim($e->getFirstname() . ' ' . $e->getLastname()),
'image' => $e->getImage(),
// Personal
'personal' => array(
'First Name' => $e->getFirstname(),
'Last Name' => $e->getLastname(),
'Date of Birth' => $fmtDate($e->getDob()),
'Gender' => (isset($sexList[$e->getSex()]) ? $sexList[$e->getSex()] : $e->getSex()),
'Blood Group' => (isset($bloodList[$e->getBlood()]) ? $bloodList[$e->getBlood()] : $e->getBlood()),
'Religion' => $e->getReligion(),
'NID' => $e->getNid(),
'TIN' => $e->getTin(),
"Father's Name" => $e->getFather(),
"Mother's Name" => $e->getMother(),
'Spouse' => $e->getSpouse(),
'Nationality/Country' => $e->getCountry(),
'Residency Status' => $e->getResidencyStatus(),
),
// Contact
'contact' => array(
'Phone' => $e->getPhone(),
'Official Phone' => $e->getOfficialPhone(),
'Email' => $e->getEmail(),
'Emergency Contact' => $e->getEmmContact() ?: $e->getEmergencyContactNumber(),
'Postal Code' => $e->getPostalCode(),
'Current Address' => $e->getCurrAddr(),
'Permanent Address' => $e->getPermAddr(),
),
// Employment
'employment' => array(
'Employee Code' => $e->getEmpCode(),
'Username' => $e->getUsername(),
'Designation' => $desgName ?: $e->getDesg(),
'Department' => $deptName ?: $e->getDept(),
'Branch' => $branchName ?: $e->getBranch(),
'Division' => $divName ?: $e->getDivision(),
'Supervisor' => $supName,
'Employment Type' => (isset($typeList[$e->getEmpType()]) ? $typeList[$e->getEmpType()] : $e->getEmpType()),
'Employee Level' => $e->getEmployeeLevel(),
'Joining Date' => $fmtDate($e->getJoiningDate()),
'Valid Till' => $fmtDate($e->getEmpValidTill()),
'Status' => ($e->getEmpStatus() == 1 ? 'Active' : 'Inactive'),
'Current Employment' => $e->getCurrentEmployment(),
),
// Payroll & Bank
'bank' => array(
'Beneficiary Name' => $e->getBeneficiaryName(),
'Bank' => $bankName,
'Branch Name' => $e->getBranchName(),
'Account No' => $e->getBankAcc(),
'Account Type' => $e->getBankAccType(),
'Routing Code' => $e->getRoutingCode(),
'SWIFT Code' => $e->getSwiftCode(),
'Valid From' => $fmtDate($e->getBankAccValidFrom()),
'Valid To' => $fmtDate($e->getBankAccValidTo()),
),
// Leave allocations
'leave' => array(
'Sick (SL)' => $e->getSlQty(),
'Casual (CL)' => $e->getClQty(),
'Earned (EL)' => $e->getElQty(),
'Maternity (ML)' => $e->getMlQty(),
'Weekly Holiday' => $e->getWeeklyHoliday(),
),
'skills' => $skillNames,
'educationData' => $jdec($e->getEducationData()),
'experienceData' => $jdec($e->getWorkExperienceData()),
'languagesData' => $jdec($e->getLanguagesData()),
);
return $this->render('@Application/pages/human_resource/views/employee_view.html.twig', array(
'page_title' => 'Employee View',
'data' => $data,
));
}
public function OrganizationChartAction()
{
$em = $this->getDoctrine()->getManager();
$Reponse = HumanResource::TwigDataForOrgChart($em);
return $this->render('@Application/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()->fetchAllAssociative($query);
$res = $stmt;
// 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');
$session = $data->getSession();
// $token = $session->get(UserConstants::USER_TOKEN);
// $providedToken = $data->headers->get('auth-token');
//
// if (empty($providedToken) || $providedToken !== $token) {
// return new JsonResponse([
// 'status' => 'error',
// 'message' => 'Token not match or missing',
// ], 401);
// }
$workHourPolicy = $em->getRepository('ApplicationBundle\\Entity\\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);
}
// 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')) {
if ($data->request->get('requestFromMobile')) {
$empId = $data->request->get('employeeId');
$userId = $data->request->get('userId', 0);
} else {
$empId = $data->request->get('employeeId', 0);
$userId = $data->request->get('userId', $data->request->get('id', 0));
}
$dtTs = $data->request->get('timeTs', 0);
$timeZoneStr = '+0000';
if ($dtTs == 0) {
$currTsTime = new \DateTime();
$dtTs = $currTsTime->format('U');
} else {
$currTsTime = new \DateTime('@' . $dtTs);
}
$today = new \DateTime(date('y-m-d'));
$currTsTime->setTimezone(new \DateTimeZone('UTC'));
$attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' . $timeZoneStr);
$appId = $data->getSession()->get(UserConstants::USER_APP_ID);
$geofenceContext = array(
'lat' => $data->request->get('lat'),
'lng' => $data->request->get('lng'),
'accuracy' => $data->request->get('accuracy'),
'locationAccuracy' => $data->request->get('locationAccuracy'),
'gpsAccuracy' => $data->request->get('gpsAccuracy'),
'isMockLocation' => $data->request->get('isMockLocation'),
'mock_location' => $data->request->get('mock_location'),
'isRemoteWork' => $data->request->get('isRemoteWork'),
'remote_work' => $data->request->get('remote_work'),
);
$response = MiscActions::autoAttendanceGeneral($this->getDoctrine()->getManager(), $empId, $userId, $appId, $dtTs, $options, $data->request->get('requestFromMobile'), HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED, $geofenceContext);
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.',
)
);
} else {
if ($data->get('manualAttendance')) {
return $this->render(
'@Application/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 AttendanceForAppAction(Request $data, $remoteVerify = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $data->getSession();
$token = $session->get(UserConstants::USER_TOKEN);
$providedToken = $data->headers->get('auth-token');
if (empty($providedToken) || $providedToken !== $token) {
return new JsonResponse([
'status' => 'error',
'message' => 'Token not match or missing',
], 401);
}
$workHourPolicy = $em->getRepository('ApplicationBundle\\Entity\\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);
}
// 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(
'@Application/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(
'@Application/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(
'@Application/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);
$attachmentValidationError = $this->validateLeaveAttachmentFiles($request->files);
if ($attachmentValidationError !== null) {
$this->addFlash('error', $attachmentValidationError);
if ($data->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'errorStr' => $attachmentValidationError,
));
} else {
return $this->redirectToRoute('employee_leave');
}
}
$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 ($this->getLeaveUploadedFiles($request->files) as $uploadedFile) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$extension = $this->getLeaveAttachmentExtension($uploadedFile);
$size = $uploadedFile->getSize();
$fileName = 'LDOC_' . $applicationId . '_' . (md5(uniqid())) . '.' . $extension;
$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->setName($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\\Entity\\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(
'@Application/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);
$attachmentValidationError = $this->validateLeaveAttachmentFiles($data->files);
if ($attachmentValidationError !== null) {
$this->addFlash('error', $attachmentValidationError);
return $this->redirectToRoute('employee_leave');
}
$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(
'@Application/pages/human_resource/views/leave_application_view.html.twig',
array(
'page_title' => 'View Leave Application',
'Applicant' => $TwigData['Applicant'],
'Application' => $TwigData['Application'],
'LeaveType' => $TwigData['LeaveType'],
'LeaveCategory' => $TwigData['LeaveCategory'],
'leaveDataArray' => $TwigData['leaveDataArray'],
'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);
$Authorizations = System::getSignatureListForDocumentPrint($em, array_flip(GeneralConstant::$Entity_list)['EmployeeLeaveApplication'], $id);
$TwigData = HumanResource::TwigDataForViewLeaveApplication($em, $request, $id);
if ($TwigData['HasErr']) {
return new JsonResponse(array(
'success' => false,
'msg' => $TwigData['Msg']
));
}
$ApplicationCategory = $TwigData['Application']->getLeaveCategory();
$ApplicationType = ($ApplicationCategory != 1 && $ApplicationCategory != 2) ? $TwigData['LeaveType'] : '';
return $this->render(
'@Application/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(),
'Authorizations' => $Authorizations,
'ApplicationType' => $ApplicationType,
'ApplicationCategory' => $ApplicationCategory,
'Applicant' => $TwigData['Applicant'],
'Application' => $TwigData['Application'],
'LeaveType' => $TwigData['LeaveType'],
'LeaveCategory' => $TwigData['LeaveCategory'],
'leaveDataArray' => $TwigData['leaveDataArray'],
'FrwdEmp' => $TwigData['FrwdEmp'],
'ApplicantDesg' => $TwigData['ApplicantDesg'],
'approval_status' => $TwigData['approval_status'],
'approval_data' => $TwigData['approval_data'],
'document_log' => $TwigData['document_log'],
'red' => 0,
'invoice_footer' => 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("@Application/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('@Application/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(
'@Application/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('@Application/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('@Application/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 AttendanceCustomReportAction(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('@Application/pages/human_resource/report/custom_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('@Application/pages/human_resource/report/custom_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(
'@Application/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 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('@Application/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('@Application/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(
'@Application/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 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('@Application/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 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\\Entity\\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\\Entity\\EducationQualification')->findAll();
$employeeIds = $em->getRepository('ApplicationBundle\\Entity\\Employee')->findAll();
$location = HumanResourceConstant::$location;
$salaryPer = HumanResourceConstant::$salaryPer;
$workExperience = HumanResourceConstant::$workExperience;
$jobOpeningStatus = HumanResourceConstant::$jobOpeningStatus;
$compatibility = HumanResourceConstant::$compatibility;
return $this->render('@Application/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\\Entity\\EntitySkill')->findAll();
//$companyId = $this->getLoggedUserCompanyId($request);
$gender = HumanResourceConstant::$sex;
$blood = HumanResourceConstant::$BloodGroup;
//$userId = $session->get(UserConstants::USER_ID);
return $this->render('@Application/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\\Entity\\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('@Application/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\\Entity\\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\\Entity\\JobRecruitment')->find($id);
$em_goc = $this->getDoctrine()->getManager('company_group');
$applicantApplicationList = $em_goc->getRepository("CompanyGroupBundle\\Entity\\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('@Application/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\\Entity\\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('@Application/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\\Entity\\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('@Application/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)['EmployeePerformanceEvolution'],
// $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',
// 'Document Added.'
// );
// $url = $this->generateUrl(
// 'create_employee_performance_evaluation'
// );
// return $this->redirect($url);
}
}
$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('@Application/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('@Application/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\\Entity\\EmployeeDetails')->findAll();
$skill = $em->getRepository('ApplicationBundle\\Entity\\Skill')->findAll();
return $this->render('@Application/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(
'@Application/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(
'@Application/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(
'@Application/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(
'@Application/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 deleteLastAttendanceAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$lastAttendance = $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance')
->createQueryBuilder('ea')
->orderBy('ea.id', 'DESC')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
$lastAttendanceLog = $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')
->createQueryBuilder('eal')
->orderBy('eal.id', 'DESC')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
$deletedCount = 0;
if ($lastAttendance) {
$em->remove($lastAttendance);
$deletedCount++;
}
if ($lastAttendanceLog) {
$em->remove($lastAttendanceLog);
$deletedCount++;
}
$em->flush();
return new JsonResponse(
[
'success' => true,
'message' => "Deleted `$deletedCount` rows from attendance tables."
]
);
}
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, []);
// Same guard as HumanResource::TwigDataForScheduledMeetingView — an unmapped type must
// not take the page down.
$mtKey = $scheduledMeeting->getMeetingType();
$meetingType = isset(MeetingSchedulingConstant::$meetingType[$mtKey])
? MeetingSchedulingConstant::$meetingType[$mtKey]
: ($mtKey === null || $mtKey === '' ? 'Meeting' : 'Meeting (type ' . $mtKey . ')');
foreach ($sendEmailInvitationTo as $key => $email) {
$name = ucWords(str_replace("_", " ", $key));
$bodyHtml = '';
$bodyTemplate = '@Application/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(
'@Application/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(
'@Application/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 MeetingSchedulingForAppAction(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$mailer = $this->get('mail_module');
$helper = new HumanResourceHelper($em, $mailer);
try {
$data = $request->request->all();
$files = $request->files->all();
$companyId = $this->getLoggedUserCompanyId($request);
$meeting = $helper->prepareMeeting($data, $session);
$agendaList = [];
if (!empty($data['agendaList']) && is_array($data['agendaList'])) {
foreach ($data['agendaList'] as $index => $agendaData) {
$agenda = [
'title' => $agendaData['title'] ?? null,
'desc' => $agendaData['desc'] ?? null,
'notes' => $agendaData['notes'] ?? null,
'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
'otherDocuments' => [],
];
if (!empty($files['agendaList'][$index]['otherDocuments'])) {
foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
$uploadedFilePath = $this->uploadMeetingFile($uploadedFile, $request);
if ($uploadedFilePath) {
$agenda['otherDocuments'][] = [
'fileName' => basename($uploadedFilePath),
'path' => $uploadedFilePath,
'type' => $uploadedFile->getClientOriginalExtension(),
];
}
}
}
$agendaList[] = $agenda;
}
}
$meeting->setAgendaList(json_encode($agendaList));
[$internalInfo, $otherInfo, $internalIds] = $helper->resolveParticipants(
$data['guests'] ?? [],
$session->get('userEmployeeId')
);
// Save **full participant objects** to DB
$meeting->setInternalParticipantIds(!empty($internalInfo) ? json_encode($internalInfo) : null);
$meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
$meeting->setParticipantInfo(json_encode([
'internal' => $internalInfo,
'other' => $otherInfo,
]));
// Persist the meeting
$em->persist($meeting);
$em->flush();
// Send invitations
$helper->sendInvitations($meeting, $internalIds, $otherInfo, $companyId);
return new JsonResponse([
'success' => true,
'message' => 'Meeting scheduled successfully',
'meetingId' => $meeting->getScheduleId(),
'documentHas' => $meeting->getDocumentHash(),
]);
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}
}
public function updateMeetingForAppAction(Request $request, int $meetingId): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$mailer = $this->get('mail_module');
$helper = new HumanResourceHelper($em, $mailer);
try {
$data = $request->request->all();
$files = $request->files->all();
$meeting = $em->getRepository(ScheduledMeeting::class)->find($meetingId);
if (!$meeting) {
return new JsonResponse(['success' => false, 'error' => 'Meeting not found'], 404);
}
$meeting->setTitle($data['title'] ?? $meeting->getTitle());
$meeting->setSpecialType($data['specialType'] ?? $meeting->getSpecialType());
$meeting->setStartAt(!empty($data['startAt']) ? new \DateTime($data['startAt']) : $meeting->getStartAt());
$meeting->setEndAt(!empty($data['endAt']) ? new \DateTime($data['endAt']) : $meeting->getEndAt());
$meeting->setMeetingType($data['meetingType'] ?? $meeting->getMeetingType());
$meeting->setLocation($data['location'] ?? $meeting->getLocation());
$meeting->setRoomId($data['roomId'] ?? $meeting->getRoomId());
$meeting->setDesc($data['desc'] ?? $meeting->getDesc());
$meeting->setLastModifiedDate(new \DateTime());
if (isset($data['agendaList']) && is_array($data['agendaList'])) {
$agendaList = [];
foreach ($data['agendaList'] as $index => $agendaData) {
$agenda = [
'title' => $agendaData['title'] ?? null,
'desc' => $agendaData['desc'] ?? null,
'notes' => $agendaData['notes'] ?? null,
'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
'otherDocuments' => [],
];
if (!empty($files['agendaList'][$index]['otherDocuments'])) {
foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
$uploadedFilePath = $this->uploadMeetingFile($uploadedFile, $request);
if ($uploadedFilePath) {
$agenda['otherDocuments'][] = [
'fileName' => basename($uploadedFilePath),
'path' => $uploadedFilePath,
'type' => $uploadedFile->getClientOriginalExtension(),
];
}
}
}
if (!empty($agendaData['otherDocumentsExisting'])) {
$agenda['otherDocuments'] = array_merge(
$agenda['otherDocuments'],
$agendaData['otherDocumentsExisting']
);
}
$agendaList[] = $agenda;
}
$meeting->setAgendaList(json_encode($agendaList));
}
if (isset($data['guests'])) {
[$internalIds, $otherInfo] = $helper->resolveParticipants($data['guests'], $session->get('userEmployeeId'));
$meeting->setInternalParticipantIds(!empty($internalIds) ? json_encode($internalIds) : null);
$meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
}
$em->persist($meeting);
$em->flush();
if (isset($internalIds) || isset($otherInfo)) {
$helper->sendInvitations($meeting, $internalIds ?? [], $otherInfo ?? [], $meeting->getCompanyId());
}
return new JsonResponse([
'success' => true,
'message' => 'Meeting updated successfully',
'meetingId' => $meeting->getScheduleId(),
'facilitator' => ['id' => $meeting->getFacilitatorId(), 'name' => $meeting->getFacilitatorName()],
'companyId' => $meeting->getCompanyId(),
'branchId' => $meeting->getBranchId(),
'internalParticipants' => json_decode($meeting->getInternalParticipantIds(), true) ?? [],
'otherParticipants' => json_decode($meeting->getOtherParticipantInfo(), true) ?? [],
'agendas' => json_decode($meeting->getAgendaList(), true) ?? [],
]);
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}
}
public function GetDocumentsForMeetingScheduleAppAction(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$hrHelper = new HumanResourceHelper($em);
try {
$documents = $hrHelper->getAllDocumentsFromApproval($request);
return ResponseStructure::success($documents, 'Documents fetched successfully');
} catch (\Exception $e) {
return ResponseStructure::error($e->getMessage());
}
}
public function getMeetingsByDateAction(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$type = $request->query->get('type'); // Day, Week, Month, Yearly, Custom
$repo = $em->getRepository(ScheduledMeeting::class);
$today = new \DateTime();
$fromDate = null;
$toDate = (clone $today)->setTime(23, 59, 59);
switch ($type) {
case 'Day':
$fromDate = (clone $today)->setTime(0, 0, 0);
break;
case 'Week':
$fromDate = (clone $today)->modify('-6 days')->setTime(0, 0, 0);
break;
case 'Month':
$fromDate = (clone $today)->modify('-30 days')->setTime(0, 0, 0);
break;
case 'Yearly':
$fromDate = (clone $today)->modify('-1 year')->setTime(0, 0, 0);
break;
case 'Custom':
$start = $request->query->get('start');
$end = $request->query->get('end');
if (!$start || !$end) {
return new JsonResponse(['error' => 'Start and end date are required for Custom type'], 400);
}
$fromDate = new \DateTime($start . " 00:00:00");
$toDate = new \DateTime($end . " 23:59:59");
break;
default:
return new JsonResponse(['error' => 'Invalid type parameter'], 400);
}
$meetings = $repo->createQueryBuilder('pv')
->where('pv.startAt >= :fromDate')
->andWhere('pv.startAt <= :toDate')
->setParameter('fromDate', $fromDate)
->setParameter('toDate', $toDate)
->orderBy('pv.startAt', 'DESC')
->getQuery()
->getResult();
$data = [];
foreach ($meetings as $meeting) {
$data[] = [
'id' => $meeting->getScheduleId(),
'title' => $meeting->getTitle(),
'desc' => $meeting->getDesc(),
'startAt' => $meeting->getStartAt()->format('Y-m-d H:i:s'),
'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
'roomId' => $meeting->getRoomId(),
'meetingType' => $meetingType[$meeting->getMeetingType()] ?? null,
'location' => $meeting->getLocation(),
'participant' => json_decode($meeting->getParticipantInfo()),
'status' => $meeting->getStatus(),
'approved' => (bool)$meeting->getApproved(),
];
}
return new JsonResponse([
'success' => true,
'message' => 'Scheduled Meeting data retrieved successfully',
'type' => $type,
'fromDate' => $fromDate->format('Y-m-d'),
'toDate' => $toDate->format('Y-m-d'),
'count' => count($data),
'data' => $data,
]);
}
public function getMeetingByYearlyAction(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$yearParam = $request->query->get('year');
try {
$data = HumanResourceHelper::GetMeetingByYearlyAction($em, $yearParam);
return new JsonResponse($data, 200);
} catch (\Exception $e) {
return new JsonResponse([
'success' => false,
'error' => $e->getMessage()
], 400);
}
}
public function getMeetingByIdAction(Request $request, int $id): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$meeting = $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
if (!$meeting) {
return new JsonResponse([
'success' => false,
'error' => 'Meeting not found'
], 404);
}
return new JsonResponse([
'success' => true,
'meeting' => [
'id' => $meeting->getScheduleId(),
'docHash' => $meeting->getDocumentHash(),
'title' => $meeting->getTitle(),
'desc' => $meeting->getDesc(),
'specialType' => $meeting->getSpecialType(),
'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('Y-m-d H:i:s') : null,
'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
'meetingType' => $meeting->getMeetingType(),
'location' => $meeting->getLocation(),
'roomId' => $meeting->getRoomId(),
'facilitator' => [
'id' => $meeting->getFacilitatorId(),
'name' => $meeting->getFacilitatorName()
],
'companyId' => $meeting->getCompanyId(),
'branchId' => $meeting->getBranchId(),
'agendaList' => $meeting->getAgendaList() ? json_decode($meeting->getAgendaList(), true) : [],
'internalParticipants' => $meeting->getInternalParticipantIds() ? json_decode($meeting->getInternalParticipantIds(), true) : [],
'otherParticipants' => $meeting->getOtherParticipantInfo() ? json_decode($meeting->getOtherParticipantInfo(), true) : [],
'createdAt' => $meeting->getCreatedAt()->format('Y-m-d H:i:s'),
]
]);
}
public function updateMeetingAction(Request $request, int $id): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$meeting = $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
if (!$meeting) {
return new JsonResponse(['success' => false, 'error' => 'Meeting not found'], 404);
}
$data = json_decode($request->getContent(), true);
if (!$data) {
$data = $request->request->all();
}
if (!$data) {
return new JsonResponse(['success' => false, 'error' => 'Invalid data'], 400);
}
if (isset($data['title'])) $meeting->setTitle($data['title']);
if (isset($data['desc'])) $meeting->setDesc($data['desc']);
if (isset($data['startAt'])) $meeting->setStartAt(new \DateTime($data['startAt']));
if (isset($data['endAt'])) $meeting->setEndAt(new \DateTime($data['endAt']));
if (isset($data['location'])) $meeting->setLocation($data['location']);
if (isset($data['meetingType'])) $meeting->setMeetingType($data['meetingType']);
if (isset($data['roomId'])) $meeting->setRoomId($data['roomId']);
if (isset($data['agendaList'])) {
$agendaList = is_array($data['agendaList']) ? $data['agendaList'] : json_decode($data['agendaList'], true);
$meeting->setAgendaList(json_encode($agendaList));
}
$meeting->setLastModifiedDate(new \DateTime());
$em->flush();
return new JsonResponse([
'success' => true,
'message' => 'Meeting updated successfully',
'meetingId' => $meeting->getScheduleId()
]);
}
public function deleteMeetingAction(Request $request, int $id): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$meeting = $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
if (!$meeting) {
return new JsonResponse(['success' => false, 'error' => 'Meeting not found'], 404);
}
$em->remove($meeting);
$em->flush();
return new JsonResponse([
'success' => true,
'message' => 'Meeting deleted successfully',
'deletedId' => $id
]);
}
public function searchParticipantByEmailAction(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$email = trim($request->query->get('email'));
if (empty($email)) {
return new JsonResponse([
'success' => false,
'error' => 'Email is required'
], 400);
}
try {
$companyId = $this->getLoggedUserCompanyId($request);
$client = $em->getRepository(\ApplicationBundle\Entity\AccClients::class)
->findOneBy(['email' => $email]);
if ($client) {
return new JsonResponse([
'success' => true,
'type' => 'client',
'data' => [
'client_id' => $client->getClientId(),
'company_id' => $client->getCompanyId(),
'client_name' => $client->getClientName(),
'email' => $client->getEmail(),
]
]);
}
$employee = $em->getRepository(\ApplicationBundle\Entity\Employee::class)
->findOneBy(['email' => $email]);
if ($employee) {
return new JsonResponse([
'success' => true,
'type' => 'employee',
'data' => [
'name' => $employee->getName(),
'email' => $employee->getEmail(),
'user_id' => $employee->getUserId(),
'address_contact' => $employee->getAddressContact(),
]
]);
}
return new JsonResponse([
'success' => false,
'error' => 'No client or employee found for this email'
], 404);
} catch (\Exception $e) {
return new JsonResponse([
'success' => false,
'error' => $e->getMessage()
], 500);
}
}
public function GetRoomInformationForMeetingAction(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$onlyAvailable = $request->query->getBoolean('onlyAvailable', false);
$rooms = HumanResourceHelper::getRooms($em, $onlyAvailable);
return new JsonResponse([
'status' => 'success',
'data' => $rooms
]);
}
public function MeetingTypeAction(Request $request)
{
return new JsonResponse([
'success' => true,
'data' => MeetingSchedulingConstant::$meetingType
]);
}
public function GetPriorityListAction()
{
$priority = HumanResourceHelper::priorityList();
return new JsonResponse([
'success' => true,
'data' => $priority
]);
}
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(
'@Application/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(
'@Application/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(
'@Application/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(
'@Application/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_') {
$stmt = $em->getConnection()->fetchAllAssociative(
"SELECT * FROM questionnaire WHERE 1 LIMIT 10"
);
} else {
$stmt = $em->getConnection()->fetchAllAssociative(
"SELECT * FROM questionnaire WHERE question_text LIKE :search LIMIT 10",
['search' => '%' . $search . '%']
);
}
$queryResult = $stmt;
$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\\Entity\\Skill')->findAll();
$courses = $em->getRepository('ApplicationBundle\\Entity\\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(
'@Application/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\\Entity\\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\\Entity\\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\\Entity\\SalarySegregationPolicy')->findOneBy(
// array(
// 'transactionId' => $id, ///material
//
// )
// );
}
} else {
}
}
$employeeIds = $em->getRepository("ApplicationBundle\\Entity\\Employee")->findAll();
$employeeType = HumanResourceConstant::$employeeType;
$employeeExpenseAllowanceTypes = HumanResourceConstant::$employeeExpenseAllowanceTypes;
$Designation = $em->getRepository("ApplicationBundle\\Entity\\SysDepartmentPosition")->findAll();
$branch = $em->getRepository("ApplicationBundle\\Entity\\Branch")->findAll();
$departments = $em->getRepository("ApplicationBundle\\Entity\\SysDepartment")->findAll();
$department = [];
foreach ($departments as $entry) {
$department[$entry->getDepartmentId()] = array(
'id' => $entry->getDepartmentId(),
'name' => $entry->getDepartmentName(),
);
}
return $this->render(
'@Application/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('@Application/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\\Entity\\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\\Entity\\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\\Entity\\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(
'@Application/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\\Entity\\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(
'@Application/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('@Application/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\\Entity\\EmployeeWorkplace')->findAll();
// $employee = $em->getRepository('ApplicationBundle\\Entity\\Employee')->findAll();
return $this->render('@Application/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\\Entity\\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('@Application/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('@Application/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\\Entity\\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('@Application/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('@Application/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;
// The bare `payslip` route carries no action default, so a plain GET used to match none of
// the branches below and fall out of the function returning null (a 500). It is reachable:
// ModuleConstant registers it as the "Payslip" Spotlight module, and disburse_salary.html
// POSTs to it to save signatures. Treat a bare GET as the list — what "Payslip" means —
// and leave the POST path alone.
if (!$action && !$req->isMethod('POST')) {
$action = 'list';
}
if ($action === 'list') {
$response = HumanResource::twigDataForPayslipList($em);
$approval_status = GeneralConstant::$approvalAction;
return $this->render(
'@Application/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(
'@Application/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'],
'emp_code' => $response['employeeCode'],
'employee_code' => $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,
'statutory_lines' => $response['statutory_lines'],
'statutory_total' => $response['statutory_total'],
'statutory_employer_total' => $response['statutory_employer_total'],
'statutory_country' => $response['statutory_country'],
'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(
'@Application/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'],
'emp_code' => $response['employeeCode'],
'employee_code' => $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,
'statutory_lines' => $response['statutory_lines'],
'statutory_total' => $response['statutory_total'],
'statutory_employer_total' => $response['statutory_employer_total'],
'statutory_country' => $response['statutory_country'],
'red' => 0
)
);
}
if ($req->isMethod('POST')) {
// TEMP DEBUG — capture the raw posted disburse payload (controller reloads reliably)
@file_put_contents($this->get('kernel')->getLogDir() . '/payslip_post_dbg.log',
'[' . date('H:i:s') . '] rowCount=' . (is_array($req->get('relevantEmployeeDataArray')) ? count($req->get('relevantEmployeeDataArray')) : 'not-array') .
' | firstRow=' . substr(json_encode($req->get('relevantEmployeeDataArray')[0] ?? 'MISSING'), 0, 600) . "\n", FILE_APPEND);
$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]);
}
// Never fall through returning null — an unknown action is a 404, not a 500.
throw $this->createNotFoundException('Unknown payslip action.');
}
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('@Application/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(
'@Application/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(
'@Application/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(
'@Application/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("@Application/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(
'@Application/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(
'@Application/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(
'@Application/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\\Entity\\HolidayCalendar')
->findBy(array())
]
);
}
public function HolidayViewAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$HolidaysCalendar = $em->getRepository(HolidayCalendar::class)->find($id);
$holidayCalendarDetails = $em->getRepository('ApplicationBundle\\Entity\\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('@Application/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\\Entity\\HolidayCalendar')
->findOneBy(array(
'holidayCalendarId' => $id
));
$holidayCalendarDetails = $em->getRepository('ApplicationBundle\\Entity\\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\\Entity\\HolidayCalendar')
->findOneBy(array(
'holidayCalendarId' => $id
));
$holidayCalendarDetails = $em->getRepository('ApplicationBundle\\Entity\\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->setName($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('@Application/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('@Application/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('@Application/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('@Application/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('@Application/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('@Application/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('@Application/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\\Entity\\BonusPolicy')
->findOneBy(
array(
'id' => $docId
)
);
//notify
$this->addFlash(
'success',
'Policy Successfully Updated.'
);
$url = $this->generateUrl(
'bonus_policy_list'
);
// 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"
//
// );
// bonus_policy_list has no {id} param — redirect to the list itself (appending
// /$docId produced an unmatched URL that fell back to the sales dashboard).
return $this->redirect($url);
}
}
//for edits
if ($id == 0) {
} else {
$extDocData = $em->getRepository('ApplicationBundle\\Entity\\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\\Entity\\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('@Application/pages/human_resource/input_forms/create_bonus_policy.html.twig', array(
'page_title' => (is_object($extDocData) ? 'Edit Bonus Policy' : 'Create Bonus Policy'),
'employeeIds' => $employeeIds,
'employeeType' => $employeeType,
'Designation' => $Designation,
'branch' => $branch,
'department' => $department,
// Edit support: when an id was supplied, $extDocData holds the loaded BonusPolicy so the
// form can pre-fill (docExists gates the edit bindings, same pattern as other forms).
'docExists' => (is_object($extDocData) ? 1 : 0),
'extDocData' => $extDocData,
));
}
public function BonusPolicyListAction()
{
$em = $this->getDoctrine()->getManager();
$bonusPolicy = $em->getRepository(BonusPolicy::class)->findAll();
return $this->render('@Application/pages/human_resource/list/bonus_policy_list.html.twig', array(
'page_title' => 'Bonus Policy List',
'bonusPolicy' => $bonusPolicy
));
}
/**
* Festival Bonus disbursement. GET shows the run form (pick a Bonus Policy + festival label +
* period); when a policy is selected it previews the eligible employees and their computed bonus
* amounts (reusing the payroll policy math). POST action=disburse persists standalone bonus
* payslips (payslipType=2) via BonusDisbursementService, which flow through the normal approval
* funnel and then into the payslip -> payment-voucher pipeline. Money never moves automatically.
*/
public function DisburseBonusAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$bonusPolicies = $em->getRepository(BonusPolicy::class)->findBy(
['approved' => GeneralConstant::APPROVED],
['updatedAt' => 'DESC', 'createdAt' => 'DESC', 'id' => 'DESC']
);
$policyId = (int) $request->get('policyId', 0);
$festivalLabel = trim((string) $request->get('festivalLabel', ''));
$fromStr = $request->get('fromDate', (new \DateTime('first day of this month'))->format('Y-m-d'));
$toStr = $request->get('toDate', (new \DateTime('last day of this month'))->format('Y-m-d'));
$from = new \DateTime($fromStr);
$to = new \DateTime($toStr);
$selectedPolicy = $policyId > 0 ? $em->getRepository(BonusPolicy::class)->find($policyId) : null;
$rows = [];
$totalBonus = 0;
if ($selectedPolicy) {
$rows = \ApplicationBundle\Modules\HumanResource\Service\BonusDisbursementService::computeBonusRows($em, $selectedPolicy, $from, $to);
foreach ($rows as $r) {
$totalBonus += (1 * $r['gross']);
}
}
// Disburse: persist the (optionally edited) bonus payslips.
if ($request->isMethod('POST') && $request->request->get('action') === 'disburse' && $selectedPolicy) {
$overrides = $request->request->get('amount', []); // id => amount
$overrideById = [];
if (is_array($overrides)) {
foreach ($overrides as $eid => $amt) {
$overrideById[(int) $eid] = 1 * $amt;
}
}
$createdIds = \ApplicationBundle\Modules\HumanResource\Service\BonusDisbursementService::persistBonusPayslips(
$em, $request, $selectedPolicy, $festivalLabel, $from, $to, $rows, $overrideById
);
$this->addFlash('success', count($createdIds) . ' bonus payslip(s) created for "' . ($festivalLabel ?: 'Festival Bonus') . '". Approve, then disburse against bank.');
return $this->redirectToRoute('payslip');
}
return $this->render('@Application/pages/human_resource/report/disburse_bonus.html.twig', array(
'page_title' => 'Bonus Disbursement',
'bonusPolicies' => $bonusPolicies,
'selectedPolicyId' => $policyId,
'festivalLabel' => $festivalLabel,
'fromDate' => $from->format('Y-m-d'),
'toDate' => $to->format('Y-m-d'),
'rows' => $rows,
'totalBonus' => $totalBonus,
));
}
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']]
['entity_view_route_path_name']
)
);
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\\Entity\\IncrementPolicy')
->findOneBy(
array(
'id' => $docId
)
);
//notify
$this->addFlash(
'success',
'Policy Successfully Updated.'
);
$url = $this->generateUrl(
'view_increment_policy'
);
return $this->redirect($url . "/" . $docId);
}
}
//for edits
if ($id == 0) {
} else {
$extDocData = $em->getRepository('ApplicationBundle\\Entity\\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\\Entity\\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('@Application/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('@Application/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('@Application/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\\Entity\\ConsultancyTopic')->findAll();
return $this->render('@Application/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\\Entity\\EntityCreateDocument')->findAll();
$topicList = $em->getRepository('CompanyGroupBundle\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\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('@Application/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\\Entity\\EntityCountryConsultantRequirements')->findAll();
$documentQRY = $em->getRepository('CompanyGroupBundle\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\PromoCode')->findAll();
$applicantList = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
$promoCodeId = $id;
$entity = [];
if ($promoCodeId != 0)
$entity = $em->getRepository('CompanyGroupBundle\\Entity\\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\\Entity\\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\\Entity\\EntityCreateDocument')->findAll();
$thisDoc = [];
if ($id != 0)
$thisDoc = $em->getRepository('CompanyGroupBundle\\Entity\\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('@Application/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\\Entity\\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\\Entity\\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\\Entity\\EntityCreateTopic')->findAll();
$applicant = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
$blogs = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateBlog')->findAll();
$topicIds = [];
foreach ($blogs as $blog) {
$topicIds [] = $blog->getTopicId();
}
// $topic = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findBy(
// array(
// 'id' => $topicIds
// )
// );
return $this->render('@Application/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\\Entity\\EntityCreateTopic')->findAll();
$applicant = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
$blogs = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateBlog')->find($id);
return $this->render('@Application/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('@Application/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\\Entity\\SysDepartmentPosition")->findAll();
$departments = $em->getRepository("ApplicationBundle\\Entity\\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 = '@Application/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' => \ApplicationBundle\Helper\MailerConfig::host(),
'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 = '@Application/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' => \ApplicationBundle\Helper\MailerConfig::host(),
'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('@Application/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('@Application/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\\Entity\\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\\Entity\\EmployeeAttendanceLog')->findOneBy(
// array(
// 'employeeId' => 3
// )
// );
$DateRange = [];
$holidayDates = $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')->findAll();
foreach ($holidayDates as $holiday) {
$holidaayData = array(
'startDate' => $holiday->getStartDate(),
'endDate' => $holiday->getEndDate(),
);
$DateRange = $holidaayData;
}
$employeeDataDetail = [];
$employeeDetail = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findOneBy(
array(
'id' => 3
)
);
// foreach($employeeDetail as $employee){
$employeeData = array(
'firstName' => $employeeDetail->getFirstname(),
'firstname' => $employeeDetail->getFirstname(),
'lastName' => $employeeDetail->getLastname(),
'lastname' => $employeeDetail->getLastname(),
'name' => trim($employeeDetail->getFirstname() . ' ' . $employeeDetail->getLastname()),
'empCode' => $employeeDetail->getEmpCode(),
'emp_code' => $employeeDetail->getEmpCode(),
'employeeCode' => $employeeDetail->getEmpCode(),
'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('@Application/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\\Entity\\EmployeeDetails')->find($id);
return new JsonResponse(
array(
'success' => true,
'firstName' => $employeeDetail->getFirstName(),
'firstname' => $employeeDetail->getFirstName(),
'lastName' => $employeeDetail->getLastName(),
'lastname' => $employeeDetail->getLastName(),
'name' => trim($employeeDetail->getFirstName() . ' ' . $employeeDetail->getLastName()),
'employeeCode' => $employeeDetail->getEmpCode(),
'emp_code' => $employeeDetail->getEmpCode(),
)
);
}
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\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\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('@Application/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));
$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', $request->request->get('employeeId', 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\\Entity\\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\\Entity\\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\\Entity\\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('@Application/pages/human_resource/attendance/create_attendance_amendment.html.twig', $returnData);
}
public function AttendanceAmendmentListAction(Request $request)
{
$data = [];
return $this->render('@Application/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('@Application/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('@Application/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('@Application/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('@Application/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('@Application/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\\Entity\\EmployeeDetails')->find($id);
// $employeeData = [];
// foreach ($employeeDetails as $employeeDetail) {
// $data = array(
// 'firstName' => $employeeDetail->getNid(),
//
//
//
// );
//
//
// $employeeData[] = $data;
// }
return $this->render('@Application/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\\Entity\\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();
$token = $session->get(UserConstants::USER_TOKEN);
$employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$planningItemId = $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID);
$attendanceData = $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendance');
$currentStatus = HumanResource::getCurrentStatusFromDb($attendanceData, $employeeId, $currentDate);
$providedToken = $request->headers->get('auth-token');
if (empty($providedToken) || $providedToken !== $token) {
return new JsonResponse([
'status' => 'error',
'message' => 'Token not match or missing',
], 401);
}
$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\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\EmployeeLeaveApplication')
->createQueryBuilder('L')
->select('COUNT(L.employeeLeaveApplicationId)')
->where('L.employeeId = :employeeId')
->setParameter('employeeId', $employeeId)
->getQuery()
->getSingleScalarResult();
// Get paginated results
$leaveRecords = $em->getRepository('ApplicationBundle\\Entity\\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)
->orderBy('L.employeeLeaveApplicationId', 'DESC') //
->getQuery()
->getResult();
// Count total approved (approved = 1)
$totalApproved = $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
->createQueryBuilder('L')
->select('COUNT(L.employeeLeaveApplicationId)')
->where('L.employeeId = :employeeId')
->andWhere('L.approved = 1')
->setParameter('employeeId', $employeeId)
->getQuery()
->getSingleScalarResult();
// Count total pending (approved = 3)
$totalPending = $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
->createQueryBuilder('L')
->select('COUNT(L.employeeLeaveApplicationId)')
->where('L.employeeId = :employeeId')
->andWhere('L.approved = 3')
->setParameter('employeeId', $employeeId)
->getQuery()
->getSingleScalarResult();
// Count total cancelled (approved = 0)
$totalCancelled = $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
->createQueryBuilder('L')
->select('COUNT(L.employeeLeaveApplicationId)')
->where('L.employeeId = :employeeId')
->andWhere('L.approved = 0')
->setParameter('employeeId', $employeeId)
->getQuery()
->getSingleScalarResult();
// 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',
];
}
$employee = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
->find($employeeId);
$totalLeaveBalance = 0;
for ($i = 1; $i <= 10; $i++) {
$getter = "getLeave{$i}Tkn";
$totalLeaveBalance += $employee->$getter();
}
// Final response with pagination meta
return new JsonResponse([
'success' => true,
'message' => 'Leave application list fetched successfully',
'totalLeaveBalance' => (int)($totalLeaveBalance ?? 0),
'totalApproved' => (int)($totalApproved ?? 0),
'totalPending' => (int)($totalPending ?? 0),
'totalCancelled' => (int)($totalCancelled ?? 0),
'data' => $formattedData,
'CurrentPage' => $page,
'limit' => $limit,
'total' => $total,
]);
}
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;
if ($id) {
$leaveSetting = $em->getRepository('ApplicationBundle\\Entity\\LeaveSettings')->find($id);
}
if (!$leaveSetting) {
$leaveSetting = new LeaveSettings();
}
$leaveSetting->setId($id);
$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');
}
$defaultLeaveType = HumanResourceConstant::$defaultLeaveType;
$savedLeaveSettings = $em->getRepository('ApplicationBundle\\Entity\\LeaveSettings')->findAll();
$useDefaultLeave = count($savedLeaveSettings) === 0;
$leaveSettings = array_map(function ($setting) {
return [
'id' => $setting->getId(),
'leaveTitle' => $setting->getLeaveTitle(),
'carryForwardType' => $setting->getCarryForwardType(),
'carryForwardQty' => $setting->getCarryForwardQty(),
'totalLeave' => $setting->getTotalLeave(),
'resetFrequencyType' => $setting->getResetFrequencyType(),
'resetFrequencyQty' => $setting->getResetFrequencyQty(),
'additionCondition' => $setting->getAdditionCondition(),
'additionConditionDuration' => $setting->getAdditionConditionDuration(),
];
}, $savedLeaveSettings);
return $this->render('@Application/pages/human_resource/input_forms/leave_settings.html.twig', [
'page_title' => 'Leave Settings',
'defaultLeaveType' => $defaultLeaveType,
'leaveSettings' => $leaveSettings,
'useDefaultLeave' => $useDefaultLeave,
]);
}
/**
* HRM Command Center — a cp-shell, SaaS-style dashboard: live workforce,
* attendance, leave/resignation queue and payroll cost trend at a glance.
* Every KPI query is wrapped fail-safe so the page can never 500 on a
* tenant whose schema/data differs.
*/
public function HrmCockpitAction(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$one = function ($sql, $p = []) use ($conn) { try { $v = $conn->fetchOne($sql, $p); return $v === false ? null : $v; } catch (\Throwable $e) { return null; } };
$all = function ($sql, $p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql, $p); } catch (\Throwable $e) { return []; } };
$activeHead = (int) $one("SELECT COUNT(*) FROM employee_details WHERE emp_status = 1");
$totalHead = (int) $one("SELECT COUNT(*) FROM employee_details");
$joiners30 = (int) $one("SELECT COUNT(*) FROM employee_details WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
// Composition by employment type (active only)
$typeLabels = [1 => 'Full-time', 2 => 'Part-time', 3 => 'Intern', 4 => 'Temporary', 5 => 'Contractual'];
$byType = [];
foreach ($all("SELECT emp_type t, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY emp_type") as $r) {
$byType[$typeLabels[(int) $r['t']] ?? ('Type ' . (int) $r['t'])] = (int) $r['c'];
}
// Composition by gender (sex stored as varchar — normalise common encodings)
$male = 0; $female = 0; $otherSex = 0;
foreach ($all("SELECT sex, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY sex") as $r) {
$s = strtolower(trim((string) $r['sex'])); $c = (int) $r['c'];
if (in_array($s, ['1', 'm', 'male'], true)) { $male += $c; }
elseif (in_array($s, ['2', 'f', 'female'], true)) { $female += $c; }
else { $otherSex += $c; }
}
// Attendance today
$presentToday = (int) $one("SELECT COUNT(DISTINCT employee_id) FROM employee_attendance WHERE DATE(created_at) = CURDATE()");
$attRate = $activeHead > 0 ? (int) round($presentToday * 100 / $activeHead) : 0;
// Queues (approval convention: 3 = pending)
$pendingLeave = (int) $one("SELECT COUNT(*) FROM employee_leave_application WHERE (delete_flag IS NULL OR delete_flag = 0) AND approved = 3");
$pendingResign = (int) $one("SELECT COUNT(*) FROM resign_application WHERE approved = 3");
// Payroll cost trend (last 6 periods)
$periods = $all(
"SELECT DATE_FORMAT(start_date, '%Y-%m') ym,
COUNT(*) slips, SUM(approved = 1) appr,
ROUND(SUM(payable_salary), 2) payable,
ROUND(SUM(CAST(eart AS DECIMAL(18,2))), 2) gross,
ROUND(SUM(CAST(dedt AS DECIMAL(18,2))), 2) ded
FROM payslip WHERE start_date IS NOT NULL
GROUP BY ym ORDER BY ym DESC LIMIT 6");
$latest = $periods[0] ?? null;
$trend = array_reverse($periods); // chronological for the bar chart
$maxPayable = 0.0;
foreach ($trend as $t) { $maxPayable = max($maxPayable, (float) $t['payable']); }
// Recent joiners
$recentJoiners = $all(
"SELECT firstname, lastname, emp_code, image, emp_type, joining_date
FROM employee_details WHERE joining_date IS NOT NULL
ORDER BY joining_date DESC LIMIT 6");
// Statutory gate + currency
$statutoryOn = ((string) $one("SELECT data FROM acc_setting WHERE name = 'payroll_statutory_enabled' LIMIT 1")) === '1';
$cc = strtoupper((string) $one("SELECT co.code FROM company c LEFT JOIN countries co ON co.country_id = c.country_id ORDER BY c.id LIMIT 1"));
$currency = ['BD' => '৳', 'SG' => 'S$', 'DE' => '€'][$cc] ?? '';
// ── Intelligent helper — surface the most useful next action ──
$pendingHr = $pendingLeave + $pendingResign;
if ($pendingHr > 0) {
$bits = [];
if ($pendingLeave > 0) { $bits[] = $pendingLeave . ' leave'; }
if ($pendingResign > 0) { $bits[] = $pendingResign . ' resignation'; }
$hrHelper = ['type' => 'warn', 'text' => implode(' and ', $bits) . ' request' . ($pendingHr == 1 ? '' : 's') . ' pending your approval.'];
} elseif ($activeHead > 0) {
$hrHelper = ['type' => 'ok', 'text' => 'Attendance ' . $attRate . '% today (' . $presentToday . ' of ' . $activeHead . ' present) — no pending leave or resignation approvals.'];
} else {
$hrHelper = null;
}
return $this->render('@Application/pages/human_resource/cockpit/hrm_cockpit.html.twig', [
'page_title' => 'HR Command Center',
'hrHelper' => $hrHelper,
'activeHead' => $activeHead,
'totalHead' => $totalHead,
'joiners30' => $joiners30,
'byType' => $byType,
'male' => $male, 'female' => $female, 'otherSex' => $otherSex,
'presentToday' => $presentToday, 'attRate' => $attRate,
'pendingLeave' => $pendingLeave, 'pendingResign' => $pendingResign,
'latest' => $latest, 'trend' => $trend, 'maxPayable' => $maxPayable,
'recentJoiners' => $recentJoiners, 'typeLabels' => $typeLabels,
'statutoryOn' => $statutoryOn, 'currency' => $currency, 'country' => $cc,
]);
}
/** Field Force Map page — who/where/what (Nectar attendance + task clock-in). */
public function HrmFieldForceMapAction(Request $request): Response
{
$hours = (int) $request->query->get('hours', 24);
$d = $this->fieldForceData($this->getDoctrine()->getManager()->getConnection(), $hours);
return $this->render('@Application/pages/human_resource/cockpit/hrm_field_force.html.twig', array_merge(['page_title' => 'Field Force Map'], $d));
}
/** Live JSON feed powering the field-force map auto-refresh poll. */
public function HrmFieldForceDataAction(Request $request): Response
{
return new \Symfony\Component\HttpFoundation\JsonResponse(
$this->fieldForceData($this->getDoctrine()->getManager()->getConnection(), (int) $request->query->get('hours', 24))
);
}
/**
* Build field-force data: latest GPS per employee (employee_attendance_log) +
* active task (Nectar task_log) + planned visits. Shared by the page render
* and the auto-refresh JSON feed.
*/
private function fieldForceData($conn, $hours = 24): array
{
$hours = max(1, min(720, (int) $hours)); // trail window: 1h .. 30d
$all = function ($sql, $p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql, $p); } catch (\Throwable $e) { return []; } };
// Latest GPS log per ACTIVE employee (status<>0). The latest log's GPS is
// the employee's last clock-in position (if clocked in) or last clock-out
// position (if clocked out) — i.e. their current/last-known position.
$rows = $all(
"SELECT l.employee_id, e.name AS emp_name,
l.current_lat, l.current_lng, l.current_address, l.current_work_status,
l.clocked_in, l.is_present, l.is_late, l.is_from_assigned_area,
l.last_start_time, l.total_work_hour, l.attendance_source
FROM employee_attendance_log l
JOIN (SELECT employee_id, MAX(id) AS mid FROM employee_attendance_log
WHERE current_lat IS NOT NULL AND current_lat <> 0 AND current_lat <> ''
GROUP BY employee_id) m ON m.mid = l.id
JOIN employee e ON e.employee_id = l.employee_id
WHERE (e.status IS NULL OR e.status <> 0)
ORDER BY l.last_start_time DESC"
);
// Current active task per employee (Nectar task clock-in): started, not
// ended. Gives "what they're doing" (task + project) and a task-level GPS
// when the app captured one. InnoTracker is obsolete and not used here.
$taskByEmp = [];
foreach ($all(
"SELECT tl.employee_id, pi.item_alias AS task_name, p.project_name,
tl.lat AS task_lat, tl.lng AS task_lng
FROM task_log tl
JOIN (SELECT employee_id, MAX(id) AS mid FROM task_log
WHERE employee_id IS NOT NULL AND actual_start_ts IS NOT NULL
AND (actual_end_ts IS NULL OR actual_end_ts = 0)
GROUP BY employee_id) m ON m.mid = tl.id
LEFT JOIN planning_item pi ON pi.id = tl.planning_item_id
LEFT JOIN project p ON p.project_id = tl.project_id"
) as $t) {
$taskByEmp[(int) $t['employee_id']] = [
'task' => trim((string) $t['task_name']),
'project' => trim((string) $t['project_name']),
'lat' => (float) $t['task_lat'], 'lng' => (float) $t['task_lng'],
];
}
$now = new \DateTime();
$people = []; $working = 0; $stale = 0; $offsite = 0; $seenEmp = [];
foreach ($rows as $r) {
$lat = (float) $r['current_lat']; $lng = (float) $r['current_lng'];
if ($lat == 0.0 && $lng == 0.0) { continue; }
$mins = null; $last = trim((string) $r['last_start_time']);
if ($last !== '' && $last !== '0000-00-00 00:00:00') {
try { $mins = (int) round(($now->getTimestamp() - (new \DateTime($last))->getTimestamp()) / 60); } catch (\Throwable $e) {}
}
$eid = (int) $r['employee_id'];
$seenEmp[$eid] = true;
$task = $taskByEmp[$eid] ?? null;
$hasTask = $task && $task['task'] !== '';
// Prefer task-level GPS (more precise / current) when the app captured one.
if ($task && $task['lat'] != 0.0) { $lat = $task['lat']; $lng = $task['lng']; }
$clockedIn = (int) $r['clocked_in'] === 1;
// status: working (on a task or on the clock, fresh) / idle / stale (no fresh ping)
$status = 'idle';
if ($mins !== null && $mins > 180 && !$hasTask) { $status = 'stale'; $stale++; }
elseif ($clockedIn || $hasTask) { $status = 'working'; $working++; }
if (isset($r['is_from_assigned_area']) && (int) $r['is_from_assigned_area'] === 0 && $clockedIn) { $offsite++; }
$people[] = [
'id' => $eid,
'name' => trim((string) $r['emp_name']) ?: ('Employee #' . $eid),
'lat' => $lat, 'lng' => $lng,
'address' => trim((string) $r['current_address']) ?: '',
'clockedIn' => $clockedIn,
'status' => $status,
'task' => $hasTask ? $task['task'] : '',
'project' => $hasTask ? $task['project'] : '',
'workHours' => (float) $r['total_work_hour'],
'isLate' => (int) $r['is_late'] === 1,
'offsite' => isset($r['is_from_assigned_area']) ? ((int) $r['is_from_assigned_area'] === 0) : null,
'lastSeen' => $last,
'minsAgo' => $mins,
'source' => (string) $r['attendance_source'],
];
}
// Employees on an active task with task-level GPS but no attendance ping
// (located purely by the Nectar task clock-in).
foreach ($taskByEmp as $eid => $t) {
if (isset($seenEmp[$eid]) || $t['lat'] == 0.0 || $t['task'] === '') { continue; }
$nm = $all("SELECT name FROM employee WHERE employee_id = :id AND (status IS NULL OR status <> 0)", ['id' => $eid]);
if (empty($nm)) { continue; } // inactive / unknown employee → skip
$working++;
$people[] = [
'id' => $eid,
'name' => ($nm[0]['name'] ?? '') ?: ('Employee #' . $eid),
'lat' => $t['lat'], 'lng' => $t['lng'], 'address' => '',
'clockedIn' => true, 'status' => 'working',
'task' => $t['task'], 'project' => $t['project'],
'workHours' => 0.0, 'isLate' => false, 'offsite' => null,
'lastSeen' => '', 'minsAgo' => null, 'source' => 'task',
];
}
// Planned visits (with coordinates) for context overlay.
$visits = $all(
"SELECT v.latitude, v.longitude, v.location, v.start_date, v.priority_status
FROM plan_visit v
WHERE v.latitude IS NOT NULL AND v.latitude <> 0
AND (v.delete_flag IS NULL OR v.delete_flag = 0)
ORDER BY v.start_date DESC LIMIT 200"
);
$visitPins = [];
foreach ($visits as $v) {
$vlat = (float) $v['latitude']; $vlng = (float) $v['longitude'];
if ($vlat == 0.0 && $vlng == 0.0) { continue; }
$visitPins[] = ['lat' => $vlat, 'lng' => $vlng, 'location' => trim((string) $v['location']), 'date' => (string) $v['start_date']];
}
// Route-history trail: GPS pings within the selected window ($hours, default
// 24h), chronological, capped to the most recent 60 points per employee.
$trails = [];
foreach ($all(
"SELECT employee_id, current_lat, current_lng
FROM employee_attendance_log
WHERE current_lat IS NOT NULL AND current_lat <> 0 AND current_lat <> ''
AND last_start_time >= DATE_SUB(NOW(), INTERVAL " . (int) $hours . " HOUR)
ORDER BY employee_id, id ASC"
) as $g) {
$eid = (int) $g['employee_id'];
$la = (float) $g['current_lat']; $ln = (float) $g['current_lng'];
if ($la == 0.0 && $ln == 0.0) { continue; }
if (!isset($trails[$eid])) { $trails[$eid] = []; }
$trails[$eid][] = ['lat' => $la, 'lng' => $ln];
}
// Keep only trails for the active employees shown on the map; cap length.
$personIds = [];
foreach ($people as $p) { $personIds[$p['id']] = true; }
foreach ($trails as $eid => $pts) {
if (!isset($personIds[$eid])) { unset($trails[$eid]); continue; }
if (count($pts) > 60) { $trails[$eid] = array_slice($pts, -60); }
}
return [
'people' => $people,
'visits' => $visitPins,
'trails' => $trails,
'hours' => $hours,
'kpi' => ['total' => count($people), 'working' => $working, 'stale' => $stale, 'offsite' => $offsite],
];
}
/**
* cp-shell Payroll Report — pick a period, see headline totals and a
* by-employee breakdown (gross / deductions / net), with print. Fail-safe
* DBAL; reads payslip header figures (consistent with the GL & return data).
*/
public function HrmPayrollReportAction(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$one = function ($sql, $p = []) use ($conn) { try { $v = $conn->fetchOne($sql, $p); return $v === false ? null : $v; } catch (\Throwable $e) { return null; } };
$all = function ($sql, $p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql, $p); } catch (\Throwable $e) { return []; } };
// Available periods (YYYY-MM) for the selector.
$periodRows = $all("SELECT DISTINCT DATE_FORMAT(start_date, '%Y-%m') ym FROM payslip WHERE start_date IS NOT NULL ORDER BY ym DESC");
$periods = array_map(function ($r) { return $r['ym']; }, $periodRows);
$period = (string) $request->query->get('period', '');
if ($period === '' || !in_array($period, $periods, true)) {
$period = $periods[0] ?? date('Y-m');
}
// Per-employee breakdown for the chosen period.
$rows = $all(
"SELECT p.sys_id,
COALESCE(NULLIF(TRIM(CONCAT(COALESCE(e.firstname,''),' ',COALESCE(e.lastname,''))),''), CONCAT('Emp #', p.sys_id)) AS name,
e.emp_code,
ROUND(SUM(CAST(NULLIF(p.eart,'') AS DECIMAL(18,2))),2) gross,
ROUND(SUM(CAST(NULLIF(p.dedt,'') AS DECIMAL(18,2))),2) ded,
ROUND(SUM(p.payable_salary),2) net,
MAX(p.approved) approved
FROM payslip p
LEFT JOIN employee_details e ON e.id = p.sys_id
WHERE DATE_FORMAT(p.start_date, '%Y-%m') = :ym
GROUP BY p.sys_id, name, e.emp_code
ORDER BY net DESC",
['ym' => $period]
);
$totGross = 0.0; $totDed = 0.0; $totNet = 0.0; $approvedCount = 0;
foreach ($rows as $r) {
$totGross += (float) $r['gross']; $totDed += (float) $r['ded']; $totNet += (float) $r['net'];
if ((int) $r['approved'] === 1) { $approvedCount++; }
}
$cc = strtoupper((string) $one("SELECT co.code FROM company c LEFT JOIN countries co ON co.country_id = c.country_id ORDER BY c.id LIMIT 1"));
$currency = ['BD' => '৳', 'SG' => 'S$', 'DE' => '€'][$cc] ?? '';
$statutoryOn = ((string) $one("SELECT data FROM acc_setting WHERE name = 'payroll_statutory_enabled' LIMIT 1")) === '1';
return $this->render('@Application/pages/human_resource/cockpit/hrm_payroll_report.html.twig', [
'page_title' => 'Payroll Report',
'periods' => $periods, 'period' => $period, 'rows' => $rows,
'totGross' => $totGross, 'totDed' => $totDed, 'totNet' => $totNet,
'headcount' => count($rows), 'approvedCount' => $approvedCount,
'currency' => $currency, 'country' => $cc, 'statutoryOn' => $statutoryOn,
]);
}
/**
* cp-shell Headcount & Attrition report — joiners vs leavers over the last
* 12 months, attrition rate, average tenure, and composition by type/branch.
* Fail-safe DBAL.
*/
public function HrmHeadcountReportAction(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$one = function ($sql, $p = []) use ($conn) { try { $v = $conn->fetchOne($sql, $p); return $v === false ? null : $v; } catch (\Throwable $e) { return null; } };
$all = function ($sql, $p = []) use ($conn) { try { return $conn->fetchAllAssociative($sql, $p); } catch (\Throwable $e) { return []; } };
$active = (int) $one("SELECT COUNT(*) FROM employee_details WHERE emp_status = 1");
$total = (int) $one("SELECT COUNT(*) FROM employee_details");
$joiners12 = (int) $one("SELECT COUNT(*) FROM employee_details WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)");
$leavers12 = (int) $one("SELECT COUNT(*) FROM resign_application WHERE approved = 1 AND COALESCE(resigned_from, created_at) >= DATE_SUB(NOW(), INTERVAL 12 MONTH)");
$attrition = $active > 0 ? round($leavers12 * 100 / ($active + $leavers12), 1) : 0.0;
$avgTenure = (float) $one("SELECT ROUND(AVG(DATEDIFF(NOW(), joining_date)) / 365.0, 1) FROM employee_details WHERE emp_status = 1 AND joining_date IS NOT NULL");
// 12-month joiners vs leavers axis (built in PHP so empty months show as 0).
$months = [];
$cur = new \DateTime('first day of this month');
for ($i = 11; $i >= 0; $i--) {
$k = (clone $cur)->modify("-$i month")->format('Y-m');
$months[$k] = ['joiners' => 0, 'leavers' => 0];
}
foreach ($all("SELECT DATE_FORMAT(joining_date,'%Y-%m') m, COUNT(*) c FROM employee_details WHERE joining_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY m") as $r) {
if (isset($months[$r['m']])) { $months[$r['m']]['joiners'] = (int) $r['c']; }
}
foreach ($all("SELECT DATE_FORMAT(COALESCE(resigned_from, created_at),'%Y-%m') m, COUNT(*) c FROM resign_application WHERE approved = 1 AND COALESCE(resigned_from, created_at) >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY m") as $r) {
if (isset($months[$r['m']])) { $months[$r['m']]['leavers'] = (int) $r['c']; }
}
$maxFlow = 1;
foreach ($months as $v) { $maxFlow = max($maxFlow, $v['joiners'], $v['leavers']); }
// Composition
$typeLabels = [1 => 'Full-time', 2 => 'Part-time', 3 => 'Intern', 4 => 'Temporary', 5 => 'Contractual'];
$byType = [];
foreach ($all("SELECT emp_type t, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY emp_type") as $r) {
$byType[$typeLabels[(int) $r['t']] ?? ('Type ' . (int) $r['t'])] = (int) $r['c'];
}
$byBranch = [];
foreach ($all("SELECT COALESCE(NULLIF(TRIM(branch_name),''),'Unassigned') b, COUNT(*) c FROM employee_details WHERE emp_status = 1 GROUP BY b ORDER BY c DESC LIMIT 8") as $r) {
$byBranch[$r['b']] = (int) $r['c'];
}
$recentLeavers = $all(
"SELECT COALESCE(NULLIF(TRIM(CONCAT(COALESCE(e.firstname,''),' ',COALESCE(e.lastname,''))),''), CONCAT('Emp #', r.employee_id)) AS name,
e.emp_code, e.branch_name, COALESCE(r.resigned_from, r.created_at) AS dt
FROM resign_application r LEFT JOIN employee_details e ON e.id = r.employee_id
WHERE r.approved = 1 ORDER BY dt DESC LIMIT 6");
$cc = strtoupper((string) $one("SELECT co.code FROM company c LEFT JOIN countries co ON co.country_id = c.country_id ORDER BY c.id LIMIT 1"));
return $this->render('@Application/pages/human_resource/cockpit/hrm_headcount_report.html.twig', [
'page_title' => 'Headcount & Attrition',
'active' => $active, 'total' => $total, 'joiners12' => $joiners12, 'leavers12' => $leavers12,
'attrition' => $attrition, 'avgTenure' => $avgTenure,
'months' => $months, 'maxFlow' => $maxFlow,
'byType' => $byType, 'byBranch' => $byBranch, 'recentLeavers' => $recentLeavers, 'country' => $cc,
]);
}
/**
* Renders the Employee Dashboard with attendance, active clock status, and leave balances.
*/
public function EmployeeDashboardAction(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$empId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$userId = $session->get(UserConstants::USER_ID);
if (!$empId || !$userId) {
return $this->redirectToRoute('user_login');
}
$localTz = new \DateTimeZone('+0600');
$utcTz = new \DateTimeZone('UTC');
$today = new \DateTime('now', $localTz);
$todayStr = $today->format('Y-m-d');
// ── 1. Basic Info ──────────────────────────────────────────────────────
$employee = $em->getRepository(Employee::class)->findOneBy(['employeeId' => $empId]);
$employeeName = $employee
? ($employee->getFirstName() . ' ' . $employee->getLastName())
: 'Employee';
// ── 2. Attendance Logic (today's clock-in/out) ────────────────────────
$todayMidnight = new \DateTime($todayStr . ' 00:00:00');
$todayAttendance = $em->getRepository(EmployeeAttendance::class)->findOneBy([
'employeeId' => $empId,
'date' => $todayMidnight,
]);
$entryTime = null;
$lastOutTime = null;
$currentLocation = 'none';
$workedSeconds = 0;
if (
$todayAttendance
&& method_exists($todayAttendance, 'getData')
&& $todayAttendance->getData()
) {
$attData = json_decode($todayAttendance->getData(), true);
if (is_array($attData) && isset($attData['in'])) {
$inCount = count($attData['in']);
$outCount = isset($attData['out']) ? count($attData['out']) : 0;
// Accumulate fully-completed in/out pairs
for ($i = 0; $i < $outCount; $i++) {
$inDt = new \DateTime($todayStr . ' ' . $attData['in'][$i], $utcTz);
$outDt = new \DateTime($todayStr . ' ' . $attData['out'][$i], $utcTz);
$workedSeconds += max(0, $outDt->getTimestamp() - $inDt->getTimestamp());
}
if ($inCount > $outCount) {
// Currently on-site
$currentLocation = 'in';
$entryDt = new \DateTime($todayStr . ' ' . $attData['in'][$inCount - 1], $utcTz);
$entryDt->setTimezone($localTz);
$entryTime = $entryDt->format('Y-m-d H:i:s');
} elseif ($outCount > 0) {
// Clocked out
$currentLocation = 'out';
$outDt = new \DateTime($todayStr . ' ' . $attData['out'][$outCount - 1], $utcTz);
$outDt->setTimezone($localTz);
$lastOutTime = $outDt->format('Y-m-d H:i:s');
}
}
}
// ── Task Log: sync with attendance state ──────────────────────────────
// Only acts when attendance state and task-log state are out of sync.
// Does NOT create duplicate logs on page refresh.
$currTs = (new \DateTime())->format('U');
$activeTaskLog = $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
->findOneBy(['userId' => $userId, 'workingStatus' => 1]);
if ($currentLocation === 'in' && !$activeTaskLog) {
// Clocked IN but no open task log — create one
$planningItemId = $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID, 0);
// Fall back to last known planning item if session has none
if (!$planningItemId) {
$lastTask = $em->getRepository('ApplicationBundle\\Entity\\TaskLog')
->findOneBy(['userId' => $userId], ['id' => 'DESC']);
$planningItemId = $lastTask ? $lastTask->getPlanningItemId() : 0;
}
$taskLog = new \ApplicationBundle\Entity\TaskLog();
$taskLog->setPlanningItemId($planningItemId);
$taskLog->setUserId($userId);
$taskLog->setLogType('session');
$taskLog->setWorkingStatus(1);
$taskLog->setActualStartTs($currTs);
$em->persist($taskLog);
$em->flush();
$session->set(UserConstants::USER_CURRENT_TASK_ID, $taskLog->getId());
$session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID, $planningItemId);
} elseif (($currentLocation === 'out' || $currentLocation === 'none') && $activeTaskLog) {
// Clocked OUT (or no attendance) but task log still open — close it
$em->getConnection()->executeStatement(
'UPDATE task_log SET working_status=2, actual_end_ts=' . $currTs .
' WHERE working_status=1 AND user_id=' . $userId
);
$session->set(UserConstants::USER_CURRENT_TASK_ID, 0);
$session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID, 0);
} elseif ($currentLocation === 'in' && $activeTaskLog) {
// Already in sync — keep session aligned with DB record
$session->set(UserConstants::USER_CURRENT_TASK_ID, $activeTaskLog->getId());
$session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID, $activeTaskLog->getPlanningItemId());
}
// ── 3. Leave Management ───────────────────────────────────────────────
$employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->find($empId);
$leaveBalanceList = [];
$leaveNamesMap = [];
$totalUsedDays = 0;
$totalAllowedLimit = 0;
if ($employeeDetails) {
$leaveConfig = json_decode($employeeDetails->getLeaveData(), true) ?? [];
foreach ($leaveConfig as $config) {
$id = $config['id'];
$title = $config['title'];
$limit = (float)$config['total_leave'];
$leaveNamesMap[$id] = $title;
$getter = "getLeave{$id}Tkn";
$taken = method_exists($employeeDetails, $getter)
? (float)$employeeDetails->$getter()
: 0;
$totalUsedDays += $taken;
$totalAllowedLimit += $limit;
$leaveBalanceList[] = ['name' => $title, 'used' => $taken, 'limit' => $limit];
}
}
// ── 4. Upcoming Leaves ────────────────────────────────────────────────
$upcomingEntities = $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
->createQueryBuilder('L')
->where('L.employeeId = :empId AND L.approved = 1 AND L.leaveStartDate >= :today')
->setParameter('empId', $empId)
->setParameter('today', $todayMidnight)
->orderBy('L.leaveStartDate', 'ASC')
->setMaxResults(3)
->getQuery()->getResult();
$upcomingLeaveFormatted = [];
foreach ($upcomingEntities as $entity) {
$upcomingLeaveFormatted[] = [
'leaveStartDate' => $entity->getLeaveStartDate(),
'leaveEndDate' => $entity->getLeaveEndDate(),
'leaveDaysCountable' => $entity->getLeaveDaysCountable(),
'leaveTypeName' => $leaveNamesMap[$entity->getLeaveTypeId()] ?? 'General Leave',
];
}
// ── 5. Calendar year boundaries ───────────────────────────────────────
$yearStart = new \DateTime($today->format('Y') . '-01-01 00:00:00');
$yearEnd = new \DateTime($today->format('Y') . '-12-31 23:59:59');
// ── 6a. Calendar: Leave dates (current year) ──────────────────────────
$calendarLeaveEntities = $em->getRepository('ApplicationBundle\\Entity\\EmployeeLeaveApplication')
->createQueryBuilder('L')
->where('L.employeeId = :empId AND L.approved = 1')
->andWhere('L.leaveStartDate <= :yearEnd')
->andWhere('L.leaveEndDate >= :yearStart')
->setParameter('empId', $empId)
->setParameter('yearStart', $yearStart)
->setParameter('yearEnd', $yearEnd)
->getQuery()->getResult();
$calendarEvents = [];
foreach ($calendarLeaveEntities as $lv) {
$cursor = clone $lv->getLeaveStartDate();
$end = clone $lv->getLeaveEndDate();
$typeName = $leaveNamesMap[$lv->getLeaveTypeId()] ?? 'Leave';
while ($cursor <= $end) {
$calendarEvents[] = [
'date' => $cursor->format('Y-m-d'),
'type' => $typeName,
'kind' => 'leave',
];
$cursor->modify('+1 day');
}
}
// ── 6b. Calendar: Holiday dates (current year) ────────────────────────
$companyId = $session->get(UserConstants::USER_COMPANY_ID) ?? 0;
$approvedCalendarIds = $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendar')
->createQueryBuilder('H')
->select('H.holidayCalendarId')
->where('H.approved = 1')
->andWhere('H.CompanyId = :cid')
->setParameter('cid', $companyId)
->getQuery()
->getSingleColumnResult();
$calendarHolidayDates = [];
if (!empty($approvedCalendarIds)) {
$holidayDateRows = $em->getRepository('ApplicationBundle\\Entity\\HolidayCalendarDates')
->createQueryBuilder('D')
->where('D.holidayCalendarId IN (:calIds)')
->andWhere('D.startDate <= :yearEnd')
->andWhere('D.endDate >= :yearStart')
->setParameter('calIds', $approvedCalendarIds)
->setParameter('yearStart', $yearStart)
->setParameter('yearEnd', $yearEnd)
->getQuery()->getResult();
foreach ($holidayDateRows as $row) {
$cursor = clone $row->getStartDate();
$end = clone $row->getEndDate();
$title = $row->getHolidayTitle() ?: 'Holiday';
while ($cursor <= $end) {
$calendarHolidayDates[] = [
'date' => $cursor->format('Y-m-d'),
'type' => $title,
'kind' => 'holiday',
];
$cursor->modify('+1 day');
}
}
}
// ── 6c. Calendar: Present dates (current year) ────────────────────────
// Uses EmployeeAttendanceLog where isPresent = 1.
// NOTE: adjust the getter (getLastStartTime / getLastEndTime) to whichever
// column stores the working date in your entity.
$attendanceLogs = $em->getRepository('ApplicationBundle\\Entity\\EmployeeAttendanceLog')
->createQueryBuilder('a')
->where('a.employeeId = :empId')
->andWhere('a.isPresent = 1')
->andWhere('a.last_end_time >= :yearStart')
->andWhere('a.last_end_time <= :yearEnd')
->setParameter('empId', $empId)
->setParameter('yearStart', $yearStart)
->setParameter('yearEnd', $yearEnd)
->getQuery()
->getResult();
$calendarPresentDates = [];
foreach ($attendanceLogs as $log) {
// If your entity uses getLastStartTime() instead, change the line below
$dt = $log->getLastEndTime();
if ($dt instanceof \DateTime) {
$calendarPresentDates[] = $dt->format('Y-m-d');
}
}
$calendarPresentDates = array_values(array_unique($calendarPresentDates));
// Merge leave + holiday events for the calendar
$calendarEvents = array_merge($calendarEvents, $calendarHolidayDates);
// ── 7. Planning Items (To-Do List) ────────────────────────────────────
$planningItems = $em->getRepository('ApplicationBundle\\Entity\\PlanningItem')
->createQueryBuilder('P')
->where('P.status = 1')
->andWhere(
'P.assignedTo = :empId OR P.assignedToIds LIKE :empIdLike'
)
->setParameter('empId', $empId)
->setParameter('empIdLike', '%' . $empId . '%')
->orderBy('P.estimatedCompletionTimeTs', 'DESC')
->setMaxResults(10)
->getQuery()->getResult();
$todoList = [];
foreach ($planningItems as $item) {
$dueTs = $item->getEstimatedCompletionTimeTs();
$todoList[] = [
'id' => $item->getId(),
'title' => $item->getItemAlias() ?: $item->getDescription() ?: 'Untitled Task',
'desc' => $item->getItemDesc() ?: '',
'stage' => (int)$item->getStage(),
'urgency' => (int)$item->getUrgency(),
'dueTs' => $dueTs,
'dueDate' => $dueTs ? date('d M Y', $dueTs) : null,
'isOverdue' => $dueTs && $dueTs < time() && (int)$item->getStage() < 2,
'percentage' => (int)($item->getCompletionPercentage() ?? 0),
];
}
// ── Render ────────────────────────────────────────────────────────────
return $this->render('@Application/pages/dashboard/employeeDashboard.html.twig', [
'page_title' => 'My Dashboard',
'employeeName' => $employeeName,
'empId' => $empId,
'userId' => $userId,
'entryTime' => $entryTime,
'lastOutTime' => $lastOutTime,
'currentLocation' => $currentLocation,
'workedSeconds' => $workedSeconds,
'leaveBalance' => $leaveBalanceList,
'totalLeaveQty' => $totalAllowedLimit,
'totalUsedDays' => $totalUsedDays,
'totalLeaveRemaining' => max(0, $totalAllowedLimit - $totalUsedDays),
'upcomingLeave' => $upcomingLeaveFormatted,
'calendarLeaveDates' => $calendarEvents,
'calendarPresentDates' => $calendarPresentDates,
'weekendDays' => [5, 6],
'todoList' => $todoList,
]);
}
public function leavePolicyListAction()
{
return $this->render("@Application/pages/human_resource/list/leaveApplicationSettingsList.html.twig", array(
'page_title' => 'Leave PolicyList',
));
}
public function getEmployeeProfileDataAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$userId = $session->get(UserConstants::USER_ID);
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$employeeData = $em->getRepository('ApplicationBundle\\Entity\\Employee')
->findOneBy(
array(
'userId' => $userId
)
);
// The logged-in user may be known to this tenant without having an
// Employee record here (e.g. an owner/admin who isn't an employee).
// Return an empty-but-valid profile instead of dereferencing null,
// which previously 500'd and broke the app dashboard.
if (!$employeeData) {
$data = EmployeePayloadNormalizer::normalize([
'firstname' => '',
'lastname' => '',
'image' => '',
]);
$data['userImage'] = '';
return new JsonResponse([
'success' => true,
'data' => $data
]);
}
$data = EmployeePayloadNormalizer::normalize([
'firstname' => $employeeData->getFirstname(),
'lastname' => $employeeData->getLastname(),
'image' => $employeeData->getImage(),
]);
$data['userImage'] = $absoluteUrl . '' . $employeeData->getImage();
return new JsonResponse([
'success' => true,
'data' => $data
]);
}
// public function getMeetingSummaryAction(Request $request)
// {
// $em = $this->getDoctrine()->getManager();
// $meetingId = $request->query->get('id');
//
// $queryBuilder = $em->createQueryBuilder();
// $queryBuilder
// ->select('M', 'r.roomNo')
// ->from('ApplicationBundle:ScheduledMeeting', 'M')
// ->leftJoin('ApplicationBundle:Room', 'r', 'WITH', 'M.roomId = r.roomId')
// ->where('M.scheduleId = :id')
// ->setParameter('id', $meetingId);
//
// $data = $queryBuilder->getQuery()->getResult();
//
// $result = [];
//
// foreach ($data as $row) {
// $meeting = $row[0];
//
// $result[] = [
// 'scheduleId' => $meeting->getScheduleId(),
// 'title' => $meeting->getTitle(),
// 'location' => $meeting->getLocation(),
// 'roomId' => $meeting->getRoomId(),
// 'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('d-m-Y') : null,
// 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('d-m-Y') : null,
// 'agendaList' => $meeting->getAgendaList(),
// 'roomNo' => $row['roomNo']
// ];
// }
//
// return new JsonResponse($result);
// }
public function getMeetingSummaryAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$meetingId = $request->query->get('id');
$queryBuilder = $em->createQueryBuilder();
$queryBuilder
->select('M', 'r.roomNo')
->from('ApplicationBundle:ScheduledMeeting', 'M')
->leftJoin('ApplicationBundle:Room', 'r', 'WITH', 'M.roomId = r.roomId')
->where('M.scheduleId = :id')
->setParameter('id', $meetingId);
$data = $queryBuilder->getQuery()->getResult();
$result = [];
foreach ($data as $row) {
$meeting = $row[0];
$participantIds = json_decode($meeting->getInternalParticipantIds(), true) ?? [];
$participants = [];
if (!empty($participantIds)) {
$empQuery = $em->createQueryBuilder()
->select('e.employeeId', 'e.name', 'e.image')
->from('ApplicationBundle:Employee', 'e')
->where('e.employeeId IN (:ids)')
->setParameter('ids', $participantIds)
->getQuery()
->getArrayResult();
foreach ($empQuery as $emp) {
$participants[] = [
'name' => $emp['name'],
'image' => rtrim($absoluteUrl, '/') . '/' . ltrim($emp['image'], '/')
];
}
}
$result[] = [
'scheduleId' => $meeting->getScheduleId(),
'title' => $meeting->getTitle(),
'location' => $meeting->getLocation(),
'roomId' => $meeting->getRoomId(),
'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('d-m-Y') : null,
'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('d-m-Y') : null,
'agendaList' => $meeting->getAgendaList(),
'roomNo' => $row['roomNo'],
'Participant' => $participants
];
}
return new JsonResponse([
'status' => 'success',
'message' => 'Meeting retrieved successfully',
'data' => $result
], 200);
}
private function getLeaveUploadedFiles($files)
{
$uploadedFiles = array();
foreach ($files as $uploadedFileGroup) {
if (is_array($uploadedFileGroup)) {
foreach ($uploadedFileGroup as $uploadedFile) {
if ($uploadedFile !== null) {
$uploadedFiles[] = $uploadedFile;
}
}
} elseif ($uploadedFileGroup !== null) {
$uploadedFiles[] = $uploadedFileGroup;
}
}
return $uploadedFiles;
}
private function getLeaveAttachmentExtension($uploadedFile)
{
$extension = strtolower((string)$uploadedFile->guessExtension());
if ($extension === '') {
$extension = strtolower((string)$uploadedFile->getClientOriginalExtension());
}
return $extension;
}
private function validateLeaveAttachmentFiles($files)
{
$allowedExtensions = array('pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx');
$maxFileSize = 5 * 1024 * 1024;
foreach ($this->getLeaveUploadedFiles($files) as $uploadedFile) {
$extension = $this->getLeaveAttachmentExtension($uploadedFile);
if (!in_array($extension, $allowedExtensions, true)) {
return "Only PDF, JPG, JPEG, PNG, DOC, and DOCX files are allowed for supporting documents.";
}
if ((int)$uploadedFile->getSize() > $maxFileSize) {
return "Each supporting document must be 5 MB or smaller.";
}
}
return null;
}
}