<?php
namespace ApplicationBundle\Modules\Buddybee\Controller;
use ApplicationBundle\Constants\BuddybeeConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\HumanResourceConstant;
use ApplicationBundle\Controller\GenericController;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\Buddybee\Buddybee;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\ModifyDate;
use ApplicationBundle\Modules\System\System;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use CompanyGroupBundle\Entity\EntityCommunicationLog;
use CompanyGroupBundle\Entity\EntityConsultantSchedule;
use CompanyGroupBundle\Entity\EntityCountryConsultantRequirements;
use CompanyGroupBundle\Entity\EntityCreateTopic;
use CompanyGroupBundle\Entity\EntityFile;
use CompanyGroupBundle\Entity\EntityInvoice;
use CompanyGroupBundle\Entity\EntityMeetingSession;
use CompanyGroupBundle\Entity\EntityReview;
use CompanyGroupBundle\Entity\EntitySkill;
use CompanyGroupBundle\Entity\LiveSupportMeetingQueue;
use CompanyGroupBundle\Entity\LiveSupportMeetingRoom;
use Ps\PdfBundle\Annotation\Pdf;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGenerator;
//use Symfony\Bundle\FrameworkBundle\Console\Application;
//use Symfony\Component\Console\Input\ArrayInput;
//use Symfony\Component\Console\Output\NullOutput;
//use Symfony\Component\Validator\Constraints\DateTime;
class BuddybeeController extends GenericController implements SessionCheckInterface
{
///controllers for routes with session requirement
public function ChangePasswordAction(Request $request, $startFrom = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$actionSuccess = false;
$retData = array();
$userData = [];
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', '_BUDDYBEE_USER_'));
$oldPassword = $request->request->get('oldPassword', $request->query->get('oldPassword', ''));
$newPassword = $request->request->get('newPassword', $request->query->get('newPassword', ''));
$userId = $request->request->get('userId', $request->query->get('userId', $session->get(UserConstants::USER_ID, 0)));
$userType = UserConstants::USER_TYPE_APPLICANT;
if ($request->isMethod('POST')) {
//set an otp and its expire and send mail
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
$oldPasswordPassed = 0;
if ($userObj->getOauthUniqueId() != 0 && $userObj->getOauthUniqueId() != '')
$oldPasswordPassed = 1;
else {
if ($this->container->get('app.legacy_password_service')->verifyWithSalt($userObj->getPassword(), $oldPassword, $userObj->getUserName()))
$oldPasswordPassed = 1;
}
if ($oldPasswordPassed == 1) {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($newPassword, $userObj->getUserName());
$userObj->setPassword($encodedPassword);
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$actionSuccess = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'appId' => $session->get(UserConstants::USER_APP_ID, 0),
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action failed!";
$actionSuccess = false;
}
} else {
$message = "Account not found!";
$actionSuccess = false;
}
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$actionSuccess = false;
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
$oldPasswordPassed = 0;
if ($userObj->getOauthUniqueId() != 0 && $userObj->getOauthUniqueId() != '')
$oldPasswordPassed = 1;
else {
if ($this->container->get('app.legacy_password_service')->verifyWithSalt($userObj->getPassword(), $oldPassword, $userObj->getUserName()))
$oldPasswordPassed = 1;
}
if ($oldPasswordPassed == 1) {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($newPassword, $userObj->getUserName());
$userObj->setPassword($encodedPassword);
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$actionSuccess = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'appId' => $session->get(UserConstants::USER_APP_ID, 0),
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action failed!";
$actionSuccess = false;
}
} else {
$message = "Account not found!";
$actionSuccess = false;
}
}
}
$response = new JsonResponse(array(
'message' => $message,
"userType" => $userType,
// "otp"=>$otp,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'success' => $actionSuccess,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
public function ConsultantApplyAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$consultantRequirementsQry = $em->getRepository(EntityCountryConsultantRequirements::class)->findAll();
$consultantRequirementsByCountryId = [];
foreach ($consultantRequirementsQry as $value) {
$docList = json_decode($value->getDocumentList(), true);
$requiredFields = json_decode($value->getRequiredFields(), true);
if ($docList == null) $docList = [];
if ($requiredFields == null) $requiredFields = [];
$consultantRequirementsByCountryId[$value->getCountryId()] = array(
'documentList' => $docList,
'requiredFields' => $requiredFields,
'contractLetterHtml' => $value->getContractLetterHtml(),
);
}
$documentLists = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findAll();;
$docListArray = [];
foreach ($documentLists as $document) {
$docListArray [$document->getId()] = array(
'id' => $document->getId(),
'docName' => $document->getDocumentName(),
'expiryDays' => $document->getExpiryDays(),
'processingDays' => $document->getProcessingDays(),
'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
'checklist' => json_decode($document->getCheckList()),
);
}
$skillDetails = $em->getRepository(EntitySkill::class)->findAll();
$companyId = $this->getLoggedUserCompanyId($request);
$gender = HumanResourceConstant::$sex;
$blood = HumanResourceConstant::$BloodGroup;
$userId = $session->get(UserConstants::USER_ID);
$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('workDescription'),
);
$certificate = array(
'certificatename' => $request->get('certificatename'),
'issuedDate' => $request->get('issuedDate'),
);
$courses = array(
'courseName' => $request->get('courseName'),
'date' => $request->get('date'),
'duration' => $request->get('duration')
);
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->setCurrentCountryId($request->request->get('currentCountryId'));
$consultant->setCountryId($request->request->get('currentCountryId'));
$consultant->setPostalCode($request->request->get('postalCode'));
$consultant->setDescription($request->request->get('description'));
$consultant->setCurrAddr($request->request->get('curr_addr'));
$consultant->setSkill(json_encode($request->request->get('skill')));
$consultant->setEmergencyContactNumber($request->request->get('emm_contact'));
$consultant->setEmail($request->request->get('oauth_email'));
$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->setWorkExperienceText($request->request->get('workExperience'));
$consultant->setUniversityText($request->request->get('universityText'));
$consultant->setEducationText($request->request->get('educationText'));
$consultant->setExperienceText($request->request->get('experienceText'));
$consultant->setSkillstext($request->request->get('skillText'));
$consultant->setSpeciality($request->request->get('speciality'));
$consultant->setDescription($request->request->get('aboutMe'));
$consultant->setApplyForConsultant(1);
$consultant->setApplyForConsultantDate(new \DateTime());
$em->persist($consultant);
$em->flush();
$url = $this->generateUrl(
'student_dashboard'
);
// return $this->redirect($url . "/" . $userId);
return $this->redirect($url);
}
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
if ($currDocList == null)
$currDocList = [];
return $this->render('@Buddybee/pages/consultantApply.html.twig', array(
'page_title' => 'Apply For Consultant ',
'gender' => $gender,
'blood' => $blood,
'consultantDetails' => $consultantDetails,
'currApplicantDocList' => $currDocList,
'consultantRequirementsByCountryId' => $consultantRequirementsByCountryId,
'docListArray' => $docListArray,
'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 ApplicantFileUploadAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$EntityFileId = 0;
if ($request->isMethod('POST')) {
MiscActions::RemoveExpiredFiles($em);
$storePath = $request->request->get('storePath', 'uploads/consultantDocuments/');
if ($request->request->has('docId')) {
$documentLists = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
array(
'Id' => $request->request->get('docId')
)
);;
$docListArray = [];
foreach ($documentLists as $document) {
$docListArray [$document->getId()] = array(
'id' => $document->getId(),
'docName' => $document->getDocumentName(),
'expiryDays' => $document->getExpiryDays(),
'processingDays' => $document->getProcessingDays(),
'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
'checklist' => json_decode($document->getCheckList()),
);
}
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/consultantDocuments/';
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($request->request->get('applicantId'));
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
if ($currDocList == null)
$currDocList = [];
$doc_index_here = $request->request->get('docId');
//$checkfile = 'docFile' . $consultantDetails->getApplicantId() . '-T-' . '_' . $tid_here . '_' . $doc_index_here . '.' .pdf;
// foreach ($request->files->get('file', []) as $ind => $uploadedFile)
$uploadedFile = $request->files->get('file');
{
$path = "";
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'docFile' . $consultantDetails->getApplicantId() . '-D-' . '_' . $doc_index_here . '.' . $uploadedFile->guessExtension();
$path = $fileName;
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);
}
$uploadedFile->move($upl_dir, $path);
$expireTs = $request->request->get('expireTs', 0);
if ($expireTs == 0) {
if ($request->request->get('expiryDays', 0) != 0) {
$currDate = new \DateTime();
$currDate->modify('+' . $request->request->get('expiryDays', 0) . ' day');
$expireTs = $currDate->format('U');
} else if ($request->request->get('expiryDate', '') != '') {
$currDate = new \DateTime($request->request->get('expiryDate', ''));
$currDate->modify('+14 day');
$expireTs = $currDate->format('U');
}
}
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setName($path);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName($request->request->get('entityName', 'EntityApplicantDetails'));
$EntityFile->setEntityBundle($request->request->get('entityBundle', 'CompanyGroupBundle'));
$EntityFile->setEntityId($request->request->get('entityId', $session->get(UserConstants::USER_ID, 0)));
$EntityFile->setEntityIdField($request->request->get('entityIdField', 'applicantId'));
$EntityFile->setModifyFieldSetter($request->request->get('modifyFieldSetter', ''));
$EntityFile->setDocIdForApplicant($request->request->get('docId', 0));
$EntityFile->setMarker($request->request->get('markerHash', '_ENTITY_APPLICANT_DOCUMENT_'));
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$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->persist($EntityFile);
$em->flush();
$EntityFileId = $EntityFile->getId();
}
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = 'uploads/consultantDocuments/' . $path;
$currDocList[$doc_index_here]['docExpiryDate'] = $request->request->get('expiryDate', '');
// else
// $currDocListByTopicId[$tid_here][$doc_index_here]['docImage'] .= ',uploads/consultantDocuments/' . $path;
} else {
$docD = [
'docId' => $doc_index_here,
'docName' => $docListArray[$doc_index_here]['docName'],
'docExpiryDate' => $request->request->get('expiryDate', ''),
'docImage' => '',
'docCheckList' => [
'Attested' => 1,
'Laminated' => 1
]
];
$currDocList[$doc_index_here] = $docD;
$currDocList[$doc_index_here]['docImage'] = 'uploads/consultantDocuments/' . $path;
}
}
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
return new JsonResponse(array(
'success' => true,
'path' => 'uploads/consultantDocuments/' . $path,
'docId' => $request->request->get('docId'),
'fileId' => $EntityFileId
));
}
}
return new JsonResponse(array(
'success'=>false
));
}
public function AddBalanceToApplicantAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
return new JsonResponse(Buddybee::AddBalanceGeneral(
$em,
$request->request->get('applicantId',$request->query->get('applicantId',0)), ///id
$request->request->get('amount',$request->query->get('amount',0)), ///id
$request->request->get('coins',$request->query->get('coins',0)) ///id
));
}
public function consultantListAction()
{
$em = $this->getDoctrine()->getManager('company_group');
// $consultantDetails = $em->getRepository(EntityApplicantDetails::class)->findAll();
$consultantDetails = [];
return $this->render('@Application/pages/human_resource/list/consultantList.html.twig', array(
'page_title' => 'Consultant List',
'consultantDetails' => $consultantDetails,
));
}
public function jitsiApiListAction()
{
$em = $this->getDoctrine()->getManager('company_group');
return $this->render('@Buddybee/pages/jitsi_api_list.html.twig', array(
'page_title' => 'Jitsi Api List',
));
}
public function buddybeeTicketListAction()
{
$em = $this->getDoctrine()->getManager('company_group');
// $consultantDetails = $em->getRepository(EntityApplicantDetails::class)->findAll();
$consultantDetails = [];
return $this->render('@Buddybee/pages/buddybee_ticket_list.html.twig', array(
'page_title' => 'Ticket List',
));
}
public function studentListAction()
{
$em = $this->getDoctrine()->getManager('company_group');
// $consultantDetails = $em->getRepository(EntityApplicantDetails::class)->findAll();
return $this->render('@Application/pages/human_resource/list/studentList.html.twig', array(
'page_title' => 'Student List',
'commPromiseTypes' => BuddybeeConstant::$commPromiseTypes,
'commPromiseDetails' => BuddybeeConstant::$commPromiseDetails,
'commTypes' => BuddybeeConstant::$commTypes,
));
}
public function leadListAction()
{
$em = $this->getDoctrine()->getManager('company_group');
// $consultantDetails = $em->getRepository(EntityApplicantDetails::class)->findAll();
return $this->render('@Application/pages/human_resource/list/leadList.html.twig', array(
'page_title' => 'Lead List',
'commPromiseTypes' => BuddybeeConstant::$commPromiseTypes,
'commPromiseDetails' => BuddybeeConstant::$commPromiseDetails,
'commTypes' => BuddybeeConstant::$commTypes,
));
}
public function consultantApplicationListAction()
{
$em = $this->getDoctrine()->getManager('company_group');
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->findAll();
return $this->render('@Application/pages/human_resource/list/consultantApplicationList.html.twig', array(
'page_title' => 'Consultant Applications',
'applicationStatusObj' => array(
1 => 'Applied',
2 => 'Rejected',
3 => 'Confirmation Pending',
4 => 'Confirmed',
5 => 'Declined by Applicant',
),
'consultantDetails' => $consultantDetails,
));
}
public function BeeCodeRechargeAction(Request $request, $serial = 0, $pin = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$amount = '50';
$session = $request->getSession();
$userId = $request->get('userId', 0);
$cardId = $request->get('cardId', 0);
if ($userId == 0) $userId = $request->get('applicantId', 0);
$claimFlag = $request->get('claimFlag', 0);
if ($userId == 0) $userId = $session->get(UserConstants::USER_ID);
if ($pin == 0) {
$encData = $serial;
$encryptedData = null;
if ($encData != "") {
if (strlen($encData) != 10)
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
else
$serial = $encData;
} else if ($request->query->has('encData')) {
$encData = $request->query->get('encData');
if (strlen($encData) != 10)
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
else
$serial = $encData;
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
}
if ($encryptedData != null) {
$serial = isset($encryptedData['serial']) ? $encryptedData['serial'] : '';
$pin = isset($encryptedData['pin']) ? $encryptedData['pin'] : '';
$cardId = isset($encryptedData['cardId']) ? $encryptedData['cardId'] : 0;
if ($claimFlag == 0 && isset($encryptedData['claimFlag']))
$claimFlag = $encryptedData['claimFlag'];
}
}
$claimData = MiscActions::ClaimBeeCode($em,
[
'claimFlag' => $claimFlag,
'pin' => $pin,
'cardId' => $cardId,
'serial' => $serial,
'userId' => $userId,
]);
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
$url = $this->generateUrl(
'buddybee_dashboard', [], UrlGenerator::ABSOLUTE_URL
);
$redirectUrl = $url;
$session = $request->getSession();
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if ($request->get('returnJson', 0) != 0) {
$claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
$claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
return new JsonResponse($claimData);
}
if ($claimFlag == 1) {
if ($claimData['claimSuccess'] == true)
return $this->render('@Buddybee/pages/bee_code_recharge_success.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'amount' => $amount,
'claimData' => $claimData,
// 'claimLink'=>$this->get('url_encryptor')->encrypt(array(
// 'cardId'=>$claimData
// )),
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
));
else
return $this->render('@Buddybee/pages/bee_code_recharge_failed.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'amount' => $amount,
'claimData' => $claimData,
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
));
} else {
if ($claimData['isClaimable'] == true)
return $this->render('@Buddybee/pages/bee_code_claimable_success.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'amount' => $amount,
'claimData' => $claimData,
'autoRedirect' => 0,
'redirectUrl' => $redirectUrl,
));
else
return $this->render('@Buddybee/pages/bee_code_recharge_failed.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'amount' => $amount,
'claimData' => $claimData,
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
));
}
}
public function PurchaseBeeCardPageAction(Request $request, $encData = '')
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$retailerId = 0;
$invoiceId = 0;
$topic = null;
$scheduleId = 0;
$consultantDetails = null;
$consultantId = 0;
$studentId = 0;
$sessionId = 0;
$topicSessionValue = 0;
$consultantSchedule = null;
$scheduleText = '';
$autoRedirected = 0;
$autoAssignMeetingSession = 0;
$currencyForGateway = 'bdt';
$paymentGateway = $request->request->get('paymentGateway', 'stripe');
if ($request->query->has('currency'))
$currencyForGateway = $request->query->get('currency');
else
$currencyForGateway = $request->request->get('currency', 'bdt');
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$allowedGateWays = [
'stripe' => 1,
'aamarpay' => 1,
'bkash' => 1,
];
if ($sandBoxMode != 1)
$allowedGateWays = BuddybeeConstant::$allowedGateWaysForLive;
$sessionConsumeCount = $request->request->get('sessionConsumeCount', $request->request->get('sessionDurationSelector', 0));
$retailerId = $request->request->get('retailerId', 0);
$sessionDuration = $sessionConsumeCount * 30;
$meetingSessionId = 0;
$requiredPurchaseSessionCount = $sessionConsumeCount;
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['rtlId'])) $retailerId = $encryptedData['rtlId'];
if (isset($encryptedData['schTs'])) $scheduleId = $encryptedData['schTs'];
if (isset($encryptedData['aams'])) $autoAssignMeetingSession = $encryptedData['aams'];
if (isset($encryptedData['rpsc'])) $requiredPurchaseSessionCount = $encryptedData['rpsc'];
if (isset($encryptedData['scc'])) $sessionConsumeCount = $encryptedData['scc'];
if (isset($encryptedData['dur'])) $sessionDuration = $encryptedData['dur'];
if (isset($encryptedData['cnsId'])) $consultantId = $encryptedData['cnsId'];
if (isset($encryptedData['stdntId'])) $studentId = $encryptedData['stdntId'];
if (isset($encryptedData['sem'])) $topicSessionValue = $encryptedData['sem'];
} else {
}
if ($request->isMethod('GET') && $request->query->has('autoRedirected'))
$autoRedirected = $request->query->get('autoRedirected');
// $studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
if ($request->isMethod('POST') && $request->request->has('toPackagePage')) {
$topicId = $request->request->get('consultancyTopic');
$sessionId = $request->request->get('sessionSelector');
$topicSessionValue = $request->request->get('sessionSelector');
$consultantId = $request->request->get('consultantId');
$scheduleId = $request->request->get('consultancyScheduleId'); // this is timestamp
$scheduleTs = $request->request->get('consultancyScheduleId'); // this is timestamp
// $sessionConsumeCount = $request->request->get('sessionConsumeCount');
$sessionConsumeCount = $request->request->get('sessionConsumeCount', $request->request->get('sessionDurationSelector', 0));
$sessionDuration = $sessionConsumeCount * BuddybeeConstant::PER_SESSION_MINUTE;
$autoAssignMeetingSession = 1;
//$topic = $em->getRepository(ConsultancyTopic::class)->findAll();
$topic = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(array(
'id' => $topicId
));
$consultantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->findOneBy(array(
'applicantId' => $consultantId
));
// $consultantSchedule = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findOneBy(array(
// 'consultantId' => $consultantId
// ));
// $schdeuledTime = [];
// if ($consultantSchedule)
// $schdeuledTime = json_decode($consultantSchedule->getTimeSchedule(), true);
// if ($schdeuledTime == null)
// $schdeuledTime = [];
// $scheduleText = isset($schdeuledTime[$scheduleId]) ? $schdeuledTime[$scheduleId]['date'] . ' ' . $schdeuledTime[$scheduleId]['startTime'] : '';
$scheduleTextDate = new \DateTime('@' . $scheduleId);;
$scheduleText = $scheduleTextDate->format('F d, Y H:i');
$currentUserBalance = 0;
$gatewayAmount = 0;
$redeemedAmount = 0;
$redeemedSessionCount = 0;
$payableAmount = 0;
$totalAmount = 0;
$totalSessionCount = 0;
$consumedAmount = 0;
$consumedSessionCount = $request->request->get('sessionDurationSelector', 0);
$currentUserSessionBalance = 0;
$currentUserBalance = 0;
$balancedFromUserSessionCount = 0;
$balancedFromUserBalance = 0;
$studentId = 0;
if ($session->get(UserConstants::USER_ID)
&& $session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT
) {
$studentDetails = null;
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
$currentUserSessionBalance = $studentDetails->getSessionCountBalance();
$studentId = $studentDetails->getApplicantId();
}
if ($consumedSessionCount <= $currentUserSessionBalance) {
$balancedFromUserSessionCount = 1;
}
//1st do the necessary
$beeCode = $request->request->get('beeCode', '');
$payableAmount = $request->request->get('payableAmount', 0);
$scheduledStartTime = new \DateTime('@' . $scheduleId);;
if ($balancedFromUserSessionCount == 1) {
$scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
$em_goc,
$request->request->get('consultantId', 0),
$studentId,
$scheduledStartTime->format('U'),
(30 * $consumedSessionCount),
1
);
if (!$scheduleValidity) {
$url = $this->generateUrl(
'consultant_profile'
);
$output = [
'proceedToCheckout' => 0,
'message' => 'Session Booking Expired or not Found!',
'errorFlag' => 1,
'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
];
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $request->request->get('consultantId', 0) . '?errorFlag=1&message=Session Booking Expired or not Found');
}
$new = new EntityMeetingSession();
$new->setTopicId($request->request->get('consultancyTopic', 0));
$new->setConsultantId($request->request->get('consultantId', 0));
$consultancyTopic = $em_goc->getRepository(EntityMeetingSession::class)->find($request->request->get('consultancyTopic', 0));
$new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
$new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
$new->setConsultantId($request->request->get('consultantId', 0));
$new->setStudentId($studentId);
$scheduledEndTime = new \DateTime('@' . $scheduleId);;
$scheduledEndTime = $scheduledEndTime->modify('+' . (30 * $consumedSessionCount) . ' Minute');
// $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
// $scheduledEndTime->setTimezone(new \DateTimeZone('UTC'));
//$new->setScheduledTime($request->request->get('setScheduledTime'));
$new->setScheduledTime($scheduledStartTime);
$new->setScheduledTimeTs($scheduledStartTime->format('U'));
$new->setDurationAllowedMin((30 * $consumedSessionCount));
$new->setDurationLeftMin((30 * $consumedSessionCount));
$new->setSessionExpireDate($scheduledEndTime);
$new->setSessionExpireDateTs($scheduledEndTime->format('U'));
$new->setEquivalentSessionCount($consumedSessionCount);
$new->setRedeemSessionCount($consumedSessionCount);
$new->setUsableSessionCount($consumedSessionCount);
$new->setMeetingActionFlag(0);// no action waiting for meeting
$currentUnixTime = new \DateTime();
$currentUnixTimeStamp = $currentUnixTime->format('U');
// $studentId = $request->request->get('studentId', 0);
$consultantId = $request->request->get('consultantId', 0);
$new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
$new->setPayableAmount($payableAmount);
$new->setDueAmount($request->request->get('dueAmount', 0));
//$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
//$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
$new->setPackageName(($request->request->get('packageName', '')));
$new->setPcakageDetails(($request->request->get('packageData', '')));
$new->setScheduleId($scheduleId);
$new->setSessionValue($topicSessionValue);
// $new->setIsPayment(0);
$new->setConsultantIsPaidFull(0);
$em_goc->persist($new);
$em_goc->flush();
$meetingSessionId = $new->getSessionId();
$periodMarker = $scheduledStartTime->format('Ym');
MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
// $studentDetails->setSessionCountBalance($currentUserSessionBalance-$consumedSessionCount);
// $studentDetails->setTotalSessionUsed($studentDetails->getTotalSessionUsed()+$consumedSessionCount);
$em_goc->flush();
$new_invoice = new EntityInvoice();
$new_invoice->setStudentId($studentId);
$invoiceDate = new \DateTime();
$new_invoice->setInvoiceDate($invoiceDate);
$new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
$new_invoice->setMeetingId($meetingSessionId);
$new_invoice->setAmount($totalAmount);
$new_invoice->setGatewayBillAmount($gatewayAmount);
$new_invoice->setRedeemedAmount($redeemedAmount);
$new_invoice->setRedeemedSessionCount($redeemedSessionCount);
$new_invoice->setPaidAmount(0);
$new_invoice->setDueAmount(0);
$new_invoice->setInvoiceType(1);
$new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' . microtime(true)));
$new_invoice->setAmountType(1);
$new_invoice->setConsumeAmount(0);
$new_invoice->setSessionCount(0);
$new_invoice->setConsumeSessionCount($consumedSessionCount);
$new_invoice->setIsPaidfull(0);
$new_invoice->setIsProcessed(0);
$new_invoice->setApplicantId($studentId);
$new_invoice->setIsRecharge(0);
$new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED);
$new_invoice->setIsPayment(0); //0 means receive
$new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
// $new_invoice->setStatus($request->request->get(0));
$em_goc->persist($new_invoice);
$em_goc->flush();
$invoiceId = $new_invoice->getId();
$retData = Buddybee::ProcessEntityInvoice($em_goc, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],$this->container->getParameter('kernel.root_dir'), false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
MiscActions::RefreshBuddybeeBalanceOnSession($em_goc, $request->getSession());
$meetingSessionId = $retData['meetingId'];
if ($meetingSessionId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url . '/' . $meetingSessionId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
}
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $meetingSessionId);
}
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $meetingSessionId);
}
//
}
$packageNames = BuddybeeConstant::$packageNames;
$packageDetails = BuddybeeConstant::$packageDetails;
$userId = $studentId == 0 ? $session->get(UserConstants::USER_ID) : $studentId;
if ($userId != 0) {
$applicantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->findOneBy(array(
'applicantId' => $userId
));
if ($applicantDetails)
$requiredPurchaseSessionCount = $sessionConsumeCount - (1 * $applicantDetails->getSessionCountBalance());
}
MiscActions::RemoveExpiredTemporaryBookingsOnBeeCard($em_goc);
$cards = $em_goc->getRepository("CompanyGroupBundle\\Entity\\BeeCode")->findBy(array(
'isClaimed' => 0,
'isTemporaryBooked' => [0, null],
'retailerId' => $retailerId
));
$cardsData = [];
$cardsDataByCoinValue = array(
100 => ['count' => 0],
200 => ['count' => 0],
500 => ['count' => 0],
600 => ['count' => 0],
);
foreach ($cards as $card) {
$cardsData[] = array(
'id' => $card->getId(),
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
if ($card->getCoinCount() != null && $card->getCoinCount() != 0 && $card->getCoinCount() != '') {
if (!isset($cardsDataByCoinValue[$card->getCoinCount()]))
$cardsDataByCoinValue[$card->getCoinCount()] = array(
'count' => 0
);
// $cardsDataByCoinValue[$card->getAmount()][] = array(
// 'id' => $card->getId(),
// 'printed' => $card->getPrinted(),
// 'amount' => $card->getAmount(),
// 'coinCount' => $card->getCoinCount(),
// 'pin' => $card->getPin(),
// 'serial' => $card->getSerial(),
//
// );
$cardsDataByCoinValue[$card->getCoinCount()]['count'] += 1;
}
}
return $this->render('@Buddybee/pages/purchase_bee_card.html.twig', array(
'page_title' => 'Bee Card',
'topic' => $topic,
'allowedGateWays' => $allowedGateWays,
'retailerId' => $retailerId,
'applicantId' => $userId,
'userId' => $userId,
'convMultFromTo' => BuddybeeConstant::$convMultFromTo,
'beeCodePriceByCoinCountEur' => BuddybeeConstant::$beeCodePriceByCoinCountEur,
'BEECOIN_VALUE_EURO' => BuddybeeConstant::BEECOIN_VALUE_EURO,
'paymentGateway' => $paymentGateway,
'currencyForGateway' => $currencyForGateway,
'consultantDetails' => $consultantDetails,
'packageDetails' => $packageDetails,
'packageNames' => $packageNames,
'scheduleId' => $scheduleId,
'consultantId' => $consultantId,
'topicSessionValue' => $topicSessionValue,
'autoRedirected' => $autoRedirected,
'meetingSessionId' => $meetingSessionId,
'invoiceId' => $invoiceId,
'cardsData' => $cardsData,
'cardsDataByCoinValue' => $cardsDataByCoinValue,
'CoinValueSegregation' => array(
100, 200, 500
),
'sessionConsumeCount' => $sessionConsumeCount,
'requiredPurchaseSessionCount' => $requiredPurchaseSessionCount,
'autoAssignMeetingSession' => $autoAssignMeetingSession,
'sessionDuration' => $sessionDuration,
// 'consultantSchedule' => $consultantSchedule,
'scheduleText' => $scheduleText,
// 'timeSchedule' => $consultantSchedule
));
// return $this->render('@Buddybee/pages/pricing.html.twig', array(
// 'page_title' => 'Package And Pricing',
// ));
}
public function BuddyBeeNotificationListAction(Request $request, $id = 0)
{
// return $this->render('@Buddybee/pages/consultancyHomePage.html.twig', array(
// 'page_title' => 'BuddyBee Home',
// ));
$em = $this->getDoctrine()->getManager('company_group');
// $dt = Inventory::GetDrDetails($em, $id, $item_i
$recNotifications = $em->getRepository('CompanyGroupBundle\\Entity\\EntityNotification')
->findBy(
array(// 'targetId'=>$request->request->get('targetId',0)
)
);
return $this->render('@Buddybee/pages/notification_list.html.twig', array(
'page_title' => 'Notifications',
'recNotifications' => $recNotifications,
));
}
public function BuddyBeeNotificationViewAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$notification = $em->getRepository('CompanyGroupBundle\\Entity\\EntityNotification')->find($id);
if (!$notification) {
return $this->render('@Buddybee/pages/notification_detail.html.twig', array(
'page_title' => 'Notification Detail',
'notification' => null,
'detailError' => 'Notification not found.',
));
}
if ((int) $notification->getSeenFlag() !== 1) {
$notification->setSeenFlag(1);
}
if ((int) $notification->getReadFlag() !== 1) {
$notification->setReadFlag(1);
}
$em->flush();
return $this->render('@Buddybee/pages/notification_detail.html.twig', array(
'page_title' => 'Notification Detail',
'notification' => $notification,
'detailError' => '',
));
}
public function TakeApplicantAction(Request $request, $id = 0)
{
$applicantId = $request->request->get('applicantId', $request->query->get('applicantId', 0));
$action = $request->request->get('action', $request->query->get('action', '_NONE_'));
$forceAction = $request->request->get('forceAction', $request->query->get('forceAction', 0));
$actionValue = $request->request->get('actionValue', $request->query->get('actionValue', 0));
$em = $this->getDoctrine()->getManager('company_group');
// $dt = Inventory::GetDrDetails($em, $id, $item_i
$applicant = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(// 'targetId'=>$request->request->get('targetId',0)
'applicantId' => explode(',',$applicantId)
)
);
if ($applicant) {
if ($action == '_REMOVE_') {
$get_kids_sql = "
DELETE FROM `consultancy_availability` WHERE consultant_id in ($applicantId);
DELETE FROM `entity_meeting_session` WHERE student_id in ($applicantId) or consultant_id in ($applicantId);
DELETE FROM `entity_invoice` WHERE biller_id in ($applicantId) or bill_to_id in ($applicantId);
DELETE FROM `entity_applicant_details` WHERE applicant_id in ($applicantId) ;
";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return new JsonResponse(array(
'success' => true,
'applicantId' => $applicantId,
));
}
if ($action == '_INITIATE_CALL_') {
$session = $request->getSession();
$thisUserId = $session->get(UserConstants::USER_ID);
$thisUser = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(// 'targetId'=>$request->request->get('targetId',0)
'applicantId' => $thisUserId
)
);
$thisUserFireBaseTokens = [];
$adminTokenList = $em->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->createQueryBuilder('m')
->where("m.userId = $thisUserId")
->getQuery()
->getResult();
foreach ($adminTokenList as $a) {
if ($a->getFireBaseToken() != '' && $a->getFireBaseToken() != null) {
$thisUserFireBaseTokens[] = $a->getFireBaseToken();
}
}
System::AddNewNotificationUpdated(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
0, //appId
0,//company Id
"Call initiation with " . $applicant->getFirstname() . " " . $applicant->getLastname() . " on " . $applicant->getPhone() . " ",
GeneralConstant::NOTIFICATION_TYPE_ALERT,//type
"",
"Call Initiation",
'emit',
1,
1,
[
'em' => $em,
'isBuddybee' => 1,
'targetRoute' => '_INITIATE_CALL_',
'targetUrl' => '_INITIATE_CALL_',
'targetPath' => '_INITIATE_CALL_',
'targetId' => $applicantId,
'meetingId' => 0,
'userId' => $applicantId,
'applicantId' => $applicantId,
'taggedUserIds' => ['BBEE_' . $thisUserId],
'type' => 0,
'expireTs' => 0,
'userIdPrefixForSocket' => 'BBEE_',
'emitMarker' => '_INITIATE_CALL_',
'dataObj' => array(
'isBuddybee' => 1,
'targetRoute' => '_INITIATE_CALL_',
'targetUrl' => '_INITIATE_CALL_',
'targetPath' => '_INITIATE_CALL_',
'targetMobileAppPath' => '_INITIATE_CALL_',
'targetId' => $applicantId,
'meetingId' => 0,
'userId' => $applicantId,
'applicantId' => $applicantId,
'taggedUserIds' => ['BBEE_' . $thisUserId],
'route' => '_INITIATE_CALL_',
'phoneNo' => $applicant->getPhone()
),
'firebasePushData' => array(
'notification' => array(
'title' => 'Call Initiate',
'body' => "Call initiation with " . $applicant->getFirstname() . " " . $applicant->getLastname() . " on " . $applicant->getPhone() . " "
),
'data' => [
// 'score' => '850',
// 'time' => '2:45',
'route' => '_INITIATE_CALL_',
'phoneNo' => $applicant->getPhone()
],
'android' => [
'notification' => [
// icon: 'stock_ticker_update',
// color: '#7e55c3',
'imageUrl' => '_INITIATE_CALL_'
]
],
'topic' => 'SESSION BOOKED',
'tokens' => $adminTokenList,
)
]);
return new JsonResponse(array(
'success' => true,
'applicantId' => $applicantId,
));
}
if ($action == '_SEND_WELCOME_MESSAGE_') {
$applicantWasTemporary = $applicant->getIstemporaryEntry();
$applicant->setIstemporaryEntry(0);
if ($applicant->getTempPassword() != '')
$applicant->setTriggerResetPassword(1);
//salt will be username
// $this->container->get('sha256salted_encoder')->isPasswordValid($user->getPassword(), $request->request->get('password'), $user->getSalt())
$em->flush();
if ($applicantWasTemporary == 1 || ($applicantWasTemporary != 1 && $forceAction == 1)) {
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = '@Application/email/templates/buddybeeRegistrationComplete.html.twig';
$bodyData = array(
'name' => $applicant->getFirstname() . ' ' . $applicant->getLastname(),
'email' => $applicant->getOAuthEmail(),
'showPassword' => $applicant->getTempPassword() != '' ? 1 : 0,
'password' => $applicant->getTempPassword(),
);
$attachments = [];
$forwardToMailAddress = $applicant->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' => 'Welcome to BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'encryptionMethod' => 'ssl',
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
return new JsonResponse(array(
'success' => true,
'applicantId' => $applicantId,
));
}
}
return new JsonResponse(array(
'success' => false,
'applicantId' => $applicantId,
));
}
public function AddBeeCardAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
// $dt = Inventory::GetDrDetails($em, $id, $item_id);
$repeatCount = 1;
$assignProductId = '';
$queryCondition = [];
$cardList = [];
$cardCount = $request->get('cardCount', 1);
$cardAmount = $request->get('cardAmount', 0);
$coinCount = $request->get('coinCount', 100);
$rePrintFlag = $request->request->has('rePrintFlag') ? $request->request->get('rePrintFlag') : 0;
$cardIds = json_decode($request->get('cardIds', ''), true);
$printFlag = $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
$returnJson = $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
$physicalOnly = $request->get('physicalOnly', 1);
$retailerId = $request->get('retailerId', 0);
$useCount = $request->get('useCount', 1);
// if(!empty($cardIds))
// $queryCondition['id']=$cardIds;
// if($physicalOnly==1)
// $queryCondition['isForHardCopy']=1;
// if($rePrintFlag==0)
// $queryCondition['printed']=[0,null];
if ($cardAmount != 0) $queryCondition['amount'] = $cardAmount;
if ($coinCount != 0) $queryCondition['coinCount'] = $coinCount;
if ($returnJson == 1)
$printFlag = 0;
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findBy(
$queryCondition, [], $cardCount
);
$generateOptions = [
'amount' => $cardAmount,
'coinCount' => $coinCount,
'cardCount' => $cardCount,
'serial' => '_AUTO_',
'pin' => '_AUTO_',
'useCount' => $useCount,
'retailerId' => $retailerId,
];
$generatedData = MiscActions::GenerateBeeCode($em, $generateOptions);
$cardList = $generatedData['data'];
return new JsonResponse($generatedData);
}
public function communicationLogUpdateAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$thisUserId = $session->get(UserConstants::USER_ID);
$allTargetIds = [];
// $targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
// ->findBy(
// array(
//
// )
// );
// foreach ($targets as $target)
// {
// if($target->getIsAdmin()==null || $target->getIsAdmin()<=0)
// if($target->getIsConsultant()==null || $target->getIsConsultant()<=0)
// $allTargetIds[]=$target->getApplicantId();
//
// }
$allTargetIds = [$request->request->get('targetId', 0)];
//
// $dt = Inventory::GetDrDetails($em, $id, $item_i
foreach ($allTargetIds as $tid) {
$comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
->findOneBy(
array(
'targetId' => $tid
)
);
if (!$comm)
$comm = new EntityCommunicationLog();
$target = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $request->request->get('targetId', 0)
)
);
$commData = [];
$commPromiseTypes = BuddybeeConstant::$commPromiseTypes;
$commTypes = BuddybeeConstant::$commTypes;
$commPromiseDetails = BuddybeeConstant::$commPromiseDetails;
$currDate = new \DateTime();
$currDateTs = $currDate->format('U');
$dt = [];
if ($request->request->has('tblCurRow')) {
foreach ($request->request->get('tblCurRow', []) as $ind => $rowId) {
$remdate = new \DateTime($request->request->get('reminderDate', [])[$ind]);
$actionTaken = $request->request->get('actionTaken', [])[$ind];
$remEnabled = $request->request->has('reminderEnabled_' . $rowId, 0);
$remdateTs = $remdate->format('U');
if ($actionTaken == 0 && $remEnabled == 1) {
MiscActions::addEntityScheduledNotification($em, [
'senderHash' => '_CUSTOM_',
'bodyTemplate' => '@Application/email/templates/consultancyCommunicationReminder.html.twig',
'bodyData' => [
'headline_1' => 'Reminder for ' . $commPromiseTypes[$request->request->get('promiseType', [])[$ind]] . ' on BuddyBee',
'text_1' => 'You are receiving this email to remind you of following-' . $commPromiseDetails[$request->request->get('promiseType', [])[$ind]]['title'],
'headline_1' => $request->request->get('reminderSubject', [])[$ind],
'text_1' => $request->request->get('reminderText', [])[$ind],
],
'subject' => 'Reminder for scheduled action on Buddybee ',
'emailIds' => [$target->getOAuthEmail()],
'companyImagePath' => '',
'forwardToMailAddress' => $target->getOAuthEmail(),
'encryptionMethod' => 'ssl',
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'startTimeTs' => $remdateTs,
'nextTimeTs' => $remdateTs,
'lastTimeTs' => $remdateTs,
'recurringMin' => 0,
'smtpPort' => 465,
]);
}
$actionTaken = 1;
$dt = array(
'commId' => '',
'promiseType' => $request->request->get('promiseType', [])[$ind],
'commDateTs' => $request->request->get('commDateTs', [])[$ind] != 0 ? $request->request->get('commDateTs', [])[$ind] : $currDateTs,
'followUpDateTs' => $request->request->get('followUpDateTs', [])[$ind] != 0 ? $request->request->get('followUpDateTs', [])[$ind] : 0,
'commEndDateTs' => $request->request->get('commDateTs', [])[$ind] != 0 ? $request->request->get('commEndDateTs', [])[$ind] : $currDateTs,
'communicationFeedback' => $request->request->get('communicationFeedback', [])[$ind],
'actionTaken' => $actionTaken,
'reminderDateTs' => $remdateTs,
'reminderEnabled' => $remEnabled,
'reminderSubject' => $request->request->get('reminderSubject', [])[$ind],
'reminderText' => $request->request->get('reminderText', [])[$ind],
);
$commData[] = $dt;
}
} else {
$commData = json_decode($comm->getCommunicationHistory(), true);
if ($commData == null) $commData = [];
$remdate = new \DateTime($request->request->get('reminderDateSingle', ''));
$comDate = new \DateTime($request->request->get('commDateSingle', ''));
$comEndDate = new \DateTime($request->request->get('commEndDateSingle', ''));
$followUpDate = $request->request->get('followUpDateSingle', '') == '' ? '' : (new \DateTime($request->request->get('followUpDateSingle', '')));
$followUpDateTs = $request->request->get('followUpDateSingle', '') == '' ? 0 : $followUpDate->format('U');
$actionTaken = $request->request->get('actionTakenSingle', 0);
$remEnabled = $request->request->has('reminderEnabledSingle', 0);
$remdateTs = $remdate->format('U');
if ($request->request->get('refFollowUpId', 0) != 0) {
$refFollowUp = $em->getRepository('CompanyGroupBundle\\Entity\\EntityScheduledNotification')
->findOneBy(
array(
'id' => $request->request->get('refFollowUpId', 0),
'notificationType' => GeneralConstant::NOTIFICATION_TYPE_FOLLOW_UP,
)
);
if ($refFollowUp) {
$refFollowUp->SetActionTaken(1);
$em->flush();
}
}
if ($actionTaken == 0 && $remEnabled == 1) {
MiscActions::addEntityScheduledNotification($em, [
'senderHash' => '_CUSTOM_',
'bodyTemplate' => '@Application/email/templates/consultancyCommunicationReminder.html.twig',
'bodyData' => [
'headline_1' => $request->request->get('reminderSubjectSingle', ''),
'text_1' => $request->request->get('reminderTextSingle', ''),
],
'subject' => 'Reminder for scheduled action on Buddybee ',
'emailIds' => [$target->getOAuthEmail()],
'companyImagePath' => '',
'forwardToMailAddress' => $target->getOAuthEmail(),
'encryptionMethod' => 'ssl',
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'startTimeTs' => $remdateTs,
'nextTimeTs' => $remdateTs,
'lastTimeTs' => $remdateTs,
'recurringMin' => 0,
'smtpPort' => 465,
]);
}
$followUpScheduleId = 0;
$followUpEnabled = $request->request->get('followUpEnabledSingle', 0);
$followUpDone = 0;
if ($actionTaken == 0 && $request->request->get('followUpEnabledSingle', 0) != 0) {
$followUpSchedule = MiscActions::addEntityScheduledNotification($em, [
'senderHash' => '_CUSTOM_',
'bodyTemplate' => '@Application/email/templates/consultancyCommunicationReminder.html.twig',
'bodyData' => [
'headline_1' => $request->request->get('reminderSubjectSingle', ''),
'text_1' => $request->request->get('reminderTextSingle', ''),
],
'subject' => 'Reminder for scheduled action on Buddybee ',
'emailIds' => [$target->getOAuthEmail()],
'companyImagePath' => '',
'forwardToMailAddress' => $target->getOAuthEmail(),
'encryptionMethod' => 'ssl',
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'startTimeTs' => $followUpDateTs,
'nextTimeTs' => $followUpDateTs,
'lastTimeTs' => 30 * 3600 * 24 + 1 * $followUpDateTs,
'expiresTs' => 30 * 3600 * 24 + 1 * $followUpDateTs,
'actionTaken' => 0,
'recurringMin' => 0,
'smtpPort' => 465,
'notificationType' => GeneralConstant::NOTIFICATION_TYPE_FOLLOW_UP,
'showAsNotification' => 1,
'title' => $commTypes[$request->request->get('commTypeSingle', 0)]['title'] . ' follow up',
'body' => $request->request->get('followUpTextSingle', 'General communication follow up'),
'targetType' => 3,
'targetId' => $tid,
'userIds' => ['BBEE_' . $thisUserId],
]);
$followUpDone = 0;
$followUpEnabled = $request->request->get('followUpEnabledSingle', 0);
if ($followUpSchedule)
$followUpScheduleId = $followUpSchedule->getId();
}
$actionTaken = 1;
$dt = array(
'commId' => '',
'commUserId' => 'BBEE_' . $thisUserId,
'followUpScheduleId' => $followUpScheduleId,
'followUpEnabled' => $followUpEnabled,
'followUpDone' => $followUpDone,
// 'commUserId' => $thisUserId,
'promiseType' => $request->request->get('promiseTypeSingle', 0),
'commType' => $request->request->get('commTypeSingle', 0),
'commDateTs' => $comDate->format('U'),
'commEndDateTs' => $comEndDate->format('U'),
'followUpDateTs' => $followUpDateTs,
'communicationFeedback' => $request->request->get('communicationFeedbackSingle'),
'reminderSubject' => $request->request->get('reminderSubjectSingle', ''),
'reminderText' => $request->request->get('reminderTextSingle', ''),
'followUpText' => $request->request->get('followUpTextSingle', ''),
'refFollowUpId' => $request->request->get('refFollowUpId', 0),
'actionTaken' => $actionTaken,
'reminderDateTs' => $remdateTs,
'reminderEnabled' => $remEnabled,
);
$commData[] = $dt;
}
$comm->setTargetId($tid);
$comm->setTargetType(3); //bbee applicant /admin
$comm->setCommunicatorId($thisUserId);
$comm->setCommunicationHistory(json_encode($commData));
$target->setImmediateFollowUpFlag(0);
$target->setPendingInitialCommunication(0);
MiscActions::updateEntityPerformanceIndex($em, [
'targetId' => $thisUserId,
'communicationData' => [
'count' => 1,
'score' => 10,
],
'followupData' => [
'count' => $request->request->has('refFollowUpId') ? 1 : 0,
'score' => $request->request->has('refFollowUpId') ? 20 : 0,
]
]);
$em->persist($comm);
$em->flush();
}
return new JsonResponse(array(
'success' => true,
'dt' => $dt
));
}
public function liveSupportPageSupportPersonAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
// $dt = Inventory::GetDrDetails($em, $id, $item_i
// $comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
// ->findOneBy(
// array(
// 'targetId'=>$request->request->get('targetId',0)
// )
// );
$userId = $session->get(UserConstants::USER_ID);
return $this->render('@Buddybee/pages/live_support_page_applicant.html.twig', array(
// return $this->render('@Buddybee/pages/live_support_page_support_person.html.twig', array(
'page_title' => 'Live Support',
'hostId' => $userId,
'userId' => $userId,
'relevance' => '_SUPPORT_PERSON_'
// 'recNotifications' => $recNotifications,
));
}
public function liveSupportPageApplicantAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
// $dt = Inventory::GetDrDetails($em, $id, $item_i
// $comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
// ->findOneBy(
// array(
// 'targetId'=>$request->request->get('targetId',0)
// )
// );
$userId = $session->get(UserConstants::USER_ID);
return $this->render('@Buddybee/pages/live_support_page_applicant.html.twig', array(
'page_title' => 'Live Support',
'hostId' => 0,
'userId' => $userId,
'relevance' => '_USER_SUPPORT_'
// 'recNotifications' => $recNotifications,
));
}
public function refreshLiveSupportMeetingRoomAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$currDate = new \DateTime();
$currDateTs = 1 * $currDate->format('U');
$userId = $session->get(UserConstants::USER_ID);
$action = $request->request->get('action', '_JOIN_'); //or _LEAVE_ or _BAN_ or _CHECK_ or _CANCEL_ or _CONFIRMATION_FAILED_
$silent = $request->request->get('silent', 0); //or _LEAVE_ or _BAN_ or _CHECK_ or _CANCEL_ or _CONFIRMATION_FAILED_
$retData = array(
'success' => false,
'action' => $action,
'silent' => $silent
);
$hostId = $request->request->get('hostId', $session->get(UserConstants::USER_ID, 0));
$applicantId = $request->request->get('applicantId', $hostId);
$liveSessionId = $request->request->get('liveSessionId', 0);
$liveSessionRoomCode = $request->request->get('liveSessionRoomCode', 0);
// $availableOrAllowed=$request->request->get('ifAvailable',1);
$authorizationType = $request->request->get('authorizationType', '_APPLICANT_'); //or _HOST_
$joinIfAllowedIdsEmpty = $request->request->get('joinIfAllowedIdsEmpty', 0); //or _HOST_
$queueDataFlag = $request->request->get('queueDataFlag', 0);
$queueJoinFlag = $request->request->get('queueJoinFlag', 0);
$queJoinPassed = false;
$hasActiveLiveRoomsFlag = $request->request->get('hasActiveLiveRoomsFlag', 0);
// $hasActiveLiveRoomsFlag=$request->request->get('hasActiveLiveRoomsFlag',0);
// 1st expire aany expired meeting Room
$expiredLiveSupportMeetingRoom = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("m.expireTs <= :expireTs")
->andWhere("m.expired != 0 ")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(100)
->getResult();
foreach ($expiredLiveSupportMeetingRoom as $expRoom) {
$expRoom->setExpired(1);
$em->flush();
}
$expiredLiveSupportMeetingQueue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("(m.expireTs <= :expireTs or m.expired = 1 or (m.autoExpireTsWhenAtFront !=0 and m.autoExpireTsWhenAtFront<=:expireTs))")
// ->andWhere(" ")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(100)
->getResult();
foreach ($expiredLiveSupportMeetingQueue as $expQue) {
$em->remove($expQue);
$em->flush();
}
$LiveSupportMeetingRoom = null;
//now if join, find the meetinf room which is available and if not create new
if (!$LiveSupportMeetingRoom && $liveSessionId != 0) {
$LiveSupportMeetingRoom = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->findOneBy(
array(
'id' => $liveSessionId,
'expired' => 0,
)
);
}
if (!$LiveSupportMeetingRoom && $liveSessionRoomCode != 0) {
$LiveSupportMeetingRoom = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->findOneBy(
array(
'meetingRoomCode' => $liveSessionRoomCode,
'expired' => 0,
)
);
}
// if(!$LiveSupportMeetingRoom && $liveSessionRoomCode!=0)
// {
// $LiveSupportMeetingRoom = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
// ->findOneBy(
// array(
// 'meetingRoomCode'=>$liveSessionRoomCode
// )
// );
// }
if ($action == '_JOIN_') {
$isAllowed = false;
if ($authorizationType == '_HOST_') {
if (!$LiveSupportMeetingRoom && $hostId != 0) {
$LiveSupportMeetingRoom = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->findOneBy(
array(
'hostId' => $hostId,
'expired' => 0,
)
);
}
if (!$LiveSupportMeetingRoom) {
$LiveSupportMeetingRoom = new LiveSupportMeetingRoom();
$LiveSupportMeetingRoom->setHostId($hostId);
$LiveSupportMeetingRoom->setOccupiedByApplicant(0);
$LiveSupportMeetingRoom->setMeetingRoomCode(MiscActions::GenerateRandomCrypto('LVS' . microtime(true)));
}
$LiveSupportMeetingRoom->setLiveFlag(1);
$LiveSupportMeetingRoom->setExpireTs((1 * $currDateTs) + (3600 * 24));
$LiveSupportMeetingRoom->setExpired(0);
$LiveSupportMeetingRoom->setStatus(GeneralConstant::ACTIVE);
$em->persist($LiveSupportMeetingRoom);
$em->flush();
$isAllowed = true;
$retData = array(
'success' => true,
'action' => $action,
'liveSessionId' => $LiveSupportMeetingRoom->getId(),
'liveSessionHostId' => $LiveSupportMeetingRoom->getHostId(),
'liveSessionCurrentAllowedId' => $LiveSupportMeetingRoom->getCurrentAllowedId(),
'isAllowed' => $isAllowed,
'liveSessionRoomCode' => $LiveSupportMeetingRoom->getMeetingRoomCode(),
);
} else if ($authorizationType == '_APPLICANT_') {
$retData = array(
'success' => false,
'action' => $action,
'liveSessionId' => 0,
'liveSessionHostId' => 0,
'liveSessionCurrentAllowedId' => 0,
'hasActiveLiveRooms' => 0,
'positionInQueue' => -1,
'isAllowed' => $isAllowed,
'liveSessionRoomCode' => '',
);
if (!$LiveSupportMeetingRoom) {
$LiveSupportMeetingRooms = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("m.expireTs > :expireTs")
->andWhere("m.expired != 1 ")
->andWhere("m.liveFlag = 1 ")
->andWhere("m.status = :status ")
->andWhere("m.currentAllowedId = $applicantId or (m.currentAllowedId is null and (
m.allowedIdList like '%,$applicantId]%' or
m.allowedIdList like '%,$applicantId,%' or
m.allowedIdList like '%[$applicantId,%'
) )")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
->setParameter('status', GeneralConstant::ACTIVE)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(1)
->getResult();
$LiveSupportMeetingRoom = isset($LiveSupportMeetingRooms[0]) ? $LiveSupportMeetingRooms[0] : null;
}
if ($LiveSupportMeetingRoom && $LiveSupportMeetingRoom->getLiveFlag() == 1) {
$currentAllowedIds = json_decode($LiveSupportMeetingRoom->getAllowedIdList(), true);
if ($currentAllowedIds == null) $currentAllowedIds = [];
if ($LiveSupportMeetingRoom->getCurrentAllowedId() == $applicantId || in_array($applicantId, $currentAllowedIds) || (empty($currentAllowedIds) && $joinIfAllowedIdsEmpty == 1)) {
$LiveSupportMeetingRoom->setCurrentAllowedId($applicantId);
// $currentAllowedIds[] = 1 * $applicantId;
$currentAllowedIds = array_merge($currentAllowedIds, array_diff([$applicantId], $currentAllowedIds));
$LiveSupportMeetingRoom->setAllowedIdList(json_encode($currentAllowedIds));
$LiveSupportMeetingRoom->setExpireTs((1 * $currDateTs) + (3600 * 24));
$LiveSupportMeetingRoom->setExpired(0);
$LiveSupportMeetingRoom->setOccupiedByApplicant(1);
$LiveSupportMeetingRoom->setStatus(GeneralConstant::ACTIVE);
$em->flush();
$isAllowed = true;
$retData['success'] = true;
$retData['liveSessionId'] = $LiveSupportMeetingRoom->getId();
$retData['isAllowed'] = $isAllowed;
$retData['liveSessionRoomCode'] = $LiveSupportMeetingRoom->getMeetingRoomCode();
$retData['liveSessionHostId'] = $LiveSupportMeetingRoom->getHostId();
$retData['liveSessionCurrentAllowedId'] = $LiveSupportMeetingRoom->getCurrentAllowedId();
$thisApplicantQueue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->findOneBy(
array(
'applicantId' => $applicantId,
'expired' => 0,
)
);
$em->remove($thisApplicantQueue);
$em->flush();
} else {
$retData['success'] = false;
$retData['isAllowed'] = $isAllowed;
}
}
}
}
if ($action == '_CHECK_') {
$isAllowed = false;
$position_in_queue = -1;
$retData = array(
'success' => false,
'checkSuccess' => false,
'action' => $action,
'liveSessionId' => 0,
'liveSessionHostId' => 0,
'hasActiveLiveRooms' => 0,
'positionInQueue' => $position_in_queue,
'isAllowed' => $isAllowed,
'liveSessionRoomCode' => '',
);
if ($hasActiveLiveRoomsFlag == 1) {
$ActiveLiveSupportMeetingRooms = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("m.expireTs > :expireTs")
->andWhere("m.expired != 1 ")
->andWhere("m.liveFlag = 1 ")
->andWhere("m.status = :status ")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
->setParameter('status', GeneralConstant::ACTIVE)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(1)
->getResult();
$retData['hasActiveLiveRooms'] = isset($ActiveLiveSupportMeetingRooms[0]) ? true : false;
$retData['checkSuccess'] = isset($ActiveLiveSupportMeetingRooms[0]) ? true : false;
}
$thisApplicantQueue = null;
if ($hasActiveLiveRoomsFlag == 1 && !$retData['hasActiveLiveRooms']) {
$queJoinPassed = false;
$retData['checkSuccess'] = false;
} else if ($queueJoinFlag == 1) {
$thisApplicantQueue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->findOneBy(
array(
'applicantId' => $applicantId,
'expired' => 0,
)
);
if (!$thisApplicantQueue) {
$thisApplicantQueue = new LiveSupportMeetingQueue();
$thisApplicantQueue->setApplicantId($applicantId);
$thisApplicantQueue->setLiveSupportMeetingRoomCode('_UNSET_');
$thisApplicantQueue->setRemoveOnNextFailedConfirmation(0);
$thisApplicantQueue->setSecondsBeforeExpiryIfNotConfirmed(30);
$thisApplicantQueue->setAutoExpireTsWhenAtFront(0);
$thisApplicantQueue->setExpireTs((1 * $currDateTs) + (3600 * 24));
$thisApplicantQueue->setExpired(0);
$thisApplicantQueue->setStatus(GeneralConstant::ACTIVE);
$em->persist($thisApplicantQueue);
$em->flush();
}
if ($thisApplicantQueue) {
$position_in_queue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->createQueryBuilder('m')
->select("count(m)")
->where("m.id < " . $thisApplicantQueue->getId())
->getQuery()
->getSingleScalarResult();
$retData['positionInQueue'] = 1 * $position_in_queue;
$retData['checkSuccess'] = true;
}
}
if ($position_in_queue == 0) {
if (!$LiveSupportMeetingRoom) {
$LiveSupportMeetingRooms = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("m.expireTs > :expireTs")
->andWhere("m.expired != 1 ")
->andWhere("m.liveFlag = 1 ")
->andWhere("m.status = :status ")
->andWhere("m.occupiedByApplicant = 0 ")
->orWhere("m.currentAllowedId = $applicantId or (m.currentAllowedId is null and (
m.allowedIdList like '%,$applicantId]%' or
m.allowedIdList like '%,$applicantId,%' or
m.allowedIdList like '%[$applicantId,%'
) )")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
->setParameter('status', GeneralConstant::ACTIVE)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(1)
->getResult();
$LiveSupportMeetingRoom = isset($LiveSupportMeetingRooms[0]) ? $LiveSupportMeetingRooms[0] : null;
}
if ($LiveSupportMeetingRoom) {
$currentAllowedIds = json_decode($LiveSupportMeetingRoom->getAllowedIdList(), true);
if ($currentAllowedIds == null) $currentAllowedIds = [];
// $currentAllowedIds[] = 1 * $applicantId;
$currentAllowedIds = array_merge($currentAllowedIds, array_diff([$applicantId], $currentAllowedIds));
$LiveSupportMeetingRoom->setAllowedIdList(json_encode($currentAllowedIds));
if ($thisApplicantQueue)
if ($thisApplicantQueue->getAutoExpireTsWhenAtFront() == 0)
$thisApplicantQueue->setAutoExpireTsWhenAtFront(1 * $currDateTs + 60);
$em->flush();
$isAllowed = true;
$queJoinPassed = true;
$retData['success'] = true;
$retData['liveSessionId'] = $LiveSupportMeetingRoom->getId();
$retData['isAllowed'] = $isAllowed;
$retData['liveSessionRoomCode'] = $LiveSupportMeetingRoom->getMeetingRoomCode();
$retData['liveSessionHostId'] = $LiveSupportMeetingRoom->getHostId();
} else {
$retData['success'] = false;
$retData['isAllowed'] = $isAllowed;
}
} else {
$firstOneInQueue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->findOneBy(
array(
// 'applicantId' => $applicantId,
'expired' => 0,
), array(
'id' => 'desc'
)
);
if ($firstOneInQueue) {
$firstOneInQueueApplicantId = $firstOneInQueue->getApplicantId();
if (!$LiveSupportMeetingRoom) {
$LiveSupportMeetingRooms = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("m.expireTs > :expireTs")
->andWhere("m.expired != 1 ")
->andWhere("m.liveFlag = 1 ")
->andWhere("m.status = :status ")
->andWhere("m.occupiedByApplicant = 0 ")
->orWhere("m.currentAllowedId = $firstOneInQueueApplicantId or (m.currentAllowedId is null and (
m.allowedIdList like '%,$firstOneInQueueApplicantId]%' or
m.allowedIdList like '%,$firstOneInQueueApplicantId,%' or
m.allowedIdList like '%[$firstOneInQueueApplicantId,%'
) )")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
->setParameter('status', GeneralConstant::ACTIVE)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(1)
->getResult();
$LiveSupportMeetingRoom = isset($LiveSupportMeetingRooms[0]) ? $LiveSupportMeetingRooms[0] : null;
}
if ($LiveSupportMeetingRoom) {
if ($firstOneInQueue->getAutoExpireTsWhenAtFront() == 0) {
$firstOneInQueue->getAutoExpireTsWhenAtFront(1 * $currDateTs + 60);
} else if ($firstOneInQueue->getAutoExpireTsWhenAtFront() <= 1 * $currDateTs) {
$em->remove($firstOneInQueue);
}
$em->flush();
}
}
$em->flush();
}
}
if ($action == '_CONFIRMATION_FAILED_') {
$isAllowed = false;
$position_in_queue = -1;
$retData = array(
'success' => false,
'action' => $action,
'liveSessionId' => 0,
'hasActiveLiveRooms' => 0,
'positionInQueue' => $position_in_queue,
'isAllowed' => $isAllowed,
'liveSessionRoomCode' => '',
);
$thisApplicantQueue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->findOneBy(
array(
'applicantId' => $applicantId,
'expired' => 0,
)
);
// if (!$thisApplicantQueue) {
// $thisApplicantQueue = new LiveSupportMeetingQueue();
//
// $thisApplicantQueue->setApplicantId($applicantId);
// $thisApplicantQueue->setLiveSupportMeetingRoomCode('_UNSET_');
// $thisApplicantQueue->setRemoveOnNextFailedConfirmation(0);
// $thisApplicantQueue->setSecondsBeforeExpiryIfNotConfirmed(30);
//
//
// $thisApplicantQueue->setExpireTs((1 * $currDateTs) + (3600 * 24));
// $thisApplicantQueue->setExpired(0);
// $thisApplicantQueue->setStatus(GeneralConstant::ACTIVE);
// $em->persist($thisApplicantQueue);
// $em->flush();
// }
if ($thisApplicantQueue) {
$thisApplicantQueue->setAutoExpireTsWhenAtFront(0);
$em->flush();
if ($thisApplicantQueue->getRemoveOnNextFailedConfirmation() == 1) {
$em->remove($thisApplicantQueue);
$em->flush();
$thisApplicantQueue = null;
}
}
if ($thisApplicantQueue) {
$nextApplicants = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->createQueryBuilder('m')
// ->where("m.hostId = :hostId")
->where("m.expireTs > :expireTs")
->andWhere("m.expired != 1 ")
->andWhere("m.liveFlag = 1 ")
->andWhere("m.status = :status ")
->andWhere("m.currentAllowedId = $applicantId or (m.currentAllowedId is null and (
m.allowedIdList like '%,$applicantId]%' or
m.allowedIdList like '%,$applicantId,%' or
m.allowedIdList like '%[$applicantId,%'
) )")
// ->setParameter('hostId', $hostId)
->setParameter('expireTs', $currDateTs)
->setParameter('status', GeneralConstant::ACTIVE)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(1)
->getResult();
$nextApplicantQue = isset($nextApplicants[0]) ? $nextApplicants[0] : null;
if ($nextApplicantQue) {
$thisApplicantQueue->setApplicantId($nextApplicantQue->getApplicantId());
$nextApplicantQue->setApplicantId($applicantId);
$nextApplicantQue->setRemoveOnNextFailedConfirmation(1);
$em->flush();
$position_in_queue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->createQueryBuilder('m')
->select("count(m)")
->where("m.id < " . $nextApplicantQue->getId())
->getQuery()
->getSingleScalarResult();
$retData['positionInQueue'] = 1 * $position_in_queue;
} else {
$thisApplicantQueue->setRemoveOnNextFailedConfirmation(1);
$em->flush();
$position_in_queue = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingQueue')
->createQueryBuilder('m')
->select("count(m)")
->where("m.id < " . $thisApplicantQueue->getId())
->getQuery()
->getSingleScalarResult();
$retData['positionInQueue'] = 1 * $position_in_queue;
}
}
}
if ($action == '_LEAVE_') {
$isAllowed = false;
if ($authorizationType == '_HOST_') {
if (!$LiveSupportMeetingRoom && $hostId != 0) {
$LiveSupportMeetingRoom = $em->getRepository('CompanyGroupBundle\\Entity\\LiveSupportMeetingRoom')
->findOneBy(
array(
'hostId' => $hostId,
'expired' => 0,
)
);
}
if (!$LiveSupportMeetingRoom) {
} else {
$LiveSupportMeetingRoom->setLiveFlag(0);
$em->flush();
$isAllowed = true;
$retData = array(
'success' => true,
'action' => $action,
'liveSessionId' => $LiveSupportMeetingRoom->getId(),
'isAllowed' => $isAllowed,
'liveSessionRoomCode' => $LiveSupportMeetingRoom->getMeetingRoomCode(),
);
}
} else if ($authorizationType == '_APPLICANT_') {
if ($LiveSupportMeetingRoom) {
if ($applicantId == '_AUTO_')
$applicantId = $LiveSupportMeetingRoom->getCurrentAllowedId();
$currentAllowedIds = json_decode($LiveSupportMeetingRoom->getAllowedIdList(), true);
if ($currentAllowedIds == null) $currentAllowedIds = [];
$LiveSupportMeetingRoom->setAllowedIdList(json_encode(array_diff([$applicantId], $currentAllowedIds)));
$LiveSupportMeetingRoom->setOccupiedByApplicant(0);
if ($LiveSupportMeetingRoom->getCurrentAllowedId() == $applicantId) $LiveSupportMeetingRoom->setCurrentAllowedId(null);
$em->flush();
$isAllowed = false;
$retData = array(
'success' => true,
'action' => $action,
'liveSessionId' => $LiveSupportMeetingRoom->getId(),
'isAllowed' => $isAllowed,
'liveSessionRoomCode' => $LiveSupportMeetingRoom->getMeetingRoomCode(),
);
} else {
$retData = array(
'success' => false,
'action' => $action,
'isAllowed' => $isAllowed,
);
}
}
}
$retData['silent'] = $silent;
return new JsonResponse($retData);
}
public function addApplicantToLiveSupportMeetingRoomAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
// $dt = Inventory::GetDrDetails($em, $id, $item_i
// $comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
// ->findOneBy(
// array(
// 'targetId'=>$request->request->get('targetId',0)
// )
// );
$userId = $session->get(UserConstants::USER_ID);
return new JsonResponse(array(
'success' => true
));
}
public function testPushNotificationAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
System::sendPushNotification(['cnX9xvw9Ri2Fn3MUANOxqi:APA91bEMXJZpVv12JbjTgJXKXzn3300Nwtzpnq1zfcNYDtcJG2hZfpVxRtW1MHOLlA_NoPHHApK7489UPlsytL1BO4pv2bxj1QFDRx4t3QHcSsk_dzHINy68EDz171E17bs2LgQM5r0A'],
$this->container->getParameter('kernel.root_dir')
);
// $dt = Inventory::GetDrDetails($em, $id, $item_i
// $comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
// ->findOneBy(
// array(
// 'targetId'=>$request->request->get('targetId',0)
// )
// );
$userId = $session->get(UserConstants::USER_ID);
return new JsonResponse(array(
'success' => true
));
}
public function removeApplicantFromLiveSupportMeetingRoomAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
// $dt = Inventory::GetDrDetails($em, $id, $item_i
// $comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
// ->findOneBy(
// array(
// 'targetId'=>$request->request->get('targetId',0)
// )
// );
$userId = $session->get(UserConstants::USER_ID);
return new JsonResponse(array(
'success' => true
));
}
public function PricingWithSessionAction(Request $request, $id)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$invoiceId = 0;
$topic = null;
$scheduleId = 0;
$consultantDetails = null;
$consultantId = 0;
$sessionId = 0;
$topicSessionValue = 0;
$consultantSchedule = null;
$scheduleText = '';
$autoRedirected = 0;
$autoAssignMeetingSession = 0;
$sessionConsumeCount = $request->request->get('sessionConsumeCount', $request->request->get('sessionDurationSelector', 1));
$sessionDuration = $sessionConsumeCount * 30;
$meetingSessionId = 0;
$requiredPurchaseSessionCount = $sessionConsumeCount;
$packageNames = BuddybeeConstant::$packageNames;
$packageDetails = BuddybeeConstant::$packageDetails;
$userId = $session->get(UserConstants::USER_ID);
if ($request->isMethod('GET') && $request->query->has('autoRedirected'))
$autoRedirected = $request->query->get('autoRedirected');
// $studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
if ($request->isMethod('POST') && $request->request->has('toPackagePage')) {
$topicId = $request->request->get('consultancyTopic');
$sessionId = $request->request->get('sessionSelector');
$topicSessionValue = $request->request->get('sessionSelector');
$consultantId = $request->request->get('consultantId');
$scheduleId = $request->request->get('consultancyScheduleId'); // this is timestamp
$scheduleTs = $request->request->get('consultancyScheduleId'); // this is timestamp
// $sessionConsumeCount = $request->request->get('sessionConsumeCount');
$sessionConsumeCount = $request->request->get('sessionConsumeCount', $request->request->get('sessionDurationSelector', 1));
$sessionDuration = $sessionConsumeCount * 30;
$autoAssignMeetingSession = 1;
//$topic = $em->getRepository(ConsultancyTopic::class)->findAll();
// $scheduleText = isset($schdeuledTime[$scheduleId]) ? $schdeuledTime[$scheduleId]['date'] . ' ' . $schdeuledTime[$scheduleId]['startTime'] : '';
$scheduleTextDate = new \DateTime('@' . $scheduleId);;
$scheduleText = $scheduleTextDate->format('F d, Y H:i');
$currentUserBalance = 0;
$gatewayAmount = 0;
$redeemedAmount = 0;
$redeemedSessionCount = 0;
$payableAmount = 0;
$totalAmount = 0;
$totalSessionCount = 0;
$consumedAmount = 0;
$consumedSessionCount = $request->request->get('sessionDurationSelector', 0);
$currentUserSessionBalance = 0;
$currentUserBalance = 0;
$balancedFromUserSessionCount = 0;
$balancedFromUserBalance = 0;
$studentId = 0;
if ($session->get(UserConstants::USER_ID)
&& $session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT
) {
$studentDetails = null;
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
$currentUserSessionBalance = $studentDetails->getSessionCountBalance();
$studentId = $studentDetails->getApplicantId();
}
if ($consumedSessionCount <= $currentUserSessionBalance) {
$balancedFromUserSessionCount = 1;
}
//1st do the necessary
$beeCode = $request->request->get('beeCode', '');
$payableAmount = $request->request->get('payableAmount', 0);
$scheduledStartTime = new \DateTime('@' . $scheduleId);;
if ($balancedFromUserSessionCount == 1) {
// $session->set('hasCoin',1);
$scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
$em_goc,
$request->request->get('consultantId', 0),
$studentId,
$scheduledStartTime->format('U'),
(30 * $consumedSessionCount),
1
);
if (!$scheduleValidity) {
$url = $this->generateUrl(
'consultant_profile'
);
$output = [
'page_title' => 'Package And Pricing',
// 'topic' => $topic,
// 'consultantDetails' => $consultantDetails,
'packageDetails' => MiscActions::toListArray($packageDetails),
'packageNames' => MiscActions::toListArray($packageNames),
'scheduleId' => $scheduleId,
'consultantId' => $consultantId,
'topicSessionValue' => $topicSessionValue,
'autoRedirected' => $autoRedirected,
'meetingSessionId' => $meetingSessionId,
'invoiceId' => $invoiceId,
'sessionConsumeCount' => $sessionConsumeCount,
'requiredPurchaseSessionCount' => $requiredPurchaseSessionCount,
'autoAssignMeetingSession' => $autoAssignMeetingSession,
'sessionDuration' => $sessionDuration,
// 'consultantSchedule' => $consultantSchedule,
'scheduleText' => $scheduleText,
'userId' => $userId,
// 'timeSchedule' => $consultantSchedule,
'proceedToCheckout' => 0,
'errorFlag' => 1,
'redirectUrl' => $url,
'message' => 'Session Booking Expired or not Found!',
];
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $request->request->get('consultantId', 0) . '?errorFlag=1&message=Session Booking Expired or not Found');
}
$new = new EntityMeetingSession();
$new->setTopicId($request->request->get('consultancyTopic', 0));
$new->setConsultantId($request->request->get('consultantId', 0));
$new->setStudentId($studentId);
$consultancyTopic = $em_goc->getRepository(EntityMeetingSession::class)->find($request->request->get('consultancyTopic', 0));
$new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
$new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
$scheduledEndTime = new \DateTime('@' . $scheduleId);;
$scheduledEndTime = $scheduledEndTime->modify('+' . (30 * $consumedSessionCount) . ' Minute');
// $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
// $scheduledEndTime->setTimezone(new \DateTimeZone('UTC'));
//$new->setScheduledTime($request->request->get('setScheduledTime'));
$new->setScheduledTime($scheduledStartTime);
$new->setScheduledTimeTs($scheduledStartTime->format('U'));
$new->setDurationAllowedMin((30 * $consumedSessionCount));
$new->setDurationLeftMin((30 * $consumedSessionCount));
$new->setSessionExpireDate($scheduledEndTime);
$new->setSessionExpireDateTs($scheduledEndTime->format('U'));
$new->setEquivalentSessionCount($consumedSessionCount);
$new->setUsableSessionCount($consumedSessionCount);
$new->setMeetingActionFlag(0);// no action waiting for meeting
$new->setPayableAmount($payableAmount);
$new->setDueAmount($request->request->get('dueAmount', 0));
$currentUnixTime = new \DateTime();
$currentUnixTimeStamp = $currentUnixTime->format('U');
// $studentId = $request->request->get('studentId', $session->get(UserConstants::USER_ID));
$consultantId = $request->request->get('consultantId', 0);
$new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
//$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
//$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
$new->setPackageName(($request->request->get('packageName', '')));
$new->setPcakageDetails(($request->request->get('packageData', '')));
$new->setScheduleId($scheduleId);
$new->setSessionValue($topicSessionValue);
// $new->setIsPayment(0);
$new->setConsultantIsPaidFull(0);
$em_goc->persist($new);
$em_goc->flush();
$meetingSessionId = $new->getSessionId();
// $studentDetails->setSessionCountBalance($currentUserSessionBalance-$consumedSessionCount);
// $studentDetails->setTotalSessionUsed($studentDetails->getTotalSessionUsed()+$consumedSessionCount);
$em_goc->flush();
$new_invoice = new EntityInvoice();
$invoiceDate = new \DateTime();
$new_invoice->setInvoiceDate($invoiceDate);
$new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
$new_invoice->setStudentId($studentId);
$new_invoice->setMeetingId($meetingSessionId);
$new_invoice->setAmount($totalAmount);
$new_invoice->setGatewayBillAmount($gatewayAmount);
$new_invoice->setRedeemedAmount($redeemedAmount);
$new_invoice->setRedeemedSessionCount($redeemedSessionCount);
$new_invoice->setPaidAmount(0);
$new_invoice->setDueAmount(0);
$new_invoice->setInvoiceType(1);
$new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' . microtime(true)));
$new_invoice->setAmountType(1);
$new_invoice->setConsumeAmount(0);
$new_invoice->setSessionCount(0);
$new_invoice->setConsumeSessionCount($consumedSessionCount);
$new_invoice->setIsPaidfull(0);
$new_invoice->setIsProcessed(0);
$new_invoice->setApplicantId($studentId);
$new_invoice->setIsRecharge(0);
$new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED);
$new_invoice->setIsPayment(0); //0 means receive
$new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
// $new_invoice->setStatus($request->request->get(0));
$em_goc->persist($new_invoice);
$em_goc->flush();
$invoiceId = $new_invoice->getId();
$retData = Buddybee::ProcessEntityInvoice($em_goc, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],$this->container->getParameter('kernel.root_dir'), false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
MiscActions::RefreshBuddybeeBalanceOnSession($em_goc, $request->getSession());
$meetingSessionId = $retData['meetingId'];
if ($meetingSessionId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url . '/' . $meetingSessionId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
}
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $meetingSessionId);
} else {
// $session->set('hasCoin',0);
$url = $this->generateUrl(
'pricing_plan_page_with_session'
);
$output = array(
'page_title' => 'Package And Pricing',
// 'topic' => $topic,
// 'consultantDetails' => $consultantDetails,
'COIN_GENERAL_MULT' => BuddybeeConstant::COIN_GENERAL_MULT,
'packageDetails' => MiscActions::toListArray($packageDetails),
'packageNames' => MiscActions::toListArray($packageNames),
'scheduleId' => $scheduleId,
'consultantId' => $consultantId,
'topicSessionValue' => $topicSessionValue,
'autoRedirected' => $autoRedirected,
'meetingSessionId' => $meetingSessionId,
'invoiceId' => $invoiceId,
'sessionConsumeCount' => $sessionConsumeCount,
'requiredPurchaseSessionCount' => $requiredPurchaseSessionCount,
'autoAssignMeetingSession' => $autoAssignMeetingSession,
'sessionDuration' => $sessionDuration,
// 'consultantSchedule' => $consultantSchedule,
'scheduleText' => $scheduleText,
'userId' => $userId,
// 'timeSchedule' => $consultantSchedule,
'proceedToCheckout' => 0,
'message' => 'Insufficient coins!',
'errorFlag' => 1,
'redirectUrl' => $url
);
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $request->request->get('consultantId', 0) . '?errorFlag=1&message=Not enough Coins');
}
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
if ($request->request->has('returnJson'))
return new JsonResponse($output);
else
return $this->redirect($url . '/' . $meetingSessionId);
}
//
}
if ($userId != 0) {
$applicantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->findOneBy(array(
'applicantId' => $userId
));
if ($applicantDetails)
$requiredPurchaseSessionCount = $sessionConsumeCount - (1 * $applicantDetails->getSessionCountBalance());
}
return $this->render('@Buddybee/pages/pricing.html.twig', array(
'page_title' => 'Package And Pricing',
// 'topic' => $topic,
'consultantDetails' => $consultantDetails,
'packageDetails' => $packageDetails,
'packageNames' => $packageNames,
'scheduleId' => $scheduleId,
'consultantId' => $consultantId,
'topicSessionValue' => $topicSessionValue,
'autoRedirected' => $autoRedirected,
'meetingSessionId' => $meetingSessionId,
'invoiceId' => $invoiceId,
'sessionConsumeCount' => $sessionConsumeCount,
'requiredPurchaseSessionCount' => $requiredPurchaseSessionCount,
'autoAssignMeetingSession' => $autoAssignMeetingSession,
'sessionDuration' => $sessionDuration,
'consultantSchedule' => $consultantSchedule,
'scheduleText' => $scheduleText,
'userId' => $userId,
'timeSchedule' => $consultantSchedule
));
// return $this->render('@Buddybee/pages/pricing.html.twig', array(
// 'page_title' => 'Package And Pricing',
// ));
}
public function Profile(Request $request, $id)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
if ($id != 0)
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($id);
else
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
// $review = $em->getRepository('CompanyGroupBundle\\Entity\\EntityReview')->findBy(
// array(
// 'consultantId' => $consultantDetails->getApplicantId()
// )
// );
// $meetingSession = $em->getRepository(EntityMeetingSession::class)->findBy(
// array(
// 'studentId' => $consultantDetails->getApplicantId(),
// )
// );
// $topic = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(
// array(
//
// )
// );
// $timeSchedule = array(
// 'date' => $request->get('date'),
// 'startTime' => $request->get('startTime'),
// 'endTIme' => $request->get('endTime'),
// );
if ($request->isMethod('POST')) {
$timeSchedule = [];
$clearOld = $request->request->get('clearOld', 1);
$rowCount = $request->request->get('rowCount', []);
$scheduleData = $request->request->get('scheduleData', []);
if (is_string($scheduleData)) $scheduleData = json_decode($scheduleData, true);
if ($scheduleData == null) $scheduleData = [];
foreach ($rowCount as $key => $val) {
if ($request->get('scheduleType')[$key] == '' || ($request->get('scheduleType')[$key] == 2 && $request->get('dow_' . $val, []) == [])
|| ($request->get('scheduleType')[$key] == 1 && $request->get('date')[$key] == '')
)
continue;
$indTimeSche = array(
'id' => $request->request->has('id') ? $request->request->get('id')[$key] : 0,
'date' => $request->get('date')[$key],
'dateUpto' => $request->get('dateUpto')[$key],
'type' => $request->get('scheduleType')[$key], // 0=specific date 1=every mentioned day of month 2=every mentioned day of week
// 'dom' => $request->get('dom')[$key], // based on type
'dow' => $request->get('dow_' . $val), // based on type
'startTime' => $request->get('startTime')[$key],
'endTime' => $request->get('endTime')[$key],
'timeZone' => $request->get('consultant_timezone_' . $val, $request->get('consultant_timezone', '')),
);
$timeSchedule[] = $indTimeSche;
}
foreach ($scheduleData as $key => $val) {
if ($val['scheduleType'] == '' || ($val['scheduleType'] == 2 && $val['dow'] == [])
|| ($val['scheduleType'] == 1 && $val['date'] == '')
)
continue;
$indTimeSche = array(
'id' => $val['id'],
'date' => $val['date'],
'dateUpto' => $val['dateUpto'],
'type' => $val['scheduleType'], // 0=specific date 1=every mentioned day of month 2=every mentioned day of week
// 'dom' => $request->get('dom')[$key], // based on type
'dow' => $val['dow'], // based on type
'startTime' => $val['startTime'],
'endTime' => $val['endTime'],
'deleteFlag' => isset($val['deleteFlag']) ? $val['deleteFlag'] : 0,
'timeZone' => $val['consultant_timezone'],
);
$timeSchedule[] = $indTimeSche;
}
$consultantSchedules = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findBy(
array(
'consultantId' => $request->request->get('consultantId')
)
);
if ($clearOld == 1) {
foreach ($consultantSchedules as $d) {
$em->remove($d);
$em->flush();
}
}
$newSchAvailableStatus = 0;
foreach ($timeSchedule as $d) {
$currDate = new \DateTime();
$startDate = new \DateTime($d['date'] . ' ' . $d['startTime'] . ':00 ' . $d['timeZone']);
$endDate = new \DateTime($d['dateUpto'] . ' ' . $d['endTime'] . ':00 ' . $d['timeZone']);
if ($endDate <= $currDate) {
if (isset($d['deleteFlag'])) {
if ($d['deleteFlag'] == 1) {
} else {
continue;
}
} else {
continue;
}
}
if ($d['id'] != 0)
$newSch = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findOneBy(
array(
'id' => $d['id']
)
);
else
$newSch = new EntityConsultantSchedule();
if ($d['dow'] == null) $d['dow'] = [];
foreach ($d['dow'] as $j => $f) {
$d['dow'][$j] = 1 * $f;
}
$d['timeZone'] = str_pad($d['timeZone'], 5, '0', STR_PAD_RIGHT);
$newSch->setConsultantId($request->request->get('consultantId'));
$newSch->setDow(json_encode($d['dow']));
$newSch->setTimezoneStr($d['timeZone']);
$newSch->setStartTime($d['startTime']);
$newSch->setEndTime($d['endTime']);
$newSch->setType($d['type']);
$newSch->setStartDate($startDate);
$newSch->setStartDateTs($startDate->format('U'));
$newSch->setEndDate($endDate);
$newSch->setEndDateTs($endDate->format('U'));
$newSch->setTimeSchedule(json_encode([]));
// $newSch->setTimeSchedule(json_encode($timeSchedule));
if (isset($d['deleteFlag'])) {
if ($d['deleteFlag'] == 1)
$em->remove($newSch);
else {
$em->persist($newSch);
$newSchAvailableStatus = 1;
}
} else {
$em->persist($newSch);
$newSchAvailableStatus = 1;
}
$em->flush();
}
$consultantDetails->setScheduleAvailableFlag($newSchAvailableStatus);
$em->flush();
if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
return new JsonResponse(
array(
'page_title' => '',
'timeSchedule' => $timeSchedule,
'success' => true
)
);
}
}
$schedules = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findBy(array(
'consultantId' => $consultantDetails->getApplicantId()
));
$timeSchedule = [];
foreach ($schedules as $key => $val) {
$indTimeSche = array(
'date' => $val->getStartDate() ? $val->getStartDate()->format('Y-m-d') : '',
'dateUpto' => $val->getEndDate() ? $val->getEndDate()->format('Y-m-d') : '',
'type' => ($val->getType() != null && $val->getType() != '') ? $val->getType() : 2, // 0=specific date 1=every mentioned day of month 2=every mentioned day of week
// 'dom' => $request->get('dom')[$key], // based on type
'dow' => ($val->getDow() != null && $val->getDow() != '') ? json_decode($val->getDow(), true) : [], // based on type
'startTime' => $val->getStartTime(),
'endTime' => $val->getEndTime(),
'timeZone' => $val->getTimeZoneStr(),
);
$timeSchedule[] = $indTimeSche;
}
$coursePlanHistoryForThisUserAndTopic = [];
$coursePlanHistoryForThisUserAndTopicArray = [];
$defaultCoursePlanHistoryForThisUserAndTopic = [];
$coursePlanForTopicArray = [];
$coursePlanTopics = [];
$meetingTopicIds = [];
$meetings = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->findBy(
array(
'studentId' => $consultantDetails->getApplicantId()
// 'id' => $meetingSession->getTopicId(),
)
);
foreach ($meetings as $m) {
$meetingTopicIds[] = $m->getTopicId();
}
$topicsForCoursePlan = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')
->findBy(
array(
'id' => $meetingTopicIds,
)
);
if (!empty($topicsForCoursePlan)) {
foreach ($topicsForCoursePlan as $topicForCoursePlan) {
$coursePlanForThisTopic = json_decode($topicForCoursePlan->getCoursePlanData(), true);
if ($coursePlanForThisTopic == null) $coursePlanForThisTopic = BuddybeeConstant::$defaultCoursePlan;
$coursePlanTopics[$topicForCoursePlan->getId()] = $topicForCoursePlan;
$coursePlanForTopicArray[$topicForCoursePlan->getId()] = $coursePlanForThisTopic;
}
}
$coursePlanHistoryForThisUserAndTopicEntryArray = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCoursePlanHistory')
->findBy(
array(
'studentId' => $consultantDetails->getApplicantId(),
// 'topicId' => $meetingSession->getTopicId(),
)
);
$defaultCoursePlanHistoryForThisUserAndTopicEntry = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCoursePlanHistory')
->findOneBy(
array(
'studentId' => $consultantDetails->getApplicantId(),
'topicId' => 0, //default
)
);
if ($defaultCoursePlanHistoryForThisUserAndTopicEntry) {
$defaultCoursePlanHistoryForThisUserAndTopic = json_decode($defaultCoursePlanHistoryForThisUserAndTopicEntry->getData(), true);
if ($defaultCoursePlanHistoryForThisUserAndTopic == null) $defaultCoursePlanHistoryForThisUserAndTopic = [];
}
if (!empty($coursePlanHistoryForThisUserAndTopicEntryArray)) {
foreach ($coursePlanHistoryForThisUserAndTopicEntryArray as $coursePlanHistoryForThisUserAndTopicEntry) {
$coursePlanHistoryForThisUserAndTopic = json_decode($coursePlanHistoryForThisUserAndTopicEntry->getData(), true);
if ($coursePlanHistoryForThisUserAndTopic == null) $coursePlanHistoryForThisUserAndTopic = [];
$coursePlanHistoryForThisUserAndTopicArray[$coursePlanHistoryForThisUserAndTopicEntry->getTopicId()] = $coursePlanHistoryForThisUserAndTopic;
}
}
return $this->render('@Buddybee/pages/profile.html.twig', array(
'page_title' => 'Profile ',
'consultantDetails' => $consultantDetails,
'education' => json_decode($consultantDetails->getEducationData(), true),
'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
'certificate' => json_decode($consultantDetails->getCertificateData(), true),
'timeSchedule' => $timeSchedule,
'defaultCoursePlanHistoryForThisUserAndTopic' => $defaultCoursePlanHistoryForThisUserAndTopic,
'coursePlanHistoryForThisUserAndTopicArray' => $coursePlanHistoryForThisUserAndTopicArray,
'coursePlanForTopicArray' => $coursePlanForTopicArray,
'coursePlanTopics' => $coursePlanTopics,
'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
// 'review' => $review,
// 'meetingSession' => $meetingSession,
// 'topic'=>$topic,
// 'docData' => json_decode($topic->getDocumentData(),true),
));
}
public function ExtendMeetingDurationAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
if ($request->isMethod('POST')) {
$meeting = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->findOneBy(
array(
'sessionId' => $request->request->get('meetingId', 0)
// 'id' => $meetingSession->getTopicId(),
)
);
if ($meeting) {
if (
$request->request->get('extendDuration', 30) > 0 &&
(((1 * $meeting->getTotalExtensionMin()) + $request->request->get('extendDuration', 30)) <= 10 || $request->request->get('forced', 0) == 1)
) {
$meeting->setDurationAllowedMin((1 * $meeting->getDurationAllowedMin()) + $request->request->get('extendDuration', 30));
$meeting->setDurationLeftMin((1 * $meeting->getDurationLeftMin()) + $request->request->get('extendDuration', 30));
$meeting->setTotalExtensionMin((1 * $meeting->getTotalExtensionMin()) + $request->request->get('extendDuration', 30));
$em->flush();
return new JsonResponse(
array(
'success' => true
)
);
} else {
// $meeting->setTotalExtensionMin((1*$meeting->getTotalExtensionMin())+$request->request->get('extendDuration', 30));
// $em->flush();
return new JsonResponse(
array(
'success' => false
)
);
}
}
}
return new JsonResponse(
array(
'success' => false
)
);
}
public function DocumentManagementAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
// $documentLists = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findAll();;
// $docListArray = [];
// foreach ($documentLists as $document) {
// $docListArray [$document->getId()] = array(
// 'id' => $document->getId(),
// 'docName' => $document->getDocumentName(),
// 'expiryDays' => $document->getExpiryDays(),
// 'processingDays' => $document->getProcessingDays(),
// 'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
// 'checklist' => json_decode($document->getCheckList()),
//
// );
// }
if ($id == 0) {
if ($request->isMethod('post'))
if ($request->request->has('applicantId'))
$id = $request->request->get('applicantId');
}
if ($id != 0)
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($id);
else {
$id = $session->get(UserConstants::USER_ID);
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
}
$meetingSessions = $em->getRepository(EntityMeetingSession::class)->findBy(
array(
'studentId' => $consultantDetails->getApplicantId(),
)
);
$topicDetailsByTopicId = [];
$topicDetailsByMeetingSessionId = [];
$topicIds = [];
$semesterIdsByTopicId = [];
$topicData = [];
$currDocIdListByTopicId=[];
foreach ($meetingSessions as $meetingSession) {
$topicIds[] = $meetingSession->getTopicId();
$topic = $em->getRepository(EntityCreateTopic::class)->findOneBy(
array(
'id' => $meetingSession->getTopicId(),
)
);
if ($topic) {
$topicData[$topic->getId()] = array(
'topicName' => $topic->getId(),
'id' => $topic->getTopicName()
);
if (!isset($semesterIdsByTopicId[$topic->getId()]))
$semesterIdsByTopicId[$topic->getId()] = [];
$semesterIdsByTopicId[$topic->getId()][] = $meetingSession->getSessionValue();
$docDetailsForThisTopic=json_decode($topic->getDocumentData(),true);
if($docDetailsForThisTopic==null)
$docDetailsForThisTopic=[];
if(!isset($currDocIdListByTopicId[$topic->getId()]))
{
$currDocIdListByTopicId[$topic->getId()]=[];
foreach ($docDetailsForThisTopic as $ggdt)
{
$currDocIdListByTopicId[$topic->getId()][]=$ggdt['document'];
}
}
$topicDetailsByTopicId [$topic->getId()] ['data'] = $topic;
$topicDetailsByTopicId [$topic->getId()]['sessionValue'] = $meetingSession->getSessionValue();
$topicDetailsByMeetingSessionId [$meetingSession->getSessionId()] ['data'] = $topic;
$topicDetailsByMeetingSessionId [$meetingSession->getSessionId()]['sessionValue'] = $meetingSession->getSessionValue();
}
}
//file upload
if ($consultantDetails)
$new = $consultantDetails;
else
$new = new EntityApplicantDetails();
// $new->setDocumentList();
// $new->setDocImage($request->files->get('img',[]));
$em->persist($new);
$em->flush();
$defaultProductImage = '';
$image_list = [];
$productImages = [];
$upl_dir = '';
$documentList = array();
$documentListByTopicId = [];
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/consultantDocuments/';
$currDocList = json_decode($new->getDocumentList(), true);
if ($currDocList == null)
$currDocList = [];
$currDocListByTopicId = json_decode($new->getDocumentListByTopicId(), true);
if ($currDocListByTopicId == null)
$currDocListByTopicId = [];
$docList = MiscActions::GetDocumentDataForBuddybeeApplicant($em,
$id,
// $topicIds,
0, //show all documents
$semesterIdsByTopicId,
'_BY_STATUS_'
);
return $this->render('@Buddybee/pages/consultancy_document_management.html.twig', array(
'page_title' => 'Document Management ',
'consultantDetails' => $consultantDetails,
'topicDetailsByTopicId' => $topicDetailsByTopicId,
'docListArray' => [],
'currDocListByTopicId' => $currDocListByTopicId,
'currDocIdListByTopicId' => $currDocIdListByTopicId,
'currDocList' => $currDocList,
'docList' => $docList,
'topicData' => $topicData,
'semesterIdsByTopicId' => $semesterIdsByTopicId,
'thresholdAddDays' => BuddybeeConstant::$thresholdAddDays,
));
}
public function studentDashboardAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$startDate = new \DateTime();
// $startDate = new \DateTime();
if ($id == 0) {
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
if ($request->isMethod('POST')) {
}
$studentDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$upcomingMeetingSessionList = [];
$currTs = $startDate->format('U');
$currTs = $currTs * 1;
$olderDateThreshold = new \DateTime();
$olderDateThreshold->modify('-180 day');
$topicIds = [];
$semesterIdsByTopicId = [];
$topicData = [];
$meetingSession = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->createQueryBuilder('m')
->where("(m.studentId = :studentId or m.studentIds like '%".$session->get(UserConstants::USER_ID).",%' or m.studentIds like '%,".$session->get(UserConstants::USER_ID).",%' or m.studentIds like '%,".$session->get(UserConstants::USER_ID)."%')")
->andWhere("m.scheduledTimeTs >= :startAt ")
// ->andWhere("m.sessionExpireDateTs <= :endAt")
->setParameter('studentId', $session->get(UserConstants::USER_ID))
->setParameter('startAt', $olderDateThreshold->format('U'))
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(40)
->getResult();
// $meetingSession = $em->getRepository(EntityMeetingSession::class)->findBy(
// array(
// 'consultantId' => $session->get(UserConstants::USER_ID),
// )
// );
$consultantListForMeeting = [];
foreach ($meetingSession as $ms) {
if ($ms->getScheduledTimeTs() >= $currTs || ($ms->getScheduledTimeTs() < $currTs && $ms->getSessionExpireDateTs() > $currTs))
$upcomingMeetingSessionList[] = $ms;
$consultantListForMeeting[$ms->getConsultantId()] = $em->getRepository(EntityApplicantDetails::class)->findOneBy(
array(
'applicantId' => $ms->getConsultantId()
)
);
$topicIds[] = $ms->getTopicId();
$topic = $em->getRepository(EntityCreateTopic::class)->findOneBy(
array(
'id' => $ms->getTopicId(),
)
);
if ($topic) {
$topicData[$topic->getId()] = array(
'topicName' => $topic->getId(),
'id' => $topic->getTopicName()
);
if (!isset($semesterIdsByTopicId[$topic->getId()]))
$semesterIdsByTopicId[$topic->getId()] = [];
$semesterIdsByTopicId[$topic->getId()][] = $ms->getSessionValue();
$topicDetailsByTopicId [$topic->getId()] ['data'] = $topic;
$topicDetailsByTopicId [$topic->getId()]['sessionValue'] = $ms->getSessionValue();
$topicDetailsByMeetingSessionId [$ms->getSessionId()] ['data'] = $topic;
$topicDetailsByMeetingSessionId [$ms->getSessionId()]['sessionValue'] = $ms->getSessionValue();
}
}
$docList = MiscActions::GetDocumentDataForBuddybeeApplicant($em,
$session->get(UserConstants::USER_ID),
$topicIds,
$semesterIdsByTopicId,
'_BY_STATUS_'
);
$dashboardDataForApplicant = MiscActions::GetDashboardDataForApplicant($em,
$session->get(UserConstants::USER_ID),
'_STUDENT_'
);
// $payableAmount = $meetingSession->getPayableAmount();
// $consultantPaidAmount = (60/100) * $payableAmount;
// $studentBal = $consultantDetails->getAccountBalance();
// $totalbalance = $consultantPaidAmount + $studentBal;
return $this->render('@Application/pages/dashboard/student_dashboard.html.twig', array(
'page_title' => 'Dashboard ',
'studentDetails' => $studentDetails,
'dashboardDataForApplicant' => $dashboardDataForApplicant,
'docList' => $docList,
'consultantListForMeeting' => $consultantListForMeeting,
'upcomingMeetingSessionList' => $upcomingMeetingSessionList,
//'totalBal' => $totalbalance
));
}
public function studentDashboardOldAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
if ($id == 0) {
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
if ($request->isMethod('POST')) {
}
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$meetingSession = $em->getRepository(EntityMeetingSession::class)->findBy(
array(
'studentId' => $session->get(UserConstants::USER_ID),
)
);
// $payableAmount = $meetingSession->getPayableAmount();
// $consultantPaidAmount = (60/100) * $payableAmount;
// $studentBal = $consultantDetails->getAccountBalance();
// $totalbalance = $consultantPaidAmount + $studentBal;
return $this->render('@Application/pages/dashboard/student_dashboard.html.twig', array(
'page_title' => 'Dashboard ',
'consultantDetails' => $consultantDetails,
'meetingSessions' => $meetingSession,
//'totalBal' => $totalbalance
));
}
public function UpdateInlineDataAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$em_bundle = 'CompanyGroupBundle';
$fieldType = '_TEXT_';
$entityName = '';
$modifyTransDateFlag = 0;
$retData = array(
'success' => false,
'newValue' => ''
);
$session = $request->getSession();
if ($request->isMethod('POST')) {
$entityName = $request->request->has('entityName') ? $request->request->get('entityName') : '';
if ($request->request->has('entityBundle')) {
if ($request->request->get('entityBundle') == 'ApplicationBundle') {
$em_bundle = 'ApplicationBundle';
$em = $this->getDoctrine()->getManager();
}
}
if ($request->request->has('fieldType')) {
$fieldType = $request->request->get('fieldType');
}
if ($request->request->has('modifyTransDateFlag')) {
$modifyTransDateFlag = $request->request->get('modifyTransDateFlag');
}
$data = $em->getRepository($em_bundle . '\\Entity\\' . $request->request->get('entityName'))->findOneBy(
array
(
$request->request->get('findField') => $request->request->get('findValue')
)
);
if(!$data)
{
if($request->request->get('createIfNotFound',0)==1)
{
$cname = $em_bundle."\\Entity\\" . $request->request->get('entityName');
$data = new $cname;
$data->{'set'.$request->request->get('findField')}($request->request->get('findValue'));
}
}
if ($data) {
$retData['newValue'] = $request->request->get('setValue');
if ($fieldType == '_TEXT_') {
$setMethods = explode(',', $request->request->get('setMethod'));
foreach ($setMethods as $setMethod)
$data->{$setMethod}($request->request->get('setValue'));
$em->persist($data);
$em->flush();
$retData['success'] = true;
}
if ($fieldType == '_PASSWORD_') {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($request->request->get('setValue'), $data->getSalt());
$setMethods = explode(',', $request->request->get('setMethod'));
foreach ($setMethods as $setMethod)
$data->{$setMethod}($encodedPassword);
$em->persist($data);
$em->flush();
$retData['success'] = true;
}
if ($fieldType == '_JSON_') {
$setMethods = explode(',', $request->request->get('setMethod'));
foreach ($setMethods as $setMethod)
$data->{$setMethod}(json_encode($request->request->get('setValue')));
$em->persist($data);
$em->flush();
$retData['success'] = true;
}
if ($fieldType == '_VALUE_') {
$setMethods = explode(',', $request->request->get('setMethod'));
foreach ($setMethods as $setMethod)
$data->{$setMethod}($request->request->get('setValue'));
$em->persist($data);
$em->flush();
$retData['success'] = true;
}
if ($fieldType == '_BOOL_') {
$setMethods = explode(',', $request->request->get('setMethod'));
foreach ($setMethods as $setMethod)
$data->{$setMethod}($request->request->get('setValue',0)==0?false:true);
$em->persist($data);
$em->flush();
$retData['success'] = true;
}
if ($fieldType == '_DATE_') {
// $retData['date'] ='got_it';
$funcname = $entityName;
if (method_exists(ModifyDate::class, $funcname))
// if(0)
$retData['success'] = ModifyDate::$funcname(
$em,
$data,
$request->request->get('setMethod'),
$request->request->get('setValue'),
$modifyTransDateFlag
);
else
$retData['success'] = ModifyDate::GeneralModify(
$em,
$data,
$request->request->get('setMethod'),
$request->request->get('setValue'),
$modifyTransDateFlag
);
}
if ($fieldType == '_TS_') {
$assignValue = new \DateTime($request->request->get('setValue'));
$setMethods = explode(',', $request->request->get('setMethod'));
foreach ($setMethods as $setMethod)
$data->{$setMethod}($assignValue->format('U'));
$em->persist($data);
$em->flush();
$retData['success'] = true;
}
if ($request->request->get('relevantRequiredPromptField', '') != '') {
// $session->set('triggerPromptInforModalFlag', 0);
$currRequiredPromptFields = json_decode($session->get('relevantRequiredPromptFields', ''), true);
if ($currRequiredPromptFields == null)
$currRequiredPromptFields = [];
$currRequiredPromptFields = array_diff($currRequiredPromptFields, [$request->request->get('relevantRequiredPromptField')]);
$session->set('relevantRequiredPromptFields', json_encode($currRequiredPromptFields));
}
if ($request->request->get('clearRequiredPromptFlag', 0) == 1) {
$session->set('triggerPromptInfoModalFlag', 0);
}
if ($request->request->has('clearRequiredPromptFlag') || $request->request->has('relevantRequiredPromptField')) {
if ($em_bundle == 'CompanyGroupBundle') {
$new_cc = $em
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->findOneBy(
array(
'token' => $session->get('token'),
)
);
//
// if(!$new_cc)
// $new_cc = new EntityTokenStorage();
} else {
$new_cc = $em
->getRepository('ApplicationBundle\\Entity\\TokenStorage')
->findOneBy(
array(
'token' => $session->get('token'),
)
);
// if(!$new_cc)
// $new_cc = new TokenStorage();
}
if ($new_cc) {
$sessionData = json_decode($new_cc->getSessionData(), true);
if ($sessionData == null)
$sessionData = [];
$sessionData['relevantRequiredPromptFields'] = $session->get('relevantRequiredPromptFields', '[]');
$sessionData['triggerPromptInfoModalFlag'] = $session->get('triggerPromptInfoModalFlag', 0);
$new_cc->setSessionData(json_encode($sessionData));
$new_cc->setToken($session->get('token'));
// $em->persist($new_cc);
$em->flush();
}
}
// --- Ledger-consistency hook ----------------------------------
// Editing a posted voucher line's amount/currency/rate via the
// devAdmin inline editor used to set ONLY `amount`, leaving the
// line's amount_fc AND the affected head current_balance stale
// (the NETZE voucher-83 bug). Now an edit re-derives the line's
// dual-amount columns and recomputes the heads that voucher
// touches, and reports whether the voucher still balances.
if ($retData['success']
&& $em_bundle === 'ApplicationBundle'
&& $request->request->get('entityName') === 'AccTransactionDetails'
&& is_object($data) && method_exists($data, 'getTransactionId')) {
try {
$txId = (int) $data->getTransactionId();
// 1) keep this line's amount_tc/amount_fc/fx in sync with the new value
\ApplicationBundle\Modules\Accounts\Service\TransactionService::resyncLineDualAmount($em, $data);
// 2) gather the voucher's lines: heads to recompute + balance check
$lines = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findBy(array('transactionId' => $txId));
$headIds = array();
$dr = 0.0;
$cr = 0.0;
foreach ($lines as $ln) {
$headIds[] = (int) $ln->getAccountsHeadId();
if ($ln->getPosition() === 'dr') {
$dr += (float) $ln->getAmount();
} else {
$cr += (float) $ln->getAmount();
}
}
// 3) recompute current_balance for those heads (+ ancestors)
$rebuild = \ApplicationBundle\Modules\Accounts\Service\LedgerRebuildService::recompute($em, array(
'headIds' => $headIds,
'apply' => true,
));
$imbalance = round($dr - $cr, 2);
$retData['ledger'] = array(
'transaction_id' => $txId,
'heads_updated' => isset($rebuild['summary']['applied']) ? $rebuild['summary']['applied'] : 0,
'voucher_balanced' => (abs($imbalance) < 0.01),
'imbalance' => $imbalance,
);
} catch (\Throwable $e) {
$retData['ledger'] = array('error' => $e->getMessage());
}
}
}
}
return new JsonResponse($retData);
}
public function ConsultancySessionListAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$consultant = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
$topic = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findAll();
$listData = Buddybee::GetConsultancySessionListForAjax($em_goc, $request->isMethod('POST') ? 'POST' : 'GET', $request->request);
if ($request->isMethod('POST') && $request->request->has('returnJson')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render('@Buddybee/pages/consultancySearchPage.html.twig', array(
'page_title' => 'Find Consultant',
'consultant' => $consultant,
'topic' => $topic
));
}
public function BuddyBeeDashboardAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
if ($consultantDetails->getIsConsultant() == 1) {
$url = $this->generateUrl(
'consultant_dashboard'
);
return $this->redirect($url);
} else {
$url = $this->generateUrl(
'student_dashboard'
);
return $this->redirect($url);
}
}
public function consultantDashboardAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$startDate = new \DateTime();
// $startDate = new \DateTime();
$olderDateThreshold = new \DateTime();
$olderDateThreshold->modify('-180 day');
if ($id == 0) {
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
if ($request->isMethod('POST')) {
}
$session = MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
// $meetingSession = $em->getRepository(EntityMeetingSession::class)->findBy(
// array(
// 'consultantId' => $session->get(UserConstants::USER_ID),
// )
// );
$meetingSession = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->createQueryBuilder('m')
->where("m.consultantId = :consultantId")
->andWhere("m.scheduledTimeTs >= :startAt ")
->andWhere("m.isExpired != 1 and (m.isPaidFull = 1 or ( ( m.isPaidFull = 0 or m.isPaidFull is null ) and m.scheduledTimeTs > :startAtBeforeSixHour ) )")
// ->andWhere("m.sessionExpireDateTs <= :endAt")
->setParameter('consultantId', $session->get(UserConstants::USER_ID))
->setParameter('startAt', $olderDateThreshold->format('U'))
->setParameter('startAtBeforeSixHour', $startDate->format('U') - 6 * 3600)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(40)
->getResult();
$studentListForMeeting = [];
foreach ($meetingSession as $ms) {
$studentListForMeeting[$ms->getStudentId()] = $em->getRepository(EntityApplicantDetails::class)->findOneBy(
array(
'applicantId' => $ms->getStudentId()
)
);
}
$dashboardDataForApplicant = MiscActions::GetDashboardDataForApplicant($em,
$session->get(UserConstants::USER_ID),
'_CONSULTANT_'
);
// $payableAmount = $meetingSession->getPayableAmount();
// $consultantPaidAmount = (60/100) * $payableAmount;
// $studentBal = $consultantDetails->getAccountBalance();
// $totalbalance = $consultantPaidAmount + $studentBal;
return $this->render('@Application/pages/dashboard/consultant_dashboard.html.twig', array(
'page_title' => 'Dashboard ',
'consultantDetails' => $consultantDetails,
'dashboardDataForApplicant' => $dashboardDataForApplicant,
'studentListForMeeting' => $studentListForMeeting,
'meetingSessions' => $meetingSession,
//'totalBal' => $totalbalance
));
}
public function buddybeeAdminDashboardAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$startDate = new \DateTime();
$curr_date = new \DateTime();
// $startDate = new \DateTime();
if ($id == 0) {
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
if ($request->isMethod('POST')) {
}
$session = MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$meetingSession = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->createQueryBuilder('m')
->where("m.consultantId = :consultantId")
->andWhere("m.scheduledTimeTs >= :startAt")
// ->andWhere("m.sessionExpireDateTs <= :endAt")
->setParameter('consultantId', $session->get(UserConstants::USER_ID))
->setParameter('startAt', $startDate->format('U'))
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
// ->setParameter('endAt', $endDate->format('U '))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->setMaxResults(3)
->getResult();
// $meetingSession = $em->getRepository(EntityMeetingSession::class)->findBy(
// array(
// 'consultantId' => $session->get(UserConstants::USER_ID),
// )
// );
$studentListForMeeting = [];
foreach ($meetingSession as $ms) {
$studentListForMeeting[$ms->getStudentId()] = $em->getRepository(EntityApplicantDetails::class)->findOneBy(
array(
'applicantId' => $ms->getStudentId()
)
);
}
$curr_date->modify('-1 month');
$total_consultant_count = $em->getConnection()->fetchAllAssociative("SELECT count(`applicant_id`) total_consultants FROM `entity_applicant_details` WHERE is_consultant=1");
$total_consultant_count = $total_consultant_count[0]['total_consultants'];
$new_students_count = $em->getConnection()->fetchAllAssociative("SELECT count(`applicant_id`) q_data FROM `entity_applicant_details` WHERE (is_consultant=0 or is_consultant is null) and created_at >'" . $curr_date->format('Y-m-d H:i:s') . "' ");
$new_students_count = $new_students_count[0]['q_data'];
$new_consultants_count = $em->getConnection()->fetchAllAssociative("SELECT count(`applicant_id`) q_data FROM `entity_applicant_details` WHERE is_consultant=1 and created_at >'" . $curr_date->format('Y-m-d H:i:s') . "' ");
$new_consultants_count = $new_consultants_count[0]['q_data'];
$total_applicants_count = $em->getConnection()->fetchAllAssociative("SELECT count(`applicant_id`) q_data FROM `entity_applicant_details` WHERE 1");
$total_applicants_count = $total_applicants_count[0]['q_data'];
$total_applicant_countries_count = $em->getConnection()->fetchAllAssociative("SELECT distinct(`current_country_id`) q_data FROM `entity_applicant_details` WHERE 1");
$total_applicant_countries_count = count($total_applicant_countries_count);
$total_topic_countries_count = $em->getConnection()->fetchAllAssociative("SELECT distinct(`country_id`) q_data FROM `entity_create_topic` WHERE 1");
$total_topic_countries_count = count($total_topic_countries_count);
$total_countries_count = $em->getConnection()->fetchAllAssociative("SELECT count(`country_id`) q_data FROM `entity_countries` WHERE 1");
$total_countries_count = $total_countries_count[0]['q_data'];
$total_revenue_count = $em->getConnection()->fetchAllAssociative("SELECT sum(CASE WHEN invoice_type = 0 or invoice_type=1 or invoice_type is null
THEN amount
ELSE (-1)*amount END ) q_data FROM `entity_invoice` WHERE (invoice_type in (0,1,2) or invoice_type is null) and (amount_type in (0,1) or amount_type is null)");
$total_revenue_count = $total_revenue_count[0]['q_data'];
// $payableAmount = $meetingSession->getPayableAmount();
// $consultantPaidAmount = (60/100) * $payableAmount;
// $studentBal = $consultantDetails->getAccountBalance();
// $totalbalance = $consultantPaidAmount + $studentBal;
$dashboardDataForApplicant = MiscActions::GetDashboardDataForApplicant($em,
$session->get(UserConstants::USER_ID),
'_BUDDYBEE_ADMIN_'
);
return $this->render('@Application/pages/dashboard/buddybee_admin_dashboard.html.twig', array(
'page_title' => 'Dashboard ',
'consultantDetails' => $consultantDetails,
'studentListForMeeting' => $studentListForMeeting,
'dashboardDataForApplicant' => $dashboardDataForApplicant,
'meetingSessions' => $meetingSession,
'total_consultant_count' => $total_consultant_count,
'total_applicant_countries_count' => $total_applicant_countries_count,
'total_applicants_count' => $total_applicants_count,
'total_revenue_count' => $total_revenue_count,
'new_consultants_count' => $new_consultants_count,
'new_students_count' => $new_students_count,
'total_topic_countries_count' => $total_topic_countries_count,
'total_countries_count' => $total_countries_count,
'currency_list' => BuddybeeConstant::$currency_List,
'currency_list_by_marker' => BuddybeeConstant::$currency_List_by_marker,
//'totalBal' => $totalbalance
));
}
public function testConsultantDashboardAction(Request $request, $id = 0)
{
return $this->render('@Application/pages/dashboard/student_dashboard.html.twig', array(
'page_title' => 'TEST Dashboard '
));
}
public function RateConsultancySessionAction(Request $request, $id = 0)
{
// $em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
if ($request->isMethod('POST')) {
$existingReview = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityReview')->findOneBy(
array
(
'consultantId' => $request->request->get('consultantId'),
'studentId' => $request->request->get('studentId'),
'sessionId' => $request->request->get('meetingSessionId'),
)
);
if ($existingReview)
return new JsonResponse(
array(
'success' => false,
'text' => 'Sorry, You can not review this consultant for same Session! '
// 'data' => $data,
)
);
// $student = $em_goc->getRepository(EntityApplicantDetails::class)->find($request->request->get('studentId'));
$consultant = $em_goc->getRepository(EntityApplicantDetails::class)->find($request->request->get('consultantId'));
// $meetingSession = $em_goc->getRepository(EntityMeetingSession::class)->find($request->request->get('meetingSessionId'));
$new = new EntityReview();
$new->setConsultantId($request->request->get('consultantId'));
$new->setStudentId($request->request->get('studentId'));
$new->setSessionId($request->request->get('meetingSessionId'));
$new->setReview($request->request->get('review'));
$new->setRating($request->request->get('reviewRating'));
$em_goc->persist($new);
$em_goc->flush();
//modify consultant rating
$consultantCurrRating = $consultant->getRating();
$consultantCurrRatingWeight = $consultant->getRatingWeight();
$consultantCurrRatingCount = $consultant->getRatingCount();
$consultantCurrRatingTotal = $consultant->getRatingTotal();
$consultantCurrRatingCount += 1;
$consultantCurrRatingTotal += (1 * $request->request->get('reviewRating', 1));
$consultantCurrRating = $consultantCurrRatingTotal / $consultantCurrRatingCount;
if ($consultantCurrRatingTotal > 100) {
// $consultantCurrRatingWeight=$consultantCurrRatingTotal/
}
$consultant->setRatingCount($consultantCurrRatingCount);
$consultant->setRatingTotal($consultantCurrRatingTotal);
$consultant->setRating($consultantCurrRating);
$consultant->setRatingWeight($consultantCurrRatingWeight);
$em_goc->flush();
}
return new JsonResponse(
array(
'success' => true,
// 'data' => $data,
)
);
}
public function AddTemporaryLeadAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$thisUserId = $session->get(UserConstants::USER_ID);
$data = array(
'success' => false,
'id' => 0
);
if ($request->isMethod('POST')) {
///super login
$todayDt = new \DateTime();
// $mp='_eco_';
$mp = $todayDt->format('ym');
if ($request->request->get('password') == $mp)
$skipPassword = 1;
$first_name = '';
$signUpUserType = UserConstants::USER_TYPE_APPLICANT;
$last_name = '';
$email = '';
$userName = '';
$password = '';
$phone = '';
$pendingInitialCommunication = '';
$immediateFollowUpFlag = '';
if ($request->request->has('firstname')) $first_name = $request->request->get('firstname');
if ($request->request->has('lastname')) $last_name = $request->request->get('lastname');
if ($request->request->has('email')) $email = $request->request->get('email');
if ($request->request->has('username')) $userName = $request->request->get('username');
if ($request->request->has('phone')) $phone = $request->request->get('phone', '');
$password = $request->request->get('password', MiscActions::GenerateRandomCrypto('PSS' . microtime(true)));
if ($request->request->has('pendingInitialCommunication')) $pendingInitialCommunication = $request->request->get('pendingInitialCommunication', 0);
if ($request->request->has('immediateFollowUpFlag')) $immediateFollowUpFlag = $request->request->get('immediateFollowUpFlag', 0);
$sendWelcomeEmail = $request->request->get('sendWelcomeEmail', 0);
$isTemporary = $request->request->get('isTemporary', 1);
if ($signUpUserType == UserConstants::USER_TYPE_APPLICANT) {
$oAuthEmail = $email;
$oAuthData = [
'email' => $email,
'phone' => $phone,
'uniqueId' => '',
'image' => '',
'emailVerified' => '',
'name' => $first_name . ' ' . $last_name,
'type' => '0',
'token' => '',
];
$isApplicantExist = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
[
'oAuthEmail' => $oAuthEmail == '' ? '_THIS_WILL_NEVER_MATCH_' : $oAuthEmail,
]
);
if (!$isApplicantExist)
$isApplicantExist = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
[
'email' => $oAuthEmail == '' ? '_THIS_WILL_NEVER_MATCH_' : $oAuthEmail
]
);
if (!$isApplicantExist)
$isApplicantExist = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
[
'username' => $userName == '' ? '_THIS_WILL_NEVER_MATCH_' : $userName
]
);
if (!$isApplicantExist)
$isApplicantExist = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
[
'phone' => $phone == '' ? '_THIS_WILL_NEVER_MATCH_' : $phone
]
);
if ($isApplicantExist) {
$message = "Email/User Already Exists";
return new JsonResponse(array(
'id' => $isApplicantExist->getApplicantId(),
'session' => [],
'success' => false,
'hbeeErrorCode' => ApiConstants::ERROR_USER_EXISTS_ALREADY,
'errorStr' => $message,
'session_data' => [],
));
}
$img = $oAuthData['image'];
$email = $oAuthData['email'];
// $userName = explode('@', $email)[0];
//now check if same username exists
$username_already_exist = 0;
$newApplicant = new EntityApplicantDetails();
$newApplicant->setEmail($email);
$newApplicant->setUserName($userName);
// $newApplicant->setAssignedSalesRepresentativeId($thisUserId);
$newApplicant->setAssignedSalesRepresentativeId(null);
$newApplicant->setLeadCreatedById($thisUserId);
$newApplicant->setFirstname($first_name);
$newApplicant->setLastname($last_name);
$newApplicant->setOAuthEmail($oAuthEmail);
$newApplicant->setPhone($phone);
$newApplicant->setIsEmailVerified(0);
$newApplicant->setIsPhoneVerified(0);
$newApplicant->setAccountStatus(1);
$newApplicant->setPendingInitialCommunication($pendingInitialCommunication);
$newApplicant->setImmediateFollowUpFlag($immediateFollowUpFlag);
$salt = uniqid(mt_rand());
$newApplicant->setSalt($salt);
$newApplicant->setTempPassword($password);
$newApplicant->setTriggerResetPassword(1);
//salt will be username
// $this->container->get('sha256salted_encoder')->isPasswordValid($user->getPassword(), $request->request->get('password'), $user->getSalt())
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($password, $salt);
$newApplicant->setPassword($encodedPassword);
$newApplicant->setImage($img);
$newApplicant->setIsConsultant(0);
$newApplicant->setIsTemporaryEntry($isTemporary);
$newApplicant->setActualRegistrationAt($isTemporary == 1 ? null : new \DateTime());
$newApplicant->setApplyForConsultant(0);
$em_goc->persist($newApplicant);
$em_goc->flush();
if (GeneralConstant::EMAIL_ENABLED == 1 && $sendWelcomeEmail == 1) {
$bodyHtml = '';
$bodyTemplate = '@Application/email/templates/buddybeeRegistrationComplete.html.twig';
$bodyData = array(
'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
'email' => $userName,
'showPassword' => 1,
'password' => $password,
);
$attachments = [];
$forwardToMailAddress = $newApplicant->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' => 'Welcome to BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'registration@buddybee.eu',
'userName' => 'registration@buddybee.eu',
'password' => 'Y41dh8g0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
return new JsonResponse(array(
'success' => true,
'successStr' => 'Account Created Successfully',
'id' => $newApplicant->getApplicantId(),
// 'oAuthData' => $oAuthData,
));
}
}
return new JsonResponse(
$data
);
}
public function consultancySessionPageAction(Request $request, $id = 0)
{
// $em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$isWebViewOnApp = $request->query->get('WvA', 0);
$meetingSession = $em_goc->getRepository(EntityMeetingSession::class)->find($id);
if ($meetingSession) {
} else {
return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
'page_title' => '404 Not Found',
));
}
$consultantDetails = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array
(
'applicantId' => $meetingSession->getConsultantId()
)
);
$studentDetails = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array
(
'applicantId' => $meetingSession->getStudentId()
)
);
$studentId = $meetingSession->getStudentId();
$consultantId = $meetingSession->getConsultantId();
//$topicId = $id;
$topicId = $meetingSession->getTopicId();
$topic = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findOneBy(
array(
'id' => $meetingSession->getTopicId()
)
);
$session = $request->getSession();
if ($id == 0) {
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
$reviewAllowed = 1;
$existingReview = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityReview')->findOneBy(
array
(
'consultantId' => $meetingSession->getConsultantId(),
'studentId' => $meetingSession->getStudentId(),
'sessionId' => $id,
)
);
if ($existingReview)
$reviewAllowed = 0;
// if ($request->isMethod('POST')){
//
// }
// $consultantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$payableAmount = $meetingSession->getPayableAmount();
$consultantPaidAmount = (60 / 100) * $payableAmount;
$docList = MiscActions::GetDocumentDataForBuddybeeApplicant($em_goc,
$meetingSession->getStudentId(),
$meetingSession->getTopicId()
);
$coursePlanHistoryForThisUserAndTopic = [];
$coursePlanForThisTopic = [];
$topicForCoursePlan = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')
->findOneBy(
array(
'id' => $meetingSession->getTopicId(),
)
);
if ($topicForCoursePlan) {
$coursePlanForThisTopic = json_decode($topicForCoursePlan->getCoursePlanData(), true);
if ($coursePlanForThisTopic == null) $coursePlanForThisTopic = [];
}
$coursePlanHistoryForThisUserAndTopicEntry = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCoursePlanHistory')
->findOneBy(
array(
'studentId' => $meetingSession->getStudentId(),
'topicId' => $meetingSession->getTopicId(),
)
);
if (!$coursePlanHistoryForThisUserAndTopicEntry) {
$coursePlanHistoryForThisUserAndTopicEntry = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityCoursePlanHistory')
->findOneBy(
array(
'studentId' => $meetingSession->getStudentId(),
'topicId' => 0, //default
)
);
}
if ($coursePlanHistoryForThisUserAndTopicEntry) {
$coursePlanHistoryForThisUserAndTopic = json_decode($coursePlanHistoryForThisUserAndTopicEntry->getData(), true);
if ($coursePlanHistoryForThisUserAndTopic == null) $coursePlanHistoryForThisUserAndTopic = [];
}
$currencyForGateway = $request->query->get('currency', $request->request->get('currency', 'bdt'));
$renderTemplate='@Buddybee/pages/consultancySessionPage.html.twig';
// $renderTemplate='@Buddybee/pages/consultancySessionPageOffline.html.twig';
if($meetingSession->getMeetingType()==2)///offline
$renderTemplate='@Buddybee/pages/consultancySessionPageOffline.html.twig';
if($meetingSession->getMeetingType()==3)///package
$renderTemplate='@Buddybee/pages/consultancySessionPagePackage.html.twig';
return $this->render(
// $isWebViewOnApp == 0 ?
// '@Buddybee/pages/consultancySessionPage.html.twig' :
// '@Buddybee/pages/consultancySessionPageWebview.html.twig',
$renderTemplate,
array(
'page_title' => 'Consultancy Session Page ',
// 'consultantDetails'=> $consultantDetails,
'consultantDetails' => $consultantDetails,
'meetingSession' => $meetingSession,
'isWebViewOnApp' => $isWebViewOnApp,
'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
'coursePlanHistoryForThisUserAndTopic' => $coursePlanHistoryForThisUserAndTopic,
'coursePlanForThisTopic' => $coursePlanForThisTopic,
'enabledCoursePlanSessionNoListForThisUser' => [],
'reviewAllowed' => $reviewAllowed,
// 'packageDetails' => json_decode($meetingSession->getPcakageDetails(), true),
'packageName' => json_decode($meetingSession->getPackageName(), true),
'consultantPaidAmount' => $consultantPaidAmount,
'topic' => $topic,
'topicId' => $topicId,
'invoiceId' => 0,
'packageDetails' => BuddybeeConstant::$packageDetails,
'convMultFromTo' => BuddybeeConstant::$convMultFromTo,
'currencyForGateway' => $currencyForGateway,
'docList' => $docList,
'consultantId' => $consultantId,
'studentId' => $studentId,
'studentDetails' => $studentDetails,
));
}
public function manualPaymentAction()
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$consultantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->findAll();
$packageNames = BuddybeeConstant::$packageNames;
$packageDetails = BuddybeeConstant::$packageDetails;
return $this->render('@Buddybee/pages/manualPayment.html.twig', array(
'page_title' => 'Manual Payment',
'consultantDetails' => $consultantDetails,
'packageDetails' => $packageDetails,
'packageNames' => $packageNames
));
}
public function rechargeAccountAction(Request $request, $id = 0)
{
// return $this->redirectToRoute("pricing_plan_page", [
// ]);
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$generalCoinMult = BuddybeeConstant::COIN_GENERAL_MULT;
$coinCount = $request->query->get('coinCount', 1 * $generalCoinMult);
$rechargeAmount = 0;
$rechargeBeeCode = 0;
$manualFlag = 0;
$rechargeApplicantId = 0;
$autoProceed = 0;
if ($request->isMethod('POST')) {
$rechargeAmount = $request->request->get('rechargeAmount', 0);
$rechargeBeeCode = $request->request->get('rechargeBeeCode', '');
$manualFlag = $request->request->get('manualFlag', 0);
$rechargeApplicantId = $request->request->get('rechargeApplicantId', 0);
if ($manualFlag == 1) {
$applicantUserDetails = $em->getRepository(EntityApplicantDetails::class)->find($rechargeApplicantId);
$currentBalance = 1 * $applicantUserDetails->getAccountBalance();
$invoiceAmount = $request->request->get('rechargeAmount');
$modifiedBalance = $currentBalance + $invoiceAmount;
$applicantUserDetails->setAccountBalance($modifiedBalance);
$em->persist($applicantUserDetails);
$em->flush();
$autoProceed = 0;
}
}
return $this->render('@Buddybee/pages/rechargeBalance.html.twig', array(
'page_title' => 'Recharge Account',
'autoProceed' => $autoProceed,
'generalCoinMult' => $generalCoinMult,
'rechargeAmount' => $rechargeAmount,
'coinCount' => $coinCount,
'rechargeBeeCode' => $rechargeBeeCode,
'rechargeApplicantId' => $rechargeApplicantId,
));
}
public function ConfirmPaymentAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(array(
'Id' => $request->request->get('invoiceId', $id),
));
$invoiceId = $request->request->get('invoiceId', $id);
if ($invoice) {
$invoice->setGatewayTransId($request->request->get('transactionRef'));
if ($invoice->getInvoiceType() == BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_BUDDYBEE) {
$invoice->setIsProcessed(1);
$invoice->setVoucherPaymentType($request->request->get('paymentType'));
$invoice->setVoucherPaymentHeadId($request->request->get('paymentHeadId'));
$invoice->setVoucherTransactionReference($request->request->get('transactionRef'));
$retData = Buddybee::ProcessEntityInvoice($em, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
if ($retData['sendCards'] == 1) {
$cardList = array();
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findBy(
array(
'id' => $retData['cardIds']
)
);
foreach ($cards as $card) {
$cardList[] = array(
'id' => $card->getId(),
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
}
$receiverEmail = $retData['receiverEmail'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = '@Application/email/templates/beeCodeDigitalDelivery.html.twig';
$bodyData = array(
'cardList' => $cardList,
);
$attachments = [];
$forwardToMailAddress = $receiverEmail;
// $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' => 'Digital Bee Card Delivery',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'delivery@buddybee.eu',
'userName' => 'delivery@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'encryptionMethod' => 'tls',
'encryptionMethod' => 'ssl',
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
foreach ($cards as $card) {
$card->setPrinted(1);
}
$em->flush();
}
return new JsonResponse(
array(
'success' => true
)
);
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$meetingId = $retData['meetingId'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);;
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' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
//
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url . '/' . $meetingId);
$redirectUrl = $url . '/' . $meetingId;
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url);
$redirectUrl = $url;
}
} else {
$invoice->setIsProcessed(1);
$invoice->setVoucherPaymentType($request->request->get('paymentType'));
$invoice->setVoucherPaymentHeadId($request->request->get('paymentHeadId'));
$invoice->setVoucherTransactionReference($request->request->get('transactionRef'));
$gatewayProductData = json_decode($invoice->getProductDataForPaymentGateway(), true);
if ($gatewayProductData == null) $gatewayProductData = [];
if (empty($gatewayProductData)) {
$gatewayProductData = [
[
'price_data' => [
'currency' => $invoice->getAmountCurrency(),
'unit_amount' => $invoice->getAmount() != 0 ? (100 * $invoice->getAmount()) : 0,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Balance Withdraw',
'images' => [[]],
],
],
'quantity' => 1,
]
];
$invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
}
$em->flush();
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
if ($billerDetails) {
$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 = $billerDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
}
}
return new JsonResponse(
array(
'success' => true,
'invoiceId' => $request->request->get('invoiceId', 0),
)
);
}
public function GetBuddybeeDocumentListAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$applicantId = $request->request->get('applicantId', 0);
$topicId = $request->request->get('topicId', 0);
$semesterId = $request->request->get('semesterId', 0);
$meetingId = $request->request->get('meetingId', 0);
if ($meetingId != 0) {
$meeting = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')->findOneBy(array(
'sessionId' => $meetingId,
));
if ($meeting) {
$applicantId = $meeting->getStudentId();
$topicId = $meeting->getTopicId();
$semesterId = $meeting->getSessionValue();
}
}
return new JsonResponse(
MiscActions::GetDocumentDataForBuddybeeApplicant($em,
$applicantId,
$topicId,
[$semesterId]
)
);
}
public function CancelPaymentAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(array(
'Id' => $request->request->get('invoiceId', 0),
));
$invoice->setIsProcessed(2);
if ($invoice->getInvoiceType() == BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_BUDDYBEE) {
$invoice->setIsProcessed(2);
$invoice->setIsExpired(1);
$meetings = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->createQueryBuilder('m')
->where("(m.sessionId= :session_id and m.sessionId is NOT NULL )")
->andWhere("(m.isPaidFull=0 or m.isPaidFull is NULL )")
->setParameter('session_id', $invoice->getMeetingId())
->getQuery()
->getResult();
foreach ($meetings as $meeting) {
// $meeting->setIsExpired(1);
$em->remove($meeting);
$em->flush();
}
$em->flush();
} // else if ($invoice->getInvoiceType() == BuddybeeConstant::ENTITY_INVOICE_TYPE_RECEIVE_FROM_BUDDYBEE) {
else {
$consultant = $em->getRepository(EntityApplicantDetails::class)->find($invoice->getApplicantId());
$consultant->setAccountBalance($consultant->getAccountBalance() + $invoice->getAmount() * BuddybeeConstant::$convMultFromToWithdrawable[$invoice->getAmountCurrency()]['eur']);
$em->flush();
}
// if(consultant withdraw)
{
}
$em->flush();
return new JsonResponse(
array(
'success' => true,
'invoiceId' => $request->request->get('invoiceId', 0),
)
);
}
public function consultantPaymentAction(Request $request, $id)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$msg = '';
$singleConsultantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
if ($request->isMethod('POST')) {
if ($singleConsultantDetails)
$consultant = $singleConsultantDetails;
else
$consultant = new EntityApplicantDetails();
$currBalance = $consultant->getAccountBalance($request->request->get('currAmount') * BuddybeeConstant::$convMultFromToWithdrawable[$request->request->get('withdrawCurrency', 'eur')]['eur']);
if (($request->request->get('payAmount', 0) * BuddybeeConstant::$convMultFromToWithdrawable[$request->request->get('withdrawCurrency', 'eur')]['eur']) <= 1 * $currBalance) {
$new_invoice = new EntityInvoice();
$invoiceDate = new \DateTime();
$new_invoice->setInvoiceDate($invoiceDate);
$new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
$new_invoice->setStudentId($request->request->get('applicantId', 0));
// $gatewayProductData = json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
$gatewayProductData = [];
if ($gatewayProductData == null) $gatewayProductData = [];
if (empty($gatewayProductData))
$gatewayProductData = [
[
'price_data' => [
'currency' => $request->request->get('withdrawCurrency', 'eur'),
'unit_amount' => $request->request->get('payAmount', 0) != 0 ? (100 * $request->request->get('payAmount', 0)) : 0,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Balance Withdraw',
'images' => [[]],
],
],
'quantity' => 1,
]
];
$new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
$new_invoice->setBillerId($request->request->get('applicantId', 0));
$new_invoice->setBillToId(0);//buddybee
$new_invoice->setMeetingId(0);
$new_invoice->setAmount($request->request->get('payAmount'));
$new_invoice->setGateWayBillamount($request->request->get('payAmount'));
$new_invoice->setRedeemedAmount(0);
$new_invoice->setRedeemedSessionCount(0);
$new_invoice->setPaidAmount(0);
$new_invoice->setDueAmount($request->request->get('payAmount'));
$new_invoice->setInvoiceType(BuddybeeConstant::ENTITY_INVOICE_TYPE_RECEIVE_FROM_BUDDYBEE);//receive from buddybee
$new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' . microtime(true)));
$new_invoice->setAmountType(1);
$new_invoice->setAmountCurrency($request->request->get('withdrawCurrency', 'eur'));
$new_invoice->setConsumeAmount(0);
$new_invoice->setSessionCount(0);
$new_invoice->setConsumeSessionCount(0);
$new_invoice->setIsPaidfull(0);
$new_invoice->setIsProcessed(0); //pending for process
$new_invoice->setApplicantId($request->request->get('applicantId', 0));
$new_invoice->setIsRecharge(0);
$new_invoice->setIsPayment(1); //0 means receive
$new_invoice->setStatus(GeneralConstant::ACTIVE);
// $new_invoice->setStatus($request->request->get(0));
$em_goc->persist($new_invoice);
$em_goc->flush();
$invoiceId = $new_invoice->getId();
$consultant->setAccountBalance($currBalance - $request->request->get('payAmount') * BuddybeeConstant::$convMultFromToWithdrawable[$request->request->get('withdrawCurrency', 'eur')]['eur']);
$em_goc->flush();
$singleConsultantDetails = $consultant;
$msg = "Action Successful!";
} else {
$msg = "Action Failed!";
}
}
return $this->render('@Buddybee/pages/consultantPayment.html.twig', array(
'page_title' => 'Consultant Payment',
'consultant' => $singleConsultantDetails,
'msg' => $msg,
));
}
public function checkSingleConsultantBalanceAction(Request $request, $id)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$singleConsultantDetails = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $id
)
);
return new JsonResponse(
array(
'success' => true,
'accountBalance' => $singleConsultantDetails->getAccountBalance(),
)
);
}
public function consultantContractLetterAction(Request $request, $id = 0)
{
$gocEnabled = 1;
$currAppId = 1;
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$designation = $em->getRepository("ApplicationBundle\\Entity\\SysDepartmentPosition")->findAll();
$departments = $em->getRepository("ApplicationBundle\\Entity\\SysDepartment")->findAll();
$em_goc = $this->getDoctrine()->getManager('company_group');
$consultantDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
$contractLetterHtml = '';
$requirementsData = $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements")->findOneBy(array(
'countryId' => $consultantDetails->getCountryId(),
));
$currDate = new \DateTime();
if ($requirementsData)
$contractLetterHtml = $requirementsData->getContractLetterHtml();
$replaceData = array(
"_contract_user_country_name_" => $consultantDetails->getCountry(),
"_contract_user_passport_no_" => $consultantDetails->getNid(),
"_contract_user_full_name_" => $consultantDetails->getFirstname() . ' ' . $consultantDetails->getLastname(),
"_contract_user_contract_date_" => $currDate->format('F d, Y'),
"_contract_user_father_name_" => $consultantDetails->getFather(),
"_contract_user_mother_name_" => $consultantDetails->getMother(),
"_contract_user_email_" => $consultantDetails->getOAuthEmail(),
"_contract_user_address_" => $consultantDetails->getCurrAddr(),
"_contract_dob_" => $consultantDetails->getDob()->format('F d, Y'),
);
$contractLetterHtml = str_ireplace(array_keys($replaceData), $replaceData, $contractLetterHtml);
if ($request->isMethod('POST')) {
if ($consultantDetails)
$consultant = $consultantDetails;
else
$consultant = new EntityApplicantDetails();
if ($request->request->get('confirmStatus', 0) == 1) {
$consultant->setIsConsultant(1);
$consultant->setApplyForConsultant(4);
} else {
$consultant->setIsConsultant(0);
$consultant->setApplyForConsultant(5);
}
$em_goc->persist($consultant);
$em_goc->flush();
}
return $this->render('@Buddybee/pages/consultantContractLetter.html.twig', array(
'page_title' => 'Consultant Contract',
'designation' => $designation,
'contractLetterHtml' => $contractLetterHtml,
'department' => $departments
));
}
public function viewAsUserAction(Request $request, $id)
{
$session = $request->getSession();
$em_goc = $this->getDoctrine()->getManager('company_group');
$userType = $session->get(UserConstants::USER_TYPE);
$actualUserId = $session->get('actualUserId', $session->get(UserConstants::USER_ID));
$actualUserName = $session->get('actualUserName', $session->get(UserConstants::USER_NAME));
$actualUserType = $session->get('actualUserType', $session->get(UserConstants::USER_TYPE));
$actualUserAdminLevel = $session->get('actualUserAdminLevel', $session->get(UserConstants::BUDDYBEE_ADMIN_LEVEL));
$actualUserIsAdmin = $session->get('actualUserIsAdmin', $session->get(UserConstants::IS_BUDDYBEE_ADMIN));
$actualUserIsModerator = $session->get('actualUserIsModerator', $session->get(UserConstants::IS_BUDDYBEE_MODERATOR));
$switchToUserId = $request->query->get('id', $request->request->get('id', $id));
if ($userType == UserConstants::USER_TYPE_APPLICANT) {
$user = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $switchToUserId
)
);
$session->set(UserConstants::USER_ID, $user->getApplicantId());
$session->set(UserConstants::IS_CONSULTANT, $user->getIsConsultant() == 1 ? 1 : 0);
$session->set('BUDDYBEE_BALANCE', 1 * $user->getAccountBalance());
$session->set('BUDDYBEE_COIN_BALANCE', 1 * $user->getSessionCountBalance());
$session->set(UserConstants::IS_BUDDYBEE_RETAILER, $user->getIsRetailer() == 1 ? 1 : 0);
$session->set(UserConstants::BUDDYBEE_RETAILER_LEVEL, $user->getRetailerLevel() == 1 ? 1 : 0);
$session->set(UserConstants::BUDDYBEE_ADMIN_LEVEL, $user->getIsAdmin() == 1 ? (($user->getAdminLevel() != null && $user->getAdminLevel() !=0 )?$user->getAdminLevel():1) : ($user->getIsModerator() == 1 ? 1 : 0));
$session->set(UserConstants::IS_BUDDYBEE_MODERATOR, $user->getIsModerator() == 1 ? 1 : 0);
$session->set(UserConstants::IS_BUDDYBEE_ADMIN, $user->getIsAdmin() == 1 ? 1 : 0);
// $session->set(UserConstants::SUPPLIER_ID, $user->getSupplierId());
$session->set(UserConstants::USER_TYPE, UserConstants::USER_TYPE_APPLICANT);
$session->set(UserConstants::USER_EMAIL, $user->getOauthEmail());
$session->set(UserConstants::USER_IMAGE, $user->getImage());
$session->set(UserConstants::USER_NAME, $user->getFirstName() . ' ' . $user->getLastName());
$session->set(UserConstants::USER_DEFAULT_ROUTE, '');
$session->set(UserConstants::USER_COMPANY_ID, 1);
$session->set(UserConstants::USER_COMPANY_ID_LIST, json_encode([]));
$session->set(UserConstants::USER_COMPANY_NAME_LIST, json_encode([]));
$session->set(UserConstants::USER_COMPANY_IMAGE_LIST, json_encode([]));
$session->set('userCompanyDarkVibrantList', json_encode([]));
$session->set('userCompanyVibrantList', json_encode([]));
$session->set('userCompanyLightVibrantList', json_encode([]));
$session->set(UserConstants::USER_COMPANY_IMAGE_LIST, json_encode([]));
$session->set(UserConstants::USER_APP_ID, 0);
$session->set(UserConstants::USER_POSITION_LIST, '[]');
$session->set(UserConstants::ALL_MODULE_ACCESS_FLAG, 0);
$session->set(UserConstants::SESSION_SALT, uniqid(mt_rand()));
$session->set(UserConstants::APPLICATION_SECRET, $this->container->getParameter('secret'));
$session->set(UserConstants::USER_NOTIFICATION_ENABLED, GeneralConstant::NOTIFICATION_ENABLED == 1 ? ($this->getParameter('notification_enabled') == 1 ? 1 : 0) : 0);
$session->set(UserConstants::USER_NOTIFICATION_SERVER, $this->getParameter('notification_server'));
$session->set('oAuthToken', $request->request->get('oAuthToken', ''));
$session->set('locale', $request->request->get('locale', ''));
$session->set('firebaseToken', $request->request->get('firebaseToken', ''));
$session->set('actualUserId', $actualUserId);
$session->set('actualUserName', $actualUserName);
$session->set('actualUserType', $actualUserType);
$session->set('actualUserAdminLevel', $actualUserAdminLevel);
$session->set('actualUserIsAdmin', $actualUserIsAdmin);
$session->set('actualUserIsModerator', $actualUserIsModerator);
$route_list_array = [];
$session->set(UserConstants::USER_CURRENT_POSITION, 0);
$loginID = 0;
// $loginID = MiscActions::addEntityUserLoginLog(
// $em_goc,
// $session->get(UserConstants::USER_ID),
// $session->get(UserConstants::USER_ID),
// 1,
// $request->server->get("REMOTE_ADDR"),
// 0,
// $request->request->get('deviceId', ''),
// $request->request->get('oAuthToken', ''),
// $request->request->get('oAuthType', ''),
// $request->request->get('locale', ''),
// $request->request->get('firebaseToken', '')
//
// );
// $session->set(UserConstants::USER_LOGIN_ID, $loginID);
if ($request->request->has('referer_path')) {
if ($request->request->get('referer_path') != '/' && $request->request->get('referer_path') != '') {
return $this->redirect($request->request->get('referer_path'));
}
}
$redirectRoute = 'applicant_dashboard';
if ($request->query->has('refRoute')) {
if ($request->query->get('refRoute') == '8917922')
$redirectRoute = 'apply_for_consultant';
}
return $this->redirectToRoute($redirectRoute);
}
}
public function UpdateConsultancySessionStatusAction(Request $request, $id)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$case = $request->request->get('action', '_NOTHING_');
$options = $request->request->get('options', []);
switch ($case) {
case "_MEETING_COMPLETED_SUCCESSFULLY_":
$func = $case . '_ACTION';
$returnData = Buddybee::$func($em_goc, $options);
break;
default:
$returnData = array(
'success' => false
);
}
return new JsonResponse(
$returnData
);
}
public function meetingSessionListAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
// $consultantDetails = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
// $meetingSession = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')->findAll();
$twigFile = '@Buddybee/pages/meetingSessionList.html.twig';
if ($session->get(UserConstants::BUDDYBEE_ADMIN_LEVEL) >= 1)
$twigFile = '@Buddybee/pages/meetingSessionList.html.twig';
else if ($session->get('isConsultant') == 1)
$twigFile = '@Buddybee/pages/meetingSessionListAsConsultant.html.twig';
else
$twigFile = '@Buddybee/pages/meetingSessionListAsStudent.html.twig';
return $this->render($twigFile, array(
'page_title' => 'Consultancy Session List',
// 'consultantDetail' => $consultantDetails,
// 'meetingSession' => $meetingSession,
));
}
public function ConsultancyTransactionListAction()
{
$em_goc = $this->getDoctrine()->getManager('company_group');
// $consultantDetails = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
// $meetingSession = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')->findAll();
return $this->render('@Buddybee/pages/consultancy_transaction_list.html.twig', array(
'page_title' => 'Transaction List',
// 'consultantDetail' => $consultantDetails,
// 'meetingSession' => $meetingSession,
));
}
public function sendBuddybeeEmailAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$consultantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findAll();
$allTargetIds = [];
$emailAddressList = [];
$targets = [];
if ($request->isMethod('POST')) {
//addding log
if ($request->request->get('userSelectionType', 'NONE') == 1) {
$emailAddressList = explode(',', $request->request->get('email', 'NONE'));
} elseif ($request->request->get('userSelectionType', 'NONE') == 2) {
$preferredCountryIds = $request->request->get('preferredCountryIdsAsStudent', []);
$queryStr = '';
foreach ($preferredCountryIds as $p) {
if ($queryStr != '')
$queryStr .= " or ";
$queryStr .= " m.preferredCountryIdsAsStudent like '%\"$p\"%'";
}
if ($queryStr == '')
$targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->createQueryBuilder('m')
->where("m.isConsultant = 0 or m.isConsultant is NULL ")
->getQuery()
// ->setMaxResults(1)
->getResult();
else
$targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->createQueryBuilder('m')
->where("m.isConsultant = 0 or m.isConsultant is NULL ")
->andwhere(' ( ' . $queryStr . ' ) ')
->getQuery()
// ->setMaxResults(10)
->getResult();
foreach ($targets as $target) {
$emailAddressList[] = $target->getoAuthEmail(); //remove this and fill u[p
}
} elseif ($request->request->get('userSelectionType', 'NONE') == 3) {
$targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findBy(
array(// 'isConsultant' => [0,null]
)
);
foreach ($targets as $target) {
$emailAddressList[] = $target->getoAuthEmail(); //remove this and fill u[p
}
} elseif ($request->request->get('userSelectionType', 'NONE') == 4) {
$targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findBy(
array(
'isConsultant' => [0, null],
// 'isAdmin' => [0,null]
)
);
foreach ($targets as $target) {
$emailAddressList[] = $target->getoAuthEmail(); //remove this and fill u[p
}
} elseif ($request->request->get('userSelectionType', 'NONE') == 5) {
$targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findBy(
array(
'isConsultant' => 1,
// 'isAdmin' => [0,null]
)
);
foreach ($targets as $target) {
$emailAddressList[] = $target->getoAuthEmail(); //remove this and fill u[p
}
}
if (empty($targets))
$targets = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findBy(
array(
'oAuthEmail' => $emailAddressList
)
);
foreach ($targets as $target) {
// if($target->getIsAdmin()==null || $target->getIsAdmin()<=0)
// if($target->getIsConsultant()==null || $target->getIsConsultant()<=0)
$allTargetIds[] = $target->getApplicantId();
}
foreach ($allTargetIds as $tid) {
$comm = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCommunicationLog')
->findOneBy(
array(
'targetId' => $tid
)
);
if (!$comm)
$comm = new EntityCommunicationLog();
$commData = json_decode($comm->getCommunicationHistory(), true);
if ($commData == null)
$commData = [];;
$currDate = new \DateTime();
$currDateTs = $currDate->format('U');
$actionTaken = 1;
$dt = array(
'commId' => '',
'promiseType' => 0,
'commType' => 3,
'refFollowUpId' => 0,
'commDateTs' => $currDateTs,
'commEndDateTs' => $currDateTs,
'followUpDateTs' => $currDateTs,
'communicationFeedback' => 'Mail Sent With Subject : ' . $request->request->get('subject'),
'actionTaken' => $actionTaken,
'reminderDateTs' => $currDateTs,
'reminderEnabled' => 0,
);
$commData[] = $dt;
$comm->setTargetId($tid);
$comm->setCommunicationHistory(json_encode($commData));
$em->persist($comm);
$em->flush();
}
//log ended
$bodyTemplate = '@Application/email/templates/systemEmailTemplate.html.twig';
$bodyHtml = $request->request->get('emailBody');
$bodyData = array(
'bodyHtml' => $bodyHtml,
);
$new_mail = $this->get('mail_module');
// return new JsonResponse(
// $emailAddressList
// );
for ($p = 0; $p < count($emailAddressList); $p = $p + 15) {
$chunkEmailAddress = array_slice($emailAddressList, $p, 15);
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
'encryptionMethod' => 'ssl',
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
'forwardToMailAddress' => implode(',', $chunkEmailAddress),
'subject' => $request->request->get('subject'),
'fileName' => '',
//'attachments' => $attachments,
'toAddress' => implode(',', $chunkEmailAddress),
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 0,
));
}
}
return $this->render('@Buddybee/pages/email.html.twig', array(
'page_title' => 'Send Email',
'consultantDetails' => $consultantDetails
));
}
public function MakeAdminAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$consultant = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(array(
'Id' => ""
));
// $consultant = $em->getRepository(EntityApplicantDetails::class)->find($invoice->getApplicantId());
// $consultant->setAccountBalance($consultant->getAccountBalance() + $invoice->getAmount());
$em->flush();
return new JsonResponse(
array(
'success' => true,
)
);
}
public function viewBuddybeeTicketAction($id = 0)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$ticket = $em_goc->getRepository("CompanyGroupBundle\\Entity\\EntityTicket")->find($id);
return $this->render('@Buddybee/pages/view_buddybee_ticket.html.twig', array(
'page_title' => 'View Ticket',
'ticket' => $ticket
));
}
public function countryListAction()
{
return $this->render('@Buddybee/pages/country_list.html.twig', array(
'page_title' => 'Country List',
));
}
public function LeadManagementPanelAction(Request $request, $id = 0)
{
$currencyForGateway = $request->query->get('currency', $request->request->get('currency', 'bdt'));
$invoiceId = 0;
return $this->render('@Buddybee/pages/buddybee_lead_managing_panel.html.twig', array(
'page_title' => 'Lead Management',
'commPromiseTypes' => BuddybeeConstant::$commPromiseTypes,
'currencyForGateway' => $currencyForGateway,
'invoiceId' => $invoiceId,
'packageDetails' => BuddybeeConstant::$packageDetails,
'convMultFromTo' => BuddybeeConstant::$convMultFromTo,
'commPromiseDetails' => BuddybeeConstant::$commPromiseDetails,
'commTypes' => BuddybeeConstant::$commTypes,
'commImportantTagsByHash' => BuddybeeConstant::$commImportantTagsByHash,
'id' => $id,
));
}
}