<?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\Employee;
use ApplicationBundle\Entity\EmployeeDetails;
use ApplicationBundle\Entity\SysModule;
use ApplicationBundle\Entity\SysUser;
use ApplicationBundle\Interfaces\LoginInterface;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\Api\Constants\ApiConstants;
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\EmsSite;
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
{
private function getCloudApiKey()
{
$configured = '';
if ($this->container->hasParameter('cloud_api_key')) {
$configured = trim((string)$this->container->getParameter('cloud_api_key'));
}
if ($configured === '') {
$configured = trim((string)getenv('HONEYBEE_CLOUD_API_KEY'));
}
if ($configured === '') {
$configured = 'dev-cloud-key';
}
return $configured;
}
private function jsonErrorResponse($statusCode, $code, $message, array $details = array())
{
return new JsonResponse(array(
'status' => 'error',
'error' => array(
'code' => $code,
'message' => $message,
'details' => $details,
),
'meta' => array(
'schema_version' => '1.0',
'correlation_id' => uniqid('corr_', true),
),
), $statusCode);
}
private function ensureCloudImportTables($em_goc)
{
$conn = $em_goc->getConnection();
if (strtolower($conn->getDatabasePlatform()->getName()) !== 'mysql') {
return;
}
$conn->executeStatement('CREATE TABLE IF NOT EXISTS cloud_site_bundle_import_ledger (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
idempotency_key VARCHAR(255) NOT NULL,
bundle_hash VARCHAR(64) NOT NULL,
site_uid VARCHAR(255) NOT NULL,
source_system VARCHAR(64) NOT NULL,
correlation_id VARCHAR(255) NULL,
status VARCHAR(32) NOT NULL DEFAULT \'processing\',
request_json LONGTEXT NOT NULL,
response_json LONGTEXT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY uniq_cloud_site_bundle_import_key (idempotency_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
$conn->executeStatement('CREATE TABLE IF NOT EXISTS cloud_site_bundle_entity (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
site_uid VARCHAR(255) NOT NULL,
entity_type VARCHAR(64) NOT NULL,
entity_uid VARCHAR(255) NOT NULL,
bundle_hash VARCHAR(64) NOT NULL,
correlation_id VARCHAR(255) NULL,
payload_json LONGTEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY uniq_cloud_site_bundle_entity (site_uid, entity_type, entity_uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
}
private function upsertCloudBundleEntity($em_goc, $siteUid, $entityType, $entityUid, array $payload, $bundleHash, $correlationId)
{
$conn = $em_goc->getConnection();
$now = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
$conn->executeStatement(
'INSERT INTO cloud_site_bundle_entity
(site_uid, entity_type, entity_uid, bundle_hash, correlation_id, payload_json, created_at, updated_at)
VALUES
(:site_uid, :entity_type, :entity_uid, :bundle_hash, :correlation_id, :payload_json, :created_at, :updated_at)
ON DUPLICATE KEY UPDATE
bundle_hash = VALUES(bundle_hash),
correlation_id = VALUES(correlation_id),
payload_json = VALUES(payload_json),
updated_at = VALUES(updated_at)',
array(
'site_uid' => (string)$siteUid,
'entity_type' => (string)$entityType,
'entity_uid' => (string)$entityUid,
'bundle_hash' => (string)$bundleHash,
'correlation_id' => (string)$correlationId,
'payload_json' => json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
'created_at' => $now,
'updated_at' => $now,
)
);
}
private function getInfluxSettings()
{
$getEnv = function ($key) {
$value = getenv($key);
return $value === false ? '' : trim((string)$value);
};
return array(
'enabled' => $getEnv('HONEYBEE_INFLUX_WRITE_URL') !== '' && $getEnv('HONEYBEE_INFLUX_BUCKET') !== '',
'write_url' => $getEnv('HONEYBEE_INFLUX_WRITE_URL'),
'bucket' => $getEnv('HONEYBEE_INFLUX_BUCKET'),
'org' => $getEnv('HONEYBEE_INFLUX_ORG'),
'token' => $getEnv('HONEYBEE_INFLUX_TOKEN'),
'measurement' => $getEnv('HONEYBEE_INFLUX_MEASUREMENT') ?: 'telemetry',
'query_url' => $getEnv('HONEYBEE_INFLUX_QUERY_URL'),
'timeout' => (int)($getEnv('HONEYBEE_INFLUX_TIMEOUT') ?: 5),
);
}
private function escapeInfluxTag($value)
{
return str_replace(array('\\', ' ', ','), array('\\\\', '\ ', '\,'), (string)$value);
}
private function escapeInfluxFieldString($value)
{
return '"' . str_replace(array('\\', '"'), array('\\\\', '\"'), (string)$value) . '"';
}
private function httpRequest($url, $method, array $headers, $body, $timeout = 5)
{
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$responseBody = curl_exec($ch);
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
return array(
'ok' => $status >= 200 && $status < 300,
'status' => $status,
'body' => $responseBody,
'error' => $error,
);
}
$context = stream_context_create(array(
'http' => array(
'method' => $method,
'header' => implode("\r\n", $headers),
'content' => $body,
'timeout' => $timeout,
),
));
$responseBody = @file_get_contents($url, false, $context);
$status = 0;
if (isset($http_response_header) && is_array($http_response_header)) {
foreach ($http_response_header as $headerLine) {
if (preg_match('/^HTTP\/\S+\s+(\d+)/', $headerLine, $matches)) {
$status = (int)$matches[1];
break;
}
}
}
return array(
'ok' => $status >= 200 && $status < 300,
'status' => $status,
'body' => $responseBody,
'error' => $responseBody === false ? 'stream_request_failed' : '',
);
}
private function toInfluxFieldValue($value)
{
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
if (is_int($value)) {
return $value . 'i';
}
if (is_float($value) || is_numeric($value)) {
return (string)(0 + $value);
}
if (is_null($value)) {
return '""';
}
return $this->escapeInfluxFieldString($value);
}
private function writeInstantTelemetryToInflux(array $record, $siteUid, array $dashboardContext, $bundleHash, $correlationId)
{
$settings = $this->getInfluxSettings();
if (empty($settings['enabled'])) {
return false;
}
$timestamp = new \DateTime(isset($record['timestamp']) ? $record['timestamp'] : 'now');
$timestamp->setTimezone(new \DateTimeZone('+0000'));
$timestampNs = (string)((int)$timestamp->format('U') * 1000000000);
$tags = array(
'site_uid' => $siteUid,
'device_uid' => (string)($record['device_uid'] ?? $record['device_id'] ?? ''),
'point_uid' => (string)($record['point_uid'] ?? ''),
'point_code' => (string)($record['point_code'] ?? $record['identifier'] ?? ''),
'source' => (string)($record['source'] ?? 'honeycore'),
);
if (!empty($dashboardContext['site_type'])) {
$tags['site_type'] = (string)$dashboardContext['site_type'];
}
if (!empty($record['unit'])) {
$tags['unit'] = (string)$record['unit'];
}
$tagParts = array();
foreach ($tags as $tagKey => $tagValue) {
if ($tagValue === '') {
continue;
}
$tagParts[] = $this->escapeInfluxTag($tagKey) . '=' . $this->escapeInfluxTag($tagValue);
}
$fields = array(
'value' => $this->toInfluxFieldValue($record['value'] ?? null),
'record_id' => $this->escapeInfluxFieldString($record['record_id'] ?? ''),
'alias' => $this->escapeInfluxFieldString($record['alias'] ?? ''),
'schema_version' => $this->escapeInfluxFieldString($record['schema_version'] ?? '1.0'),
'bundle_hash' => $this->escapeInfluxFieldString($bundleHash),
'correlation_id' => $this->escapeInfluxFieldString($record['correlation_id'] ?? $correlationId),
);
if (isset($record['quality'])) {
$fields['quality'] = $this->escapeInfluxFieldString((string)$record['quality']);
}
if (isset($record['raw_value']) && is_scalar($record['raw_value'])) {
$fields['raw_value'] = $this->escapeInfluxFieldString((string)$record['raw_value']);
}
$line = $settings['measurement'];
if (!empty($tagParts)) {
$line .= ',' . implode(',', $tagParts);
}
$line .= ' ';
$fieldParts = array();
foreach ($fields as $fieldKey => $fieldValue) {
$fieldParts[] = $fieldKey . '=' . $fieldValue;
}
$line .= implode(',', $fieldParts) . ' ' . $timestampNs;
$writeUrl = $settings['write_url'];
$separator = strpos($writeUrl, '?') === false ? '?' : '&';
$writeUrl .= $separator . http_build_query(array(
'bucket' => $settings['bucket'],
'org' => $settings['org'],
'precision' => 'ns',
));
$headers = array(
'Content-Type: text/plain; charset=utf-8',
);
if ($settings['token'] !== '') {
$headers[] = 'Authorization: Token ' . $settings['token'];
}
$response = $this->httpRequest($writeUrl, 'POST', $headers, $line, $settings['timeout']);
if (!$response['ok']) {
return false;
}
return true;
}
private function upsertCloudTelemetry($em_goc, array $record, $siteUid, array $dashboardContext, $bundleHash, $correlationId)
{
if ($this->writeInstantTelemetryToInflux($record, $siteUid, $dashboardContext, $bundleHash, $correlationId)) {
return;
}
$siteIdInt = (int)$siteUid;
if ($siteIdInt <= 0) {
return;
}
$recordId = (string)($record['record_id'] ?? '');
if ($recordId === '') {
return;
}
$timestamp = new \DateTime(isset($record['timestamp']) ? $record['timestamp'] : 'now');
$timestamp->setTimezone(new \DateTimeZone('+0000'));
$entry = $em_goc->getRepository(DeviceSensorData::class)->findOneBy(array(
'recordId' => $recordId,
));
if (!$entry) {
$entry = new DeviceSensorData();
$entry->setRecordId($recordId);
$entry->setSiteId($siteIdInt);
}
$entry->setDeviceId((string)($record['device_uid'] ?? $record['device_id'] ?? ''));
$entry->setIdentifier((string)($record['point_code'] ?? $record['identifier'] ?? ''));
$entry->setAlias((string)($record['alias'] ?? ''));
$entry->setValue(is_scalar($record['value'] ?? null) ? (string)$record['value'] : json_encode($record['value'] ?? null));
$entry->setTimeStamp($timestamp);
$entry->setTimeStampTs((int)$timestamp->format('U'));
$em_goc->persist($entry);
$em_goc->flush();
}
public function CloudSiteBundleImportAction(Request $request, $id = 0)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$this->ensureCloudImportTables($em_goc);
$expectedApiKey = $this->getCloudApiKey();
$providedApiKey = trim((string)$request->headers->get('X-API-Key', ''));
if ($providedApiKey === '' || !hash_equals($expectedApiKey, $providedApiKey)) {
return $this->jsonErrorResponse(401, 'invalid_api_key', 'Invalid or missing cloud API key.');
}
$idempotencyKey = trim((string)$request->headers->get('Idempotency-Key', ''));
if ($idempotencyKey === '') {
return $this->jsonErrorResponse(400, 'missing_idempotency_key', 'Idempotency-Key header is required.');
}
$bundle = json_decode($request->getContent(), true);
if (!is_array($bundle)) {
return $this->jsonErrorResponse(400, 'invalid_json', 'Request body must be valid JSON.');
}
if (($bundle['schema_version'] ?? '') !== '1.0') {
return $this->jsonErrorResponse(400, 'invalid_schema_version', 'schema_version must be 1.0.');
}
if (($bundle['package_type'] ?? '') !== 'site_bundle') {
return $this->jsonErrorResponse(400, 'invalid_package_type', 'package_type must be site_bundle.');
}
$source = isset($bundle['source']) && is_array($bundle['source']) ? $bundle['source'] : array();
if (($source['system'] ?? '') !== 'honeycore') {
return $this->jsonErrorResponse(400, 'invalid_source_system', 'source.system must be honeycore.');
}
$siteUid = (string)($source['site_uid'] ?? '');
if ($siteUid === '') {
return $this->jsonErrorResponse(400, 'missing_site_uid', 'source.site_uid is required.');
}
$bundleHash = hash('sha256', json_encode($bundle, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
$correlationId = (string)($source['correlation_id'] ?? uniqid('corr_', true));
$conn = $em_goc->getConnection();
$existingLedger = $conn->fetchAssociative(
'SELECT response_json FROM cloud_site_bundle_import_ledger WHERE idempotency_key = :idempotency_key',
array('idempotency_key' => $idempotencyKey)
);
if ($existingLedger && !empty($existingLedger['response_json'])) {
return new JsonResponse(json_decode($existingLedger['response_json'], true), 200);
}
$now = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
$conn->executeStatement(
'INSERT INTO cloud_site_bundle_import_ledger
(idempotency_key, bundle_hash, site_uid, source_system, correlation_id, status, request_json, created_at, updated_at)
VALUES
(:idempotency_key, :bundle_hash, :site_uid, :source_system, :correlation_id, :status, :request_json, :created_at, :updated_at)
ON DUPLICATE KEY UPDATE
bundle_hash = VALUES(bundle_hash),
site_uid = VALUES(site_uid),
source_system = VALUES(source_system),
correlation_id = VALUES(correlation_id),
status = VALUES(status),
request_json = VALUES(request_json),
updated_at = VALUES(updated_at)',
array(
'idempotency_key' => $idempotencyKey,
'bundle_hash' => $bundleHash,
'site_uid' => $siteUid,
'source_system' => 'honeycore',
'correlation_id' => $correlationId,
'status' => 'processing',
'request_json' => json_encode($bundle, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
'created_at' => $now,
'updated_at' => $now,
)
);
$sitePayload = isset($bundle['site']) && is_array($bundle['site']) ? $bundle['site'] : array();
$dashboardContext = isset($bundle['dashboard_context']) && is_array($bundle['dashboard_context']) ? $bundle['dashboard_context'] : array();
$siteEntity = ctype_digit($siteUid) ? $em_goc->getRepository(EmsSite::class)->find((int)$siteUid) : null;
if (!$siteEntity) {
$siteEntity = new EmsSite();
}
if (method_exists($siteEntity, 'setSiteType')) {
$siteEntity->setSiteType((string)($sitePayload['site_type'] ?? $dashboardContext['site_type'] ?? $bundle['site_type'] ?? 'SOPHIA'));
}
if (method_exists($siteEntity, 'setSiteName') && isset($sitePayload['site_name'])) {
$siteEntity->setSiteName((string)$sitePayload['site_name']);
}
if (method_exists($siteEntity, 'setSiteLocation') && isset($sitePayload['address'])) {
$siteEntity->setSiteLocation((string)$sitePayload['address']);
}
if (method_exists($siteEntity, 'setSiteNote') && isset($sitePayload['description'])) {
$siteEntity->setSiteNote((string)$sitePayload['description']);
}
if (method_exists($siteEntity, 'setContactPerson') && isset($sitePayload['operator'])) {
$siteEntity->setContactPerson((string)$sitePayload['operator']);
}
if (method_exists($siteEntity, 'setSiteIcon') && isset($sitePayload['image_url'])) {
$siteEntity->setSiteIcon((string)$sitePayload['image_url']);
}
$em_goc->persist($siteEntity);
$em_goc->flush();
$this->upsertCloudBundleEntity($em_goc, $siteUid, 'site', $siteUid, $sitePayload, $bundleHash, $correlationId);
foreach (array('system_mode', 'dashboard_context') as $entityType) {
if (isset($bundle[$entityType]) && is_array($bundle[$entityType])) {
$this->upsertCloudBundleEntity($em_goc, $siteUid, $entityType, $siteUid, $bundle[$entityType], $bundleHash, $correlationId);
}
}
foreach (array('devices', 'points', 'constraints', 'control_actions') as $entityType) {
if (empty($bundle[$entityType]) || !is_array($bundle[$entityType])) {
continue;
}
foreach ($bundle[$entityType] as $row) {
if (!is_array($row)) {
continue;
}
$entityUid = '';
if ($entityType === 'devices') {
$entityUid = (string)($row['device_uid'] ?? '');
} elseif ($entityType === 'points') {
$entityUid = (string)($row['point_uid'] ?? '');
} elseif ($entityType === 'constraints') {
$entityUid = (string)($row['constraint_uid'] ?? '');
} elseif ($entityType === 'control_actions') {
$entityUid = (string)($row['action_id'] ?? '');
}
if ($entityUid === '') {
$entityUid = md5(json_encode($row));
}
$this->upsertCloudBundleEntity($em_goc, $siteUid, $entityType, $entityUid, $row, $bundleHash, $correlationId);
}
}
$telemetryCount = 0;
if (!empty($bundle['telemetry']) && is_array($bundle['telemetry'])) {
foreach ($bundle['telemetry'] as $record) {
if (!is_array($record)) {
continue;
}
$this->upsertCloudTelemetry($em_goc, $record, $siteUid, $dashboardContext, $bundleHash, $correlationId);
$telemetryCount++;
}
}
$responseEnvelope = array(
'status' => 'ok',
'data' => array(
'site_uid' => $siteUid,
'site_id' => ctype_digit($siteUid) ? (int)$siteUid : $siteUid,
'telemetry_count' => $telemetryCount,
'entity_count' => isset($bundle['devices']) && is_array($bundle['devices']) ? count($bundle['devices']) : 0,
),
'meta' => array(
'schema_version' => '1.0',
'correlation_id' => $correlationId,
'idempotency_key' => $idempotencyKey,
'bundle_hash' => $bundleHash,
),
'error' => null,
);
$conn->executeStatement(
'UPDATE cloud_site_bundle_import_ledger
SET status = :status, response_json = :response_json, updated_at = :updated_at
WHERE idempotency_key = :idempotency_key',
array(
'status' => 'ok',
'response_json' => json_encode($responseEnvelope, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
'updated_at' => (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s'),
'idempotency_key' => $idempotencyKey,
)
);
return new JsonResponse($responseEnvelope, 200);
}
public function DeviceDataHeartBeatAction(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
return new JsonResponse(array(
'success' => true,
));
}
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\\Entity\\' . $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\\Entity\\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\\Entity\\' . $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 = MiscActions::getServerListById(
$this->container->getParameter('database_user'),
$this->container->getParameter('database_password'),
$this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []
);
$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\\Entity\\CompanyGroup")
->findOneBy(array(
'appId' => $appId
));
if (!$goc)
$goc = new CompanyGroup();
if ($appId == 0) {
$biggestAppIdCg = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle\\Entity\\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', 1));
$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->setOwnerId($session->get(UserConstants::USER_ID));
$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\\Entity\\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);
// MiscActions::UpdateCompanyListInSession($em_goc, $centralUser->getApplicantId(), 1, 1, 1, $d);
//temporary solution
MiscActions::UpdateCompanyListInSession($em_goc, $session->get(UserConstants::USER_ID), 1, 1, 1, $d);
}
///now update Server
///
///
if ($post->get('skipUpdateCompanyToErpServer', '0') == 0) {
$response = MiscActions::updateCompanyToErpServer($em_goc, $goc->getAppId(), $this->container->getParameter('kernel.root_dir'));
if (isset($response['success']) && $response['success'] === true) {
return new JsonResponse(array(
'success' => true,
'message' => "Successfully Initialized The Company",
'data' => [],
'user_access_data' => $d,
'initiated' => 1,
));
}
} else {
return new JsonResponse(array(
'success' => true,
'message' => "Successfully Initialized The Company",
'data' => [],
'user_access_data' => $d,
'initiated' => 1,
));
}
}
return new JsonResponse(array(
'success' => false,
'message' => "Company Could not be Initialized or Updated",
'data' => [],
'user_access_data' => $d,
'initiated' => 0,
));
} else {
$em_goc = $this->getDoctrine()->getManager('company_group');
$findByQuery = array(
// 'active' => 1
'appId' => $post->get('app_id')
);
$goc = $em_goc->getRepository("CompanyGroupBundle\\Entity\\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\\Entity\\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->setAddress("xyz");
$company->setShippingAddress($post->get('s_address'));
// $company->setShippingAddress("abc");
$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->setCompanyHash($post->get('companyGroupHash', ''));
//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
//
// );
if ($company->getAppId()) {
// $returnData['message']='';
return new JsonResponse(array(
'success' => true,
'message' => "Successfully Initialized The Company",
'data' => [],
'user_access_data' => $d,
'initiated' => 1,
'app_id' => $company->getAppId(),
));
}
// return new JsonResponse($post_fields);
}
return new JsonResponse(array(
'success' => false,
'message' => "Company Could not be Initialized or Updated",
'data' => [],
'user_access_data' => $d,
'initiated' => 0,
'app_id' => 0
));
}
public function GenerateErpSubscriptionAction(Request $request, $id = 0)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$appId = $request->get('app_id', 0);
$userNo = $request->get('user_no', 0);
$adminNo = $request->get('admin_no', 0);
$post = $request;
$session = $request->getSession();
$d = array();
$returnData = array(
"invoiceAmount" => 0,
"dueAmount" => 0,
"invoiceId" => 0,
"isPaid" => 1,
);
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 = MiscActions::getServerListById(
$this->container->getParameter('database_user'),
$this->container->getParameter('database_password'),
$this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []
);
$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\\Entity\\CompanyGroup")
->findOneBy(array(
'appId' => $appId
));
if (!$goc)
$goc = new CompanyGroup();
$userNo = $goc->getUserAllowed();
$adminNo = $goc->getAdminUserAllowed();
//calculate usage here
$returnData = MiscActions::getInvoiceableAmountErpSubscription(GeneralConstant::$packageDetails, $userNo, $adminNo, $goc->getCompanyGroupBillingFrequency() == 2 ? 'yearly' : 'monthly');
$goc->setUserAllowed($returnData['noOfUser']);
$goc->setAdminUserAllowed($returnData['noOfAdmin']);
if ($returnData['dueAmount'] <= 0) {
if ($goc->getInitiateFlag() != 1) {
$goc->setInitiateFlag(2);
}
}
$em_goc->flush();
//if not covered by packages , temprarily grand free access if available . meanwhile alert sales
}
}
return new JsonResponse($returnData);
}
public function SyncCompanyGroupToErpServerAction(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 = MiscActions::getServerListById(
$this->container->getParameter('database_user'),
$this->container->getParameter('database_password'),
$this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []
);
$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\\Entity\\CompanyGroup")
->findOneBy(array(
'appId' => $appId
));
if (!$goc)
$goc = new CompanyGroup();
if ($appId == 0) {
$biggestAppIdCg = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy(array(// 'appId' => $appId
), array(
'appId' => 'desc'
));
if ($biggestAppIdCg)
$appId = 1 + $biggestAppIdCg->getAppId();
}
if ($goc->getInitiateFlag() == 1 || $goc->getInitiateFlag() == 2) {
$response = MiscActions::updateCompanyToErpServer($em_goc, $goc->getAppId(), $this->container->getParameter('kernel.root_dir'));
if (isset($response['success']) && $response['success'] === true) {
$goc->setInitiateFlag(1);
$em_goc->persist($goc);
$em_goc->flush();
return new JsonResponse(array(
'success' => true,
'message' => "Successfully Initialized The Company On Erp Server",
'data' => [],
'user_access_data' => $d,
'initiated' => 1,
));
}
}
}
return new JsonResponse(array(
'success' => false,
'message' => "Company Could not be Initialized or Updated",
'data' => [],
'user_access_data' => $d,
'initiated' => 0,
));
}
return new JsonResponse(array(
'success' => false,
'message' => "Company Could not be Initialized or Updated",
'data' => [],
'user_access_data' => $d,
'initiated' => 0,
'app_id' => 0
));
}
//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_local_default = $this->getDoctrine()->getManager();
$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);
$em_local_default->getConnection()->connect();
$em_local_default_connected = $em_local_default->getConnection()->isConnected();
if ($em_local_default_connected) {
$tool = new SchemaTool($em_local_default);
$classes = $em_local_default->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()->fetchAllAssociative($query);
$results = $stmt;
foreach ($results as $qpo) {
if ($this->container->get('app.legacy_password_service')->verifyWithSalt($qpo['password'], '', $qpo['salt'])
|| $this->container->get('app.legacy_password_service')->verifyWithSalt($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()->executeStatement($queryGG);
}
}
}
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()->fetchAllAssociative($query);
$results = $stmt;
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()->fetchAllAssociative($query);
$results = $stmt;
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()->executeStatement($query);
}
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()->executeStatement($query);
}
$get_kids_sql = "update `company_group` set `schema_update_pending_flag` =1 where 1;";
$stmt = $em_goc->getConnection()->executeStatement($get_kids_sql);
$stmt = $em_goc->getConnection()->fetchAllAssociative("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
//
$check_here = $stmt;
$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()->fetchAllAssociative("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
//
$check_here = $stmt;
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\\Entity\\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) {
$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();
$em->getConnection()->connect();
$indConnected = $em->getConnection()->isConnected();
if ($indConnected) {
$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()->executeStatement($get_kids_sql);
}
$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()->executeStatement($query);
}
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\\Entity\\' . $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\\Entity\\' . $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\\Entity\\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\\Entity\\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)['Opportunity'],
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\\Entity\\' . 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 == 'Opportunity') {
$theDocData = $em->getRepository('ApplicationBundle\\Entity\\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\\Entity\\DocumentData')
->findOneBy(
array(
'proposalId' => $the_actual_doc->getSalesProposalId()
)
);
if (!$theDocData)
if ($the_actual_doc->getOpportunityId() != null && $the_actual_doc->getOpportunityId() != 0)
$theDocData = $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
->findOneBy(
array(
'opportunityId' => $the_actual_doc->getOpportunityId()
)
);
if (!$theDocData)
if ($the_actual_doc->getProjectId() != null && $the_actual_doc->getProjectId() != 0)
$theDocData = $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
->findOneBy(
array(
'projectId' => $the_actual_doc->getProjectId()
)
);
if (!$theDocData) {
$theDocData = new DocumentData();
if ($entityNameHere == 'SalesProposal')
$theDocData->setProposalId($the_actual_doc->getSalesProposalId());
if ($entityNameHere == 'Opportunity')
$theDocData->setOpportunityId($the_actual_doc->getOpportunityId());
}
} else {
$theDocData = $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
->findOneBy(
array(
'id' => $the_actual_doc->getDocumentDataId()
)
);
if (!$theDocData)
$theDocData = $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
->findOneBy(
array(
'projectId' => $the_actual_doc->getProjectId()
)
);
if (!$theDocData) {
$theDocData = new DocumentData();
$theDocData->setProjectId($the_actual_doc->getProjectId());
}
}
if ($entityNameHere == 'ProjectBoq' || $entityNameHere == 'Opportunity' || $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 == 'Opportunity') $tempId = $the_actual_doc->getOpportunityId();
$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\\Entity\\Project')
->findOneBy(
array(
'projectId' => $the_actual_doc->getProjectId()
)
);
if ($theProj)
$theProj->setDocumentDataId($the_actual_doc->getDocumentDataId());
$em->flush();
}
}
}
}
if ($request->query->get('newDocDataItemSegmentFix', 0) == 1) {
$the_actual_docs = $em->getRepository('ApplicationBundle\\Entity\\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 = $the_actual_doc;
$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) {
$newSingleSet = $dt_poka;
$newSegmentData = array();
//unify the ids of segmnent. services will start from 1000+service segmentId for unification
if (!isset($newSingleSet['itemSegmentData'])) {
$newSingleSet['itemSegmentData'] = [];
}
if ($newSingleSet['itemSegmentData'] == null) {
$newSingleSet['itemSegmentData'] = [];
}
if (empty($newSingleSet['itemSegmentData'])) {
$gupu = [];
$newModSeg = $gupu;
$newModSeg['index'] = 0;
$newModSeg['title'] = 'Items & Services';
$newModSeg['scfc'] = 0;
$newModSeg['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;
}
$newData[$kho] = $newSingleSet;
}
$theDocData->setData(json_encode($newData));
$em->persist($theDocData);
$em->flush();
}
$em->flush();
}
}
if ($request->query->get('convertMarginToMarkupOldDocumentData', 0) == 1) {
$the_actual_docs = $em->getRepository('ApplicationBundle\\Entity\\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()->executeStatement($query);
}
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()->executeStatement($get_kids_sql);
$query = "SELECT * from company where 1";
$stmt = $em->getConnection()->fetchAllAssociative($query);
//
$results = $stmt;
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()->executeStatement($get_kids_sql);
}
$query = "SELECT * from client_level where 1";
$stmt = $em->getConnection()->fetchAllAssociative($query);
//
$results = $stmt;
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()->executeStatement($get_kids_sql);
//
}
$query = "SELECT * from sales_level where 1";
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results = $stmt;
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()->executeStatement($get_kids_sql);
}
$services = $em->getRepository('ApplicationBundle\\Entity\\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()->fetchAllAssociative($query);
$results = $stmt;
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()->executeStatement($get_kids_sql);
}
} 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()->executeStatement($get_kids_sql);
}
//
$query = "SELECT * from warehouse_action where 1";
$stmt = $em->getConnection()->fetchAllAssociative($query);
$newresults = $stmt;
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()->executeStatement($get_kids_sql);
}
}
$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()->fetchAllAssociative($get_kids_sql);
$dataList = $stmt;
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()->fetchAllAssociative($get_kids_sql_2);
$dataList = $stmt;
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()->executeStatement($get_kids_sql_3);
}
}
$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()->fetchAllAssociative($get_kids_sql);
$dataList = $stmt;
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()->executeStatement($get_kids_sql);
}
}
}
$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()->fetchAllAssociative($get_kids_sql);
$dataList = $stmt;
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()->executeStatement($get_kids_sql);
}
}
}
}
if ($request->query->get('employeeDetailsToProfile', 0) == 1) {
$migrationStats = $this->migrateEmployeeDetailsToProfile($em);
$configJson['employeeDetailsToProfile'] = $migrationStats;
}
$get_kids_sql = "update `company_group` set `schema_update_pending_flag` =0 where `id`=$gocId;";
$stmt = $em_goc->getConnection()->executeStatement($get_kids_sql);
$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\\Entity\\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\\Entity\\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()->executeStatement($get_kids_sql);
$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\\Entity\\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\\Entity\\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()->executeStatement($get_kids_sql);
//
//
//
// $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 = MiscActions::getServerListById($this->container->getParameter('database_user'), $this->container->getParameter('database_password'), $this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []);
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\\Entity\\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\\Entity\\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\\Entity\\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(),
'address' => $company->getAddress(),
's_address' => $company->getShippingAddress(),
'b_address' => $company->getBillingAddress(),
'company_image' => $company->getImage(),
'motto' => $company->getMotto(),
'i_footer' => $company->getInvoiceFooter(),
'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(),
'currentSubscriptionPackageId' => $company->getCurrentSubscriptionPackageId(),
'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\\Entity\\CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
}
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\\Entity\\CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
}
}
return new JsonResponse($gocDataList);
} else {
$findByQuery = array(
'userId' => $session->get(UserConstants::USER_ID, 0)
);
$employee = $this->getDoctrine()->getManager()
->getRepository("ApplicationBundle\\Entity\\Employee")
->findOneBy($findByQuery);
$assignedTaskList = array();
$currentlyWorkingTaskList = array();
if ($employee) {
$findByQuery = array(
'assignedTo' => $employee->getEmployeeId(),
'hasChild' => [0, null]
);
$assignedTaskListData = $this->getDoctrine()->getManager()
->getRepository("ApplicationBundle\\Entity\\PlanningItem")
->findBy($findByQuery);
$findByQuery = array(
'employeeId' => $employee->getEmployeeId(),
);
$currentlyWorkingTaskListData = $this->getDoctrine()->getManager()
->getRepository("ApplicationBundle\\Entity\\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\\Entity\\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\\Entity\\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']] = [];
}
if (in_array(1, $userTypesByAppIds[$cwa['getUserAppId']]) && $cwa['getUserType'] == 2) {
$userTypesByAppIds[$cwa['getUserAppId']] = array_diff($userTypesByAppIds[$cwa['getUserAppId']], [1]);
}
if (in_array(2, $userTypesByAppIds[$cwa['getUserAppId']]) && $cwa['getUserType'] == 1) {
$userTypesByAppIds[$cwa['getUserAppId']] = array_diff($userTypesByAppIds[$cwa['getUserAppId']], [2]);
}
$userTypesByAppIds[$cwa['getUserAppId']] = array_merge($userTypesByAppIds[$cwa['getUserAppId']], array_diff([$cwa['getUserType']], $userTypesByAppIds[$cwa['getUserAppId']]));
// $userTypesByAppIds[$cwa['getUserAppId']] = [$cwa['getUserType']];
$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\\Entity\\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\\Entity\\CompanyGroup")
->findBy($findByQuery);
foreach ($gocList as $entry) {
$d = array(
'name' => $entry->getName(),
'id' => $entry->getId(),
'image' => $entry->getImage(),
'companyGroupHash' => $entry->getCompanyGroupHash(),
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'appId' => $entry->getAppId(),
'companyRemaining' => $entry->getCompanyRemaining(),
'companyAllowed' => $entry->getCompanyAllowed(),
);
$gocDataList[$entry->getId()] = $d;
$gocDataListByAppId[$entry->getAppId()] = $d;
}
$debugCount = 0;
foreach ($gocDataList as $gocId => $entry) {
// 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\\Entity\\SysUser')
->findBy(
array(
'userId' => $userIds
)
);
else
$users = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\SysUser')
->findBy(
array()
);
$output = '';
$userData = array();
$userFiles = array();
foreach ($users as $user) {
$file = $this->container->getParameter('kernel.root_dir') . '/../web/' . $user->getImage(); //<-- 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()->fetchAllAssociative($query);
$results = $stmt;
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()->fetchAllAssociative($query);
$results = $stmt;
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\\Entity\\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\\Entity\\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\\Entity\\SysUser')->findOneBy(['globalId' => $globalId]);
if (!$user) {
return new JsonResponse(['success' => false, 'message' => 'User not found'], 404);
}
// $user = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['userId' => $user->getUserId()]);
// if (!$user) {
// $user = new \ApplicationBundle\Entity\EncryptedSignature();
// $user->setUserId($user->getUserId());
// $user->setCreatedAt(new \DateTime());
// }
if (!isset($userData['getFirstname']) && !isset($userData['getFirstName'])) {
if (isset($userData['getName'])) {
$nameStrArr = explode(" ", $userData['getName']);
$userData['getFirstname'] = isset($nameStrArr[0]) ? $nameStrArr[0] : '';
$userData['getLastname'] = isset($nameStrArr[1]) ? $nameStrArr[1] : '';
}
$userData['getFirstName'] = $userData['getFirstname'];
$userData['getLastName'] = $userData['getLastname'];
} else if (!isset($userData['getFirstName'])) {
$userData['getFirstName'] = $userData['getFirstname'];
$userData['getLastName'] = $userData['getLastname'];
} else if (!isset($userData['getFirstname'])) {
$userData['getFirstname'] = $userData['getFirstName'];
$userData['getLastname'] = $userData['getLastName'];
}
$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\\Entity\\Employee')->findOneBy(['userId' => $user->getUserId()]);
if ($employee) {
$employee->setFirstName($userData['getFirstname']);
$employee->setLastName($userData['getLastname']);
$employee->setName($userData['getFirstname'] . ' ' . $userData['getLastname']);
$em->persist($employee);
}
if ($employee)
$employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
->findOneBy(['id' => $employee->getEmployeeId()]);
else
$employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\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 MergeApplicantGlobalIdOnServerAction(Request $request)
{
$payload = json_decode($request->getContent(), true);
if (!is_array($payload)) {
$payload = $request->request->all();
}
$oldGlobalId = isset($payload['oldGlobalId']) ? (int)$payload['oldGlobalId'] : 0;
$newGlobalId = isset($payload['newGlobalId']) ? (int)$payload['newGlobalId'] : 0;
$appIds = isset($payload['appIds']) ? $payload['appIds'] : [];
if (is_string($appIds)) {
$decoded = json_decode($appIds, true);
$appIds = is_array($decoded) ? $decoded : explode(',', $appIds);
}
if (!is_array($appIds)) {
$appIds = [];
}
$appIds = array_values(array_unique(array_filter(array_map('intval', $appIds))));
if ($oldGlobalId <= 0 || $newGlobalId <= 0 || empty($appIds)) {
return new JsonResponse(['success' => false, 'message' => 'oldGlobalId, newGlobalId and appIds are required.'], 400);
}
$emGoc = $this->getDoctrine()->getManager('company_group');
$companies = $emGoc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['appId' => $appIds]);
$results = [];
foreach ($companies as $entry) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$entry->getDbName(),
$entry->getDbUser(),
$entry->getDbPass(),
$entry->getDbHost(),
$reset = true
);
$em = $this->getDoctrine()->getManager();
$oldUser = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $oldGlobalId]);
$newUser = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $newGlobalId]);
$appResult = [
'appId' => (int)$entry->getAppId(),
'oldFound' => $oldUser ? true : false,
'newFound' => $newUser ? true : false,
'mergedIntoExistingUser' => false,
'retaggedOldUser' => false,
];
if ($oldUser && $newUser && (int)$oldUser->getUserId() !== (int)$newUser->getUserId()) {
if (!$newUser->getEmail() && $oldUser->getEmail()) {
$newUser->setEmail($oldUser->getEmail());
}
if (!$newUser->getImage() && $oldUser->getImage()) {
$newUser->setImage($oldUser->getImage());
}
if (!$newUser->getName() && $oldUser->getName()) {
$newUser->setName($oldUser->getName());
}
$conn = $em->getConnection();
$conn->executeStatement('UPDATE employee SET user_id = :newUserId WHERE user_id = :oldUserId', [
'newUserId' => (int)$newUser->getUserId(),
'oldUserId' => (int)$oldUser->getUserId(),
]);
$conn->executeStatement('UPDATE employee_details SET user_id = :newUserId WHERE user_id = :oldUserId', [
'newUserId' => (int)$newUser->getUserId(),
'oldUserId' => (int)$oldUser->getUserId(),
]);
$oldUser->setGlobalId(null);
$oldUser->setStatus(0);
$oldUser->setUserName(($oldUser->getUserName() ?: 'merged_user') . '_merged_' . $oldGlobalId);
if ($oldUser->getEmail()) {
$oldUser->setEmail('merged_' . $oldGlobalId . '_' . time() . '@invalid.local');
}
$em->persist($newUser);
$em->persist($oldUser);
$em->flush();
$appResult['mergedIntoExistingUser'] = true;
} elseif ($oldUser) {
$oldUser->setGlobalId($newGlobalId);
$em->persist($oldUser);
$em->flush();
$appResult['retaggedOldUser'] = true;
}
$results[] = $appResult;
}
return new JsonResponse([
'success' => true,
'results' => $results,
]);
}
public function SyncCentralUserToServerAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$post = $request;
$serverList = MiscActions::getServerListById($this->container->getParameter('database_user'), $this->container->getParameter('database_password'), $this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []);
$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\\Entity\\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\\Entity\\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\\Entity\\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\\Entity\\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);
if (!isset($userData['getFirstname']) && !isset($userData['getFirstName'])) {
if (isset($userData['getName'])) {
$nameStrArr = explode(" ", $userData['getName']);
$userData['getFirstname'] = isset($nameStrArr[0]) ? $nameStrArr[0] : '';
$userData['getLastname'] = isset($nameStrArr[1]) ? $nameStrArr[1] : '';
}
$userData['getFirstName'] = $userData['getFirstname'];
$userData['getLastName'] = $userData['getLastname'];
} else if (!isset($userData['getFirstName'])) {
$userData['getFirstName'] = $userData['getFirstname'];
$userData['getLastName'] = $userData['getLastname'];
} else if (!isset($userData['getFirstname'])) {
$userData['getFirstname'] = $userData['getFirstName'];
$userData['getLastname'] = $userData['getLastName'];
}
if (!isset($userData['getName'])) {
$userData['getName'] = $userData['getFirstname'] . ' ' . $userData['getLastName'];
}
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();
///new test add employee
///
$employee = $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(['userId' => $user->getUserId()]);
if (!$employee)
$employee = new Employee();
if ($employee) {
$employee->setFirstName($userData['getFirstname']);
$employee->setLastName($userData['getLastname']);
$employee->setName($userData['getFirstname'] . ' ' . $userData['getLastname']);
$employee->setUserId($user->getUserId());
$em->persist($employee);
}
$em->flush();
if ($employee)
$employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
->findOneBy(['id' => $employee->getEmployeeId()]);
else
$employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
->findOneBy(['userId' => $user->getUserId()]);
if (!$employeeDetails) {
$employeeDetails = new EmployeeDetails();
$employeeDetails->setEmpType(1);
$employeeDetails->setEmpStatus(1);
}
if ($employeeDetails) {
$employeeDetails->setFirstname($userData['getFirstname']);
$employeeDetails->setLastname($userData['getLastname']);
$employeeDetails->setUsername($userData['getUsername']);
$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);
$employeeDetails->setUserId($user->getUserId());
$employeeDetails->setId($employee->getEmployeeId());
$em->persist($employeeDetails);
}
$em->flush();
/// new test end
$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\\Entity\\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()->fetchAllAssociative($query);
$results = $stmt;
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()->fetchAllAssociative($query);
$results = $stmt;
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()->fetchAllAssociative($query);
$results = $stmt;
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()->fetchAllAssociative($query);
$results = $stmt;
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\\Entity\\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\\Entity\\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()->executeStatement($get_kids_sql);
$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\\Entity\\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()->fetchAllAssociative($query);
$tables = $stmt;
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()->executeStatement($query);
$query = "UPDATE " . $tablename['TABLE_NAME'] . " set specification_id=null;";
$stmt = $em->getConnection()->executeStatement($query);
}
//now add all spec to cat table
$query = "TRUNCATE inv_product_sub_categories";
$stmt = $em->getConnection()->executeStatement($query);
$query = "SELECT * FROM inv_product_specifications WHERE 1;";
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results = $stmt;
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()->executeStatement($query);
}
$query = "TRUNCATE inv_product_specifications";
$stmt = $em->getConnection()->executeStatement($query);
}
}
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\\Entity\\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('app.legacy_password_service')->hashWithSalt($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()->executeStatement($query);
}
$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 = '@Application/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' => 'accounts@ourhoneybee.eu',
'userName' => 'accounts@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 = '@Application/email/user/registration.html.twig';
$bodyData = array(
'name' => $request->request->get('name'),
'companyData' => $companyData,
'userName' => $request->request->get('username'),
'password' => $request->request->get('password'),
);
$attachments = [];
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_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\\Entity\\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
);
}
public function GetTenantDashboardMetricsAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType === '_CENTRAL_') {
return new JsonResponse([
'success' => false,
'message' => 'Tenant metrics are available only on ERP servers.',
], 400);
}
$days = max(1, (int)$request->get('days', 30));
$requestedAppIds = $this->normalizeTenantAppIds($request);
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$companyRows = $this->loadTenantCompanyRows($conn, $requestedAppIds);
if (empty($companyRows)) {
$companyRows = [
[
'id' => 0,
'appId' => $requestedAppIds[0] ?? 0,
'name' => 'Company',
'email' => '',
'company_status' => 'active',
'package_type' => null,
'subscription_expiry' => null,
'last_activity_at' => null,
],
];
}
$userCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_user');
$activeUserCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_user WHERE status = 1 OR account_status IN (1, 2, 3)');
$loginCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_login_log');
$pageVisitCount = (int)$conn->fetchOne("SELECT COUNT(*) FROM user_activity_logs WHERE action_type = 'page_visit'");
$apiCallCount = (int)$conn->fetchOne("SELECT COUNT(*) FROM user_activity_logs WHERE action_type = 'api_call'");
$salesOrderCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sales_order');
$salesInvoiceCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sales_invoice');
$purchaseOrderCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM purchase_order');
$purchaseInvoiceCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM purchase_invoice');
$salesInvoiceTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM sales_invoice");
$salesPaidTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) FROM sales_invoice");
$purchaseInvoiceTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM purchase_invoice");
$purchasePaidTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) FROM purchase_invoice");
$activityTrend = $conn->fetchAllAssociative('
SELECT DATE(created_at) AS day, action_type AS activity_type, COUNT(*) AS total
FROM user_activity_logs
WHERE created_at >= DATE_SUB(NOW(), INTERVAL :days DAY)
AND action_type IN (\'page_visit\', \'api_call\')
GROUP BY DATE(created_at), action_type
ORDER BY day ASC
', ['days' => $days], ['days' => \PDO::PARAM_INT]);
$loginTrend = $conn->fetchAllAssociative('
SELECT DATE(log_time) AS day, COUNT(*) AS total
FROM sys_login_log
WHERE log_time >= DATE_SUB(NOW(), INTERVAL :days DAY)
GROUP BY DATE(log_time)
ORDER BY day ASC
', ['days' => $days], ['days' => \PDO::PARAM_INT]);
$revenueTrend = $conn->fetchAllAssociative("
SELECT DATE(sales_invoice_date) AS day, COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) AS total
FROM sales_invoice
WHERE sales_invoice_date >= DATE_SUB(NOW(), INTERVAL :days DAY)
GROUP BY DATE(sales_invoice_date)
ORDER BY day ASC
", ['days' => $days], ['days' => \PDO::PARAM_INT]);
$recentActivity = $conn->fetchAllAssociative('
SELECT
id,
user_id AS userId,
session_id AS sessionId,
route,
action_type AS activityType,
metadata,
duration_seconds AS durationSeconds,
created_at AS createdAt
FROM user_activity_logs
ORDER BY created_at DESC
LIMIT 10
');
$recentLogins = $conn->fetchAllAssociative('
SELECT
login_id AS loginId,
user_id AS userId,
position_id AS positionId,
log_time AS logTime,
log_status AS logStatus
FROM sys_login_log
ORDER BY log_time DESC
LIMIT 10
');
$recentSales = $conn->fetchAllAssociative('
SELECT
sales_invoice_id AS salesInvoiceId,
sales_invoice_number AS salesInvoiceNumber,
company_id AS companyId,
sales_invoice_date AS salesInvoiceDate,
invoice_amount AS invoiceAmount,
received_amount AS paidAmount,
due_amount AS dueAmount
FROM sales_invoice
ORDER BY sales_invoice_date DESC
LIMIT 10
');
$firstActivityAt = $recentActivity[0]['createdAt'] ?? null;
$firstLoginAt = $recentLogins[0]['logTime'] ?? null;
$firstSalesAt = $recentSales[0]['salesInvoiceDate'] ?? null;
$companySnapshots = [];
$totalLastActivity = null;
foreach ($companyRows as $row) {
$companyLastActivity = $this->maxTenantActivityTimestamp(
$row['last_activity_at'] ?? null,
$firstActivityAt,
$firstLoginAt,
$firstSalesAt
);
$companySnapshots[(int)($row['appId'] ?? 0)] = [
'id' => $row['id'] ?? 0,
'appId' => (int)($row['appId'] ?? 0),
'name' => $row['name'] ?? 'Company',
'email' => $row['email'] ?? '',
'company_status' => $row['company_status'] ?? 'active',
'package_type' => $row['package_type'] ?? null,
'subscription_expiry' => $row['subscription_expiry'] ?? null,
'last_activity_at' => $companyLastActivity,
'user_count' => $userCount,
'active_user_count' => $activeUserCount,
'login_count' => $loginCount,
'page_visit_count' => $pageVisitCount,
'api_call_count' => $apiCallCount,
'sales_order_count' => $salesOrderCount,
'sales_invoice_count' => $salesInvoiceCount,
'purchase_order_count' => $purchaseOrderCount,
'purchase_invoice_count' => $purchaseInvoiceCount,
'sales_invoice_total' => $salesInvoiceTotal,
'sales_paid_total' => $salesPaidTotal,
'purchase_invoice_total' => $purchaseInvoiceTotal,
'purchase_paid_total' => $purchasePaidTotal,
'recent_activity' => $recentActivity,
'recent_logins' => $recentLogins,
'recent_sales' => $recentSales,
];
$totalLastActivity = $this->maxTenantActivityTimestamp($totalLastActivity, $companyLastActivity);
}
return new JsonResponse([
'success' => true,
'system_type' => $systemType,
'days' => $days,
'requested_app_ids' => $requestedAppIds,
'company_count' => count($companySnapshots),
'companies' => $companySnapshots,
'totals' => [
'user_count' => $userCount,
'active_user_count' => $activeUserCount,
'login_count' => $loginCount,
'page_visit_count' => $pageVisitCount,
'api_call_count' => $apiCallCount,
'sales_order_count' => $salesOrderCount,
'sales_invoice_count' => $salesInvoiceCount,
'purchase_order_count' => $purchaseOrderCount,
'purchase_invoice_count' => $purchaseInvoiceCount,
'sales_invoice_total' => $salesInvoiceTotal,
'sales_paid_total' => $salesPaidTotal,
'purchase_invoice_total' => $purchaseInvoiceTotal,
'purchase_paid_total' => $purchasePaidTotal,
'last_activity_at' => $totalLastActivity,
],
'trend_rows' => [
'activity' => $activityTrend,
'login' => $loginTrend,
'revenue' => $revenueTrend,
],
]);
}
private function normalizeTenantAppIds(Request $request)
{
$appIds = $request->get('appIds', []);
$appId = (int)$request->get('appId', 0);
if (is_string($appIds)) {
$decoded = json_decode($appIds, true);
if (is_array($decoded)) {
$appIds = $decoded;
} else {
$appIds = [$appIds];
}
}
if (!is_array($appIds)) {
$appIds = [];
}
if ($appId > 0) {
$appIds[] = $appId;
}
return array_values(array_unique(array_filter(array_map('intval', $appIds))));
}
private function loadTenantCompanyRows($conn, array $appIds = [])
{
$sql = '
SELECT
id,
app_id AS appId,
name,
email,
company_status,
package_type,
subscription_expiry,
last_activity_at
FROM company
';
if (!empty($appIds)) {
$sql .= ' WHERE app_id IN (' . implode(',', array_map('intval', $appIds)) . ')';
}
$sql .= ' ORDER BY id ASC';
return $conn->fetchAllAssociative($sql);
}
private function maxTenantActivityTimestamp(...$values)
{
$maxTs = null;
$maxValue = null;
foreach ($values as $value) {
if (empty($value)) {
continue;
}
$ts = strtotime((string)$value);
if ($ts === false) {
continue;
}
if ($maxTs === null || $ts > $maxTs) {
$maxTs = $ts;
$maxValue = is_string($value) ? $value : (string)$value;
}
}
return $maxValue;
}
private function populateEmployeeCoreFromDetails(Employee $employee, EmployeeDetails $details, array &$stats = null)
{
$changed = false;
$assignIfEmpty = function ($setter, $value, $label = null) use ($employee, &$changed, &$stats) {
if ($value === null || $value === '') {
return;
}
$getter = 'get' . substr($setter, 3);
if (method_exists($employee, $getter)) {
$current = $employee->{$getter}();
if ($current !== null && $current !== '') {
if ($stats !== null && $label !== null && (string)$current !== (string)$value) {
if (!isset($stats['conflict_count'])) {
$stats['conflict_count'] = 0;
}
if (!isset($stats['conflict_fields'])) {
$stats['conflict_fields'] = array();
}
$stats['conflict_count']++;
$stats['conflict_fields'][] = $label;
}
return;
}
}
if (method_exists($employee, $setter)) {
$employee->{$setter}($value);
$changed = true;
}
};
$firstName = method_exists($details, 'getFirstname') ? $details->getFirstname() : null;
$lastName = method_exists($details, 'getLastname') ? $details->getLastname() : null;
$name = trim((string)$firstName . ' ' . (string)$lastName);
if ($name === '') {
$name = null;
}
$assignIfEmpty('setFirstName', $firstName, 'firstName');
$assignIfEmpty('setLastName', $lastName, 'lastName');
$assignIfEmpty('setName', $name, 'name');
$assignIfEmpty('setEmail', method_exists($details, 'getEmail') ? $details->getEmail() : null, 'email');
$phone = null;
if (method_exists($details, 'getPhone')) {
$phone = $details->getPhone();
}
if (($phone === null || $phone === '') && method_exists($details, 'getOfficialPhone')) {
$phone = $details->getOfficialPhone();
}
$assignIfEmpty('setContactNumber', $phone, 'contactNumber');
$assignIfEmpty('setCurrentAddress', method_exists($details, 'getCurrAddr') ? $details->getCurrAddr() : null, 'currentAddress');
$assignIfEmpty('setPermanentAddress', method_exists($details, 'getPermAddr') ? $details->getPermAddr() : null, 'permanentAddress');
$assignIfEmpty('setImage', method_exists($details, 'getImage') ? $details->getImage() : null, 'image');
$assignIfEmpty('setIdsByDevice', method_exists($details, 'getIdsByDevice') ? $details->getIdsByDevice() : null, 'idsByDevice');
$assignIfEmpty('setEmployeeCode', method_exists($details, 'getEmpCode') ? $details->getEmpCode() : null, 'employeeCode');
$assignIfEmpty('setEmployeeLevel', method_exists($details, 'getEmployeeLevel') ? $details->getEmployeeLevel() : null, 'employeeLevel');
$assignIfEmpty('setUserId', method_exists($details, 'getUserId') ? $details->getUserId() : null, 'userId');
if (method_exists($details, 'getEmpStatus')) {
$status = $details->getEmpStatus();
if ($status !== null && $status !== '') {
$assignIfEmpty('setStatus', (string)$status, 'status');
}
}
if (method_exists($details, 'getJoiningDate')) {
$joiningDate = $details->getJoiningDate();
if ($joiningDate !== null && method_exists($employee, 'getJoiningDate')) {
$currentJoiningDate = $employee->getJoiningDate();
if ($currentJoiningDate === null || $currentJoiningDate === '') {
if (method_exists($employee, 'setJoiningDate')) {
$employee->setJoiningDate($joiningDate);
$changed = true;
} elseif ($stats !== null) {
if (!isset($stats['conflict_count'])) {
$stats['conflict_count'] = 0;
}
if (!isset($stats['conflict_fields'])) {
$stats['conflict_fields'] = array();
}
$stats['conflict_count']++;
$stats['conflict_fields'][] = 'joiningDate';
}
}
}
}
return $changed;
}
private function migrateEmployeeDetailsToProfile($em)
{
$stats = array(
'supported' => true,
'skipped' => false,
'created_profile_table' => false,
'profile_rows_synced' => 0,
'profile_rows_rekeyed' => 0,
'employee_rows_synced' => 0,
'created_employee_shells' => 0,
'conflict_count' => 0,
'conflict_fields' => array(),
'messages' => array(),
);
$conn = $em->getConnection();
$platformName = strtolower((string)$conn->getDatabasePlatform()->getName());
if ($platformName !== 'mysql') {
$stats['supported'] = false;
$stats['skipped'] = true;
$stats['messages'][] = 'employee migration is mysql-only';
return $stats;
}
$tableExists = function ($tableName) use ($conn) {
$rows = $conn->fetchAllAssociative(
"SELECT COUNT(*) AS table_count
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = '" . str_replace("'", "''", $tableName) . "'"
);
return isset($rows[0]['table_count']) && (int)$rows[0]['table_count'] > 0;
};
if (!$tableExists('employee_details')) {
$stats['skipped'] = true;
$stats['messages'][] = 'employee_details table was not found';
return $stats;
}
if (!$tableExists('employee_profile')) {
$ddlRows = $conn->fetchAllAssociative('SHOW CREATE TABLE `employee_details`');
if (!empty($ddlRows[0])) {
$createSql = '';
$rowValues = array_values($ddlRows[0]);
foreach ($rowValues as $value) {
if (is_string($value) && stripos($value, 'CREATE TABLE') === 0) {
$createSql = $value;
break;
}
}
if ($createSql === '' && isset($rowValues[1])) {
$createSql = $rowValues[1];
}
if ($createSql !== '') {
$createSql = str_replace('CREATE TABLE `employee_details`', 'CREATE TABLE `employee_profile`', $createSql);
$createSql = str_replace('`id`', '`employee_id`', $createSql);
$conn->executeStatement($createSql);
$stats['created_profile_table'] = true;
}
}
}
$copyColumns = array();
$columnRows = $conn->fetchAllAssociative('SHOW COLUMNS FROM `employee_details`');
foreach ($columnRows as $columnRow) {
if (!isset($columnRow['Field'])) {
continue;
}
if ($columnRow['Field'] === 'id') {
continue;
}
$copyColumns[] = $columnRow['Field'];
}
if (!empty($copyColumns) && $tableExists('employee_profile')) {
$insertColumns = array_merge(array('employee_id'), $copyColumns);
$insertColumnsSql = array();
foreach ($insertColumns as $columnName) {
$insertColumnsSql[] = '`' . $columnName . '`';
}
$selectColumnsSql = array('`id` AS `employee_id`');
foreach ($copyColumns as $columnName) {
$selectColumnsSql[] = '`' . $columnName . '`';
}
$updateColumnsSql = array();
foreach ($copyColumns as $columnName) {
$updateColumnsSql[] = '`' . $columnName . '` = VALUES(`' . $columnName . '`)';
}
$syncSql = 'INSERT INTO `employee_profile` (' . implode(', ', $insertColumnsSql) . ')
SELECT ' . implode(', ', $selectColumnsSql) . '
FROM `employee_details`
ON DUPLICATE KEY UPDATE ' . implode(', ', $updateColumnsSql);
$conn->executeStatement($syncSql);
$stats['profile_rows_synced'] = (int)$conn->fetchOne('SELECT COUNT(*) FROM `employee_profile`');
}
$detailsRows = $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findBy(array(), array('id' => 'ASC'));
$employeeRepo = $em->getRepository('ApplicationBundle\\Entity\\Employee');
foreach ($detailsRows as $details) {
$employee = $employeeRepo->findOneBy(array('employeeId' => $details->getId()));
if (!$employee && method_exists($details, 'getUserId') && $details->getUserId()) {
$employee = $employeeRepo->findOneBy(array('userId' => $details->getUserId()));
}
$oldEmployeeId = null;
if ($employee) {
$oldEmployeeId = $employee->getEmployeeId();
} else {
$employee = new Employee();
$stats['created_employee_shells']++;
}
$changed = $this->populateEmployeeCoreFromDetails($employee, $details, $stats);
if (!$oldEmployeeId && method_exists($details, 'getUserId') && $details->getUserId() && method_exists($employee, 'setUserId')) {
$employee->setUserId($details->getUserId());
$changed = true;
}
if ($changed || !$oldEmployeeId) {
$em->persist($employee);
$em->flush();
$stats['employee_rows_synced']++;
} else {
$em->persist($employee);
}
$newEmployeeId = $employee->getEmployeeId();
if ((int)$details->getId() !== (int)$newEmployeeId && $tableExists('employee_profile')) {
$conn->executeStatement(
'UPDATE `employee_profile` SET `employee_id` = :new_id WHERE `employee_id` = :old_id',
array(
'new_id' => $newEmployeeId,
'old_id' => $details->getId(),
)
);
$stats['profile_rows_rekeyed']++;
}
}
return $stats;
}
// =========================================================================
// OWNER DASHBOARD SNAPSHOT
// Called by the central server's OwnerDashboardService::curlErpSnapshot().
// Returns a JSON snapshot of financials + KPIs for the company owner portal.
// No session required — this is a server-to-server call.
// =========================================================================
public function GetOwnerDashboardSnapshotAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type')
? $this->container->getParameter('system_type')
: '_ERP_';
if ($systemType === '_CENTRAL_') {
return new JsonResponse([
'success' => false,
'message' => 'Owner snapshot only available on ERP servers.',
], 400);
}
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
// ── Financial data ────────────────────────────────────────────────────
$revenueThisMonth = 0.0;
$revenueLast = 0.0;
$expensesThisMonth = 0.0;
$receivables = 0.0;
$payables = 0.0;
try {
$revenueThisMonth = (float)$conn->fetchOne("
SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
FROM sales_invoice
WHERE YEAR(sales_invoice_date) = YEAR(NOW())
AND MONTH(sales_invoice_date) = MONTH(NOW())
");
$revenueLast = (float)$conn->fetchOne("
SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
FROM sales_invoice
WHERE sales_invoice_date >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01')
AND sales_invoice_date < DATE_FORMAT(NOW(), '%Y-%m-01')
");
$expensesThisMonth = (float)$conn->fetchOne("
SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
FROM purchase_invoice
WHERE YEAR(invoice_date) = YEAR(NOW())
AND MONTH(invoice_date) = MONTH(NOW())
");
$receivables = (float)$conn->fetchOne("
SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0)
FROM sales_invoice
WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')
");
$payables = (float)$conn->fetchOne("
SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0)
FROM purchase_invoice
WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')
");
} catch (\Exception $e) {
// Tables may not exist on all ERP versions — skip gracefully
}
$profitThisMonth = $revenueThisMonth - $expensesThisMonth;
// Monthly revenue trend (last 6 months)
$monthlyTrend = [];
try {
$trendRows = $conn->fetchAllAssociative("
SELECT DATE_FORMAT(sales_invoice_date, '%Y-%m') AS month,
COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0) AS amount
FROM sales_invoice
WHERE sales_invoice_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
GROUP BY DATE_FORMAT(sales_invoice_date, '%Y-%m')
ORDER BY month ASC
");
foreach ($trendRows as $row) {
$monthlyTrend[] = ['month' => $row['month'], 'amount' => (float)$row['amount']];
}
} catch (\Exception $e) {
// Skip
}
// ── KPI data ──────────────────────────────────────────────────────────
$totalEmployees = 0;
$presentToday = 0;
$attendancePct = 0.0;
$tasksTotal = 0;
$tasksCompleted = 0;
$tasksOverdue = 0;
$taskRate = 0.0;
$openInvoices = 0;
$overdueInvoices = 0;
$totalInvoiceAmt = 0.0;
try {
$totalEmployees = (int)$conn->fetchOne(
"SELECT COUNT(*) FROM employee WHERE status = 1 OR status IS NULL"
);
} catch (\Exception $e) {
try {
$totalEmployees = (int)$conn->fetchOne(
"SELECT COUNT(*) FROM sys_user WHERE status = 1"
);
} catch (\Exception $ex) {
}
}
// Attendance: try common table names used by the ERP HR module
try {
$today = date('Y-m-d');
$presentToday = (int)$conn->fetchOne(
"SELECT COUNT(DISTINCT employee_id) FROM employee_daily_log
WHERE log_date = :d AND in_time IS NOT NULL",
['d' => $today]
);
} catch (\Exception $e) {
try {
$today = date('Y-m-d');
$presentToday = (int)$conn->fetchOne(
"SELECT COUNT(DISTINCT user_id) FROM user_activity_logs
WHERE DATE(created_at) = :d AND action_type = 'page_visit'",
['d' => $today]
);
} catch (\Exception $ex) {
}
}
if ($totalEmployees > 0) {
$attendancePct = round(($presentToday / $totalEmployees) * 100, 1);
}
// Tasks: try common task table names
try {
$tasksTotal = (int)$conn->fetchOne("SELECT COUNT(*) FROM task");
$tasksCompleted = (int)$conn->fetchOne("SELECT COUNT(*) FROM task WHERE status IN ('done','completed','closed')");
$tasksOverdue = (int)$conn->fetchOne("SELECT COUNT(*) FROM task WHERE due_date < NOW() AND status NOT IN ('done','completed','closed')");
} catch (\Exception $e) {
try {
$tasksTotal = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task");
$tasksCompleted = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task WHERE status IN ('done','completed','closed')");
$tasksOverdue = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task WHERE due_date < NOW() AND status NOT IN ('done','completed','closed')");
} catch (\Exception $ex) {
}
}
if ($tasksTotal > 0) {
$taskRate = round(($tasksCompleted / $tasksTotal) * 100, 1);
}
// Invoice KPIs
try {
$openInvoices = (int)$conn->fetchOne("SELECT COUNT(*) FROM sales_invoice WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')");
$overdueInvoices = (int)$conn->fetchOne("SELECT COUNT(*) FROM sales_invoice WHERE due_date < NOW() AND (payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid'))");
$totalInvoiceAmt = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM sales_invoice");
} catch (\Exception $e) {
}
// ── Recent activity ───────────────────────────────────────────────────
$recentActivity = [];
try {
$rows = $conn->fetchAllAssociative("
SELECT action_type AS action, route AS description, created_at AS at
FROM user_activity_logs
ORDER BY created_at DESC
LIMIT 10
");
foreach ($rows as $row) {
$recentActivity[] = [
'action' => $row['action'] ?? 'activity',
'description' => $row['description'] ?? '',
'at' => $row['at'] ?? '',
];
}
} catch (\Exception $e) {
}
return new JsonResponse([
'success' => true,
'fetched_at' => (new \DateTime())->format('c'),
'financials' => [
'revenue_this_month' => $revenueThisMonth,
'revenue_last_month' => $revenueLast,
'expenses_this_month' => $expensesThisMonth,
'profit_this_month' => $profitThisMonth,
'outstanding_receivables' => $receivables,
'outstanding_payables' => $payables,
'monthly_revenue_trend' => $monthlyTrend,
],
'kpis' => [
'total_employees' => $totalEmployees,
'present_today' => $presentToday,
'attendance_rate_percent' => $attendancePct,
'tasks_total' => $tasksTotal,
'tasks_completed' => $tasksCompleted,
'tasks_overdue' => $tasksOverdue,
'task_completion_rate_percent' => $taskRate,
'open_sales_invoices' => $openInvoices,
'overdue_sales_invoices' => $overdueInvoices,
'total_sales_invoices_amount' => $totalInvoiceAmt,
],
'alerts' => [],
'recent_activity' => $recentActivity,
]);
}
// =========================================================================
// CENTRAL SSO ENTRY POINT
// The central server redirects the company owner here after generating an
// SSO token. This action validates the token with the central server and
// auto-logs the user in to the ERP.
// =========================================================================
public function CentralSsoAction(Request $request)
{
$token = (string)$request->query->get('token', '');
$returnUrl = (string)$request->query->get('returnUrl', '');
if ($token === '') {
return $this->render('@Application/pages/error/generic_error.html.twig', [
'message' => 'Invalid SSO token.',
]);
}
// Ask the central server to validate the token
$centralBase = $this->container->hasParameter('central_server_url')
? rtrim($this->container->getParameter('central_server_url'), '/')
: '';
if ($centralBase === '') {
return $this->render('@Application/pages/error/generic_error.html.twig', [
'message' => 'Central server URL not configured on this ERP instance.',
]);
}
$validateUrl = $centralBase . '/my/sso/validate';
$body = http_build_query(['token' => $token]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $validateUrl,
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_TIMEOUT => 8,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_POSTFIELDS => $body,
]);
$raw = curl_exec($curl);
curl_close($curl);
if (!$raw) {
return $this->render('@Application/pages/error/generic_error.html.twig', [
'message' => 'Could not reach the central server for SSO validation.',
]);
}
$payload = json_decode($raw, true);
if (!is_array($payload) || empty($payload['success'])) {
return $this->render('@Application/pages/error/generic_error.html.twig', [
'message' => 'SSO token is invalid or has expired. Please try again.',
]);
}
$email = (string)($payload['email'] ?? '');
if ($email === '') {
return $this->render('@Application/pages/error/generic_error.html.twig', [
'message' => 'No email returned from SSO validation.',
]);
}
// Find the local user by email
$em = $this->getDoctrine()->getManager();
$conn = $em->getConnection();
$userRow = null;
try {
$userRow = $conn->fetchAssociative(
"SELECT * FROM sys_user WHERE email = :email AND status = 1 LIMIT 1",
['email' => $email]
);
} catch (\Exception $e) {
}
if (!$userRow) {
return $this->render('@Application/pages/error/generic_error.html.twig', [
'message' => 'No matching active user found in this ERP for email: ' . htmlspecialchars($email),
]);
}
// Auto-login: populate session exactly as the normal login flow does
$session = $request->getSession();
$session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_ID, $userRow['user_id'] ?? $userRow['id'] ?? 0);
$session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_NAME, $userRow['name'] ?? $payload['name'] ?? '');
$session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_TYPE, $userRow['user_type'] ?? 0);
$session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_COMPANY_ID, $userRow['user_company_id'] ?? $userRow['company_id'] ?? 0);
// Redirect to ERP dashboard or the requested returnUrl
if ($returnUrl !== '' && strpos($returnUrl, 'http') === 0) {
return $this->redirect($returnUrl);
}
return $this->redirectToRoute('central_landing');
}
}