<?php
namespace ApplicationBundle\Controller;
use ApplicationBundle\ApplicationBundle;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\ModuleConstant;
use ApplicationBundle\Entity\Approval;
use ApplicationBundle\Entity\Company;
use ApplicationBundle\Entity\DocumentData;
use ApplicationBundle\Entity\SysModule;
use ApplicationBundle\Entity\SysUser;
use ApplicationBundle\Interfaces\LoginInterface;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\Inventory\Inventory;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Users;
use CompanyGroupBundle\Entity\CompanyGroup;
use CompanyGroupBundle\Entity\DeviceSensorData;
use CompanyGroupBundle\Entity\DeviceSensorDataDay;
use CompanyGroupBundle\Entity\DeviceSensorDataHour;
use CompanyGroupBundle\Entity\DeviceSensorDataMonth;
use CompanyGroupBundle\Entity\DeviceSensorDataWeek;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGenerator;
class ApplicationManagementController extends GenericController implements LoginInterface
{
public function DeviceDataEmsIngestAction(Request $request, $id = 0)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$content = $request->getContent(); // raw body string
$data = json_decode($content, true); // decode JSON if needed
// Example: access fields
if ($data == null) $data = [];
$emsDataSegregation = GeneralConstant::$emsDataSegregation;
$segregatedData = [];
$segregatedDataByDeviceId = [];
$siteId = (isset($data['siteId'])) ? $data['siteId'] : 0;
//first create a new array or records which will then be modified and or created
$modifiedData = array();
$firstTs = 0;
$lastTs = 0;
$siteIds = [$siteId];
// $defaultData = [
// 'marker' => '',
// 'ts' => '',
// 'data' => []
// ];
$defaultValues = [0, 0, 0, 0];
if (isset($data['records']))
foreach ($data['records'] as $key => $value) {
$timeStampDt = new \DateTime($value['timestamp']);
$timeStampDt->setTimezone(new \DateTimeZone('+0000'));
$timeStampTs = 1 * $timeStampDt->format('U');
if ($timeStampTs > $lastTs) $lastTs = $timeStampTs;
if ($timeStampTs < $firstTs || $firstTs = 0) $firstTs = $timeStampTs;
if (!in_array($data['siteId'], $siteIds)) $siteIds[] = $data['siteId'];
foreach ($emsDataSegregation as $key2 => $dataSegregation) {
if (!isset($segregatedDataByDeviceId[$value['device_id']]))
$segregatedDataByDeviceId[$value['device_id']] = [];
if (!isset($segregatedDataByDeviceId[$value['device_id']][$key2]))
$segregatedDataByDeviceId[$value['device_id']][$key2] = [];
$segregatedData = $segregatedDataByDeviceId[$value['device_id']];
// $segregatedData[$key2] = [
//// '20250406': [
//// 'marker' => '',
//// 'ts' => '',
//// 'data' => ['Battery_power' => [0, 2, 1, 4]]
//// ]
// ];
// [{'_identifier_':{min,max,avg,count}}]
$markerForThis = 1 * $timeStampDt->format($dataSegregation['markerStr']);
if (isset($dataSegregation['isWeek'])) {
$startDtForThis = new \DateTime();
$startDtForThis->setISODate($timeStampDt->format('Y'), $timeStampDt->format('W'));
} else {
$startDtForThis = new \DateTime($timeStampDt->format($dataSegregation['startTsFormat']));
}
$startDtForThis->setTimezone(new \DateTimeZone('+0000'));
$startTsForThis = $startDtForThis->format('U');
if (!isset($segregatedData[$key2][$markerForThis]))
$segregatedData[$key2][$markerForThis] = [
'marker' => $markerForThis,
'ts' => $startTsForThis,
'data' => []
];
if (!isset($segregatedData[$key2][$markerForThis]['data'][$value['identifier']]))
$segregatedData[$key2][$markerForThis]['data'][$value['identifier']] = $defaultValues;
$newValues = $segregatedData[$key2][$markerForThis]['data'][$value['identifier']];
//indexes 0:min, 1:max, 2:avg, 3:count
$min = $newValues[0];
$max = $newValues[1];
$avg = $newValues[2];
$count = $newValues[3];
//now modify
if ($value['value'] > $max) $max = $value['value'];
if ($value['value'] < $min) $min = $value['value'];
$avg = ($count * $avg + $value['value']) / ($count + 1);
$count++;
$newValues = [$min, $max, $avg, $count];
$segregatedData[$key2][$markerForThis]['data'][$value['identifier']] = $newValues;
$segregatedDataByDeviceId[$value['device_id']] = $segregatedData;
}
}
//nnow data are segregated now add them
foreach ($emsDataSegregation as $key2 => $dataSegregation) {
foreach ($segregatedDataByDeviceId as $deviceId => $segregatedData) {
if (!isset($segregatedData[$key2]))
$segregatedData[$key2] = [];
foreach ($segregatedData[$key2] as $key3 => $dt) {
$timeStampDt = new \DateTime('@' . $dt['ts']);
$timeStampDt->setTimezone(new \DateTimeZone('+0000'));
$markerForThis = $dt['marker'];
$entry = $this->getDoctrine()->getManager('company_group')
->getRepository('CompanyGroupBundle:' . $dataSegregation['repository'])
->findOneBy(array(
'marker' => $markerForThis,
'siteId' => $siteId,
'deviceId' => $deviceId
));
$repoClassName = "CompanyGroupBundle\\Entity\\" . $dataSegregation['repository'];
$hasEntry = 1;
if (!$entry) {
$hasEntry = 0;
$entry = new $repoClassName();
$entry->setTimeStamp($timeStampDt);
$entry->setTimeStampTs($dt['ts']);
$entry->setSiteId($siteId);
$entry->setMarker($markerForThis);
$entry->setDeviceId($deviceId);
}
$existingData = json_decode($entry->getData(), true);
if ($existingData == null) $existingData = [];
// $existingData=$segregatedDataByDeviceId; //temp
foreach ($dt['data'] as $identifier => $newValues) {
if (!isset($existingData[$identifier]))
$existingData[$identifier] = $newValues;
else {
//indexes 0:min, 1:max, 2:avg, 3:count
$min = $existingData[$identifier][0];
$max = $existingData[$identifier][1];
$avg = $existingData[$identifier][2];
$count = $existingData[$identifier][3];
//now modify
if ($newValues[1] > $max) $max = $newValues[1];
if ($newValues[0] < $min) $min = $newValues[0];
$avg = ($count * $avg + $newValues[2] * $newValues[3]) / ($count + $newValues[3]);
$count = $count + $newValues[3];
$existingData[$identifier] = [$min, $max, $avg, $count];
}
}
$entry->setData(json_encode($existingData));
if ($hasEntry == 0)
$em_goc->persist($entry);
$em_goc->flush();
}
}
}
return new JsonResponse(array(
'success' => true,
));
}
public function DeviceDataEmsIngestActionLater(Request $request, $id = 0)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$content = $request->getContent(); // raw body string
$data = json_decode($content, true); // decode JSON if needed
// Example: access fields
if ($data == null) $data = [];
$siteId = (isset($data['siteId'])) ? $data['siteId'] : 0;
if (isset($data['records']))
foreach ($data['records'] as $key => $value) {
// $entry = $this->getDoctrine()->getManager('company_group')
// ->getRepository("CompanyGroupBundle:DeviceSensorData")
// ->findOneBy(array(
// 'recordId' => $value['record_id']
// ));
$entry = null;
$hasEntry = 1;
if (!$entry) {
$hasEntry = 0;
$entry = new DeviceSensorData();
}
$timeStampDt = new \DateTime($value['timestamp']);
$entry->setDeviceId($value['device_id']);
$entry->setRecordId($value['record_id']);
$entry->setSiteId($siteId);
$entry->setAlias($value['alias']);
$entry->setValue($value['value']);
$entry->setIdentifier($value['identifier']);
$entry->setTimeStamp($timeStampDt);
$entry->setTimeStampTs($timeStampDt->format('U'));
if ($hasEntry == 0)
$em_goc->persist($entry);
$em_goc->flush();
}
return new JsonResponse(array(
'success' => true,
));
}
public function DeviceDataEmsGetAction(Request $request, $id = 0)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$returnData = array(
'success' => false,
'dataList' => []
);
$getDatakeys = ['_BY_DAY_', '_BY_HOUR_'];
$emsDataSegregation = GeneralConstant::$emsDataSegregation;
foreach ($getDatakeys as $key2) {
$dataSegregation = $emsDataSegregation[$key2];
if (!isset($returnData['dataList'][$key2]))
$returnData['dataList'][$key2] = [];
$repoClassName = $dataSegregation['repository'];
$dataQry = $this->getDoctrine()->getManager('company_group')
->getRepository('CompanyGroupBundle:' . $dataSegregation['repository'])
->createQueryBuilder('a')
->where('1=1');
if ($request->get('start_ts', 0) != 0) $dataQry->andWhere('a.timeStampTs >= ' . $request->get('start_ts', 0));
if ($request->get('end_ts', 0) != 0) $dataQry->andWhere('a.timeStampTs <= ' . $request->get('end_ts', 0));
if (!empty($request->get('device_ids', [])))
$dataQry->andWhere('a.deviceId in ( ' . implode(',', $request->get('device_ids', [])) . ' ) ');
if (!empty($request->get('identifiers', [])))
$dataQry->andWhere('a.identifier in ( ' . implode(',', $request->get('identifiers', [])) . ' ) ');
if (!empty($request->get('site_ids', [])))
$dataQry->andWhere('a.siteId in ( ' . implode(',', $request->get('site_ids', [])) . ' ) ');
$data = $dataQry
->setMaxResults(1000)
->getQuery()
->getResult();
if (!empty($data))
$returnData['success'] = true;
foreach ($data as $key => $entry) {
$value = array();
$timeStampDt = $entry->getTimeStamp();
$timeStampDt->setTimezone(new \DateTimeZone('+0000'));
$existingData = json_decode($entry->getData(), true);
if ($existingData == null) $existingData = [];
foreach ($existingData as $identifier => $newValues) {
$value['device_id'] = $entry->getDeviceId();
$value['value'] = $newValues[2];
$value['identifier'] = $identifier;
$value['timestamp'] = $timeStampDt;
$value['timestamp_ts'] = $entry->getTimeStampTs();;
$returnData['dataList'][$key2][] = $value;
}
}
}
return new JsonResponse($returnData);
}
public function UpdateCompanyGroupAction(Request $request, $id = 0)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$appId = $request->get('app_id', 0);
$post = $request;
$session = $request->getSession();
$d = array();
if ($systemType == '_CENTRAL_') {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
if ($connected) {
$goc = null;
$serverList = GeneralConstant::$serverListById;
$companyGroupHash = $post->get('company_short_code', '');
$defaultUsageDate = new \DateTime();
$defaultUsageDate->modify('+1 year');
$usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str', $defaultUsageDate->format('Y-m-d')));
$companyGroupServerId = $post->get('server_id', 1);
$companyGroupServerAddress = $serverList[$companyGroupServerId]['absoluteUrl'];
$companyGroupServerPort = $serverList[$companyGroupServerId]['port'];
$companyGroupServerHash = $serverList[$companyGroupServerId]['serverMarker'];
// $dbUser=
if ($appId != 0)
$goc = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy(array(
'appId' => $appId
));
if (!$goc)
$goc = new CompanyGroup();
if ($appId == 0) {
$biggestAppIdCg = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy(array(// 'appId' => $appId
), array(
'appId' => 'desc'
));
if ($biggestAppIdCg)
$appId = 1 + $biggestAppIdCg->getAppId();
}
if ($post->get('company_name', '') != '') {
$goc->setName($post->get('company_name'));
$goc->setCompanyGroupHash($companyGroupHash);
$goc->setAppId($appId);
$goc->setActive(1);
$goc->setAddress($post->get('address'));
$goc->setShippingAddress($post->get('s_address'));
$goc->setBillingAddress($post->get('b_address'));
$goc->setMotto($post->get('motto'));
$goc->setInitiateFlag($post->get('initiate_flag', 2));
$goc->setInvoiceFooter($post->get('i_footer'));
$goc->setGeneralFooter($post->get('g_footer'));
$goc->setCompanyReg($post->get('company_reg', ''));
$goc->setCompanyTin($post->get('company_tin', ''));
$goc->setCompanyBin($post->get('company_bin', ''));
$goc->setCompanyTl($post->get('company_tl', ''));
$goc->setCompanyType($post->get('company_type', ''));
$goc->setCurrentSubscriptionPackageId($post->get('package', ''));
$goc->setUsageValidUptoDate($usageValidUpto);
$goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
// $goc->setCu($post->get('package', ''));
$goc->setAdminUserAllowed($post->get('number_of_admin_user', ''));
$goc->setUserAllowed($post->get('number_of_user', ''));
$goc->setSubscriptionMonth($post->get('subscription_month', ''));
$goc->setCompanyDescription($post->get('company_description', ''));
$goc->setDbUser($post->get('db_user'));
$goc->setDbPass($post->get('db_pass'));
$goc->setDbHost($post->get('db_host'));
$goc->setCompanyGroupServerId($companyGroupServerId);
$goc->setCompanyGroupServerAddress($companyGroupServerAddress);
$goc->setCompanyGroupServerPort($companyGroupServerPort);
$goc->setCompanyGroupServerHash($companyGroupServerHash);
foreach ($request->files as $uploadedFile) {
if ($uploadedFile != null) {
$fileName = 'company_image' . $appId . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage())) {
unlink($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage());
}
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
if ($path != "")
$goc->setImage('/uploads/CompanyImage/' . $path);
}
}
$em_goc->persist($goc);
$em_goc->flush();
$goc->setDbName('cg_' . $appId . '_' . $companyGroupHash);
$goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
$goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
$goc->setDbHost('localhost');
$em_goc->flush();
$centralUser = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:EntityApplicantDetails")
->findOneBy(array(
'applicantId' => $session->get(UserConstants::USER_ID, 0)
));
if ($centralUser) {
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
$userTypesByAppIds = json_decode($centralUser->getUserTypesByAppIds(), true);
if ($userAppIds == null) $userAppIds = [];
if ($userTypesByAppIds == null) $userTypesByAppIds = [];
$userAppIds = array_merge($userAppIds, array_diff([$appId], $userAppIds));
if (!isset($userTypesByAppIds[$appId])) {
$userTypesByAppIds[$appId] = [];
}
$userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
$centralUser->setUserAppIds(json_encode($userAppIds));
$centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
$em_goc->flush();
}
$accessList = $session->get('userAccessList', []);
$d = array(
'userType' => UserConstants::USER_TYPE_SYSTEM,
'globalId' => $session->get(UserConstants::USER_ID, 0),
'serverId' => $companyGroupServerId,
'serverUrl' => $companyGroupServerAddress,
'serverPort' => $companyGroupServerPort,
'systemType' => '_ERP_',
'companyId' => 1,
'appId' => $appId,
'companyLogoUrl' => $goc->getImage(),
'companyName' => $goc->getName(),
'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
array(
'globalId' => $session->get(UserConstants::USER_ID, 0),
'appId' => $appId,
'authenticate' => 1,
'userType' => UserConstants::USER_TYPE_SYSTEM
)
)
),
'userCompanyList' => [
]
);
$accessList[] = $d;
$session->set('userAccessList', $accessList);
}
///now update Server
///
if ($goc->getInitiateFlag() == 2 || $goc->getInitiateFlag() == 1) //pending Initiation and paid
{
///NOw pushing to server
$output = '';
$file = $this->container->getParameter('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);
}
}
$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(),
'company_address' => $goc->getAddress(),
'company_s_address' => $goc->getShippingAddress(),
'company_b_address' => $goc->getBillingAddress(),
'company_image' => $goc->getImage(),
'company_motto' => $goc->getMotto(),
'company_i_footer' => $goc->getInvoiceFooter(),
'company_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' => '@' . $usageValidUpto->format('U'),
// '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);
$goc->setInitiateFlag(1);// initiated
}
}
return new JsonResponse(array(
'user_access_data' => $d,
'initiated' => 1
));
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$findByQuery = array(
// 'active' => 1
'appId' => $post->get('app_id')
);
$goc = $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy($findByQuery);
if (!$goc)
$goc = new CompanyGroup();
$goc->setName($post->get('company_name'));
$goc->setCompanyGroupHash($post->get('companyGroupHash'));
$goc->setAppId($post->get('app_id'));
// $goc->setCompanyType($post->get('company_type'));
$goc->setAddress($post->get('address'));
// $goc->setDarkVibrant($post->get('dark_vibrant'));
// $goc->setLightVibrant($post->get('light_vibrant'));
// $goc->setVibrant($post->get('vibrant'));
$goc->setDbName($post->get('db_name'));
$goc->setDbUser($post->get('db_user'));
$goc->setDbPass($post->get('db_pass'));
$goc->setDbHost($post->get('db_host'));
$goc->setActive(1);
$goc->setShippingAddress($post->get('s_address'));
$goc->setBillingAddress($post->get('b_address'));
$goc->setMotto($post->get('motto'));
$goc->setInvoiceFooter($post->get('i_footer'));
$goc->setGeneralFooter($post->get('g_footer'));
$goc->setCompanyReg($post->get('company_reg', ''));
$goc->setCompanyTin($post->get('company_tin', ''));
$goc->setCompanyBin($post->get('company_bin', ''));
$goc->setCompanyTl($post->get('company_tl', ''));
$goc->setCompanyType($post->get('company_type', ''));
$goc->setCurrentSubscriptionPackageId($post->get('package', ''));
// $goc->setCu($post->get('package', ''));
$goc->setAdminUserAllowed($post->get('number_of_admin_user', ''));
$goc->setUserAllowed($post->get('number_of_user', ''));
$goc->setSubscriptionMonth($post->get('subscription_month', ''));
$goc->setCompanyDescription($post->get('company_description', ''));
$goc->setCompanyGroupServerId($post->get('companyGroupServerId', ''));
$goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress', ''));
$goc->setCompanyGroupServerPort($post->get('companyGroupServerPort', ''));
$goc->setCompanyGroupServerHash($post->get('companyGroupServerHash', ''));
// $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
// $goc->setSmsSettings($post->get('sms_settings'));
foreach ($request->files as $uploadedFile) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$fileName = 'company_image' . $post->get('app_id') . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage())) {
unlink($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage());
}
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
if ($path != "")
$goc->setImage('/uploads/CompanyImage/' . $path);
}
}
$em_goc->persist($goc);
$em_goc->flush();
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$goc->getDbName(),
$goc->getDbUser(),
$goc->getDbPass(),
$goc->getDbHost(),
$reset = true);
$em = $this->getDoctrine()->getManager();
$prePopulateFlag = 0;
if ($em->getConnection()->isConnected()) {
} else {
$servername = $goc->getDbHost();
$username = $goc->getDbUser();
$password = $goc->getDbPass();
// Create connection
$conn = new \mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE " . $goc->getDbName();
if ($conn->query($sql) === TRUE) {
$prePopulateFlag = 1;
// echo "Database created successfully";
} else {
// echo "Error creating database: " . $conn->error;
}
$conn->close();
}
$connector->resetConnection(
'default',
$goc->getDbName(),
$goc->getDbUser(),
$goc->getDbPass(),
$goc->getDbHost(),
$reset = true);
$em = $this->getDoctrine()->getManager();
$tool = new SchemaTool($em);
$classes = $em->getMetadataFactory()->getAllMetadata();
// $tool->createSchema($classes);
$tool->updateSchema($classes);
if ($prePopulateFlag == 1) {
System::prePopulateDatabase($em);
}
//now modify the company
$company = $em
->getRepository('ApplicationBundle:Company')
->findOneBy(
array()
);
if (!$company)
$company = new Company();
$company->setImage($goc->getImage());
$company->setName($post->get('company_name'));
$company->setCompanyHash($post->get('company_short_code'));
$company->setAppId($post->get('app_id'));
$company->setActive(1);
$company->setAddress($post->get('address'));
$company->setShippingAddress($post->get('s_address'));
$company->setBillingAddress($post->get('b_address'));
$company->setMotto($post->get('motto'));
$company->setInvoiceFooter($post->get('i_footer'));
$company->setGeneralFooter($post->get('g_footer'));
$company->setCompanyReg($post->get('company_reg', ''));
$company->setCompanyTin($post->get('company_tin', ''));
$company->setCompanyBin($post->get('company_bin', ''));
$company->setCompanyTl($post->get('company_tl', ''));
$company->setCompanyType($post->get('company_type', ''));
$company->setAdminUserAllowed($post->get('number_of_admin_user', ''));
$company->setUserAllowed($post->get('number_of_user', ''));
// $company->setCompanyGroupServerId($post->get('companyGroupServerId', ''));
// $company->setCompanyGroupServerAddress($post->get('companyGroupServerAddress', ''));
// $company->setCompanyGroupServerPort($post->get('companyGroupServerPort', ''));
$company->setCompanyHash($post->get('companyGroupHash', ''));
// $company->setCompanyGroupServerHash($post->get('companyGroupServerHash', ''));
//new fields
if ($post->get('usage_valid_upto_dt_str', null) != null) {
$usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str', null));
$company->setUsageValidUptoDate($usageValidUpto);
$company->setUsageValidUptoDateTs($usageValidUpto->format('U'));
} else {
$company->setUsageValidUptoDate(null);
$company->setUsageValidUptoDateTs(0);
}
$em->persist($company);
$em->flush();
//initiate Admin
$userName = $request->request->get('username', $request->query->get('username', 'admin'));
$name = $request->request->get('name', $request->query->get('name', 'System Admin'));
$password = $request->request->get('password', $request->query->get('password', 'admin'));
$email = $request->request->get('email', $request->query->get('email', 'admin'));
$encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userName);
$companyIds = $request->request->get('companyIds', $request->query->get('companyIds', [1]));
$branchIds = $request->request->get('branchIds', $request->query->get('branchIds', []));
$appIds = $request->request->get('appIds', $request->query->get('appIds', [$post->get('app_id', 0)]));
$freshFlag = $request->request->get('fresh', $request->query->get('fresh', 0));
$message = $this->get('user_module')->addNewUser(
$name,
$email,
$userName,
$password,
'',
0,
1,
UserConstants::USER_TYPE_SYSTEM,
$companyIds,
$branchIds,
'',
"",
1
);
$post_fields = array(
'app_id' => $company->getAppId(),
);
return new JsonResponse($post_fields);
}
}
//update database schema
public function RunScheduledNotificationAction(Request $request)
{
$message = "";
$gocList = [];
$outputList = [];
$scheduler = $this->get('scheduler_service');
$connector = $this->get('application_connector');
$mail_module = $this->get('mail_module');
$gocEnabled = 1;
// if($this->getContainer()->hasParameter('entity_group_enabled'))
// $gocEnabled= $this->getContainer()->getParameter('entity_group_enabled');
// $to_print=$app_data->UpdatePostDatedTransaction();
// $output->writeln($to_print);
$to_print = $scheduler->checkAndSendScheduledNotification($connector, $gocEnabled, 0, $mail_module);
return new JsonResponse(array(
'to_print' => $to_print
));
}
public function UpdateDatabaseSchemaAction(Request $request)
{
$dtHere = array(
'autoStartUpdateHit' => $request->query->get('autoStartUpdateHit', 0),
'page_title' => 'Server Actions',
);
if ($request->query->get('returnJson', 0) == 1) {
$message = "";
$gocList = [];
$outputList = [];
$configJson = array();
$configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
$configJson['success'] = false;
$configJson['debugData'] = [];
$configJson['pending_doc_count'] = 0;
$configJson['initiateDataBaseFlagByGoc'] = array();
$configJson['motherLode'] = "http://erp.ourhoneybee.eu";
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$thisMomentNow = new \DateTime();
$currTimeTs = $thisMomentNow->format('U');
$em = $this->getDoctrine()->getManager('company_group');
$em_goc = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
$serverId = $this->container->hasParameter('server_id') ? $this->container->getParameter('server_id') : '_ALL_';
if ($connected) {
if ($request->query->get('prepareEntityGroup', 0) == 1) {
$tool = new SchemaTool($em);
$classes = $em->getMetadataFactory()->getAllMetadata();
// $tool->createSchema($classes);
$tool->updateSchema($classes);
if ($request->query->get('fixEmptyPassword', 0) == 1) {
$query = "SELECT * from entity_applicant_details where password not like '##UNLOCKED##'";
$stmt = $em_goc->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $qpo) {
if ($this->container->get('sha256salted_encoder')->isPasswordValid($qpo['password'], '', $qpo['salt'])
|| $this->container->get('sha256salted_encoder')->isPasswordValid($qpo['password'], null, $qpo['salt'])
) {
$queryGG = "update entity_applicant_details set password ='##UNLOCKED##' and trigger_reset_password=1 where applicant_id=" . $qpo['applicant_id'];
$stmt = $em_goc->getConnection()->prepare($queryGG);
$stmt->execute();
$stmt->closeCursor();
}
}
}
if ($request->query->get('triggerReferScore', 0) == 1) {
$query = "SELECT * from entity_meeting_session where booked_by_id !=0 and booked_by_id is not NULL and booked_by_id !=student_id";
$stmt = $em_goc->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $qpo) {
MiscActions::updateEntityPerformanceIndex($em_goc, [
'targetId' => $qpo['booked_by_id'],
'conversionData' => [
'count' => 1,
'score' => 10,
]
],
new \DateTime($qpo['created_at']));
}
$query = "SELECT * from entity_meeting_session where booking_referer_id !=0 and booking_referer_id is not NULL and booking_referer_id !=student_id";
$stmt = $em_goc->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $qpo) {
MiscActions::updateEntityPerformanceIndex($em_goc, [
'targetId' => $qpo['booking_referer_id'],
'referData' => [
'count' => 1,
'score' => 10,
]
],
new \DateTime($qpo['created_at'])
);
}
}
if ($request->query->get('refreshBuddyBeeSalt', 0) == 1) {
$query = "
UPDATE entity_applicant_details set temp_password='' where 1;
UPDATE entity_applicant_details set salt=username where username != '' and username is not NULL and (salt ='' or salt is NULL);
UPDATE entity_applicant_details set salt='beesalt' where (salt ='' or salt is NULL) and (username ='' or username is NULL);
";
$stmt = $em_goc->getConnection()->prepare($query);
$stmt->execute();
$stmt->closeCursor();
}
if ($request->query->get('refreshLastSettingsUpdatedTs', 0) == 1) {
$query = "
UPDATE entity_user set last_settings_updated_ts=$currTimeTs where 1;
UPDATE entity_applicant_details set last_settings_updated_ts=$currTimeTs where 1;
";
$stmt = $em_goc->getConnection()->prepare($query);
$stmt->execute();
$stmt->closeCursor();
}
$get_kids_sql = "update `company_group` set `schema_update_pending_flag` =1 where 1;";
$stmt = $em_goc->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
$stmt = $em_goc->getConnection()->prepare("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
$stmt->execute();
$check_here = $stmt->fetchAll();
$pending_id_count = 0;
if (isset($check_here[0]))
$pending_id_count = $check_here[0]['id_count'];
return new JsonResponse(array(
'pending_doc_count' => $pending_id_count,
'success' => true
));
} else
if ($systemType != '_CENTRAL_') {
$stmt = $em_goc->getConnection()->prepare("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
$stmt->execute();
$check_here = $stmt->fetchAll();
if (isset($check_here[0]))
$configJson['pending_doc_count'] = $check_here[0]['id_count'];
// if($serverId!='_ALL_')
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(
array(
'active' => 1,
// 'serverId' => 1,
'schemaUpdatePendingFlag' => 1
), array(), 1
);
}
}
$gocDataList = [];
$gocEntryObjectList = [];
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'image' => $entry->getImage(),
'shippingAddress' => $entry->getShippingAddress(),
'billingAddress' => $entry->getBillingAddress(),
'id' => $entry->getId(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocEntryObjectList[$entry->getId()] = $entry;
}
$gocDbName = '';
$gocDbUser = '';
$gocDbPass = '';
$gocDbHost = '';
$gocId = 0;
foreach ($gocDataList as $gocId => $entry) {
if (1) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
$configJson['name'] = $entry['name'];
$configJson['image'] = $entry['image'];
$configJson['appId'] = $entry['appId'];
if ($request->query->get('delTable', '') != '') {
$get_kids_sql = "DROP TABLE " . $request->query->get('delTable') . " ;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
$tool = new SchemaTool($em);
$classes = $em->getMetadataFactory()->getAllMetadata();
// $tool->createSchema($classes);
$tool->updateSchema($classes);
//temp
//temp end
if ($request->query->get('refreshLastSettingsUpdatedTs', 0) == 1) {
$query = "
UPDATE sys_user set last_settings_updated_ts=$currTimeTs where 1;
UPDATE acc_clients set last_settings_updated_ts=$currTimeTs where 1;
UPDATE acc_suppliers set last_settings_updated_ts=$currTimeTs where 1;
";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$stmt->closeCursor();
}
if ($request->query->get('encryptTrans', 0) == 1) {
MiscActions::encryptTrans($em, '_ALL_', 0);
}
if ($request->query->get('decryptTrans', 0) == 1) {
MiscActions::decryptTrans($em, '_ALL_', 0);
}
if ($request->query->get('createdByRefresh', 0) == 1) {
foreach (GeneralConstant::$Entity_list as $entity => $entityName) {
if (in_array($entity, [54]))
continue;
if (!$em->getMetadataFactory()->isTransient('ApplicationBundle:' . $entityName)) {
// $className = ('\\ApplicationBundle\\Entity\\') . $entityName;
// $theEntity = new $className();
// $test_now=$theEntity->getCreatedUserId();
//if its approval decode signature and add it to dbase and pass the id
$sigId = null;
$doc = null;
$docList = $em->getRepository('ApplicationBundle:' . $entityName)
->findBy(
array(// GeneralConstant::$Entity_id_field_list[$entity] => $entity_id,
)
);
foreach ($docList as $doc) {
$notYetAdded = 1;
foreach ([1, 2] as $approveRole) {
$getIdfunc = GeneralConstant::$Entity_id_get_method_list[$entity];
$entity_id = $doc->$getIdfunc();
$loginId = null;
$sigId = null;
$user_data = [];
if ($approveRole == 1) //created
{
$loginId = $doc->getCreatedLoginId();
$notYetAdded = $doc->getCreatedUserId() == null ? 1 : 0;
$sigId = $doc->getCreatedSigId();
$user_data = Users::getUserInfoByLoginId($em, $loginId);
if (isset($user_data['id'])) {
$doc->setCreatedUserId($user_data['id']);
$doc->setCreatedSigId(null);
}
$em->flush();
}
if ($approveRole == 2) //edited
{
$loginId = $doc->getEditedLoginId();
$sigId = $doc->getEditedSigId();
$notYetAdded = $doc->getEditedUserId() == null ? 1 : 0;
$user_data = Users::getUserInfoByLoginId($em, $loginId);
$doc->setEditedSigId($sigId);
if (isset($user_data['id'])) {
$doc->setEditedUserId($user_data['id']);
$doc->setEditedSigId(null);
$doc->setLastModifiedDate(new \DateTime());
}
$em->flush();
}
if (isset($user_data['id']) && $notYetAdded == 1) {
$new = new Approval();
$new->setEntity($entity);
$new->setEntityId($entity_id);
$new->setPositionId(null);
$new->setSequence(0);
$new->setSkipPrintFlag(0);
$new->setUserAssignType(1);
$new->setDocumentHash($doc->getDocumentHash());
// $new->setUserIds($value->getUserId()); //<-----
$new->setRoleType($approveRole);
$new->setRequired(0);
$new->setSuccession(0);
$new->setAction(1); //pending status
$new->setLoginId($loginId); //pending status
$new->setCurrent(GeneralConstant::CURRENTLY_NON_PENDING_APPROVAL);
$new->setSuccessionTimeout(0);
$new->setSigId($sigId);
$new->setNote('');
$new->setUserIds(json_encode([$user_data['id']])); //<-----
$em->persist($new);
$em->flush();
}
}
}
}
}
}
if ($request->query->get('rectifyOldBoq', 0) == 1) {
$boqs = $em
->getRepository('ApplicationBundle:ProjectBoq')
->findby(array(// 'projectId'=>$projectId
));
foreach ($boqs as $boq) {
//
// //now the data
// $data = [];
// $newData = [];
// if ($boq)
// $data = json_decode($boq->getData(), true);
// if ($data == null)
// $data = [];
// $defValuesProduct = array(
// 'product_note' => '',
// 'product_alias' => '',
// 'is_foreign_item' => 0,
// 'product_segmentIndex' => 0,
// 'product_currency_id' => 0,
// 'product_currency_text' => '',
// 'product_currency_multiply_rate' => 1,
// 'product_scope' => 1,
// 'product_scopeHolderId' => 0,
// 'product_scopeHolderName' => '',
// 'product_scopeDescription' => '',
// );
// $defValuesService = array(
// 'service_note' => '',
// 'service_alias' => '',
// 'is_foreign_service' => 0,
// 'service_segmentIndex' => 0,
// 'service_currency_id' => 0,
// 'service_currency_text' => '',
// 'service_currency_multiply_rate' => 1,
// 'service_scope' => 1,
// 'service_scopeHolderId' => 0,
// 'service_scopeHolderName' => '',
// 'service_scopeDescription' => '',
// );
//
//
// if (!empty($data)) {
// $last_key = array_key_last($data);
//// if (isset($data[$last_key]['Products']['product_scope']))
//// continue;
//// if (count($data[$last_key]['Products']['products'])==count($data[$last_key]['Products']['is_foreign_item']) )
//
//
// $kho = 0;
// $dt_poka = $data[0];
// foreach ($data as $kho => $dt_poka) {
//
//
// if (isset($dt_poka['Products']['products']))
// foreach ($defValuesProduct as $gopaa => $boka) {
// if (!isset($dt_poka['Products'][$gopaa]))
// $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
// else if ($dt_poka['Products'][$gopaa] == null)
// $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
//
//
// }
// if (isset($dt_poka['Services']['services']))
// foreach ($defValuesService as $gopaa => $boka) {
// if (!isset($dt_poka['Services'][$gopaa]))
// $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
// else if ($dt_poka['Services'][$gopaa] == null)
// $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
//
// }
//
// if (!isset($dt_poka['serviceSegmentData']))
// $dt_poka['serviceSegmentData'] = [
// array(
// "title" => "General Services",
// "index" => 0,
// )
// ];
// else if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
// $dt_poka['serviceSegmentData'] = [
// array(
// "title" => "General Services",
// "index" => 0,
// )
// ];
//
// if (!isset($dt_poka['productSegmentData']))
// $dt_poka['productSegmentData'] = [
// array(
// "title" => "General Items",
// "index" => 0,
// )
// ];
// else if ($dt_poka['productSegmentData'] == null || empty($dt_poka['productSegmentData']))
// $dt_poka['productSegmentData'] = [
// array(
// "title" => "General Items",
// "index" => 0,
// )
// ];
//
//
// $newData[$kho] = $dt_poka;
// }
//
//
// $boq->setData(json_encode($newData));
// $em->flush();
//
//
// }
$theProj = $em->getRepository('ApplicationBundle:Project')
->findOneBy(
array(
'projectId' => $boq->getProjectId()
)
);
if ($theProj)
$theProj->setDocumentDataId($boq->getDocumentDataId());
$em->flush();
}
}
if ($request->query->get('oldBoqToNewSystem', 0) == 1) {
$entitiesGG = [
array_flip(GeneralConstant::$Entity_list)['ProjectBoq'],
array_flip(GeneralConstant::$Entity_list)['ProjectMaterial'],
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
array_flip(GeneralConstant::$Entity_list)['SalesLead'],
array_flip(GeneralConstant::$Entity_list)['ProjectOffer'],
array_flip(GeneralConstant::$Entity_list)['ProjectProposal'],
];
foreach ($entitiesGG as $ent) {
$entityNameHere = GeneralConstant::$Entity_list[$ent];
$the_actual_docs = $em->getRepository('ApplicationBundle:' . GeneralConstant::$Entity_list[$ent])
->findBy(
array(// GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
)
);
foreach ($the_actual_docs as $the_actual_doc) {
//now the data
//first find the docData if available
$theDocData = null;
if ($entityNameHere == 'SalesProposal' || $entityNameHere == 'SalesLead') {
$theDocData = $em->getRepository('ApplicationBundle:DocumentData')
->findOneBy(
array(
'id' => $the_actual_doc->getDocumentDataId()
)
);
if (!$theDocData)
if ($the_actual_doc->getSalesProposalId() != null && $the_actual_doc->getSalesProposalId() != 0)
$theDocData = $em->getRepository('ApplicationBundle:DocumentData')
->findOneBy(
array(
'proposalId' => $the_actual_doc->getSalesProposalId()
)
);
if (!$theDocData)
if ($the_actual_doc->getLeadId() != null && $the_actual_doc->getLeadId() != 0)
$theDocData = $em->getRepository('ApplicationBundle:DocumentData')
->findOneBy(
array(
'leadId' => $the_actual_doc->getLeadId()
)
);
if (!$theDocData)
if ($the_actual_doc->getProjectId() != null && $the_actual_doc->getProjectId() != 0)
$theDocData = $em->getRepository('ApplicationBundle:DocumentData')
->findOneBy(
array(
'projectId' => $the_actual_doc->getProjectId()
)
);
if (!$theDocData) {
$theDocData = new DocumentData();
if ($entityNameHere == 'SalesProposal')
$theDocData->setProposalId($the_actual_doc->getSalesProposalId());
if ($entityNameHere == 'SalesLead')
$theDocData->setLeadId($the_actual_doc->getLeadId());
}
} else {
$theDocData = $em->getRepository('ApplicationBundle:DocumentData')
->findOneBy(
array(
'id' => $the_actual_doc->getDocumentDataId()
)
);
if (!$theDocData)
$theDocData = $em->getRepository('ApplicationBundle:DocumentData')
->findOneBy(
array(
'projectId' => $the_actual_doc->getProjectId()
)
);
if (!$theDocData) {
$theDocData = new DocumentData();
$theDocData->setProjectId($the_actual_doc->getProjectId());
}
}
if ($entityNameHere == 'ProjectBoq' || $entityNameHere == 'SalesLead' || $entityNameHere == 'SalesProposal') {
$data = [];
$newData = [];
$data = json_decode($the_actual_doc->getData(), true);
if ($data == null)
$data = [];
if (!empty($data)) {
$last_key = array_key_last($data);
$lastIndex = 0;
foreach ($data as $kho => $dt_poka) {
$cur_date = new \DateTime();
$lead_date = new \DateTime(isset($dt_poka['lead_date']) ? $dt_poka['lead_date'] : '');
$newSingleSet = array(
'refPoNumber' => isset($dt_poka['refPoNumber']) ? $dt_poka['refPoNumber'] : '',
'segmentData' => isset($dt_poka['segmentData']) ? $dt_poka['segmentData'] : [],
'proposal_title' => isset($dt_poka['proposal_title']) ? $dt_poka['proposal_title'] : '',
'to_position' => isset($dt_poka['to_position']) ? $dt_poka['to_position'] : '',
'system_subCategory' => isset($dt_poka['system_subCategory']) ? $dt_poka['system_subCategory'] : '',
'system_size' => isset($dt_poka['system_size']) ? $dt_poka['system_size'] : '',
'system_unit' => isset($dt_poka['system_unit']) ? $dt_poka['system_unit'] : '',
'system_price' => isset($dt_poka['system_price']) ? $dt_poka['system_price'] : '',
'msaTotal' => isset($dt_poka['msaTotal']) ? $dt_poka['msaTotal'] : 0,
'totalProjectValue' => isset($dt_poka['totalProjectValue']) ? $dt_poka['totalProjectValue'] : 0,
'cl_subject' => isset($dt_poka['cl_subject']) ? $dt_poka['cl_subject'] : '',
'cl_body' => isset($dt_poka['cl_body']) ? $dt_poka['cl_body'] : '',
'vatPercentage' => isset($dt_poka['vatPercentage']) ? $dt_poka['vatPercentage'] : '',
'aitPercentage' => isset($dt_poka['aitPercentage']) ? $dt_poka['aitPercentage'] : '',
'proposalSalesValue' => isset($dt_poka['proposalSalesValue']) ? $dt_poka['proposalSalesValue'] : '',
'combined_proposal_item_name' => isset($dt_poka['combined_proposal_item_name']) ? $dt_poka['combined_proposal_item_name'] : '',
'combined_proposal_details_price' => isset($dt_poka['combined_proposal_details_price']) ? $dt_poka['combined_proposal_details_price'] : '',
'check_boq' => isset($dt_poka['check_boq']) ? $dt_poka['check_boq'] : 0,
'check_boq_individual_price' => isset($dt_poka['check_boq_individual_price']) ? $dt_poka['check_boq_individual_price'] : 0,
'check_show_combined_only' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
'check_override_markup' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
'clientId' => isset($dt_poka['client_id']) ? $dt_poka['client_id'] : 0,
'salesPersonId' => isset($dt_poka['salesPersonID']) ? $dt_poka['salesPersonID'] : 0,
'clientName' => isset($dt_poka['clientName']) ? $dt_poka['clientName'] : '',
'ClientContactPerson' => isset($dt_poka['ClientContactPerson']) ? $dt_poka['ClientContactPerson'] : '',
'ClientContactNumber' => isset($dt_poka['ClientContactNumber']) ? $dt_poka['ClientContactNumber'] : '',
'ClientDeliveryAddress' => isset($dt_poka['ClientDeliveryAddress']) ? $dt_poka['ClientDeliveryAddress'] : '',
'ClientBillingAddress' => isset($dt_poka['ClientBillingAddress']) ? $dt_poka['ClientBillingAddress'] : '',
'leadDate' => $lead_date->format('Y-m-d'),
'date' => $cur_date->format('Y-m-d'),
);
$newSegmentData = array();
$oldSegmentSystem = 0;
if (isset($dt_poka['productSegmentData']) || isset($dt_poka['serviceSegmentData']))
$oldSegmentSystem = 1;
if ($oldSegmentSystem == 1) {
//unify the ids of segmnent. services will start from 1000+service segmentId for unification
if (isset($dt_poka['productSegmentData']))
foreach ($dt_poka['productSegmentData'] as $supu => $gupu) {
$newModSeg = $gupu;
$newModSeg['index'] = $gupu['index'];
$newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Items';
$newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
$newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
$newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
$newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
$newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
$newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
$newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
$newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
$newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
$newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
$newSegmentData[] = $newModSeg;
}
if (isset($dt_poka['serviceSegmentData']))
if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
foreach ($dt_poka['serviceSegmentData'] as $supu => $gupu) {
if ($gupu['index'] == 'undefined') $gupu['index'] = 0;
if (!is_numeric($gupu['index'])) $gupu['index'] = 0;
$newModSeg = $gupu;
$newModSeg['index'] = 1000 + 1 * $gupu['index'];
$newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Services';
$newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
$newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
$newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
$newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
$newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
$newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
$newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
$newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
$newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
$newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
$newSegmentData[] = $newModSeg;
}
$newSingleSet['itemSegmentData'] = $newSegmentData;
}
$lastSequenceBySegment = array();
//now modify Services or products
$oldProductSystem = 0;
if (!isset($dt_poka['rowData']))
$dt_poka['rowData'] = array();
if (isset($dt_poka['Products']) || isset($dt_poka['Services']) || isset($dt_poka['ArCosts'])) {
$oldProductSystem = 1;
}
if ($oldProductSystem == 1) {
$theDt = array(
'products' => [],
'services' => [],
'ar_heads' => [],
);
if (isset($dt_poka['Products']))
$theDt = $dt_poka['Products'];
if (isset($theDt['products']))
foreach ($theDt['products'] as $f => $pid) {
$unit = isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0;
$indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
if ($indexForThis == -1) {
$indexForThis = $lastIndex;
$lastIndex++;
}
$unitPrice = isset($theDt['product_unit_price'][$f]) ? $theDt['product_unit_price'][$f] : 0;
if ($unit == '') $unit = 0;
if ($unitPrice == '') $unitPrice = 0;
$totalPrice = $unit * $unitPrice;
$segmentIndex = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : 0;
$sequence = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : '_UNSET_';
if (!isset($lastSequenceBySegment[$segmentIndex]))
$lastSequenceBySegment[$segmentIndex] = -1;
if ($sequence == '_UNSET_')
$sequence = $lastSequenceBySegment[$segmentIndex] + 1;
else if ($sequence == $lastSequenceBySegment[$segmentIndex])
$sequence = $lastSequenceBySegment[$segmentIndex] + 1;
$lastSequenceBySegment[$segmentIndex] = $sequence;
$unitSalesPrice = isset($theDt['product_unit_sales_price'][$f]) ? $theDt['product_unit_sales_price'][$f] : $unitPrice;
if ($unitSalesPrice == '') $unitSalesPrice = 0;
$totalSalesPrice = $unit * $unitSalesPrice;
$marginAmount = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitSalesPrice - $unitPrice);
$marginRate = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitPrice == 0 ? 0 : (100 * $marginAmount / $unitPrice));
$discountAmount = isset($theDt['product_dr'][$f]) ? $theDt['product_dr'][$f] : 0;
$discountRate = isset($theDt['product_da'][$f]) ? $theDt['product_da'][$f] : ($totalSalesPrice == 0 ? 0 : (100 * $discountAmount / $totalSalesPrice));
$discountedAmount = $totalSalesPrice - $discountAmount;
$taxRate = isset($theDt['product_tax_percentage'][$f]) ? $theDt['product_tax_percentage'][$f] : ($unitPrice == 0 ? 0 : (100 * $discountAmount / $unitPrice));
$taxAmount = isset($theDt['product_tax_amount'][$f]) ? $theDt['product_tax_amount'][$f] : 0;
$finalAmount = $discountedAmount + $taxAmount;
$row = array(
'type' => 1,//1:product 2=service 4=tools 5:text 6: expense against head
'id' => $pid,
'index' => $indexForThis,
'isForeign' => isset($theDt['is_foreign_item'][$f]) ? $theDt['is_foreign_item'][$f] : 0,
'sequence' => $sequence,
'segmentIndex' => $segmentIndex,
'soItemId' => isset($theDt['product_soItemId'][$f]) ? $theDt['product_soItemId'][$f] : 0,
'soItemDelivered' => isset($theDt['product_soItemDelivered'][$f]) ? $theDt['product_soItemDelivered'][$f] : 0,
'soItemFound' => isset($theDt['product_soItemFound'][$f]) ? $theDt['product_soItemFound'][$f] : 0,
'alias' => isset($theDt['product_alias'][$f]) ? $theDt['product_alias'][$f] : '',
'name' => isset($theDt['product_name'][$f]) ? $theDt['product_name'][$f] : '',
'note' => isset($theDt['product_note'][$f]) ? $theDt['product_note'][$f] : '',
'fdm' => isset($theDt['product_fdm'][$f]) ? $theDt['product_fdm'][$f] : null,
'unit' => isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0,
'unitTypeId' => isset($theDt['product_unit_type'][$f]) ? $theDt['product_unit_type'][$f] : 0,
'unitPrice' => $unitPrice,
'totalPrice' => $totalPrice,
'unitSalesPrice' => $unitSalesPrice,
'totalSalesPrice' => $totalSalesPrice,
'marginRate' => $marginRate,
'marginAmount' => $marginAmount,
'discountRate' => $discountRate,
'discountAmount' => $discountAmount,
'discountedAmount' => $discountedAmount,
'taxRate' => $taxRate,
'taxAmount' => $taxAmount,
'finalAmount' => $finalAmount,
'recurring' => isset($theDt['product_recurring'][$f]) ? $theDt['product_recurring'][$f] : 0,
'currency' => isset($theDt['product_currency_id'][$f]) ? $theDt['product_currency_id'][$f] : 0,
'currencyText' => isset($theDt['product_currency_text'][$f]) ? $theDt['product_currency_text'][$f] : '',
'currencyMultiplyRate' => isset($theDt['product_currency_multiply_rate'][$f]) ? $theDt['product_currency_multiply_rate'][$f] : 1,
'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
'taxId' => isset($theDt['product_tax_config_id'][$f]) ? $theDt['product_tax_config_id'][$f] : 0,
'taxName' => isset($theDt['product_tax_config_text'][$f]) ? $theDt['product_tax_config_text'][$f] : '',
'dependencyOnIndex' => isset($theDt['product_dependency_of_index'][$f]) ? $theDt['product_dependency_of_index'][$f] : 0,
'dependencyOnPid' => isset($theDt['product_dependency_of_product_id'][$f]) ? $theDt['product_dependency_of_product_id'][$f] : 0,
'dependencyOnSid' => isset($theDt['product_dependency_of_service_id'][$f]) ? $theDt['product_dependency_of_service_id'][$f] : 0,
'dependencyOnSegment' => isset($theDt['product_dependency_of_product_index'][$f]) ? $theDt['product_dependency_of_product_index'][$f] : 0,
'warranty' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : 0,
'origin' => isset($theDt['product_origin'][$f]) ? $theDt['product_origin'][$f] : 0,
'origins' => isset($theDt['product_origin'][$f]) ? [$theDt['product_origin'][$f]] : [],
'scope' => isset($theDt['product_scope'][$f]) ? $theDt['product_scope'][$f] : 0,
'scopeId' => isset($theDt['product_scopeHolderId'][$f]) ? [$theDt['product_scopeHolderId'][$f]] : 0,
'scopeName' => isset($theDt['product_scopeHolderName'][$f]) ? [$theDt['product_scopeHolderName'][$f]] : '',
'scopeDescription' => isset($theDt['product_scopeDescription'][$f]) ? [$theDt['product_scopeDescription'][$f]] : '',
'deliverySchedule' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : [],
'deliveryPorts' => isset($theDt['product_delivery_ports'][$f]) ? $theDt['product_delivery_ports'][$f] : [],
'billingSchedule' => isset($theDt['product_billing_schedule'][$f]) ? $theDt['product_billing_schedule'][$f] : [],
'referenceNo' => isset($theDt['product_reference_price'][$f]) ? $theDt['product_reference_price'][$f] : '',
'referenceFiles' => isset($theDt['product_reference_price_file'][$f]) ? $theDt['product_reference_price_file'][$f] : '',
);
$dt_poka['rowData'][] = $row;
}
//now the services
$theDt = array(
'products' => [],
'services' => [],
'ar_heads' => [],
);
if (isset($dt_poka['Services']))
$theDt = $dt_poka['Services'];
if (isset($theDt['services']))
foreach ($theDt['services'] as $f => $pid) {
$unit = isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0;
$indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
if ($indexForThis == -1) {
$indexForThis = $lastIndex;
$lastIndex++;
}
$unitPrice = isset($theDt['service_unit_price'][$f]) ? $theDt['service_unit_price'][$f] : 0;
$totalPrice = $unit * $unitPrice;
$segmentIndex = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : 0;
if ($segmentIndex == 'undefined') $segmentIndex = 0;
if (!is_numeric($segmentIndex)) $segmentIndex = 0;
if ($oldSegmentSystem == 1)
$segmentIndex = 1000 + $segmentIndex;
$sequence = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : '_UNSET_';
if (!isset($lastSequenceBySegment[$segmentIndex]))
$lastSequenceBySegment[$segmentIndex] = -1;
if ($sequence == '_UNSET_')
$sequence = $lastSequenceBySegment[$segmentIndex] + 1;
else if ($sequence == $lastSequenceBySegment[$segmentIndex])
$sequence = $lastSequenceBySegment[$segmentIndex] + 1;
$lastSequenceBySegment[$segmentIndex] = $sequence;
$unitSalesPrice = isset($theDt['service_unit_sales_price'][$f]) ? $theDt['service_unit_sales_price'][$f] : $unitPrice;
$totalSalesPrice = $unit * $unitSalesPrice;
$marginAmount = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitSalesPrice - $unitPrice);
$marginRate = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitPrice == 0 ? 0 : (100 * $marginAmount / $unitPrice));
$discountAmount = isset($theDt['service_dr'][$f]) ? $theDt['service_dr'][$f] : 0;
$discountRate = isset($theDt['service_da'][$f]) ? $theDt['service_da'][$f] : ($totalSalesPrice == 0 ? 0 : (100 * $discountAmount / $totalSalesPrice));
$discountedAmount = $totalSalesPrice - $discountAmount;
$taxRate = isset($theDt['service_tax_percentage'][$f]) ? $theDt['service_tax_percentage'][$f] : ($unitPrice == 0 ? 0 : (100 * $discountAmount / $unitPrice));
$taxAmount = isset($theDt['service_tax_amount'][$f]) ? $theDt['service_tax_amount'][$f] : 0;
$finalAmount = $discountedAmount + $taxAmount;
$row = array(
'type' => 2,//1:product 2=service 4=tools 5:text 6: expense against head
'id' => $pid,
'index' => $indexForThis,
'isForeign' => isset($theDt['is_foreign_service'][$f]) ? $theDt['is_foreign_service'][$f] : 0,
'sequence' => $sequence,
'segmentIndex' => $segmentIndex,
'soItemId' => isset($theDt['service_soItemId'][$f]) ? $theDt['service_soItemId'][$f] : 0,
'soItemDelivered' => isset($theDt['service_soItemDelivered'][$f]) ? $theDt['service_soItemDelivered'][$f] : 0,
'soItemFound' => isset($theDt['service_soItemFound'][$f]) ? $theDt['service_soItemFound'][$f] : 0,
'alias' => isset($theDt['service_alias'][$f]) ? $theDt['service_alias'][$f] : '',
'name' => isset($theDt['service_name'][$f]) ? $theDt['service_name'][$f] : '',
'note' => isset($theDt['service_note'][$f]) ? $theDt['service_note'][$f] : '',
'fdm' => isset($theDt['service_fdm'][$f]) ? $theDt['service_fdm'][$f] : null,
'unit' => isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0,
'unitTypeId' => isset($theDt['service_unit_type'][$f]) ? $theDt['service_unit_type'][$f] : 0,
'unitPrice' => $unitPrice,
'totalPrice' => $totalPrice,
'unitSalesPrice' => $unitSalesPrice,
'totalSalesPrice' => $totalSalesPrice,
'marginRate' => $marginRate,
'marginAmount' => $marginAmount,
'discountRate' => $discountRate,
'discountAmount' => $discountAmount,
'discountedAmount' => $discountedAmount,
'taxRate' => $taxRate,
'taxAmount' => $taxAmount,
'finalAmount' => $finalAmount,
'recurring' => isset($theDt['service_recurring'][$f]) ? $theDt['service_recurring'][$f] : 0,
'currency' => isset($theDt['service_currency_id'][$f]) ? $theDt['service_currency_id'][$f] : 0,
'currencyText' => isset($theDt['service_currency_text'][$f]) ? $theDt['service_currency_text'][$f] : '',
'currencyMultiplyRate' => isset($theDt['service_currency_multiply_rate'][$f]) ? $theDt['service_currency_multiply_rate'][$f] : 1,
'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
'taxId' => isset($theDt['service_tax_config_id'][$f]) ? $theDt['service_tax_config_id'][$f] : 0,
'taxName' => isset($theDt['service_tax_config_text'][$f]) ? $theDt['service_tax_config_text'][$f] : '',
'dependencyOnIndex' => isset($theDt['service_dependency_of_index'][$f]) ? $theDt['service_dependency_of_index'][$f] : 0,
'dependencyOnPid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
'dependencyOnSid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
'dependencyOnSegment' => isset($theDt['service_dependency_of_service_index'][$f]) ? $theDt['service_dependency_of_service_index'][$f] : 0,
'warranty' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : 0,
'origin' => isset($theDt['service_origin'][$f]) ? $theDt['service_origin'][$f] : 0,
'origins' => isset($theDt['service_origin'][$f]) ? [$theDt['service_origin'][$f]] : [],
'scope' => isset($theDt['service_scope'][$f]) ? $theDt['service_scope'][$f] : 0,
'scopeId' => isset($theDt['service_scopeHolderId'][$f]) ? [$theDt['service_scopeHolderId'][$f]] : 0,
'scopeName' => isset($theDt['service_scopeHolderName'][$f]) ? [$theDt['service_scopeHolderName'][$f]] : '',
'scopeDescription' => isset($theDt['service_scopeDescription'][$f]) ? [$theDt['service_scopeDescription'][$f]] : '',
'deliverySchedule' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : [],
'deliveryPorts' => isset($theDt['service_delivery_ports'][$f]) ? $theDt['service_delivery_ports'][$f] : [],
'billingSchedule' => isset($theDt['service_billing_schedule'][$f]) ? $theDt['service_billing_schedule'][$f] : [],
'referenceNo' => isset($theDt['service_reference_price'][$f]) ? $theDt['service_reference_price'][$f] : '',
'referenceFiles' => isset($theDt['service_reference_price_file'][$f]) ? $theDt['service_reference_price_file'][$f] : '',
);
$dt_poka['rowData'][] = $row;
}
//now accounts /Cost
$theDt = array(
'products' => [],
'services' => [],
'ar_heads' => [],
);
if (isset($dt_poka['ArCosts']))
$theDt = $dt_poka['ArCosts'];
if (isset($theDt['ar_heads']))
foreach ($theDt['ar_heads'] as $f => $pid) {
$unit = isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0;
if (!is_numeric($unit)) $unit = 0;
$indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
if ($indexForThis == -1) {
$indexForThis = $lastIndex;
$lastIndex++;
}
$unitPrice = isset($theDt['ar_unit_price'][$f]) ? $theDt['ar_unit_price'][$f] : 0;
if (!is_numeric($unitPrice)) $unitPrice = 0;
$totalPrice = $unit * $unitPrice;
$segmentIndex = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : 0;
if ($oldSegmentSystem == 1)
$segmentIndex = 1000 + $segmentIndex;
$sequence = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : '_UNSET_';
if (!isset($lastSequenceBySegment[$segmentIndex]))
$lastSequenceBySegment[$segmentIndex] = -1;
if ($sequence == '_UNSET_')
$sequence = $lastSequenceBySegment[$segmentIndex] + 1;
else if ($sequence == $lastSequenceBySegment[$segmentIndex])
$sequence = $lastSequenceBySegment[$segmentIndex] + 1;
$lastSequenceBySegment[$segmentIndex] = $sequence;
$unitSalesPrice = isset($theDt['ar_unit_sales_price'][$f]) ? $theDt['ar_unit_sales_price'][$f] : $unitPrice;
$totalSalesPrice = $unit * $unitSalesPrice;
$marginAmount = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitSalesPrice - $unitPrice);
$marginRate = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitPrice == 0 ? 0 : (100 * $marginAmount / $unitPrice));
$discountAmount = isset($theDt['ar_dr'][$f]) ? $theDt['ar_dr'][$f] : 0;
$discountRate = isset($theDt['ar_da'][$f]) ? $theDt['ar_da'][$f] : ($totalSalesPrice == 0 ? 0 : (100 * $discountAmount / $totalSalesPrice));
$discountedAmount = $totalSalesPrice - $discountAmount;
$taxRate = isset($theDt['ar_tax_percentage'][$f]) ? $theDt['ar_tax_percentage'][$f] : ($unitPrice == 0 ? 0 : (100 * $discountAmount / $unitPrice));
$taxAmount = isset($theDt['ar_tax_amount'][$f]) ? $theDt['ar_tax_amount'][$f] : 0;
$finalAmount = $discountedAmount + $taxAmount;
$row = array(
'type' => 6,//1:product 2=service 4=tools 5:text 6: expense against head
'id' => $pid,
'index' => $indexForThis,
'isForeign' => isset($theDt['is_foreign_cost'][$f]) ? $theDt['is_foreign_cost'][$f] : 0,
'sequence' => $sequence,
'segmentIndex' => $segmentIndex,
'soItemId' => isset($theDt['ar_soItemId'][$f]) ? $theDt['ar_soItemId'][$f] : 0,
'soItemDelivered' => isset($theDt['ar_soItemDelivered'][$f]) ? $theDt['ar_soItemDelivered'][$f] : 0,
'soItemFound' => isset($theDt['ar_soItemFound'][$f]) ? $theDt['ar_soItemFound'][$f] : 0,
'alias' => isset($theDt['ar_alias'][$f]) ? $theDt['ar_alias'][$f] : '',
'name' => isset($theDt['ar_name'][$f]) ? $theDt['ar_name'][$f] : '',
'note' => isset($theDt['ar_note'][$f]) ? $theDt['ar_note'][$f] : '',
'fdm' => isset($theDt['ar_fdm'][$f]) ? $theDt['ar_fdm'][$f] : null,
'unit' => isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0,
'unitTypeId' => isset($theDt['ar_unit_type'][$f]) ? $theDt['ar_unit_type'][$f] : 0,
'unitPrice' => $unitPrice,
'totalPrice' => $totalPrice,
'unitSalesPrice' => $unitSalesPrice,
'totalSalesPrice' => $totalSalesPrice,
'marginRate' => $marginRate,
'marginAmount' => $marginAmount,
'discountRate' => $discountRate,
'discountAmount' => $discountAmount,
'discountedAmount' => $discountedAmount,
'taxRate' => $taxRate,
'taxAmount' => $taxAmount,
'finalAmount' => $finalAmount,
'recurring' => isset($theDt['ar_recurring'][$f]) ? $theDt['ar_recurring'][$f] : 0,
'currency' => isset($theDt['ar_currency_id'][$f]) ? $theDt['ar_currency_id'][$f] : 0,
'currencyText' => isset($theDt['ar_currency_text'][$f]) ? $theDt['ar_currency_text'][$f] : '',
'currencyMultiplyRate' => isset($theDt['ar_currency_multiply_rate'][$f]) ? $theDt['ar_currency_multiply_rate'][$f] : 1,
'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
'taxId' => isset($theDt['ar_tax_config_id'][$f]) ? $theDt['ar_tax_config_id'][$f] : 0,
'taxName' => isset($theDt['ar_tax_config_text'][$f]) ? $theDt['ar_tax_config_text'][$f] : '',
'dependencyOnIndex' => isset($theDt['ar_dependency_of_index'][$f]) ? $theDt['ar_dependency_of_index'][$f] : 0,
'dependencyOnPid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
'dependencyOnSid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
'dependencyOnSegment' => isset($theDt['ar_dependency_of_ar_index'][$f]) ? $theDt['ar_dependency_of_ar_index'][$f] : 0,
'warranty' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : 0,
'origin' => isset($theDt['ar_origin'][$f]) ? $theDt['ar_origin'][$f] : 0,
'origins' => isset($theDt['ar_origin'][$f]) ? [$theDt['ar_origin'][$f]] : [],
'scope' => isset($theDt['ar_scope'][$f]) ? $theDt['ar_scope'][$f] : 0,
'scopeId' => isset($theDt['ar_scopeHolderId'][$f]) ? [$theDt['ar_scopeHolderId'][$f]] : 0,
'scopeName' => isset($theDt['ar_scopeHolderName'][$f]) ? [$theDt['ar_scopeHolderName'][$f]] : '',
'scopeDescription' => isset($theDt['ar_scopeDescription'][$f]) ? [$theDt['ar_scopeDescription'][$f]] : '',
'deliverySchedule' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : [],
'deliveryPorts' => isset($theDt['ar_delivery_ports'][$f]) ? $theDt['ar_delivery_ports'][$f] : [],
'billingSchedule' => isset($theDt['ar_billing_schedule'][$f]) ? $theDt['ar_billing_schedule'][$f] : [],
'referenceNo' => isset($theDt['ar_reference_price'][$f]) ? $theDt['ar_reference_price'][$f] : '',
'referenceFiles' => isset($theDt['ar_reference_price_file'][$f]) ? $theDt['ar_reference_price_file'][$f] : '',
);
$dt_poka['rowData'][] = $row;
}
// $configJson['debugData'][]=$dt_poka;
}
$newSingleSet['rowData'] = $dt_poka['rowData'];
unset($dt_poka['productSegmentData']);
unset($dt_poka['serviceSegmentData']);
unset($dt_poka['Products']);
unset($dt_poka['Services']);
$newData[$kho] = $newSingleSet;
}
$theDocData->setData(json_encode($newData));
$em->persist($theDocData);
$em->flush();
}
$tempId = 0;
if ($entityNameHere == 'SalesProposal') $tempId = $the_actual_doc->getSalesProposalId();
if ($entityNameHere == 'ProjectBoq') $tempId = $the_actual_doc->getProjectId();
if ($entityNameHere == 'SalesLead') $tempId = $the_actual_doc->getLeadId();
$configJson['debugData'][] = array(
'entityNameHere' => $entityNameHere,
'entityId' => $tempId,
'dt' => $newData,
);
}
$the_actual_doc->setData(null);
$the_actual_doc->setDocumentDataId($theDocData->getId());
$em->flush();
if ($entityNameHere == 'ProjectBoq') {
$theProj = $em->getRepository('ApplicationBundle:Project')
->findOneBy(
array(
'projectId' => $the_actual_doc->getProjectId()
)
);
if ($theProj)
$theProj->setDocumentDataId($the_actual_doc->getDocumentDataId());
$em->flush();
}
}
}
}
if ($request->query->get('convertMarginToMarkupOldDocumentData', 0) == 1) {
$the_actual_docs = $em->getRepository('ApplicationBundle:DocumentData')
->findBy(
array(// GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
)
);
foreach ($the_actual_docs as $the_actual_doc) {
//now the data
//first find the docData if available
$theDocData = [];
$theDocData = json_decode($the_actual_doc->getData(), true);
if ($theDocData == null)
$theDocData = [];
$entries = $theDocData;
foreach ($entries as $jojo => $mod) {
if (isset($mod['rowData'])) {
$rows = $mod['rowData'];
if (is_string($rows))
$rows = json_decode($rows, true);
if ($rows == null)
$rows = [];
foreach ($rows as $indu => $row) {
if (!is_numeric($row['unitSalesPrice'])) $row['unitSalesPrice'] = 0;
if (!is_numeric($row['unitPrice'])) $row['unitPrice'] = 0;
if (!is_numeric($row['marginAmount'])) $row['marginAmount'] = 0;
if (!isset($row['markupRate'])) {
$rows[$indu]['markupRate'] = $row['marginRate'];
}
$rows[$indu]['marginRate'] = $row['unitSalesPrice'] != 0 ? 100 * $row['marginAmount'] / $row['unitSalesPrice'] : 0;
}
$entries[$jojo]['rowData'] = $rows;
}
}
$the_actual_doc->setData(json_encode($entries));
// $the_actual_doc->setDocumentDataId($theDocData->getId());
$em->flush();
}
}
if ($request->query->get('rectifyTransCurr', 0) == 1) {
$query = "
UPDATE `acc_transaction_details` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
UPDATE `acc_transaction_details` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
UPDATE `acc_transactions` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
UPDATE `acc_transactions` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
UPDATE `expense_invoice` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
UPDATE `expense_invoice` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$stmt->closeCursor();
}
if ($request->query->get('deepRefresh', 0) == 1) {
//new for updating app id
$get_kids_sql = "UPDATE `company` set app_id=" . $entry['appId'] . " ;
UPDATE `sys_user` set app_id=" . $entry['appId'] . " ;";
$get_kids_sql .= "
UPDATE `inv_products` set default_color_id=0 where default_color_id ='' or default_color_id is null ;
UPDATE `inv_products` set default_size=0 where default_size ='' or default_size is null ;
UPDATE `inventory_storage` set color= (select default_color_id from inv_products where inv_products.id=inventory_storage.product_id)
where inventory_storage.color =0 or inventory_storage.color is null or inventory_storage.color ='' ;
UPDATE `inventory_storage` set owner_type= 0 where inventory_storage.owner_type is null or inventory_storage.owner_type ='' ;
UPDATE `inventory_storage` set owner_id= 0 where inventory_storage.owner_id is null or inventory_storage.owner_id ='' ;
UPDATE `acc_clients` set client_level= 1 where client_level is null or client_level ='' or client_level=0 ;
UPDATE `acc_clients` set parent_id= 0 where parent_id is null or parent_id ='' ;
UPDATE `sales_order` set sales_level= 0 where sales_level is null or sales_level ='' ;
";
$get_kids_sql .= " UPDATE `inventory_storage` set color=0 where color='' or color is null;
UPDATE `inventory_storage` set `size`=0 where `size`='' or size is null;
UPDATE `inv_item_transaction` set color=0 where color='' or color is null;
UPDATE `inv_item_transaction` set `size`=0 where `size`='' or size is null;
UPDATE `inv_closing_balance` set color=0 where color='' or color is null;
UPDATE `inv_closing_balance` set `size`=0 where `size`='' or size is null;
UPDATE `sales_order_item` set `size_id`=(select default_size from inv_products where inv_products.id=sales_order_item.product_id ) where sales_order_item.product_id!=0 and (`size_id`='' or size_id is null);
UPDATE `sales_order_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=sales_order_item.product_id ) where sales_order_item.product_id!=0 and (`color_id`='' or color_id is null);
UPDATE `delivery_receipt_item` set `size_id`=(select default_size from inv_products where inv_products.id=delivery_receipt_item.product_id ) where delivery_receipt_item.product_id!=0 and (`size_id`='' or size_id is null);
UPDATE `delivery_receipt_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=delivery_receipt_item.product_id ) where delivery_receipt_item.product_id!=0 and (`color_id`='' or color_id is null);
UPDATE `delivery_order_item` set `size_id`=(select default_size from inv_products where inv_products.id=delivery_order_item.product_id ) where delivery_order_item.product_id!=0 and (`size_id`='' or size_id is null);
UPDATE `delivery_order_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=delivery_order_item.product_id ) where delivery_order_item.product_id!=0 and (`color_id`='' or color_id is null);
UPDATE `sales_invoice_item` set `size_id`=(select default_size from inv_products where inv_products.id=sales_invoice_item.product_id ) where sales_invoice_item.product_id!=0 and (`size_id`='' or size_id is null);
UPDATE `sales_invoice_item` set `color_id`=(select default_color_id from inv_products where inv_products.id=sales_invoice_item.product_id ) where sales_invoice_item.product_id!=0 and (`color_id`='' or color_id is null);
UPDATE `inventory_storage` set curr_purchase_price= (select curr_purchase_price from inv_products where inv_products.id=inventory_storage.product_id)
where inventory_storage.curr_purchase_price=0 or inventory_storage.curr_purchase_price is null;
delete TABLE service_opearation;
delete TABLE assesment_and_confirmation;
";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
$query = "SELECT * from company where 1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
//insert client level query here
$createdDate = new \DateTime();
$cgEntry = $gocEntryObjectList[$gocId];
$get_kids_sql = "INSERT INTO `company` (`id`, `name`, `image`, `app_id`, `created_at`, `company_hash`, `company_unique_code`, `enabled_module_id_list`, `usage_valid_upto_date`,`active`) VALUES
(1, '" . $cgEntry->getName() . "', '" . $cgEntry->getImage() . "'," . $cgEntry->getAppId() . ",'" . $createdDate->format('Y-m-d H:i:s') . "', '" . $cgEntry->getCompanyGroupHash() . "','" . $cgEntry->getCompanyGroupUniqueCode() . "',NULL, NULL,1);";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
$query = "SELECT * from client_level where 1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
//insert client level query here
$get_kids_sql = "INSERT INTO `client_level` (`id`, `name`, `level_value`,`company_id`, `parent_level_id`, `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`) VALUES
(1, 'Primary',1, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
(2, 'Secondary',2, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
(3, 'Tertiary',3, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)
;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
$query = "SELECT * from sales_level where 1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (empty($results)) {
//insert client level query here
$get_kids_sql = "INSERT INTO `sales_level` (`id`, `name`, `level_value`,`company_id`, `parent_level_id`, `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`) VALUES
(1, 'Primary',0, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
(2, 'Secondary',1, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
(3, 'Tertiary',2, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL);";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
$services = $em->getRepository('ApplicationBundle:AccService')->findBy(array(
// 'serviceId' => $ex_id//for now for stock of goods
// 'opening_locked'=>0
));
foreach ($services as $service) {
$productFdm = $service->getProductFdm();
if (strpos($productFdm, 'P_') !== false)
$productFdm = str_replace('P_', 'P' . $service->getServiceId() . '_', $productFdm);
$service->setProductFdm($productFdm);
$em->flush();
}
$query = "SELECT * from warehouse_action where 1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
//insert client level query here
foreach ($results as $qryResult) {
$get_kids_sql = "update `warehouse_action` set `accounts_head_id` =(select `data` from acc_setting where acc_setting.`name` like 'warehouse_action_" . $qryResult['id'] . "') where id=" . $qryResult['id'];
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
} else {
foreach (GeneralConstant::$warehouse_action_list as $dt_pika) {
$get_kids_sql = "INSERT INTO `warehouse_action` (`id`, `name`,`company_id`, `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`)
VALUES(" . $dt_pika['id'] . ", '" . $dt_pika['name'] . "', 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
//
$query = "SELECT * from warehouse_action where 1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$newresults = $stmt->fetchAll();
foreach ($newresults as $qryResult) {
$get_kids_sql = "update `warehouse_action` set `accounts_head_id` =(select `data` from acc_setting where acc_setting.`name` like 'warehouse_action_" . $qryResult['id'] . "') where id=" . $qryResult['id'];
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
}
$modify_product_by_code_ids_table_list = [
'stock_transfer_item',
];
$modify_product_by_code_ids_field_list = [
'product_by_code_ids'
];
$modify_product_by_code_sales_code_field_list = [
'sales_code_range'
];
$modify_product_by_code_item_id_field_list = [
'id'
];
foreach ($modify_product_by_code_ids_table_list as $mindex => $dt_table_name) {
$get_kids_sql = "select * from " . $dt_table_name . " where " .
$modify_product_by_code_ids_field_list[$mindex] . " is null or " .
$modify_product_by_code_ids_field_list[$mindex] . " ='' or " .
$modify_product_by_code_ids_field_list[$mindex] . " ='[]' ;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$dataList = $stmt->fetchAll();
foreach ($dataList as $mdt) {
$sales_code_range_str = $mdt[$modify_product_by_code_sales_code_field_list[$mindex]];
$sales_code_range = [];
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
$sales_code_range = json_decode($sales_code_range_str, true, 512, JSON_BIGINT_AS_STRING);
} else {
$max_int_length = strlen((string)PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $sales_code_range_str);
$sales_code_range = json_decode($json_without_bigints, true);
}
// $sales_code_range= json_decode($entry->getSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
$pbcIds = [];
if ($sales_code_range == null)
$sales_code_range = [];
if (empty($sales_code_range)) {
} else {
$get_kids_sql_2 = "select * from product_by_code where sales_code in ('" . implode("','", $sales_code_range) . "');";
$stmt = $em->getConnection()->prepare($get_kids_sql_2);
$stmt->execute();
$dataList = $stmt->fetchAll();
foreach ($dataList as $pbc) {
$pbcIds[] = 1 * $pbc['product_by_code_id'];
}
}
$get_kids_sql_3 = "update " . $dt_table_name .
" set " . $modify_product_by_code_ids_field_list[$mindex] . "='" . json_encode($pbcIds) . "'" .
" where " . $modify_product_by_code_item_id_field_list[$mindex] . "=" . $mdt[$modify_product_by_code_item_id_field_list[$mindex]] . ";";
$stmt = $em->getConnection()->prepare($get_kids_sql_3);
$stmt->execute();
$stmt->closeCursor();
}
}
$modify_voucher_date_table_list = [
// 'stock_received_note',
// 'stock_transfer',
// 'stock_consumption_note',
// 'fixed_asset_conversion_note',
// 'fixed_asset_product'
];
$modify_date_field_list = [
// 'stock_received_note_date',
// 'stock_transfer_date',
// 'stock_consumption_note_date',
// 'fixed_asset_conversion_note_date',
// 'fixed_asset_product'
];
foreach ($modify_voucher_date_table_list as $mindex => $dt_table_name) {
$get_kids_sql = "select * from " . $dt_table_name . " where 1;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$dataList = $stmt->fetchAll();
foreach ($dataList as $mdt) {
$curr_v_ids = json_decode($mdt['voucher_ids'], true);
if ($curr_v_ids == null)
$curr_v_ids = [];
$date_for_this = $mdt[$modify_date_field_list[$mindex]];
foreach ($curr_v_ids as $vid) {
//new for updating app id
$get_kids_sql = "UPDATE `acc_transactions`
set transaction_date='" . $date_for_this . "',
ledger_hit_date='" . $date_for_this . "'
where transaction_id=" . $vid . ";
UPDATE `acc_transactions_details`
set transaction_date='" . $date_for_this . "',
ledger_hit_date='" . $date_for_this . "'
where transaction_id=" . $vid . ";";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
}
}
$modify_voucher_narration_table_list = [
// 'expense_invoice',
// 'stock_transfer',
// 'stock_consumption_note',
// 'fixed_asset_conversion_note',
// 'fixed_asset_product'
];
$modify_narr_field_list = [
// 'description',
// 'stock_transfer_date',
// 'stock_consumption_note_date',
// 'fixed_asset_conversion_note_date',
// 'fixed_asset_product'
];
foreach ($modify_voucher_narration_table_list as $mindex => $dt_table_name) {
$get_kids_sql = "select * from " . $dt_table_name . " where 1;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$dataList = $stmt->fetchAll();
foreach ($dataList as $mdt) {
$curr_v_ids = json_decode($mdt['voucher_ids'], true);
if ($curr_v_ids == null)
$curr_v_ids = [];
$narr_for_this = $mdt[$modify_narr_field_list[$mindex]];
foreach ($curr_v_ids as $vid) {
//new for updating app id
$get_kids_sql = "UPDATE `acc_transactions`
set description='" . $narr_for_this . "'
where transaction_id=" . $vid . "; ";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
}
}
}
$get_kids_sql = "update `company_group` set `schema_update_pending_flag` =0 where `id`=$gocId;";
$stmt = $em_goc->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
$configJson['success'] = true;
//this is for large amount of goc we will see later
// file_put_contents($path, json_encode($configJson));//overwrite
// return $this->redirectToRoute('update_database_schema');
}
}
return new JsonResponse($configJson);
} else {
return $this->render(
'@System/pages/server_actions.html.twig',
$dtHere
);
}
}
public function UpdateRoutesAction(Request $request)
{
$message = "";
$gocList = [];
$outputList = [];
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
if ($connected)
if ($systemType != '_CENTRAL_') {
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(
array(
'active' => 1
)
);
}
$gocDataList = [];
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
$gocDbName = '';
$gocDbUser = '';
$gocDbPass = '';
$gocDbHost = '';
$gocId = 0;
// $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
$config_dir = $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
if (!file_exists($config_dir)) {
mkdir($config_dir, 0777, true);
}
// $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
// $content = file_exists($path) ? file_get_contents($path) : null;
$content = [];
$configJson = array();
if ($content)
$configJson = json_decode($content, true);
$configJsonOld = $configJson;
// if($configJson)
// {
//
// }
// else
{
$configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
$configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
$configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
$configJson['initiateDataBaseFlagByGoc'] = array();
$configJson['motherLode'] = "http://innobd.com";
foreach ($gocDataList as $gocId => $entry) {
$configJson['initiateDataBaseFlagByGoc'][$gocId . "_" . $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
}
}
//now check if database shcema update is true
// if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
if (1) //temporary overwrite all
{
//if goclist is not empty switch to each company dbase and schema update
// if(!empty($gocDataList))
if (1) {
foreach ($gocDataList as $gocId => $entry) {
if ($configJson['initiateDataBaseFlagByGoc'][$gocId . "_" . $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
// $iv = '1234567812345678';
// $pass = $hash;
//
// $str = $str . 'YmLRocksLikeABoss';
// $data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
//
// $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
//
//now 1st of all lets get the Existing routes
$extRoutesById = [];
$extRoutesByRoute = [];
$modules = $em->getRepository("ApplicationBundle:SysModule")
->findBy(
array()
);
$module_data = [];
foreach ($modules as $mod) {
$dt = array(
'id' => $mod->getModuleId(),
'route' => $mod->getModuleRoute(),
'name' => $mod->getModuleName(),
'parentId' => $mod->getParentId(),
'level' => $mod->getLevel(),
'eFA' => $mod->getEnabledForAll(),
);
$extRoutesById[$mod->getModuleId()] = $dt;
$extRoutesByRoute[$mod->getModuleRoute()] = $dt;
}
//now clear the module table
$get_kids_sql = "truncate `sys_module` ; ";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
$newRoutes = ModuleConstant::$moduleList;
$newRoutesByRoute = [];
foreach ($newRoutes as $mod) {
$new = new SysModule();
$new->setModuleId($mod['id']);
$new->setModuleRoute($mod['route']);
$new->setModuleName($mod['name']);
$new->setParentId($mod['parentId']);
$new->setlevel($mod['level']);
$new->setEnabledForAll($mod['eFA']);
$new->setStatus(isset($mod['status']) ? $mod['status'] : GeneralConstant::ACTIVE);
// $new->set(GeneralConstant::ACTIVE);
$em->persist($new);
$newRoutesByRoute[$mod['route']] = $mod;
}
$em->flush();
//now lets get the ext modules for positions
$depPosDefModules = $em->getRepository("ApplicationBundle:SysDeptPositionDefaultModule")
->findBy(
array()
);
foreach ($depPosDefModules as $defmod) {
$moduleList = json_decode($defmod->getModuleIds());
$newModuleList = [];
foreach ($moduleList as $oldId) {
$newId = 0;
if (isset($extRoutesById[$oldId])) {
if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
$newModuleList[] = 1 * $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
}
}
}
$defmod->setModuleIds(json_encode($newModuleList));
$em->flush();
}
//now users
$users = $em->getRepository("ApplicationBundle:SysUser")
->findBy(
array()
);
foreach ($users as $defmod) {
$moduleList = json_decode($defmod->getModuleIds());
if ($moduleList == null)
continue;
$newModuleList = [];
foreach ($moduleList as $oldId) {
$newId = 0;
if (isset($extRoutesById[$oldId])) {
if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
$newModuleList[] = 1 * $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
}
}
}
$defmod->setModuleIds(json_encode($newModuleList));
$em->flush();
}
$module_data = [];
// $tool = new SchemaTool($em);
//
// $classes = $em->getMetadataFactory()->getAllMetadata();
//// $tool->createSchema($classes);
// $tool->updateSchema($classes);
//
// //new for updating app id
// $get_kids_sql = "UPDATE `company` set app_id=".$entry['appId']." ;
// UPDATE `sys_user` set app_id=".$entry['appId']." ;";
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $stmt->closeCursor();
//
// $configJson['initiateDataBaseFlagByGoc'][$gocId."_".$entry['appId']]=GeneralConstant::ENTITY_APP_FLAG_FALSE;
//this is for large amount of goc we will see later
// file_put_contents($path, json_encode($configJson));//overwrite
// return $this->redirectToRoute('update_database_schema');
}
}
} else {
$em = $this->getDoctrine()->getManager();
$tool = new SchemaTool($em);
// $classes = array(
// $em->getClassMetadata('Entities\User'),
// $em->getClassMetadata('Entities\Profile')
// );
$classes = $em->getMetadataFactory()->getAllMetadata();
// $tool->createSchema($classes);
$tool->updateSchema($classes);
}
}
$allSchemaUpdateDone = 1;
foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
$allSchemaUpdateDone = 0;
}
if ($allSchemaUpdateDone == 1)
$configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
///last
// file_put_contents($path, json_encode($configJson));//overwrite
return new Response(json_encode($configJsonOld));
}
public function CheckTimeStampAction(Request $request)
{
$message = "";
$gocList = [];
$outputList = [];
$toConvertDateStrFromQry = $request->query->get('convDate', '');
$currentRegionalDateStrFromQry = $request->query->get('currDate', '');
$convertedTime = MiscActions::ConvertRegionalTimeToServerTime($currentRegionalDateStrFromQry, $toConvertDateStrFromQry);
$currentServerTime = new \DateTime();
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
///last
// file_put_contents($path, json_encode($configJson));//overwrite
return new Response(json_encode(array(
'convertedTime' => $convertedTime->format('Y-m-d h:i:s'),
'convertedTimeUnix' => $convertedTime->format('U'),
'convertedTimeRFC' => $convertedTime->format(DATE_RFC822),
'currentServerTime' => $currentServerTime->format('Y-m-d h:i:s'),
'currentServerTimeRFC' => $currentServerTime->format(DATE_RFC822),
'currentServerTimeUnix' => $currentServerTime->format('U'),
)));
}
public function GetUsersFromCentralServerAction(Request $request, $id = 0)
{
}
public function UpdateCompanyDataToCentralServerAction(Request $request, $id = 0)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$post = $request;
$serverList = GeneralConstant::$serverListById;
if ($systemType == '_CENTRAL_') {
$em_goc = $this->getDoctrine()->getManager('company_group');
// 'company_id' => $company->getId(),
// 'app_id' => $entry['appId'],
// 'dark_vibrant' => $company->getDarkVibrant(),
// 'light_vibrant' => $company->getLightVibrant(),
// 'vibrant' => $company->getVibrant(),
// 'company_type' => $company->getCompanyType(),
// 'company_name' => $company->getName(),
// 'company_address' => $company->getAddress(),
// 'company_s_address' => $company->getShippingAddress(),
// 'company_b_address' => $company->getBillingAddress(),
// 'company_image' => $company->getImage(),
// 'company_motto' => $company->getMotto(),
// 'company_i_footer' => $company->getInvoiceFooter(),
// 'company_g_footer' => $company->getGeneralFooter(),
// 'company_tin' => $company->getCompanyTin(),
// 'company_bin' => $company->getCompanyBin(),
// 'company_reg' => $company->getCompanyReg(),
// 'company_tl' => $company->getCompanyTl(),
// 'sms_enabled' => $company->getSmsNotificationEnabled(),
// 'sms_settings' => $company->getSmsSettings(),
// 'file'=>$output
$findByQuery = array(
// 'active' => 1
'appId' => $post->get('app_id')
);
$goc = $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy($findByQuery);
if (!$goc)
$goc = new CompanyGroup();
$goc->setName($post->get('company_name'));
$goc->setAppId($post->get('app_id'));
// $goc->setCompanyType($post->get('company_type'));
$goc->setAddress($post->get('address'));
// $goc->setDarkVibrant($post->get('dark_vibrant'));
// $goc->setLightVibrant($post->get('light_vibrant'));
// $goc->setVibrant($post->get('vibrant'));
$goc->setShippingAddress($post->get('s_address'));
$goc->setBillingAddress($post->get('b_address'));
$goc->setMotto($post->get('motto'));
$goc->setInvoiceFooter($post->get('i_footer'));
$goc->setGeneralFooter($post->get('g_footer'));
$goc->setCompanyReg($post->get('company_reg', ''));
$goc->setCompanyTin($post->get('company_tin', ''));
$goc->setCompanyBin($post->get('company_bin', ''));
$goc->setCompanyTl($post->get('company_tl', ''));
$goc->setCompanyGroupServerId($post->get('companyGroupServerId', ''));
$goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress', ''));
$goc->setCompanyGroupServerPort($post->get('companyGroupServerPort', ''));
$goc->setCompanyGroupServerHash($post->get('companyGroupServerHash', ''));
// $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
// $goc->setSmsSettings($post->get('sms_settings'));
foreach ($request->files as $uploadedFile) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$fileName = 'company_image' . $post->get('app_id') . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage())) {
unlink($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage());
}
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
if ($path != "")
$goc->setImage('/uploads/CompanyImage/' . $path);
}
}
$em_goc->persist($goc);
$em_goc->flush();
return new JsonResponse([]);
} else {
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
$gocDataList = [];
if ($connected) {
$findByQuery = array(
'active' => 1
);
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'companyGroupServerId' => $entry->getCompanyGroupServerId(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
foreach ($gocDataList as $gocId => $entry) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
$company = $this->getDoctrine()
->getRepository('ApplicationBundle:Company')
->findOneBy(
array()
);
$output = '';
$file = $this->container->getParameter('kernel.root_dir') . '/../web' . $company->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);
}
}
$post_fields = array(
'company_id' => $company->getId(),
'app_id' => $entry['appId'],
'dark_vibrant' => $company->getDarkVibrant(),
'light_vibrant' => $company->getLightVibrant(),
'vibrant' => $company->getVibrant(),
'company_type' => $company->getCompanyType(),
'company_name' => $company->getName(),
'company_address' => $company->getAddress(),
'company_s_address' => $company->getShippingAddress(),
'company_b_address' => $company->getBillingAddress(),
'company_image' => $company->getImage(),
'company_motto' => $company->getMotto(),
'company_i_footer' => $company->getInvoiceFooter(),
'company_g_footer' => $company->getGeneralFooter(),
'company_tin' => $company->getCompanyTin(),
'company_bin' => $company->getCompanyBin(),
'company_reg' => $company->getCompanyReg(),
'company_tl' => $company->getCompanyTl(),
'sms_enabled' => $company->getSmsNotificationEnabled(),
'sms_settings' => $company->getSmsSettings(),
'companyGroupHash' => $company->getCompanyHash(),
'companyGroupServerId' => $entry['companyGroupServerId'],
'companyGroupServerAddress' => $serverList[$entry['companyGroupServerId']]['absoluteUrl'],
'companyGroupServerHash' => $serverList[$entry['companyGroupServerId']]['serverMarker'],
'companyGroupServerPort' => $request->server->get("SERVER_PORT"),
'file' => $output
);
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/UpdateCompanyDataToCentralServer';
$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);
}
}
return new JsonResponse([]);
}
}
public function GetAppListFromCentralServerAction(Request $request, $id = 0)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$appIds = $request->get('appIds', []);
$appId = $request->get('appId', 0);
if (is_string($appIds)) $appIds = json_decode($appIds, true);
if ($appIds == null) $appIds = [];
if ($appId != 0)
$appIds[] = $appId;
if ($systemType == '_CENTRAL_') {
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
$gocDataList = [];
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds != '_ALL_' && $appIds != [])
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
}
return new JsonResponse($gocDataList);
} else {
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/GetAppListFromCentralServer';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
),
// CURLOPT_USERAGENT => 'InnoPM',
CURLOPT_POSTFIELDS => http_build_query([
'appIds' => $appIds
])
));
// $headers = array(
// "Accept: application/json",
// );
// curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
////for debug only!
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
return new JsonResponse(json_decode($retData, true));
}
}
public function GetTaskListForMenuAction(Request $request, $id = 0)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$session = $request->getSession();
$appIds = $request->get('appIds', []);
$appId = $request->get('appId', 0);
if (is_string($appIds)) $appIds = json_decode($appIds, true);
if ($appIds == null) $appIds = [];
if ($appId != 0)
$appIds[] = $appId;
if ($systemType == '_CENTRAL_') {
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
$gocDataList = [];
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds != '_ALL_' && $appIds != [])
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
}
return new JsonResponse($gocDataList);
} else {
$findByQuery = array(
'userId' => $session->get(UserConstants::USER_ID, 0)
);
$employee = $this->getDoctrine()->getManager()
->getRepository("ApplicationBundle:Employee")
->findOneBy($findByQuery);
$assignedTaskList = array();
$currentlyWorkingTaskList = array();
if ($employee) {
$findByQuery = array(
'assignedTo' => $employee->getEmployeeId(),
'hasChild' => [0, null]
);
$assignedTaskListData = $this->getDoctrine()->getManager()
->getRepository("ApplicationBundle:PlanningItem")
->findBy($findByQuery);
$findByQuery = array(
'employeeId' => $employee->getEmployeeId(),
);
$currentlyWorkingTaskListData = $this->getDoctrine()->getManager()
->getRepository("ApplicationBundle:TaskLog")
->findBy($findByQuery);
foreach ($assignedTaskListData as $entry) {
$dt = array(
'description' => $entry->getDescription(),
'urgency' => $entry->getUrgency()
);
$assignedTaskList[] = $dt;
}
foreach ($currentlyWorkingTaskListData as $entry) {
$dt = array();
$currentlyWorkingTaskList[] = $dt;
}
}
return new JsonResponse(array(
'assignedTaskList' => $assignedTaskList,
'currentlyWorkingTaskList' => $currentlyWorkingTaskList,
));
}
}
public function SyncUserToCentralUserAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$post = $request;
$globalIdsByAppIdAndUser = [];
if ($systemType == '_CENTRAL_') {
$userDataList = $request->get('userData', []);
if (is_string($userDataList)) $userDataList = json_decode($userDataList, true);
if ($userDataList == null) $userDataList = [];
$em_goc = $this->getDoctrine()->getManager('company_group');
//1st step get all company item ids and then check for global id null if its null then the
// return new JsonResponse(
// array(
// 'userDataList' => $userDataList
// )
// );
////ITEMGROUPS
foreach ($userDataList as $k => $cwa) {
$centralUser = $em_goc
->getRepository("CompanyGroupBundle:EntityApplicantDetails")
->findOneBy(
array(
'applicantId' => $cwa['getGlobalId']
)
);
if ($centralUser) {
$centralUser->setFirstname($cwa['getFirstname'] ?? null);
$centralUser->setLastname($cwa['getLastname'] ?? null);
$centralUser->setEmail($cwa['getEmail'] ?? null);
$centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
$centralUser->setPhone($cwa['getPhone'] ?? null);
$centralUser->setNid($cwa['getNid'] ?? null);
$centralUser->setSex($cwa['getSex'] ?? null);
$centralUser->setBlood($cwa['getBlood'] ?? null);
$centralUser->setFather($cwa['getFather'] ?? null);
$centralUser->setMother($cwa['getMother'] ?? null);
$centralUser->setSpouse($cwa['getSpouse'] ?? null);
$centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
$centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
$centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
$centralUser->setEmpType($cwa['getEmpType'] ?? null);
$centralUser->setTin($cwa['getTin'] ?? null);
$centralUser->setDept($cwa['getDept'] ?? null);
$centralUser->setDesg($cwa['getDesg'] ?? null);
$centralUser->setBranch($cwa['getBranch'] ?? null);
$centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
$centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
$centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
$centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
$centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
$centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
$centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
} else {
$qry = $em_goc->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->createQueryBuilder('m')
->where("m.email like '" . $cwa['getEmail'] . "'");
if ($cwa['getOAuthEmail'] != '' && $cwa['getOAuthEmail'] != null)
$qry->orWhere("m.oAuthEmail like '" . $cwa['getOAuthEmail'] . "'");
if ($cwa['getPhoneNumber'] != '' && $cwa['getPhoneNumber'] != null)
$qry->orWhere("m.phone like '" . $cwa['getPhoneNumber'] . "'");
$targets = $qry->getQuery()
->setMaxResults(1)
->getResult();
if (!empty($targets))
$centralUser = $targets[0];
}
if ($centralUser) {
$centralUser->setFirstname($cwa['getFirstname'] ?? null);
$centralUser->setLastname($cwa['getLastname'] ?? null);
$centralUser->setEmail($cwa['getEmail'] ?? null);
$centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
$centralUser->setPhone($cwa['getPhone'] ?? null);
$centralUser->setNid($cwa['getNid'] ?? null);
$centralUser->setSex($cwa['getSex'] ?? null);
$centralUser->setBlood($cwa['getBlood'] ?? null);
$centralUser->setFather($cwa['getFather'] ?? null);
$centralUser->setMother($cwa['getMother'] ?? null);
$centralUser->setSpouse($cwa['getSpouse'] ?? null);
$centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
$centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
$centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
$centralUser->setEmpType($cwa['getEmpType'] ?? null);
$centralUser->setTin($cwa['getTin'] ?? null);
$centralUser->setDept($cwa['getDept'] ?? null);
$centralUser->setDesg($cwa['getDesg'] ?? null);
$centralUser->setBranch($cwa['getBranch'] ?? null);
$centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
$centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
$centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
$centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
$centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
$centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
$centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
} else
$centralUser = new EntityApplicantDetails();
//
// $getters = array_filter(get_class_methods($data), function ($method) {
// return 'get' === substr($method, 0, 3);
// });
// Manual mapping starts here
$centralUser->setFirstname($cwa['getFirstname'] ?? null);
$centralUser->setLastname($cwa['getLastname'] ?? null);
$centralUser->setEmail($cwa['getEmail'] ?? null);
$centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
$centralUser->setPhone($cwa['getPhone'] ?? null);
$centralUser->setNid($cwa['getNid'] ?? null);
$centralUser->setSex($cwa['getSex'] ?? null);
$centralUser->setBlood($cwa['getBlood'] ?? null);
$centralUser->setFather($cwa['getFather'] ?? null);
$centralUser->setMother($cwa['getMother'] ?? null);
$centralUser->setSpouse($cwa['getSpouse'] ?? null);
$centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
$centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
$centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
$centralUser->setEmpType($cwa['getEmpType'] ?? null);
$centralUser->setTin($cwa['getTin'] ?? null);
$centralUser->setDept($cwa['getDept'] ?? null);
$centralUser->setDesg($cwa['getDesg'] ?? null);
$centralUser->setBranch($cwa['getBranch'] ?? null);
$centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
$centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
// Date fields
$centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
$centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
$centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
$centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
$centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
// Continue mapping more fields as needed...
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
$userTypesByAppIds = json_decode($centralUser->getUserTypesByAppIds(), true);
if ($userAppIds == null) $userAppIds = [];
if ($userTypesByAppIds == null) $userTypesByAppIds = [];
$userAppIds = array_merge($userAppIds, array_diff([$cwa['getUserAppId']], $userAppIds));
if (!isset($userTypesByAppIds[$cwa['getUserAppId']])) {
$userTypesByAppIds[$cwa['getUserAppId']] = [];
}
$userTypesByAppIds[$cwa['getUserAppId']] = array_merge($userTypesByAppIds[$cwa['getUserAppId']], array_diff([$cwa['getUserType']], $userTypesByAppIds[$cwa['getUserAppId']]));
$userFullName = $cwa['getName'];
$userFullNameArr = explode(' ', $cwa['getName']);
$userFirstName = isset($userFullNameArr[0]) ? $userFullNameArr[0] : '';
$userLastName = '';
if (isset($userFullNameArr[1])) {
foreach ($userFullNameArr as $kunky => $chunky) {
if ($kunky != 0) {
$userLastName .= $chunky;
}
if ($kunky < count($userFullNameArr) - 1) {
$userLastName .= ' ';
}
}
}
$centralUser->setUserAppIds(json_encode($userAppIds));
$centralUser->setFirstname($userFirstName);
$centralUser->setLastname($userLastName);
$centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
$em_goc->persist($centralUser);
$em_goc->flush();
$uploadedFile = $request->files->get('file_' . $cwa['getUserAppId'] . '_' . $cwa['getUserId'], null);
{
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$fileName = 'user_image' . $centralUser->getApplicantId() . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' . $centralUser->getImage())) {
unlink($this->container->getParameter('kernel.root_dir') . '/../web/' . $centralUser->getImage());
}
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
if ($path != "")
$centralUser->setImage('uploads/UserImage/' . $path);
}
}
$em_goc->flush();
if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
$globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
$globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
array(
'gid' => $centralUser->getApplicantId()
);
$companies = $em_goc->getRepository('CompanyGroupBundle:CompanyGroup')->findBy([
'appId' => $userAppIds
]);
$globalId = $cwa['getGlobalId'];
$userData = $userDataList;
$dataByServerId = [];
$gocDataListByAppId = [];
foreach ($companies as $entry) {
$gocDataListByAppId[$entry->getAppId()] = [
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $entry->getAppId(),
'serverId' => $entry->getCompanyGroupServerId(),
];
if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
$dataByServerId[$entry->getCompanyGroupServerId()] = array(
'serverId' => $entry->getCompanyGroupServerId(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $userAppIds,
'payload' => array(
'globalId' => $globalId,
'appId' => $userAppIds,
'userData' => $userData,
// 'approvalHash' => $approvalHash
)
);
}
$urls = [];
foreach ($dataByServerId as $entry) {
$serverAddress = $entry['serverAddress'];
if (!$serverAddress) continue;
$syncUrl = $serverAddress . '/ReceiveUserFromCentral';
$payload = $entry['payload'];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $syncUrl,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($err) {
error_log("ERP Sync Error [Server: {$entry['serverAddress']}]: $err");
} else {
error_log("ERP Sync Success [HTTP $httpCode]: $response");
}
}
}
return new JsonResponse(
array(
'globalIdsData' => $globalIdsByAppIdAndUser
)
);
} else {
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = $request->get('appIds', '_UNSET_');
$userIds = $request->get('userIds', '_UNSET_');
if ($connected) {
$findByQuery = array(
'active' => 1
);
if ($appIds !== '_UNSET_')
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
// if($debugCount>0)
// continue;
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
if ($userIds !== '_UNSET_')
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage(); //<-- Path could be relative
// $output=$file;
if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
// $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = $output;
} else {
// unlink($this->container->getParameter('kernel.root_dir') . '/../web'. $centralUser->getImage());
$user->setImage(null);
$userFiles['file_' . $user->getUserAppId() . '_' . $user->getUserId()] = 'pika';
$em->flush();
}
$getters = array_filter(get_class_methods($user), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array(// 'file'=>$output
);
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($user->{$getter}() instanceof \DateTime) {
$ggtd = $user->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $user->{$getter}();
}
$userData[] = $userDataSingle;
}
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend
);
//now customers
$emailFieldName = 'email';
$phoneFieldName = 'contact_number';
$query = "SELECT * from acc_clients where 1=1 ";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
foreach ($results as $dt) {
$dt['company_id'] = "1";
$companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
$userDataSingle = array(
'getUserAppId' => strval(UserConstants::USER_TYPE_CLIENT),
'getUserName' => 'CID-' . str_pad($dt['client_id'], 8, '0', STR_PAD_LEFT),
'getUserId' => $dt['client_id']
);
// $userData[] = $userDataSingle;
}
}
//now suppliers
$emailFieldName = 'email';
$phoneFieldName = 'contact_number';
$query = "SELECT * from acc_suppliers where 1=1 ";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
foreach ($results as $dt) {
$dt['company_id'] = "1";
$companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
$userDataSingle = array(
'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
'userName' => 'SID-' . str_pad($dt['supplier_id'], 8, '0', STR_PAD_LEFT),
'userId' => $dt['supplier_id'],
);
// $userData[] = $userDataSingle;
}
}
// if ($skipSend == 0)
{
$urlToCall = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncUserToCentralUser';
$userFiles['userData'] = json_encode($userData);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
// CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HTTPHEADER => array(// "Accept: multipart/form-data",
),
// CURLOPT_USERAGENT => 'InnoPM',
// CURLOPT_POSTFIELDS => array(
// 'userData'=>json_encode($userData),
// 'userFiles'=>$userFiles
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = json_decode($retData, true);
$retDataDebug[$debugCount] = $retDataObj;
if (isset($retDataObj['globalIdsData']))
foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataListByAppId[$app_id]['dbName'],
$gocDataListByAppId[$app_id]['dbUser'],
$gocDataListByAppId[$app_id]['dbPass'],
$gocDataListByAppId[$app_id]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
foreach ($usrList as $sys_id => $globaldata) {
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'userId' => $sys_id
)
);
if ($user) {
$user->setGlobalId($globaldata['gid']);
$em->flush();
}
}
}
}
$debugCount++;
}
}
return new JsonResponse($retDataDebug);
}
}
public function ReceiveUserFromCentralAction(Request $request)
{
$data = json_decode($request->getContent(), true);
if (
!$data ||
!isset($data['globalId']) ||
!isset($data['appId']) ||
!isset($data['userData'])
) {
return new JsonResponse(['success' => false, 'message' => 'Missing required fields'], 400);
}
$globalId = $data['globalId'];
$userDataRaw = $data['userData'];
if (is_string($userDataRaw)) {
$userDataRaw = json_decode($userDataRaw, true);
}
if (!is_array($userDataRaw)) {
return new JsonResponse(['success' => false, 'message' => 'Invalid userData format'], 400);
}
$userData = is_array($userDataRaw[0] ?? null) ? $userDataRaw[0] : $userDataRaw;
if (is_string($userData)) {
$userData = json_decode($userData, true);
}
if (!is_array($userData)) {
return new JsonResponse(['success' => false, 'message' => 'Invalid userData format'], 400);
}
$companyIds = is_array($data['appId']) ? $data['appId'] : [$data['appId']];
$em_goc = $this->getDoctrine()->getManager('company_group');
$companies = $em_goc->getRepository('CompanyGroupBundle:CompanyGroup')->findBy([
'appId' => $companyIds
]);
foreach ($companies as $entry) {
$goc = [
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $entry->getAppId(),
// 'serverId' => $entry->getServerId(),
];
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$goc['dbName'],
$goc['dbUser'],
$goc['dbPass'],
$goc['dbHost'],
$reset = true
);
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationBundle:SysUser')->findOneBy(['globalId' => $globalId]);
if (!$user) {
return new JsonResponse(['success' => false, 'message' => 'User not found'], 404);
}
// $user = $em->getRepository('ApplicationBundle:SysUser')->findOneBy(['userId' => $user->getUserId()]);
// if (!$user) {
// $user = new \ApplicationBundle\Entity\EncryptedSignature();
// $user->setUserId($user->getUserId());
// $user->setCreatedAt(new \DateTime());
// }
$user->setUserName($userData['getFirstname'] . ' ' . $userData['getLastname']);
$user->setUserCompanyId(1);
$user->setGlobalId($globalId);
$user->setUserName($userData['getName'] ?? null);
$user->setUpdatedAt(new \DateTime());
$em->persist($user);
$em->flush();
$employee = $em->getRepository('ApplicationBundle:Employee')->findOneBy(['userId' => $user->getUserId()]);
if ($employee) {
$employee->setFirstName($userData['getFirstname']);
$employee->setLastName($userData['getLastname']);
$em->persist($employee);
}
if ($employee)
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')
->findOneBy(['id' => $employee->getEmployeeId()]);
else
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')
->findOneBy(['userId' => $user->getUserId()]);
if ($employeeDetails) {
$employeeDetails->setFirstname($userData['getFirstname']);
$employeeDetails->setLastname($userData['getLastname']);
$employeeDetails->setEmail($userData['getEmail']);
$employeeDetails->setPhone($userData['getPhone'] ?? null);
$employeeDetails->setNid($userData['getNid'] ?? null);
$employeeDetails->setSex($userData['getSex'] ?? null);
$employeeDetails->setBlood($userData['getBlood'] ?? null);
$employeeDetails->setFather($userData['getFather'] ?? null);
$employeeDetails->setMother($userData['getMother'] ?? null);
$employeeDetails->setSpouse($userData['getSpouse'] ?? null);
$employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
$employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
$em->persist($employeeDetails);
}
$em->flush();
}
return new JsonResponse(['success' => true, 'message' => 'User, Employee, and EmployeeDetails updated in all ERP servers']);
}
public function SyncCentralUserToServerAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$post = $request;
$serverList = GeneralConstant::$serverListById;
$globalIdsByAppIdAndUser = [];
if ($systemType == '_CENTRAL_') {
$userDataList = [];
$retAppIds = [];
$appIdList = [];
$userIdList = [];
$retDataDebug = [];
$appIds = $request->get('appIds', '_UNSET_');
if ($appIds != '_UNSET_') {
$appIdList = $userIdList = explode(',', $appIds);;
if ($appIdList == null) $appIdList = [];
}
$userIds = $request->get('userIds', '_UNSET_');
if ($userIds != '_UNSET_') {
$userIdList = explode(',', $userIds);
if ($userIdList == null) $userIdList = [];
}
if (is_string($userDataList)) $userDataList = json_decode($userDataList, true);
if ($userDataList == null) $userDataList = [];
$em_goc = $this->getDoctrine()->getManager('company_group');
$centralUserQry = $em_goc->getRepository('CompanyGroupBundle:EntityApplicantDetails')
->createQueryBuilder('m')
->where("1=1");
if (!empty($userIdList))
$centralUserQry->andWhere("m.applicantId in (" . implode(',', $userIdList) . " )");
$centralUsers = $centralUserQry->getQuery()
->setMaxResults(1)
->getResult();
////ITEMGROUPS
foreach ($centralUsers as $centralUser) {
if ($centralUser) {
} else {
}
$toSetUserData = [];
$userData = array();
$userFiles = array();
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $centralUser->getImage(); //<-- Path could be relative
// $output=$file;
if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($file)) {
// $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
if (strpos($mime, 'image') !== false) {
$output = new \CURLFile($file, $mime, $name);
}
$skipSend = 0;
$userFiles['file_' . $centralUser->getApplicantId()] = $output;
} else {
$centralUser->setImage(null);
$userFiles['file_' . $centralUser->getApplicantId()] = 'pika';
$em_goc->flush();
}
//
$getters = array_filter(get_class_methods($centralUser), function ($method) {
return 'get' === substr($method, 0, 3);
});
$userDataSingle = array();
foreach ($getters as $getter) {
if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
continue;
// if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
// {
// $userDataSingle[$getter]= $user->{$getter}();
// }
if ($centralUser->{$getter}() instanceof \DateTime) {
$ggtd = $centralUser->{$getter}();
$userDataSingle[$getter] = $ggtd->format('Y-m-d');
} else
$userDataSingle[$getter] = $centralUser->{$getter}();
}
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
if ($userAppIds == null) $userAppIds = [];
$appIdList = array_merge($appIdList, array_diff($userAppIds, $appIdList));
$userTypesByAppIds = json_decode($centralUser->getUserTypesByAppIds(), true);
if ($userTypesByAppIds == null) $userTypesByAppIds = [];
$userDataSingle['userTypesByAppIds'] = $userTypesByAppIds;
$userDataList[] = $userDataSingle;
$em_goc->persist($centralUser);
$em_goc->flush();
}
$em_goc->flush();
$serverIdsCalledAlready = [];
$appList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(array(
'appId' => $appIdList
)
);
$userFiles['userData'] = json_encode($userDataList);
foreach ($appList as $app) {
if (!in_array($app->getCompanyGroupServerId(), $serverIdsCalledAlready)) {
if (isset($serverList[$app->getCompanyGroupServerId()])) {
// if ($skipSend == 0)
{
$urlToCall = $serverList[$app->getCompanyGroupServerId()]['absoluteUrl'] . '/SyncCentralUserToServer';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array(),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = json_decode($retData, true);
$retDataDebug[] = $retDataObj;
}
}
$serverIdsCalledAlready[] = $app->getCompanyGroupServerId();
}
}
// if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
// $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
//
// $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
// array(
// 'gid' => $centralUser->getApplicantId()
// );
return new JsonResponse(
array(
"success" => true,
"retDataDebug" => $retDataDebug,
"serverIdsCalledAlready" => $serverIdsCalledAlready,
"appIdList" => $appIdList,
"userFiles" => $userFiles,
"retAppIds" => $retAppIds,
)
);
} else {
$userDataList = $request->get('userData', []);
if (is_string($userDataList)) $userDataList = json_decode($userDataList, true);
if ($userDataList == null) $userDataList = [];
foreach ($userDataList as $userData) {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
$gocDataList = [];
$gocDataListByAppId = [];
$retDataDebug = array();
$appIds = json_decode($userData['getUserAppIds'], true);
if ($appIds == null) $appIds = [];
$userTypesByAppIds = json_decode($userData['getUserTypesByAppIds'], true);
if ($userTypesByAppIds == null) $userTypesByAppIds = [];
$userIds = $request->get('userIds', '_UNSET_');
if ($connected && !empty($appIds)) {
$findByQuery = array(
'active' => 1
);
$findByQuery['appId'] = $appIds;
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy($findByQuery);
$imagePathToSet = '';
$uploadedFile = $request->files->get('file_' . $userData['getApplicantId'], null);
{
if ($uploadedFile != null) {
$fileName = 'user_image' . $userData['getApplicantId'] . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
$imagePathToSet = 'uploads/UserImage/' . $path;
}
}
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
// if($debugCount>0)
// continue;
$skipSend = 1;
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
$user = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'globalId' => $userData['getApplicantId']
)
);
$output = '';
if (!$user)
$user = new SysUser();
$user->setGlobalId($userData['getApplicantId']);
$user->setUserAppId($entry['appId']);
$user_type = 1;
if (isset($userData['userTypesByAppIds'][$entry['appId']])) {
$user_type = $userData['userTypesByAppIds'][$entry['appId']];
}
$user->setUserType($user_type);
$user->setUserAppIdList(json_encode($appIds));
$user->setName($userData['getFirstname'] . ' ' . $userData['getLastname']);
$user->setStatus(UserConstants::ACTIVE_USER);
foreach ($userData as $getter => $value) {
if ($getter == 'getApplicantId')
continue;
$setMethod = str_replace('get', 'set', $getter);
if (method_exists($user, $setMethod)) {
if ($user->{$getter}() instanceof \DateTime)
$user->{$setMethod}(new \DateTime($value)); // `foo!`
else if ($setMethod == 'setUserAppIds') {
} else
$user->{$setMethod}($value); // `foo!`
}
}
if ($imagePathToSet != "") {
if ($user->getImage() != $imagePathToSet && $user->getImage() != '' && $user->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage())) {
unlink($this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage());
}
$user->setImage($imagePathToSet);
}
$em->persist($user);
$em->flush();
$debugCount++;
$retDataDebug[$debugCount] = array(
'skipSend' => $skipSend,
'userId' => $user->getUserId(),
'appId' => $user->getUserAppId(),
);
}
}
}
return new JsonResponse($retDataDebug);
}
}
public function GetUsersByQueryAction(Request $request, $id = 0)
{
$message = "";
$gocList = [];
$outputList = [];
$queryType = '_ANY_';
// if ($request->has('queryType'))
$queryType = $request->get('queryType', '_ANY_');
$returnData = [];
$debugData = [];
$returnDataArray = [];
$returnDataByServerId = [];
$serverId = $request->get('serverId', 4);
$serverUrl = $request->get('serverUrl', 'http://194.195.244.141');
$serverPort = $request->get('serverPort', '');
$queryStr = $request->get('queryStr', '');
$queryStrEmail = $request->get('quryStrEmail', '');
$queryStrPhone = $request->get('quryStrPhone', '');
if ($queryStrEmail == '' && $queryStrPhone == '') {
$queryStrEmail = $queryStr;
}
// sample
// data will be by company id
$d = array(
'userType' => 2,
'userId' => 4,
'userName' => 'abc',
'loginUserName' => 'CID-abc',
'serverId' => $serverId,
'serverUrl' => $serverUrl,
'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
'gocId' => 2,
'companyId' => 1,
'appId' => 45,
'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
'companyName' => 'HoneyBee Iot Ltd.',
'userCompanyIds' => [1, 4],
'userAppIds' => [1, 40],
'userCompanyList' => [
1 => [
'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
'companyName' => 'HoneyBee IoT Ltd.',
],
4 => [
'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
'companyName' => 'Nastec Srl',
]
]
);
// return new JsonResponse(array(
// $d, $d
// ));
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
if ($connected)
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(
array(
'active' => 1
)
);
$gocDataList = [];
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
$gocDbName = '';
$gocDbUser = '';
$gocDbPass = '';
$gocDbHost = '';
$gocId = 0;
// $web_root_dir = $this->container->getParameter('kernel.root_dir'). '/../web' ;
$web_root_dir = $url = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
// $root_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf';
foreach ($gocDataList as $gocId => $entry) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
$companyList = [];
$query = "SELECT * from company where 1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results))
foreach ($results as $dt) {
$companyList[$dt['id']] = $dt;
}
else
$companyList = array(
1 => [
'image' => '',
'name' => 'Company',
]
);
///SysUSER
$fieldName = ($queryType == '_EMAIL_' || $queryType == '_ANY_') ? 'email' : 'phone_number';
if ($queryStrEmail == '' && $queryStrPhone == '') {
} else {
$emailFieldName = 'email';
$phoneFieldName = 'phone_number';
$userNameFieldName = 'user_name';
$query = "SELECT * from sys_user where 1=1 ";
$query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail' " : '';
$query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%' " : '';
$query .= ($queryStr != '') ? " or $userNameFieldName like '$queryStr' " : '';
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
foreach ($results as $dt) {
// if($dt['company_id']==0 || $dt['company_id'] ==null)
$dt['company_id'] = "1";
$user_app_ids = json_decode($dt['user_app_id_list'], true);
if ($user_app_ids == null) $user_app_ids = [$dt['app_id']];
$user_company_ids = json_decode($dt['user_company_id_list'], true);
if ($user_company_ids == null) $user_company_ids = [$dt['company_id']];
$companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
$d = array(
'userType' => $dt['user_type'],
'userName' => $dt['user_name'],
'userId' => $dt['user_id'],
'loginUserName' => $dt['user_name'],
'email' => $dt['email'],
'phone' => $dt['phone_number'],
'serverId' => $serverId,
'serverUrl' => $serverUrl,
'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
'gocId' => $gocId,
'companyId' => $dt['company_id'],
'appId' => $dt['app_id'],
'companyLogoUrl' => $web_root_dir . $companyData['image'],
'companyName' => $companyData['name'],
'userCompanyIds' => $user_company_ids,
'userAppIds' => $user_app_ids,
'userCompanyList' => [
]
);
foreach ($user_company_ids as $cid) {
$d['userCompanyList'][$cid] = [
'companyLogoUrl' => $web_root_dir . $companyList[$cid]['image'],
'companyName' => $companyList[$cid]['name'],
];
}
$returnData[] = $d;
$returnDataByServerId[$serverId][] = $d;
}
}
//now customers
$emailFieldName = 'email';
$phoneFieldName = 'contact_number';
$query = "SELECT * from acc_clients where 1=1 ";
$query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" : '';
$query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" : '';
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
foreach ($results as $dt) {
$dt['company_id'] = "1";
$companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
$d = array(
'userType' => strval(UserConstants::USER_TYPE_CLIENT),
'userName' => 'CID-' . str_pad($dt['client_id'], 8, '0', STR_PAD_LEFT),
'userId' => $dt['client_id'],
'loginUserName' => $dt['username'],
'email' => $dt['email'],
'phone' => $dt['contact_number'],
'serverId' => $serverId,
'serverUrl' => $serverUrl,
'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
'gocId' => $gocId,
'companyId' => $dt['company_id'],
'appId' => $dt['app_id'],
'companyLogoUrl' => $web_root_dir . $companyData['image'],
'companyName' => $companyData['name'],
'userCompanyIds' => [],
'userAppIds' => [],
'userCompanyList' => [
]
);
$returnData[] = $d;
$returnDataByServerId[$serverId][] = $d;
}
}
//now suppliers
$emailFieldName = 'email';
$phoneFieldName = 'contact_number';
$query = "SELECT * from acc_suppliers where 1=1 ";
$query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" : '';
$query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" : '';
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
foreach ($results as $dt) {
$dt['company_id'] = "1";
$companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
$d = array(
'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
'userName' => 'SID-' . str_pad($dt['supplier_id'], 8, '0', STR_PAD_LEFT),
'userId' => $dt['supplier_id'],
'loginUserName' => $dt['username'],
'email' => $dt['email'],
'phone' => $dt['contact_number'],
'serverId' => $serverId,
'serverUrl' => $serverUrl,
'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
'gocId' => $gocId,
'companyId' => $dt['company_id'],
'appId' => $dt['app_id'],
'companyLogoUrl' => $web_root_dir . $companyData['image'],
'companyName' => $companyData['name'],
'userCompanyIds' => [],
'userAppIds' => [],
'userCompanyList' => [
]
);
$returnData[] = $d;
$returnDataByServerId[$serverId][] = $d;
}
}
}
}
return new JsonResponse(array(
'success' => true,
'data' => $returnData,
'debugData' => $debugData,
'dataByServerId' => $returnDataByServerId,
'queryType' => $queryType
));
}
public function GetHoneybeeServerListAction(Request $request, $id = 0)
{
$serverList = GeneralConstant::$serverList;
return new JsonResponse(array(
'success' => true,
'data' => $serverList,
));
}
public function ServerListAction()
{
$serverList = GeneralConstant::$serverList;
return new JsonResponse(
$serverList
);
}
public function widgetModuleListAction()
{
$widgetsModuleList = [
[
'name' => 'Accounts',
'id' => 1,
'hash' => '_ACC_',
'enabled' => true,
'hidden' => true,
],
[
'name' => 'Sales',
'id' => 2,
'hash' => '_SL_',
'enabled' => true,
'hidden' => true,
],
[
'name' => 'Human Resource',
'id' => 3,
'hash' => '_HRM_',
'enabled' => true,
'hidden' => true,
],
[
'name' => 'Admin',
'id' => 4,
'hash' => '_ADM_',
'enabled' => true,
'hidden' => true,
],
];
return new JsonResponse(
array(
'success' => true,
'widgetModuleList' => $widgetsModuleList
)
);
}
public function widgetListAction()
{
$widgetsList = [
[
'id' => 1,
'name' => 'Expense',
'hash' => '_EXP_',
'widgetModuleId' => 1,
'widgetName' => 'Accounts',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://e7.pngegg.com/pngimages/640/646/png-clipart-expense-management-computer-icons-finance-others-miscellaneous-text.png',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 2,
'name' => 'Attendance',
'hash' => '_ATD_',
'widgetModuleId' => 3,
'widgetName' => 'Human Resource',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://cdn.iconscout.com/icon/premium/png-256-thumb/biometric-attendance-1-1106795.png',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 3,
'name' => 'Payment',
'hash' => '_PMT_',
'widgetModuleId' => 1,
'widgetName' => 'Accounts',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://banner2.cleanpng.com/20180628/gbi/kisspng-management-accounting-accountant-gestin-kontabil-contador-5b356a344f40d2.2788485015302272523246.jpg',
'showOnHome' => true,
'routeList' => [
["id" => 3, "route" => "create_payment_voucher", "name" => "Make Payment", "parentId" => 3,],
["id" => 4, "route" => "create_receipt_voucher", "name" => "Make Receipt", "parentId" => 3,],
]
],
[
'id' => 4,
'name' => 'Report',
'hash' => '_RPRT_',
'widgetModuleId' => 1,
'widgetName' => 'Accounts',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://cdn-icons-png.flaticon.com/512/3093/3093748.png',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 5,
'name' => 'Leave Application',
'hash' => '_LEVAPP_',
'widgetModuleId' => 3,
'widgetName' => 'Human Resource',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://icons.veryicon.com/png/o/transport/easy-office-system-icon-library/leave-request.png',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 6,
'name' => 'Fund Requisition',
'hash' => '_FR_',
'widgetModuleId' => 1,
'widgetName' => 'Accounts',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://www.pngall.com/wp-content/uploads/13/Fund-PNG-Image.png',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 7,
'name' => 'My Task',
'hash' => '_MT_',
'widgetModuleId' => 3,
'widgetName' => 'Human Resource',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://st.depositphotos.com/44273736/54272/v/450/depositphotos_542726218-stock-illustration-premium-download-icon-task-management.jpg',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 8,
'name' => 'Fund Transfer',
'hash' => '_FT_',
'widgetModuleId' => 3,
'widgetName' => 'Accounts',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 9,
'name' => 'Stock Management',
'hash' => '_SM_',
'widgetModuleId' => 3,
'widgetName' => 'Inventory',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
'showOnHome' => true,
'routeList' => [
]
],
[
'id' => 10,
'name' => 'Approval',
'hash' => '_ADM_',
'widgetModuleId' => 4,
'widgetName' => 'Inventory',
'screenName' => '',
'hidden' => true,
'enabled' => true,
'image' => 'https://cdn.icon-icons.com/icons2/907/PNG/512/approve-sign-in-a-black-rounded-square-shape_icon-icons.com_70558.png',
'showOnHome' => true,
'routeList' => [
]
],
];
return new JsonResponse(
array(
'success' => true,
'widgetList' => $widgetsList
)
);
}
public function addRemoveWidgetAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
// $user = $em->getRepository("ApplicationBundle:SysUser")
// ->findBy();
return new JsonResponse(
// $user
);
}
public function EncryptParentModulesAction(Request $request, $appId = 0, $companyId = 0)
{
$message = "";
$gocList = [];
$outputList = [];
$pmodules = [];
if ($request->query->has('modulesByComma'))
$pmodules = explode(',', $request->query->get('modulesByComma'));
$iv = '1234567812345678';
$pass = $appId . '_' . $companyId;
// $method = 'aes-256-cbc';
$str = json_encode($pmodules);
// $str=$request->query->get('modulesByComma');
$str = $str . 'YmLRocksLikeABoss';
$data = $str;
$data = openssl_encrypt($str, "AES-128-CBC", $pass, 0, $iv);
// $data=$str;
// $data = openssl_decrypt($data, "AES-128-CBC", $pass, 0, $iv);
// $data = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $pass, 0, $iv);
return new Response($data);
// return new JsonResponse(array(
// 'encData'=>$data
// ));
}
public function PrepareDatabaseAction(Request $request)
{
$message = "";
$gocList = [];
$outputList = [];
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
if ($connected)
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(
array(
'active' => 1
)
);
$gocDataList = [];
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
$gocDbName = '';
$gocDbUser = '';
$gocDbPass = '';
$gocDbHost = '';
$gocId = 0;
// $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
$config_dir = $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
if (!file_exists($config_dir)) {
mkdir($config_dir, 0777, true);
}
// $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
// $content = file_exists($path) ? file_get_contents($path) : null;
$content = [];
$configJson = array();
if ($content)
$configJson = json_decode($content, true);
$configJsonOld = $configJson;
// if($configJson)
// {
//
// }
// else
{
$configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
$configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
$configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
$configJson['initiateDataBaseFlagByGoc'] = array();
$configJson['motherLode'] = "http://innobd.com";
foreach ($gocDataList as $gocId => $entry) {
$configJson['initiateDataBaseFlagByGoc'][$gocId . "_" . $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
}
}
//now check if database shcema update is true
// if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
if (1) //temporary overwrite all
{
//if goclist is not empty switch to each company dbase and schema update
// if(!empty($gocDataList))
if (1) {
foreach ($gocDataList as $gocId => $entry) {
if ($configJson['initiateDataBaseFlagByGoc'][$gocId . "_" . $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
true);
$em = $this->getDoctrine()->getManager();
if ($em->getConnection()->isConnected()) {
} else {
$servername = $gocDataList[$gocId]['dbHost'];
$username = $gocDataList[$gocId]['dbUser'];
$password = $gocDataList[$gocId]['dbPass'];
// Create connection
$conn = new \mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE " . $gocDataList[$gocId]['dbName'];
if ($conn->query($sql) === TRUE) {
// echo "Database created successfully";
} else {
// echo "Error creating database: " . $conn->error;
}
$conn->close();
}
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
true);
$em = $this->getDoctrine()->getManager();
$tool = new SchemaTool($em);
$classes = $em->getMetadataFactory()->getAllMetadata();
// $tool->createSchema($classes);
$tool->updateSchema($classes);
//new for updating app id
$get_kids_sql = "UPDATE `company` set app_id=" . $entry['appId'] . " ;
UPDATE `sys_user` set app_id=" . $entry['appId'] . " ;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
$configJson['initiateDataBaseFlagByGoc'][$gocId . "_" . $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
//this is for large amount of goc we will see later
// file_put_contents($path, json_encode($configJson));//overwrite
// return $this->redirectToRoute('update_database_schema');
}
}
} else {
$em = $this->getDoctrine()->getManager();
$tool = new SchemaTool($em);
// $classes = array(
// $em->getClassMetadata('Entities\User'),
// $em->getClassMetadata('Entities\Profile')
// );
$classes = $em->getMetadataFactory()->getAllMetadata();
// $tool->createSchema($classes);
$tool->updateSchema($classes);
}
}
$allSchemaUpdateDone = 1;
foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
$allSchemaUpdateDone = 0;
}
if ($allSchemaUpdateDone == 1)
$configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
///last
// file_put_contents($path, json_encode($configJson));//overwrite
return new Response(json_encode($configJsonOld));
}
public function ConvertSpecificationToSubCategoryAction(Request $request)
{
$message = "";
$gocList = [];
$outputList = [];
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$connected = $em->getConnection()->isConnected();
if ($connected)
$gocList = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(
array(
'active' => 1
)
);
$gocDataList = [];
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
$gocDbName = '';
$gocDbUser = '';
$gocDbPass = '';
$gocDbHost = '';
$gocId = 0;
// $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
$config_dir = $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
if (!file_exists($config_dir)) {
mkdir($config_dir, 0777, true);
}
// $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
// $content = file_exists($path) ? file_get_contents($path) : null;
$content = [];
$configJson = array();
if ($content)
$configJson = json_decode($content, true);
$configJsonOld = $configJson;
// if($configJson)
// {
//
// }
// else
{
$configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
$configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
$configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
$configJson['initiateDataBaseFlagByGoc'] = array();
$configJson['motherLode'] = "http://innobd.com";
foreach ($gocDataList as $gocId => $entry) {
$configJson['initiateDataBaseFlagByGoc'][$gocId . "_" . $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
}
}
$foundClasses = [];
if (1) {
foreach ($gocDataList as $gocId => $entry) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true);
$em = $this->getDoctrine()->getManager();
/////////////////////////////Now get all entity and if entity has specificationId (and subcatid) the asssign
$query = "show tables;";
$query = "SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('specification_id','sub_category_id')
AND TABLE_SCHEMA='" . $gocDataList[$gocId]['dbName'] . "' ;";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$tables = $stmt->fetchAll();
foreach ($tables as $tablename) {
// $theClass=new $entity;
$foundClasses[] = $tablename['TABLE_NAME'];
$query = "UPDATE " . $tablename['TABLE_NAME'] . " set sub_category_id=specification_id where 1;";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$query = "UPDATE " . $tablename['TABLE_NAME'] . " set specification_id=null;";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
}
//now add all spec to cat table
$query = "TRUNCATE inv_product_sub_categories";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$query = "SELECT * FROM inv_product_specifications WHERE 1;";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $result) {
foreach ($result as $k => $res) {
if ($res == '')
$result[$k] = 'NULL';
}
$query = "INSERT INTO `inv_product_sub_categories`(`id`, `name`, `status`, `ig_id`, `category_id`, `company_id`, `created_login_id`, `edited_login_id`, `created_at`, `updated_at`)
VALUES (" . $result['id'] . ",'" . str_replace("'", "''", $result['name']) . "'," . $result['status'] . "," . $result['ig_id'] . "," . $result['category_id'] . "," . $result['company_id'] . "," . $result['created_login_id'] . "," . $result['edited_login_id'] . ",'" . $result['created_at'] . "','" . $result['updated_at'] . "')";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
}
$query = "TRUNCATE inv_product_specifications";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
}
}
return new Response(json_encode($foundClasses));
}
public function initiateAdminAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$gocId = 0;
$appId = 0;
$gocEnabled = 0;
if ($this->container->hasParameter('entity_group_enabled'))
$gocEnabled = $this->container->getParameter('entity_group_enabled');
if ($gocEnabled == 1)
$connected = $em_goc->getConnection()->isConnected();
else
$connected = false;
if ($connected)
$gocList = $em_goc
->getRepository("CompanyGroupBundle:CompanyGroup")
->findBy(
array(
'active' => 1
)
);
$gocDataList = [];
$gocDataListForLoginWeb = [];
$gocDataListByAppId = [];
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'appId' => $entry->getAppId(),
'skipInWebFlag' => $entry->getSkipInWebFlag(),
'skipInAppFlag' => $entry->getSkipInAppFlag(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
if (in_array($entry->getSkipInWebFlag(), [0, null]))
$gocDataListForLoginWeb[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
if ($request->request->has('gocId') || $request->query->has('gocId')) {
$hasGoc = 1;
$gocId = $request->request->get('gocId');
}
if ($request->request->has('appId') || $request->query->has('appId')) {
$hasGoc = 1;
$appId = $request->request->get('appId');
}
$refRoute = $request->request->get('refRoute', $request->query->get('refRoute', ''));
if ($hasGoc == 1) {
if ($gocId != 0 && $gocId != "") {
$appId = $gocDataList[$gocId]['appId'];
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDataList[$gocId]['dbName'],
$gocDataList[$gocId]['dbUser'],
$gocDataList[$gocId]['dbPass'],
$gocDataList[$gocId]['dbHost'],
$reset = true
);
} else if ($appId != 0 && $appId != "") {
$gocDbName = $gocDataListByAppId[$appId]['dbName'];
$gocDbUser = $gocDataListByAppId[$appId]['dbUser'];
$gocDbPass = $gocDataListByAppId[$appId]['dbPass'];
$gocDbHost = $gocDataListByAppId[$appId]['dbHost'];
$gocId = $gocDataListByAppId[$appId]['id'];
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$gocDbName,
$gocDbUser,
$gocDbPass,
$gocDbHost,
$reset = true
);
}
}
$userName = $request->request->get('username', $request->query->get('username', 'admin'));
$name = $request->request->get('name', $request->query->get('name', 'System Admin'));
$password = $request->request->get('password', $request->query->get('password', 'admin'));
$email = $request->request->get('email', $request->query->get('email', 'admin'));
$encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userName);
$companyIds = $request->request->get('companyIds', $request->query->get('companyIds', [1]));
$branchIds = $request->request->get('branchIds', $request->query->get('branchIds', [1]));
$appIds = $request->request->get('appIds', $request->query->get('appIds', [$appId]));
$freshFlag = $request->request->get('fresh', $request->query->get('fresh', 1));
if ($freshFlag == 1) {
$query = "DELETE FROM sys_user WHERE user_type=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
}
$message = $this->get('user_module')->addNewUser(
$name,
$email,
$userName,
$password,
'',
0,
1,
UserConstants::USER_TYPE_SYSTEM,
$companyIds,
$branchIds,
'',
"",
1
);
$companyData = $message[2];
if ($message[0] == 'success') {
$oAuthData = [
'email' => $email,
'uniqueId' => '',
'image' => '',
'emailVerified' => '',
'name' => $name,
'type' => '0',
'token' => '',
];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/templates:userRegistrationCompleteHoneybee.html.twig';
$bodyData = array(
'name' => $name,
'email' => $email,
'password' => $password,
);
$attachments = [];
$forwardToMailAddress = $email;
if (filter_var($forwardToMailAddress, FILTER_VALIDATE_EMAIL)) {
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Welcome to Honeybee Ecosystem ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
// if ($request->request->get('remoteVerify', 0) == 1)
//// if(1)
// return new JsonResponse(array(
// 'success' => true,
// 'successStr' => 'Account Created Successfully',
// 'id' => $newApplicant->getApplicantId(),
// 'oAuthData' => $oAuthData,
// 'refRoute' => $refRoute,
// 'remoteVerify' => 1,
// ));
// else
// return $this->redirectToRoute("user_login", [
// 'id' => $newApplicant->getApplicantId(),
// 'oAuthData' => $oAuthData,
// 'refRoute' => $refRoute,
//
// ]);
$bodyHtml = '';
$bodyTemplate = 'ApplicationBundle:email/user:registration.html.twig';
$bodyData = array(
'name' => $request->request->get('name'),
'companyData' => $companyData,
'userName' => $request->request->get('username'),
'password' => $request->request->get('password'),
);
$attachments = [];
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_USER_MANAGEMENT_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $request->request->get('email'),
'subject' => 'User Registration on HoneyBee Ecosystem under Company ' . $companyData->getName(),
'fileName' => '',
'attachments' => $attachments,
'toAddress' => $request->request->get('email'),
// 'fromAddress'=>'sales@entity.innobd.com',
// 'userName'=>'sales@entity.innobd.com',
// 'password'=>'Y41dh8g0112',
// 'smtpServer'=>'smtp.hostinger.com',
// 'smtpPort'=>587,
// 'emailBody'=>$bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $request->request->get('company'),
'companyImagePath' => $companyData->getImage()
));
// $emailmessage = (new \Swift_Message('Registration to Entity'))
// ->setFrom('registration@entity.innobd.com')
// ->setTo($request->request->get('email'))
// ->setBody(
// $this->renderView(
// 'ApplicationBundle:email/user:registration.html.twig',
// array('name' => $request->request->get('name'),
// 'companyData' => $companyData,
// 'userName' => $request->request->get('email'),
// 'password' => $request->request->get('password'),
// )
// ),
// 'text/html'
// );
// /*
// * If you also want to include a plaintext version of the message
// ->addPart(
// $this->renderView(
// 'Emails/registration.txt.twig',
// array('name' => $name)
// ),
// 'text/plain'
// )
// */
//// ;
// $this->get('mailer')->send($emailmessage);
}
$this->addFlash(
$message[0],
$message[1]
);
// MiscActions::initiateAdminUser($em,$freshFlag,$userName,$name,$email,$encodedPassword,$appIds,$companyIds);
$this->addFlash(
'success',
'The Action was Successful.'
);
return $this->redirectToRoute('user_login');
}
public function DumpCurrModulesAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$modules = $em->getRepository("ApplicationBundle:SysModule")
->findBy(
array(// 'active'=>1
)
);
$module_data = [];
foreach ($modules as $entry) {
$dt = array(
'id' => $entry->getModuleId(),
'route' => $entry->getModuleRoute(),
'name' => $entry->getModuleName(),
'parentId' => $entry->getParentId(),
'level' => $entry->getLevel(),
'eFA' => $entry->getEnabledForAll(),
);
$module_data[$entry->getModuleId()] = $dt;
}
return new JsonResponse(
$module_data
);
}
}