<?php
/**
* Created by PhpStorm.
* User: ehsan_pc
* Date: 3/14/2016
* Time: 4:22 PM
*/
namespace ApplicationBundle\Modules\System;
use ApplicationBundle\Constants\ApprovalConstant;
use ApplicationBundle\Constants\BuddybeeConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\HumanResourceConstant;
use ApplicationBundle\Entity\CashFlowProjection;
use ApplicationBundle\Entity\Employee;
use ApplicationBundle\Entity\EmployeeAttendance;
use ApplicationBundle\Helper\Generic;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\Consultancy\Consultancy;
use ApplicationBundle\Modules\HumanResource\HumanResource;
use ApplicationBundle\Modules\User\Users;
use CompanyGroupBundle\Entity\BeeCode;
use CompanyGroupBundle\Entity\ConsultancyAvailability;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use CompanyGroupBundle\Entity\EntityLoginLog;
use CompanyGroupBundle\Entity\EntityPerformanceIndex;
use CompanyGroupBundle\Entity\EntityScheduledNotification;
use CompanyGroupBundle\Entity\EntityTemporaryBooking;
use CompanyGroupBundle\Entity\EntityTicket;
use CompanyGroupBundle\Entity\EntityTokenStorage;
use Symfony\Component\HttpFoundation\JsonResponse;
class MiscActions
{
public static function verifyRecaptchaEnterprise(
string $token,
string $expectedAction,
string $siteKey,
string $projectId,
string $apiKey,
float $minScore = 0.5
)
{
if ($token === '') {
return ['ok' => false, 'reason' => 'missing_token'];
}
$url = "https://recaptchaenterprise.googleapis.com/v1/projects/"
. rawurlencode($projectId)
. "/assessments?key="
. rawurlencode($apiKey);
$payload = [
'event' => [
'token' => $token,
'expectedAction' => $expectedAction,
'siteKey' => $siteKey,
],
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 6,
]);
$raw = curl_exec($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($raw === false || $raw === '' || $httpCode < 200 || $httpCode >= 300) {
return ['ok' => false, 'reason' => 'http_error', 'http' => $httpCode, 'curl' => $err, 'raw' => $raw];
}
$data = json_decode($raw, true);
if (!is_array($data)) {
return ['ok' => false, 'reason' => 'invalid_json', 'raw' => $raw];
}
// --- Important fields in Enterprise response ---
// tokenProperties: { valid, action, hostname, invalidReason }
// riskAnalysis: { score, reasons[] }
$tokenProps = $data['tokenProperties'] ?? [];
$risk = $data['riskAnalysis'] ?? [];
$valid = (bool)($tokenProps['valid'] ?? false);
if (!$valid) {
return [
'ok' => false,
'reason' => 'token_invalid',
'invalidReason' => $tokenProps['invalidReason'] ?? null,
'data' => $data
];
}
$action = (string)($tokenProps['action'] ?? '');
if ($action !== $expectedAction) {
return ['ok' => false, 'reason' => 'action_mismatch', 'action' => $action, 'data' => $data];
}
$score = (float)($risk['score'] ?? 0.0);
if ($score < $minScore) {
return [
'ok' => false,
'reason' => 'low_score',
'score' => $score,
'reasons' => $risk['reasons'] ?? [],
'data' => $data
];
}
return ['ok' => true, 'score' => $score, 'reasons' => $risk['reasons'] ?? [], 'data' => $data];
}
public static function stripGetSetKeys($data)
{
// If object, convert to array first
if (is_object($data)) {
$data = (array)$data;
}
// If not array, return as-is
if (!is_array($data)) {
return $data;
}
$result = [];
foreach ($data as $key => $value) {
// Normalize key: remove get/set prefix
if (is_string($key) && preg_match('/^(get|set)(.+)$/', $key, $matches)) {
$newKey = lcfirst($matches[2]);
} else {
$newKey = $key;
}
// Recursively process nested arrays / objects
$result[$newKey] = self::stripGetSetKeys($value);
}
return $result;
}
public static function autoAttendanceGeneral($em, $empId, $userId, $appId, $dtTs, $options = [], $requestFromMobile = 0, $markerId = HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED)
{
$timeZoneStr = '+0000';
$sysUserId = $userId;
if ($sysUserId == 0)
$sysUserId = $em->getRepository(Employee::class)
->findOneBy(['employeeId' => $empId])->getUserId();
if ($dtTs == 0) {
$currTsTime = new \DateTime();
$dtTs = $currTsTime->format('U');
} else {
$currTsTime = new \DateTime('@' . $dtTs);
}
$today = new \DateTime(date('y-m-d'));
$currTsTime->setTimezone(new \DateTimeZone('UTC'));
$attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' . $timeZoneStr);
$EmployeeAttendance = $em
->getRepository(EmployeeAttendance::class)
->findOneBy(array('employeeId' => $empId, 'date' => $attDate));
if (!$EmployeeAttendance)
$EmployeeAttendance = new EmployeeAttendance;
$attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, ['requestFromMobile' => $requestFromMobile], $EmployeeAttendance, $attDate, $dtTs, $timeZoneStr, $markerId);
if (!isset($dataByAttId[$attendanceInfo->getId()]))
$dataByAttId[$attendanceInfo->getId()] = array(
'attendanceInfo' => $attendanceInfo,
'empId' => $empId,
'lat' => 0,
'lng' => 0,
'address' => 0,
'sysUserId' => $sysUserId,
'companyId' => 1,
'appId' => $appId,
'positionArray' => []
);
$posData = array(
'ts' => $dtTs,
'lat' => 0,
'lng' => 0,
'marker' => $markerId,
'src' => 1,
);
$dataByAttId[$attendanceInfo->getId()]['markerId'] = $markerId;
//this markerId will be calclulted and modified to check if user is in our out of office/workplace later
$dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
$dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
$dataByAttId[$attendanceInfo->getId()]['lat'] = 0; //for last lat lng etc
$dataByAttId[$attendanceInfo->getId()]['lng'] = 0; //for last lat lng etc
if (isset($d['address']))
$dataByAttId[$attendanceInfo->getId()]['address'] = ''; //for last lat lng etc
$response = array(
'success' => true
);
foreach ($dataByAttId as $attInfoId => $d) {
$response = HumanResource::setAttendanceLogFlutterApp($em,
$d['empId'],
$d['sysUserId'],
$d['companyId'],
$d['appId'],
['requestFromMobile' => $requestFromMobile],
$d['attendanceInfo'],
$options,
$d['positionArray'],
$d['lat'],
$d['lng'],
$d['address'],
$d['markerId']
);
}
return $response;
}
public static function updateCompanyToErpServer($em, $appId, $kernel_root_dir)
{
$goc = $em
->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy(array(
'appId' => $appId
));
$returnData = array(
'success' => false,
'message' => "Company Could not be Initialized or Updated",
'data' => [],
'initiated' => 0,
);
if ($goc->getInitiateFlag() == 2 || $goc->getInitiateFlag() == 1) //pending Initiation and paid
{
///NOw pushing to server
$output = '';
$file = $kernel_root_dir . '/../web' . $goc->getImage(); //<-- Path could be relative
if (file_exists($file)) {
// $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
}
$validUptoDt = new \DateTime('@' . $goc->getUsageValidUptoDateTs());
$post_fields = array(
'company_id' => 1,
'goc_id' => $goc->getId(),
'app_id' => $goc->getAppId(),
'dark_vibrant' => '',
'light_vibrant' => '',
'vibrant' => '',
'company_type' => $goc->getCompanyType(),
'company_name' => $goc->getName(),
'address' => $goc->getAddress(),
's_address' => $goc->getShippingAddress(),
'b_address' => $goc->getBillingAddress(),
'company_image' => $goc->getImage(),
'motto' => $goc->getMotto(),
'i_footer' => $goc->getInvoiceFooter(),
'g_footer' => $goc->getGeneralFooter(),
'company_tin' => $goc->getCompanyTin(),
'company_bin' => $goc->getCompanyBin(),
'company_reg' => $goc->getCompanyReg(),
'company_tl' => $goc->getCompanyTl(),
'usage_valid_upto_dt_str' => '@' . $goc->getUsageValidUptoDateTs(),
'usage_valid_upto_ts' => $goc->getUsageValidUptoDateTs(),
// 'sms_enabled' => $goc->getSmsNotificationEnabled(),
// 'sms_settings' => $goc->getSmsSettings(),
'companyGroupHash' => $goc->getCompanyGroupHash(),
'number_of_admin_user' => $goc->getAdminUserAllowed(),
'number_of_user' => $goc->getUserAllowed(),
'db_name' => $goc->getDbName(),
'db_user' => $goc->getDbUser(),
'db_pass' => $goc->getDbPass(),
'db_host' => $goc->getDbHost(),
'companyGroupServerId' => $goc->getCompanyGroupServerId(),
'companyGroupServerAddress' => $goc->getCompanyGroupServerAddress(),
'companyGroupServerHash' => $goc->getCompanyGroupServerHash(),
'companyGroupServerPort' => $goc->getCompanyGroupServerPort(),
'file' => $output
);
$urlToCall = $goc->getCompanyGroupServerAddress() . '/UpdateCompanyGroupDataToRelevantServer';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array(),
CURLOPT_POSTFIELDS => $post_fields
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
if ($errData) {
// $returnData['message']='';
} else {
$response = json_decode($retData, true);
if (isset($response['success']) && $response['success'] === true) {
$returnData['success'] = true;
$returnData['initiated'] = true;
$returnData['message'] = 'Successfully Initialized The Company';
$goc->setInitiateFlag(1);// initiated
$em->flush();
} else {
}
}
}
return $returnData;
}
public static function relayResponseFromCentral()
{
// $urlToCall = $goc->getCompanyGroupServerAddress() . '/UpdateCompanyGroupDataToRelevantServer';
//
// $curl = curl_init();
// curl_setopt_array($curl, array(
// CURLOPT_RETURNTRANSFER => 1,
// CURLOPT_POST => 1,
// CURLOPT_URL => $urlToCall,
// CURLOPT_CONNECTTIMEOUT => 10,
// CURLOPT_SSL_VERIFYPEER => false,
// CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_HTTPHEADER => array(),
// CURLOPT_POSTFIELDS => $post_fields
// ));
//
// $retData = curl_exec($curl);
// $errData = curl_error($curl);
// curl_close($curl);
}
public static function ProcessQrData($em_goc, $em, $data = [])
{
}
public static function encryptTrans($em, $transIds = '_ALL_', $hbeeOnly = 0)
{
$hash = '_DEFAULT_';
// $hbeeOnly=0;
$comp = $em
->getRepository('ApplicationBundle\\Entity\\Company')
->findOneby(array(// 'projectId'=>$projectId
));
if ($comp) {
$hash = $comp->getCompanyHash();
if ($hbeeOnly == 1)
if ($comp->getAppId() != 1)
return 0;
}
if ($hash == null || $hash == '')
$hash = '_DEFAULT_';
if ($transIds == '_ALL_')
$trans = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findby(array(// 'projectId'=>$projectId
));
else
$trans = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findby(array(
'transactionId' => $transIds
));
foreach ($trans as $t) {
$amount = $t->getAmount();
$note = $t->getNote();
$iv = '1234567812345678';
$pass = $hash;
$suffix = '_enpaac_';
if ($amount != null) {
$str = $amount;
$data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
$data = base64_encode($data) . '' . $suffix;
$t->setAmountEncoded($data);
$t->setAmount(null);
$str = $note;
$data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
$data = base64_encode($data) . '' . $suffix;
$t->setNote($data);
}
// $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
$em->flush();
// $iv = '1234567812345678';
// $decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", $approveHash, OPENSSL_RAW_DATA, $iv);
//
// if ($decrypted != false) {
//
// if (!strpos($decrypted, 'YmLRocksLikeABoss'))
// return 0;
//
// return 1;
//
// }
}
}
public static function decryptTrans($em, $transIds = '_ALL_', $hbeeOnly = 0)
{
$hash = '_DEFAULT_';
// $hbeeOnly=0;
$comp = $em
->getRepository('ApplicationBundle\\Entity\\Company')
->findOneby(array(// 'projectId'=>$projectId
));
if ($comp) {
$hash = $comp->getCompanyHash();
if ($hbeeOnly == 1)
if ($comp->getAppId() != 1)
return 0;
}
if ($hash == null || $hash == '')
$hash = '_DEFAULT_';
if ($transIds == '_ALL_')
$trans = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findby(array(// 'projectId'=>$projectId
));
else
$trans = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findby(array(
'transactionId' => $transIds
));
foreach ($trans as $t) {
$amount = $t->getAmountEncoded();
$note = $t->getNote();
$iv = '1234567812345678';
$pass = $hash;
$suffix = '_enpaac_';
if ($amount != null) {
$dt = $amount;
$dt = str_replace($suffix, '', $dt);
$decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
if ($decrypted != false) {
$t->setAmount(1 * $decrypted);
$t->setAmountEncoded(null);
}
$dt = $note;
$dt = str_replace($suffix, '', $dt);
$decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
if ($decrypted != false) $t->setNote($decrypted);
}
$em->flush();
}
}
public static function getStorageIdentifier($options = [
'productId' => 0,
'warehouseId' => 0,
'actionTagId' => 0,
'color' => 0,
'size' => 0,
'batchNo' => '',
'projectId' => 0,
'soId' => 0,
])
{
$str = '_UNSET_';
if (isset($options['productId'])) {
if ($options['productId'] != 0) {
$str = "_P#" . $options['productId'] . "_";//_S#2__C#0__B#889_
if (isset($options['warehouseId'])) {
if ($options['warehouseId'] != 0 && $options['warehouseId'] != '' && $options['warehouseId'] != null)
$str = ($str . "_W#" . $options['warehouseId'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_W#0_");
}
if (isset($options['actionTagId'])) {
if ($options['actionTagId'] != 0 && $options['actionTagId'] != '' && $options['actionTagId'] != null)
$str = ($str . "_V#" . $options['actionTagId'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_V#0_");
}
if (isset($options['color'])) {
if ($options['color'] != 0 && $options['color'] != '' && $options['color'] != null)
$str = ($str . "_C#" . $options['color'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_C#0_");
}
if (isset($options['size'])) {
if ($options['size'] != 0 && $options['size'] != '' && $options['size'] != null)
$str = ($str . "_S#" . $options['size'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_S#0_");
}
if (isset($options['batchNo'])) {
if ($options['batchNo'] != 0 && $options['batchNo'] != '' && $options['batchNo'] != null)
$str = ($str . "_B#" . $options['batchNo'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_B#0_");
}
if (isset($options['projectId'])) {
if ($options['projectId'] != 0 && $options['projectId'] != '' && $options['projectId'] != null)
$str = ($str . "_PRJ#" . $options['projectId'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_PRJ#0_");
}
if (isset($options['soId'])) {
if ($options['soId'] != 0 && $options['soId'] != '' && $options['soId'] != null)
$str = ($str . "_SO#" . $options['soId'] . "_");//_S#2__C#0__B#889_
else
$str = ($str . "_SO#0_");
}
}
} else {
}
return $str;
}
public static function getExpandedDataFromGlobalId($globalIdStr)
{
$id = 0;
$appId = 0;
$entity = 0;
$entityId = 0;
$idType = 'D'; // or _USER_ or _CUSTOMER_ or _SUPPLIER_ or _EMPLOYEE_
$idTypeMarker = '_DOCUMENT_'; // or _USER_ or _CUSTOMER_ or _SUPPLIER_ or _EMPLOYEE_
$idTypeByMarker = array(
'_DOCUMENT_' => 'D',
'_USER_' => 'U',
'_CUSTOMER_' => 'C',
'_SUPPLIER_' => 'S',
'_EMPLOYEE_' => 'E'
);
$idTypeByIdType = array_flip($idTypeByMarker);
$idType = substr("$globalIdStr", 0, 1);
$appId = substr("$globalIdStr", 1, 5);
$entity = substr("$globalIdStr", 6, 2);
$id = substr("$globalIdStr", 8, 8);
$entityId = $id;
$idTypeMarker = isset($idTypeByIdType[$idType]) ? $idTypeByIdType[$idType] : '';
return array(
'id' => $id,
'appId' => $appId,
'idType' => $idType,
'idTypeMarker' => $idTypeMarker,
'entity' => $entity,
'entityId' => $entityId,
);
}
public static function getGlobalIdForRecognition($id = 0,
$appId = 0,
$entity = 0,
$entityId = 0,
$idType = '_DOCUMENT_')
{
$idTypeByMarker = array(
'_DOCUMENT_' => 'D',
'_USER_' => 'U',
'_CUSTOMER_' => 'C',
'_SUPPLIER_' => 'S',
'_EMPLOYEE_' => 'E'
);
$globalIdStr = '';
$globalIdStr = (($idTypeByMarker[$idType]) . (str_pad($appId, 5, '0', STR_PAD_LEFT)) . (str_pad($entity, 2, '0', STR_PAD_LEFT))
. (str_pad($id, 8, '0', STR_PAD_LEFT)));
return $globalIdStr;
}
public static function GenerateRandomCrypto($serialP, $minLength = 0)
{
$cryptoDt = [
0 => 'A',
1 => '9',
2 => '7',
3 => '2',
4 => '4',
5 => '1',
6 => '8',
7 => '5',
8 => '6',
9 => 'C',
];
$serialP .= ('' . strval(rand(1120, 9999)));
$serial = '';
$serialBrokenIntoArray = str_split($serialP);
foreach ($serialBrokenIntoArray as $ser) {
if (isset($cryptoDt[$ser]))
$serial .= $cryptoDt[$ser];
else
$serial .= $ser;
}
$serial = substr($serial, 6, 10);
// $serial .= strval(rand(112, 999));
//
// $serial = substr($serial, 6, 10);
return $serial;
}
public static function addEntityScheduledNotification($em, $data)
{
$cdata = [
'senderHash' => isset($data['senderHash']) ? $data['senderHash'] : '_CUSTOM_',
'bodyTemplate' => isset($data['bodyTemplate']) ? $data['bodyTemplate'] : 'ApplicationBundle:email/scheduled_mail:meeting_schedule_reminder.html.twig',
'bodyData' => isset($data['bodyData']) ? $data['bodyData'] : [],
'subject' => isset($data['subject']) ? $data['subject'] : '',
'emailIds' => isset($data['emailIds']) ? $data['emailIds'] : (isset($data['forwardToMailAddress']) ? [$data['forwardToMailAddress']] : ['eco.buet@gmail.com']),
'companyImagePath' => isset($data['companyImagePath']) ? $data['companyImagePath'] : '',
'forwardToMailAddress' => isset($data['forwardToMailAddress']) ? $data['forwardToMailAddress'] : 'eco.buet@gmail.com',
'encryptionMethod' => 'ssl',
'fromAddress' => isset($data['fromAddress']) ? $data['fromAddress'] : 'no-reply@buddybee.eu',
'userName' => isset($data['userName']) ? $data['userName'] : 'no-reply@buddybee.eu',
'password' => isset($data['password']) ? $data['password'] : 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465
];
// $mailModule=new Email($em,)
$currTime = new \DateTime();
$currTs = $currTime->format('U');
$new = new EntityScheduledNotification();
$new->setData(json_encode($cdata));
$new->setRecurringMin(isset($data['recurringMin']) ? $data['recurringMin'] : 0);
$new->setStartTimeTs(isset($data['startTimeTs']) ? $data['startTimeTs'] : $currTs);
$new->setNextTimeTs(isset($data['nextTimeTs']) ? $data['nextTimeTs'] : $currTs);
$new->setLastTimeTs(isset($data['lastTimeTs']) ? $data['lastTimeTs'] : $currTs);
$new->setCompanyId(isset($data['companyId']) ? $data['companyId'] : 0);
$new->setEnabled(1);
$new->setActionTaken(isset($data['actionTaken']) ? $data['actionTaken'] : 0);
$new->setExpiresTs(isset($data['expiresTs']) ? $data['expiresTs'] : (isset($data['lastTimeTs']) ? $data['lastTimeTs'] : $currTs));
$new->setNotificationType(isset($data['notificationType']) ? $data['notificationType'] : GeneralConstant::NOTIFICATION_TYPE_EMAIL);
$new->setShowAsNotification(isset($data['showAsNotification']) ? $data['showAsNotification'] : 0);
$new->setTitle(isset($data['title']) ? $data['title'] : 0);
$new->setBody(isset($data['body']) ? $data['body'] : 0);
$new->setTargetId(isset($data['targetId']) ? $data['targetId'] : 0);
$new->setEntityMeetingSessionId(isset($data['meetingId']) ? $data['meetingId'] : 0);
$new->setTargetType(isset($data['targetType']) ? $data['targetType'] : 0);
$new->setUserIds(json_encode(isset($data['userIds']) ? $data['userIds'] : []));
$em->persist($new);
$em->flush();
return $new;
}
public static function updateEntityPerformanceIndex($em, $data, $currTime = null)
{
if ($currTime == null)
$currTime = new \DateTime();
$dayMarker = 'D' . $currTime->format('Ymd');
$weekMarker = 'W' . $currTime->format('W');
$monthMarker = 'M' . $currTime->format('Ym');
$yearMarker = 'Y' . $currTime->format('Y');
$markers = [$dayMarker, $weekMarker, $monthMarker, $yearMarker];
$markerTypes = [1, 2, 3, 4];
foreach ($markers as $ind => $marker) {
$markerType = $markerTypes[$ind];
$pi = $em->getRepository('CompanyGroupBundle\\Entity\\EntityPerformanceIndex')->findOneBy(
array(
'targetId' => $data['targetId'],
'targetType' => isset($data['targetType']) ? $data['targetType'] : 3,
'indexType' => $markerType,
'indexMarker' => $marker,
)
);
if (!$pi) {
$pi = new EntityPerformanceIndex();
$pi->setTargetId($data['targetId']);
$pi->setIndexType($markerType);
$pi->setIndexMarker($marker);
$pi->setTargetType(isset($data['targetType']) ? $data['targetType'] : 3);
}
if (isset($data['communicationData'])) {
$pi->setCommunicationCount(1 * $pi->getCommunicationCount() + $data['communicationData']['count']);
$pi->setCommunicationScore(1 * $pi->getCommunicationScore() + $data['communicationData']['score']);
}
if (isset($data['followupData'])) {
$pi->setCommunicationCount(1 * $pi->getFollowupCount() + $data['followupData']['count']);
$pi->setCommunicationScore(1 * $pi->getFollowupScore() + $data['followupData']['score']);
}
if (isset($data['conversionData'])) {
$pi->setConversionCount(1 * $pi->getConversionCount() + $data['conversionData']['count']);
$pi->setConversionScore(1 * $pi->getConversionScore() + $data['conversionData']['score']);
}
if (isset($data['referData'])) {
$pi->setReferCount(1 * $pi->getReferCount() + $data['referData']['count']);
$pi->setReferScore(1 * $pi->getReferScore() + $data['referData']['score']);
}
$em->persist($pi);
$em->flush();
}
return 1;
}
public static function uniqueCombination($in, $minLength = 1, $max = 2000)
{
$count = count($in);
$members = pow(2, $count);
$return = array();
for ($i = 0; $i < $members; $i++) {
$b = sprintf("%0" . $count . "b", $i);
$out = array();
for ($j = 0; $j < $count; $j++) {
$b{$j} == '1' and $out[] = $in[$j];
}
count($out) >= $minLength && count($out) <= $max and $return[] = $out;
}
return $return;
}
public static function GenerateOtp($expireSecond = 180)
{
$data = [];
$success = true;
$expireSecond = 180;
$currTime = new \DateTime();
$expireTime = $currTime->modify('+' . $expireSecond . ' second');
$serial = '';
$cryptoDt = [
0 => 'A',
1 => '9',
2 => '7',
3 => '2',
4 => '4',
5 => '1',
6 => '8',
7 => '5',
8 => '6',
9 => 'C',
];
// $serialP=floor(microtime(true) * 1000);
//
// $serial='';
// $serialBrokenIntoArray=str_split($serialP);
// foreach($serialBrokenIntoArray as $ser)
// {
// if(isset($cryptoDt[$ser]))
// $serial.=$cryptoDt[$ser];
// }
$serial .= strval(rand(1120, 9999));
// $serial=substr($serial,6,10);
return array(
'success' => $success,
'otp' => $serial,
'expireTs' => $expireTime->format('U'),
// 'expireHRT'=>$expireTime->format('d F'),
);
}
public static function GenerateEntityTicket($em, $options, $request)
{
$data = [];
$success = true;
$expDt = new \DateTime();
$currDt = new \DateTime();
$expDt->modify('+1 year');
$expTs = $expDt->format('U');
$ticket = new EntityTicket();
if (empty($options))
$options = array(
'title' => $request->request->get('title', '<no title>'),
'ticketBody' => $request->request->get('ticketBody', '<no body>'),
'replyTo' => $request->request->get('replyTo', null),
'ticketMarkerHash' => $request->request->get('ticketMarkerHash', ''),
'email' => $request->request->get('email', ''),
'phone' => $request->request->get('phone', ''),
'name' => $request->request->get('name', ''),
'preferredContactMethod' => $request->request->get('preferredContactMethod', 1),
'ticketAssignedDate' => $request->request->get('ticketAssignedDate', ''),
'userId' => $request->request->get('userId', 0),
'type' => $request->request->get('type', 90),
'entity' => $request->request->get('entity', ''),
'entityId' => $request->request->get('entityId', ''),
'meetingId' => $request->request->get('meetingId', 0),
'applicantId' => $request->request->get('applicantId', 0),
'expired' => $request->request->get('expired', 0),
'urgency' => $request->request->get('urgency', 1),
'attachments' => $request->request->get('attachments', []),
);
$ticket->setTitle($options['title']);
$ticket->setTicketBody($options['ticketBody']);
$ticket->setReplyTo($options['replyTo']);
$ticket->setTicketMarkerHash($options['ticketMarkerHash']);
$ticket->setEmail($options['email']);
$ticket->setPhone($options['phone']);
$ticket->setName($options['name']);
$ticket->setPreferredContactMethod($options['preferredContactMethod']);
$ticket->setUserId($options['userId']);
$ticket->setType($options['type']);
$ticket->setEntity($options['entity']);
$ticket->setEntityId($options['entityId']);
$ticket->setApplicantId($options['applicantId']);
$ticket->setExpired($options['expired']);
$ticket->setUrgency($options['urgency']);
$ticket->setMeetingId($options['meetingId']);
$ticket->setAttachments(json_encode($options['attachments']));
$ticket->setTicketAssignedDate(new \DateTime($options['ticketAssignedDate']));
$em->persist($ticket);
$em->flush();
$data = array(
'id' => $ticket->getId(),
'ticketEntityObj' => $ticket,
);
return array(
'success' => $success,
'data' => $data,
);
}
public static function GenerateBeeCode($em, $options)
{
$data = [];
$success = true;
$extDt = new \DateTime();
$extDt->modify('+1 year');
$expTs = $extDt->format('U');
for ($c = 0; $c < $options['cardCount']; $c++) {
$serial = $options['serial'];
$pin = $options['pin'];
$useCount = $options['useCount'];
$cryptoDt = [
0 => 'A',
1 => '9',
2 => '7',
3 => '2',
4 => '4',
5 => '1',
6 => '8',
7 => '5',
8 => '6',
9 => 'C',
];
if ($serial == '_AUTO_') {
$serialDt = new \DateTime();
// $serialP=$serialDt->format('U');
$serialP = floor(microtime(true) * 1000);
$serial = '';
$serialBrokenIntoArray = str_split($serialP);
foreach ($serialBrokenIntoArray as $ser) {
if (isset($cryptoDt[$ser]))
$serial .= $cryptoDt[$ser];
}
$serial .= strval(rand(112, 999));
$serial = substr($serial, 6, 10);
}
if ($pin == '_AUTO_') {
$pin = rand(12345, 99999);
$pin = strval($pin);
}
$card = new BeeCode();
$card->setPrinted(0);
$card->setAmount($options['amount']);
$card->setCoinCount($options['coinCount']);
$card->setIsForHardCopy(isset($options['isForHardCopy']) ? $options['isForHardCopy'] : 0);
$card->setRetailerId($options['retailerId']);
$card->setPin($pin);
$card->setSerial($serial);
$card->setIsClaimed(0);
$card->setIsClaimed(0);
$card->setExpireTs($expTs);
$card->setUseCount($useCount);
$em->persist($card);
$em->flush();
$data[] = array(
'id' => $card->getId(),
'cardEntityObj' => $card,
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
}
return array(
'success' => $success,
'data' => $data,
);
}
public static function ClaimBeeCode($em, $options)
{
$data = [
'claimableCoin' => 0,
'claimableAmount' => 0,
'claimedAmount' => 0,
'claimedCoin' => 0,
'cardId' => 0,
'overrideBySystem' => 0,
];
$success = false;
$isClaimable = false;
$claimSuccess = false;
$claimFlag = isset($options['claimFlag']) ? $options['claimFlag'] : 0;
$userId = isset($options['userId']) ? $options['userId'] : 0;
$cardId = isset($options['cardId']) ? $options['cardId'] : 0;
$overrideBySystem = isset($options['overrideBySystem']) ? $options['overrideBySystem'] : 0;
//check 1st
$serial = isset($options['serial']) ? $options['serial'] : '_NONE_';
$pin = isset($options['pin']) ? $options['pin'] : '_NONE_';
if ($overrideBySystem) {
$queryCondition = array(
'id' => $cardId,
);
} else {
if (strlen($pin) == 10) {
$startInd = 2;
$pin = substr($pin, $startInd, 5);
}
if ($cardId != 0) {
$queryCondition = array(
'id' => $cardId,
);
} else {
$queryCondition = array(
'serial' => $serial,
'pin' => $pin,
);
}
}
$card = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findOneBy(
$queryCondition
);
if ($card) {
$cardId = $card->getId();
if ($card->getIsClaimed() != 1) {
$isClaimable = true;
if ($success == false) $success = true;
$data['claimableAmount'] = $card->getAmount();
$data['claimableCoin'] = $card->getCoinCount();
if ($claimFlag == 1 && $userId != 0) {
Buddybee::AddBalanceGeneral(
$em,
$userId, ///id
$card->getAmount(), //amount
$card->getCoinCount()
);
if ($card->getUseCount() <= 1) {
$card->setIsClaimed(1);
}
$card->setUseCount(1 * $card->getUseCount() - 1);
$em->flush();
$data['claimedAmount'] = $card->getAmount();
$data['claimedCoin'] = $card->getCoinCount();
$claimSuccess = true;
if ($success == false) $success = true;
}
}
}
return array(
'success' => $claimFlag == 1 ? $claimSuccess : $isClaimable,
'exists' => $card ? true : false,
'isClaimable' => $isClaimable,
'claimSuccess' => $claimSuccess,
'data' => $data,
'cardId' => $cardId,
'claimFlag' => $claimFlag,
'serial' => $serial,
'pin' => $pin,
);
}
public static function ClaimPromoCode($em, $options)
{
$data = [
'success' => false,
'message' => 'Invalid Code',
'claimableCoin' => 0,
'isClaimable' => 0,
'currency' => 'eur',
'claimableAmount' => 0,
'claimedAmount' => 0,
'claimedCoin' => 0,
'promoCodeId' => 0,
'overrideBySystem' => 0,
];
$success = false;
$isClaimable = false;
$claimSuccess = false;
$claimFlag = isset($options['claimFlag']) ? $options['claimFlag'] : 0;
$currency = isset($options['currency']) ? $options['currency'] : 'eur';
$currencyMult = BuddybeeConstant::$convMultFromTo[$currency]['eur'];
$userId = isset($options['userId']) ? $options['userId'] : 0;
$cardId = isset($options['cardId']) ? $options['cardId'] : 0;
$promoCodeId = isset($options['cardId']) ? $options['promoCodeId'] : 0;
$overrideBySystem = isset($options['overrideBySystem']) ? $options['overrideBySystem'] : 0;
//check 1st
$serial = isset($options['serial']) ? $options['serial'] : '_NONE_';
$pin = isset($options['pin']) ? $options['pin'] : '_NONE_';
$promoCodeStr = isset($options['promoCode']) ? $options['promoCode'] : '_NONE_';
$orderValue = $currencyMult * (isset($options['orderValue']) ? $options['orderValue'] : 0);
$orderCoins = isset($options['orderCoin']) ? $options['orderCoin'] : 0;
$isReferral = isset($options['isReferral']) ? $options['isReferral'] : 0;
$thisUserThisPromoUseCount = 0;
$currDt = new \DateTime();
$currDtTs = 1 * ($currDt->format('U'));
$claimedAmount = 0;
$claimableAmount = 0;
$claimedCoin = 0;
$claimableCoin = 0;
$claimFailMessage = '';
if ($isReferral == 1) {
$userData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array('applicantId' => $userId)
);
$referrerData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array('codeAsReferer' => $promoCodeStr)
);
$promoCode = $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')
->findOneBy(
array(
'code' => '_GEN_REFER_'
)
);
if ($promoCode) {
$data = array(
'success' => true,
'message' => '',
'id' => $promoCode->getId(),
'code' => $promoCode->getCode(),
'promoType' => $promoCode->getPromoType(),
'promoValue' => $promoCode->getPromoValue(),
'maxDiscountAmount' => $promoCode->getMaxDiscountAmount(),
'maxCoinAddition' => $promoCode->getMaxCoinAddition(),
'minAmountForApplication' => $promoCode->getMinAmountForApplication(),
'minCoinForApplication' => $promoCode->getMinCoinForApplication(),
'nextApplicationEachCoinCount' => $promoCode->getNextApplicationEachCoinCount(),
'maxUseCount' => $promoCode->getMaxUseCount(),
'maxUseCountPerUser' => $promoCode->getMaxUseCountPerUser(),
'useCountBalance' => $promoCode->getUseCountBalance(),
'useCountBalanceUser' => 0,
'startsAtTs' => $promoCode->getStartsAtTs(),
'expiresAtTs' => $promoCode->getExpiresAtTs(),
'perpetual' => $promoCode->getPerpetual(),
);
}
//get the applicant Data
if ($promoCode) {
$promoCodeId = $promoCode->getId();
$isClaimable = false;
if ($success == false) $success = true;
if ($userData)
$claimedPromoCodeIds = json_decode($userData->getClaimedPromoCodeIds(), true);
else
$claimedPromoCodeIds = [];
if ($claimedPromoCodeIds == null) $claimedPromoCodeIds = [];
$claimedPromoCodeCountByIds = array_count_values($claimedPromoCodeIds);
if (isset($claimedPromoCodeCountByIds[$promoCodeId]))
$thisUserThisPromoUseCount = 1 * $claimedPromoCodeCountByIds[$promoCodeId];
//check one by one if any claim condition doesnot match
if ($promoCode->getUseCountBalance() != -1 && $promoCode->getUseCountBalance() <= 0) {
$claimFailMessage = "This code can no longer be used!";
}
if ($promoCode->getMaxUseCountPerUser() != -1 && $promoCode->getMaxUseCountPerUser() <= $thisUserThisPromoUseCount) {
$claimFailMessage = "This code can no longer be used for this user!";
} else if ($promoCode->getPerpetual() != 1 && $promoCode->getExpiresAtTs() < $currDtTs) {
$claimFailMessage = "This code has Expired!";
} else if ($promoCode->getStartsAtTs() > $currDtTs) {
$claimFailMessage = "This code is not yet usable!";
} else {
if ($promoCode->getPromoType() == 1) //amount discount
{
if ($promoCode->getMinAmountForApplication() != -1 && $promoCode->getMinAmountForApplication() > $orderValue) {
$claimFailMessage = "Minimum order for this code is " . $promoCode->getMinAmountForApplication();
} else if ($promoCode->getMinCoinForApplication() != -1 && $promoCode->getMinCoinForApplication() > $orderCoins) {
$claimFailMessage = "You must Purchase at least " . $promoCode->getMinCoinForApplication() . " points/coins";
} else {
$claimableAmount = $promoCode->getPromoValue();
if ($promoCode->getNextApplicationEachCoinCount() != -1 && $promoCode->getNextApplicationEachCoinCount() != 0 && $orderCoins != 0) {
$extraCoins = $orderCoins - $promoCode->getMinCoinForApplication();
$it = $extraCoins / (1 * $promoCode->getNextApplicationEachCoinCount());
$claimableAmount += ($it * $promoCode->getPromoValue());
}
if ($promoCode->getMaxDiscountAmount() != -1 && $claimableAmount > $promoCode->getMaxDiscountAmount()) {
$claimableAmount = $promoCode->getMaxDiscountAmount();
}
$isClaimable = true;
}
}
if ($promoCode->getPromoType() == 2) //percentage discount
{
if ($promoCode->getMinAmountForApplication() != -1 && $promoCode->getMinAmountForApplication() > $orderValue) {
$claimFailMessage = "Minimum order for this code is " . $promoCode->getMinAmountForApplication();
} else if ($promoCode->getMinCoinForApplication() != -1 && $promoCode->getMinCoinForApplication() > $orderCoins) {
$claimFailMessage = "You must Purchase at least " . $promoCode->getMinCoinForApplication() . " points/coins";
} else {
$claimableAmount = $orderValue * $promoCode->getPromoValue() / 100;
if ($promoCode->getNextApplicationEachCoinCount() != -1 && $promoCode->getNextApplicationEachCoinCount() != 0 && $orderCoins != 0) {
$extraCoins = $orderCoins - $promoCode->getMinCoinForApplication();
$it = $extraCoins / (1 * $promoCode->getNextApplicationEachCoinCount());
$claimableAmount += ($it * $orderValue * $promoCode->getPromoValue() / 100);
}
if ($promoCode->getMaxDiscountAmount() != -1 && $claimableAmount > $promoCode->getMaxDiscountAmount()) {
$claimableAmount = $promoCode->getMaxDiscountAmount();
}
$isClaimable = true;
}
}
}
//if this stage has come then the
$data['claimableAmount'] = strval($claimableAmount);
$data['claimableCoin'] = $claimableCoin;
if ($claimFlag == 1 && $userId != 0) {
$claimedPromoCodeIds[] = $promoCodeId;
$userData->setClaimedPromoCodeIds(json_encode($claimedPromoCodeIds));
$promoCode->setUseCountBalance(1 * $promoCode->setUseCountBalance() - 1);
$em->flush();
if ($promoCode->getMaxReferralCommissionCount() != -1 && $promoCode->getReferralCommissionCountBalance() > 0) {
$claimFailMessage = "Minimum order for this code is " . $promoCode->getMinAmountForApplication();
} else {
$referrerData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array('applicantId' => $promoCode->getReferralApplicantId())
);
if ($referrerData) {
$referralAmount = 0;
$referralCoin = 0;
if ($promoCode->getReferralCommissionType() == 1)//amount addition
{
$referralAmount = $promoCode->getReferralAmount();
// $referralAmount=$orderValue*$promoCode->getReferralAmount()->getPromoValue()/100;
} else if ($promoCode->getReferralCommissionType() == 2)//percent addition
{
// $referralAmount = $promoCode->getReferralAmount();
$referralAmount = $orderValue * $promoCode->getReferralAmount() / 100;
}
if ($promoCode->getMaxReferralCommissionAmount() != -1 && $referralAmount > $promoCode->getMaxReferralCommissionAmount()) {
$referralAmount = $promoCode->getMaxReferralCommissionAmount();
}
$referrerData->setReferredAmountEarned(1 * $referrerData->setReferredAmountEarned() + $referralAmount);
$promoCode->setReferralCommissionCountBalance(1 * $promoCode->setReferralCommissionCountBalance() - 1);
$em->flush();
}
}
$claimedAmount = $claimableAmount;
$claimedCoin = $claimableCoin;
$em->flush();
$data['claimedAmount'] = $claimedAmount;
$data['claimedCoin'] = $claimedCoin;
$claimSuccess = true;
if ($success == false) $success = true;
}
}
return array(
'success' => $claimFlag == 1 ? $claimSuccess : $isClaimable,
'exists' => $promoCode ? true : false,
'isClaimable' => $isClaimable,
'claimFailMessage' => $claimFailMessage,
'claimSuccess' => $claimSuccess,
'data' => $data,
'promoCodeId' => $promoCodeId,
'claimFlag' => $claimFlag,
);
} else {
//1st searching for direct code
$promoCode = $em->getRepository('CompanyGroupBundle\\Entity\\PromoCode')
->findOneBy(
array(
'code' => $promoCodeStr
)
);
if ($promoCode) {
$data = array(
'success' => true,
'message' => '',
'id' => $promoCode->getId(),
'code' => $promoCode->getCode(),
'promoType' => $promoCode->getPromoType(),
'promoValue' => $promoCode->getPromoValue(),
'maxDiscountAmount' => $promoCode->getMaxDiscountAmount(),
'maxCoinAddition' => $promoCode->getMaxCoinAddition(),
'minAmountForApplication' => $promoCode->getMinAmountForApplication(),
'minCoinForApplication' => $promoCode->getMinCoinForApplication(),
'nextApplicationEachCoinCount' => $promoCode->getNextApplicationEachCoinCount(),
'maxUseCount' => $promoCode->getMaxUseCount(),
'maxUseCountPerUser' => $promoCode->getMaxUseCountPerUser(),
'useCountBalance' => $promoCode->getUseCountBalance(),
'useCountBalanceUser' => 0,
'startsAtTs' => $promoCode->getStartsAtTs(),
'expiresAtTs' => $promoCode->getExpiresAtTs(),
'perpetual' => $promoCode->getPerpetual(),
);
}
//get the applicant Data
$userData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array('applicantId' => $userId)
);
if ($promoCode) {
$promoCodeId = $promoCode->getId();
$isClaimable = false;
if ($success == false) $success = true;
if ($userData)
$claimedPromoCodeIds = json_decode($userData->getClaimedPromoCodeIds(), true);
else
$claimedPromoCodeIds = [];
if ($claimedPromoCodeIds == null) $claimedPromoCodeIds = [];
$claimedPromoCodeCountByIds = array_count_values($claimedPromoCodeIds);
if (isset($claimedPromoCodeCountByIds[$promoCodeId]))
$thisUserThisPromoUseCount = 1 * $claimedPromoCodeCountByIds[$promoCodeId];
//check one by one if any claim condition doesnot match
if ($promoCode->getUseCountBalance() != -1 && $promoCode->getUseCountBalance() <= 0) {
$claimFailMessage = "This code can no longer be used!";
}
if ($promoCode->getMaxUseCountPerUser() != -1 && $promoCode->getMaxUseCountPerUser() <= $thisUserThisPromoUseCount) {
$claimFailMessage = "This code can no longer be used for this user!";
} else if ($promoCode->getPerpetual() != 1 && $promoCode->getExpiresAtTs() < $currDtTs) {
$claimFailMessage = "This code has Expired!";
} else if ($promoCode->getStartsAtTs() > $currDtTs) {
$claimFailMessage = "This code is not yet usable!";
} else {
if ($promoCode->getPromoType() == 1) //amount discount
{
if ($promoCode->getMinAmountForApplication() != -1 && $promoCode->getMinAmountForApplication() > $orderValue) {
$claimFailMessage = "Minimum order for this code is " . $promoCode->getMinAmountForApplication();
} else if ($promoCode->getMinCoinForApplication() != -1 && $promoCode->getMinCoinForApplication() > $orderCoins) {
$claimFailMessage = "You must Purchase at least " . $promoCode->getMinCoinForApplication() . " points/coins";
} else {
$claimableAmount = $promoCode->getPromoValue();
if ($promoCode->getNextApplicationEachCoinCount() != -1 && $promoCode->getNextApplicationEachCoinCount() != 0 && $orderCoins != 0) {
$extraCoins = $orderCoins - $promoCode->getMinCoinForApplication();
$it = $extraCoins / (1 * $promoCode->getNextApplicationEachCoinCount());
$claimableAmount += ($it * $promoCode->getPromoValue());
}
if ($promoCode->getMaxDiscountAmount() != -1 && $claimableAmount > $promoCode->getMaxDiscountAmount()) {
$claimableAmount = $promoCode->getMaxDiscountAmount();
}
$isClaimable = true;
}
}
if ($promoCode->getPromoType() == 2) //percentage discount
{
if ($promoCode->getMinAmountForApplication() != -1 && $promoCode->getMinAmountForApplication() > $orderValue) {
$claimFailMessage = "Minimum order for this code is " . $promoCode->getMinAmountForApplication();
} else if ($promoCode->getMinCoinForApplication() != -1 && $promoCode->getMinCoinForApplication() > $orderCoins) {
$claimFailMessage = "You must Purchase at least " . $promoCode->getMinCoinForApplication() . " points/coins";
} else {
$claimableAmount = $orderValue * $promoCode->getPromoValue() / 100;
if ($promoCode->getNextApplicationEachCoinCount() != -1 && $promoCode->getNextApplicationEachCoinCount() != 0 && $orderCoins != 0) {
$extraCoins = $orderCoins - $promoCode->getMinCoinForApplication();
$it = $extraCoins / (1 * $promoCode->getNextApplicationEachCoinCount());
$claimableAmount += ($it * $orderValue * $promoCode->getPromoValue() / 100);
}
if ($promoCode->getMaxDiscountAmount() != -1 && $claimableAmount > $promoCode->getMaxDiscountAmount()) {
$claimableAmount = $promoCode->getMaxDiscountAmount();
}
$isClaimable = true;
}
}
}
//if this stage has come then the
$data['claimableAmount'] = strval($claimableAmount);
$data['claimableCoin'] = $claimableCoin;
if ($claimFlag == 1 && $userId != 0) {
$claimedPromoCodeIds[] = $promoCodeId;
$userData->setClaimedPromoCodeIds(json_encode($claimedPromoCodeIds));
$promoCode->setUseCountBalance(1 * $promoCode->getUseCountBalance() - 1);
$em->flush();
if ($promoCode->getMaxReferralCommissionCount() != -1 && $promoCode->getReferralCommissionCountBalance() > 0) {
$claimFailMessage = "Minimum order for this code is " . $promoCode->getMinAmountForApplication();
} else {
$referrerData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array('applicantId' => $promoCode->getReferralApplicantId())
);
if ($referrerData) {
$referralAmount = 0;
$referralCoin = 0;
if ($promoCode->getReferralCommissionType() == 1)//amount addition
{
$referralAmount = $promoCode->getReferralAmount();
// $referralAmount=$orderValue*$promoCode->getReferralAmount()->getPromoValue()/100;
} else if ($promoCode->getReferralCommissionType() == 2)//percent addition
{
// $referralAmount = $promoCode->getReferralAmount();
$referralAmount = $orderValue * $promoCode->getReferralAmount() / 100;
}
if ($promoCode->getMaxReferralCommissionAmount() != -1 && $referralAmount > $promoCode->getMaxReferralCommissionAmount()) {
$referralAmount = $promoCode->getMaxReferralCommissionAmount();
}
$referrerData->setReferredAmountEarned(1 * $referrerData->getReferredAmountEarned() + $referralAmount);
$promoCode->setReferralCommissionCountBalance(1 * $promoCode->getReferralCommissionCountBalance() - 1);
$em->flush();
}
}
$claimedAmount = $claimableAmount;
$claimedCoin = $claimableCoin;
$em->flush();
$data['claimedAmount'] = $claimedAmount;
$data['claimedCoin'] = $claimedCoin;
$claimSuccess = true;
if ($success == false) $success = true;
}
// $data['success']=$claimFlag == 1 ? $claimSuccess : $isClaimable;
$data['message'] = $claimFailMessage;
$data['isClaimable'] = $isClaimable;
$data['claimSuccess'] = $claimSuccess;
}
return array(
'success' => $claimFlag == 1 ? $claimSuccess : $isClaimable,
'exists' => $promoCode ? true : false,
'isClaimable' => $isClaimable,
'claimFailMessage' => $claimFailMessage,
'claimSuccess' => $claimSuccess,
'data' => $data,
'promoCodeId' => $promoCodeId,
'claimFlag' => $claimFlag,
);
}
}
public static function toListArray($obj)
{
$array = array();
foreach ($obj as $ob)
$array[] = $ob;
return $array;
}
public static function filterPackageList($options = [])
{
$requiredPurchaseSessionCount = isset($options['requiredPurchaseSessionCount']) ? $options['requiredPurchaseSessionCount'] : 0;
$packageNames = BuddybeeConstant::$packageNames;
$packageDetails = BuddybeeConstant::$packageDetails;
$array = array(
'packageNames' => [],
'packageDetails' => [],
'selectionValue' => 2 * BuddybeeConstant::COIN_GENERAL_MULT,
'selectionPackageId' => 0,
);
foreach ($packageDetails as $key => $obj) {
if ($obj['sessionMaxCount'] < $requiredPurchaseSessionCount)
continue;
$array['selectionPackageId'] = $key;
if ($obj['sessionMinCount'] > $requiredPurchaseSessionCount)
$array['selectionValue'] = $obj['sessionMinCount'];
else {
$obj['sessionMinCount'] = $requiredPurchaseSessionCount;
$array['selectionValue'] = $requiredPurchaseSessionCount;
}
$obj['packageId'] = $key;
$array['packageNames'][] = $obj['packageName'];
$array['packageDetails'][] = $obj;
}
return $array;
}
public static function ConvertRegionalTimeToServerTime($currentRegionalTimeStr, $toConvertRegionalTimeStr)
{
$currSvrTime = new \DateTime();
$toConvertTime = new \DateTime($toConvertRegionalTimeStr);
$currClientTime = new \DateTime($currentRegionalTimeStr);
$interval = $currClientTime->diff($currSvrTime);
if ($currClientTime > $currSvrTime)
$toConvertTime->add($interval);
else
$toConvertTime->sub($interval);
return $toConvertTime;
}
public static function RemoveFileById($em, $id, $afterRemoveConfig)
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
//remove restrictions over 1 year old
$currDateNow->modify('-365 Day');
$get_kids_sql = "select * FROM `entity_files` WHERE id = " . $id;
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
foreach ($query_output as $q) {
if (file_exists($q['path'])) {
chmod($q['path'], 0755);
unlink($q['path']);
}
if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
$consultantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $q['entity_id']
)
);;
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
} else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
$entityDoc = $em->getRepository($q['entity_bundle'] . ':' . $q['entity_name'])->findOneBy(
array(
$q['entity_id_field'] => $q['entity_id']
)
);
if ($entityDoc) {
$entityDoc->{$q['modify_field_setter']}('');
$em->flush();
}
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
}
}
$get_kids_sql = "DELETE FROM `entity_files` WHERE id = " . $id;
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return true;
}
public static function RemoveFileByCondition($em, $conditionOptions = [])
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
//remove restrictions over 1 year old
$currDateNow->modify('-365 Day');
$EntityFile = $em->getRepository('CompanyGroupBundle\\Entity\\EntityFile')->findOneBy(
$conditionOptions
);
if ($EntityFile) {
$q = array(
'path' => $EntityFile->getPath(),
'entity_name' => $EntityFile->getEntityName(),
'entity_id_field' => $EntityFile->getEntityIdField(),
'entity_id' => $EntityFile->getEntityId(),
'entity_bundle' => $EntityFile->getEntityBundle(),
'marker' => $EntityFile->getMarker(),
'doc_id_for_applicant' => $EntityFile->getDocIdForApplicant(),
'modify_field_setter' => $EntityFile->getModifyFieldSetter(),
);
if (file_exists($q['path'])) {
chmod($q['path'], 0755);
unlink($q['path']);
}
if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
$consultantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $q['entity_id']
)
);;
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
} else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
$entityDoc = $em->getRepository($q['entity_bundle'] . ':' . $q['entity_name'])->findOneBy(
array(
$q['entity_id_field'] => $q['entity_id']
)
);
if ($entityDoc) {
$entityDoc->{$q['modify_field_setter']}('');
$em->flush();
}
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
}
$em->remove($EntityFile);
$em->flush();
}
//
// $get_kids_sql = "DELETE FROM `entity_files` WHERE path like '% " . $pathStr."%'";
// $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
//
//
return true;
}
public static function RemoveFileByPath($em, $pathStr, $afterRemoveConfig = [])
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
//remove restrictions over 1 year old
$currDateNow->modify('-365 Day');
$get_kids_sql = "select * FROM `entity_files` WHERE path like '%" . $pathStr . "%'";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
foreach ($query_output as $q) {
if (file_exists($q['path'])) {
chmod($q['path'], 0755);
unlink($q['path']);
}
if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
$consultantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $q['entity_id']
)
);;
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
} else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
$entityDoc = $em->getRepository($q['entity_bundle'] . ':' . $q['entity_name'])->findOneBy(
array(
$q['entity_id_field'] => $q['entity_id']
)
);
if ($entityDoc) {
$entityDoc->{$q['modify_field_setter']}('');
$em->flush();
}
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
}
}
$get_kids_sql = "DELETE FROM `entity_files` WHERE path like '% " . $pathStr . "%'";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return true;
}
public static function RemoveFilesForEntityDoc($em, $entityName = '', $entityId = 0)
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
//remove restrictions over 1 year old
$currDateNow->modify('-365 Day');
$get_kids_sql = "select * FROM `entity_files` WHERE entity_name='" . $entityName . "' and entity_id =" . $entityId;
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
foreach ($query_output as $q) {
if (file_exists($q['path'])) {
chmod($q['path'], 0755);
unlink($q['path']);
}
}
return true;
}
public static function RemoveExpiredDocs($em)
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
//remove restrictions over 1 year old
$currDateNow->modify('-10 Day');
// foreach (GeneralConstant::$Entity_list as $entity=>$entityName) {
//
// $query = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
// ->createQueryBuilder('p')
// ->where("p.timeStampOfForm is NOT NULL ")
// ->andWhere("p.approved is NULL ")
// ->andWhere("p.timeStampOfForm <= " . $currDateNow->format('U'));
// $results = $query->getQuery()->getResult();
//
// foreach ($results as $r) {
// $em->remove($r);
// $em->flush();
// }
// }
return true;
}
public static function RemoveExpiredFiles($em)
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
$currDateNow->modify('-120 Day');
$get_kids_sql = "select * FROM `entity_files` WHERE expire_ts!=0 and expire_ts < " . $currDateNow->format('U');
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$query_output = [];
foreach ($query_output as $q) {
if ($q['marker'] == '_ENTITY_APPLICANT_DOCUMENT_') {
$consultantDetails = $em->getRepository(EntityApplicantDetails::class)->find($q['entity_id']);
if ($consultantDetails) {
$currDocList = json_decode($consultantDetails->getDocumentList(), true);
$doc_index_here = $q['doc_id_for_applicant'];
if ($currDocList == null)
$currDocList = [];
if (isset($currDocList[$doc_index_here])) {
$currDocList[$doc_index_here]['docImage'] = '';
$currDocList[$doc_index_here]['docExpiryDate'] = '';
$consultantDetails->setDocumentList(json_encode($currDocList));
$em->flush();
}
}
} else if ($q['entity_bundle'] != '' && $q['entity_name'] != '' && $q['entity_id_field'] != '') {
$entity_id = array_flip(GeneralConstant::$Entity_list)[$q['entity_name']]; //change
$entityDoc = $em->getRepository(isset(GeneralConstant::$Entity_fqcn_by_id[$entity_id]) ? GeneralConstant::$Entity_fqcn_by_id[$entity_id] : ($q['entity_bundle'] . '\\Entity\\' . $q['entity_name']))->findOneBy(
array(
$q['entity_id_field'] => $q['entity_id']
)
);
if ($entityDoc) {
if (method_exists($entityDoc, 'getApproved'))
if ($entityDoc->getApproved() == 1) {
$get_kids_sql = "UPDATE `entity_files` SET expire_ts=0 WHERE id= " . $q['id'];
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
continue;
}
$entityDoc->{$q['modify_field_setter']}('');
$em->flush();
}
}
if (file_exists($q['path'])) {
chmod($q['path'], 0755);
unlink($q['path']);
}
}
$get_kids_sql = "DELETE FROM `entity_files` WHERE expire_ts!=0 and expire_ts < " . $currDateNow->format('U');
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return true;
}
public static function RemoveExpiredScheduleRestrictions($em, $applicantId = [])
{
//remove expired availability 1st
// return true; //for now
$currDateNow = new \DateTime();
//remove restrictions over 1 year old
$currDateNow->modify('-365 Day');
$get_kids_sql = "DELETE FROM `consultancy_availability` WHERE expires_ts < " . $currDateNow->format('U');
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return true;
}
public static function AddScheduleRestrictions($em, $applicantId = 0, $periodMarker = '')
{
//remove expired schedules 1st
$returnData = [];
$consultant = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $applicantId
)
);
if (!$consultant)
return null;
$new = new ConsultancyAvailability();
$Y = intdiv($periodMarker, 100);
$M = $periodMarker % 100;
$new->setType(2);
$new->setYear($Y);
$new->setMonth($M);
$startAt = new \DateTime($Y . '-' . str_pad($M, 2, '0', STR_PAD_LEFT) . '-01 00:00:00 +0000');
$M = $M + 1;
if ($M == 13) {
$M = 1;
$Y++;
}
$expiresAt = new \DateTime($Y . '-' . str_pad($M, 2, '0', STR_PAD_LEFT) . '-01 00:00:00 +0000');
$new->setConsultantId($consultant->getApplicantId());
$new->setPeriodMarker($periodMarker);;
$new->setStartTs($startAt->format('U'));
$new->setExpiresTs($expiresAt->format('U'));
$countryRestrictionData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findOneBy(
array(
'countryId' => $consultant->getCurrentCountryId()
)
);
if ($countryRestrictionData) {
if ($countryRestrictionData->getAllowedWorkingHoursPerMonth() != -1)
$new->setAllowedHours(1 * $countryRestrictionData->getAllowedWorkingHoursPerMonth());
else
$new->setAllowedHours(160);
} else
$new->setAllowedHours(160);
$new->setAvailableHours($new->getAllowedHours());
$new->setBookedHours(0);
$new->setTemporaryBookedHours(0);
$em->persist($new);
$em->flush();
return $new; //for now
}
public static function SchedulingAvailabilityByRestrictions($em, $scheduleMarker, $startDateStr, $consultantId, $duration)
{
MiscActions::RemoveExpiredScheduleRestrictions($em);
$nextAvailableTs = 0;
$allowed = 0;
$availableMin = 0;
$startDate = new \DateTime($startDateStr);
$startDate->setTimezone(new \DateTimeZone('+0000'));
$endDate = new \DateTime($startDateStr);
$applicableMarkers = [];
$availableMinByPeriodMarker = [];
$allowedMinByPeriodMarker = [];
$restrictionDataByPeriodMarker = [];
if ($scheduleMarker == '_NEXT_60_DAYS_') {
$endDate->modify('+60 Day');
}
$toTestStartDate = clone($startDate);
$toTestEndDate = clone($endDate);
$consultancyAvailabilityDataArray = [];
while ($toTestStartDate <= $toTestEndDate) {
$toTestStartDate->modify('+1 Day');
$markerForThis = $toTestStartDate->format('Ym');
if (!in_array($markerForThis, $applicableMarkers))
$applicableMarkers[] = $markerForThis;
}
$query = $em->getRepository('CompanyGroupBundle\\Entity\\ConsultancyAvailability')
->createQueryBuilder('p')
->where('p.periodMarker in (:pm)')
->andWhere('p.consultantId = :aid')
->andWhere('p.type = :typ')
// ->andWhere('p.startTs < :sd')
// ->andWhere('p.expiresTs < :ed')
->setParameter('typ', 2)
->setParameter('aid', $consultantId)
// ->setParameter('sd', $startDate->format('U'))
// ->setParameter('ed', $endDate->format('U'))
->setParameter('pm', $applicableMarkers);
// $query->setMaxResults(1);
$consultantAvailabilityData = $query->getQuery()->getResult();
foreach ($consultantAvailabilityData as $d) {
$consultancyAvailabilityDataArray[$d->getPeriodMarker()] = $d;
}
foreach ($applicableMarkers as $pm) {
if (!isset($consultancyAvailabilityDataArray[$pm])) {
$d = MiscActions::AddScheduleRestrictions($em, $consultantId, $pm);
} else {
$d = $consultancyAvailabilityDataArray[$pm];
}
$availableMin = 60 * ((1 * $d->getAvailableHours()) - (1 * $d->getTemporaryBookedHours()));
$availableMinByPeriodMarker[$pm] = $availableMin;
$allowedMinByPeriodMarker[$pm] = (60 * $d->getAllowedHours());
$restrictionDataByPeriodMarker[$pm] = array(
'startTs' => $d->getStartTs(),
'allowedHours' => $d->getAllowedHours(),
'availableHours' => $d->getAvailableHours(),
'expiresTs' => $d->getExpiresTs(),
);
if ($availableMin > 0) {
$allowed = 1;
$nextAvailableTs = $d->getStartTs();
}
}
// return array(
// 'allowed' => 1,
// 'availableMin' => 450,
// 'nextAvailableTs' => $nextAvailableTs,
// 'restrictionDataByPeriodMarker' => [],
// 'applicableMarkers' => $applicableMarkers,
// 'availableMinByPeriodMarker' => [],
// 'allowedMinByPeriodMarker' => [],
// );
return array(
'allowed' => $allowed,
'availableMin' => $availableMin,
'nextAvailableTs' => $nextAvailableTs,
'restrictionDataByPeriodMarker' => $restrictionDataByPeriodMarker,
'applicableMarkers' => $applicableMarkers,
'availableMinByPeriodMarker' => $availableMinByPeriodMarker,
// 'availableMinByPeriodMarker' => [],
'allowedMinByPeriodMarker' => $allowedMinByPeriodMarker,
);
}
public static function UpdateSchedulingRestrictions($em, $applicantId, $periodMarker, $toAddBookedHours = 0, $toAddTemporaryBookedHours = 0)
{
MiscActions::RemoveExpiredScheduleRestrictions($em);
$returnData = [];
$consultant = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $applicantId
)
);
$new = $em->getRepository('CompanyGroupBundle\\Entity\\ConsultancyAvailability')->findOneBy(
array(
'periodMarker' => $periodMarker,
'consultantId' => $applicantId
)
);
if (!$new) {
$new = new ConsultancyAvailability();
$Y = intdiv($periodMarker, 100);
$M = $periodMarker % 100;
$new->setType(2);
$new->setYear($Y);
$new->setMonth($M);
$startAt = new \DateTime($Y . '-' . str_pad($M, 2, '0', STR_PAD_LEFT) . '-01 00:00:00 +0000');
$M = $M + 1;
if ($M == 13) {
$M = 1;
$Y++;
}
$expiresAt = new \DateTime($Y . '-' . str_pad($M, 2, '0', STR_PAD_LEFT) . '-01 00:00:00 +0000');
$new->setConsultantId($consultant->getApplicantId());
$new->setPeriodMarker($periodMarker);;
$new->setStartTs($startAt->format('U'));
$new->setExpiresTs($expiresAt->format('U'));
$countryRestrictionData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findOneBy(
array(
'countryId' => $consultant->getCurrentCountryId()
)
);
if ($countryRestrictionData) {
if ($countryRestrictionData->getAllowedWorkingHoursPerMonth() != -1)
$new->setAllowedHours(1 * $countryRestrictionData->getAllowedWorkingHoursPerMonth());
else
$new->setAllowedHours(160);
} else
$new->setAllowedHours(160);
$new->setAvailableHours($new->getAllowedHours());
$new->setBookedHours(0);
$new->setTemporaryBookedHours(0);
$em->persist($new);
}
$new->setBookedHours((1 * $new->getBookedHours()) + (1 * $toAddBookedHours));
$new->setAvailableHours((1 * $new->getAvailableHours()) - (1 * $toAddBookedHours));
$new->setTemporaryBookedHours((1 * $new->getTemporaryBookedHours()) + (1 * $toAddTemporaryBookedHours));
$em->flush();
return $new; //for now
}
public static function GetConsultantExistingSchedules($em, $consultantId, $startDateStr = '', $endDateStr = '', $durationMin = 90, $options = [])
{
//start end dates and respose dats are all with time zones or UTC and ideally the UTC time stamps
$startDate = new \DateTime($startDateStr);
if ($endDateStr == '') {
$endDate = clone($startDate);
// if (isset($options['_THIS_DAY_']))
// $endDate->modify('+1439 Minute');
// else if (isset($options['_NEXT_60_DAYS_']))
// $endDate->modify('+60 Day');
// else if (isset($options['_NEXT_DAYS_']))
// $endDate->modify('+' . $options['_NEXT_DAYS_'] . ' Day');
// else
$endDate->modify('+1439 Minute');
} else
$endDate = new \DateTime($endDateStr);
$schedulesList = [];
$debugData = [];
$closestDateTs = 0;
//now get schedules
$consultantScheduleData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findBy(array(
'consultantId' => $consultantId
));
$consultantTimeZone = '';
$consultantSchedules = [];
if ($consultantScheduleData) {
$consultantSchedules = [];
foreach ($consultantScheduleData 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(),
);
$consultantSchedules[] = $indTimeSche;
}
foreach ($consultantSchedules as $consultantSchedule) {
$consultantTimeZone = $consultantSchedule['timeZone'];
}
$existingBookedSchedules = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->createQueryBuilder('m')
->where("m.consultantId = :consultantId")
->andWhere("m.isExpired != 1")
->andWhere("m.scheduledTimeTs >= :startAt")
->andWhere("m.sessionExpireDateTs <= :endAt")
->setParameter('consultantId', $consultantId)
->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()
->getResult();
$skipDateTimeStart = [];
$skipDateTimeEnd = [];
foreach ($existingBookedSchedules as $existingBookedSchedule) {
$scheduledStartTime = new \DateTime('@' . $existingBookedSchedule->getScheduledTimeTs());;
// $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
// $scheduledStartTime->setTimezone(new \DateTimeZone('+0000'));
$skipDateTimeStart[] = $scheduledStartTime;
$skipDateTimeEnd[] = new \DateTime('@' . $existingBookedSchedule->getSessionExpireDateTs());
}
foreach ($consultantSchedules as $consultantSchedule) {
$scheduleType = $consultantSchedule['type'];
$consultantScheduleStartAtTime = new \DateTime($consultantSchedule['date'] . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleEndAtTime = new \DateTime($consultantSchedule['date'] . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleUpToDate = new \DateTime($consultantSchedule['dateUpto'] . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$dateAllowed = 0;
$allowedStartTime = 0;
$allowedEndTime = 0;
if ($scheduleType == 1)//specific date
{
$startDateForCheck = clone($startDate);
$safetyLoopBreaker = 3000;
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
// $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
// $startDateForCheck->modify('+1 Day');
}
while ($startDateForCheck < $endDate && $safetyLoopBreaker >= 0) {
$safetyLoopBreaker--;
foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
$startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
}
}
if ($startDateForCheck >= $consultantScheduleUpToDate) {
$safetyLoopBreaker = 0;
break;
}
if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
$timeUnix = $startDateForCheck->format('U');
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $timeUnix,
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
if ($closestDateTs > $timeUnix || $closestDateTs == 0)
$closestDateTs = $timeUnix;
}
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
} else
$startDateForCheck->modify('+' . $durationMin . ' Minute');
}
$debugData['sLoopBreakerSpDate'] = $safetyLoopBreaker;
} else if ($scheduleType == 2)//days of week
{
$dow = $consultantSchedule['dow'];
$startDateForCheck = clone($startDate);
$safetyLoopBreaker = 3000;
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
// $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
// $startDateForCheck->modify('+1 Day');
}
while ($startDateForCheck < $endDate && $safetyLoopBreaker >= 0) {
// $debugData[]=[
// 'loopDate'=>$startDateForCheck->format('Y-m-d H:i:s'),
// 'weekDate'=>$startDateForCheck->format('N'),
// 'dow'=>$dow,
// 'consultantScheduleStartAtTime'=>$consultantScheduleStartAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleEndAtTime'=>$consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleUpToDate'=>$consultantScheduleUpToDate->format('Y-m-d H:i:s'),
// 'in'=>in_array($startDateForCheck->format('N'),$dow)
// ];
$safetyLoopBreaker--;
foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
$debugData[] = [
'loopDate' => $startDateForCheck->format('Y-m-d H:i:sP'),
// 'weekDate' => $startDateForCheck->format('N'),
// 'dow' => $dow,
'skipDateTimeStart' => $skidDTS->format('Y-m-d H:i:sP'),
'skipDateTimeEnd' => $skipDateTimeEnd[$key_DTS]->format('Y-m-d H:i:sP'),
// 'consultantScheduleStartAtTime' => $consultantScheduleStartAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleEndAtTime' => $consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleUpToDate' => $consultantScheduleUpToDate->format('Y-m-d H:i:s'),
// 'in' => in_array($startDateForCheck->format('N'), $dow)
];
if ($startDateForCheck >= $skidDTS && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
$startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
}
}
if ($startDateForCheck >= $consultantScheduleUpToDate) {
$safetyLoopBreaker = 0;
break;
}
if (!in_array($startDateForCheck->format('N'), $dow)) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
continue;
}
if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
$timeUnix = $startDateForCheck->format('U');
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $timeUnix,
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
if ($closestDateTs > $timeUnix || $closestDateTs == 0)
$closestDateTs = $timeUnix;
}
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($consultantScheduleStartAtTime->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
} else
$startDateForCheck->modify('+' . $durationMin . ' Minute');
}
$debugData['sLoopBreakerDow'] = $safetyLoopBreaker;
} else if ($scheduleType == 3)//Exclude date
{
$startDateForCheck = clone($startDate);
$safetyLoopBreaker = 3000;
while ($startDateForCheck < $endDate && $safetyLoopBreaker >= 0) {
$safetyLoopBreaker--;
foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
$startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
}
}
if ($startDateForCheck >= $consultantScheduleUpToDate) {
$safetyLoopBreaker = 0;
break;
}
if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $startDateForCheck->format('U'),
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
}
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
} else
$startDateForCheck->modify('+' . $durationMin . ' Minute');
}
}
if ($dateAllowed == 1) {
}
}
$em->flush();
}
// return [$schedulesList,$consultantSchedules,$debugData];
return [
'scheduleList' => $schedulesList,
'closestDateTs' => $closestDateTs,
'debugData' => $debugData,
];
}
public static function RemoveExpiredTemporaryBookingsOnBeeCard($em)
{
//remove expired schedules 1st
//now that we go the data we can empty the closing table
$currDateNow = new \DateTime();
$get_kids_sql = "UPDATE `bee_code` set is_temporary_booked=0, booked_by=0 WHERE booking_expire_ts < " . $currDateNow->format('U');
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return true;
}
public static function RemoveExpiredTemporaryBookings($em)
{
//remove expired schedules 1st
//now that we go the data we can empty the closing table
$currDateNow = new \DateTime();
$get_kids_sql = "select * FROM `entity_temporary_booking` WHERE booking_expires_ts < " . $currDateNow->format('U');
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
foreach ($query_output as $q) {
$dt = new \DateTime('@' . $q['scheduled_time_ts']);
$periodMarker = $dt->format('Ym');
MiscActions::UpdateSchedulingRestrictions($em, $q['consultant_id'], $periodMarker, 0, -(($q['duration_allowed_min']) / 60));
}
$get_kids_sql = "DELETE FROM `entity_temporary_booking` WHERE booking_expires_ts < " . $currDateNow->format('U');
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
return true;
}
public static function getSessionDurationObject($em = '')
{
// $consultantScheduleData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findOneBy(
// array(
// 'consultantId' => $consultantId
// )
// );
return array('object' => BuddybeeConstant::$sessionDurationObject, 'array' => BuddybeeConstant::$sessionDurationArray);
}
public static function GetConsultantSchedules($em, $consultantId, $startDateStr = '', $endDateStr = '', $durationMin = 90, $options = [])
{
//start end dates and respose dats are all with time zones or UTC and ideally the UTC time stamps
$startDate = new \DateTime($startDateStr); ///add @ on the string if you provide timeunix
$startDate->setTimezone(new \DateTimeZone('+0000'));
$currDateNow = new \DateTime();
if (is_string($options)) {
$options = json_decode($options, true);
if ($options == null)
$options = [];
}
$sessionDurationData = MiscActions::getSessionDurationObject($em);
$defaultselection = 1 * BuddybeeConstant::COIN_GENERAL_MULT;
$currentSelection = $defaultselection;
if ($durationMin == '_UNSET_') {
$durationMin = $sessionDurationData['object'][$defaultselection]['durationMin'];
$currentSelection = $defaultselection;
} else {
foreach ($sessionDurationData['object'] as $t => $p) {
if ($p['durationMin'] == $durationMin)
$currentSelection = $t;
}
}
if ($endDateStr == '') {
$endDate = clone($startDate);
if (isset($options['_THIS_DAY_']))
$endDate->modify('+1439 Minute');
else if (isset($options['_NEXT_60_DAYS_']))
$endDate->modify('+60 Day');
else if (isset($options['_NEXT_DAYS_'])) ///'_NEXT_DAYS_':59
$endDate->modify('+' . $options['_NEXT_DAYS_'] . ' Day');
else
$endDate->modify('+1439 Minute');
} else
$endDate = new \DateTime($endDateStr);
$schedulesList = [];
$debugData = [];
$closestDateTs = 0;
$singleFlag = isset($options['singleFlag']) ? $options['singleFlag'] : 0;
$extensionFlag = isset($options['forExtension']) ? $options['forExtension'] : 0;
$availableMinByPeriodMarker = MiscActions::SchedulingAvailabilityByRestrictions($em, '_NEXT_60_DAYS_', $startDateStr, $consultantId, $durationMin)['availableMinByPeriodMarker'];
//now get schedules
$consultantScheduleData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityConsultantSchedule')->findBy(
array(
'consultantId' => $consultantId
)
);
$consultantTimeZone = '';
$consultantSchedules = [];
if (!empty($consultantScheduleData)) {
foreach ($consultantScheduleData 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(),
);
$consultantSchedules[] = $indTimeSche;
}
foreach ($consultantSchedules as $consultantSchedule) {
$consultantTimeZone = $consultantSchedule['timeZone'];
}
$existingBookedSchedules = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
->createQueryBuilder('m')
->where("m.consultantId = :consultantId")
->andWhere("m.isExpired != 1")
->andWhere("m.scheduledTimeTs >= :startAt")
->andWhere("m.sessionExpireDateTs <= :endAt")
->setParameter('consultantId', $consultantId)
->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()
->getResult();
$skipDateTimeStart = [];
$skipDateTimeEnd = [];
foreach ($existingBookedSchedules as $existingBookedSchedule) {
$scheduledStartTime = new \DateTime('@' . $existingBookedSchedule->getScheduledTimeTs());;
// $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
// $scheduledStartTime->setTimezone(new \DateTimeZone('+0000'));
$skipDateTimeStart[] = $scheduledStartTime;
$skipDateTimeEnd[] = new \DateTime('@' . $existingBookedSchedule->getSessionExpireDateTs());
}
//remove expired schedules 1st
//now that we go the data we can empty the closing table
MiscActions::RemoveExpiredTemporaryBookings($em);
$existingBookedSchedules = $em->getRepository('CompanyGroupBundle\\Entity\\EntityTemporaryBooking')
->createQueryBuilder('m')
->where("m.consultantId = :consultantId")
->andWhere("m.scheduledTimeTs >= :startAt")
->andWhere("m.sessionExpireDateTs <= :endAt")
->setParameter('consultantId', $consultantId)
->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()
->getResult();
foreach ($existingBookedSchedules as $existingBookedSchedule) {
$scheduledStartTime = new \DateTime('@' . $existingBookedSchedule->getScheduledTimeTs());;
// $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
// $scheduledStartTime->setTimezone(new \DateTimeZone('+0000'));
$skipDateTimeStart[] = $scheduledStartTime;
$skipDateTimeEnd[] = new \DateTime('@' . $existingBookedSchedule->getSessionExpireDateTs());
}
foreach ($consultantSchedules as $consultantSchedule) {
$scheduleType = $consultantSchedule['type'];
$consultantTimeZone = $consultantSchedule['timeZone'];
$consultantScheduleStartAtTime = new \DateTime($consultantSchedule['date'] . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleEndAtTime = new \DateTime($consultantSchedule['date'] . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleUpToDate = new \DateTime($consultantSchedule['dateUpto'] . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$dateAllowed = 0;
$allowedStartTime = 0;
$allowedEndTime = 0;
$hasAtleastOneSchedule = 0;
$debugData['strt_' . $consultantSchedule['date']] = array();
$debugData['end_' . $consultantSchedule['date']] = array();
$debugData['slb_' . $consultantSchedule['date']] = array();
if ($scheduleType == 1)//specific date
{
$startDateForCheck = clone($startDate);
$safetyLoopBreaker = 3000;
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
// $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
// $startDateForCheck->modify('+1 Day');
}
while ($startDateForCheck < $endDate && $safetyLoopBreaker >= 0) {
$debugData['strt_' . $consultantSchedule['date']][] = $startDateForCheck->format(DATE_RFC822);
$debugData['end_' . $consultantSchedule['date']][] = $endDate->format(DATE_RFC822);
$periodMarker = $startDateForCheck->format('Ym');
if (isset($availableMinByPeriodMarker[$periodMarker])) {
if ($availableMinByPeriodMarker[$periodMarker] < $durationMin) {
$Y = intdiv($periodMarker, 100);
$M = $periodMarker % 100;
$M = $M + 1;
if ($M == 13) {
$M = 1;
$Y++;
}
$startDateForCheck = new \DateTime($Y . '-' . str_pad($M, 2, '0', STR_PAD_LEFT) . '-01 ' . $consultantSchedule['startTime'] . ':00 +0000');
continue;
}
}
$safetyLoopBreaker--;
$checkingNextSlot = 0;
foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
// if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
// $startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
// $startDateForCheck->modify('+'.BuddybeeConstant::BETWEEN_SESSION_MINUTE.' Minute');
// }
$dbg = [
'loopDate' => $startDateForCheck->format('Y-m-d H:i:sP'),
'loopDateTs' => $startDateForCheck->format('U'),
'weekDate' => $startDateForCheck->format('N'),
// 'dow' => $dow,
'skipDateTimeStart' => $skidDTS->format('Y-m-d H:i:sP'),
'skipDateTimeStartTs' => $skidDTS->format('U'),
'skipDateTimeEnd' => $skipDateTimeEnd[$key_DTS]->format('Y-m-d H:i:sP'),
'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
// 'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
'consultantScheduleStartAtTime' => $consultantScheduleStartAtTime->format('Y-m-d H:i:sP'),
// 'consultantScheduleEndAtTime' => $consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleUpToDate' => $consultantScheduleUpToDate->format('Y-m-d H:i:s'),
// 'in' => in_array($startDateForCheck->format('N'), $dow)
];
if ($startDateForCheck >= $skidDTS && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
$dbg['found'] = 1;
$startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
$startDateForCheck->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$startDateForCheck->setTimezone(new \DateTimeZone($consultantTimeZone));
$dbg['modifiedStart'] = $startDateForCheck->format('Y-m-d H:i:sP');
$debugData[] = $dbg;
$hasAtleastOneSchedule = 1;
$checkingNextSlot = 1;
// break;
} else {
if ($checkingNextSlot == 1)
break;
}
// $debugData[] =$dbg;
}
if ($startDateForCheck >= $consultantScheduleUpToDate) {
$safetyLoopBreaker = 0;
break;
}
$supposedEndDt = clone($startDateForCheck);
$supposedEndDt->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$supposedEndDt->modify('+' . $durationMin . ' Minute');
// if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck < $consultantScheduleEndAtTime )
if ($startDateForCheck >= $consultantScheduleStartAtTime && $supposedEndDt <= $consultantScheduleEndAtTime) {
if ($hasAtleastOneSchedule == 0) {
$startDateForCheckNew = clone($consultantScheduleStartAtTime);
$supposedEndDt = clone($startDateForCheckNew);
$supposedEndDt->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$supposedEndDt->modify('+' . $durationMin . ' Minute');
if ($startDateForCheckNew >= $startDate && $supposedEndDt <= $consultantScheduleEndAtTime) {
$startDateForCheck = $startDateForCheckNew;
$timeUnix = $startDateForCheck->format('U');
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $timeUnix,
'mon' => $startDateForCheck->format('m'),
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
$hasAtleastOneSchedule = 1;
if ($singleFlag == 1) {
$safetyLoopBreaker = 0;
break;
}
if ($closestDateTs > $timeUnix || $closestDateTs == 0)
$closestDateTs = $timeUnix;
}
} else {
$timeUnix = $startDateForCheck->format('U');
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $timeUnix,
'mon' => $startDateForCheck->format('m'),
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
$hasAtleastOneSchedule = 1;
if ($singleFlag == 1) {
$safetyLoopBreaker = 0;
break;
}
if ($closestDateTs > $timeUnix || $closestDateTs == 0)
$closestDateTs = $timeUnix;
}
}
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
} else {
$startDateForCheck->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$startDateForCheck->modify('+' . $durationMin . ' Minute');
}
// $startDateForCheck->modify('+' . $durationMin . ' Minute');
}
$debugData['sLoopBreakerSpD'] = $safetyLoopBreaker;
$debugData['slb_' . $consultantSchedule['date']][] = $safetyLoopBreaker;
} else if ($scheduleType == 2)//days of week
{
$dow = $consultantSchedule['dow'];
$startDateForCheck = clone($startDate);
$safetyLoopBreaker = 3000;
$hasAtleastOneSchedule = 0;
// $debugData['strt_'.$consultantSchedule['date']] = $startDateForCheck->format(DATE_RFC822);
// $debugData['end_'.$consultantSchedule['date']] = $endDate->format(DATE_RFC822);
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleEndAtTime = new \DateTime($startDateForCheck->format('Y-m-d') . ' ' . $consultantSchedule['endTime'] . ':00 ' . $consultantTimeZone);
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
// $startDateForCheck=new \DateTime($startDateForCheck->format('Y-m-d '.' '.$consultantSchedule['startTime'].':00 '.$consultantTimeZone));
// $startDateForCheck->modify('+1 Day');
}
while ($startDateForCheck < $endDate && $safetyLoopBreaker >= 0) {
$debugData['strt_' . $consultantSchedule['date']][] = $startDateForCheck->format(DATE_RFC822);
$debugData['end_' . $consultantSchedule['date']][] = $endDate->format(DATE_RFC822);
$periodMarker = $startDateForCheck->format('Ym');
if (isset($availableMinByPeriodMarker[$periodMarker])) {
if ($availableMinByPeriodMarker[$periodMarker] < $durationMin) {
$Y = intdiv($periodMarker, 100);
$M = $periodMarker % 100;
$M = $M + 1;
if ($M == 13) {
$M = 1;
$Y++;
}
$startDateForCheck = new \DateTime($Y . '-' . str_pad($M, 2, '0', STR_PAD_LEFT) . '-01 ' . $consultantSchedule['startTime'] . ':00 +0000');
continue;
}
}
// $debugData[]=[
// 'loopDate'=>$startDateForCheck->format('Y-m-d H:i:s'),
// 'weekDate'=>$startDateForCheck->format('N'),
// 'dow'=>$dow,
// 'consultantScheduleStartAtTime'=>$consultantScheduleStartAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleEndAtTime'=>$consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleUpToDate'=>$consultantScheduleUpToDate->format('Y-m-d H:i:s'),
// 'in'=>in_array($startDateForCheck->format('N'),$dow)
// ];
$safetyLoopBreaker--;
$checkingNextSlot = 0;
foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
$dbg = [
'loopDate' => $startDateForCheck->format('Y-m-d H:i:sP'),
'loopDateTs' => $startDateForCheck->format('U'),
'weekDate' => $startDateForCheck->format('N'),
// 'dow' => $dow,
'skipDateTimeStart' => $skidDTS->format('Y-m-d H:i:sP'),
'skipDateTimeStartTs' => $skidDTS->format('U'),
'skipDateTimeEnd' => $skipDateTimeEnd[$key_DTS]->format('Y-m-d H:i:sP'),
'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
// 'skipDateTimeEndTs' => $skipDateTimeEnd[$key_DTS]->format('U'),
'consultantScheduleStartAtTime' => $consultantScheduleStartAtTime->format('Y-m-d H:i:sP'),
// 'consultantScheduleEndAtTime' => $consultantScheduleEndAtTime->format('Y-m-d H:i:s'),
// 'consultantScheduleUpToDate' => $consultantScheduleUpToDate->format('Y-m-d H:i:s'),
// 'in' => in_array($startDateForCheck->format('N'), $dow)
];
if ($startDateForCheck >= $skidDTS && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
$dbg['found'] = 1;
$startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
$startDateForCheck->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$startDateForCheck->setTimezone(new \DateTimeZone($consultantTimeZone));
$dbg['modifiedStart'] = $startDateForCheck->format('Y-m-d H:i:sP');
$dbg['safetyLoopBreaker'] = $safetyLoopBreaker;
$debugData[] = $dbg;
$hasAtleastOneSchedule = 1;
$checkingNextSlot = 1;
// break;
} else {
if ($checkingNextSlot == 1)
break;
}
// $debugData[] =$dbg;
}
if ($startDateForCheck >= $consultantScheduleUpToDate) {
$safetyLoopBreaker = 0;
break;
}
if (!in_array($startDateForCheck->format('N'), $dow)) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($consultantScheduleStartAtTime->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
// $startDateForCheck->modify('+1 Day');
continue;
}
$supposedEndDt = clone($startDateForCheck);
$supposedEndDt->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$supposedEndDt->modify('+' . $durationMin . ' Minute');
// if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck < $consultantScheduleEndAtTime )
if ($startDateForCheck >= $consultantScheduleStartAtTime && $supposedEndDt <= $consultantScheduleEndAtTime) {
if ($hasAtleastOneSchedule == 0) {
$startDateForCheckNew = clone($consultantScheduleStartAtTime);
$supposedEndDt = clone($startDateForCheckNew);
$supposedEndDt->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$supposedEndDt->modify('+' . $durationMin . ' Minute');
if ($startDateForCheckNew >= $startDate && $supposedEndDt <= $consultantScheduleEndAtTime) {
$startDateForCheck = $startDateForCheckNew;
$timeUnix = $startDateForCheck->format('U');
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'safetyLoopBreaker' => $safetyLoopBreaker,
'timeUnix' => $timeUnix,
'mon' => $startDateForCheck->format('m'),
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
$hasAtleastOneSchedule = 1;
if ($singleFlag == 1) {
$safetyLoopBreaker = 0;
break;
}
if ($closestDateTs > $timeUnix || $closestDateTs == 0)
$closestDateTs = $timeUnix;
}
} else {
$timeUnix = $startDateForCheck->format('U');
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $timeUnix,
'mon' => $startDateForCheck->format('m'),
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
$hasAtleastOneSchedule = 1;
if ($singleFlag == 1) {
$safetyLoopBreaker = 0;
break;
}
if ($closestDateTs > $timeUnix || $closestDateTs == 0)
$closestDateTs = $timeUnix;
}
}
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
} else {
$startDateForCheck->modify('+' . BuddybeeConstant::BETWEEN_SESSION_MINUTE . ' Minute');
$startDateForCheck->modify('+' . $durationMin . ' Minute');
}
}
$debugData['sLoopBreaker'] = $safetyLoopBreaker;
$debugData['slb_' . $consultantSchedule['date']][] = $safetyLoopBreaker;
} else if ($scheduleType == 3)//Exclude date
{
$startDateForCheck = clone($startDate);
$safetyLoopBreaker = 3000;
while ($startDateForCheck < $endDate && $safetyLoopBreaker >= 0) {
$safetyLoopBreaker--;
foreach ($skipDateTimeStart as $key_DTS => $skidDTS) {
if ($startDateForCheck >= $skipDateTimeStart && $startDateForCheck <= $skipDateTimeEnd[$key_DTS]) {
$startDateForCheck = clone($skipDateTimeEnd[$key_DTS]);
}
}
if ($startDateForCheck >= $consultantScheduleUpToDate) {
$safetyLoopBreaker = 0;
break;
}
if ($startDateForCheck >= $consultantScheduleStartAtTime && $startDateForCheck <= $consultantScheduleEndAtTime) {
$availableSchedule = [
'time' => $startDateForCheck->format('Y-m-d h:i:s'),
'timeUnix' => $startDateForCheck->format('U'),
'timeRfc' => $startDateForCheck->format(DATE_RFC822),
];
$schedulesList[] = $availableSchedule;
if ($singleFlag == 1) {
$safetyLoopBreaker = 0;
break;
}
}
if ($startDateForCheck >= $consultantScheduleEndAtTime) {
$consultantScheduleStartAtTime->modify('+1 Day');
$consultantScheduleEndAtTime->modify('+1 Day');
$startDateForCheck = new \DateTime($startDateForCheck->format('Y-m-d ' . ' ' . $consultantSchedule['startTime'] . ':00 ' . $consultantTimeZone));
$startDateForCheck->modify('+1 Day');
} else
$startDateForCheck->modify('+' . $durationMin . ' Minute');
}
}
if ($dateAllowed == 1) {
}
}
$em->flush();
}
// return [$schedulesList,$consultantSchedules,$debugData];
return [
'scheduleList' => $schedulesList,
'closestDateTs' => $closestDateTs,
'defaultselection' => $defaultselection,
'durationMin' => $durationMin,
'startDate' => $startDate->format(DATE_RFC822),
'availableMinByPeriodMarker' => $availableMinByPeriodMarker,
'currentSelectionId' => $currentSelection,
'sessionDurationData' => $sessionDurationData,
'debugData' => $debugData,
'consultantSchedules' => $consultantSchedules,
];
}
public static function ConfirmConsultancySchedule($em, $confirmStatus = 0, $meetingId = 0, $newConsultantId = 0, $newStudentId = 0, $confirmType = '_CONSULTANT_', $redeemAction = 0)
{
// $options['extendOnly'] = 1;
// $options['sessionCount'] = 1;
$new = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')->findOneBy(array(
'sessionId' => $meetingId
));
$studentId = $newStudentId == 0 ? $new->getStudentId() : $newStudentId;
$newSessionCount = $new->getEquivalentSessionCount();
$redeemableSessionCount = 1 * $new->getRedeemSessionCount();
if ($confirmType == '_STUDENT_')
$new->setScheduleConfirmedByStudent($confirmStatus);
else if ($confirmType == '_CONSULTANT_')
$new->setScheduleConfirmedByConsultant($confirmStatus);
else {
$new->setScheduleConfirmedByStudent($confirmStatus);
$new->setScheduleConfirmedByConsultant($confirmStatus);
}
$em->persist($new);
$em->flush();
$meetingSessionId = $new->getSessionId();
if ($confirmStatus == 1) {
if ($redeemAction == 1) {
Buddybee::AddBalanceGeneral(
$em,
$studentId, ///id
0, //amount
$redeemableSessionCount
);
$em->remove($new);
$em->flush();
return array(
'success' => true,
'errorCode' => '_SUCCESS_REDEEM_',
'redeemedSessionCount' => $redeemableSessionCount,
'newConsumedSessionCount' => 0,
'message' => 'Action Completed.',
'scheduledTimeTs' => $new->getScheduledTimeTs(),
);
}
} else {
// $scheduledStartTime->setTimezone(new \DateTimeZone('UTC'));
// $scheduledEndTime->setTimezone(new \DateTimeZone('UTC'));
//$new->setScheduledTime($request->request->get('setScheduledTime'));
return array(
'success' => true,
'errorCode' => '_SUCCESS_RESCHEDULE_',
'redeemedSessionCount' => $redeemableSessionCount,
'newConsumedSessionCount' => $newSessionCount,
'message' => 'Action Completed.',
'scheduledTimeTs' => $new->getScheduledTimeTs(),
);
}
}
public static function CheckIfScheduleCanBeConfirmed($em, $consultantId, $studentId, $scheduledTimeTs = '', $durationMin = 90, $deleteThisTempBooking = 0)
{
//start end dates and respose dats are all with time zones or UTC and ideally the UTC time stamps
// $scheduledTimeTs = $startDate->format('U');
MiscActions::RemoveExpiredTemporaryBookings($em);
$existingBookedSchedules = $em->getRepository('CompanyGroupBundle\\Entity\\EntityTemporaryBooking')
->createQueryBuilder('m')
->where("m.consultantId = :consultantId")
->andwhere("(m.studentId = :studentId or m.studentId=0)")
->andWhere("m.scheduledTimeTs = :startAt")
->andWhere("m.durationAllowedMin <= :durationAllowedMin")
->setParameter('consultantId', $consultantId)
->setParameter('studentId', $studentId)
->setParameter('startAt', $scheduledTimeTs)
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
->setParameter('durationAllowedMin', $durationMin)
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->getResult();
$result = false;
if (empty($existingBookedSchedules))
return false;
else {
$result = true;
if ($deleteThisTempBooking == 1) {
foreach ($existingBookedSchedules as $existingBookedSchedule)
$em->remove($existingBookedSchedule);
$em->flush();
}
}
return $result;
}
public static function AddBeeCardTemporaryBooking($em, $cardIds = [], $cardOptionsByCoinCount = [], $retailerId = 0, $applicantIdId = 0, $createIfNeeded = 0)
{
MiscActions::RemoveExpiredTemporaryBookingsOnBeeCard($em);
$currDate = new \DateTime();
$bookingExpireDate = new \DateTime();
$bookingExpireDate->modify('+15 minute');
$bookingExpireTs = $bookingExpireDate->format('U');
$bookingAllowed = 0;
$data = array(
'success' => false,
);
$cardEntityByCoinCount = array();
$cardDataByCoinCount = array();
$bookedCardIdsByCoinCount = array();
$bookedCardCountByCoinCount = array();
$queriedCardCountByCoinCount = array();
$missingCardFlagByCoinCount = array();
$bookedCardIds = array();
if (!empty($cardIds)) {
$bookingAllowed = 1;
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->createQueryBuilder('m')
->where("m.retailerId = :retailerId")
->andwhere("(m.id in (:ids)")
->andWhere("(m.isTemporaryBooked = 0 or m.isTemporaryBooked is null)")
->andWhere("(m.isClaimed = 0 or m.isClaimed is null)")
->andWhere("m.expireTs < :currTs")
->setParameter('retailerId', $retailerId)
->setParameter('ids', implode(',', $cardIds))
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
->setParameter('currTs', $currDate->format('U'))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->getQuery()
->getResult();
foreach ($cards as $card) {
if (!isset($cardEntityByCoinCount[$card->getCoinCount()]))
$cardEntityByCoinCount[$card->getCoinCount()] = array();
if (!isset($queriedCardCountByCoinCount[$card->getCoinCount()]))
$queriedCardCountByCoinCount[$card->getCoinCount()] = 0;
$cardEntityByCoinCount[$card->getCoinCount()][] = $card;
$queriedCardCountByCoinCount[$card->getCoinCount()] = (1 * $queriedCardCountByCoinCount[$card->getCoinCount()]) + 1;
}
if (count($cardIds) != count($cards)) {
$bookingAllowed = 0;
$data['success'] = false;
}
if ($bookingAllowed == 1) {
$data['success'] = true;
foreach ($cardEntityByCoinCount as $coinCount => $entityList) {
if (!isset($bookedCardIdsByCoinCount[$coinCount]))
$bookedCardIdsByCoinCount[$coinCount] = array();
if (!isset($bookedCardCountByCoinCount[$coinCount]))
$bookedCardCountByCoinCount[$coinCount] = count($entityList);
foreach ($entityList as $crd) {
$crd->setBookingExpireTs($bookingExpireTs);
$crd->setIsTemporaryBooked(1);
$crd->setBookedBy(1);
$bookedCardIdsByCoinCount = array();
$bookedCardCountByCoinCount = array();
}
}
$em->flush();
}
} else {
$bookingAllowed = 1;
foreach ($cardOptionsByCoinCount as $cpd) {
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->createQueryBuilder('m')
->where("m.retailerId = :retailerId")
->andwhere("(m.coinCount = :coinCount)")
->andWhere("(m.isTemporaryBooked = 0 or m.isTemporaryBooked is null)")
->andWhere("(m.isClaimed = 0 or m.isClaimed is null)")
->andWhere("(m.expireTs < :currTs or m.expireTs is null)")
->setParameter('retailerId', $retailerId)
->setParameter('coinCount', $cpd['coinCount'])
// ->setParameter('startAt', $startDate->format('Y-m-d h:i:s'))
->setParameter('currTs', $currDate->format('U'))
// ->setParameter('endAt', $endDate->format('Y-m-d h:i:s'))
->setMaxResults($cpd['qty'])
->getQuery()
->getResult();
foreach ($cards as $card) {
if (!isset($cardEntityByCoinCount[$card->getCoinCount()]))
$cardEntityByCoinCount[$card->getCoinCount()] = array();
if (!isset($queriedCardCountByCoinCount[$card->getCoinCount()]))
$queriedCardCountByCoinCount[$card->getCoinCount()] = 0;
$cardEntityByCoinCount[$card->getCoinCount()][] = $card;
$queriedCardCountByCoinCount[$card->getCoinCount()] = (1 * $queriedCardCountByCoinCount[$card->getCoinCount()]) + 1;
}
if ((1 * $cpd['qty']) > count($cards)) {
if ($createIfNeeded == 1) {
$generateOptions = [
'amount' => isset($cpd['amount']) ? $cpd['amount'] : 0,
'coinCount' => $cpd['coinCount'],
'cardCount' => ((1 * $cpd['qty']) > count($cards)),
'serial' => '_AUTO_',
'pin' => '_AUTO_',
'useCount' => 1,
'retailerId' => $retailerId,
];
$generatedData = MiscActions::GenerateBeeCode($em, $generateOptions);
foreach ($generatedData['data'] as $cardDt) {
$card = $cardDt['cardEntityObj'];
if (!isset($cardEntityByCoinCount[$card->getCoinCount()]))
$cardEntityByCoinCount[$card->getCoinCount()] = array();
if (!isset($queriedCardCountByCoinCount[$card->getCoinCount()]))
$queriedCardCountByCoinCount[$card->getCoinCount()] = 0;
$cardEntityByCoinCount[$card->getCoinCount()][] = $card;
$cards[] = $card;
$queriedCardCountByCoinCount[$card->getCoinCount()] = (1 * $queriedCardCountByCoinCount[$card->getCoinCount()]) + 1;
}
}
}
if ((1 * $cpd['qty']) > count($cards)) {
$bookingAllowed = 0;
$data['success'] = false;
}
}
if ($bookingAllowed == 1) {
$data['success'] = true;
foreach ($cardEntityByCoinCount as $coinCount => $entityList) {
if (!isset($bookedCardIdsByCoinCount[$coinCount]))
$bookedCardIdsByCoinCount[$coinCount] = array();
if (!isset($bookedCardCountByCoinCount[$coinCount]))
$bookedCardCountByCoinCount[$coinCount] = count($entityList);
foreach ($entityList as $crd) {
$crd->setBookingExpireTs($bookingExpireTs);
$crd->setIsTemporaryBooked(1);
$crd->setBookedBy(1);
$bookedCardIdsByCoinCount[$coinCount][] = $crd->getId();
$bookedCardIds[] = $crd->getId();
}
}
$em->flush();
}
}
$data['bookedCardIdsByCoinCount'] = $bookedCardIdsByCoinCount;
$data['bookedCardCountByCoinCount'] = $bookedCardCountByCoinCount;
$data['bookedCardIds'] = $bookedCardIds;
return $data;
}
public static function AddTemporaryBooking($em, $topicId, $scheduledStartTimeTs, $consultantId, $studentId, $duration, $forcedSchdeuleDt = '')
{
MiscActions::RemoveExpiredTemporaryBookings($em);
$new = new EntityTemporaryBooking();
$new->setTopicId($topicId);
$new->setConsultantId($consultantId);
$new->setStudentId($studentId);
if ($scheduledStartTimeTs == 0 || $scheduledStartTimeTs == '') {
if ($forcedSchdeuleDt != '') {
$forcedSchdeuleDtime = new \DateTime($forcedSchdeuleDt);
$scheduledStartTimeTs = $forcedSchdeuleDtime->format('U');
}
}
$scheduledStartTime = new \DateTime('@' . $scheduledStartTimeTs);
$scheduledEndTime = new \DateTime('@' . $scheduledStartTimeTs);
$scheduledEndTime = $scheduledEndTime->modify('+' . $duration . ' minute');
$new->setScheduledTime($scheduledStartTime);
$new->setDurationAllowedMin($duration);
$new->setSessionExpireDate($scheduledEndTime);
$new->setSessionExpireDateTs($scheduledEndTime->format('U'));
$new->setScheduledTime($scheduledStartTime);
$new->setScheduledTimeTs($scheduledStartTime->format('U'));
$currentUnixTime = new \DateTime();
if ($studentId == 0)
$currentUnixTime->modify('+5 Minute');
else
$currentUnixTime->modify('+10 Minute');
$bookingExpiresTs = $currentUnixTime->format('U');
$new->setBookingExpiresTs($bookingExpiresTs);
$em->persist($new);
$em->flush();
$periodMarker = $scheduledStartTime->format('Ym');
MiscActions::UpdateSchedulingRestrictions($em, $consultantId, $periodMarker, 0, (($duration) / 60));
// return $new->getBookingId();
return array(
'bookingId' => $new->getBookingId(),
'ts' => $new->getScheduledTimeTs(),
);
}
public static function GetDashboardDataForApplicant($em, $applicantId, $markerHash = '_STUDENT_')
{
$data = [];
$applicantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array
(
'applicantId' => $applicantId
)
);
if ($markerHash == '_CONSULTANT_') {
///earned this month
$currDateNow = new \DateTime();
$thisMonthFirstDateStr = $currDateNow->format('Y-m-') . '01 00:00:00';
$nextMmonthFirstDate = new \DateTime();
$nextMmonthFirstDate->modify('first day of next month');
$nextMonthFirstDateStr = $nextMmonthFirstDate->format('Y-m-d') . ' 00:00:00';
// $currDateNow = new \DateTime();
// $currDateNow->modify('-365 Day');
$stmt = $em->getConnection()->fetchAllAssociative("select sum(amount) total_amount FROM `entity_invoice` WHERE applicant_id = $applicantId and invoice_type=5 and amount_type in (0,1)
and created_at <'$nextMonthFirstDateStr' and created_at>='$thisMonthFirstDateStr'");
$query_output = $stmt;
$data['earnedThisMonth'] = isset($query_output[0]) ? $query_output[0]['total_amount'] : 0;
}
return $data;
}
public static function GetDocumentDataForBuddybeeApplicant($em, $applicantId, $topicId = 0, $semesterIdsData = [], $sort = '_DEFAULT_', $outputAs = 'object')
{
$data = array(
'hasMissingDoc' => 0,
'hasExpiredDoc' => 0,
'documentList' => [],
'documentListByStatus' => [],
'documentListObj' => null,
'documentDataByTopicId' => [],
);
$documentList = [];
$documentListObj = [];
$hasMissingDoc = 0;
$hasExpiredDoc = 0;
$documentListByStatus = [];
$applicantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array
(
'applicantId' => $applicantId
)
);
if ($applicantDetails) {
$toGetDocumentIds = [];
$stagesArray = [];
$documentByStages = [];
$studentDocData = json_decode($applicantDetails->getDocumentList(), true);
if ($studentDocData == null) $studentDocData = [];
foreach ($studentDocData as $did => $dt) {
if (!in_array($did, $toGetDocumentIds))
$toGetDocumentIds[] = $did;
}
$documentDataByTopicId = [];
$documentDataByTopicIdArray = [];
//$topicId = $id;
$topics = [];
$documentListFindData = [];
$documentListFindData = [];
$topicDocumentList = [];
if ($topicId != 0) {
$topics = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findBy(
array(
'id' => $topicId
)
);
$toGetDocumentIds = [];
foreach ($topics as $topic) {
$topicDocumentData = json_decode($topic->getDocumentData(), true);
if ($topicDocumentData == null) $topicDocumentData = [];
foreach ($topicDocumentData as $did => $dt) {
if (!in_array($dt['document'], $toGetDocumentIds))
$toGetDocumentIds[] = $dt['document'];
}
}
$documentListFindData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
array(
'Id' => $toGetDocumentIds
)
);
} else {
$documentListFindData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
array()
);
}
$currDateTime = new \DateTime();
$currDateTimeStr = $currDateTime->format('Y-m-d');
$currentNow = time();
foreach ($documentListFindData as $did => $document) {
$chkList = json_decode($document->getCheckList(), true);
if ($chkList == null) $chkList = [];
$expireDate = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docExpiryDate'] : '';
$expiredFlag = 2; //pending
if ($expireDate != '') {
$expireDateTime = new \DateTime($expireDate);
if ($expireDateTime <= $currDateTime)
$expiredFlag = 1;
else
$expiredFlag = 0;
}
if ($expiredFlag == 1)
$hasExpiredDoc = 1;
$evaluationStatus = 0; //pending
$evaluationComment = [];
if (isset($studentDocData[$document->getId()])) {
if (isset($studentDocData[$document->getId()]['evaluationStatus']))
$evaluationStatus = $studentDocData[$document->getId()]['evaluationStatus'];
if (isset($studentDocData[$document->getId()]['evaluationComment']))
$evaluationComment = $studentDocData[$document->getId()]['evaluationComment'];
}
$docImage = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docImage'] : '';
$documentStatus = 0;// required or not uploaded
if ($docImage != '') {
if ($expiredFlag == 1)
$documentStatus = 0;
else {
if ($evaluationStatus == 1)
$documentStatus = 1;/// complete
else
$documentStatus = 2;/// Pending
}
}
if ($documentStatus == 0)
$hasMissingDoc = 1;
$docData = array(
'docId' => $document->getId(),
'docName' => $document->getDocumentName(),
'docExpiryDays' => $document->getExpiryDays(),
'docExpiryDate' => $expireDate,
'minEtaDate' => $currDateTimeStr,
'minEtaDays' => 0,
'docExpiredFlag' => $expiredFlag,
'docImage' => $docImage,
'documentStatus' => $documentStatus,
'evaluationStatus' => $evaluationStatus,
'evaluationComment' => $evaluationComment,
'processingDays' => $document->getProcessingDays(),
'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
'docChecklist' => $chkList,
'docAcquiredChecklist' => isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docCheckList'] : [],
);
$documentList[] = $docData;
$documentListObj[$document->getId()] = $docData;
}
if ($topicId != 0) {
foreach ($topics as $topic) {
$topicDocumentData = json_decode($topic->getDocumentData(), true);
if ($topicDocumentData == null) $topicDocumentData = [];
$docDataForThisTopic = [];
$minEtaThisTopic = clone($currDateTime);
$minEtaStrThisTopic = $currDateTimeStr;
if (!empty($semesterIdsData))
if (isset($semesterIdsData[$topic->getId()])) {
$topicSemesterData = json_decode($topic->getSessionData(), true);
if ($topicSemesterData == null) $topicSemesterData = [];
foreach ($topicSemesterData as $topicSemester) {
if (in_array($topicSemester['sessionId'], $semesterIdsData[$topic->getId()])) {
$thresholdThisSemester = new \DateTime($topicSemester['threshold']);
if ($thresholdThisSemester < $minEtaThisTopic) {
$minEtaThisTopic = clone($thresholdThisSemester);
$minEtaStrThisTopic = $thresholdThisSemester->format('Y-m-d');
}
}
}
}
foreach ($topicDocumentData as $did => $dt) {
if (isset($documentListObj[$dt['document']])) {
$docData = $documentListObj[$dt['document']];
$currMinEtaDoc = new \DateTime($docData['minEtaDate']);
if ($docData['docExpiryDays'] == '')
$docData['docExpiryDays'] = $dt['expDays'];
$docData['stage'] = $dt['stage'];
$thresholdDaysOffsetForThis = isset($dt['thresholdDaysOffset']) ? 1 * $dt['thresholdDaysOffset'] : 0;
$minEtaThisTopicThisDoc = clone $minEtaThisTopic;
if ($thresholdDaysOffsetForThis > 0)
$minEtaThisTopicThisDoc->modify('-' . $thresholdDaysOffsetForThis . ' day');
if ($minEtaThisTopicThisDoc < $currMinEtaDoc) {
$docData['minEtaDate'] = $minEtaThisTopicThisDoc->format('Y-m-d');
$now = time(); // or your date as well
$eta_date = strtotime($minEtaThisTopicThisDoc->format('Y-m-d'));
$etaDays = (($eta_date - $currentNow) / (60 * 60 * 24));
$docData['minEtaDays'] = $etaDays;
$documentListObj[$dt['document']]['minEtaDate'] = $minEtaThisTopicThisDoc->format('Y-m-d');;
$documentListObj[$dt['document']]['minEtaDays'] = $etaDays;
}
$docData['emergencyProcessingDays'] = $dt['emergencyProcessingDays'];
$docData['generalProcessingDays'] = $dt['generalProcessingDays'];
$docData['docChecklist'] = $dt['checklist'];
$docDataForThisTopic[] = $docData;
}
}
$documentDataByTopicId[$topic->getId()] = $docDataForThisTopic;
}
}
if ($sort == '_BY_STATUS_') {
$documentListByStatus[0] = array(
'hashed_topic_ids' => '',
'docList' => []
);
foreach ($documentListObj as $doc) {
if ($doc['documentStatus'] == 0) {
$documentListByStatus[0]['docList'][] = $doc;
}
}
$documentListByStatus[1] = array(
'hashed_topic_ids' => '',
'docList' => []
);
foreach ($documentListObj as $doc) {
if ($doc['documentStatus'] == 1) {
$documentListByStatus[1]['docList'][] = $doc;
}
}
$documentListByStatus[2] = array(
'hashed_topic_ids' => '',
'docList' => []
);
foreach ($documentListObj as $doc) {
if ($doc['documentStatus'] == 2) {
$documentListByStatus[2]['docList'][] = $doc;
}
}
}
$data = [
'hasMissingDoc' => $hasMissingDoc,
'hasExpiredDoc' => $hasExpiredDoc,
'documentList' => $documentList,
'documentListByStatus' => $documentListByStatus,
'documentListObj' => $documentListObj,
'documentDataByTopicId' => $documentDataByTopicId,
];
}
return $data;
}
public static function GetDocumentDataForBuddybeeConsultantApply($em, $applicantId, $countryId = 0, $sort = '_DEFAULT_', $outputAs = 'object')
{
$data = [];
$applicantDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array
(
'applicantId' => $applicantId
)
);
$toGetDocumentIds = [];
$studentDocData = json_decode($applicantDetails->getDocumentList(), true);
if ($studentDocData == null) $studentDocData = [];
foreach ($studentDocData as $did => $dt) {
if (!in_array($did, $toGetDocumentIds))
$toGetDocumentIds[] = $did;
}
$documentDataByTopicId = [];
$documentDataByTopicIdArray = [];
//$topicId = $id;
$topics = [];
$documentListFindData = [];
$documentList = [];
$documentListObj = [];
$documentListFindData = [];
$topicDocumentList = [];
if ($countryId != 0) {
$topics = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCountryConsultantRequirements')->findBy(
array(
'countryId' => $countryId
)
);
$toGetDocumentIds = [];
foreach ($topics as $topic) {
$topicDocumentList = json_decode($topic->getDocumentList(), true);
if ($topicDocumentList == null) $topicDocumentList = [];
foreach ($topicDocumentList as $did => $dt) {
if (!in_array($dt['document'], $toGetDocumentIds))
$toGetDocumentIds[] = $dt['document'];
}
}
$documentListFindData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
array(
'Id' => $toGetDocumentIds
)
);
} else {
$documentListFindData = $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findBy(
array()
);
}
$currDateTime = new \DateTime();
foreach ($documentListFindData as $did => $document) {
$chkList = json_decode($document->getCheckList(), true);
if ($chkList == null) $chkList = [];
$expireDate = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docExpiryDate'] : '';
$expiredFlag = 2; //pending
if ($expireDate != '') {
$expireDateTime = new \DateTime($expireDate);
if ($expireDateTime <= $currDateTime)
$expiredFlag = 1;
else
$expiredFlag = 0;
}
$evaluationStatus = 0; //pending
$evaluationComment = [];
if (isset($studentDocData[$document->getId()])) {
if (isset($studentDocData[$document->getId()]['evaluationStatus']))
$evaluationStatus = $studentDocData[$document->getId()]['evaluationStatus'];
if (isset($studentDocData[$document->getId()]['evaluationComment']))
$evaluationComment = $studentDocData[$document->getId()]['evaluationComment'];
}
$docImage = isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docImage'] : '';
$documentStatus = 0;// required or not uploaded
if ($docImage != '') {
if ($expiredFlag == 1)
$documentStatus = 0;
else {
if ($evaluationStatus == 1)
$documentStatus = 1;/// complete
else
$documentStatus = 2;/// Pending
}
}
$docData = array(
'docId' => $document->getId(),
'docName' => $document->getDocumentName(),
'docExpiryDays' => $document->getExpiryDays(),
'docExpiryDate' => $expireDate,
'docExpiredFlag' => $expiredFlag,
'docImage' => $docImage,
'documentStatus' => $documentStatus,
'evaluationStatus' => $evaluationStatus,
'evaluationComment' => $evaluationComment,
'processingDays' => $document->getProcessingDays(),
'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
'docChecklist' => $chkList,
'docAcquiredChecklist' => isset($studentDocData[$document->getId()]) ? $studentDocData[$document->getId()]['docCheckList'] : [],
);
$documentList[] = $docData;
$documentListObj[$document->getId()] = $docData;
}
if ($countryId != 0) {
foreach ($topics as $topic) {
$topicDocumentData = json_decode($topic->getDocumentList(), true);
if ($topicDocumentData == null) $topicDocumentData = [];
$docDataForThisTopic = [];
foreach ($topicDocumentData as $did => $dt) {
if (isset($documentListObj[$dt['document']])) {
$docData = $documentListObj[$dt['document']];
$docDataForThisTopic[] = $docData;
}
}
$documentDataByTopicId[$topic->getCountryId()] = $docDataForThisTopic;
}
}
$data = [
'documentList' => $documentList,
'documentListObj' => $documentListObj,
'documentDataByTopicId' => $documentDataByTopicId,
];
return $data;
}
public static function ModifyDocumentStatus($em, $applicantId, $documentId, $toSetStatus = 1, $topicId = 0, $comment = '')
{
$user = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $applicantId
));
$docData = json_decode($user->getDocumentList(), true);
$docDataByTopicId = json_decode($user->getDocumentListByTopicId(), true);
if ($docData == null) $docData = [];
if ($docDataByTopicId == null) $docDataByTopicId = [];
if (isset($docData[$documentId])) {
$docData[$documentId]['evaluationStatus'] = $toSetStatus;
if (!isset($docData[$documentId]['evaluationComment']))
$docData[$documentId]['evaluationComment'] = [];
$docData[$documentId]['evaluationComment'][] = $comment;
}
if (isset($docDataByTopicId[$topicId])) {
if (isset($docDataByTopicId[$topicId][$documentId])) {
$docDataByTopicId[$topicId][$documentId]['evaluationStatus'] = $toSetStatus;
if (!isset($docDataByTopicId[$topicId][$documentId]['evaluationComment']))
$docDataByTopicId[$topicId][$documentId]['evaluationComment'] = [];
$docDataByTopicId[$topicId][$documentId]['evaluationComment'][] = $comment;
}
}
$user->setDocumentList(json_encode($docData));
$user->setDocumentListByTopicId(json_encode($docDataByTopicId));
$em->flush();
return true;
}
public static function RefreshBuddybeeBalanceOnSession($em, $session)
{
if ($session->has(UserConstants::USER_ID)) {
if ($session->get(UserConstants::USER_ID) != 0) {
if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
$user = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $session->get(UserConstants::USER_ID)
));
$session->set('BUDDYBEE_BALANCE', 1 * $user->getAccountBalance());
$session->set('BUDDYBEE_COIN_BALANCE', 1 * $user->getSessionCountBalance());
}
}
}
return $session;
}
public static function ConvertCurrentUserToAdmin($em, $session, $level = 1)
{
if ($session->has(UserConstants::USER_ID)) {
if ($session->get(UserConstants::USER_ID) != 0) {
if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
$user = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $session->get(UserConstants::USER_ID)
));
$user->setIsAdmin(1);
$user->setAdminLevel($level);
$em->flush();
$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);
}
}
}
return $session;
}
public static function GetDtDataAjax($em, $method = 'GET', $postData = [], $companyId = 0, $kernelRoot = '')
{
$entityConfig = [];
if ($postData->has('config')) {
$entityConfig = $postData->get('config');
}
// System::log_it($kernelRoot,json_encode( $entityConfig),'entityConfig',0);
$Transaction = [];
$dt_list = [];
$response = [];
$skipColumnNames = isset($entityConfig['skipColumnNames']) ? $entityConfig['skipColumnNames'] : [];
$flagColNames = isset($entityConfig['flagColNames']) ? $entityConfig['flagColNames'] : [];
$flagConversionByCols = isset($entityConfig['flagConversionByCols']) ? $entityConfig['flagConversionByCols'] : [];
$draftFlagList = array(
'' => '',
'0' => 'No',
'1' => 'Yes',
);
$stageFlagList = array(
0 => 'Pending',
'' => '',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$approvedFlagList = array(
0 => 'Declined',
'' => '',
1 => 'Approved',
2 => 'Reverted',
3 => 'Pending',
4 => 'Forwarded',
);
if ($method == 'POST') {
$getUnitListFlag = 1;
if ($postData->has('columns') || $postData->has('pageNumber')) {
$draw = intval($postData->get('draw'));
$start = $postData->has('start') ? $postData->get('start') : ($postData->get('pageNumber') - 1) * $postData->get('pageSize');
$length = $postData->has('length') ? $postData->get('length') : $postData->get('pageSize');
$search = $postData->has('search') ? $postData->get('search') : '';
$orders = $postData->has('order') ? $postData->get('order') : (isset($entityConfig['order']) ? $entityConfig['order'] : []);
$joinOrders = $postData->has('joinOrder') ? $postData->get('joinOrder') : (isset($entityConfig['joinOrder']) ? $entityConfig['joinOrder'] : []);
$columns = $postData->has('columns') ? $postData->get('columns') : (isset($entityConfig['columns']) ? $entityConfig['columns'] : []);
$getUnitListFlag = $postData->has('getUnitListFlag') ? $postData->get('getUnitListFlag') : 1;
// Orders
foreach ($orders as $key => $order) {
$orders[$key]['name'] = $columns[$order['column']]['name'];
}
foreach ($joinOrders as $key => $order) {
$orders[array_key_last($orders) + 1] = $order;
}
// Get results from the Repository
$results = $em->getRepository(str_replace(':', '\\Entity\\', $entityConfig['mainTableClass']))->getRequiredDTData($em, $entityConfig, $start, $length, $orders,
$search, $columns, $skipColumnNames, $flagColNames, $flagConversionByCols);
$objects = $results["results"];
// $total_objects_count = $em->getRepository($entityConfig['mainTableClass'])->countRel();
$total_objects_count = $results["countResult"];
$selected_objects_count = count($objects);
$filtered_objects_count = $results["countResult"];
// System::log_it($kernelRoot,json_encode( $objects),'test_dt_data',0);
$dateFieldsToStr = isset($entityConfig['dateFieldsToStr']) ? $entityConfig['dateFieldsToStr'] : [];
$otherDateFieldsToStr = isset($entityConfig['otherDateFieldsToStr']) ? $entityConfig['otherDateFieldsToStr'] : [];
$convertToObjectFields = isset($entityConfig['convertToObjectFields']) ? $entityConfig['convertToObjectFields'] : [];
$timestampFieldsToStr = isset($entityConfig['timestampFieldsToStr']) ? $entityConfig['timestampFieldsToStr'] : [];
$timestampFieldsToStrFormat = isset($entityConfig['timestampFieldsToStrFormat']) ? $entityConfig['timestampFieldsToStrFormat'] : [];
$dateFieldsToStrFormat = isset($entityConfig['dateFieldsToStrFormat']) ? $entityConfig['dateFieldsToStrFormat'] : [];
$otherDateFieldsToStrFormat = isset($entityConfig['otherDateFieldsToStrFormat']) ? $entityConfig['otherDateFieldsToStrFormat'] : [];
$joinTableList = isset($entityConfig['joinTableList']) ? $entityConfig['joinTableList'] : [];
$encryptedDataList = isset($entityConfig['encryptedDataList']) ? $entityConfig['encryptedDataList'] : [];
if (empty($joinTableList)) {
foreach ($objects as $pq) {
$p = $pq;
$d = $pq;
$d[$entityConfig['mainTableAlias']] = $pq;
foreach ($convertToObjectFields as $key_ind => $convertToObjectField) //for now main table only
{
$curr_obj = [];
if (isset($d[$entityConfig['mainTableAlias']][$convertToObjectField]))
$curr_obj = json_decode($d[$entityConfig['mainTableAlias']][$convertToObjectField], true);
else
$curr_obj = [];
if ($curr_obj == null)
$curr_obj = [];
$d[$entityConfig['mainTableAlias']][$convertToObjectField] = $curr_obj;
}
foreach ($dateFieldsToStr as $key_ind => $dateField) //for now main table only
{
$formatForThis = isset($dateFieldsToStrFormat[$key_ind]) ? $dateFieldsToStrFormat[$key_ind] : 'm-d-Y';
// System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
// System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
$this_date = $d[$entityConfig['mainTableAlias']][$dateField];
else
$this_date = null;
$d[$entityConfig['mainTableAlias']][$dateField . 'Str'] = ($this_date == null || $this_date == '') ? '' : $this_date->format($formatForThis);
}
foreach ($encryptedDataList as $key_ind => $encryptedDataCon) //for now main table only
{
if (isset($d[$entityConfig['mainTableAlias']][$encryptedDataCon])) {
$iv = '1234567812345678';
$pass = '_enc_';
$suffix = '_enpaac_';
// {field:alias}
$str = $d[$entityConfig['mainTableAlias']][$encryptedDataCon];
$data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
$data = base64_encode($data) . '' . $suffix;
$d['encrypted_' . $encryptedDataCon] = $data;
}
}
foreach ($otherDateFieldsToStr as $key_ind => $dateField) {
$formatForThis = isset($otherDateFieldsToStrFormat[$key_ind]) ? $otherDateFieldsToStrFormat[$key_ind] : 'm-d-Y';
if (isset($d[$dateField]))
$this_date = $d[$dateField];
else
$this_date = new \DateTime();
$d[$dateField . 'Str'] = ($this_date == null || $this_date == '') ? '' : $this_date->format($formatForThis);
}
// System::log_it($kernelRoot, json_encode($otherDateFieldsToStr),'date_test_again');
foreach ($timestampFieldsToStr as $key_ind => $dateField) //for now main table only
{
$formatForThis = isset($timestampFieldsToStrFormat[$key_ind]) ? $timestampFieldsToStrFormat[$key_ind] : 'm-d-Y';
// System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
// System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
$this_date = new \DateTime('@' . $d[$entityConfig['mainTableAlias']][$dateField]);
else
$this_date = null;
$d[$entityConfig['mainTableAlias']][$dateField . 'Str'] = ($this_date == null || $this_date == '') ? '' : $this_date->format($formatForThis);
}
// $q=$pq[1];
$dt_list[] = $d;
}
} else {
foreach ($objects as $pq) {
$p = $pq[0];
$d = $pq;
$d[$entityConfig['mainTableAlias']] = $pq[0];
$d[0] = [];
foreach ($convertToObjectFields as $key_ind => $convertToObjectField) //for now main table only
{
$curr_obj = [];
if (isset($d[$entityConfig['mainTableAlias']][$convertToObjectField]))
$curr_obj = json_decode($d[$entityConfig['mainTableAlias']][$convertToObjectField], true);
else
$curr_obj = [];
if ($curr_obj == null)
$curr_obj = [];
$d[$entityConfig['mainTableAlias']][$convertToObjectField] = $curr_obj;
}
foreach ($dateFieldsToStr as $key_ind => $dateField) //for now main table only
{
$formatForThis = isset($dateFieldsToStrFormat[$key_ind]) ? $dateFieldsToStrFormat[$key_ind] : 'm-d-Y';
// System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
// System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
$this_date = $d[$entityConfig['mainTableAlias']][$dateField];
else
$this_date = null;
$d[$entityConfig['mainTableAlias']][$dateField . 'Str'] = ($this_date == null || $this_date == '') ? '' : $this_date->format($formatForThis);
}
$encData = [];
foreach ($encryptedDataList as $key_ind => $encryptedDataCon) //for now main table only
{
if (isset($d[$entityConfig['mainTableAlias']][$encryptedDataCon])) {
$iv = '1234567812345678';
$pass = '_enc_';
$suffix = '_enpaac_';
// {field:alias}
$str = $d[$entityConfig['mainTableAlias']][$encryptedDataCon];
$data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
$data = base64_encode($data) . '' . $suffix;
$d['encrypted_' . $encryptedDataCon] = $data;
// $d['encrypted_' . $encryptedDataCon] = $str;
}
}
foreach ($otherDateFieldsToStr as $key_ind => $dateField) {
$formatForThis = isset($otherDateFieldsToStrFormat[$key_ind]) ? $otherDateFieldsToStrFormat[$key_ind] : 'm-d-Y';
if (isset($d[$dateField]))
$this_date = $d[$dateField];
else
$this_date = new \DateTime();
$d[$dateField . 'Str'] = ($this_date == null || $this_date == '') ? '' : $this_date->format($formatForThis);
}
// System::log_it($kernelRoot, json_encode($otherDateFieldsToStr),'date_test_again');
foreach ($timestampFieldsToStr as $key_ind => $dateField) //for now main table only
{
$formatForThis = isset($timestampFieldsToStrFormat[$key_ind]) ? $timestampFieldsToStrFormat[$key_ind] : 'm-d-Y';
// System::log_it($kernelRoot,json_encode( $d[$entityConfig['mainTableAlias']][$dateField]),'date_test');
// System::log_it($kernelRoot,$d[$entityConfig['mainTableAlias']][$dateField]->format('m-d-Y'),'date_test_again');
if (isset($d[$entityConfig['mainTableAlias']][$dateField]))
$this_date = new \DateTime('@' . $d[$entityConfig['mainTableAlias']][$dateField]);
else
$this_date = null;
$d[$entityConfig['mainTableAlias']][$dateField . 'Str'] = ($this_date == null || $this_date == '') ? '' : $this_date->format($formatForThis);
}
// $q=$pq[1];
$dt_list[] = $d;
}
}
// Construct response
$response = array(
"draw" => $draw,
"objects" => $objects,
"unitList" => [],
"getUnitListFlag" => $getUnitListFlag,
'totalObjectsCount' => $total_objects_count,
"recordsTotal" => $total_objects_count,
"recordsFiltered" => $filtered_objects_count,
"data" => $dt_list,
"debugData" => $results['debugData']
);
}
} else {
//
// $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
// array(), array('transactionDate' => 'desc')
// );
// foreach ($Transaction as $p) {
// array_push($v_list,
// array(
// 'id' => $p->getTransactionId(),
// 'id_padded' => str_pad($p->getTransactionId(), 8, '0', STR_PAD_LEFT),
// 'doc_hash' => $p->getDocumentHash(),
// 'desc' => $p->getDescription(),
// 'date' => $p->getTransactionDate(),
// 'date_str' => $p->getTransactionDate()->format('F d, Y'),
// 'type' => $type_list[$p->getDocumentType()],
// 'amount' => $p->getTransactionAmount(),
// 'provisional' => $p->getProvisional(),
// 'ledgerHit' => $p->getLedgerHit(),
// 'approved' => $p->getApproved(),
// 'view_button' => 'view',
// 'print_button' => 'print',
// 'status' => GeneralConstant::$approvalAction[$p->getApproved()],
//// 'total_dr'=>$total_dr,
//// 'total_cr'=>$total_cr
// ));
// }
$response = array(
"draw" => 1,
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => $dt_list,
);
}
return $response;
}
public static function uploadFile($fileObj, $uplDir)
{
$path = "";
$uploadedFile = $fileObj;
{
if ($uploadedFile != null) {
$fileName = 'p' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
// $upl_dir = $uplDir;
if (!file_exists($uplDir)) {
mkdir($uplDir, 0777, true);
}
$file = $uploadedFile->move($uplDir, $path);
}
$file_list[] = $path;
$defaultImage = $path;
}
return $path;
}
public static function GetNumberHash($em, $t, $p, $a, $timestamp = '', $documentId = 0, $companyId = 0)
{
$result = [];
$t = strtoupper($t);
$entityListByTypeHash = GeneralConstant::$Entity_list_by_type_hash;
if (isset($entityListByTypeHash[$t])) {
$entityName = $entityListByTypeHash[$t];
//1st of all check if the doc exists as booked with current timestamp if yes just return the doc numberhash and change dochash if needed
if ($documentId != 0) {
$qryArray = array(
GeneralConstant::$Entity_id_field_list[array_flip(GeneralConstant::$Entity_list)[$entityName]] => $documentId,
);
$doc = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
->findOneBy(
$qryArray,
array()
);
if ($doc) {
//doc found so refresh the doc has if neeeded other wise return the number hash
if ($doc->getTypeHash() == $t && $doc->getPrefixHash() == $p && $doc->getAssocHash() == $a) {
return $doc->getNumberHash();
}
}
}
if ($timestamp != '') {
$qryArray = array(
// 'typeHash' => $t,
// 'prefixHash' => $p,
// 'assocHash' => $a,
'timeStampOfForm' => $timestamp,
'docBookedFlag' => 1,
'CompanyId' => $companyId,
);
$doc = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
->findOneBy(
$qryArray,
array(
'numberHash' => 'DESC'
)
);
if ($doc) {
//doc found so refresh the doc has if neeeded other wise return the number hash
if ($doc->getTypeHash() == $t && $doc->getPrefixHash() == $p && $doc->getAssocHash() == $a) {
return $doc->getNumberHash();
} else {
$result = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
->findOneBy(
array(
'typeHash' => $t,
'prefixHash' => $p,
'assocHash' => $a,
),
array(
'numberHash' => 'DESC'
)
);
$numberhash = 1;
if ($result) {
$numberhash = 1 + (1 * $result->getNumberhash());
} else {
}
$doc->setTypeHash($t);
$doc->setPrefixHash($p);
$doc->setAssocHash($a);
$doc->setNumberHash($numberhash);
$doc->setDocumentHash($t . '/' . $p . '/' . $a . '/' . $numberhash);
$em->flush();
return $numberhash;
}
} else {
$cname = "ApplicationBundle\\Entity\\" . $entityName;
$doc = new $cname;
$result = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
->findOneBy(
array(
'typeHash' => $t,
'prefixHash' => $p,
'assocHash' => $a,
),
array(
'numberHash' => 'DESC'
)
);
$numberhash = 1;
if ($result) {
$numberhash = 1 + (1 * $result->getNumberhash());
} else {
}
$doc->setTypeHash($t);
$doc->setPrefixHash($p);
$doc->setAssocHash($a);
$doc->setNumberHash($numberhash);
$doc->setTimeStampOfForm($timestamp);
$doc->setDocBookedFlag(1);
$doc->setCompanyId($companyId);
$doc->setDocumentHash($t . '/' . $p . '/' . $a . '/' . $numberhash);
method_exists($doc, 'setProjectId') ? $doc->setProjectId(0) : 0;
$em->persist($doc);
$em->flush();
return $numberhash;
}
} else {
$result = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
->findOneBy(
array(
'typeHash' => $t,
'prefixHash' => $p,
'assocHash' => $a,
),
array(
'numberHash' => 'DESC'
)
);
$numberhash = 1;
if ($result) {
$numberhash = 1 + (1 * $result->getNumberhash());
} else {
}
return $numberhash;
}
} else {
// if ($t == 'DO') {
// $result = $em
// ->getRepository('ApplicationBundle\\Entity\\DeliveryOrder')
// ->findBy(
// array(
// 'typeHash' => $t,
// 'prefixHash' => $p,
// 'assocHash' => $a,
// )
// );
// }
}
$max = 0;
// $debug_data='';
// $debug_data=[];
foreach ($result as $res) {
// $debug_data.=','.$res->getNumberHash();
if ((1 * $res->getNumberHash()) > $max)
$max = (1 * $res->getNumberHash());
}
// $count = count($result);
$count = $max;
$count++;
return ($count);
// return($entityListByTypeHash[$t]);
// return($debug_data);
// return(json_encode($debug_data));
}
//task related
public static function AddCashFlowProjection($em, $id = 0, $data = [])
{
$sampleData = [
'planningItemId' => 0,
'fundRequisitionId' => 0,
'concernedPersonId' => 0,
'type' => 1, //exp
'subType' => 1, //1== khoroch hobe 2: ashbe
'cashFlowType' => 1, //2== RCV /in 1: Payment/out
'creationType' => 1, //auto 2: doc 3 :manual
'entity' => 0,
'entityId' => 0,
'checkId' => 0,
'entityDocHash' => '',
'amountType' => 1, // 1:Fund/Money 2:Material 3: Bank Guarantee 4: Credit
'cashFlowAmount' => 0,
'expAstAmount' => 0,
'accumulatedCashFlowAmount' => 0,
'accumulatedCashFlowBalance' => 0,
'accumulatedExpAstAmount' => 0,
'relevantExpAstHeadId' => 0,
'balancingHeadId' => 0,
'cashFlowHeadId' => 0,
'cashFlowHeadType' => 1,
'relevantProductIds' => [],
'reminderDateTs' => 0,
'cashFlowDateTs' => 0,
'expireDateTs' => 0,
'expAstRealizationDateTs' => 0,
];
foreach ($sampleData as $index => $value) {
if (!isset($data[$index]))
$data[$index] = $value;
}
if (!isset($data['planningItemId'])) $data['planningItemId'] = 0;
if (!isset($data['fundRequisitionId'])) $data['fundRequisitionId'] = 0;
if ($id != 0)
$cf = $em
->getRepository('ApplicationBundle\\Entity\\CashFlowProjection')
->findOneBy(
array(
'id' => $id,
)
);
else if ($data['planningItemId'] != 0)
$cf = $em
->getRepository('ApplicationBundle\\Entity\\CashFlowProjection')
->findOneBy(
array(
'planningItemId' => $data['planningItemId'],
)
);
else if ($data['fundRequisitionId'] != 0)
$cf = $em
->getRepository('ApplicationBundle\\Entity\\CashFlowProjection')
->findOneBy(
array(
'fundRequisitionId' => $data['fundRequisitionId'],
)
);
else
$cf = new CashFlowProjection();
$cf->setPlanningItemId(isset($data['planningItemId']) ? $data['planningItemId'] : 0);
$cf->setFundRequisitionId(isset($data['fundRequisitionId']) ? $data['fundRequisitionId'] : 0);
$cf->setCheckId(isset($data['checkId']) ? $data['checkId'] : 0);
$cf->setType(isset($data['type']) ? $data['type'] : 1);
$cf->setSubType(isset($data['subType']) ? $data['subType'] : 1);
$cf->setCashFlowType(isset($data['cashFlowType']) ? $data['cashFlowType'] : 1);
$cf->setCreationType(isset($data['creationType']) ? $data['creationType'] : 1);
$cf->setEntity($data['entity']);
$cf->setEntityId($data['entityId']);
$cf->setCheckId($data['checkId']);
$cf->setEntityDocHash($data['entityDocHash']);
$cf->setConcernedPersonId(isset($data['concernedPersonId']) ? $data['concernedPersonId'] : 0);
$cf->setAmountType(isset($data['amountType']) ? $data['amountType'] : 1);
$cf->setcashFlowAmount(isset($data['cashFlowAmount']) ? $data['cashFlowAmount'] : 0);
$cf->setAccumulatedCashFlowAmount(isset($data['accumulatedCashFlowAmount']) ? $data['accumulatedCashFlowAmount'] : 0);
$cf->setAccumulatedCashFlowBalance(isset($data['accumulatedCashFlowBalance']) ? $data['accumulatedCashFlowBalance'] : 0);
$cf->setAccumulatedExpAstAmount(isset($data['accumulatedExpAstAmount']) ? $data['accumulatedExpAstAmount'] : 0);
$cf->setExpAstAmount(isset($data['expAstAmount']) ? $data['expAstAmount'] : 0);
$cf->setRelevantExpAstHeadId(isset($data['relevantExpAstHeadId']) ? $data['relevantExpAstHeadId'] : 0);
$cf->setRelevantExpAstHeadId(isset($data['relevantExpAstHeadId']) ? $data['relevantExpAstHeadId'] : 0);
$cf->setBalancingHeadId(isset($data['balancingHeadId']) ? $data['balancingHeadId'] : 0);
if ($data['cashFlowHeadId'] != '_UNCHANGED_')
$cf->setCashFlowHeadId(isset($data['cashFlowHeadId']) ? $data['cashFlowHeadId'] : 0);
$cf->setCashFlowHeadType(isset($data['cashFlowHeadType']) ? $data['cashFlowHeadType'] : 1);
$cf->setRelevantProductIds(isset($data['relevantProductIds']) ? json_encode($data['relevantProductIds']) : '[]');
$cf->setCashFlowDateTs(isset($data['cashFlowDateTs']) ? $data['cashFlowDateTs'] : 0);
$cf->setReminderDateTs(isset($data['reminderDateTs']) ? $data['reminderDateTs'] : 0);
$cf->setExpireDateTs(isset($data['expireDateTs']) ? $data['expireDateTs'] : 0);
$cf->setExpAstRealizationDateTs(isset($data['expAstRealizationDateTs']) ? $data['expAstRealizationDateTs'] : 0);
$em->persist($cf);
$em->flush();
return $cf;
}
//task related end
public static function getDocumentsByUserId($em, $user_id = 0)
{
$data = [];
$differentDocHashGetMethodByEntityId = [
'54' => 'getName'
];
//1st get login ids basedon user id
$new_cc = $em
->getRepository('ApplicationBundle\\Entity\\SysLoginLog')
->findBy(
array(
'userId' => $user_id,
)
);
$skipEntities = [54, 76];
if (!empty($new_cc)) {
$loginIdList = [];
foreach ($new_cc as $dt) {
$loginIdList[] = $dt->getLoginId();
}
if (!empty($loginIdList)) {
$documents = GeneralConstant::$Entity_list;
$documentDetails = GeneralConstant::$Entity_list_details;
$documentIdMethodList = GeneralConstant::$Entity_id_get_method_list;
// foreach ($documents as $key => $document) {
//
// if (in_array($key, $skipEntities))
// continue;
//// if ($key>70)
//// continue;
//// if($em->getRepository('ApplicationBundle\\Entity\\' . $document)) {
// if (!$em->getMetadataFactory()->isTransient('ApplicationBundle:' . $document)) {
// $query = $em
// ->getRepository('ApplicationBundle\\Entity\\' . $document)
// ->findBy(
// array(
// 'createdLoginId' => $loginIdList,
// ),
// array(
// 'createdAt' => 'DESC'
// )
// );
// if ($query) {
// foreach ($query as $q) {
// $doc = array(
// 'documentHash' => isset($differentDocHashGetMethodByEntityId[$key]) ? $q->{$differentDocHashGetMethodByEntityId[$key]}() : $q->getDocumentHash(),
// 'lastModifiedDate' => $q->getlastModifiedDate(),
// 'createdAt' => $q->getCreatedAt(),
// 'approved' => method_exists($q, 'getApproved') ? $q->getApproved() : 1,
// 'status' => GeneralConstant::$approvalAction[method_exists($q, 'getApproved') ? $q->getApproved() : 1],
// 'documentType' => $documentDetails[$key]['entity_alias'],
// 'documentViewPathName' => isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name']
// : (isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name'] : 'dashboard'),
// 'documentId' => $q->{$documentIdMethodList[$key]}(),
// 'documentTypeId' => $key
// );
// $data[] = $doc;
// }
// }
// }
// }
foreach ($documents as $key => $document) {
if (in_array($key, $skipEntities)) {
continue;
}
$entityClass = 'ApplicationBundle\\Entity\\' . $document;
// 🚨 Skip if entity class does not exist
if (!class_exists($entityClass)) {
continue;
}
// 🚨 Skip if not a Doctrine entity
if ($em->getMetadataFactory()->isTransient($entityClass)) {
continue;
}
$query = $em
->getRepository($entityClass)
->findBy(
['createdLoginId' => $loginIdList],
['createdAt' => 'DESC']
);
if ($query) {
foreach ($query as $q) {
$doc = [
'documentHash' => isset($differentDocHashGetMethodByEntityId[$key])
? $q->{$differentDocHashGetMethodByEntityId[$key]}()
: $q->getDocumentHash(),
'lastModifiedDate' => $q->getlastModifiedDate(),
'createdAt' => $q->getCreatedAt(),
'approved' => method_exists($q, 'getApproved') ? $q->getApproved() : 1,
'status' => GeneralConstant::$approvalAction[method_exists($q, 'getApproved') ? $q->getApproved() : 1],
'documentType' => $documentDetails[$key]['entity_alias'],
'documentViewPathName' => $documentDetails[$key]['entity_view_route_path_name'] ?? 'dashboard',
'documentId' => $q->{$documentIdMethodList[$key]}(),
'documentTypeId' => $key
];
$data[] = $doc;
}
}
}
}
}
return $data;
}
public static function getDocumentsByUserIdForApp($em, $user_id = 0, $includeAbsoluteUrl = 0, $absoluteUrlList = [])
{
$data = [];
$grouped_approval_list = [];
$differentDocHashGetMethodByEntityId = [
'54' => 'getName'
];
//1st get login ids basedon user id
$new_cc = $em
->getRepository('ApplicationBundle\\Entity\\SysLoginLog')
->findBy(
array(
'userId' => $user_id,
)
);
$skipEntities = [54, 76];
if (!empty($new_cc)) {
$loginIdList = [];
foreach ($new_cc as $dt) {
$loginIdList[] = $dt->getLoginId();
}
if (!empty($loginIdList)) {
$documents = GeneralConstant::$Entity_list;
$documentDetails = GeneralConstant::$Entity_list_details;
$documentIdMethodList = GeneralConstant::$Entity_id_get_method_list;
$amount_methods = ApprovalConstant::$Entity_amount_method;
foreach ($documents as $key => $document) {
if (in_array($key, $skipEntities))
continue;
// if($em->getRepository('ApplicationBundle\\Entity\\' . $document)) {
if (!$em->getMetadataFactory()->isTransient('ApplicationBundle\\Entity\\' . $document)) {
$query = $em
->getRepository('ApplicationBundle\\Entity\\' . $document)
->findBy(
array(
'createdLoginId' => $loginIdList,
),
array(
'createdAt' => 'DESC'
)
);
if ($query) {
foreach ($query as $q) {
$doc = array(
'documentHash' => isset($differentDocHashGetMethodByEntityId[$key]) ? $q->{$differentDocHashGetMethodByEntityId[$key]}() : $q->getDocumentHash(),
// 'lastModifiedDate' => $q->getlastModifiedDate(),
'createdAt' => 1 * $q->getCreatedAt()->format('U'),
'approved' => method_exists($q, 'getApproved') ? $q->getApproved() : 1,
'status' => GeneralConstant::$approvalAction[method_exists($q, 'getApproved') ? $q->getApproved() : 1],
'documentType' => $documentDetails[$key]['entity_alias'],
'documentPrintPathName' => '',
'documentViewPathName' => isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name']
: (isset($documentDetails[$key]['entity_view_route_path_name']) ? $documentDetails[$key]['entity_view_route_path_name'] : 'dashboard'),
// 'documentId' => $q->{$documentIdMethodList[$key]}(),
'documentTypeId' => $key,
'entity' => $key,
'entityId' => $q->{$documentIdMethodList[$key]}(),
'summary' => GeneralConstant::$documentSummaryList,
"relatedDoc" => "",
"documentImage" => isset(GeneralConstant::$Entity_list_details[$key]['image_url']) ?
GeneralConstant::$Entity_list_details[$key]['image_url'] : 'https://ibb.co.com/rfk8x7m4',
);
if ($includeAbsoluteUrl == 1 && isset($absoluteUrlList[$key])) {
$doc['documentPrintPathName'] = $absoluteUrlList[$key] . '/' . $q->{$documentIdMethodList[$key]}();
}
if (isset($amount_methods[$key])) {
$doc['amount'] = $q->{$amount_methods[$key]}();
} else
$doc['amount'] = '';
$data[] = $doc;
if (!isset($grouped_approval_list[$key])) {
$applicableEntities[] = array(
'id' => $key,
'alias' => GeneralConstant::$Entity_list_details[$key]['entity_alias'],
'imageUrl' => isset(GeneralConstant::$Entity_list_details[$key]['image_url']) ?
GeneralConstant::$Entity_list_details[$key]['image_url'] : 'https://ibb.co.com/4RBXD5pt',
'documentImage' => isset(GeneralConstant::$Entity_list_details[$key]['image_url']) ?
GeneralConstant::$Entity_list_details[$key]['image_url'] : 'https://ibb.co.com/rfk8x7m4'
);
$grouped_approval_list[$key] = array();
}
}
}
}
}
}
}
return array(
'documentData' => $data,
"applicable_entities" => $applicableEntities,
);
}
public static function getLoginIdsByUserId($em, $user_id = 0)
{
$data = [];
//1st get login ids based on user id
$new_cc = $em
->getRepository('ApplicationBundle\\Entity\\SysLoginLog')
->findBy(
array(
'userId' => $user_id,
)
);
$loginIdList = [];
if (!empty($new_cc)) {
foreach ($new_cc as $dt) {
$loginIdList[] = $dt->getLoginId();
}
}
return $loginIdList;
}
public static function GetSessionDataFromToken($em, $token = '', $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1)
{
$isEntityToken = 1;
$sessionData = [];
if ($token != '') {
$new_cc = $em
// ->getRepository($isEntityToken == 1 ? 'CompanyGroupBundle\\Entity\\EntityTokenStorage' : 'ApplicationBundle:TokenStorage')
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')//enforced
->findOneBy(
array(
'token' => $token,
)
);
if ($new_cc) {
$sessionData = json_decode($new_cc->getSessionData(), true);
if ($sessionData == null)
$sessionData = [];
if ($updateValidity == 1) {
// $expire_time = $new_cc->getExpiresAt();
$expire_time = new \DateTime();
$expire_time->modify('+24 hour');
$new_cc->setExpiresAt($expire_time);
$em->flush();
}
//$new_cc->setFireBaseToken($expire_time->format(DATE_RFC7231));
$em->flush();
}
}
if ($clearExpired == 1) {
$get_kids_sql = "DELETE FROM " . ($isEntityToken == 1 ? 'entity_token_storage' : 'token_storage');
$get_kids_sql .= " WHERE ( perpetual !=1 ) and expires_at < NOW(); ";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
}
$loginIdList = [];
return array(
'sessionData' => $sessionData,
);
}
public static function UpdateSessionDataFromToken($em, $token = '', $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1)
{
$isEntityToken = 1;
$sessionData = [];
if ($token != '') {
$new_cc = $em
// ->getRepository($isEntityToken == 1 ? 'CompanyGroupBundle\\Entity\\EntityTokenStorage' : 'ApplicationBundle:TokenStorage')
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')//enforced
->findOneBy(
array(
'token' => $token,
)
);
if ($new_cc) {
$sessionData = json_decode($new_cc->getSessionData(), true);
if ($sessionData == null)
$sessionData = [];
if ($updateValidity == 1) {
$expire_time = new \DateTime();
$expire_time->modify('+24 hour');
$new_cc->setExpiresAt($expire_time);
$em->flush();
}
//$new_cc->setFireBaseToken('U'.$expire_time->format(DATE_RFC7231));
$em->flush();
}
}
if ($clearExpired == 1) {
$get_kids_sql = "DELETE FROM " . ($isEntityToken == 1 ? 'entity_token_storage' : 'token_storage');
$get_kids_sql .= " WHERE ( perpetual !=1 ) and expires_at < NOW(); ";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
}
$loginIdList = [];
return array(
'sessionData' => $sessionData,
);
}
public static function UpdateCompanyListInSession($em, $applicantId = '', $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1, $newCompany = [])
{
$sessionData = [];
// return [];
if ($applicantId != '') {
$new_cc = $em;
$new_ccs = $em
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->findBy(
array(
'userId' => $applicantId,
)
);
foreach ($new_ccs as $new_cc) {
$currDt = new \DateTime();
if ($new_cc) {
$sessionData = json_decode($new_cc->getSessionData(), true);
if ($sessionData == null) $sessionData = [
'userAccessList' => []
];
if ($new_cc->getExpiresAt() <= $currDt) {
$em->remove($new_cc);
} else {
$sessionData = json_decode($new_cc->getSessionData(), true);
if ($sessionData == null) $sessionData = [
'userAccessList' => []
];
$sessionData['userAccessList'][] = $newCompany;
if ($updateValidity == 1) {
$expire_time = new \DateTime();
$expire_time->modify('+24 hour');
$new_cc->setExpiresAt($expire_time);
$new_cc->setSessionData(json_encode($sessionData));
$em->persist($new_cc);
//$new_cc->setFireBaseToken('C'.$expire_time->format(DATE_RFC7231));
$em->flush();
}
}
}
}
}
}
// public static function UpdateCompanyListInSession($em, $applicantId = '', $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1,$newCompany)
// {
// $sessionData = [];
//
// if ($applicantId != '') {
// $new_cc = $em
// ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
// ->findBy(
// array(
// 'userId' => $applicantId,
// )
// );
//
// if ($new_cc) {
// $sessionData = json_decode($new_cc->getSessionData(), true);
// if($sessionData == null)$sessionData=[
// 'userAccessList'=>[]
// ];
//
//
// $sessionData['userAccessList'][] = $newCompany;
//
//
// if ($updateValidity == 1) {
// $expire_time = $new_cc->getExpiresAt();
// $expire_time = $expire_time->modify('+24 hour');
// $new_cc->setExpiresAt($expire_time);
// $new_cc->getSessionData($sessionData);
// $em->persist();
// $em->flush();
// }
// }
// }
// return array(
// 'sessionData' => $sessionData,
// );
// }
public static function DeleteToken($em, $token = '', $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1)
{
$isEntityToken = 1;
$sessionData = [];
if ($token != '') {
$new_cc = $em
// ->getRepository($isEntityToken == 1 ? 'CompanyGroupBundle\\Entity\\EntityTokenStorage' : 'ApplicationBundle:TokenStorage')
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->findOneBy(
array(
'token' => $token,
)
);
if ($new_cc) {
$em->remove($new_cc);
$em->flush();
}
}
if ($clearExpired == 1) {
$get_kids_sql = "DELETE FROM " . ($isEntityToken == 1 ? 'entity_token_storage' : 'token_storage');
$get_kids_sql .= " WHERE ( perpetual !=1 ) and expires_at < NOW(); ";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
}
$loginIdList = [];
return array(
'sessionData' => $sessionData,
);
}
public static function CreateTokenFromSessionData($em, $sessionData = [], $isEntityToken = 1, $clearExpired = 1, $updateValidity = 1, $updateOnly = 0)
{
// $sessionData=[];
$token = '';
$isEntityToken = 1;
if ($sessionData != []) {
if ($updateOnly == 0) {
// if ($isEntityToken == 1)
$new_cc = new EntityTokenStorage();
// else
// $new_cc = new TokenStorage();
$token = Generic::simpleRandString();
$token = $token . '' . time();
$sessionData['token'] = $token;
$new_cc->setSessionData(json_encode($sessionData));
$new_cc->setToken($token);
$new_cc->setFireBaseToken(isset($sessionData['firebaseToken']) ? $sessionData['firebaseToken'] : '');
$new_cc->setUserId(isset($sessionData['userId']) ? $sessionData['userId'] : null);
$new_cc->setUserType(isset($sessionData['userType']) ? $sessionData['userType'] : 0);
$em->persist($new_cc);
$em->flush();
if ($new_cc) {
$sessionData = json_decode($new_cc->getSessionData(), true);
if ($sessionData == null)
$sessionData = [];
if ($updateValidity == 1) {
$expire_time = new \DateTime();
$expire_time = $expire_time->modify('+24 hour');
$new_cc->setExpiresAt($expire_time);
$em->flush();
}
}
} else {
// if ($isEntityToken == 1)
// {
$new_cc = $em
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->findOneBy(
array(
'token' => $sessionData['token'],
)
);
//
// if(!$new_cc)
// $new_cc = new EntityTokenStorage();
// }
//
// else
// {
// $new_cc = $em
// ->getRepository('ApplicationBundle\\Entity\\TokenStorage')
// ->findOneBy(
// array(
// 'token' => $sessionData['token'],
// )
// );
//
//// if(!$new_cc)
//// $new_cc = new TokenStorage();
//
// }
if ($new_cc) {
$token = $sessionData['token'];
$new_cc->setSessionData(json_encode($sessionData));
$new_cc->setFireBaseToken(isset($sessionData['firebaseToken']) ? $sessionData['firebaseToken'] : '');
$new_cc->setUserId(isset($sessionData['userId']) ? $sessionData['userId'] : null);
$new_cc->setUserType(isset($sessionData['userType']) ? $sessionData['userType'] : 0);
$new_cc->setToken($token);
if ($updateValidity == 1) {
$expire_time = new \DateTime();
$expire_time = $expire_time->modify('+24 hour');
$new_cc->setExpiresAt($expire_time);
$em->flush();
}
// $em->persist($new_cc);
$em->flush();
}
}
}
if ($clearExpired == 1) {
$get_kids_sql = "DELETE FROM " . ($isEntityToken == 1 ? 'entity_token_storage' : 'token_storage');
$get_kids_sql .= " WHERE ( perpetual !=1 ) and expires_at < NOW(); ";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
}
$loginIdList = [];
return array(
'token' => $token,
'sessionData' => $sessionData,
);
}
public static function addEntityUserLoginLog($em, $userId, $applicantId, $isApplicant, $ip, $PositionId = 0, $deviceId = '', $oAuthToken = '', $oAuthType = '', $locale = 'en', $firebaseToken = '')
{
$loginLog = new EntityLoginLog();
$loginLog->setLogStatus(true);
$loginLog->setLoginIp($ip);
$loginLog->setLogTime(new \DateTime('now'));
$loginLog->setUserId($userId);
$loginLog->setApplicantId($applicantId);
$loginLog->setisApplicant($isApplicant);
$loginLog->setPositionId($PositionId);
$loginLog->setDeviceId($deviceId);
$loginLog->setLocale($locale);
$loginLog->setFirebaseToken($firebaseToken);
$loginLog->setDeviceId($deviceId);
$loginLog->setOAuthToken($oAuthToken);
$loginLog->setOAuthType($oAuthType);
$em->persist($loginLog);
$em->flush();
return $loginLog->getLoginId();
}
public static function refreshTransactions($em, $start_id = 0)
{
$query = "UPDATE acc_accounts_head SET current_balance=opening_balance,current_balance_reconciled=opening_balance WHERE 1;
UPDATE acc_transactions SET ledger_hit=0 WHERE 1;
truncate acc_closing_balance;
truncate acc_actual_closing_balance;";
$stmt = $em->getConnection()->fetchAllAssociative($query);
System::UpdatePostDatedTransaction($em);
// $distinct_parent_ids=$stmt;s
}
public static function clearAccRelatedstuffs($em, $start_id = 0)
{
$query = "UPDATE acc_accounts_head SET current_balance=opening_balance,current_balance_reconciled=opening_balance WHERE 1;
UPDATE acc_transactions SET ledger_hit=0 WHERE 1;
truncate acc_closing_balance;
truncate acc_actual_closing_balance;";
$stmt = $em->getConnection()->fetchAllAssociative($query);
// System::UpdatePostDatedTransaction($em);
// $distinct_parent_ids=$stmt;s
}
public static function refreshClosing($em, $start_id = 0)
{
// step: 1 lets set all heads' balance as their opening balance
$query = "UPDATE acc_accounts_head set current_balance=opening_balance, current_balance_reconciled=opening_balance where 1";
$stmt = $em->getConnection()->executeStatement($query);
// $distinct_parent_ids=$stmt;
// $em->flush();
// step:2 set ledger hit on all vouchers after the fiscal closing to 0
$new_cc = $em
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$query = "UPDATE acc_transactions set ledger_hit=0 ";
$date_start = "";
$date_start_str = "";
if ($new_cc) {
$date_start = new \DateTime($new_cc->getData());
$date_start_str = $date_start->format('Y-m-d');
}
if ($new_cc)
$query .= " where transaction_date>= '" . $date_start_str . " 00:00:00' ";
$stmt = $em->getConnection()->executeStatement($query);
//now step:3 clear all closing after the fiscal year start
$query = "DELETE From acc_closing_balance ";
if ($new_cc)
$query .= " where date>= '" . $date_start_str . " 00:00:00' ";
$stmt = $em->getConnection()->executeStatement($query);
$query = "DELETE From acc_actual_closing_balance ";
if ($new_cc)
$query .= " where date>= '" . $date_start_str . " 00:00:00' ";
$stmt = $em->getConnection()->executeStatement($query);
// System::UpdatePostDatedTransaction($em);
// $distinct_parent_ids=$stmt;
}
public static function setOpening($em, $id, $amount = 0, $headNature = '', $year_start)
{
$head = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(
array(
'accountsHeadId' => $id
)
);
if ($headNature == '' || $headNature == $head->getHeadNature()) {
$head->setOpeningBalance($head->getOpeningBalance() * 1 + (1 * $amount));
} else {
$head->setOpeningBalance($head->getOpeningBalance() * 1 - (1 * $amount));
// Accounts::SetClosingBalance($em,$id,$amount,$head->getHeadNature(),$year_start,0);
// Accounts::SetActualClosingBalance($em,$id,$amount,$head->getHeadNature(),$year_start,0);
}
$em->flush();
if ($head->getParentId() != 0) {
self::setOpening($em, $head->getParentId(), $head->getOpeningBalance(), $head->getHeadNature(), $year_start);
}
return 1;
}
public static function prepareDatabaseForCompany($em)
{
//1st clear the documents
$query = " TRUNCATE acc_actual_closing_balance;
TRUNCATE acc_check;
TRUNCATE acc_closing_balance;
TRUNCATE acc_transactions;
TRUNCATE acc_transaction_details;
TRUNCATE approval;
TRUNCATE delivery_confirmation;
TRUNCATE delivery_order;
TRUNCATE delivery_order_item;
TRUNCATE delivery_receipt;
TRUNCATE delivery_receipt_item;
TRUNCATE expense_invoice;
TRUNCATE fiscal_closing;
TRUNCATE grn;
TRUNCATE grn_item;
TRUNCATE inventory_storage;
TRUNCATE inv_closing_balance;
TRUNCATE inv_item_transaction;
TRUNCATE material_inward;
TRUNCATE monthly_summary;
TRUNCATE payment_log;
TRUNCATE payment_schedule;
TRUNCATE purchase_invoice;
TRUNCATE purchase_invoice_item;
TRUNCATE purchase_order;
TRUNCATE purchase_order_item;
TRUNCATE purchase_requisition;
TRUNCATE purchase_requisition_item;
TRUNCATE quality_control;
TRUNCATE receipt_check;
TRUNCATE receipt_log;
TRUNCATE sales_invoice;
TRUNCATE sales_invoice_item;
TRUNCATE sales_order;
TRUNCATE sales_order_item;
TRUNCATE signature;
TRUNCATE stock_requisition;
TRUNCATE stock_requisition_item;
TRUNCATE store_requisition;
TRUNCATE store_requisition_item;";
$stmt = $em->getConnection()->fetchAllAssociative($query);
//1st prepare the company
//now set the company data to 0
$query = "UPDATE company SET cash=0,sales=0,expense=0,payable=0,net_worth=0,monthly_growth=0 WHERE 1";
$stmt = $em->getConnection()->executeStatement($query);
//now add the initial Head, cost centres and settings
//now set opening to all head to 0;
$query = "UPDATE acc_accounts_head set opening_balance=0 where 1;
UPDATE acc_clients SET client_order_amount=0,client_invoice_amount=0,client_received=0,client_due=0 WHERE 1;
UPDATE acc_suppliers SET supplier_paid=0,supplier_due=0 WHERE 1";
$stmt = $em->getConnection()->executeStatement($query);
}
public static function refreshDatabase($em)
{
//1st clear the documents
$query = "TRUNCATE acc_actual_closing_balance;
TRUNCATE acc_check;
TRUNCATE acc_closing_balance;
TRUNCATE acc_transactions;
TRUNCATE acc_transaction_details;
TRUNCATE approval;
TRUNCATE delivery_confirmation;
TRUNCATE delivery_order;
TRUNCATE delivery_order_item;
TRUNCATE delivery_receipt;
TRUNCATE delivery_receipt_item;
TRUNCATE expense_invoice;
TRUNCATE fiscal_closing;
TRUNCATE grn;
TRUNCATE grn_item;
TRUNCATE inventory_storage;
TRUNCATE inv_closing_balance;
TRUNCATE inv_item_transaction;
TRUNCATE material_inward;
TRUNCATE monthly_summary;
TRUNCATE payment_log;
TRUNCATE payment_schedule;
TRUNCATE purchase_invoice;
TRUNCATE purchase_invoice_item;
TRUNCATE purchase_order;
TRUNCATE purchase_order_item;
TRUNCATE purchase_requisition;
TRUNCATE purchase_requisition_item;
TRUNCATE quality_control;
TRUNCATE receipt_check;
TRUNCATE receipt_log;
TRUNCATE sales_invoice;
TRUNCATE sales_invoice_item;
TRUNCATE sales_order;
TRUNCATE sales_order_item;
TRUNCATE signature;
TRUNCATE stock_requisition;
TRUNCATE stock_requisition_item;
TRUNCATE store_requisition;
TRUNCATE store_requisition_item;";
$stmt = $em->getConnection()->fetchAllAssociative($query);
//now set the company data to 0
$query = "UPDATE company SET cash=0,sales=0,expense=0,payable=0,net_worth=0,monthly_growth=0 WHERE 1";
$stmt = $em->getConnection()->executeStatement($query);
//now set opening to all head to 0;
$query = "UPDATE acc_accounts_head set opening_balance=0 where 1;
UPDATE acc_clients SET client_order_amount=0,client_invoice_amount=0,client_received=0,client_due=0 WHERE 1;
UPDATE acc_suppliers SET supplier_paid=0,supplier_due=0 WHERE 1";
$stmt = $em->getConnection()->executeStatement($query);
}
public static function initiateAdminUser($em, $freshFlag = 1, $userName = 'admin', $name = 'System', $email = "admin", $encodedPassword = "", $appIds = [], $companyIds = [])
{
//1st clear the admin
if ($freshFlag == 1) {
$query = "DELETE FROM sys_user WHERE user_type=1";
$stmt = $em->getConnection()->executeStatement($query);
}
//now set admin with pass username admin;
$query = "INSERT INTO sys_user (user_id, name, email, password, salt, user_type, position_ids, supervisor_id, company_id, status, last_edit_login_id, last_mongolog_id, created_at, updated_at, image) VALUES
(1, 'System', 'admin', '6526eaf09f043a8078b70b79334b166922857b666350a2aa4946ed7e895cf941', '128541067656c1689d9db24', 1, '[]', NULL, 1, 1, '0', '', '0000-00-00 00:00:00', NULL, '');";
$stmt = $em->getConnection()->executeStatement($query);
}
public static function getSummaryData($em, $pending_data)
{
$pending_approval_list = $pending_data['pending_approval_list'];
$override_approval_list = $pending_data['override_approval_list'];
$Entity_list = GeneralConstant::$Entity_list;
$Entity_id_field_list = GeneralConstant::$Entity_id_field_list;
$Entity_amount_method_list = ApprovalConstant::$Entity_amount_method;
$Entity_party_method_list = ApprovalConstant::$Entity_party_method;
$differentDocHashGetMethodByEntityId = [
'54' => 'getName'
];
//data format=
// {
// 'documentAmount'=>0,
// 'documentPendingAmount'=>0,
// 'documentQty'=>0,
// 'documentPartyName'=>'abc'
// }
//'documentHash' =>isset($differentDocHashGetMethodByEntityId[$key])?$q->{$differentDocHashGetMethodByEntityId[$key]}(): $q->getDocumentHash(),
foreach ($pending_approval_list as $key => $dt) {
$entity = $dt['entity'];
$entityId = $dt['entityId'];
$doc = $em->getRepository('ApplicationBundle\\Entity\\' . $Entity_list[$entity])
->findOneBy(array(
$Entity_id_field_list[$entity] => $entityId
));
if ($doc) {
$docAmount = '';
$docPartyName = '';
$docPartyMethod = '';
$docPartyId = 0;
if (isset($Entity_amount_method_list[$entity])) {
$docAmount = method_exists($doc, $Entity_amount_method_list[$entity]) ? ($doc->{$Entity_amount_method_list[$entity]}()) : 0;
}
if (isset($Entity_party_method_list[$entity])) {
if ($Entity_party_method_list[$entity] != '_NONE_') {//please correct these
$docPartyId = method_exists($doc, $Entity_party_method_list[$entity]) ? ($doc->{$Entity_party_method_list[$entity]}()) : 0;
$docPartyMethod = method_exists($doc, $Entity_party_method_list[$entity]) ? $Entity_party_method_list[$entity] : 0;
}
}
if ($docPartyMethod != '') {
if ($docPartyMethod == 'getSupplierId') {
$party = $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
->findOneBy(array(
'supplierId' => $docPartyId
));
if ($party)
$docPartyName = $party->getSupplierName();
} else if ($docPartyMethod == 'getExpenseTypeId') {
$party = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
->findOneBy(array(
'accountsHeadId' => $docPartyId
));
if ($party)
$docPartyName = $party->getName();
} else {
$party = $em->getRepository('ApplicationBundle\\Entity\\AccClients')
->findOneBy(array(
'clientId' => $docPartyId
));
if ($party)
$docPartyName = $party->getClientName();
}
}
$pending_approval_list[$key]['summaryData'] = array(
'documentAmount' => $docAmount,
'documentPartyName' => $docPartyName,
);
}
}
foreach ($override_approval_list as $key => $dt) {
$entity = $dt['entity'];
$entityId = $dt['entityId'];
$doc = $em->getRepository('ApplicationBundle\\Entity\\' . $Entity_list[$entity])
->findOneBy(array(
$Entity_id_field_list[$entity] => $entityId
));
if ($doc) {
$docAmount = '';
$docPartyName = '';
$docPartyMethod = '';
$docPartyId = 0;
if (isset($Entity_amount_method_list[$entity])) {
$docAmount = method_exists($doc, $Entity_amount_method_list[$entity]) ? ($doc->{$Entity_amount_method_list[$entity]}()) : 0;
}
if ($Entity_party_method_list[$entity] != '_NONE_') {
$docPartyId = method_exists($doc, $Entity_party_method_list[$entity]) ? ($doc->{$Entity_party_method_list[$entity]}()) : 0;
$docPartyMethod = method_exists($doc, $Entity_party_method_list[$entity]) ? $Entity_party_method_list[$entity] : 0;
}
if ($docPartyMethod != '') {
if ($docPartyMethod == 'getSupplierId') {
$party = $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
->findOneBy(array(
'supplierId' => $docPartyId
));
if ($party)
$docPartyName = $party->getSupplierName();
} else {
$party = $em->getRepository('ApplicationBundle\\Entity\\AccClients')
->findOneBy(array(
'clientId' => $docPartyId
));
if ($party)
$docPartyName = $party->getClientName();
}
}
$pending_approval_list[$key]['summaryData'] = array(
'documentAmount' => $docAmount,
'documentPartyName' => $docPartyName,
);
}
}
return array(
"pending_approval_list" => $pending_approval_list,
"override_approval_list" => $override_approval_list
);
}
public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [], $userId = 0)
{
$companyId = 0;
$data = [];
$data_by_id = [];
$html = '';
$productByCodeData = [];
$setValueArray = [];
$setValue = 0;
$setValueType = 0;// 0 for id , 1 for query
$selectAll = 0;
if ($queryStr == '_EMPTY_')
$queryStr = '';
if (isset($dataConfig['query']))
$queryStr = $dataConfig['query'];
if ($queryStr == '_EMPTY_')
$queryStr = '';
$queryStr = str_replace('_FSLASH_', '/', $queryStr);
if ($queryStr === '#setValue:') {
$queryStr = '';
}
if (!(strpos($queryStr, '#setValue:') === false)) {
$setValueArrayBeforeFilter = explode(',', str_replace('#setValue:', '', $queryStr));
foreach ($setValueArrayBeforeFilter as $svf) {
if ($svf == '_ALL_') {
$selectAll = 1;
$setValueArray = [];
continue;
}
if (is_numeric($svf)) {
$setValueArray[] = ($svf * 1);
$setValue = $svf * 1;
}
}
$queryStr = '';
}
$valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
$headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''; //Special Field
$headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0; //Special Field
$itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
$selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
$textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
$table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
$isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
$orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
$andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
$andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
$mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
$joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
$renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
$setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
$dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
$lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
$parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
$parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
$skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
$offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
$returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
$nextOffset = 0;
$totalMatchedEntries = 0;
$convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
$convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
$orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
$convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
if (is_string($andConditions)) $andConditions = json_decode($andConditions, true);
if (is_string($orConditions)) $orConditions = json_decode($orConditions, true);
if (is_string($andOrConditions)) $andOrConditions = json_decode($andOrConditions, true);
if (is_string($mustConditions)) $mustConditions = json_decode($mustConditions, true);
if (is_string($joinTableData)) $joinTableData = json_decode($joinTableData, true);
if (is_string($convertToObjectFieldList)) $convertToObjectFieldList = json_decode($convertToObjectFieldList, true);
if (is_string($orderByConditions)) $orderByConditions = json_decode($orderByConditions, true);
if (is_string($convertToUrl)) $convertToUrl = json_decode($convertToUrl, true);
if ($table == '') {
return new JsonResponse(
array(
'success' => false,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'currentTs' => (new \Datetime())->format('U'),
'isMultiple' => $isMultiple,
'setValueArray' => $setValueArray,
'setValue' => $setValue,
'data' => $data,
'dataId' => $dataId,
'selectorId' => $selectorId,
'dataById' => $data_by_id,
'selectedId' => 0,
'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
)
);
}
$restrictionData = array(
// 'table'=>'relevantField in restriction'
'warehouse_action' => 'warehouseActionIds',
'branch' => 'branchIds',
'warehouse' => 'warehouseIds',
'production_process_settings' => 'productionProcessIds',
);
$restrictionIdList = [];
$filterQryForCriteria = "select ";
$selectQry = "";
// $selectQry=" `$table`.* ";
$selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
$selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
if (is_string($selectFieldList)) $selectFieldList = json_decode($selectFieldList, true);
foreach ($selectFieldList as $selField) {
if ($selectQry != '')
$selectQry .= ", ";
if ($selField == '*')
$selectQry .= " `$table`.$selField ";
else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
if ($selectPrefix == '')
$selectQry .= " count(*) ";
else
$selectQry .= (" count(* ) $selectPrefix" . "_RESULT_COUNT_ ");
} else {
if ($selectPrefix == '')
$selectQry .= " `$table`.`$selField` ";
else
$selectQry .= (" `$table`.`$selField` $selectPrefix" . "$selField ");
}
}
$joinQry = " from $table ";
// $filterQryForCriteria = "select * from $table ";
foreach ($joinTableData as $joinIndex => $joinTableDatum) {
// $conditionStr.=' 1=1 ';
$joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
$joinTableAlias = $joinTableName . '_' . $joinIndex;
$joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''; //field of main table
$joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''; //field of joining table
$fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
$tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
$selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
$selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
$joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
$joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
$joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
if (is_string($joinAndConditions)) $joinAndConditions = json_decode($joinAndConditions, true);
if (is_string($joinAndOrConditions)) $joinAndOrConditions = json_decode($joinAndOrConditions, true);
if (is_string($joinOrConditions)) $joinOrConditions = json_decode($joinOrConditions, true);
foreach ($selectFieldList as $selField) {
if ($selField == '*')
$selectQry .= ", `$joinTableAlias`.$selField ";
else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
if ($selectPrefix == '')
$selectQry .= ", count(`$joinTableAlias`." . $joinTableOnField . ") ";
else
$selectQry .= (", count(`$joinTableAlias`." . $joinTableOnField . ") $selectPrefix" . "_RESULT_COUNT_ ");
} else {
if ($selectPrefix == '')
$selectQry .= ", `$joinTableAlias`.`$selField` ";
else
$selectQry .= (", `$joinTableAlias`.`$selField` $selectPrefix" . "$selField ");
}
}
$joinQry .= " $tableJoinType $joinTableName $joinTableAlias on ";
// if($joinTablePrimaryField!='')
// $joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
// $joinAndString = '';
$joinAndString = '';
if ($joinTablePrimaryField != '')
$joinAndString .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
foreach ($joinAndConditions as $andCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
$cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinAndString != '')
$joinAndString .= " and ";
if ($ctype == 'like') {
$joinAndString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndString != '')
$joinAndString .= " and ";
$joinAndString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinAndString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndString != '')
$joinAndString .= " and ";
$joinAndString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinAndString .= " ( ";
if (in_array('null', $cvalue)) {
$joinAndString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
if (in_array('', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
$joinAndString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
if (in_array('', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
$joinAndString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndString .= "`$joinTableAlias`.$cfield is null ";
else
$joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinAndString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinAndString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinAndString != '') {
// if ($conditionStr != '')
// $conditionStr .= (" and (" . $joinAndString . ") ");
// else
// $conditionStr .= (" (" . $joinAndString . ") ");
// }
if ($joinAndString != '')
$joinQry .= $joinAndString;
$joinAndOrString = "";
foreach ($joinAndOrConditions as $andOrCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
$cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinAndOrString != '')
$joinAndOrString .= " or ";
if ($ctype == 'like') {
$joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndOrString != '')
$joinAndOrString .= " or ";
$joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndOrString != '')
$joinAndOrString .= " or ";
$joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinAndOrString .= " ( ";
if (in_array('null', $cvalue)) {
$joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
$joinAndOrString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinAndOrString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
$joinAndOrString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
else
$joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinAndOrString != '')
// $joinQry .= $joinAndOrString;
if ($joinAndOrString != '') {
if ($joinQry != '')
$joinQry .= (" and (" . $joinAndOrString . ") ");
else
$joinQry .= (" (" . $joinAndOrString . ") ");
}
//pika
$joinOrString = "";
foreach ($joinOrConditions as $orCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
$cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinOrString != '')
$joinOrString .= " or ";
if ($ctype == 'like') {
$joinOrString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinOrString != '')
$joinOrString .= " or ";
$joinOrString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinOrString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinOrString != '')
$joinOrString .= " or ";
$joinOrString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinOrString .= " ( ";
if (in_array('null', $cvalue)) {
$joinOrString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinOrString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
$joinOrString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinOrString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinOrString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
$joinOrString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinOrString .= "`$joinTableAlias`.$cfield is null ";
else
$joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinOrString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinOrString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinOrString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinOrString != '')
// $joinQry .= $joinOrString;
if ($joinOrString != '') {
if ($joinQry != '')
$joinQry .= (" or (" . $joinOrString . ") ");
else
$joinQry .= (" (" . $joinOrString . ") ");
}
//
// $joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
}
$filterQryForCriteria .= $selectQry;
$filterQryForCriteria .= $joinQry;
if ($skipDefaultCompanyId == 0 && $companyId != 0 && !isset($dataConfig['entity_group']))
$filterQryForCriteria .= " where `$table`.`company_id`=" . $companyId . " ";
else
$filterQryForCriteria .= " where 1=1 ";
$conditionStr = "";
$aliasInCondition = $table;
if ($headMarkers != '' && $table == 'acc_accounts_head') {
$markerList = explode(',', $headMarkers);
$spMarkerQry = "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
$markerPassedHeads = [];
foreach ($markerList as $mrkr) {
$spMarkerQry .= " and marker_hash like '%" . $mrkr . "%'";
}
$spStmt = $em->getConnection()->fetchAllAssociative($spMarkerQry);
$spStmtResults = $spStmt;
foreach ($spStmtResults as $ggres) {
$markerPassedHeads[] = $ggres['accounts_head_id'];
}
if (!empty($markerPassedHeads)) {
if ($conditionStr != '')
$conditionStr .= " and (";
else
$conditionStr .= " (";
if ($headMarkersStrictMatch != 1) {
foreach ($markerPassedHeads as $mh) {
$conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" . $mh . "/%' or ";
}
}
$conditionStr .= " `$aliasInCondition`.`accounts_head_id` in (" . implode(',', $markerPassedHeads) . ") ";
$conditionStr .= " )";
}
}
if (isset($restrictionData[$table])) {
$userRestrictionData = Users::getUserApplicationAccessSettings($em, $userId)['options'];
if (isset($userRestrictionData[$restrictionData[$table]])) {
$restrictionIdList = $userRestrictionData[$restrictionData[$table]];
if ($restrictionIdList == null)
$restrictionIdList = [];
}
if (!empty($restrictionIdList)) {
if ($conditionStr != '')
$conditionStr .= " and ";
$conditionStr .= " `$table`.$valueField in (" . implode(',', $restrictionIdList) . ") ";
}
}
// $aliasInCondition = $table;
if (!empty($setValueArray) || $selectAll == 1) {
if (!empty($setValueArray)) {
if ($conditionStr != '')
$conditionStr .= " and ";
$conditionStr .= " `$aliasInCondition`.$valueField in (" . implode(',', $setValueArray) . ") ";
}
} else {
$andString = '';
foreach ($andConditions as $andCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
$cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($andString != '')
$andString .= " and ";
if ($ctype == 'like') {
$andString .= ("`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andString != '')
$andString .= " and ";
$andString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$andString .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andString != '')
$andString .= " and ";
$andString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$andString .= " ( ";
if (in_array('null', $cvalue)) {
$andString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andString .= " and ";
}
if (in_array('', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andString .= " and ";
}
$andString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andString .= " and ";
}
if (in_array('', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andString .= " and ";
}
$andString .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andString .= "`$aliasInCondition`.$cfield is null ";
else
$andString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andString .= "`$aliasInCondition`.$cfield is not null ";
else
$andString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$andString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$andString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($andString != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $andString . ") ");
else
$conditionStr .= (" (" . $andString . ") ");
}
$orString = '';
foreach ($orConditions as $orCondition) {
$ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
$cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($orString != '')
$orString .= " or ";
if ($ctype == 'like') {
$orString .= ("`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($orString != '')
$orString .= " or ";
$orString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$orString .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($orString != '')
$orString .= " or ";
$orString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$orString .= " ( ";
if (in_array('null', $cvalue)) {
$orString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$orString .= " or ";
}
if (in_array('', $cvalue)) {
$orString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$orString .= " or ";
}
$orString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
$orString .= " ( ";
if (in_array('null', $cvalue)) {
$orString .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$orString .= " or ";
}
if (in_array('', $cvalue)) {
$orString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$orString .= " or ";
}
$orString .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$orString .= "`$aliasInCondition`.$cfield is null ";
else
$orString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$orString .= "`$aliasInCondition`.$cfield is not null ";
else
$orString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$orString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$orString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($orString != '') {
if ($conditionStr != '')
$conditionStr .= (" or (" . $orString . ") ");
else
$conditionStr .= (" (" . $orString . ") ");
}
$andOrString = '';
foreach ($andOrConditions as $andOrCondition) {
$ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
$cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($andOrString != '')
$andOrString .= " or ";
if ($ctype == 'like') {
$andOrString .= (" `$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andOrString != '')
$andOrString .= " or ";
$andOrString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$andOrString .= (" `$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andOrString != '')
$andOrString .= " or ";
$andOrString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'in') {
$andOrString .= " ( ";
if (in_array('null', $cvalue)) {
$andOrString .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (in_array('', $cvalue)) {
$andOrString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (!empty($cvalue))
$andOrString .= " `$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
else
$andOrString .= " ) ";
} else if ($ctype == 'not_in') {
$andOrString .= " ( ";
if (in_array('null', $cvalue)) {
$andOrString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (in_array('', $cvalue)) {
$andOrString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (!empty($cvalue))
$andOrString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
else
$andOrString .= " ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andOrString .= "`$aliasInCondition`.$cfield is null ";
else
$andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andOrString .= "`$aliasInCondition`.$cfield is not null ";
else
$andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$andOrString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$andOrString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($andOrString != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $andOrString . ") ");
else
$conditionStr .= (" (" . $andOrString . ") ");
}
}
$mustStr = '';
///now must conditions
foreach ($mustConditions as $mustCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
$cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($mustStr != '')
$mustStr .= " and ";
if ($ctype == 'like') {
$mustStr .= ("(`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($mustStr != '')
$mustStr .= " or ";
$mustStr .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
$mustStr .= " )";
} else if ($ctype == 'not like') {
$mustStr .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($mustStr != '')
$mustStr .= " and ";
$mustStr .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'in') {
$mustStr .= " ( ";
if (in_array('null', $cvalue)) {
$mustStr .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$mustStr .= " or ";
}
if (in_array('', $cvalue)) {
$mustStr .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$mustStr .= " or ";
}
$mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'not_in') {
$mustStr .= " ( ";
if (in_array('null', $cvalue)) {
$mustStr .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$mustStr .= " and ";
}
if (in_array('', $cvalue)) {
$mustStr .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$mustStr .= " and ";
}
$mustStr .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$mustStr .= "`$aliasInCondition`.$cfield is null ";
else
$mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$mustStr .= "`$aliasInCondition`.$cfield is not null ";
else
$mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$mustStr .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$mustStr .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($mustStr != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $mustStr . ") ");
else
$conditionStr .= (" (" . $mustStr . ") ");
}
if ($conditionStr != '')
$filterQryForCriteria .= (" and (" . $conditionStr . ") ");
if ($lastChildrenOnly == 1) {
if ($filterQryForCriteria != '')
$filterQryForCriteria .= ' and';
$filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from $table)";
} else if ($parentOnly == 1) {
if ($filterQryForCriteria != '')
$filterQryForCriteria .= ' and';
$filterQryForCriteria .= "`$table`.`$valueField` in ( select distinct $parentIdField from $table)";
}
if (!empty($orderByConditions)) {
$filterQryForCriteria .= " order by ";
$fone = 1;
foreach ($orderByConditions as $orderByCondition) {
if ($fone != 1) {
$filterQryForCriteria .= " , ";
}
if (isset($orderByCondition['valueList'])) {
if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
if ($orderByCondition['valueList'] == null)
$orderByCondition['valueList'] = [];
$filterQryForCriteria .= " field(" . $orderByCondition['field'] . "," . implode(',', $orderByCondition['valueList']) . "," . $orderByCondition['field'] . ") " . $orderByCondition['sortType'] . " ";
} else
$filterQryForCriteria .= " " . $orderByCondition['field'] . " " . $orderByCondition['sortType'] . " ";
$fone = 0;
}
}
if ($returnTotalMatchedEntriesFlag == 1) {
// $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
//
// $get_kids = $stmt;
}
if ($filterQryForCriteria != '')
if (!empty($setValueArray) || $selectAll == 1) {
} else {
if ($itemLimit != '_ALL_')
$filterQryForCriteria .= " limit $offset, $itemLimit ";
else
$filterQryForCriteria .= " limit $offset, 18446744073709551615 ";
}
$get_kids_sql = $filterQryForCriteria;
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
$selectedId = 0;
if ($table == 'warehouse_action') {
if (empty($get_kids)) {
$get_kids_sql_2 = "select * from warehouse_action";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
$get_kids2 = $stmt;
if (empty($get_kids2))
$get_kids = GeneralConstant::$warehouse_action_list;
}
}
if (!empty($get_kids)) {
$nextOffset = $offset + count($get_kids);
$nextOffset++;
foreach ($get_kids as $pa) {
if (!empty($setValueArray) && $selectAll == 0) {
if (!in_array($pa[$valueField], $setValueArray))
continue;
}
if (!empty($restrictionIdList)) {
if (!in_array($pa[$valueField], $restrictionIdList))
continue;
}
if ($selectAll == 1) {
$setValueArray[] = $pa[$valueField];
$setValue = $pa[$valueField];
} else if (count($get_kids) == 1 && $setDataForSingle == 1) {
$setValueArray[] = $pa[$valueField];
$setValue = $pa[$valueField];
}
if ($valueField != '')
$pa['value'] = $pa[$valueField];
$renderedText = $renderTextFormat;
$compare_array = [];
if ($renderTextFormat != '') {
$renderedText = $renderTextFormat;
$compare_arrayFull = [];
$compare_array = [];
$toBeReplacedData = array(// 'curr'=>'tobereplaced'
);
preg_match_all("/__\w+__/", $renderedText, $compare_arrayFull);
if (isset($compare_arrayFull[0]))
$compare_array = $compare_arrayFull[0];
// $compare_array= preg_split("/__\w+__/",$renderedText);
foreach ($compare_array as $cmpdt) {
$tbr = str_replace("__", "", $cmpdt);
if ($tbr != '') {
if (isset($pa[$tbr])) {
if ($pa[$tbr] == null)
$renderedText = str_replace($cmpdt, '', $renderedText);
else
$renderedText = str_replace($cmpdt, $pa[$tbr], $renderedText);
} else {
$renderedText = str_replace($cmpdt, '', $renderedText);
}
}
}
}
$pa['rendered_text'] = $renderedText;
$pa['text'] = ($textField != '' ? $pa[$textField] : '');
// $pa['compare_array'] = $compare_array;
foreach ($convertToObjectFieldList as $convField) {
if (isset($pa[$convField])) {
$taA = json_decode($pa[$convField], true);
if ($taA == null) $taA = [];
$pa[$convField] = $taA;
} else {
$pa[$convField] = [];
}
}
foreach ($convertDateToStringFieldList as $convField) {
if (is_array($convField)) {
$fld = $convField['field'];
$frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
} else {
$fld = $convField;
$frmt = 'Y-m-d H:i:s';
}
if (isset($pa[$fld])) {
$taA = new \DateTime($pa[$fld]);
$pa[$fld] = $taA->format($frmt);
}
}
foreach ($convertToUrl as $convField) {
$fld = $convField;
if (isset($pa[$fld])) {
// $pa[$fld] =
// $this->generateUrl(
// $pa[$fld], [
//// 'refRoute' => $refRoute
// ], UrlGenerator::ABSOLUTE_URL
// );
}
}
$pa['currentTs'] = (new \Datetime())->format('U');
$data[] = $pa;
if ($valueField != '') {
$data_by_id[$pa[$valueField]] = $pa;
$selectedId = $pa[$valueField];
}
}
}
$resultData = array(
'success' => true,
'data' => $data,
'tableName' => $table,
'setValue' => $setValue,
'currentTs' => (new \Datetime())->format('U'),
'restrictionIdList' => $restrictionIdList,
'andConditions' => $andConditions,
'queryStr' => $queryStr,
'isMultiple' => $isMultiple,
'nextOffset' => $nextOffset,
'totalMatchedEntries' => $totalMatchedEntries,
'selectorId' => $selectorId,
'setValueArray' => $setValueArray,
'conditionStr' => $conditionStr,
// 'andStr' => $andString,
// 'andOrStr' => $andOrString,
'dataById' => $data_by_id,
'selectedId' => $selectedId,
'dataId' => $dataId,
'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
);
return $resultData;
}
public static function getServerListById($default_server_user, $default_server_pass, $server_config_from_parameter_array)
{
$serverList = GeneralConstant::$serverListById;
$newServerList = [];
$default_server_data = [
"port" => "",
"dbUser" => $default_server_user,
"dbPass" => $default_server_pass,
"dedicated" => "0",
"ram" => "4", //GB
"cpu" => "2", //cpu core
"storage" => "80", //GBN
"transfer" => "4", //TB
"bwIn" => "40", //GBbps
"bwOut" => "4", //GBbps
];
$server_config_from_parameter = [];
//1st get from config
foreach ($server_config_from_parameter_array as $server) {
$key = $server['id'];
if (isset($serverList[$key]))
foreach ($serverList[$key] as $index => $value) {
if (!isset($server[$index]))
$server[$index] = $value;
}
else {
foreach ($default_server_data as $index => $value) {
if (!isset($server[$index]))
$server[$index] = $value;
}
}
$server['id'] = $key;
$newServerList[$key] = $server;
$server_config_from_parameter[$key] = $server;
}
//then get the others
foreach ($serverList as $key => $server) {
if (!isset($newServerList[$key])) {
if (isset($server_config_from_parameter[$key]))
foreach ($server_config_from_parameter[$key] as $index => $value) {
$server[$index] = $value;
}
else {
$server['dbUser'] = $default_server_user;
$server['dbPass'] = $default_server_pass;
}
$newServerList[$key] = $server;
}
}
return $newServerList;
}
}