src/ApplicationBundle/Controller/ApplicationManagementController.php line 4513

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\ApplicationBundle;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\ModuleConstant;
  6. use ApplicationBundle\Entity\Approval;
  7. use ApplicationBundle\Entity\Company;
  8. use ApplicationBundle\Entity\DocumentData;
  9. use ApplicationBundle\Entity\Employee;
  10. use ApplicationBundle\Entity\EmployeeDetails;
  11. use ApplicationBundle\Entity\SysModule;
  12. use ApplicationBundle\Entity\SysUser;
  13. use ApplicationBundle\Interfaces\LoginInterface;
  14. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  15. use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  16. use ApplicationBundle\Modules\Inventory\Inventory;
  17. use ApplicationBundle\Modules\System\MiscActions;
  18. use ApplicationBundle\Modules\System\System;
  19. use ApplicationBundle\Modules\User\Users;
  20. use CompanyGroupBundle\Entity\CompanyGroup;
  21. use CompanyGroupBundle\Entity\EmsSite;
  22. use CompanyGroupBundle\Entity\DeviceSensorData;
  23. use CompanyGroupBundle\Entity\DeviceSensorDataDay;
  24. use CompanyGroupBundle\Entity\DeviceSensorDataHour;
  25. use CompanyGroupBundle\Entity\DeviceSensorDataMonth;
  26. use CompanyGroupBundle\Entity\DeviceSensorDataWeek;
  27. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  28. use Doctrine\ORM\Tools\SchemaTool;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Symfony\Component\HttpFoundation\Response;
  32. use Symfony\Component\Routing\Generator\UrlGenerator;
  33. class ApplicationManagementController extends GenericController implements LoginInterface
  34. {
  35.     private function getCloudApiKey()
  36.     {
  37.         $configured '';
  38.         if ($this->container->hasParameter('cloud_api_key')) {
  39.             $configured trim((string)$this->container->getParameter('cloud_api_key'));
  40.         }
  41.         if ($configured === '') {
  42.             $configured trim((string)getenv('HONEYBEE_CLOUD_API_KEY'));
  43.         }
  44.         if ($configured === '') {
  45.             $configured 'dev-cloud-key';
  46.         }
  47.         return $configured;
  48.     }
  49.     private function jsonErrorResponse($statusCode$code$message, array $details = array())
  50.     {
  51.         return new JsonResponse(array(
  52.             'status' => 'error',
  53.             'error' => array(
  54.                 'code' => $code,
  55.                 'message' => $message,
  56.                 'details' => $details,
  57.             ),
  58.             'meta' => array(
  59.                 'schema_version' => '1.0',
  60.                 'correlation_id' => uniqid('corr_'true),
  61.             ),
  62.         ), $statusCode);
  63.     }
  64.     private function parseModuleIdList($moduleIdList)
  65.     {
  66.         if (is_array($moduleIdList)) {
  67.             $rawList $moduleIdList;
  68.         } else {
  69.             $moduleIdList trim((string)$moduleIdList);
  70.             if ($moduleIdList === '') {
  71.                 return array();
  72.             }
  73.             $decoded json_decode($moduleIdListtrue);
  74.             $rawList is_array($decoded) ? $decoded explode(','$moduleIdList);
  75.         }
  76.         $cleanList = array();
  77.         foreach ($rawList as $moduleId) {
  78.             $moduleId = (int)$moduleId;
  79.             if ($moduleId 0) {
  80.                 $cleanList[$moduleId] = $moduleId;
  81.             }
  82.         }
  83.         return array_values($cleanList);
  84.     }
  85.     private function normalizeEmsNumericValue($value)
  86.     {
  87.         if (is_bool($value) || is_array($value) || is_object($value) || $value === null) {
  88.             return null;
  89.         }
  90.         if (is_string($value)) {
  91.             $value trim($value);
  92.             if ($value === '') {
  93.                 return null;
  94.             }
  95.         }
  96.         if (!is_numeric($value)) {
  97.             return null;
  98.         }
  99.         $number = (float)$value;
  100.         return is_finite($number) ? $number null;
  101.     }
  102.     private function updateEmsAggregateValues(array $currentValues$numericValue)
  103.     {
  104.         $numericValue = (float)$numericValue;
  105.         $count = isset($currentValues[3]) && is_numeric($currentValues[3]) ? (int)$currentValues[3] : 0;
  106.         if ($count <= 0) {
  107.             return array($numericValue$numericValue$numericValue1);
  108.         }
  109.         $min = isset($currentValues[0]) && is_numeric($currentValues[0]) ? (float)$currentValues[0] : $numericValue;
  110.         $max = isset($currentValues[1]) && is_numeric($currentValues[1]) ? (float)$currentValues[1] : $numericValue;
  111.         $avg = isset($currentValues[2]) && is_numeric($currentValues[2]) ? (float)$currentValues[2] : $numericValue;
  112.         if ($numericValue $max) {
  113.             $max $numericValue;
  114.         }
  115.         if ($numericValue $min) {
  116.             $min $numericValue;
  117.         }
  118.         $avg = (($count $avg) + $numericValue) / ($count 1);
  119.         return array($min$max$avg$count 1);
  120.     }
  121.     private function mergeEmsAggregateValues(array $existingValues, array $newValues)
  122.     {
  123.         $newCount = isset($newValues[3]) && is_numeric($newValues[3]) ? (int)$newValues[3] : 0;
  124.         if ($newCount <= 0) {
  125.             return $existingValues;
  126.         }
  127.         $newMin $this->normalizeEmsNumericValue(isset($newValues[0]) ? $newValues[0] : null);
  128.         $newMax $this->normalizeEmsNumericValue(isset($newValues[1]) ? $newValues[1] : null);
  129.         $newAvg $this->normalizeEmsNumericValue(isset($newValues[2]) ? $newValues[2] : null);
  130.         if ($newMin === null || $newMax === null || $newAvg === null) {
  131.             return $existingValues;
  132.         }
  133.         $existingCount = isset($existingValues[3]) && is_numeric($existingValues[3]) ? (int)$existingValues[3] : 0;
  134.         if ($existingCount <= 0) {
  135.             return array($newMin$newMax$newAvg$newCount);
  136.         }
  137.         $existingMin $this->normalizeEmsNumericValue(isset($existingValues[0]) ? $existingValues[0] : null);
  138.         $existingMax $this->normalizeEmsNumericValue(isset($existingValues[1]) ? $existingValues[1] : null);
  139.         $existingAvg $this->normalizeEmsNumericValue(isset($existingValues[2]) ? $existingValues[2] : null);
  140.         if ($existingMin === null || $existingMax === null || $existingAvg === null) {
  141.             return array($newMin$newMax$newAvg$newCount);
  142.         }
  143.         $min min($existingMin$newMin);
  144.         $max max($existingMax$newMax);
  145.         $avg = (($existingCount $existingAvg) + ($newCount $newAvg)) / ($existingCount $newCount);
  146.         return array($min$max$avg$existingCount $newCount);
  147.     }
  148.     private function getDefaultEnabledCompanyModuleIds()
  149.     {
  150.         $moduleIds = array();
  151.         foreach (ModuleConstant::$moduleList as $module) {
  152.             if ((int)(isset($module['defaultEnabledForCompany']) ? $module['defaultEnabledForCompany'] : 0) === 1) {
  153.                 $moduleIds[] = (int)$module['id'];
  154.             }
  155.         }
  156.         return $moduleIds;
  157.     }
  158.     private function getCentralEnabledModuleIdsForApp($appId)
  159.     {
  160.         $appId = (int)$appId;
  161.         if ($appId <= 0) {
  162.             return array();
  163.         }
  164.         $urlToCall rtrim(GeneralConstant::HONEYBEE_CENTRAL_SERVER'/') . '/GetAppListFromCentralServer';
  165.         $curl curl_init();
  166.         curl_setopt_array($curl, array(
  167.             CURLOPT_RETURNTRANSFER => 1,
  168.             CURLOPT_URL => $urlToCall,
  169.             CURLOPT_CONNECTTIMEOUT => 10,
  170.             CURLOPT_SSL_VERIFYPEER => false,
  171.             CURLOPT_SSL_VERIFYHOST => false,
  172.             CURLOPT_HTTPHEADER => array(
  173.                 'Accept: application/json',
  174.             ),
  175.             CURLOPT_POSTFIELDS => http_build_query(array(
  176.                 'appId' => $appId,
  177.             )),
  178.         ));
  179.         $retData curl_exec($curl);
  180.         $errData curl_error($curl);
  181.         curl_close($curl);
  182.         if ($errData || !$retData) {
  183.             return array();
  184.         }
  185.         $response json_decode($retDatatrue);
  186.         if (!is_array($response)) {
  187.             return array();
  188.         }
  189.         foreach ($response as $entry) {
  190.             if (isset($entry['appId']) && (int)$entry['appId'] === $appId) {
  191.                 return $this->parseModuleIdList(isset($entry['enabledModuleIdList']) ? $entry['enabledModuleIdList'] : '');
  192.             }
  193.         }
  194.         return array();
  195.     }
  196.     private function getEnabledModuleIdsForCompanyRouteSync(array $companyData$systemType)
  197.     {
  198.         $enabledModuleIds = array();
  199.         if ($systemType !== '_CENTRAL_') {
  200.             $enabledModuleIds $this->getCentralEnabledModuleIdsForApp(isset($companyData['appId']) ? $companyData['appId'] : 0);
  201.         } elseif (isset($companyData['enabledModuleIdList'])) {
  202.             $enabledModuleIds $this->parseModuleIdList($companyData['enabledModuleIdList']);
  203.         }
  204.         if (empty($enabledModuleIds)) {
  205.             $enabledModuleIds $this->getDefaultEnabledCompanyModuleIds();
  206.         }
  207.         return $enabledModuleIds;
  208.     }
  209.     private function filterModuleRoutesForCompany(array $enabledModuleIds)
  210.     {
  211.         $enabledLookup array_fill_keys(array_map('intval'$enabledModuleIds), true);
  212.         $routeList = array();
  213.         foreach (ModuleConstant::$moduleList as $module) {
  214.             $moduleId = (int)$module['id'];
  215.             if (isset($enabledLookup[$moduleId])) {
  216.                 $routeList[] = $module;
  217.             }
  218.         }
  219.         return $routeList;
  220.     }
  221.     private function ensureCloudImportTables($em_goc)
  222.     {
  223.         $conn $em_goc->getConnection();
  224.         if (strtolower($conn->getDatabasePlatform()->getName()) !== 'mysql') {
  225.             return;
  226.         }
  227.         $conn->executeStatement('CREATE TABLE IF NOT EXISTS cloud_site_bundle_import_ledger (
  228.             id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  229.             idempotency_key VARCHAR(255) NOT NULL,
  230.             bundle_hash VARCHAR(64) NOT NULL,
  231.             site_uid VARCHAR(255) NOT NULL,
  232.             source_system VARCHAR(64) NOT NULL,
  233.             correlation_id VARCHAR(255) NULL,
  234.             status VARCHAR(32) NOT NULL DEFAULT \'processing\',
  235.             request_json LONGTEXT NOT NULL,
  236.             response_json LONGTEXT NULL,
  237.             created_at DATETIME NOT NULL,
  238.             updated_at DATETIME NOT NULL,
  239.             PRIMARY KEY(id),
  240.             UNIQUE KEY uniq_cloud_site_bundle_import_key (idempotency_key)
  241.         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
  242.         $conn->executeStatement('CREATE TABLE IF NOT EXISTS cloud_site_bundle_entity (
  243.             id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  244.             site_uid VARCHAR(255) NOT NULL,
  245.             entity_type VARCHAR(64) NOT NULL,
  246.             entity_uid VARCHAR(255) NOT NULL,
  247.             bundle_hash VARCHAR(64) NOT NULL,
  248.             correlation_id VARCHAR(255) NULL,
  249.             payload_json LONGTEXT NOT NULL,
  250.             created_at DATETIME NOT NULL,
  251.             updated_at DATETIME NOT NULL,
  252.             PRIMARY KEY(id),
  253.             UNIQUE KEY uniq_cloud_site_bundle_entity (site_uid, entity_type, entity_uid)
  254.         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
  255.     }
  256.     private function ensureCloudHeartbeatTable($em_goc)
  257.     {
  258.         $conn $em_goc->getConnection();
  259.         if (strtolower($conn->getDatabasePlatform()->getName()) !== 'mysql') {
  260.             return;
  261.         }
  262.         $conn->executeStatement('CREATE TABLE IF NOT EXISTS cloud_site_heartbeat (
  263.             id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  264.             site_uid VARCHAR(255) NOT NULL,
  265.             source_system VARCHAR(64) NOT NULL DEFAULT \'honeycore\',
  266.             controller_serial VARCHAR(255) NULL,
  267.             payload_json LONGTEXT NULL,
  268.             created_at DATETIME NOT NULL,
  269.             last_seen_at DATETIME NOT NULL,
  270.             PRIMARY KEY(id),
  271.             UNIQUE KEY uniq_cloud_site_heartbeat_site (site_uid)
  272.         ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
  273.     }
  274.     private function recordCloudSiteHeartbeat($em_goc$siteUid$sourceSystem 'honeycore'$controllerSerial '', array $payload = array())
  275.     {
  276.         $siteUid trim((string)$siteUid);
  277.         if ($siteUid === '') {
  278.             return false;
  279.         }
  280.         $now = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
  281.         $this->ensureCloudHeartbeatTable($em_goc);
  282.         $em_goc->getConnection()->executeStatement(
  283.             'INSERT INTO cloud_site_heartbeat
  284.                 (site_uid, source_system, controller_serial, payload_json, created_at, last_seen_at)
  285.              VALUES
  286.                 (:site_uid, :source_system, :controller_serial, :payload_json, :created_at, :last_seen_at)
  287.              ON DUPLICATE KEY UPDATE
  288.                 source_system = VALUES(source_system),
  289.                 controller_serial = VALUES(controller_serial),
  290.                 payload_json = VALUES(payload_json),
  291.                 last_seen_at = VALUES(last_seen_at)',
  292.             array(
  293.                 'site_uid' => $siteUid,
  294.                 'source_system' => (string)$sourceSystem,
  295.                 'controller_serial' => (string)$controllerSerial,
  296.                 'payload_json' => json_encode($payloadJSON_UNESCAPED_SLASHES JSON_UNESCAPED_UNICODE),
  297.                 'created_at' => $now,
  298.                 'last_seen_at' => $now,
  299.             )
  300.         );
  301.         return $now;
  302.     }
  303.     private function upsertCloudBundleEntity($em_goc$siteUid$entityType$entityUid, array $payload$bundleHash$correlationId)
  304.     {
  305.         $conn $em_goc->getConnection();
  306.         $now = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
  307.         $conn->executeStatement(
  308.             'INSERT INTO cloud_site_bundle_entity
  309.                 (site_uid, entity_type, entity_uid, bundle_hash, correlation_id, payload_json, created_at, updated_at)
  310.              VALUES
  311.                 (:site_uid, :entity_type, :entity_uid, :bundle_hash, :correlation_id, :payload_json, :created_at, :updated_at)
  312.              ON DUPLICATE KEY UPDATE
  313.                 bundle_hash = VALUES(bundle_hash),
  314.                 correlation_id = VALUES(correlation_id),
  315.                 payload_json = VALUES(payload_json),
  316.                 updated_at = VALUES(updated_at)',
  317.             array(
  318.                 'site_uid' => (string)$siteUid,
  319.                 'entity_type' => (string)$entityType,
  320.                 'entity_uid' => (string)$entityUid,
  321.                 'bundle_hash' => (string)$bundleHash,
  322.                 'correlation_id' => (string)$correlationId,
  323.                 'payload_json' => json_encode($payloadJSON_UNESCAPED_SLASHES JSON_UNESCAPED_UNICODE),
  324.                 'created_at' => $now,
  325.                 'updated_at' => $now,
  326.             )
  327.         );
  328.     }
  329.     private function getInfluxSettings()
  330.     {
  331.         $getEnv = function ($key) {
  332.             $value getenv($key);
  333.             return $value === false '' trim((string)$value);
  334.         };
  335.         return array(
  336.             'enabled' => $getEnv('HONEYBEE_INFLUX_WRITE_URL') !== '' && $getEnv('HONEYBEE_INFLUX_BUCKET') !== '',
  337.             'write_url' => $getEnv('HONEYBEE_INFLUX_WRITE_URL'),
  338.             'bucket' => $getEnv('HONEYBEE_INFLUX_BUCKET'),
  339.             'org' => $getEnv('HONEYBEE_INFLUX_ORG'),
  340.             'token' => $getEnv('HONEYBEE_INFLUX_TOKEN'),
  341.             'measurement' => $getEnv('HONEYBEE_INFLUX_MEASUREMENT') ?: 'telemetry',
  342.             'query_url' => $getEnv('HONEYBEE_INFLUX_QUERY_URL'),
  343.             'timeout' => (int)($getEnv('HONEYBEE_INFLUX_TIMEOUT') ?: 5),
  344.         );
  345.     }
  346.     private function escapeInfluxTag($value)
  347.     {
  348.         return str_replace(array('\\'' '','), array('\\\\''\ ''\,'), (string)$value);
  349.     }
  350.     private function escapeInfluxFieldString($value)
  351.     {
  352.         return '"' str_replace(array('\\''"'), array('\\\\''\"'), (string)$value) . '"';
  353.     }
  354.     private function httpRequest($url$method, array $headers$body$timeout 5)
  355.     {
  356.         if (function_exists('curl_init')) {
  357.             $ch curl_init($url);
  358.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  359.             curl_setopt($chCURLOPT_CUSTOMREQUEST$method);
  360.             curl_setopt($chCURLOPT_TIMEOUT$timeout);
  361.             curl_setopt($chCURLOPT_HTTPHEADER$headers);
  362.             if ($body !== null) {
  363.                 curl_setopt($chCURLOPT_POSTFIELDS$body);
  364.             }
  365.             $responseBody curl_exec($ch);
  366.             $status = (int)curl_getinfo($chCURLINFO_HTTP_CODE);
  367.             $error curl_error($ch);
  368.             curl_close($ch);
  369.             return array(
  370.                 'ok' => $status >= 200 && $status 300,
  371.                 'status' => $status,
  372.                 'body' => $responseBody,
  373.                 'error' => $error,
  374.             );
  375.         }
  376.         $context stream_context_create(array(
  377.             'http' => array(
  378.                 'method' => $method,
  379.                 'header' => implode("\r\n"$headers),
  380.                 'content' => $body,
  381.                 'timeout' => $timeout,
  382.             ),
  383.         ));
  384.         $responseBody = @file_get_contents($urlfalse$context);
  385.         $status 0;
  386.         if (isset($http_response_header) && is_array($http_response_header)) {
  387.             foreach ($http_response_header as $headerLine) {
  388.                 if (preg_match('/^HTTP\/\S+\s+(\d+)/'$headerLine$matches)) {
  389.                     $status = (int)$matches[1];
  390.                     break;
  391.                 }
  392.             }
  393.         }
  394.         return array(
  395.             'ok' => $status >= 200 && $status 300,
  396.             'status' => $status,
  397.             'body' => $responseBody,
  398.             'error' => $responseBody === false 'stream_request_failed' '',
  399.         );
  400.     }
  401.     private function toInfluxFieldValue($value)
  402.     {
  403.         if (is_bool($value)) {
  404.             return $value 'true' 'false';
  405.         }
  406.         if (is_int($value)) {
  407.             return $value 'i';
  408.         }
  409.         if (is_float($value) || is_numeric($value)) {
  410.             return (string)($value);
  411.         }
  412.         if (is_null($value)) {
  413.             return '""';
  414.         }
  415.         return $this->escapeInfluxFieldString($value);
  416.     }
  417.     private function writeInstantTelemetryToInflux(array $record$siteUid, array $dashboardContext$bundleHash$correlationId)
  418.     {
  419.         $settings $this->getInfluxSettings();
  420.         if (empty($settings['enabled'])) {
  421.             return false;
  422.         }
  423.         $timestamp = new \DateTime(isset($record['timestamp']) ? $record['timestamp'] : 'now');
  424.         $timestamp->setTimezone(new \DateTimeZone('+0000'));
  425.         $timestampNs = (string)((int)$timestamp->format('U') * 1000000000);
  426.         $tags = array(
  427.             'site_uid' => $siteUid,
  428.             'device_uid' => (string)($record['device_uid'] ?? $record['device_id'] ?? ''),
  429.             'point_uid' => (string)($record['point_uid'] ?? ''),
  430.             'point_code' => (string)($record['point_code'] ?? $record['identifier'] ?? ''),
  431.             'source' => (string)($record['source'] ?? 'honeycore'),
  432.         );
  433.         if (!empty($dashboardContext['site_type'])) {
  434.             $tags['site_type'] = (string)$dashboardContext['site_type'];
  435.         }
  436.         if (!empty($record['unit'])) {
  437.             $tags['unit'] = (string)$record['unit'];
  438.         }
  439.         $tagParts = array();
  440.         foreach ($tags as $tagKey => $tagValue) {
  441.             if ($tagValue === '') {
  442.                 continue;
  443.             }
  444.             $tagParts[] = $this->escapeInfluxTag($tagKey) . '=' $this->escapeInfluxTag($tagValue);
  445.         }
  446.         $fields = array(
  447.             'value' => $this->toInfluxFieldValue($record['value'] ?? null),
  448.             'record_id' => $this->escapeInfluxFieldString($record['record_id'] ?? ''),
  449.             'alias' => $this->escapeInfluxFieldString($record['alias'] ?? ''),
  450.             'schema_version' => $this->escapeInfluxFieldString($record['schema_version'] ?? '1.0'),
  451.             'bundle_hash' => $this->escapeInfluxFieldString($bundleHash),
  452.             'correlation_id' => $this->escapeInfluxFieldString($record['correlation_id'] ?? $correlationId),
  453.         );
  454.         if (isset($record['quality'])) {
  455.             $fields['quality'] = $this->escapeInfluxFieldString((string)$record['quality']);
  456.         }
  457.         if (isset($record['raw_value']) && is_scalar($record['raw_value'])) {
  458.             $fields['raw_value'] = $this->escapeInfluxFieldString((string)$record['raw_value']);
  459.         }
  460.         $line $settings['measurement'];
  461.         if (!empty($tagParts)) {
  462.             $line .= ',' implode(','$tagParts);
  463.         }
  464.         $line .= ' ';
  465.         $fieldParts = array();
  466.         foreach ($fields as $fieldKey => $fieldValue) {
  467.             $fieldParts[] = $fieldKey '=' $fieldValue;
  468.         }
  469.         $line .= implode(','$fieldParts) . ' ' $timestampNs;
  470.         $writeUrl $settings['write_url'];
  471.         $separator strpos($writeUrl'?') === false '?' '&';
  472.         $writeUrl .= $separator http_build_query(array(
  473.                 'bucket' => $settings['bucket'],
  474.                 'org' => $settings['org'],
  475.                 'precision' => 'ns',
  476.             ));
  477.         $headers = array(
  478.             'Content-Type: text/plain; charset=utf-8',
  479.         );
  480.         if ($settings['token'] !== '') {
  481.             $headers[] = 'Authorization: Token ' $settings['token'];
  482.         }
  483.         $response $this->httpRequest($writeUrl'POST'$headers$line$settings['timeout']);
  484.         if (!$response['ok']) {
  485.             return false;
  486.         }
  487.         return true;
  488.     }
  489.     private function upsertCloudTelemetry($em_goc, array $record$siteUid, array $dashboardContext$bundleHash$correlationId)
  490.     {
  491.         if ($this->writeInstantTelemetryToInflux($record$siteUid$dashboardContext$bundleHash$correlationId)) {
  492.             return;
  493.         }
  494.         $siteIdInt = (int)$siteUid;
  495.         if ($siteIdInt <= 0) {
  496.             return;
  497.         }
  498.         $recordId = (string)($record['record_id'] ?? '');
  499.         if ($recordId === '') {
  500.             return;
  501.         }
  502.         $timestamp = new \DateTime(isset($record['timestamp']) ? $record['timestamp'] : 'now');
  503.         $timestamp->setTimezone(new \DateTimeZone('+0000'));
  504.         $entry $em_goc->getRepository(DeviceSensorData::class)->findOneBy(array(
  505.             'recordId' => $recordId,
  506.         ));
  507.         if (!$entry) {
  508.             $entry = new DeviceSensorData();
  509.             $entry->setRecordId($recordId);
  510.             $entry->setSiteId($siteIdInt);
  511.         }
  512.         $entry->setDeviceId((string)($record['device_uid'] ?? $record['device_id'] ?? ''));
  513.         $entry->setIdentifier((string)($record['point_code'] ?? $record['identifier'] ?? ''));
  514.         $entry->setAlias((string)($record['alias'] ?? ''));
  515.         $entry->setValue(is_scalar($record['value'] ?? null) ? (string)$record['value'] : json_encode($record['value'] ?? null));
  516.         $entry->setTimeStamp($timestamp);
  517.         $entry->setTimeStampTs((int)$timestamp->format('U'));
  518.         $em_goc->persist($entry);
  519.         $em_goc->flush();
  520.     }
  521.     private function normalizeCloudSiteText($value)
  522.     {
  523.         return preg_replace('/[^a-z0-9]+/'''strtolower((string)$value));
  524.     }
  525.     private function bundlePayloadMatchesSite(array $payload, array $dashboardContext$site)
  526.     {
  527.         if (!$site) {
  528.             return false;
  529.         }
  530.         $siteName method_exists($site'getSiteName') ? $this->normalizeCloudSiteText($site->getSiteName()) : '';
  531.         $siteLocation '';
  532.         if (method_exists($site'getSiteLocation')) {
  533.             $siteLocation $site->getSiteLocation();
  534.         }
  535.         if ($siteLocation === '' && method_exists($site'getAddress')) {
  536.             $siteLocation $site->getAddress();
  537.         }
  538.         $siteLocation $this->normalizeCloudSiteText($siteLocation);
  539.         $payloadNames = array(
  540.             $payload['site_name'] ?? null,
  541.             $payload['name'] ?? null,
  542.             $payload['site'] ?? null,
  543.             $dashboardContext['site_name'] ?? null,
  544.             $dashboardContext['name'] ?? null,
  545.         );
  546.         foreach ($payloadNames as $payloadName) {
  547.             $normalized $this->normalizeCloudSiteText($payloadName);
  548.             if ($normalized !== '' && $siteName !== '' && $normalized === $siteName) {
  549.                 return true;
  550.             }
  551.         }
  552.         $payloadLocation $this->normalizeCloudSiteText(
  553.             $payload['location'] ?? $payload['address'] ?? $dashboardContext['location'] ?? $dashboardContext['address'] ?? ''
  554.         );
  555.         return $payloadLocation !== '' && $siteLocation !== '' && $payloadLocation === $siteLocation;
  556.     }
  557.     private function resolveCloudBundleSiteEntity($em_goc, array $sitePayload, array $dashboardContext, array $source$routeSiteId 0)
  558.     {
  559.         $repo $em_goc->getRepository(EmsSite::class);
  560.         if ((int)$routeSiteId 0) {
  561.             $site $repo->find((int)$routeSiteId);
  562.             if ($site) {
  563.                 return $site;
  564.             }
  565.         }
  566.         $explicitCloudSiteId $source['cloud_site_id'] ?? $source['cloudSiteId'] ?? $sitePayload['cloud_site_id'] ?? $dashboardContext['cloud_site_id'] ?? null;
  567.         if ($explicitCloudSiteId !== null && ctype_digit((string)$explicitCloudSiteId)) {
  568.             $site $repo->find((int)$explicitCloudSiteId);
  569.             if ($site) {
  570.                 return $site;
  571.             }
  572.         }
  573.         $sites $repo->createQueryBuilder('s')
  574.             ->orderBy('s.id''ASC')
  575.             ->getQuery()
  576.             ->getResult();
  577.         foreach ($sites as $site) {
  578.             if ($this->bundlePayloadMatchesSite($sitePayload$dashboardContext$site)) {
  579.                 return $site;
  580.             }
  581.         }
  582.         return null;
  583.     }
  584.     public function CloudSiteBundleImportAction(Request $request$id 0)
  585.     {
  586.         $em_goc $this->getDoctrine()->getManager('company_group');
  587.         $this->ensureCloudImportTables($em_goc);
  588.         $expectedApiKey $this->getCloudApiKey();
  589.         $providedApiKey trim((string)$request->headers->get('X-API-Key'''));
  590.         if ($providedApiKey === '' || !hash_equals($expectedApiKey$providedApiKey)) {
  591.             return $this->jsonErrorResponse(401'invalid_api_key''Invalid or missing cloud API key.');
  592.         }
  593.         $idempotencyKey trim((string)$request->headers->get('Idempotency-Key'''));
  594.         if ($idempotencyKey === '') {
  595.             return $this->jsonErrorResponse(400'missing_idempotency_key''Idempotency-Key header is required.');
  596.         }
  597.         $bundle json_decode($request->getContent(), true);
  598.         if (!is_array($bundle)) {
  599.             return $this->jsonErrorResponse(400'invalid_json''Request body must be valid JSON.');
  600.         }
  601.         if (($bundle['schema_version'] ?? '') !== '1.0') {
  602.             return $this->jsonErrorResponse(400'invalid_schema_version''schema_version must be 1.0.');
  603.         }
  604.         if (($bundle['package_type'] ?? '') !== 'site_bundle') {
  605.             return $this->jsonErrorResponse(400'invalid_package_type''package_type must be site_bundle.');
  606.         }
  607.         $source = isset($bundle['source']) && is_array($bundle['source']) ? $bundle['source'] : array();
  608.         if (($source['system'] ?? '') !== 'honeycore') {
  609.             return $this->jsonErrorResponse(400'invalid_source_system''source.system must be honeycore.');
  610.         }
  611.         $siteUid = (string)($source['site_uid'] ?? '');
  612.         if ($siteUid === '') {
  613.             return $this->jsonErrorResponse(400'missing_site_uid''source.site_uid is required.');
  614.         }
  615.         $this->recordCloudSiteHeartbeat(
  616.             $em_goc,
  617.             $siteUid,
  618.             (string)($source['system'] ?? 'honeycore'),
  619.             (string)($source['controller_serial'] ?? $source['controllerSerial'] ?? ''),
  620.             array('source' => $source'package_type' => $bundle['package_type'] ?? '''schema_version' => $bundle['schema_version'] ?? '')
  621.         );
  622.         $bundleHash hash('sha256'json_encode($bundleJSON_UNESCAPED_SLASHES JSON_UNESCAPED_UNICODE));
  623.         $correlationId = (string)($source['correlation_id'] ?? uniqid('corr_'true));
  624.         $conn $em_goc->getConnection();
  625.         $existingLedger $conn->fetchAssociative(
  626.             'SELECT response_json FROM cloud_site_bundle_import_ledger WHERE idempotency_key = :idempotency_key',
  627.             array('idempotency_key' => $idempotencyKey)
  628.         );
  629.         if ($existingLedger && !empty($existingLedger['response_json'])) {
  630.             return new JsonResponse(json_decode($existingLedger['response_json'], true), 200);
  631.         }
  632.         $now = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
  633.         $conn->executeStatement(
  634.             'INSERT INTO cloud_site_bundle_import_ledger
  635.                 (idempotency_key, bundle_hash, site_uid, source_system, correlation_id, status, request_json, created_at, updated_at)
  636.              VALUES
  637.                 (:idempotency_key, :bundle_hash, :site_uid, :source_system, :correlation_id, :status, :request_json, :created_at, :updated_at)
  638.              ON DUPLICATE KEY UPDATE
  639.                 bundle_hash = VALUES(bundle_hash),
  640.                 site_uid = VALUES(site_uid),
  641.                 source_system = VALUES(source_system),
  642.                 correlation_id = VALUES(correlation_id),
  643.                 status = VALUES(status),
  644.                 request_json = VALUES(request_json),
  645.                 updated_at = VALUES(updated_at)',
  646.             array(
  647.                 'idempotency_key' => $idempotencyKey,
  648.                 'bundle_hash' => $bundleHash,
  649.                 'site_uid' => $siteUid,
  650.                 'source_system' => 'honeycore',
  651.                 'correlation_id' => $correlationId,
  652.                 'status' => 'processing',
  653.                 'request_json' => json_encode($bundleJSON_UNESCAPED_SLASHES JSON_UNESCAPED_UNICODE),
  654.                 'created_at' => $now,
  655.                 'updated_at' => $now,
  656.             )
  657.         );
  658.         $sitePayload = isset($bundle['site']) && is_array($bundle['site']) ? $bundle['site'] : array();
  659.         $dashboardContext = isset($bundle['dashboard_context']) && is_array($bundle['dashboard_context']) ? $bundle['dashboard_context'] : array();
  660.         $siteEntity $this->resolveCloudBundleSiteEntity($em_goc$sitePayload$dashboardContext$source$id);
  661.         $linkedSiteId $siteEntity $siteEntity->getId() : null;
  662.         if ($siteEntity) {
  663.             if (method_exists($siteEntity'setSiteType')) {
  664.                 $siteEntity->setSiteType((string)($sitePayload['site_type'] ?? $dashboardContext['site_type'] ?? $bundle['site_type'] ?? 'SOPHIA'));
  665.             }
  666.             if (method_exists($siteEntity'setSiteName') && isset($sitePayload['site_name'])) {
  667.                 $siteEntity->setSiteName((string)$sitePayload['site_name']);
  668.             }
  669.             if (method_exists($siteEntity'setSiteLocation') && isset($sitePayload['address'])) {
  670.                 $siteEntity->setSiteLocation((string)$sitePayload['address']);
  671.             }
  672.             if (method_exists($siteEntity'setSiteNote') && isset($sitePayload['description'])) {
  673.                 $siteEntity->setSiteNote((string)$sitePayload['description']);
  674.             }
  675.             if (method_exists($siteEntity'setContactPerson') && isset($sitePayload['operator'])) {
  676.                 $siteEntity->setContactPerson((string)$sitePayload['operator']);
  677.             }
  678.             if (method_exists($siteEntity'setSiteIcon') && isset($sitePayload['image_url'])) {
  679.                 $siteEntity->setSiteIcon((string)$sitePayload['image_url']);
  680.             }
  681.             $em_goc->persist($siteEntity);
  682.             $em_goc->flush();
  683.         }
  684.         $this->upsertCloudBundleEntity($em_goc$siteUid'site'$siteUid$sitePayload$bundleHash$correlationId);
  685.         foreach (array('system_mode''dashboard_context') as $entityType) {
  686.             if (isset($bundle[$entityType]) && is_array($bundle[$entityType])) {
  687.                 $this->upsertCloudBundleEntity($em_goc$siteUid$entityType$siteUid$bundle[$entityType], $bundleHash$correlationId);
  688.             }
  689.         }
  690.         foreach (array('devices''points''constraints''control_actions') as $entityType) {
  691.             if (empty($bundle[$entityType]) || !is_array($bundle[$entityType])) {
  692.                 continue;
  693.             }
  694.             foreach ($bundle[$entityType] as $row) {
  695.                 if (!is_array($row)) {
  696.                     continue;
  697.                 }
  698.                 $entityUid '';
  699.                 if ($entityType === 'devices') {
  700.                     $entityUid = (string)($row['device_uid'] ?? '');
  701.                 } elseif ($entityType === 'points') {
  702.                     $entityUid = (string)($row['point_uid'] ?? '');
  703.                 } elseif ($entityType === 'constraints') {
  704.                     $entityUid = (string)($row['constraint_uid'] ?? '');
  705.                 } elseif ($entityType === 'control_actions') {
  706.                     $entityUid = (string)($row['action_id'] ?? '');
  707.                 }
  708.                 if ($entityUid === '') {
  709.                     $entityUid md5(json_encode($row));
  710.                 }
  711.                 $this->upsertCloudBundleEntity($em_goc$siteUid$entityType$entityUid$row$bundleHash$correlationId);
  712.             }
  713.         }
  714.         $telemetryCount 0;
  715.         if (!empty($bundle['telemetry']) && is_array($bundle['telemetry'])) {
  716.             foreach ($bundle['telemetry'] as $record) {
  717.                 if (!is_array($record)) {
  718.                     continue;
  719.                 }
  720.                 $this->upsertCloudTelemetry($em_goc$record$siteUid$dashboardContext$bundleHash$correlationId);
  721.                 $telemetryCount++;
  722.             }
  723.         }
  724.         $responseEnvelope = array(
  725.             'status' => 'ok',
  726.             'data' => array(
  727.                 'site_uid' => $siteUid,
  728.                 'site_id' => $linkedSiteId,
  729.                 'linked_site_id' => $linkedSiteId,
  730.                 'site_link_status' => $linkedSiteId 'linked_existing_site' 'unlinked_bundle_only',
  731.                 'telemetry_count' => $telemetryCount,
  732.                 'entity_count' => isset($bundle['devices']) && is_array($bundle['devices']) ? count($bundle['devices']) : 0,
  733.             ),
  734.             'meta' => array(
  735.                 'schema_version' => '1.0',
  736.                 'correlation_id' => $correlationId,
  737.                 'idempotency_key' => $idempotencyKey,
  738.                 'bundle_hash' => $bundleHash,
  739.             ),
  740.             'error' => null,
  741.         );
  742.         $conn->executeStatement(
  743.             'UPDATE cloud_site_bundle_import_ledger
  744.              SET status = :status, response_json = :response_json, updated_at = :updated_at
  745.              WHERE idempotency_key = :idempotency_key',
  746.             array(
  747.                 'status' => 'ok',
  748.                 'response_json' => json_encode($responseEnvelopeJSON_UNESCAPED_SLASHES JSON_UNESCAPED_UNICODE),
  749.                 'updated_at' => (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s'),
  750.                 'idempotency_key' => $idempotencyKey,
  751.             )
  752.         );
  753.         return new JsonResponse($responseEnvelope200);
  754.     }
  755.     public function DeviceDataHeartBeatAction(Request $request$id 0)
  756.     {
  757.         $em_goc $this->getDoctrine()->getManager('company_group');
  758.         $content $request->getContent(); // raw body string
  759.         $data json_decode($contenttrue); // decode JSON if needed
  760.         // Example: access fields
  761.         if ($data == null$data = [];
  762.         $emsDataSegregation GeneralConstant::$emsDataSegregation;
  763.         $segregatedData = [];
  764.         $segregatedDataByDeviceId = [];
  765.         $source = isset($data['source']) && is_array($data['source']) ? $data['source'] : array();
  766.         $siteId = (string)($data['siteId'] ?? $data['site_id'] ?? $data['site_uid'] ?? $source['site_uid'] ?? '');
  767.         $siteId trim($siteId);
  768.         if ($siteId === '') {
  769.             return new JsonResponse(array(
  770.                 'success' => false,
  771.                 'error' => 'missing_site_id',
  772.                 'message' => 'Heartbeat payload must include siteId, site_id, site_uid, or source.site_uid.',
  773.             ), 400);
  774.         }
  775.         $controllerSerial = (string)($data['controllerSerial'] ?? $data['controller_serial'] ?? $source['controller_serial'] ?? '');
  776.         $heartbeatAt $this->recordCloudSiteHeartbeat(
  777.             $em_goc,
  778.             $siteId,
  779.             (string)($source['system'] ?? $data['source_system'] ?? 'honeycore'),
  780.             $controllerSerial,
  781.             $data
  782.         );
  783.         //first create a new array or records which will then be modified and or created
  784.         return new JsonResponse(array(
  785.             'success' => true,
  786.             'site_uid' => $siteId,
  787.             'heartbeat_at' => $heartbeatAt,
  788.         ));
  789.     }
  790.     public function DeviceDataEmsIngestAction(Request $request$id 0)
  791.     {
  792.         $em_goc $this->getDoctrine()->getManager('company_group');
  793.         $content $request->getContent(); // raw body string
  794.         $data json_decode($contenttrue); // decode JSON if needed
  795.         // Example: access fields
  796.         if ($data == null$data = [];
  797.         $emsDataSegregation GeneralConstant::$emsDataSegregation;
  798.         $segregatedData = [];
  799.         $segregatedDataByDeviceId = [];
  800.         $siteId = (isset($data['siteId'])) ? $data['siteId'] : 0;
  801.         if ((int)$siteId 0) {
  802.             $this->recordCloudSiteHeartbeat(
  803.                 $em_goc,
  804.                 $siteId,
  805.                 (string)($data['source_system'] ?? 'honeycore_ingest'),
  806.                 (string)($data['controllerSerial'] ?? $data['controller_serial'] ?? ''),
  807.                 array('source' => 'ems_ingest''records_count' => count($data['records'] ?? array()))
  808.             );
  809.         }
  810.         //first create a new array or records which will then be modified and or created
  811.         $modifiedData = array();
  812.         $firstTs 0;
  813.         $lastTs 0;
  814.         $siteIds = [$siteId];
  815. //        $defaultData = [
  816. //            'marker' => '',
  817. //            'ts' => '',
  818. //            'data' => []
  819. //        ];
  820.         $defaultValues = [0000];
  821.         $skippedNonNumeric 0;
  822.         $skippedInvalidRecords 0;
  823.         if (isset($data['records']))
  824.             foreach ($data['records'] as $key => $value) {
  825.                 if (!is_array($value) || !isset($value['timestamp'], $value['device_id'], $value['identifier'])) {
  826.                     $skippedInvalidRecords++;
  827.                     continue;
  828.                 }
  829.                 $identifier trim((string)$value['identifier']);
  830.                 $deviceId trim((string)$value['device_id']);
  831.                 if ($identifier === '' || $deviceId === '') {
  832.                     $skippedInvalidRecords++;
  833.                     continue;
  834.                 }
  835.                 $numericValue $this->normalizeEmsNumericValue(isset($value['value']) ? $value['value'] : null);
  836.                 if ($numericValue === null) {
  837.                     $skippedNonNumeric++;
  838.                     continue;
  839.                 }
  840.                 $timeStampDt = new \DateTime($value['timestamp']);
  841.                 $timeStampDt->setTimezone(new \DateTimeZone('+0000'));
  842.                 $timeStampTs $timeStampDt->format('U');
  843.                 if ($timeStampTs $lastTs$lastTs $timeStampTs;
  844.                 if ($timeStampTs $firstTs || $firstTs == 0$firstTs $timeStampTs;
  845.                 if (!in_array($siteId$siteIds)) $siteIds[] = $siteId;
  846.                 foreach ($emsDataSegregation as $key2 => $dataSegregation) {
  847.                     if (!isset($segregatedDataByDeviceId[$deviceId]))
  848.                         $segregatedDataByDeviceId[$deviceId] = [];
  849.                     if (!isset($segregatedDataByDeviceId[$deviceId][$key2]))
  850.                         $segregatedDataByDeviceId[$deviceId][$key2] = [];
  851.                     $segregatedData $segregatedDataByDeviceId[$deviceId];
  852. //                    $segregatedData[$key2] = [
  853. ////                             '20250406':   [
  854. ////                                    'marker' => '',
  855. ////                                    'ts' => '',
  856. ////                                    'data' => ['Battery_power' => [0, 2, 1, 4]]
  857. ////                                ]
  858. //                        ];
  859. //                    [{'_identifier_':{min,max,avg,count}}]
  860.                     $markerForThis $timeStampDt->format($dataSegregation['markerStr']);
  861.                     if (isset($dataSegregation['isWeek'])) {
  862.                         $startDtForThis = new \DateTime();
  863.                         $startDtForThis->setISODate($timeStampDt->format('Y'), $timeStampDt->format('W'));
  864.                     } else {
  865.                         $startDtForThis = new \DateTime($timeStampDt->format($dataSegregation['startTsFormat']));
  866.                     }
  867.                     $startDtForThis->setTimezone(new \DateTimeZone('+0000'));
  868.                     $startTsForThis $startDtForThis->format('U');
  869.                     if (!isset($segregatedData[$key2][$markerForThis]))
  870.                         $segregatedData[$key2][$markerForThis] = [
  871.                             'marker' => $markerForThis,
  872.                             'ts' => $startTsForThis,
  873.                             'data' => []
  874.                         ];
  875.                     if (!isset($segregatedData[$key2][$markerForThis]['data'][$identifier]))
  876.                         $segregatedData[$key2][$markerForThis]['data'][$identifier] = $defaultValues;
  877.                     $newValues $segregatedData[$key2][$markerForThis]['data'][$identifier];
  878.                     $segregatedData[$key2][$markerForThis]['data'][$identifier] = $this->updateEmsAggregateValues($newValues$numericValue);
  879.                     $segregatedDataByDeviceId[$deviceId] = $segregatedData;
  880.                 }
  881.             }
  882.         //nnow data are segregated now add them
  883.         foreach ($emsDataSegregation as $key2 => $dataSegregation) {
  884.             foreach ($segregatedDataByDeviceId as $deviceId => $segregatedData) {
  885.                 if (!isset($segregatedData[$key2]))
  886.                     $segregatedData[$key2] = [];
  887.                 foreach ($segregatedData[$key2] as $key3 => $dt) {
  888.                     $timeStampDt = new \DateTime('@' $dt['ts']);
  889.                     $timeStampDt->setTimezone(new \DateTimeZone('+0000'));
  890.                     $markerForThis $dt['marker'];
  891.                     $entry $this->getDoctrine()->getManager('company_group')
  892.                         ->getRepository('CompanyGroupBundle\\Entity\\' $dataSegregation['repository'])
  893.                         ->findOneBy(array(
  894.                             'marker' => $markerForThis,
  895.                             'siteId' => $siteId,
  896.                             'deviceId' => $deviceId
  897.                         ));
  898.                     $repoClassName "CompanyGroupBundle\\Entity\\" $dataSegregation['repository'];
  899.                     $hasEntry 1;
  900.                     if (!$entry) {
  901.                         $hasEntry 0;
  902.                         $entry = new $repoClassName();
  903.                         $entry->setTimeStamp($timeStampDt);
  904.                         $entry->setTimeStampTs($dt['ts']);
  905.                         $entry->setSiteId($siteId);
  906.                         $entry->setMarker($markerForThis);
  907.                         $entry->setDeviceId($deviceId);
  908.                     }
  909.                     $existingData json_decode($entry->getData(), true);
  910.                     if ($existingData == null$existingData = [];
  911. //                    $existingData=$segregatedDataByDeviceId; //temp
  912.                     foreach ($dt['data'] as $identifier => $newValues) {
  913.                         if (!is_array($newValues) || !isset($newValues[3]) || (int)$newValues[3] <= 0) {
  914.                             continue;
  915.                         }
  916.                         if (!isset($existingData[$identifier]) || !is_array($existingData[$identifier]))
  917.                             $existingData[$identifier] = $newValues;
  918.                         else {
  919.                             $existingData[$identifier] = $this->mergeEmsAggregateValues($existingData[$identifier], $newValues);
  920.                         }
  921.                     }
  922.                     $entry->setData(json_encode($existingData));
  923.                     if ($hasEntry == 0)
  924.                         $em_goc->persist($entry);
  925.                     $em_goc->flush();
  926.                 }
  927.             }
  928.         }
  929.         return new JsonResponse(array(
  930.             'success' => true,
  931.             'skipped_non_numeric_rollup' => $skippedNonNumeric,
  932.             'skipped_invalid_records' => $skippedInvalidRecords,
  933.         ));
  934.     }
  935.     public function DeviceDataEmsIngestActionLater(Request $request$id 0)
  936.     {
  937.         $em_goc $this->getDoctrine()->getManager('company_group');
  938.         $content $request->getContent(); // raw body string
  939.         $data json_decode($contenttrue); // decode JSON if needed
  940.         // Example: access fields
  941.         if ($data == null$data = [];
  942.         $siteId = (isset($data['siteId'])) ? $data['siteId'] : 0;
  943.         if (isset($data['records']))
  944.             foreach ($data['records'] as $key => $value) {
  945. //                $entry = $this->getDoctrine()->getManager('company_group')
  946. //                    ->getRepository("CompanyGroupBundle\\Entity\\DeviceSensorData")
  947. //                    ->findOneBy(array(
  948. //                        'recordId' => $value['record_id']
  949. //                    ));
  950.                 $entry null;
  951.                 $hasEntry 1;
  952.                 if (!$entry) {
  953.                     $hasEntry 0;
  954.                     $entry = new DeviceSensorData();
  955.                 }
  956.                 $timeStampDt = new \DateTime($value['timestamp']);
  957.                 $entry->setDeviceId($value['device_id']);
  958.                 $entry->setRecordId($value['record_id']);
  959.                 $entry->setSiteId($siteId);
  960.                 $entry->setAlias($value['alias']);
  961.                 $entry->setValue($value['value']);
  962.                 $entry->setIdentifier($value['identifier']);
  963.                 $entry->setTimeStamp($timeStampDt);
  964.                 $entry->setTimeStampTs($timeStampDt->format('U'));
  965.                 if ($hasEntry == 0)
  966.                     $em_goc->persist($entry);
  967.                 $em_goc->flush();
  968.             }
  969.         return new JsonResponse(array(
  970.             'success' => true,
  971.         ));
  972.     }
  973.     public function DeviceDataEmsGetAction(Request $request$id 0)
  974.     {
  975.         $em_goc $this->getDoctrine()->getManager('company_group');
  976.         $returnData = array(
  977.             'success' => false,
  978.             'dataList' => []
  979.         );
  980.         $getDatakeys = ['_BY_DAY_''_BY_HOUR_'];
  981.         $emsDataSegregation GeneralConstant::$emsDataSegregation;
  982.         foreach ($getDatakeys as $key2) {
  983.             $dataSegregation $emsDataSegregation[$key2];
  984.             if (!isset($returnData['dataList'][$key2]))
  985.                 $returnData['dataList'][$key2] = [];
  986.             $repoClassName $dataSegregation['repository'];
  987.             $dataQry $this->getDoctrine()->getManager('company_group')
  988.                 ->getRepository('CompanyGroupBundle\\Entity\\' $dataSegregation['repository'])
  989.                 ->createQueryBuilder('a')
  990.                 ->where('1=1');
  991.             if ($request->get('start_ts'0) != 0$dataQry->andWhere('a.timeStampTs >= ' $request->get('start_ts'0));
  992.             if ($request->get('end_ts'0) != 0$dataQry->andWhere('a.timeStampTs <= ' $request->get('end_ts'0));
  993.             if (!empty($request->get('device_ids', [])))
  994.                 $dataQry->andWhere('a.deviceId  in ( ' implode(','$request->get('device_ids', [])) . ' ) ');
  995.             if (!empty($request->get('identifiers', [])))
  996.                 $dataQry->andWhere('a.identifier  in ( ' implode(','$request->get('identifiers', [])) . ' ) ');
  997.             if (!empty($request->get('site_ids', [])))
  998.                 $dataQry->andWhere('a.siteId  in ( ' implode(','$request->get('site_ids', [])) . ' ) ');
  999.             $data $dataQry
  1000.                 ->setMaxResults(1000)
  1001.                 ->getQuery()
  1002.                 ->getResult();
  1003.             if (!empty($data))
  1004.                 $returnData['success'] = true;
  1005.             foreach ($data as $key => $entry) {
  1006.                 $value = array();
  1007.                 $timeStampDt $entry->getTimeStamp();
  1008.                 $timeStampDt->setTimezone(new \DateTimeZone('+0000'));
  1009.                 $existingData json_decode($entry->getData(), true);
  1010.                 if ($existingData == null$existingData = [];
  1011.                 foreach ($existingData as $identifier => $newValues) {
  1012.                     $value['device_id'] = $entry->getDeviceId();
  1013.                     $value['value'] = $newValues[2];
  1014.                     $value['identifier'] = $identifier;
  1015.                     $value['timestamp'] = $timeStampDt;
  1016.                     $value['timestamp_ts'] = $entry->getTimeStampTs();;
  1017.                     $returnData['dataList'][$key2][] = $value;
  1018.                 }
  1019.             }
  1020.         }
  1021.         return new JsonResponse($returnData);
  1022.     }
  1023.     public function UpdateCompanyGroupAction(Request $request$id 0)
  1024.     {
  1025.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1026.         $appId $request->get('app_id'0);
  1027.         $post $request;
  1028.         $session $request->getSession();
  1029.         $d = array();
  1030.         if ($systemType == '_CENTRAL_') {
  1031.             $em_goc $this->getDoctrine()->getManager('company_group');
  1032.             $em_goc->getConnection()->connect();
  1033.             $connected $em_goc->getConnection()->isConnected();
  1034.             $gocDataList = [];
  1035.             if ($connected) {
  1036.                 $goc null;
  1037.                 $serverList MiscActions::getServerListById(
  1038.                     $this->container->getParameter('database_user'),
  1039.                     $this->container->getParameter('database_password'),
  1040.                     $this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []
  1041.                 );
  1042.                 $companyGroupHash $post->get('company_short_code''');
  1043.                 $defaultUsageDate = new \DateTime();
  1044.                 $defaultUsageDate->modify('+1 year');
  1045.                 $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  1046.                 $companyGroupServerId $post->get('server_id'1);
  1047.                 $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  1048.                 $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  1049.                 $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  1050. //                $dbUser=
  1051.                 if ($appId != 0)
  1052.                     $goc $this->getDoctrine()->getManager('company_group')
  1053.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1054.                         ->findOneBy(array(
  1055.                             'appId' => $appId
  1056.                         ));
  1057.                 if (!$goc)
  1058.                     $goc = new CompanyGroup();
  1059.                 if ($appId == 0) {
  1060.                     $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  1061.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1062.                         ->findOneBy(array(//                            'appId' => $appId
  1063.                         ), array(
  1064.                             'appId' => 'desc'
  1065.                         ));
  1066.                     if ($biggestAppIdCg)
  1067.                         $appId $biggestAppIdCg->getAppId();
  1068.                 }
  1069.                 if ($post->get('company_name''') != '') {
  1070.                     $goc->setName($post->get('company_name'));
  1071.                     $goc->setCompanyGroupHash($companyGroupHash);
  1072.                     $goc->setAppId($appId);
  1073.                     $goc->setActive(1);
  1074.                     $goc->setAddress($post->get('address'));
  1075.                     $goc->setShippingAddress($post->get('s_address'));
  1076.                     $goc->setBillingAddress($post->get('b_address'));
  1077.                     $goc->setMotto($post->get('motto'));
  1078.                     $goc->setInitiateFlag($post->get('initiate_flag'2));
  1079.                     $goc->setInvoiceFooter($post->get('i_footer'));
  1080.                     $goc->setGeneralFooter($post->get('g_footer'));
  1081.                     $goc->setCompanyReg($post->get('company_reg'''));
  1082.                     $goc->setCompanyTin($post->get('company_tin'''));
  1083.                     $goc->setCompanyBin($post->get('company_bin'''));
  1084.                     $goc->setCompanyTl($post->get('company_tl'''));
  1085.                     $goc->setCompanyType($post->get('company_type'''));
  1086.                     $goc->setCurrentSubscriptionPackageId($post->get('package'1));
  1087.                     $goc->setUsageValidUptoDate($usageValidUpto);
  1088.                     $goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  1089. //                $goc->setCu($post->get('package', ''));
  1090.                     $goc->setAdminUserAllowed($post->get('number_of_admin_user'''));
  1091.                     $goc->setUserAllowed($post->get('number_of_user'''));
  1092.                     $goc->setSubscriptionMonth($post->get('subscription_month'''));
  1093.                     $goc->setCompanyDescription($post->get('company_description'''));
  1094.                     $goc->setDbUser($post->get('db_user'));
  1095.                     $goc->setDbPass($post->get('db_pass'));
  1096.                     $goc->setDbHost($post->get('db_host'));
  1097.                     $goc->setOwnerId($session->get(UserConstants::USER_ID));
  1098.                     $goc->setCompanyGroupServerId($companyGroupServerId);
  1099.                     $goc->setCompanyGroupServerAddress($companyGroupServerAddress);
  1100.                     $goc->setCompanyGroupServerPort($companyGroupServerPort);
  1101.                     $goc->setCompanyGroupServerHash($companyGroupServerHash);
  1102.                     foreach ($request->files as $uploadedFile) {
  1103.                         if ($uploadedFile != null) {
  1104.                             $fileName 'company_image' $appId '.' $uploadedFile->guessExtension();
  1105.                             $path $fileName;
  1106.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  1107.                             if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  1108.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  1109.                             }
  1110.                             if (!file_exists($upl_dir)) {
  1111.                                 mkdir($upl_dir0777true);
  1112.                             }
  1113.                             $file $uploadedFile->move($upl_dir$path);
  1114.                             if ($path != "")
  1115.                                 $goc->setImage('/uploads/CompanyImage/' $path);
  1116.                         }
  1117.                     }
  1118.                     $em_goc->persist($goc);
  1119.                     $em_goc->flush();
  1120.                     $goc->setDbName('cg_' $appId '_' $companyGroupHash);
  1121.                     $goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
  1122.                     $goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
  1123.                     $goc->setDbHost('localhost');
  1124.                     if ($post->get('enabled_module_id_list'null) !== null) {
  1125.                         $goc->setEnabledModuleIdList($post->get('enabled_module_id_list'''));
  1126.                     }
  1127.                     $em_goc->flush();
  1128.                     $centralUser $this->getDoctrine()->getManager('company_group')
  1129.                         ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  1130.                         ->findOneBy(array(
  1131.                             'applicantId' => $session->get(UserConstants::USER_ID0)
  1132.                         ));
  1133.                     if ($centralUser) {
  1134.                         $userAppIds json_decode($centralUser->getUserAppIds(), true);
  1135.                         $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  1136.                         if ($userAppIds == null$userAppIds = [];
  1137.                         if ($userTypesByAppIds == null$userTypesByAppIds = [];
  1138.                         $userAppIds array_merge($userAppIdsarray_diff([$appId], $userAppIds));
  1139.                         if (!isset($userTypesByAppIds[$appId])) {
  1140.                             $userTypesByAppIds[$appId] = [];
  1141.                         }
  1142.                         $userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
  1143.                         $centralUser->setUserAppIds(json_encode($userAppIds));
  1144.                         $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  1145.                         $em_goc->flush();
  1146.                     }
  1147.                     $accessList $session->get('userAccessList', []);
  1148.                     $d = array(
  1149.                         'userType' => UserConstants::USER_TYPE_SYSTEM,
  1150.                         'globalId' => $session->get(UserConstants::USER_ID0),
  1151.                         'serverId' => $companyGroupServerId,
  1152.                         'serverUrl' => $companyGroupServerAddress,
  1153.                         'serverPort' => $companyGroupServerPort,
  1154.                         'systemType' => '_ERP_',
  1155.                         'companyId' => 1,
  1156.                         'appId' => $appId,
  1157.                         'companyLogoUrl' => $goc->getImage(),
  1158.                         'companyName' => $goc->getName(),
  1159.                         'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  1160.                                 array(
  1161.                                     'globalId' => $session->get(UserConstants::USER_ID0),
  1162.                                     'appId' => $appId,
  1163.                                     'authenticate' => 1,
  1164.                                     'userType' => UserConstants::USER_TYPE_SYSTEM
  1165.                                 )
  1166.                             )
  1167.                         ),
  1168.                         'userCompanyList' => [
  1169.                         ]
  1170.                     );
  1171.                     $accessList[] = $d;
  1172.                     $session->set('userAccessList'$accessList);
  1173. //                    MiscActions::UpdateCompanyListInSession($em_goc, $centralUser->getApplicantId(), 1, 1, 1, $d);
  1174.                     //temporary solution
  1175.                     MiscActions::UpdateCompanyListInSession($em_goc$session->get(UserConstants::USER_ID), 111$d);
  1176.                 }
  1177.                 ///now update Server
  1178.                 ///
  1179.                 ///
  1180.                 if ($post->get('skipUpdateCompanyToErpServer''0') == 0) {
  1181.                     $response MiscActions::updateCompanyToErpServer($em_goc$goc->getAppId(), $this->container->getParameter('kernel.root_dir'));
  1182.                     if (isset($response['success']) && $response['success'] === true) {
  1183.                         return new JsonResponse(array(
  1184.                             'success' => true,
  1185.                             'message' => "Successfully Initialized The Company",
  1186.                             'data' => [],
  1187.                             'user_access_data' => $d,
  1188.                             'initiated' => 1,
  1189.                         ));
  1190.                     }
  1191.                 } else {
  1192.                     return new JsonResponse(array(
  1193.                         'success' => true,
  1194.                         'message' => "Successfully Initialized The Company",
  1195.                         'data' => [],
  1196.                         'user_access_data' => $d,
  1197.                         'initiated' => 1,
  1198.                     ));
  1199.                 }
  1200.             }
  1201.             return new JsonResponse(array(
  1202.                 'success' => false,
  1203.                 'message' => "Company Could not be Initialized or Updated",
  1204.                 'data' => [],
  1205.                 'user_access_data' => $d,
  1206.                 'initiated' => 0,
  1207.             ));
  1208.         } else {
  1209.             $em_goc $this->getDoctrine()->getManager('company_group');
  1210.             $findByQuery = array(
  1211. //                'active' => 1
  1212.                 'appId' => $post->get('app_id')
  1213.             );
  1214.             $goc $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1215.                 ->findOneBy($findByQuery);
  1216.             if (!$goc)
  1217.                 $goc = new CompanyGroup();
  1218.             $goc->setName($post->get('company_name'));
  1219.             $goc->setCompanyGroupHash($post->get('companyGroupHash'));
  1220.             $goc->setAppId($post->get('app_id'));
  1221. //            $goc->setCompanyType($post->get('company_type'));
  1222.             $goc->setAddress($post->get('address'));
  1223. //            $goc->setDarkVibrant($post->get('dark_vibrant'));
  1224. //            $goc->setLightVibrant($post->get('light_vibrant'));
  1225. //            $goc->setVibrant($post->get('vibrant'));
  1226.             $goc->setDbName($post->get('db_name'));
  1227.             $goc->setDbUser($post->get('db_user'));
  1228.             $goc->setDbPass($post->get('db_pass'));
  1229.             $goc->setDbHost($post->get('db_host'));
  1230.             if ($post->get('enabled_module_id_list'null) !== null) {
  1231.                 $goc->setEnabledModuleIdList($post->get('enabled_module_id_list'''));
  1232.             }
  1233.             $goc->setActive(1);
  1234.             $goc->setShippingAddress($post->get('s_address'));
  1235.             $goc->setBillingAddress($post->get('b_address'));
  1236.             $goc->setMotto($post->get('motto'));
  1237.             $goc->setInvoiceFooter($post->get('i_footer'));
  1238.             $goc->setGeneralFooter($post->get('g_footer'));
  1239.             $goc->setCompanyReg($post->get('company_reg'''));
  1240.             $goc->setCompanyTin($post->get('company_tin'''));
  1241.             $goc->setCompanyBin($post->get('company_bin'''));
  1242.             $goc->setCompanyTl($post->get('company_tl'''));
  1243.             $goc->setCompanyType($post->get('company_type'''));
  1244.             $goc->setActive((int)$post->get('active'1));
  1245.             $goc->setReadOnlyMode((int)$post->get('read_only_mode'0));
  1246.             $goc->setCompanyStatus($post->get('company_status''active'));
  1247.             $goc->setPackageType($post->get('package_type'''));
  1248.             $goc->setCurrentSubscriptionPackageId($post->get('current_subscription_package_id'$post->get('package''')));
  1249. //                $goc->setCu($post->get('package', ''));
  1250.             $goc->setAdminUserAllowed($post->get('number_of_admin_user'''));
  1251.             $goc->setUserAllowed($post->get('number_of_user'''));
  1252.             $goc->setSubscriptionMonth($post->get('subscription_month'''));
  1253.             $goc->setBillingAmount($post->get('billing_amount'''));
  1254.             $goc->setCompanyDescription($post->get('company_description'''));
  1255.             if ($post->get('subscription_expiry_dt_str''') !== '') {
  1256.                 $goc->setSubscriptionExpiry(new \DateTime($post->get('subscription_expiry_dt_str')));
  1257.             }
  1258.             $goc->setCompanyGroupServerId($post->get('companyGroupServerId'''));
  1259.             $goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress'''));
  1260.             $goc->setCompanyGroupServerPort($post->get('companyGroupServerPort'''));
  1261.             $goc->setCompanyGroupServerHash($post->get('companyGroupServerHash'''));
  1262.             if ($post->get('enabled_module_id_list'null) !== null) {
  1263.                 $goc->setEnabledModuleIdList($post->get('enabled_module_id_list'''));
  1264.             }
  1265. //            $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
  1266. //            $goc->setSmsSettings($post->get('sms_settings'));
  1267.             foreach ($request->files as $uploadedFile) {
  1268. //            if($uploadedFile->getImage())
  1269. //                var_dump($uploadedFile->getFile());
  1270. //                var_dump($uploadedFile);
  1271.                 if ($uploadedFile != null) {
  1272.                     $fileName 'company_image' $post->get('app_id') . '.' $uploadedFile->guessExtension();
  1273.                     $path $fileName;
  1274.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  1275.                     if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  1276.                         unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  1277.                     }
  1278.                     if (!file_exists($upl_dir)) {
  1279.                         mkdir($upl_dir0777true);
  1280.                     }
  1281.                     $file $uploadedFile->move($upl_dir$path);
  1282.                     if ($path != "")
  1283.                         $goc->setImage('/uploads/CompanyImage/' $path);
  1284.                 }
  1285.             }
  1286.             $em_goc->persist($goc);
  1287.             $em_goc->flush();
  1288.             $connector $this->container->get('application_connector');
  1289.             $connector->resetConnection(
  1290.                 'default',
  1291.                 $goc->getDbName(),
  1292.                 $goc->getDbUser(),
  1293.                 $goc->getDbPass(),
  1294.                 $goc->getDbHost(),
  1295.                 $reset true);
  1296.             $em $this->getDoctrine()->getManager();
  1297.             $prePopulateFlag 0;
  1298.             if ($em->getConnection()->isConnected()) {
  1299.             } else {
  1300.                 $servername $goc->getDbHost();
  1301.                 $username $goc->getDbUser();
  1302.                 $password $goc->getDbPass();
  1303.                 // Create connection
  1304.                 $conn = new \mysqli($servername$username$password);
  1305.                 // Check connection
  1306.                 if ($conn->connect_error) {
  1307.                     die("Connection failed: " $conn->connect_error);
  1308.                 }
  1309.                 // Create database
  1310.                 $sql "CREATE DATABASE " $goc->getDbName();
  1311.                 if ($conn->query($sql) === TRUE) {
  1312.                     $prePopulateFlag 1;
  1313.                     //                                echo "Database created successfully";
  1314.                 } else {
  1315.                     //                                echo "Error creating database: " . $conn->error;
  1316.                 }
  1317.                 $conn->close();
  1318.             }
  1319.             $connector->resetConnection(
  1320.                 'default',
  1321.                 $goc->getDbName(),
  1322.                 $goc->getDbUser(),
  1323.                 $goc->getDbPass(),
  1324.                 $goc->getDbHost(),
  1325.                 $reset true);
  1326.             $em $this->getDoctrine()->getManager();
  1327.             $tool = new SchemaTool($em);
  1328.             $classes $em->getMetadataFactory()->getAllMetadata();
  1329. //                    $tool->createSchema($classes);
  1330.             $tool->updateSchema($classes);
  1331.             if ($prePopulateFlag == 1) {
  1332.                 System::prePopulateDatabase($em);
  1333.             }
  1334.             //now modify the company
  1335.             $company $em
  1336.                 ->getRepository('ApplicationBundle\\Entity\\Company')
  1337.                 ->findOneBy(
  1338.                     array()
  1339.                 );
  1340.             if (!$company)
  1341.                 $company = new Company();
  1342.             $company->setImage($goc->getImage());
  1343.             $company->setName($post->get('company_name'));
  1344.             $company->setCompanyHash($post->get('company_short_code'));
  1345.             $company->setAppId($post->get('app_id'));
  1346.             $company->setActive((int)$post->get('active'1));
  1347.             $company->setAddress($post->get('address'));
  1348. //            $company->setAddress("xyz");
  1349.             $company->setShippingAddress($post->get('s_address'));
  1350. //            $company->setShippingAddress("abc");
  1351.             $company->setBillingAddress($post->get('b_address'));
  1352.             $company->setMotto($post->get('motto'));
  1353.             $company->setInvoiceFooter($post->get('i_footer'));
  1354.             $company->setGeneralFooter($post->get('g_footer'));
  1355.             $company->setCompanyReg($post->get('company_reg'''));
  1356.             $company->setCompanyTin($post->get('company_tin'''));
  1357.             $company->setCompanyBin($post->get('company_bin'''));
  1358.             $company->setCompanyTl($post->get('company_tl'''));
  1359.             $company->setCompanyType($post->get('company_type'''));
  1360.             $company->setAdminUserAllowed($post->get('number_of_admin_user'''));
  1361.             $company->setUserAllowed($post->get('number_of_user'''));
  1362.             $company->setCompanyHash($post->get('companyGroupHash'''));
  1363.             //new fields
  1364.             if ($post->get('usage_valid_upto_dt_str'null) != null) {
  1365.                 $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'null));
  1366.                 $company->setUsageValidUptoDate($usageValidUpto);
  1367.                 $company->setUsageValidUptoDateTs($usageValidUpto->format('U'));
  1368.             } else {
  1369.                 $company->setUsageValidUptoDate(null);
  1370.                 $company->setUsageValidUptoDateTs(0);
  1371.             }
  1372.             $em->persist($company);
  1373.             $em->flush();
  1374.             //initiate Admin
  1375. //            $userName = $request->request->get('username', $request->query->get('username', 'admin'));
  1376. //            $name = $request->request->get('name', $request->query->get('name', 'System Admin'));
  1377. //            $password = $request->request->get('password', $request->query->get('password', 'admin'));
  1378. //            $email = $request->request->get('email', $request->query->get('email', 'admin'));
  1379. //            $encodedPassword = $this->container->get('sha256salted_encoder')->encodePassword($password, $userName);
  1380. //            $companyIds = $request->request->get('companyIds', $request->query->get('companyIds', [1]));
  1381. //            $branchIds = $request->request->get('branchIds', $request->query->get('branchIds', []));
  1382. //            $appIds = $request->request->get('appIds', $request->query->get('appIds', [$post->get('app_id', 0)]));
  1383. //            $freshFlag = $request->request->get('fresh', $request->query->get('fresh', 0));
  1384. //
  1385. //
  1386. //            $message = $this->get('user_module')->addNewUser(
  1387. //                $name,
  1388. //                $email,
  1389. //                $userName,
  1390. //                $password,
  1391. //                '',
  1392. //                0,
  1393. //                1,
  1394. //                UserConstants::USER_TYPE_SYSTEM,
  1395. //                $companyIds,
  1396. //                $branchIds,
  1397. //                '',
  1398. //                "",
  1399. //                1
  1400. //
  1401. //            );
  1402.             if ($company->getAppId()) {
  1403. //                $returnData['message']='';
  1404.                 return new JsonResponse(array(
  1405.                     'success' => true,
  1406.                     'message' => "Successfully Initialized The Company",
  1407.                     'data' => [],
  1408.                     'user_access_data' => $d,
  1409.                     'initiated' => 1,
  1410.                     'app_id' => $company->getAppId(),
  1411.                 ));
  1412.             }
  1413. //            return new JsonResponse($post_fields);
  1414.         }
  1415.         return new JsonResponse(array(
  1416.             'success' => false,
  1417.             'message' => "Company Could not be Initialized or Updated",
  1418.             'data' => [],
  1419.             'user_access_data' => $d,
  1420.             'initiated' => 0,
  1421.             'app_id' => 0
  1422.         ));
  1423.     }
  1424.     public function GenerateErpSubscriptionAction(Request $request$id 0)
  1425.     {
  1426.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1427.         $appId $request->get('app_id'0);
  1428.         $userNo $request->get('user_no'0);
  1429.         $adminNo $request->get('admin_no'0);
  1430.         $post $request;
  1431.         $session $request->getSession();
  1432.         $d = array();
  1433.         $returnData = array(
  1434.             "invoiceAmount" => 0,
  1435.             "dueAmount" => 0,
  1436.             "invoiceId" => 0,
  1437.             "isPaid" => 1,
  1438.         );
  1439.         if ($systemType == '_CENTRAL_') {
  1440.             $em_goc $this->getDoctrine()->getManager('company_group');
  1441.             $em_goc->getConnection()->connect();
  1442.             $connected $em_goc->getConnection()->isConnected();
  1443.             $gocDataList = [];
  1444.             if ($connected) {
  1445.                 $goc null;
  1446.                 $serverList MiscActions::getServerListById(
  1447.                     $this->container->getParameter('database_user'),
  1448.                     $this->container->getParameter('database_password'),
  1449.                     $this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []
  1450.                 );
  1451.                 $companyGroupHash $post->get('company_short_code''');
  1452.                 $defaultUsageDate = new \DateTime();
  1453.                 $defaultUsageDate->modify('+1 year');
  1454.                 $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  1455.                 $companyGroupServerId $post->get('server_id'1);
  1456.                 $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  1457.                 $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  1458.                 $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  1459. //                $dbUser=
  1460.                 if ($appId != 0)
  1461.                     $goc $this->getDoctrine()->getManager('company_group')
  1462.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1463.                         ->findOneBy(array(
  1464.                             'appId' => $appId
  1465.                         ));
  1466.                 if (!$goc)
  1467.                     $goc = new CompanyGroup();
  1468.                 $userNo $goc->getUserAllowed();
  1469.                 $adminNo $goc->getAdminUserAllowed();
  1470.                 //calculate usage here
  1471.                 $returnData MiscActions::getInvoiceableAmountErpSubscription(GeneralConstant::$packageDetails$userNo$adminNo$goc->getCompanyGroupBillingFrequency() == 'yearly' 'monthly');
  1472.                 $goc->setUserAllowed($returnData['noOfUser']);
  1473.                 $goc->setAdminUserAllowed($returnData['noOfAdmin']);
  1474.                 if ($returnData['dueAmount'] <= 0) {
  1475.                     if ($goc->getInitiateFlag() != 1) {
  1476.                         $goc->setInitiateFlag(2);
  1477.                     }
  1478.                 }
  1479.                 $em_goc->flush();
  1480.                 //if not covered by packages , temprarily grand free access if available . meanwhile alert sales
  1481.             }
  1482.         }
  1483.         return new JsonResponse($returnData);
  1484.     }
  1485.     public function SyncCompanyGroupToErpServerAction(Request $request$id 0)
  1486.     {
  1487.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1488.         $appId $request->get('app_id'0);
  1489.         $post $request;
  1490.         $session $request->getSession();
  1491.         $d = array();
  1492.         if ($systemType == '_CENTRAL_') {
  1493.             $em_goc $this->getDoctrine()->getManager('company_group');
  1494.             $em_goc->getConnection()->connect();
  1495.             $connected $em_goc->getConnection()->isConnected();
  1496.             $gocDataList = [];
  1497.             if ($connected) {
  1498.                 $goc null;
  1499.                 $serverList MiscActions::getServerListById(
  1500.                     $this->container->getParameter('database_user'),
  1501.                     $this->container->getParameter('database_password'),
  1502.                     $this->container->hasParameter('server_access_list') ? $this->container->getParameter('server_access_list') : []
  1503.                 );
  1504.                 $companyGroupHash $post->get('company_short_code''');
  1505.                 $defaultUsageDate = new \DateTime();
  1506.                 $defaultUsageDate->modify('+1 year');
  1507.                 $usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str'$defaultUsageDate->format('Y-m-d')));
  1508.                 $companyGroupServerId $post->get('server_id'1);
  1509.                 $companyGroupServerAddress $serverList[$companyGroupServerId]['absoluteUrl'];
  1510.                 $companyGroupServerPort $serverList[$companyGroupServerId]['port'];
  1511.                 $companyGroupServerHash $serverList[$companyGroupServerId]['serverMarker'];
  1512. //                $dbUser=
  1513.                 if ($appId != 0)
  1514.                     $goc $this->getDoctrine()->getManager('company_group')
  1515.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1516.                         ->findOneBy(array(
  1517.                             'appId' => $appId
  1518.                         ));
  1519.                 if (!$goc)
  1520.                     $goc = new CompanyGroup();
  1521.                 if ($appId == 0) {
  1522.                     $biggestAppIdCg $this->getDoctrine()->getManager('company_group')
  1523.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1524.                         ->findOneBy(array(//                            'appId' => $appId
  1525.                         ), array(
  1526.                             'appId' => 'desc'
  1527.                         ));
  1528.                     if ($biggestAppIdCg)
  1529.                         $appId $biggestAppIdCg->getAppId();
  1530.                 }
  1531.                 if ($goc->getInitiateFlag() == || $goc->getInitiateFlag() == 2) {
  1532.                     $response MiscActions::updateCompanyToErpServer($em_goc$goc->getAppId(), $this->container->getParameter('kernel.root_dir'));
  1533.                     if (isset($response['success']) && $response['success'] === true) {
  1534.                         $goc->setInitiateFlag(1);
  1535.                         $em_goc->persist($goc);
  1536.                         $em_goc->flush();
  1537.                         return new JsonResponse(array(
  1538.                             'success' => true,
  1539.                             'message' => "Successfully Initialized The Company On Erp Server",
  1540.                             'data' => [],
  1541.                             'user_access_data' => $d,
  1542.                             'initiated' => 1,
  1543.                         ));
  1544.                     }
  1545.                 }
  1546.             }
  1547.             return new JsonResponse(array(
  1548.                 'success' => false,
  1549.                 'message' => "Company Could not be Initialized or Updated",
  1550.                 'data' => [],
  1551.                 'user_access_data' => $d,
  1552.                 'initiated' => 0,
  1553.             ));
  1554.         }
  1555.         return new JsonResponse(array(
  1556.             'success' => false,
  1557.             'message' => "Company Could not be Initialized or Updated",
  1558.             'data' => [],
  1559.             'user_access_data' => $d,
  1560.             'initiated' => 0,
  1561.             'app_id' => 0
  1562.         ));
  1563.     }
  1564.     //update database schema
  1565.     public function RunScheduledNotificationAction(Request $request)
  1566.     {
  1567.         $message "";
  1568.         $gocList = [];
  1569.         $outputList = [];
  1570.         $scheduler $this->get('scheduler_service');
  1571.         $connector $this->get('application_connector');
  1572.         $mail_module $this->get('mail_module');
  1573.         $gocEnabled 1;
  1574. //        if($this->getContainer()->hasParameter('entity_group_enabled'))
  1575. //            $gocEnabled= $this->getContainer()->getParameter('entity_group_enabled');
  1576. //        $to_print=$app_data->UpdatePostDatedTransaction();
  1577. //        $output->writeln($to_print);
  1578.         $to_print $scheduler->checkAndSendScheduledNotification($connector$gocEnabled0$mail_module);
  1579.         return new JsonResponse(array(
  1580.             'to_print' => $to_print
  1581.         ));
  1582.     }
  1583.     /**
  1584.      * HTTP-cron trigger for the billing schedule engine - same pattern as
  1585.      * run_scheduled_notification. Hit /run_billing_schedule_check periodically
  1586.      * (e.g. hourly) so milestone/day-based billing schedules generate invoices.
  1587.      * Pass ?dry_run=1 to evaluate without creating invoices.
  1588.      */
  1589.     public function RunBillingScheduleCheckAction(Request $request)
  1590.     {
  1591.         $kernel $this->get('kernel');
  1592.         $application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
  1593.         $application->setAutoExit(false);
  1594.         $inputArgs = ['command' => 'inno:billing-schedule-check'];
  1595.         if ($request->query->get('dry_run'0)) {
  1596.             $inputArgs['--dry-run'] = true;
  1597.         }
  1598.         $input = new \Symfony\Component\Console\Input\ArrayInput($inputArgs);
  1599.         $output = new \Symfony\Component\Console\Output\BufferedOutput();
  1600.         $exitCode $application->run($input$output);
  1601.         return new JsonResponse(array(
  1602.             'success' => $exitCode === 0,
  1603.             'exit_code' => $exitCode,
  1604.             'output' => $output->fetch(),
  1605.         ));
  1606.     }
  1607.     public function UpdateDatabaseSchemaAction(Request $request)
  1608.     {
  1609.         $dtHere = array(
  1610.             'autoStartUpdateHit' => $request->query->get('autoStartUpdateHit'0),
  1611.             'page_title' => 'Server Actions',
  1612.         );
  1613.         if ($request->query->get('returnJson'0) == 1) {
  1614.             $message "";
  1615.             $gocList = [];
  1616.             $outputList = [];
  1617.             $configJson = array();
  1618.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  1619.             $configJson['success'] = false;
  1620.             $configJson['debugData'] = [];
  1621.             $configJson['pending_doc_count'] = 0;
  1622.             $configJson['initiateDataBaseFlagByGoc'] = array();
  1623.             $configJson['motherLode'] = "http://erp.ourhoneybee.eu";
  1624.             $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1625.             $thisMomentNow = new \DateTime();
  1626.             $currTimeTs $thisMomentNow->format('U');
  1627.             $em $this->getDoctrine()->getManager('company_group');
  1628.             $em_local_default $this->getDoctrine()->getManager();
  1629.             $em_goc $this->getDoctrine()->getManager('company_group');
  1630.             $em->getConnection()->connect();
  1631.             $connected $em->getConnection()->isConnected();
  1632.             $serverId $this->container->hasParameter('server_id') ? $this->container->getParameter('server_id') : '_ALL_';
  1633.             if ($connected) {
  1634.                 if ($request->query->get('prepareEntityGroup'0) == 1) {
  1635.                     $tool = new SchemaTool($em);
  1636.                     $classes $em->getMetadataFactory()->getAllMetadata();
  1637. //                    $tool->createSchema($classes);
  1638.                     $tool->updateSchema($classes);
  1639.                     $em_local_default->getConnection()->connect();
  1640.                     $em_local_default_connected $em_local_default->getConnection()->isConnected();
  1641.                     if ($em_local_default_connected) {
  1642.                         $tool = new SchemaTool($em_local_default);
  1643.                         $classes $em_local_default->getMetadataFactory()->getAllMetadata();
  1644. //                    $tool->createSchema($classes);
  1645.                         $tool->updateSchema($classes);
  1646.                     }
  1647.                     if ($request->query->get('fixEmptyPassword'0) == 1) {
  1648.                         $query "SELECT * from  entity_applicant_details   where password not like '##UNLOCKED##'";
  1649.                         $stmt $em_goc->getConnection()->fetchAllAssociative($query);
  1650.                         $results $stmt;
  1651.                         foreach ($results as $qpo) {
  1652.                             if ($this->container->get('app.legacy_password_service')->verifyWithSalt($qpo['password'], ''$qpo['salt'])
  1653.                                 || $this->container->get('app.legacy_password_service')->verifyWithSalt($qpo['password'], null$qpo['salt'])
  1654.                             ) {
  1655.                                 $queryGG "update entity_applicant_details set password ='##UNLOCKED##' and trigger_reset_password=1 where applicant_id=" $qpo['applicant_id'];
  1656.                                 $stmt $em_goc->getConnection()->executeStatement($queryGG);
  1657.                             }
  1658.                         }
  1659.                     }
  1660.                     if ($request->query->get('triggerReferScore'0) == 1) {
  1661.                         $query "SELECT * from  entity_meeting_session   where booked_by_id !=0 and booked_by_id is not NULL and booked_by_id !=student_id";
  1662.                         $stmt $em_goc->getConnection()->fetchAllAssociative($query);
  1663.                         $results $stmt;
  1664.                         foreach ($results as $qpo) {
  1665.                             MiscActions::updateEntityPerformanceIndex($em_goc, [
  1666.                                 'targetId' => $qpo['booked_by_id'],
  1667.                                 'conversionData' => [
  1668.                                     'count' => 1,
  1669.                                     'score' => 10,
  1670.                                 ]
  1671.                             ],
  1672.                                 new \DateTime($qpo['created_at']));
  1673.                         }
  1674.                         $query "SELECT * from  entity_meeting_session   where booking_referer_id !=0 and booking_referer_id is not NULL and booking_referer_id !=student_id";
  1675.                         $stmt $em_goc->getConnection()->fetchAllAssociative($query);
  1676.                         $results $stmt;
  1677.                         foreach ($results as $qpo) {
  1678.                             MiscActions::updateEntityPerformanceIndex($em_goc, [
  1679.                                 'targetId' => $qpo['booking_referer_id'],
  1680.                                 'referData' => [
  1681.                                     'count' => 1,
  1682.                                     'score' => 10,
  1683.                                 ]
  1684.                             ],
  1685.                                 new \DateTime($qpo['created_at'])
  1686.                             );
  1687.                         }
  1688.                     }
  1689.                     if ($request->query->get('refreshBuddyBeeSalt'0) == 1) {
  1690.                         $query "
  1691.                         UPDATE entity_applicant_details set temp_password=''  where 1;
  1692.                         UPDATE entity_applicant_details set salt=username  where username != '' and username is not NULL and (salt ='' or salt is  NULL);
  1693.                         UPDATE entity_applicant_details set salt='beesalt'  where (salt ='' or salt is  NULL) and (username ='' or username is  NULL);
  1694.                       ";
  1695.                         $stmt $em_goc->getConnection()->executeStatement($query);
  1696.                     }
  1697.                     if ($request->query->get('refreshLastSettingsUpdatedTs'0) == 1) {
  1698.                         $query "
  1699.               
  1700.                         UPDATE entity_user set last_settings_updated_ts=$currTimeTs  where 1;
  1701.                         UPDATE entity_applicant_details set last_settings_updated_ts=$currTimeTs  where 1;
  1702.                      
  1703.                       ";
  1704.                         $stmt $em_goc->getConnection()->executeStatement($query);
  1705.                     }
  1706.                     $get_kids_sql "update `company_group` set `schema_update_pending_flag` =1 where 1;";
  1707.                     $stmt $em_goc->getConnection()->executeStatement($get_kids_sql);
  1708.                     $stmt $em_goc->getConnection()->fetchAllAssociative("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
  1709. //                    
  1710.                     $check_here $stmt;
  1711.                     $pending_id_count 0;
  1712.                     if (isset($check_here[0]))
  1713.                         $pending_id_count $check_here[0]['id_count'];
  1714.                     return new JsonResponse(array(
  1715.                         'pending_doc_count' => $pending_id_count,
  1716.                         'success' => true
  1717.                     ));
  1718.                 } else
  1719.                     if ($systemType != '_CENTRAL_') {
  1720.                         $stmt $em_goc->getConnection()->fetchAllAssociative("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
  1721. //                        
  1722.                         $check_here $stmt;
  1723.                         if (isset($check_here[0]))
  1724.                             $configJson['pending_doc_count'] = $check_here[0]['id_count'];
  1725. //                        if($serverId!='_ALL_')
  1726.                         $gocList $this->getDoctrine()->getManager('company_group')
  1727.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1728.                             ->findBy(
  1729.                                 array(
  1730.                                     'active' => 1,
  1731. //                                    'serverId' => 1,
  1732.                                     'schemaUpdatePendingFlag' => 1
  1733.                                 ), array(), 1
  1734.                             );
  1735.                     }
  1736.             }
  1737.             $gocDataList = [];
  1738.             $gocEntryObjectList = [];
  1739.             foreach ($gocList as $entry) {
  1740.                 $d = array(
  1741.                     'name' => $entry->getName(),
  1742.                     'image' => $entry->getImage(),
  1743.                     'shippingAddress' => $entry->getShippingAddress(),
  1744.                     'billingAddress' => $entry->getBillingAddress(),
  1745.                     'id' => $entry->getId(),
  1746.                     'dbName' => $entry->getDbName(),
  1747.                     'dbUser' => $entry->getDbUser(),
  1748.                     'dbPass' => $entry->getDbPass(),
  1749.                     'dbHost' => $entry->getDbHost(),
  1750.                     'appId' => $entry->getAppId(),
  1751.                     'companyRemaining' => $entry->getCompanyRemaining(),
  1752.                     'companyAllowed' => $entry->getCompanyAllowed(),
  1753.                 );
  1754.                 $gocDataList[$entry->getId()] = $d;
  1755.                 $gocEntryObjectList[$entry->getId()] = $entry;
  1756.             }
  1757.             $gocDbName '';
  1758.             $gocDbUser '';
  1759.             $gocDbPass '';
  1760.             $gocDbHost '';
  1761.             $gocId 0;
  1762.             foreach ($gocDataList as $gocId => $entry) {
  1763.                 $connector $this->container->get('application_connector');
  1764.                 $connector->resetConnection(
  1765.                     'default',
  1766.                     $gocDataList[$gocId]['dbName'],
  1767.                     $gocDataList[$gocId]['dbUser'],
  1768.                     $gocDataList[$gocId]['dbPass'],
  1769.                     $gocDataList[$gocId]['dbHost'],
  1770.                     $reset true);
  1771.                 $em $this->getDoctrine()->getManager();
  1772.                 $em->getConnection()->connect();
  1773.                 $indConnected $em->getConnection()->isConnected();
  1774.                 if ($indConnected) {
  1775.                     $configJson['name'] = $entry['name'];
  1776.                     $configJson['image'] = $entry['image'];
  1777.                     $configJson['appId'] = $entry['appId'];
  1778.                     if ($request->query->get('delTable''') != '') {
  1779.                         $get_kids_sql "DROP TABLE " $request->query->get('delTable') . "  ;";
  1780.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1781.                     }
  1782.                     $tool = new SchemaTool($em);
  1783.                     $classes $em->getMetadataFactory()->getAllMetadata();
  1784. //                    $tool->createSchema($classes);
  1785.                     $tool->updateSchema($classes);
  1786.                     //temp
  1787.                     //temp end
  1788.                     if ($request->query->get('refreshLastSettingsUpdatedTs'0) == 1) {
  1789.                         $query "
  1790.                                     UPDATE sys_user set last_settings_updated_ts=$currTimeTs  where 1;
  1791.                                     UPDATE acc_clients set last_settings_updated_ts=$currTimeTs  where 1;
  1792.                                     UPDATE acc_suppliers set last_settings_updated_ts=$currTimeTs  where 1;
  1793.                      
  1794.                       ";
  1795.                         $stmt $em->getConnection()->executeStatement($query);
  1796.                     }
  1797.                     if ($request->query->get('optimizeJunkAttendanceTable'0) == 1) {
  1798.                         $query "
  1799.                                     OPTIMIZE TABLE employee_attendance_log;
  1800.                      
  1801.                       ";
  1802.                         $stmt $em->getConnection()->executeStatement($query);
  1803.                     }
  1804.                     if ($request->query->get('encryptTrans'0) == 1) {
  1805.                         MiscActions::encryptTrans($em'_ALL_'0);
  1806.                     }
  1807.                     if ($request->query->get('decryptTrans'0) == 1) {
  1808.                         MiscActions::decryptTrans($em'_ALL_'0);
  1809.                     }
  1810.                     if ($request->query->get('createdByRefresh'0) == 1) {
  1811.                         foreach (GeneralConstant::$Entity_list as $entity => $entityName) {
  1812.                             if (in_array($entity, [54]))
  1813.                                 continue;
  1814.                             if (!$em->getMetadataFactory()->isTransient('ApplicationBundle\\Entity\\' $entityName)) {
  1815. //                                $className = ('\\ApplicationBundle\\Entity\\') . $entityName;
  1816. //                                $theEntity = new $className();
  1817. //                                $test_now=$theEntity->getCreatedUserId();
  1818.                                 //if its approval decode signature and add it to dbase and pass the id
  1819.                                 $sigId null;
  1820.                                 $doc null;
  1821.                                 $docList $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  1822.                                     ->findBy(
  1823.                                         array(//                                        GeneralConstant::$Entity_id_field_list[$entity] => $entity_id,
  1824.                                         )
  1825.                                     );
  1826.                                 foreach ($docList as $doc) {
  1827.                                     $notYetAdded 1;
  1828.                                     foreach ([12] as $approveRole) {
  1829.                                         $getIdfunc GeneralConstant::$Entity_id_get_method_list[$entity];
  1830.                                         $entity_id $doc->$getIdfunc();
  1831.                                         $loginId null;
  1832.                                         $sigId null;
  1833.                                         $user_data = [];
  1834.                                         if ($approveRole == 1//created
  1835.                                         {
  1836.                                             $loginId $doc->getCreatedLoginId();
  1837.                                             $notYetAdded $doc->getCreatedUserId() == null 0;
  1838.                                             $sigId $doc->getCreatedSigId();
  1839.                                             $user_data Users::getUserInfoByLoginId($em$loginId);
  1840.                                             if (isset($user_data['id'])) {
  1841.                                                 $doc->setCreatedUserId($user_data['id']);
  1842.                                                 $doc->setCreatedSigId(null);
  1843.                                             }
  1844.                                             $em->flush();
  1845.                                         }
  1846.                                         if ($approveRole == 2//edited
  1847.                                         {
  1848.                                             $loginId $doc->getEditedLoginId();
  1849.                                             $sigId $doc->getEditedSigId();
  1850.                                             $notYetAdded $doc->getEditedUserId() == null 0;
  1851.                                             $user_data Users::getUserInfoByLoginId($em$loginId);
  1852.                                             $doc->setEditedSigId($sigId);
  1853.                                             if (isset($user_data['id'])) {
  1854.                                                 $doc->setEditedUserId($user_data['id']);
  1855.                                                 $doc->setEditedSigId(null);
  1856.                                                 $doc->setLastModifiedDate(new \DateTime());
  1857.                                             }
  1858.                                             $em->flush();
  1859.                                         }
  1860.                                         if (isset($user_data['id']) && $notYetAdded == 1) {
  1861.                                             $new = new Approval();
  1862.                                             $new->setEntity($entity);
  1863.                                             $new->setEntityId($entity_id);
  1864.                                             $new->setPositionId(null);
  1865.                                             $new->setSequence(0);
  1866.                                             $new->setSkipPrintFlag(0);
  1867.                                             $new->setUserAssignType(1);
  1868.                                             $new->setDocumentHash($doc->getDocumentHash());
  1869.                                             //            $new->setUserIds($value->getUserId()); //<-----
  1870.                                             $new->setRoleType($approveRole);
  1871.                                             $new->setRequired(0);
  1872.                                             $new->setSuccession(0);
  1873.                                             $new->setAction(1); //pending status
  1874.                                             $new->setLoginId($loginId); //pending status
  1875.                                             $new->setCurrent(GeneralConstant::CURRENTLY_NON_PENDING_APPROVAL);
  1876.                                             $new->setSuccessionTimeout(0);
  1877.                                             $new->setSigId($sigId);
  1878.                                             $new->setNote('');
  1879.                                             $new->setUserIds(json_encode([$user_data['id']])); //<-----
  1880.                                             $em->persist($new);
  1881.                                             $em->flush();
  1882.                                         }
  1883.                                     }
  1884.                                 }
  1885.                             }
  1886.                         }
  1887.                     }
  1888.                     if ($request->query->get('rectifyOldBoq'0) == 1) {
  1889.                         $boqs $em
  1890.                             ->getRepository('ApplicationBundle\\Entity\\ProjectBoq')
  1891.                             ->findby(array(//                                    'projectId'=>$projectId
  1892.                             ));
  1893.                         foreach ($boqs as $boq) {
  1894. //
  1895. //                            //now the data
  1896. //                            $data = [];
  1897. //                            $newData = [];
  1898. //                            if ($boq)
  1899. //                                $data = json_decode($boq->getData(), true);
  1900. //                            if ($data == null)
  1901. //                                $data = [];
  1902. //                            $defValuesProduct = array(
  1903. //                                'product_note' => '',
  1904. //                                'product_alias' => '',
  1905. //                                'is_foreign_item' => 0,
  1906. //                                'product_segmentIndex' => 0,
  1907. //                                'product_currency_id' => 0,
  1908. //                                'product_currency_text' => '',
  1909. //                                'product_currency_multiply_rate' => 1,
  1910. //                                'product_scope' => 1,
  1911. //                                'product_scopeHolderId' => 0,
  1912. //                                'product_scopeHolderName' => '',
  1913. //                                'product_scopeDescription' => '',
  1914. //                            );
  1915. //                            $defValuesService = array(
  1916. //                                'service_note' => '',
  1917. //                                'service_alias' => '',
  1918. //                                'is_foreign_service' => 0,
  1919. //                                'service_segmentIndex' => 0,
  1920. //                                'service_currency_id' => 0,
  1921. //                                'service_currency_text' => '',
  1922. //                                'service_currency_multiply_rate' => 1,
  1923. //                                'service_scope' => 1,
  1924. //                                'service_scopeHolderId' => 0,
  1925. //                                'service_scopeHolderName' => '',
  1926. //                                'service_scopeDescription' => '',
  1927. //                            );
  1928. //
  1929. //
  1930. //                            if (!empty($data)) {
  1931. //                                $last_key = array_key_last($data);
  1932. ////                                if (isset($data[$last_key]['Products']['product_scope']))
  1933. ////                                    continue;
  1934. ////                                    if (count($data[$last_key]['Products']['products'])==count($data[$last_key]['Products']['is_foreign_item']) )
  1935. //
  1936. //
  1937. //                                $kho = 0;
  1938. //                                $dt_poka = $data[0];
  1939. //                                foreach ($data as $kho => $dt_poka) {
  1940. //
  1941. //
  1942. //                                    if (isset($dt_poka['Products']['products']))
  1943. //                                        foreach ($defValuesProduct as $gopaa => $boka) {
  1944. //                                            if (!isset($dt_poka['Products'][$gopaa]))
  1945. //                                                $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
  1946. //                                            else if ($dt_poka['Products'][$gopaa] == null)
  1947. //                                                $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
  1948. //
  1949. //
  1950. //                                        }
  1951. //                                    if (isset($dt_poka['Services']['services']))
  1952. //                                        foreach ($defValuesService as $gopaa => $boka) {
  1953. //                                            if (!isset($dt_poka['Services'][$gopaa]))
  1954. //                                                $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
  1955. //                                            else if ($dt_poka['Services'][$gopaa] == null)
  1956. //                                                $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
  1957. //
  1958. //                                        }
  1959. //
  1960. //                                    if (!isset($dt_poka['serviceSegmentData']))
  1961. //                                        $dt_poka['serviceSegmentData'] = [
  1962. //                                            array(
  1963. //                                                "title" => "General Services",
  1964. //                                                "index" => 0,
  1965. //                                            )
  1966. //                                        ];
  1967. //                                    else if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
  1968. //                                        $dt_poka['serviceSegmentData'] = [
  1969. //                                            array(
  1970. //                                                "title" => "General Services",
  1971. //                                                "index" => 0,
  1972. //                                            )
  1973. //                                        ];
  1974. //
  1975. //                                    if (!isset($dt_poka['productSegmentData']))
  1976. //                                        $dt_poka['productSegmentData'] = [
  1977. //                                            array(
  1978. //                                                "title" => "General Items",
  1979. //                                                "index" => 0,
  1980. //                                            )
  1981. //                                        ];
  1982. //                                    else if ($dt_poka['productSegmentData'] == null || empty($dt_poka['productSegmentData']))
  1983. //                                        $dt_poka['productSegmentData'] = [
  1984. //                                            array(
  1985. //                                                "title" => "General Items",
  1986. //                                                "index" => 0,
  1987. //                                            )
  1988. //                                        ];
  1989. //
  1990. //
  1991. //                                    $newData[$kho] = $dt_poka;
  1992. //                                }
  1993. //
  1994. //
  1995. //                                $boq->setData(json_encode($newData));
  1996. //                                $em->flush();
  1997. //
  1998. //
  1999. //                            }
  2000.                             $theProj $em->getRepository('ApplicationBundle\\Entity\\Project')
  2001.                                 ->findOneBy(
  2002.                                     array(
  2003.                                         'projectId' => $boq->getProjectId()
  2004.                                     )
  2005.                                 );
  2006.                             if ($theProj)
  2007.                                 $theProj->setDocumentDataId($boq->getDocumentDataId());
  2008.                             $em->flush();
  2009.                         }
  2010.                     }
  2011.                     if ($request->query->get('oldBoqToNewSystem'0) == 1) {
  2012.                         $entitiesGG = [
  2013.                             array_flip(GeneralConstant::$Entity_list)['ProjectBoq'],
  2014.                             array_flip(GeneralConstant::$Entity_list)['ProjectMaterial'],
  2015.                             array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  2016.                             array_flip(GeneralConstant::$Entity_list)['Opportunity'],
  2017.                             array_flip(GeneralConstant::$Entity_list)['ProjectOffer'],
  2018.                             array_flip(GeneralConstant::$Entity_list)['ProjectProposal'],
  2019.                         ];
  2020.                         foreach ($entitiesGG as $ent) {
  2021.                             $entityNameHere GeneralConstant::$Entity_list[$ent];
  2022.                             $the_actual_docs $em->getRepository('ApplicationBundle\\Entity\\' GeneralConstant::$Entity_list[$ent])
  2023.                                 ->findBy(
  2024.                                     array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  2025.                                     )
  2026.                                 );
  2027.                             foreach ($the_actual_docs as $the_actual_doc) {
  2028.                                 //now the data
  2029.                                 //first find the docData if available
  2030.                                 $theDocData null;
  2031.                                 if ($entityNameHere == 'SalesProposal' || $entityNameHere == 'Opportunity') {
  2032.                                     $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2033.                                         ->findOneBy(
  2034.                                             array(
  2035.                                                 'id' => $the_actual_doc->getDocumentDataId()
  2036.                                             )
  2037.                                         );
  2038.                                     if (!$theDocData)
  2039.                                         if ($the_actual_doc->getSalesProposalId() != null && $the_actual_doc->getSalesProposalId() != 0)
  2040.                                             $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2041.                                                 ->findOneBy(
  2042.                                                     array(
  2043.                                                         'proposalId' => $the_actual_doc->getSalesProposalId()
  2044.                                                     )
  2045.                                                 );
  2046.                                     if (!$theDocData)
  2047.                                         if ($the_actual_doc->getOpportunityId() != null && $the_actual_doc->getOpportunityId() != 0)
  2048.                                             $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2049.                                                 ->findOneBy(
  2050.                                                     array(
  2051.                                                         'opportunityId' => $the_actual_doc->getOpportunityId()
  2052.                                                     )
  2053.                                                 );
  2054.                                     if (!$theDocData)
  2055.                                         if ($the_actual_doc->getProjectId() != null && $the_actual_doc->getProjectId() != 0)
  2056.                                             $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2057.                                                 ->findOneBy(
  2058.                                                     array(
  2059.                                                         'projectId' => $the_actual_doc->getProjectId()
  2060.                                                     )
  2061.                                                 );
  2062.                                     if (!$theDocData) {
  2063.                                         $theDocData = new DocumentData();
  2064.                                         if ($entityNameHere == 'SalesProposal')
  2065.                                             $theDocData->setProposalId($the_actual_doc->getSalesProposalId());
  2066.                                         if ($entityNameHere == 'Opportunity')
  2067.                                             $theDocData->setOpportunityId($the_actual_doc->getOpportunityId());
  2068.                                     }
  2069.                                 } else {
  2070.                                     $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2071.                                         ->findOneBy(
  2072.                                             array(
  2073.                                                 'id' => $the_actual_doc->getDocumentDataId()
  2074.                                             )
  2075.                                         );
  2076.                                     if (!$theDocData)
  2077.                                         $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2078.                                             ->findOneBy(
  2079.                                                 array(
  2080.                                                     'projectId' => $the_actual_doc->getProjectId()
  2081.                                                 )
  2082.                                             );
  2083.                                     if (!$theDocData) {
  2084.                                         $theDocData = new DocumentData();
  2085.                                         $theDocData->setProjectId($the_actual_doc->getProjectId());
  2086.                                     }
  2087.                                 }
  2088.                                 if ($entityNameHere == 'ProjectBoq' || $entityNameHere == 'Opportunity' || $entityNameHere == 'SalesProposal') {
  2089.                                     $data = [];
  2090.                                     $newData = [];
  2091.                                     $data json_decode($the_actual_doc->getData(), true);
  2092.                                     if ($data == null)
  2093.                                         $data = [];
  2094.                                     if (!empty($data)) {
  2095.                                         $last_key array_key_last($data);
  2096.                                         $lastIndex 0;
  2097.                                         foreach ($data as $kho => $dt_poka) {
  2098.                                             $cur_date = new \DateTime();
  2099.                                             $lead_date = new \DateTime(isset($dt_poka['lead_date']) ? $dt_poka['lead_date'] : '');
  2100.                                             $newSingleSet = array(
  2101.                                                 'refPoNumber' => isset($dt_poka['refPoNumber']) ? $dt_poka['refPoNumber'] : '',
  2102.                                                 'segmentData' => isset($dt_poka['segmentData']) ? $dt_poka['segmentData'] : [],
  2103.                                                 'proposal_title' => isset($dt_poka['proposal_title']) ? $dt_poka['proposal_title'] : '',
  2104.                                                 'to_position' => isset($dt_poka['to_position']) ? $dt_poka['to_position'] : '',
  2105.                                                 'system_subCategory' => isset($dt_poka['system_subCategory']) ? $dt_poka['system_subCategory'] : '',
  2106.                                                 'system_size' => isset($dt_poka['system_size']) ? $dt_poka['system_size'] : '',
  2107.                                                 'system_unit' => isset($dt_poka['system_unit']) ? $dt_poka['system_unit'] : '',
  2108.                                                 'system_price' => isset($dt_poka['system_price']) ? $dt_poka['system_price'] : '',
  2109.                                                 'msaTotal' => isset($dt_poka['msaTotal']) ? $dt_poka['msaTotal'] : 0,
  2110.                                                 'totalProjectValue' => isset($dt_poka['totalProjectValue']) ? $dt_poka['totalProjectValue'] : 0,
  2111.                                                 'cl_subject' => isset($dt_poka['cl_subject']) ? $dt_poka['cl_subject'] : '',
  2112.                                                 'cl_body' => isset($dt_poka['cl_body']) ? $dt_poka['cl_body'] : '',
  2113.                                                 'vatPercentage' => isset($dt_poka['vatPercentage']) ? $dt_poka['vatPercentage'] : '',
  2114.                                                 'aitPercentage' => isset($dt_poka['aitPercentage']) ? $dt_poka['aitPercentage'] : '',
  2115.                                                 'proposalSalesValue' => isset($dt_poka['proposalSalesValue']) ? $dt_poka['proposalSalesValue'] : '',
  2116.                                                 'combined_proposal_item_name' => isset($dt_poka['combined_proposal_item_name']) ? $dt_poka['combined_proposal_item_name'] : '',
  2117.                                                 'combined_proposal_details_price' => isset($dt_poka['combined_proposal_details_price']) ? $dt_poka['combined_proposal_details_price'] : '',
  2118.                                                 'check_boq' => isset($dt_poka['check_boq']) ? $dt_poka['check_boq'] : 0,
  2119.                                                 'check_boq_individual_price' => isset($dt_poka['check_boq_individual_price']) ? $dt_poka['check_boq_individual_price'] : 0,
  2120.                                                 'check_show_combined_only' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
  2121.                                                 'check_override_markup' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
  2122.                                                 'clientId' => isset($dt_poka['client_id']) ? $dt_poka['client_id'] : 0,
  2123.                                                 'salesPersonId' => isset($dt_poka['salesPersonID']) ? $dt_poka['salesPersonID'] : 0,
  2124.                                                 'clientName' => isset($dt_poka['clientName']) ? $dt_poka['clientName'] : '',
  2125.                                                 'ClientContactPerson' => isset($dt_poka['ClientContactPerson']) ? $dt_poka['ClientContactPerson'] : '',
  2126.                                                 'ClientContactNumber' => isset($dt_poka['ClientContactNumber']) ? $dt_poka['ClientContactNumber'] : '',
  2127.                                                 'ClientDeliveryAddress' => isset($dt_poka['ClientDeliveryAddress']) ? $dt_poka['ClientDeliveryAddress'] : '',
  2128.                                                 'ClientBillingAddress' => isset($dt_poka['ClientBillingAddress']) ? $dt_poka['ClientBillingAddress'] : '',
  2129.                                                 'leadDate' => $lead_date->format('Y-m-d'),
  2130.                                                 'date' => $cur_date->format('Y-m-d'),
  2131.                                             );
  2132.                                             $newSegmentData = array();
  2133.                                             $oldSegmentSystem 0;
  2134.                                             if (isset($dt_poka['productSegmentData']) || isset($dt_poka['serviceSegmentData']))
  2135.                                                 $oldSegmentSystem 1;
  2136.                                             if ($oldSegmentSystem == 1) {
  2137.                                                 //unify the ids of segmnent. services will start from 1000+service segmentId for unification
  2138.                                                 if (isset($dt_poka['productSegmentData']))
  2139.                                                     foreach ($dt_poka['productSegmentData'] as $supu => $gupu) {
  2140.                                                         $newModSeg $gupu;
  2141.                                                         $newModSeg['index'] = $gupu['index'];
  2142.                                                         $newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Items';
  2143.                                                         $newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
  2144.                                                         $newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
  2145.                                                         $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  2146.                                                         $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  2147.                                                         $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  2148.                                                         $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  2149.                                                         $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  2150.                                                         $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  2151.                                                         $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  2152.                                                         $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  2153.                                                         $newSegmentData[] = $newModSeg;
  2154.                                                     }
  2155.                                                 if (isset($dt_poka['serviceSegmentData']))
  2156.                                                     if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
  2157.                                                         foreach ($dt_poka['serviceSegmentData'] as $supu => $gupu) {
  2158.                                                             if ($gupu['index'] == 'undefined'$gupu['index'] = 0;
  2159.                                                             if (!is_numeric($gupu['index'])) $gupu['index'] = 0;
  2160.                                                             $newModSeg $gupu;
  2161.                                                             $newModSeg['index'] = 1000 $gupu['index'];
  2162.                                                             $newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Services';
  2163.                                                             $newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
  2164.                                                             $newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
  2165.                                                             $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  2166.                                                             $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  2167.                                                             $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  2168.                                                             $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  2169.                                                             $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  2170.                                                             $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  2171.                                                             $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  2172.                                                             $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  2173.                                                             $newSegmentData[] = $newModSeg;
  2174.                                                         }
  2175.                                                 $newSingleSet['itemSegmentData'] = $newSegmentData;
  2176.                                             }
  2177.                                             $lastSequenceBySegment = array();
  2178.                                             //now modify Services or products
  2179.                                             $oldProductSystem 0;
  2180.                                             if (!isset($dt_poka['rowData']))
  2181.                                                 $dt_poka['rowData'] = array();
  2182.                                             if (isset($dt_poka['Products']) || isset($dt_poka['Services']) || isset($dt_poka['ArCosts'])) {
  2183.                                                 $oldProductSystem 1;
  2184.                                             }
  2185.                                             if ($oldProductSystem == 1) {
  2186.                                                 $theDt = array(
  2187.                                                     'products' => [],
  2188.                                                     'services' => [],
  2189.                                                     'ar_heads' => [],
  2190.                                                 );
  2191.                                                 if (isset($dt_poka['Products']))
  2192.                                                     $theDt $dt_poka['Products'];
  2193.                                                 if (isset($theDt['products']))
  2194.                                                     foreach ($theDt['products'] as $f => $pid) {
  2195.                                                         $unit = isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0;
  2196.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  2197.                                                         if ($indexForThis == -1) {
  2198.                                                             $indexForThis $lastIndex;
  2199.                                                             $lastIndex++;
  2200.                                                         }
  2201.                                                         $unitPrice = isset($theDt['product_unit_price'][$f]) ? $theDt['product_unit_price'][$f] : 0;
  2202.                                                         if ($unit == ''$unit 0;
  2203.                                                         if ($unitPrice == ''$unitPrice 0;
  2204.                                                         $totalPrice $unit $unitPrice;
  2205.                                                         $segmentIndex = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : 0;
  2206.                                                         $sequence = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : '_UNSET_';
  2207.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  2208.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  2209.                                                         if ($sequence == '_UNSET_')
  2210.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2211.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  2212.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2213.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  2214.                                                         $unitSalesPrice = isset($theDt['product_unit_sales_price'][$f]) ? $theDt['product_unit_sales_price'][$f] : $unitPrice;
  2215.                                                         if ($unitSalesPrice == ''$unitSalesPrice 0;
  2216.                                                         $totalSalesPrice $unit $unitSalesPrice;
  2217.                                                         $marginAmount = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitSalesPrice $unitPrice);
  2218.                                                         $marginRate = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  2219.                                                         $discountAmount = isset($theDt['product_dr'][$f]) ? $theDt['product_dr'][$f] : 0;
  2220.                                                         $discountRate = isset($theDt['product_da'][$f]) ? $theDt['product_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  2221.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  2222.                                                         $taxRate = isset($theDt['product_tax_percentage'][$f]) ? $theDt['product_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  2223.                                                         $taxAmount = isset($theDt['product_tax_amount'][$f]) ? $theDt['product_tax_amount'][$f] : 0;
  2224.                                                         $finalAmount $discountedAmount $taxAmount;
  2225.                                                         $row = array(
  2226.                                                             'type' => 1,//1:product 2=service 4=tools 5:text 6: expense against head
  2227.                                                             'id' => $pid,
  2228.                                                             'index' => $indexForThis,
  2229.                                                             'isForeign' => isset($theDt['is_foreign_item'][$f]) ? $theDt['is_foreign_item'][$f] : 0,
  2230.                                                             'sequence' => $sequence,
  2231.                                                             'segmentIndex' => $segmentIndex,
  2232.                                                             'soItemId' => isset($theDt['product_soItemId'][$f]) ? $theDt['product_soItemId'][$f] : 0,
  2233.                                                             'soItemDelivered' => isset($theDt['product_soItemDelivered'][$f]) ? $theDt['product_soItemDelivered'][$f] : 0,
  2234.                                                             'soItemFound' => isset($theDt['product_soItemFound'][$f]) ? $theDt['product_soItemFound'][$f] : 0,
  2235.                                                             'alias' => isset($theDt['product_alias'][$f]) ? $theDt['product_alias'][$f] : '',
  2236.                                                             'name' => isset($theDt['product_name'][$f]) ? $theDt['product_name'][$f] : '',
  2237.                                                             'note' => isset($theDt['product_note'][$f]) ? $theDt['product_note'][$f] : '',
  2238.                                                             'fdm' => isset($theDt['product_fdm'][$f]) ? $theDt['product_fdm'][$f] : null,
  2239.                                                             'unit' => isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0,
  2240.                                                             'unitTypeId' => isset($theDt['product_unit_type'][$f]) ? $theDt['product_unit_type'][$f] : 0,
  2241.                                                             'unitPrice' => $unitPrice,
  2242.                                                             'totalPrice' => $totalPrice,
  2243.                                                             'unitSalesPrice' => $unitSalesPrice,
  2244.                                                             'totalSalesPrice' => $totalSalesPrice,
  2245.                                                             'marginRate' => $marginRate,
  2246.                                                             'marginAmount' => $marginAmount,
  2247.                                                             'discountRate' => $discountRate,
  2248.                                                             'discountAmount' => $discountAmount,
  2249.                                                             'discountedAmount' => $discountedAmount,
  2250.                                                             'taxRate' => $taxRate,
  2251.                                                             'taxAmount' => $taxAmount,
  2252.                                                             'finalAmount' => $finalAmount,
  2253.                                                             'recurring' => isset($theDt['product_recurring'][$f]) ? $theDt['product_recurring'][$f] : 0,
  2254.                                                             'currency' => isset($theDt['product_currency_id'][$f]) ? $theDt['product_currency_id'][$f] : 0,
  2255.                                                             'currencyText' => isset($theDt['product_currency_text'][$f]) ? $theDt['product_currency_text'][$f] : '',
  2256.                                                             'currencyMultiplyRate' => isset($theDt['product_currency_multiply_rate'][$f]) ? $theDt['product_currency_multiply_rate'][$f] : 1,
  2257.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  2258.                                                             'taxId' => isset($theDt['product_tax_config_id'][$f]) ? $theDt['product_tax_config_id'][$f] : 0,
  2259.                                                             'taxName' => isset($theDt['product_tax_config_text'][$f]) ? $theDt['product_tax_config_text'][$f] : '',
  2260.                                                             'dependencyOnIndex' => isset($theDt['product_dependency_of_index'][$f]) ? $theDt['product_dependency_of_index'][$f] : 0,
  2261.                                                             'dependencyOnPid' => isset($theDt['product_dependency_of_product_id'][$f]) ? $theDt['product_dependency_of_product_id'][$f] : 0,
  2262.                                                             'dependencyOnSid' => isset($theDt['product_dependency_of_service_id'][$f]) ? $theDt['product_dependency_of_service_id'][$f] : 0,
  2263.                                                             'dependencyOnSegment' => isset($theDt['product_dependency_of_product_index'][$f]) ? $theDt['product_dependency_of_product_index'][$f] : 0,
  2264.                                                             'warranty' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : 0,
  2265.                                                             'origin' => isset($theDt['product_origin'][$f]) ? $theDt['product_origin'][$f] : 0,
  2266.                                                             'origins' => isset($theDt['product_origin'][$f]) ? [$theDt['product_origin'][$f]] : [],
  2267.                                                             'scope' => isset($theDt['product_scope'][$f]) ? $theDt['product_scope'][$f] : 0,
  2268.                                                             'scopeId' => isset($theDt['product_scopeHolderId'][$f]) ? [$theDt['product_scopeHolderId'][$f]] : 0,
  2269.                                                             'scopeName' => isset($theDt['product_scopeHolderName'][$f]) ? [$theDt['product_scopeHolderName'][$f]] : '',
  2270.                                                             'scopeDescription' => isset($theDt['product_scopeDescription'][$f]) ? [$theDt['product_scopeDescription'][$f]] : '',
  2271.                                                             'deliverySchedule' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : [],
  2272.                                                             'deliveryPorts' => isset($theDt['product_delivery_ports'][$f]) ? $theDt['product_delivery_ports'][$f] : [],
  2273.                                                             'billingSchedule' => isset($theDt['product_billing_schedule'][$f]) ? $theDt['product_billing_schedule'][$f] : [],
  2274.                                                             'referenceNo' => isset($theDt['product_reference_price'][$f]) ? $theDt['product_reference_price'][$f] : '',
  2275.                                                             'referenceFiles' => isset($theDt['product_reference_price_file'][$f]) ? $theDt['product_reference_price_file'][$f] : '',
  2276.                                                         );
  2277.                                                         $dt_poka['rowData'][] = $row;
  2278.                                                     }
  2279.                                                 //now the services
  2280.                                                 $theDt = array(
  2281.                                                     'products' => [],
  2282.                                                     'services' => [],
  2283.                                                     'ar_heads' => [],
  2284.                                                 );
  2285.                                                 if (isset($dt_poka['Services']))
  2286.                                                     $theDt $dt_poka['Services'];
  2287.                                                 if (isset($theDt['services']))
  2288.                                                     foreach ($theDt['services'] as $f => $pid) {
  2289.                                                         $unit = isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0;
  2290.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  2291.                                                         if ($indexForThis == -1) {
  2292.                                                             $indexForThis $lastIndex;
  2293.                                                             $lastIndex++;
  2294.                                                         }
  2295.                                                         $unitPrice = isset($theDt['service_unit_price'][$f]) ? $theDt['service_unit_price'][$f] : 0;
  2296.                                                         $totalPrice $unit $unitPrice;
  2297.                                                         $segmentIndex = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : 0;
  2298.                                                         if ($segmentIndex == 'undefined'$segmentIndex 0;
  2299.                                                         if (!is_numeric($segmentIndex)) $segmentIndex 0;
  2300.                                                         if ($oldSegmentSystem == 1)
  2301.                                                             $segmentIndex 1000 $segmentIndex;
  2302.                                                         $sequence = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : '_UNSET_';
  2303.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  2304.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  2305.                                                         if ($sequence == '_UNSET_')
  2306.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2307.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  2308.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2309.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  2310.                                                         $unitSalesPrice = isset($theDt['service_unit_sales_price'][$f]) ? $theDt['service_unit_sales_price'][$f] : $unitPrice;
  2311.                                                         $totalSalesPrice $unit $unitSalesPrice;
  2312.                                                         $marginAmount = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitSalesPrice $unitPrice);
  2313.                                                         $marginRate = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  2314.                                                         $discountAmount = isset($theDt['service_dr'][$f]) ? $theDt['service_dr'][$f] : 0;
  2315.                                                         $discountRate = isset($theDt['service_da'][$f]) ? $theDt['service_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  2316.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  2317.                                                         $taxRate = isset($theDt['service_tax_percentage'][$f]) ? $theDt['service_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  2318.                                                         $taxAmount = isset($theDt['service_tax_amount'][$f]) ? $theDt['service_tax_amount'][$f] : 0;
  2319.                                                         $finalAmount $discountedAmount $taxAmount;
  2320.                                                         $row = array(
  2321.                                                             'type' => 2,//1:product 2=service 4=tools 5:text 6: expense against head
  2322.                                                             'id' => $pid,
  2323.                                                             'index' => $indexForThis,
  2324.                                                             'isForeign' => isset($theDt['is_foreign_service'][$f]) ? $theDt['is_foreign_service'][$f] : 0,
  2325.                                                             'sequence' => $sequence,
  2326.                                                             'segmentIndex' => $segmentIndex,
  2327.                                                             'soItemId' => isset($theDt['service_soItemId'][$f]) ? $theDt['service_soItemId'][$f] : 0,
  2328.                                                             'soItemDelivered' => isset($theDt['service_soItemDelivered'][$f]) ? $theDt['service_soItemDelivered'][$f] : 0,
  2329.                                                             'soItemFound' => isset($theDt['service_soItemFound'][$f]) ? $theDt['service_soItemFound'][$f] : 0,
  2330.                                                             'alias' => isset($theDt['service_alias'][$f]) ? $theDt['service_alias'][$f] : '',
  2331.                                                             'name' => isset($theDt['service_name'][$f]) ? $theDt['service_name'][$f] : '',
  2332.                                                             'note' => isset($theDt['service_note'][$f]) ? $theDt['service_note'][$f] : '',
  2333.                                                             'fdm' => isset($theDt['service_fdm'][$f]) ? $theDt['service_fdm'][$f] : null,
  2334.                                                             'unit' => isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0,
  2335.                                                             'unitTypeId' => isset($theDt['service_unit_type'][$f]) ? $theDt['service_unit_type'][$f] : 0,
  2336.                                                             'unitPrice' => $unitPrice,
  2337.                                                             'totalPrice' => $totalPrice,
  2338.                                                             'unitSalesPrice' => $unitSalesPrice,
  2339.                                                             'totalSalesPrice' => $totalSalesPrice,
  2340.                                                             'marginRate' => $marginRate,
  2341.                                                             'marginAmount' => $marginAmount,
  2342.                                                             'discountRate' => $discountRate,
  2343.                                                             'discountAmount' => $discountAmount,
  2344.                                                             'discountedAmount' => $discountedAmount,
  2345.                                                             'taxRate' => $taxRate,
  2346.                                                             'taxAmount' => $taxAmount,
  2347.                                                             'finalAmount' => $finalAmount,
  2348.                                                             'recurring' => isset($theDt['service_recurring'][$f]) ? $theDt['service_recurring'][$f] : 0,
  2349.                                                             'currency' => isset($theDt['service_currency_id'][$f]) ? $theDt['service_currency_id'][$f] : 0,
  2350.                                                             'currencyText' => isset($theDt['service_currency_text'][$f]) ? $theDt['service_currency_text'][$f] : '',
  2351.                                                             'currencyMultiplyRate' => isset($theDt['service_currency_multiply_rate'][$f]) ? $theDt['service_currency_multiply_rate'][$f] : 1,
  2352.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  2353.                                                             'taxId' => isset($theDt['service_tax_config_id'][$f]) ? $theDt['service_tax_config_id'][$f] : 0,
  2354.                                                             'taxName' => isset($theDt['service_tax_config_text'][$f]) ? $theDt['service_tax_config_text'][$f] : '',
  2355.                                                             'dependencyOnIndex' => isset($theDt['service_dependency_of_index'][$f]) ? $theDt['service_dependency_of_index'][$f] : 0,
  2356.                                                             'dependencyOnPid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
  2357.                                                             'dependencyOnSid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
  2358.                                                             'dependencyOnSegment' => isset($theDt['service_dependency_of_service_index'][$f]) ? $theDt['service_dependency_of_service_index'][$f] : 0,
  2359.                                                             'warranty' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : 0,
  2360.                                                             'origin' => isset($theDt['service_origin'][$f]) ? $theDt['service_origin'][$f] : 0,
  2361.                                                             'origins' => isset($theDt['service_origin'][$f]) ? [$theDt['service_origin'][$f]] : [],
  2362.                                                             'scope' => isset($theDt['service_scope'][$f]) ? $theDt['service_scope'][$f] : 0,
  2363.                                                             'scopeId' => isset($theDt['service_scopeHolderId'][$f]) ? [$theDt['service_scopeHolderId'][$f]] : 0,
  2364.                                                             'scopeName' => isset($theDt['service_scopeHolderName'][$f]) ? [$theDt['service_scopeHolderName'][$f]] : '',
  2365.                                                             'scopeDescription' => isset($theDt['service_scopeDescription'][$f]) ? [$theDt['service_scopeDescription'][$f]] : '',
  2366.                                                             'deliverySchedule' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : [],
  2367.                                                             'deliveryPorts' => isset($theDt['service_delivery_ports'][$f]) ? $theDt['service_delivery_ports'][$f] : [],
  2368.                                                             'billingSchedule' => isset($theDt['service_billing_schedule'][$f]) ? $theDt['service_billing_schedule'][$f] : [],
  2369.                                                             'referenceNo' => isset($theDt['service_reference_price'][$f]) ? $theDt['service_reference_price'][$f] : '',
  2370.                                                             'referenceFiles' => isset($theDt['service_reference_price_file'][$f]) ? $theDt['service_reference_price_file'][$f] : '',
  2371.                                                         );
  2372.                                                         $dt_poka['rowData'][] = $row;
  2373.                                                     }
  2374.                                                 //now accounts /Cost
  2375.                                                 $theDt = array(
  2376.                                                     'products' => [],
  2377.                                                     'services' => [],
  2378.                                                     'ar_heads' => [],
  2379.                                                 );
  2380.                                                 if (isset($dt_poka['ArCosts']))
  2381.                                                     $theDt $dt_poka['ArCosts'];
  2382.                                                 if (isset($theDt['ar_heads']))
  2383.                                                     foreach ($theDt['ar_heads'] as $f => $pid) {
  2384.                                                         $unit = isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0;
  2385.                                                         if (!is_numeric($unit)) $unit 0;
  2386.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  2387.                                                         if ($indexForThis == -1) {
  2388.                                                             $indexForThis $lastIndex;
  2389.                                                             $lastIndex++;
  2390.                                                         }
  2391.                                                         $unitPrice = isset($theDt['ar_unit_price'][$f]) ? $theDt['ar_unit_price'][$f] : 0;
  2392.                                                         if (!is_numeric($unitPrice)) $unitPrice 0;
  2393.                                                         $totalPrice $unit $unitPrice;
  2394.                                                         $segmentIndex = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : 0;
  2395.                                                         if ($oldSegmentSystem == 1)
  2396.                                                             $segmentIndex 1000 $segmentIndex;
  2397.                                                         $sequence = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : '_UNSET_';
  2398.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  2399.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  2400.                                                         if ($sequence == '_UNSET_')
  2401.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2402.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  2403.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2404.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  2405.                                                         $unitSalesPrice = isset($theDt['ar_unit_sales_price'][$f]) ? $theDt['ar_unit_sales_price'][$f] : $unitPrice;
  2406.                                                         $totalSalesPrice $unit $unitSalesPrice;
  2407.                                                         $marginAmount = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitSalesPrice $unitPrice);
  2408.                                                         $marginRate = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  2409.                                                         $discountAmount = isset($theDt['ar_dr'][$f]) ? $theDt['ar_dr'][$f] : 0;
  2410.                                                         $discountRate = isset($theDt['ar_da'][$f]) ? $theDt['ar_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  2411.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  2412.                                                         $taxRate = isset($theDt['ar_tax_percentage'][$f]) ? $theDt['ar_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  2413.                                                         $taxAmount = isset($theDt['ar_tax_amount'][$f]) ? $theDt['ar_tax_amount'][$f] : 0;
  2414.                                                         $finalAmount $discountedAmount $taxAmount;
  2415.                                                         $row = array(
  2416.                                                             'type' => 6,//1:product 2=service 4=tools 5:text 6: expense against head
  2417.                                                             'id' => $pid,
  2418.                                                             'index' => $indexForThis,
  2419.                                                             'isForeign' => isset($theDt['is_foreign_cost'][$f]) ? $theDt['is_foreign_cost'][$f] : 0,
  2420.                                                             'sequence' => $sequence,
  2421.                                                             'segmentIndex' => $segmentIndex,
  2422.                                                             'soItemId' => isset($theDt['ar_soItemId'][$f]) ? $theDt['ar_soItemId'][$f] : 0,
  2423.                                                             'soItemDelivered' => isset($theDt['ar_soItemDelivered'][$f]) ? $theDt['ar_soItemDelivered'][$f] : 0,
  2424.                                                             'soItemFound' => isset($theDt['ar_soItemFound'][$f]) ? $theDt['ar_soItemFound'][$f] : 0,
  2425.                                                             'alias' => isset($theDt['ar_alias'][$f]) ? $theDt['ar_alias'][$f] : '',
  2426.                                                             'name' => isset($theDt['ar_name'][$f]) ? $theDt['ar_name'][$f] : '',
  2427.                                                             'note' => isset($theDt['ar_note'][$f]) ? $theDt['ar_note'][$f] : '',
  2428.                                                             'fdm' => isset($theDt['ar_fdm'][$f]) ? $theDt['ar_fdm'][$f] : null,
  2429.                                                             'unit' => isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0,
  2430.                                                             'unitTypeId' => isset($theDt['ar_unit_type'][$f]) ? $theDt['ar_unit_type'][$f] : 0,
  2431.                                                             'unitPrice' => $unitPrice,
  2432.                                                             'totalPrice' => $totalPrice,
  2433.                                                             'unitSalesPrice' => $unitSalesPrice,
  2434.                                                             'totalSalesPrice' => $totalSalesPrice,
  2435.                                                             'marginRate' => $marginRate,
  2436.                                                             'marginAmount' => $marginAmount,
  2437.                                                             'discountRate' => $discountRate,
  2438.                                                             'discountAmount' => $discountAmount,
  2439.                                                             'discountedAmount' => $discountedAmount,
  2440.                                                             'taxRate' => $taxRate,
  2441.                                                             'taxAmount' => $taxAmount,
  2442.                                                             'finalAmount' => $finalAmount,
  2443.                                                             'recurring' => isset($theDt['ar_recurring'][$f]) ? $theDt['ar_recurring'][$f] : 0,
  2444.                                                             'currency' => isset($theDt['ar_currency_id'][$f]) ? $theDt['ar_currency_id'][$f] : 0,
  2445.                                                             'currencyText' => isset($theDt['ar_currency_text'][$f]) ? $theDt['ar_currency_text'][$f] : '',
  2446.                                                             'currencyMultiplyRate' => isset($theDt['ar_currency_multiply_rate'][$f]) ? $theDt['ar_currency_multiply_rate'][$f] : 1,
  2447.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  2448.                                                             'taxId' => isset($theDt['ar_tax_config_id'][$f]) ? $theDt['ar_tax_config_id'][$f] : 0,
  2449.                                                             'taxName' => isset($theDt['ar_tax_config_text'][$f]) ? $theDt['ar_tax_config_text'][$f] : '',
  2450.                                                             'dependencyOnIndex' => isset($theDt['ar_dependency_of_index'][$f]) ? $theDt['ar_dependency_of_index'][$f] : 0,
  2451.                                                             'dependencyOnPid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
  2452.                                                             'dependencyOnSid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
  2453.                                                             'dependencyOnSegment' => isset($theDt['ar_dependency_of_ar_index'][$f]) ? $theDt['ar_dependency_of_ar_index'][$f] : 0,
  2454.                                                             'warranty' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : 0,
  2455.                                                             'origin' => isset($theDt['ar_origin'][$f]) ? $theDt['ar_origin'][$f] : 0,
  2456.                                                             'origins' => isset($theDt['ar_origin'][$f]) ? [$theDt['ar_origin'][$f]] : [],
  2457.                                                             'scope' => isset($theDt['ar_scope'][$f]) ? $theDt['ar_scope'][$f] : 0,
  2458.                                                             'scopeId' => isset($theDt['ar_scopeHolderId'][$f]) ? [$theDt['ar_scopeHolderId'][$f]] : 0,
  2459.                                                             'scopeName' => isset($theDt['ar_scopeHolderName'][$f]) ? [$theDt['ar_scopeHolderName'][$f]] : '',
  2460.                                                             'scopeDescription' => isset($theDt['ar_scopeDescription'][$f]) ? [$theDt['ar_scopeDescription'][$f]] : '',
  2461.                                                             'deliverySchedule' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : [],
  2462.                                                             'deliveryPorts' => isset($theDt['ar_delivery_ports'][$f]) ? $theDt['ar_delivery_ports'][$f] : [],
  2463.                                                             'billingSchedule' => isset($theDt['ar_billing_schedule'][$f]) ? $theDt['ar_billing_schedule'][$f] : [],
  2464.                                                             'referenceNo' => isset($theDt['ar_reference_price'][$f]) ? $theDt['ar_reference_price'][$f] : '',
  2465.                                                             'referenceFiles' => isset($theDt['ar_reference_price_file'][$f]) ? $theDt['ar_reference_price_file'][$f] : '',
  2466.                                                         );
  2467.                                                         $dt_poka['rowData'][] = $row;
  2468.                                                     }
  2469. //                                                $configJson['debugData'][]=$dt_poka;
  2470.                                             }
  2471.                                             $newSingleSet['rowData'] = $dt_poka['rowData'];
  2472.                                             unset($dt_poka['productSegmentData']);
  2473.                                             unset($dt_poka['serviceSegmentData']);
  2474.                                             unset($dt_poka['Products']);
  2475.                                             unset($dt_poka['Services']);
  2476.                                             $newData[$kho] = $newSingleSet;
  2477.                                         }
  2478.                                         $theDocData->setData(json_encode($newData));
  2479.                                         $em->persist($theDocData);
  2480.                                         $em->flush();
  2481.                                     }
  2482.                                     $tempId 0;
  2483.                                     if ($entityNameHere == 'SalesProposal'$tempId $the_actual_doc->getSalesProposalId();
  2484.                                     if ($entityNameHere == 'ProjectBoq'$tempId $the_actual_doc->getProjectId();
  2485.                                     if ($entityNameHere == 'Opportunity'$tempId $the_actual_doc->getOpportunityId();
  2486.                                     $configJson['debugData'][] = array(
  2487.                                         'entityNameHere' => $entityNameHere,
  2488.                                         'entityId' => $tempId,
  2489.                                         'dt' => $newData,
  2490.                                     );
  2491.                                 }
  2492.                                 $the_actual_doc->setData(null);
  2493.                                 $the_actual_doc->setDocumentDataId($theDocData->getId());
  2494.                                 $em->flush();
  2495.                                 if ($entityNameHere == 'ProjectBoq') {
  2496.                                     $theProj $em->getRepository('ApplicationBundle\\Entity\\Project')
  2497.                                         ->findOneBy(
  2498.                                             array(
  2499.                                                 'projectId' => $the_actual_doc->getProjectId()
  2500.                                             )
  2501.                                         );
  2502.                                     if ($theProj)
  2503.                                         $theProj->setDocumentDataId($the_actual_doc->getDocumentDataId());
  2504.                                     $em->flush();
  2505.                                 }
  2506.                             }
  2507.                         }
  2508.                     }
  2509.                     if ($request->query->get('newDocDataItemSegmentFix'0) == 1) {
  2510.                         $the_actual_docs $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2511.                             ->findBy(
  2512.                                 array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  2513.                                 )
  2514.                             );
  2515.                         foreach ($the_actual_docs as $the_actual_doc) {
  2516.                             //now the data
  2517.                             //first find the docData if available
  2518.                             $theDocData $the_actual_doc;
  2519.                                 $data = [];
  2520.                                 $newData = [];
  2521.                                 $data json_decode($the_actual_doc->getData(), true);
  2522.                                 if ($data == null)
  2523.                                     $data = [];
  2524.                                 if (!empty($data)) {
  2525.                                     $last_key array_key_last($data);
  2526.                                     $lastIndex 0;
  2527.                                     foreach ($data as $kho => $dt_poka) {
  2528.                                         $newSingleSet $dt_poka;
  2529.                                         $newSegmentData = array();
  2530.                                         //unify the ids of segmnent. services will start from 1000+service segmentId for unification
  2531.                                         if (!isset($newSingleSet['itemSegmentData'])) {
  2532.                                             $newSingleSet['itemSegmentData'] = [];
  2533.                                         }
  2534.                                         if ($newSingleSet['itemSegmentData'] == null) {
  2535.                                             $newSingleSet['itemSegmentData'] = [];
  2536.                                         }
  2537.                                         if (empty($newSingleSet['itemSegmentData'])) {
  2538.                                             $gupu = [];
  2539.                                             $newModSeg $gupu;
  2540.                                             $newModSeg['index'] = 0;
  2541.                                             $newModSeg['title'] = 'Items & Services';
  2542.                                             $newModSeg['scfc'] = 0;
  2543.                                             $newModSeg['uomCust'] = '';
  2544.                                             $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  2545.                                             $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  2546.                                             $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  2547.                                             $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  2548.                                             $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  2549.                                             $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  2550.                                             $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  2551.                                             $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  2552.                                             $newSegmentData[] = $newModSeg;
  2553.                                             $newSingleSet['itemSegmentData'] = $newSegmentData;
  2554.                                         }
  2555.                                         $newData[$kho] = $newSingleSet;
  2556.                                     }
  2557.                                     $theDocData->setData(json_encode($newData));
  2558.                                     $em->persist($theDocData);
  2559.                                     $em->flush();
  2560.                                 }
  2561.                             $em->flush();
  2562.                         }
  2563.                     }
  2564.                     if ($request->query->get('convertMarginToMarkupOldDocumentData'0) == 1) {
  2565.                         $the_actual_docs $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2566.                             ->findBy(
  2567.                                 array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  2568.                                 )
  2569.                             );
  2570.                         foreach ($the_actual_docs as $the_actual_doc) {
  2571.                             //now the data
  2572.                             //first find the docData if available
  2573.                             $theDocData = [];
  2574.                             $theDocData json_decode($the_actual_doc->getData(), true);
  2575.                             if ($theDocData == null)
  2576.                                 $theDocData = [];
  2577.                             $entries $theDocData;
  2578.                             foreach ($entries as $jojo => $mod) {
  2579.                                 if (isset($mod['rowData'])) {
  2580.                                     $rows $mod['rowData'];
  2581.                                     if (is_string($rows))
  2582.                                         $rows json_decode($rowstrue);
  2583.                                     if ($rows == null)
  2584.                                         $rows = [];
  2585.                                     foreach ($rows as $indu => $row) {
  2586.                                         if (!is_numeric($row['unitSalesPrice'])) $row['unitSalesPrice'] = 0;
  2587.                                         if (!is_numeric($row['unitPrice'])) $row['unitPrice'] = 0;
  2588.                                         if (!is_numeric($row['marginAmount'])) $row['marginAmount'] = 0;
  2589.                                         if (!isset($row['markupRate'])) {
  2590.                                             $rows[$indu]['markupRate'] = $row['marginRate'];
  2591.                                         }
  2592.                                         $rows[$indu]['marginRate'] = $row['unitSalesPrice'] != 100 $row['marginAmount'] / $row['unitSalesPrice'] : 0;
  2593.                                     }
  2594.                                     $entries[$jojo]['rowData'] = $rows;
  2595.                                 }
  2596.                             }
  2597.                             $the_actual_doc->setData(json_encode($entries));
  2598. //                                $the_actual_doc->setDocumentDataId($theDocData->getId());
  2599.                             $em->flush();
  2600.                         }
  2601.                     }
  2602.                     if ($request->query->get('rectifyTransCurr'0) == 1) {
  2603.                         $query "
  2604.                                     UPDATE `acc_transaction_details` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  2605.                                     UPDATE `acc_transaction_details` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  2606.                                     UPDATE `acc_transactions` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  2607.                                     UPDATE `acc_transactions` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  2608.                                     UPDATE `expense_invoice` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  2609.                                     UPDATE `expense_invoice` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  2610.   
  2611.                      
  2612.                       ";
  2613.                         $stmt $em->getConnection()->executeStatement($query);
  2614.                     }
  2615.                     if ($request->query->get('deepRefresh'0) == 1) {
  2616.                         //new for updating app id
  2617.                         $get_kids_sql "UPDATE `company` set app_id=" $entry['appId'] . " ;
  2618.                         UPDATE `sys_user` set app_id=" $entry['appId'] . " ;";
  2619.                         $get_kids_sql .= "
  2620.                                       UPDATE `inv_products` set default_color_id=0  where default_color_id ='' or default_color_id is null ;
  2621.                                       UPDATE `inv_products` set default_size=0  where default_size ='' or default_size is null ;
  2622.                                         UPDATE `inventory_storage` set color= (select default_color_id from inv_products where inv_products.id=inventory_storage.product_id)
  2623.                                          where inventory_storage.color =0 or inventory_storage.color is null or inventory_storage.color ='' ;
  2624.                                          UPDATE `inventory_storage` set owner_type= 0 where inventory_storage.owner_type is null or inventory_storage.owner_type ='' ;
  2625.                                          UPDATE `inventory_storage` set owner_id= 0 where inventory_storage.owner_id is null or inventory_storage.owner_id ='' ;
  2626.                                          UPDATE `acc_clients` set client_level= 1 where client_level is null or client_level ='' or client_level=0 ;
  2627.                                          UPDATE `acc_clients` set parent_id= 0 where parent_id is null or parent_id ='' ;
  2628.                                          UPDATE `sales_order` set sales_level= 0 where sales_level is null or sales_level ='' ;
  2629.                                          ";
  2630.                         $get_kids_sql .= "                UPDATE `inventory_storage` set color=0 where color='' or color is null;
  2631.                                         UPDATE `inventory_storage` set `size`=0 where `size`='' or size is null;
  2632.                                         UPDATE `inv_item_transaction` set color=0 where color='' or color is null;
  2633.                                         UPDATE `inv_item_transaction` set `size`=0 where `size`='' or size is null;
  2634.                                         UPDATE `inv_closing_balance` set color=0 where color='' or color is null;
  2635.                                         UPDATE `inv_closing_balance` set `size`=0 where `size`='' or size is null;
  2636.                                         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);
  2637.                                         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);
  2638.                                         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);
  2639.                                         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);
  2640.                                         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);
  2641.                                         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);
  2642.                                         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);
  2643.                                         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);
  2644.                                         UPDATE `inventory_storage` set curr_purchase_price= (select curr_purchase_price from inv_products where inv_products.id=inventory_storage.product_id)
  2645.                                          where inventory_storage.curr_purchase_price=0 or inventory_storage.curr_purchase_price is null;
  2646.                                        delete TABLE service_opearation;
  2647.                                        delete TABLE assesment_and_confirmation;
  2648.                                        ";
  2649.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2650.                         $query "SELECT * from  company   where 1";
  2651.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2652. //                        
  2653.                         $results $stmt;
  2654.                         if (empty($results)) {
  2655.                             //insert client level query here
  2656.                             $createdDate = new \DateTime();
  2657.                             $cgEntry $gocEntryObjectList[$gocId];
  2658.                             $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
  2659. (1, '" $cgEntry->getName() . "', '" $cgEntry->getImage() . "'," $cgEntry->getAppId() . ",'" $createdDate->format('Y-m-d H:i:s') . "', '" $cgEntry->getCompanyGroupHash() . "','" $cgEntry->getCompanyGroupUniqueCode() . "',NULL, NULL,1);";
  2660.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2661.                         }
  2662.                         $query "SELECT * from  client_level   where 1";
  2663.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2664. //                        
  2665.                         $results $stmt;
  2666.                         if (empty($results)) {
  2667.                             //insert client level query here
  2668.                             $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
  2669. (1, 'Primary',1, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2670. (2, 'Secondary',2, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2671. (3, 'Tertiary',3, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)
  2672. ;";
  2673.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2674. //                            
  2675.                         }
  2676.                         $query "SELECT * from  sales_level   where 1";
  2677.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2678.                         $results $stmt;
  2679.                         if (empty($results)) {
  2680.                             //insert client level query here
  2681.                             $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
  2682. (1, 'Primary',0, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2683. (2, 'Secondary',1, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2684. (3, 'Tertiary',2, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL);";
  2685.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2686.                         }
  2687.                         $services $em->getRepository('ApplicationBundle\\Entity\\AccService')->findBy(array(
  2688. //                            'serviceId' => $ex_id//for now for stock of goods
  2689. //                    'opening_locked'=>0
  2690.                         ));
  2691.                         foreach ($services as $service) {
  2692.                             $productFdm $service->getProductFdm();
  2693.                             if (strpos($productFdm'P_') !== false)
  2694.                                 $productFdm str_replace('P_''P' $service->getServiceId() . '_'$productFdm);
  2695.                             $service->setProductFdm($productFdm);
  2696.                             $em->flush();
  2697.                         }
  2698.                         $query "SELECT * from  warehouse_action   where 1";
  2699.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2700.                         $results $stmt;
  2701.                         if (!empty($results)) {
  2702.                             //insert client level query here
  2703.                             foreach ($results as $qryResult) {
  2704.                                 $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'];
  2705.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2706.                             }
  2707.                         } else {
  2708.                             foreach (GeneralConstant::$warehouse_action_list as $dt_pika) {
  2709.                                 $get_kids_sql "INSERT INTO `warehouse_action` (`id`, `name`,`company_id`,  `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`)
  2710. VALUES(" $dt_pika['id'] . ", '" $dt_pika['name'] . "', 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)";
  2711.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2712.                             }
  2713. //
  2714.                             $query "SELECT * from  warehouse_action   where 1";
  2715.                             $stmt $em->getConnection()->fetchAllAssociative($query);
  2716.                             $newresults $stmt;
  2717.                             foreach ($newresults as $qryResult) {
  2718.                                 $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'];
  2719.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2720.                             }
  2721.                         }
  2722.                         $modify_product_by_code_ids_table_list = [
  2723.                             'stock_transfer_item',
  2724.                         ];
  2725.                         $modify_product_by_code_ids_field_list = [
  2726.                             'product_by_code_ids'
  2727.                         ];
  2728.                         $modify_product_by_code_sales_code_field_list = [
  2729.                             'sales_code_range'
  2730.                         ];
  2731.                         $modify_product_by_code_item_id_field_list = [
  2732.                             'id'
  2733.                         ];
  2734.                         foreach ($modify_product_by_code_ids_table_list as $mindex => $dt_table_name) {
  2735.                             $get_kids_sql "select * from " $dt_table_name " where " .
  2736.                                 $modify_product_by_code_ids_field_list[$mindex] . " is null  or " .
  2737.                                 $modify_product_by_code_ids_field_list[$mindex] . " =''  or " .
  2738.                                 $modify_product_by_code_ids_field_list[$mindex] . " ='[]' ;";
  2739.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2740.                             $dataList $stmt;
  2741.                             foreach ($dataList as $mdt) {
  2742.                                 $sales_code_range_str $mdt[$modify_product_by_code_sales_code_field_list[$mindex]];
  2743.                                 $sales_code_range = [];
  2744.                                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  2745.                                     $sales_code_range json_decode($sales_code_range_strtrue512JSON_BIGINT_AS_STRING);
  2746.                                 } else {
  2747.                                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  2748.                                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$sales_code_range_str);
  2749.                                     $sales_code_range json_decode($json_without_bigintstrue);
  2750.                                 }
  2751. //                    $sales_code_range= json_decode($entry->getSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  2752.                                 $pbcIds = [];
  2753.                                 if ($sales_code_range == null)
  2754.                                     $sales_code_range = [];
  2755.                                 if (empty($sales_code_range)) {
  2756.                                 } else {
  2757.                                     $get_kids_sql_2 "select * from  product_by_code  where sales_code in ('" implode("','"$sales_code_range) . "');";
  2758.                                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  2759.                                     $dataList $stmt;
  2760.                                     foreach ($dataList as $pbc) {
  2761.                                         $pbcIds[] = $pbc['product_by_code_id'];
  2762.                                     }
  2763.                                 }
  2764.                                 $get_kids_sql_3 "update " $dt_table_name .
  2765.                                     " set  " $modify_product_by_code_ids_field_list[$mindex] . "='" json_encode($pbcIds) . "'" .
  2766.                                     " where " $modify_product_by_code_item_id_field_list[$mindex] . "=" $mdt[$modify_product_by_code_item_id_field_list[$mindex]] . ";";
  2767.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql_3);
  2768.                             }
  2769.                         }
  2770.                         $modify_voucher_date_table_list = [
  2771. //                            'stock_received_note',
  2772. //                            'stock_transfer',
  2773. //                            'stock_consumption_note',
  2774. //                            'fixed_asset_conversion_note',
  2775. //                            'fixed_asset_product'
  2776.                         ];
  2777.                         $modify_date_field_list = [
  2778. //                            'stock_received_note_date',
  2779. //                            'stock_transfer_date',
  2780. //                            'stock_consumption_note_date',
  2781. //                            'fixed_asset_conversion_note_date',
  2782. //                            'fixed_asset_product'
  2783.                         ];
  2784.                         foreach ($modify_voucher_date_table_list as $mindex => $dt_table_name) {
  2785.                             $get_kids_sql "select * from " $dt_table_name " where 1;";
  2786.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2787.                             $dataList $stmt;
  2788.                             foreach ($dataList as $mdt) {
  2789.                                 $curr_v_ids json_decode($mdt['voucher_ids'], true);
  2790.                                 if ($curr_v_ids == null)
  2791.                                     $curr_v_ids = [];
  2792.                                 $date_for_this $mdt[$modify_date_field_list[$mindex]];
  2793.                                 foreach ($curr_v_ids as $vid) {
  2794.                                     //new for updating app id
  2795.                                     $get_kids_sql "UPDATE `acc_transactions`
  2796.                                                           set transaction_date='" $date_for_this "',
  2797.                                                               ledger_hit_date='" $date_for_this "'
  2798.                                                           where transaction_id=" $vid ";
  2799.                                         UPDATE `acc_transactions_details`
  2800.                                                           set transaction_date='" $date_for_this "',
  2801.                                                               ledger_hit_date='" $date_for_this "'
  2802.                                                           where transaction_id=" $vid ";";
  2803.                                     $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2804.                                 }
  2805.                             }
  2806.                         }
  2807.                         $modify_voucher_narration_table_list = [
  2808. //                            'expense_invoice',
  2809. //                            'stock_transfer',
  2810. //                            'stock_consumption_note',
  2811. //                            'fixed_asset_conversion_note',
  2812. //                            'fixed_asset_product'
  2813.                         ];
  2814.                         $modify_narr_field_list = [
  2815. //                            'description',
  2816. //                            'stock_transfer_date',
  2817. //                            'stock_consumption_note_date',
  2818. //                            'fixed_asset_conversion_note_date',
  2819. //                            'fixed_asset_product'
  2820.                         ];
  2821.                         foreach ($modify_voucher_narration_table_list as $mindex => $dt_table_name) {
  2822.                             $get_kids_sql "select * from " $dt_table_name " where 1;";
  2823.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2824.                             $dataList $stmt;
  2825.                             foreach ($dataList as $mdt) {
  2826.                                 $curr_v_ids json_decode($mdt['voucher_ids'], true);
  2827.                                 if ($curr_v_ids == null)
  2828.                                     $curr_v_ids = [];
  2829.                                 $narr_for_this $mdt[$modify_narr_field_list[$mindex]];
  2830.                                 foreach ($curr_v_ids as $vid) {
  2831.                                     //new for updating app id
  2832.                                     $get_kids_sql "UPDATE `acc_transactions`
  2833.                                                           set description='" $narr_for_this "'
  2834.                                                           where transaction_id=" $vid "; ";
  2835.                                     $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2836.                                 }
  2837.                             }
  2838.                         }
  2839.                     }
  2840.                     if ($request->query->get('employeeDetailsToProfile'0) == 1) {
  2841.                         $migrationStats $this->migrateEmployeeDetailsToProfile($em);
  2842.                         $configJson['employeeDetailsToProfile'] = $migrationStats;
  2843.                     }
  2844.                     $get_kids_sql "update `company_group` set `schema_update_pending_flag` =0 where `id`=$gocId;";
  2845.                     $stmt $em_goc->getConnection()->executeStatement($get_kids_sql);
  2846.                     $configJson['success'] = true;
  2847.                     //this is for large amount of goc we will see  later
  2848. //                        file_put_contents($path, json_encode($configJson));//overwrite
  2849. //                        return $this->redirectToRoute('update_database_schema');
  2850.                 }
  2851.             }
  2852.             return new JsonResponse($configJson);
  2853.         } else {
  2854.             return $this->render(
  2855.                 '@System/pages/server_actions.html.twig',
  2856.                 $dtHere
  2857.             );
  2858.         }
  2859.     }
  2860.     public function UpdateRoutesAction(Request $request)
  2861.     {
  2862.         $message "";
  2863.         $gocList = [];
  2864.         $outputList = [];
  2865.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2866.         $appIdFilter = (int)$request->get('appId'$request->get('app_id'0));
  2867.         $em $this->getDoctrine()->getManager('company_group');
  2868.         $em->getConnection()->connect();
  2869.         $connected $em->getConnection()->isConnected();
  2870.         if ($connected)
  2871.             if ($systemType != '_CENTRAL_') {
  2872.                 $findByQuery = array(
  2873.                     'active' => 1
  2874.                 );
  2875.                 if ($appIdFilter 0) {
  2876.                     $findByQuery['appId'] = $appIdFilter;
  2877.                 }
  2878.                 $gocList $this->getDoctrine()->getManager('company_group')
  2879.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  2880.                     ->findBy($findByQuery);
  2881.             }
  2882.         $gocDataList = [];
  2883.         foreach ($gocList as $entry) {
  2884.             $d = array(
  2885.                 'name' => $entry->getName(),
  2886.                 'id' => $entry->getId(),
  2887.                 'dbName' => $entry->getDbName(),
  2888.                 'dbUser' => $entry->getDbUser(),
  2889.                 'dbPass' => $entry->getDbPass(),
  2890.                 'dbHost' => $entry->getDbHost(),
  2891.                 'appId' => $entry->getAppId(),
  2892.                 'companyRemaining' => $entry->getCompanyRemaining(),
  2893.                 'companyAllowed' => $entry->getCompanyAllowed(),
  2894.                 'enabledModuleIdList' => $entry->getEnabledModuleIdList(),
  2895.             );
  2896.             $gocDataList[$entry->getId()] = $d;
  2897.         }
  2898.         $gocDbName '';
  2899.         $gocDbUser '';
  2900.         $gocDbPass '';
  2901.         $gocDbHost '';
  2902.         $gocId 0;
  2903. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  2904.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  2905.         if (!file_exists($config_dir)) {
  2906.             mkdir($config_dir0777true);
  2907.         }
  2908. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  2909. //        $content = file_exists($path) ? file_get_contents($path) : null;
  2910.         $content = [];
  2911.         $configJson = array();
  2912.         if ($content)
  2913.             $configJson json_decode($contenttrue);
  2914.         $configJsonOld $configJson;
  2915. //        if($configJson)
  2916. //        {
  2917. //
  2918. //        }
  2919. //        else
  2920.         {
  2921.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  2922.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  2923.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  2924.             $configJson['initiateDataBaseFlagByGoc'] = array();
  2925.             $configJson['motherLode'] = "http://innobd.com";
  2926.             foreach ($gocDataList as $gocId => $entry) {
  2927.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  2928.             }
  2929.         }
  2930.         //now check if database shcema update is true
  2931. //        if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
  2932.         if (1//temporary overwrite all
  2933.         {
  2934.             //if goclist is not empty switch to each company dbase and schema update
  2935. //            if(!empty($gocDataList))
  2936.             if (1) {
  2937.                 foreach ($gocDataList as $gocId => $entry) {
  2938.                     if ($configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
  2939.                         $connector $this->container->get('application_connector');
  2940.                         $connector->resetConnection(
  2941.                             'default',
  2942.                             $gocDataList[$gocId]['dbName'],
  2943.                             $gocDataList[$gocId]['dbUser'],
  2944.                             $gocDataList[$gocId]['dbPass'],
  2945.                             $gocDataList[$gocId]['dbHost'],
  2946.                             $reset true);
  2947.                         $em $this->getDoctrine()->getManager();
  2948. //                        $iv = '1234567812345678';
  2949. //                        $pass = $hash;
  2950. //
  2951. //                        $str = $str . 'YmLRocksLikeABoss';
  2952. //                        $data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
  2953. //
  2954. //                        $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
  2955. //
  2956.                         //now 1st of all lets get the Existing routes
  2957.                         $extRoutesById = [];
  2958.                         $extRoutesByRoute = [];
  2959.                         $modules $em->getRepository("ApplicationBundle\\Entity\\SysModule")
  2960.                             ->findBy(
  2961.                                 array()
  2962.                             );
  2963.                         $module_data = [];
  2964.                         foreach ($modules as $mod) {
  2965.                             $dt = array(
  2966.                                 'id' => $mod->getModuleId(),
  2967.                                 'route' => $mod->getModuleRoute(),
  2968.                                 'name' => $mod->getModuleName(),
  2969.                                 'parentId' => $mod->getParentId(),
  2970.                                 'level' => $mod->getLevel(),
  2971.                                 'eFA' => $mod->getEnabledForAll(),
  2972.                             );
  2973.                             $extRoutesById[$mod->getModuleId()] = $dt;
  2974.                             $extRoutesByRoute[$mod->getModuleRoute()] = $dt;
  2975.                         }
  2976.                         //now clear the module table
  2977.                         $get_kids_sql "truncate `sys_module` ; ";
  2978.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2979.                         $enabledModuleIds $this->getEnabledModuleIdsForCompanyRouteSync($entry$systemType);
  2980.                         $newRoutes $this->filterModuleRoutesForCompany($enabledModuleIds);
  2981.                         $newRoutesByRoute = [];
  2982.                         foreach ($newRoutes as $mod) {
  2983.                             $new = new SysModule();
  2984.                             $new->setModuleId($mod['id']);
  2985.                             $new->setModuleRoute($mod['route']);
  2986.                             $new->setModuleName($mod['name']);
  2987.                             $new->setParentId($mod['parentId']);
  2988.                             $new->setlevel($mod['level']);
  2989.                             $new->setEnabledForAll($mod['eFA']);
  2990.                             $new->setStatus(isset($mod['status']) ? $mod['status'] : GeneralConstant::ACTIVE);
  2991. //                $new->set(GeneralConstant::ACTIVE);
  2992.                             $em->persist($new);
  2993.                             $newRoutesByRoute[$mod['route']] = $mod;
  2994.                         }
  2995.                         $em->flush();
  2996.                         //now lets get the ext modules for positions
  2997.                         $depPosDefModules $em->getRepository("ApplicationBundle\\Entity\\SysDeptPositionDefaultModule")
  2998.                             ->findBy(
  2999.                                 array()
  3000.                             );
  3001.                         foreach ($depPosDefModules as $defmod) {
  3002.                             $moduleList json_decode($defmod->getModuleIds());
  3003.                             $newModuleList = [];
  3004.                             foreach ($moduleList as $oldId) {
  3005.                                 $newId 0;
  3006.                                 if (isset($extRoutesById[$oldId])) {
  3007.                                     if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
  3008.                                         $newModuleList[] = $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
  3009.                                     }
  3010.                                 }
  3011.                             }
  3012.                             $defmod->setModuleIds(json_encode($newModuleList));
  3013.                             $em->flush();
  3014.                         }
  3015.                         //now users
  3016.                         $users $em->getRepository("ApplicationBundle\\Entity\\SysUser")
  3017.                             ->findBy(
  3018.                                 array()
  3019.                             );
  3020.                         foreach ($users as $defmod) {
  3021.                             $moduleList json_decode($defmod->getModuleIds());
  3022.                             if ($moduleList == null)
  3023.                                 continue;
  3024.                             $newModuleList = [];
  3025.                             foreach ($moduleList as $oldId) {
  3026.                                 $newId 0;
  3027.                                 if (isset($extRoutesById[$oldId])) {
  3028.                                     if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
  3029.                                         $newModuleList[] = $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
  3030.                                     }
  3031.                                 }
  3032.                             }
  3033.                             $defmod->setModuleIds(json_encode($newModuleList));
  3034.                             $em->flush();
  3035.                         }
  3036.                         $module_data = [];
  3037. //                        $tool = new SchemaTool($em);
  3038. //
  3039. //                        $classes = $em->getMetadataFactory()->getAllMetadata();
  3040. ////                    $tool->createSchema($classes);
  3041. //                        $tool->updateSchema($classes);
  3042. //
  3043. //                        //new for updating app id
  3044. //                        $get_kids_sql = "UPDATE `company` set app_id=".$entry['appId']." ;
  3045. //                                        UPDATE `sys_user` set app_id=".$entry['appId']." ;";
  3046. //                        $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  3047. //                        
  3048. //                        
  3049. //
  3050. //                        $configJson['initiateDataBaseFlagByGoc'][$gocId."_".$entry['appId']]=GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3051.                         //this is for large amount of goc we will see  later
  3052. //                        file_put_contents($path, json_encode($configJson));//overwrite
  3053. //                        return $this->redirectToRoute('update_database_schema');
  3054.                     }
  3055.                 }
  3056.             } else {
  3057.                 $em $this->getDoctrine()->getManager();
  3058.                 $tool = new SchemaTool($em);
  3059. //                    $classes = array(
  3060. //                        $em->getClassMetadata('Entities\User'),
  3061. //                        $em->getClassMetadata('Entities\Profile')
  3062. //                    );
  3063.                 $classes $em->getMetadataFactory()->getAllMetadata();
  3064. //                    $tool->createSchema($classes);
  3065.                 $tool->updateSchema($classes);
  3066.             }
  3067.         }
  3068.         $allSchemaUpdateDone 1;
  3069.         foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
  3070.             if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
  3071.                 $allSchemaUpdateDone 0;
  3072.         }
  3073.         if ($allSchemaUpdateDone == 1)
  3074.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3075.         ///last
  3076. //        file_put_contents($path, json_encode($configJson));//overwrite
  3077.         return new Response(json_encode($configJsonOld));
  3078.     }
  3079.     public function CheckTimeStampAction(Request $request)
  3080.     {
  3081.         $message "";
  3082.         $gocList = [];
  3083.         $outputList = [];
  3084.         $toConvertDateStrFromQry $request->query->get('convDate''');
  3085.         $currentRegionalDateStrFromQry $request->query->get('currDate''');
  3086.         $convertedTime MiscActions::ConvertRegionalTimeToServerTime($currentRegionalDateStrFromQry$toConvertDateStrFromQry);
  3087.         $currentServerTime = new \DateTime();
  3088.         $em $this->getDoctrine()->getManager('company_group');
  3089.         $em->getConnection()->connect();
  3090.         ///last
  3091. //        file_put_contents($path, json_encode($configJson));//overwrite
  3092.         return new Response(json_encode(array(
  3093.             'convertedTime' => $convertedTime->format('Y-m-d h:i:s'),
  3094.             'convertedTimeUnix' => $convertedTime->format('U'),
  3095.             'convertedTimeRFC' => $convertedTime->format(DATE_RFC822),
  3096.             'currentServerTime' => $currentServerTime->format('Y-m-d h:i:s'),
  3097.             'currentServerTimeRFC' => $currentServerTime->format(DATE_RFC822),
  3098.             'currentServerTimeUnix' => $currentServerTime->format('U'),
  3099.         )));
  3100.     }
  3101.     public function GetUsersFromCentralServerAction(Request $request$id 0)
  3102.     {
  3103.     }
  3104.     public function UpdateCompanyDataToCentralServerAction(Request $request$id 0)
  3105.     {
  3106.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3107.         $post $request;
  3108.         $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') : []);
  3109.         if ($systemType == '_CENTRAL_') {
  3110.             $em_goc $this->getDoctrine()->getManager('company_group');
  3111.             //            'company_id' => $company->getId(),
  3112.             //                            'app_id' => $entry['appId'],
  3113.             //                            'dark_vibrant' => $company->getDarkVibrant(),
  3114.             //                            'light_vibrant' => $company->getLightVibrant(),
  3115.             //                            'vibrant' => $company->getVibrant(),
  3116.             //                            'company_type' => $company->getCompanyType(),
  3117.             //                            'company_name' => $company->getName(),
  3118.             //                            'company_address' => $company->getAddress(),
  3119.             //                            'company_s_address' => $company->getShippingAddress(),
  3120.             //                            'company_b_address' => $company->getBillingAddress(),
  3121.             //                            'company_image' => $company->getImage(),
  3122.             //                            'company_motto' => $company->getMotto(),
  3123.             //                            'company_i_footer' => $company->getInvoiceFooter(),
  3124.             //                            'company_g_footer' => $company->getGeneralFooter(),
  3125.             //                            'company_tin' => $company->getCompanyTin(),
  3126.             //                            'company_bin' => $company->getCompanyBin(),
  3127.             //                            'company_reg' => $company->getCompanyReg(),
  3128.             //                            'company_tl' => $company->getCompanyTl(),
  3129.             //                            'sms_enabled' => $company->getSmsNotificationEnabled(),
  3130.             //                            'sms_settings' => $company->getSmsSettings(),
  3131.             //                            'file'=>$output
  3132.             $findByQuery = array(
  3133. //                'active' => 1
  3134.                 'appId' => $post->get('app_id')
  3135.             );
  3136.             $goc $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3137.                 ->findOneBy($findByQuery);
  3138.             if (!$goc)
  3139.                 $goc = new CompanyGroup();
  3140.             $goc->setName($post->get('company_name'));
  3141.             $goc->setAppId($post->get('app_id'));
  3142. //            $goc->setCompanyType($post->get('company_type'));
  3143.             $goc->setAddress($post->get('address'));
  3144. //            $goc->setDarkVibrant($post->get('dark_vibrant'));
  3145. //            $goc->setLightVibrant($post->get('light_vibrant'));
  3146. //            $goc->setVibrant($post->get('vibrant'));
  3147.             $goc->setShippingAddress($post->get('s_address'));
  3148.             $goc->setBillingAddress($post->get('b_address'));
  3149.             $goc->setMotto($post->get('motto'));
  3150.             $goc->setInvoiceFooter($post->get('i_footer'));
  3151.             $goc->setGeneralFooter($post->get('g_footer'));
  3152.             $goc->setCompanyReg($post->get('company_reg'''));
  3153.             $goc->setCompanyTin($post->get('company_tin'''));
  3154.             $goc->setCompanyBin($post->get('company_bin'''));
  3155.             $goc->setCompanyTl($post->get('company_tl'''));
  3156.             $goc->setCompanyGroupServerId($post->get('companyGroupServerId'''));
  3157.             $goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress'''));
  3158.             $goc->setCompanyGroupServerPort($post->get('companyGroupServerPort'''));
  3159.             $goc->setCompanyGroupServerHash($post->get('companyGroupServerHash'''));
  3160. //            $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
  3161. //            $goc->setSmsSettings($post->get('sms_settings'));
  3162.             foreach ($request->files as $uploadedFile) {
  3163. //            if($uploadedFile->getImage())
  3164. //                var_dump($uploadedFile->getFile());
  3165. //                var_dump($uploadedFile);
  3166.                 if ($uploadedFile != null) {
  3167.                     $fileName 'company_image' $post->get('app_id') . '.' $uploadedFile->guessExtension();
  3168.                     $path $fileName;
  3169.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  3170.                     if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  3171.                         unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  3172.                     }
  3173.                     if (!file_exists($upl_dir)) {
  3174.                         mkdir($upl_dir0777true);
  3175.                     }
  3176.                     $file $uploadedFile->move($upl_dir$path);
  3177.                     if ($path != "")
  3178.                         $goc->setImage('/uploads/CompanyImage/' $path);
  3179.                 }
  3180.             }
  3181.             $em_goc->persist($goc);
  3182.             $em_goc->flush();
  3183.             return new JsonResponse([]);
  3184.         } else {
  3185.             $em $this->getDoctrine()->getManager('company_group');
  3186.             $em->getConnection()->connect();
  3187.             $connected $em->getConnection()->isConnected();
  3188.             $gocDataList = [];
  3189.             if ($connected) {
  3190.                 $findByQuery = array(
  3191.                     'active' => 1
  3192.                 );
  3193.                 $gocList $this->getDoctrine()->getManager('company_group')
  3194.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3195.                     ->findBy($findByQuery);
  3196.                 foreach ($gocList as $entry) {
  3197.                     $d = array(
  3198.                         'name' => $entry->getName(),
  3199.                         'id' => $entry->getId(),
  3200.                         'image' => $entry->getImage(),
  3201.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3202.                         'companyGroupServerId' => $entry->getCompanyGroupServerId(),
  3203.                         'dbName' => $entry->getDbName(),
  3204.                         'dbUser' => $entry->getDbUser(),
  3205.                         'dbPass' => $entry->getDbPass(),
  3206.                         'dbHost' => $entry->getDbHost(),
  3207.                         'appId' => $entry->getAppId(),
  3208.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3209.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3210.                         'enabledModuleIdList' => $entry->getEnabledModuleIdList(),
  3211.                     );
  3212.                     $gocDataList[$entry->getId()] = $d;
  3213.                 }
  3214.                 foreach ($gocDataList as $gocId => $entry) {
  3215.                     $connector $this->container->get('application_connector');
  3216.                     $connector->resetConnection(
  3217.                         'default',
  3218.                         $gocDataList[$gocId]['dbName'],
  3219.                         $gocDataList[$gocId]['dbUser'],
  3220.                         $gocDataList[$gocId]['dbPass'],
  3221.                         $gocDataList[$gocId]['dbHost'],
  3222.                         $reset true);
  3223.                     $em $this->getDoctrine()->getManager();
  3224.                     $company $this->getDoctrine()
  3225.                         ->getRepository('ApplicationBundle\\Entity\\Company')
  3226.                         ->findOneBy(
  3227.                             array()
  3228.                         );
  3229.                     $output '';
  3230.                     $file $this->container->getParameter('kernel.root_dir') . '/../web' $company->getImage(); //<-- Path could be relative
  3231.                     if (file_exists($file)) {
  3232. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  3233.                         $mime mime_content_type($file);
  3234.                         $info pathinfo($file);
  3235.                         $name $info['basename'];
  3236.                         if (strpos($mime'image') !== false) {
  3237.                             $output = new \CURLFile($file$mime$name);
  3238.                         }
  3239.                     }
  3240.                     $post_fields = array(
  3241.                         'company_id' => $company->getId(),
  3242.                         'app_id' => $entry['appId'],
  3243.                         'dark_vibrant' => $company->getDarkVibrant(),
  3244.                         'light_vibrant' => $company->getLightVibrant(),
  3245.                         'vibrant' => $company->getVibrant(),
  3246.                         'company_type' => $company->getCompanyType(),
  3247.                         'company_name' => $company->getName(),
  3248.                         'address' => $company->getAddress(),
  3249.                         's_address' => $company->getShippingAddress(),
  3250.                         'b_address' => $company->getBillingAddress(),
  3251.                         'company_image' => $company->getImage(),
  3252.                         'motto' => $company->getMotto(),
  3253.                         'i_footer' => $company->getInvoiceFooter(),
  3254.                         'g_footer' => $company->getGeneralFooter(),
  3255.                         'company_tin' => $company->getCompanyTin(),
  3256.                         'company_bin' => $company->getCompanyBin(),
  3257.                         'company_reg' => $company->getCompanyReg(),
  3258.                         'company_tl' => $company->getCompanyTl(),
  3259.                         'sms_enabled' => $company->getSmsNotificationEnabled(),
  3260.                         'sms_settings' => $company->getSmsSettings(),
  3261.                         'companyGroupHash' => $company->getCompanyHash(),
  3262.                         'currentSubscriptionPackageId' => $company->getCurrentSubscriptionPackageId(),
  3263.                         'companyGroupServerId' => $entry['companyGroupServerId'],
  3264.                         'companyGroupServerAddress' => $serverList[$entry['companyGroupServerId']]['absoluteUrl'],
  3265.                         'companyGroupServerHash' => $serverList[$entry['companyGroupServerId']]['serverMarker'],
  3266.                         'companyGroupServerPort' => $request->server->get("SERVER_PORT"),
  3267.                         'file' => $output
  3268.                     );
  3269.                     $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/UpdateCompanyDataToCentralServer';
  3270.                     $curl curl_init();
  3271.                     curl_setopt_array($curl, array(
  3272.                         CURLOPT_RETURNTRANSFER => 1,
  3273.                         CURLOPT_POST => 1,
  3274.                         CURLOPT_URL => $urlToCall,
  3275.                         CURLOPT_CONNECTTIMEOUT => 10,
  3276.                         CURLOPT_SSL_VERIFYPEER => false,
  3277.                         CURLOPT_SSL_VERIFYHOST => false,
  3278.                         CURLOPT_HTTPHEADER => array(),
  3279.                         CURLOPT_POSTFIELDS => $post_fields
  3280.                     ));
  3281.                     $retData curl_exec($curl);
  3282.                     $errData curl_error($curl);
  3283.                     curl_close($curl);
  3284.                 }
  3285.             }
  3286.             return new JsonResponse([]);
  3287.         }
  3288.     }
  3289.     public function GetAppListFromCentralServerAction(Request $request$id 0)
  3290.     {
  3291.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3292.         $appIds $request->get('appIds', []);
  3293.         $appId $request->get('appId'0);
  3294.         if (is_string($appIds)) $appIds json_decode($appIdstrue);
  3295.         if ($appIds == null$appIds = [];
  3296.         if ($appId != 0)
  3297.             $appIds[] = $appId;
  3298.         if ($systemType == '_CENTRAL_') {
  3299.             $em $this->getDoctrine()->getManager('company_group');
  3300.             $em->getConnection()->connect();
  3301.             $connected $em->getConnection()->isConnected();
  3302.             $gocDataList = [];
  3303.             if ($connected) {
  3304.                 $findByQuery = array(
  3305.                     'active' => 1
  3306.                 );
  3307.                 if ($appIds != '_ALL_' && $appIds != [])
  3308.                     $findByQuery['appId'] = $appIds;
  3309.                 $gocList $this->getDoctrine()->getManager('company_group')
  3310.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3311.                     ->findBy($findByQuery);
  3312.                 foreach ($gocList as $entry) {
  3313.                     $d = array(
  3314.                         'name' => $entry->getName(),
  3315.                         'id' => $entry->getId(),
  3316.                         'image' => $entry->getImage(),
  3317.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3318.                         'dbName' => $entry->getDbName(),
  3319.                         'dbUser' => $entry->getDbUser(),
  3320.                         'dbPass' => $entry->getDbPass(),
  3321.                         'dbHost' => $entry->getDbHost(),
  3322.                         'appId' => $entry->getAppId(),
  3323.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3324.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3325.                     );
  3326.                     $gocDataList[$entry->getId()] = $d;
  3327.                 }
  3328.             }
  3329.             return new JsonResponse($gocDataList);
  3330.         } else {
  3331.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/GetAppListFromCentralServer';
  3332.             $curl curl_init();
  3333.             curl_setopt_array($curl, array(
  3334.                 CURLOPT_RETURNTRANSFER => 1,
  3335.                 CURLOPT_URL => $urlToCall,
  3336.                 CURLOPT_CONNECTTIMEOUT => 10,
  3337.                 CURLOPT_SSL_VERIFYPEER => false,
  3338.                 CURLOPT_SSL_VERIFYHOST => false,
  3339.                 CURLOPT_HTTPHEADER => array(
  3340.                     "Accept: application/json",
  3341.                 ),
  3342.                 //                        CURLOPT_USERAGENT => 'InnoPM',
  3343.                 CURLOPT_POSTFIELDS => http_build_query([
  3344.                     'appIds' => $appIds
  3345.                 ])
  3346.             ));
  3347. //        $headers = array(
  3348. //            "Accept: application/json",
  3349. //        );
  3350. //        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  3351. ////for debug only!
  3352. //        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  3353. //        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  3354.             $retData curl_exec($curl);
  3355.             $errData curl_error($curl);
  3356.             curl_close($curl);
  3357.             return new JsonResponse(json_decode($retDatatrue));
  3358.         }
  3359.     }
  3360.     public function GetTaskListForMenuAction(Request $request$id 0)
  3361.     {
  3362.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3363.         $session $request->getSession();
  3364.         $appIds $request->get('appIds', []);
  3365.         $appId $request->get('appId'0);
  3366.         if (is_string($appIds)) $appIds json_decode($appIdstrue);
  3367.         if ($appIds == null$appIds = [];
  3368.         if ($appId != 0)
  3369.             $appIds[] = $appId;
  3370.         if ($systemType == '_CENTRAL_') {
  3371.             $em $this->getDoctrine()->getManager('company_group');
  3372.             $em->getConnection()->connect();
  3373.             $connected $em->getConnection()->isConnected();
  3374.             $gocDataList = [];
  3375.             if ($connected) {
  3376.                 $findByQuery = array(
  3377.                     'active' => 1
  3378.                 );
  3379.                 if ($appIds != '_ALL_' && $appIds != [])
  3380.                     $findByQuery['appId'] = $appIds;
  3381.                 $gocList $this->getDoctrine()->getManager('company_group')
  3382.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3383.                     ->findBy($findByQuery);
  3384.                 foreach ($gocList as $entry) {
  3385.                     $d = array(
  3386.                         'name' => $entry->getName(),
  3387.                         'id' => $entry->getId(),
  3388.                         'image' => $entry->getImage(),
  3389.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3390.                         'dbName' => $entry->getDbName(),
  3391.                         'dbUser' => $entry->getDbUser(),
  3392.                         'dbPass' => $entry->getDbPass(),
  3393.                         'dbHost' => $entry->getDbHost(),
  3394.                         'appId' => $entry->getAppId(),
  3395.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3396.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3397.                     );
  3398.                     $gocDataList[$entry->getId()] = $d;
  3399.                 }
  3400.             }
  3401.             return new JsonResponse($gocDataList);
  3402.         } else {
  3403.             $findByQuery = array(
  3404.                 'userId' => $session->get(UserConstants::USER_ID0)
  3405.             );
  3406.             $employee $this->getDoctrine()->getManager()
  3407.                 ->getRepository("ApplicationBundle\\Entity\\Employee")
  3408.                 ->findOneBy($findByQuery);
  3409.             $assignedTaskList = array();
  3410.             $currentlyWorkingTaskList = array();
  3411.             if ($employee) {
  3412.                 $findByQuery = array(
  3413.                     'assignedTo' => $employee->getEmployeeId(),
  3414.                     'hasChild' => [0null]
  3415.                 );
  3416.                 $assignedTaskListData $this->getDoctrine()->getManager()
  3417.                     ->getRepository("ApplicationBundle\\Entity\\PlanningItem")
  3418.                     ->findBy($findByQuery);
  3419.                 $findByQuery = array(
  3420.                     'employeeId' => $employee->getEmployeeId(),
  3421.                 );
  3422.                 $currentlyWorkingTaskListData $this->getDoctrine()->getManager()
  3423.                     ->getRepository("ApplicationBundle\\Entity\\TaskLog")
  3424.                     ->findBy($findByQuery);
  3425.                 foreach ($assignedTaskListData as $entry) {
  3426.                     $dt = array(
  3427.                         'description' => $entry->getDescription(),
  3428.                         'urgency' => $entry->getUrgency()
  3429.                     );
  3430.                     $assignedTaskList[] = $dt;
  3431.                 }
  3432.                 foreach ($currentlyWorkingTaskListData as $entry) {
  3433.                     $dt = array();
  3434.                     $currentlyWorkingTaskList[] = $dt;
  3435.                 }
  3436.             }
  3437.             return new JsonResponse(array(
  3438.                 'assignedTaskList' => $assignedTaskList,
  3439.                 'currentlyWorkingTaskList' => $currentlyWorkingTaskList,
  3440.             ));
  3441.         }
  3442.     }
  3443.     public function SyncUserToCentralUserAction(Request $request)
  3444.     {
  3445.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3446.         $post $request;
  3447.         $globalIdsByAppIdAndUser = [];
  3448.         if ($systemType == '_CENTRAL_') {
  3449.             $userDataList $request->get('userData', []);
  3450.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  3451.             if ($userDataList == null$userDataList = [];
  3452.             $em_goc $this->getDoctrine()->getManager('company_group');
  3453.             //1st step get all company item ids and then check for global id null if its null then the
  3454. //            return new JsonResponse(
  3455. //                array(
  3456. //                    'userDataList' => $userDataList
  3457. //                )
  3458. //            );
  3459.             ////ITEMGROUPS
  3460.             foreach ($userDataList as $k => $cwa) {
  3461.                 $centralUser $em_goc
  3462.                     ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  3463.                     ->findOneBy(
  3464.                         array(
  3465.                             'applicantId' => $cwa['getGlobalId']
  3466.                         )
  3467.                     );
  3468.                 if ($centralUser) {
  3469.                     $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  3470.                     $centralUser->setLastname($cwa['getLastname'] ?? null);
  3471.                     $centralUser->setEmail($cwa['getEmail'] ?? null);
  3472.                     $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  3473.                     $centralUser->setPhone($cwa['getPhone'] ?? null);
  3474.                     $centralUser->setNid($cwa['getNid'] ?? null);
  3475.                     $centralUser->setSex($cwa['getSex'] ?? null);
  3476.                     $centralUser->setBlood($cwa['getBlood'] ?? null);
  3477.                     $centralUser->setFather($cwa['getFather'] ?? null);
  3478.                     $centralUser->setMother($cwa['getMother'] ?? null);
  3479.                     $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  3480.                     $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  3481.                     $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  3482.                     $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  3483.                     $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  3484.                     $centralUser->setTin($cwa['getTin'] ?? null);
  3485.                     $centralUser->setDept($cwa['getDept'] ?? null);
  3486.                     $centralUser->setDesg($cwa['getDesg'] ?? null);
  3487.                     $centralUser->setBranch($cwa['getBranch'] ?? null);
  3488.                     $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  3489.                     $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  3490.                     $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  3491.                     $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  3492.                     $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  3493.                     $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  3494.                     $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  3495.                 } else {
  3496.                     $qry $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3497.                         ->createQueryBuilder('m')
  3498.                         ->where("m.email like '" $cwa['getEmail'] . "'");
  3499.                     if ($cwa['getOAuthEmail'] != '' && $cwa['getOAuthEmail'] != null)
  3500.                         $qry->orWhere("m.oAuthEmail like '" $cwa['getOAuthEmail'] . "'");
  3501.                     if ($cwa['getPhoneNumber'] != '' && $cwa['getPhoneNumber'] != null)
  3502.                         $qry->orWhere("m.phone like '" $cwa['getPhoneNumber'] . "'");
  3503.                     $targets $qry->getQuery()
  3504.                         ->setMaxResults(1)
  3505.                         ->getResult();
  3506.                     if (!empty($targets))
  3507.                         $centralUser $targets[0];
  3508.                 }
  3509.                 if ($centralUser) {
  3510.                     $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  3511.                     $centralUser->setLastname($cwa['getLastname'] ?? null);
  3512.                     $centralUser->setEmail($cwa['getEmail'] ?? null);
  3513.                     $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  3514.                     $centralUser->setPhone($cwa['getPhone'] ?? null);
  3515.                     $centralUser->setNid($cwa['getNid'] ?? null);
  3516.                     $centralUser->setSex($cwa['getSex'] ?? null);
  3517.                     $centralUser->setBlood($cwa['getBlood'] ?? null);
  3518.                     $centralUser->setFather($cwa['getFather'] ?? null);
  3519.                     $centralUser->setMother($cwa['getMother'] ?? null);
  3520.                     $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  3521.                     $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  3522.                     $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  3523.                     $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  3524.                     $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  3525.                     $centralUser->setTin($cwa['getTin'] ?? null);
  3526.                     $centralUser->setDept($cwa['getDept'] ?? null);
  3527.                     $centralUser->setDesg($cwa['getDesg'] ?? null);
  3528.                     $centralUser->setBranch($cwa['getBranch'] ?? null);
  3529.                     $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  3530.                     $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  3531.                     $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  3532.                     $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  3533.                     $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  3534.                     $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  3535.                     $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  3536.                 } else
  3537.                     $centralUser = new EntityApplicantDetails();
  3538. //
  3539. //                $getters = array_filter(get_class_methods($data), function ($method) {
  3540. //                    return 'get' === substr($method, 0, 3);
  3541. //                });
  3542.                 // Manual mapping starts here
  3543.                 $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  3544.                 $centralUser->setLastname($cwa['getLastname'] ?? null);
  3545.                 $centralUser->setEmail($cwa['getEmail'] ?? null);
  3546.                 $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  3547.                 $centralUser->setPhone($cwa['getPhone'] ?? null);
  3548.                 $centralUser->setNid($cwa['getNid'] ?? null);
  3549.                 $centralUser->setSex($cwa['getSex'] ?? null);
  3550.                 $centralUser->setBlood($cwa['getBlood'] ?? null);
  3551.                 $centralUser->setFather($cwa['getFather'] ?? null);
  3552.                 $centralUser->setMother($cwa['getMother'] ?? null);
  3553.                 $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  3554.                 $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  3555.                 $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  3556.                 $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  3557.                 $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  3558.                 $centralUser->setTin($cwa['getTin'] ?? null);
  3559.                 $centralUser->setDept($cwa['getDept'] ?? null);
  3560.                 $centralUser->setDesg($cwa['getDesg'] ?? null);
  3561.                 $centralUser->setBranch($cwa['getBranch'] ?? null);
  3562.                 $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  3563.                 $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  3564. // Date fields
  3565.                 $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  3566.                 $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  3567.                 $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  3568.                 $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  3569.                 $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  3570. // Continue mapping more fields as needed...
  3571.                 $userAppIds json_decode($centralUser->getUserAppIds(), true);
  3572.                 $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  3573.                 if ($userAppIds == null$userAppIds = [];
  3574.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  3575.                 $userAppIds array_merge($userAppIdsarray_diff([$cwa['getUserAppId']], $userAppIds));
  3576.                 if (!isset($userTypesByAppIds[$cwa['getUserAppId']])) {
  3577.                     $userTypesByAppIds[$cwa['getUserAppId']] = [];
  3578.                 }
  3579.                 if (in_array(1$userTypesByAppIds[$cwa['getUserAppId']]) && $cwa['getUserType'] == 2) {
  3580.                     $userTypesByAppIds[$cwa['getUserAppId']] = array_diff($userTypesByAppIds[$cwa['getUserAppId']], [1]);
  3581.                 }
  3582.                 if (in_array(2$userTypesByAppIds[$cwa['getUserAppId']]) && $cwa['getUserType'] == 1) {
  3583.                     $userTypesByAppIds[$cwa['getUserAppId']] = array_diff($userTypesByAppIds[$cwa['getUserAppId']], [2]);
  3584.                 }
  3585.                 $userTypesByAppIds[$cwa['getUserAppId']] = array_merge($userTypesByAppIds[$cwa['getUserAppId']], array_diff([$cwa['getUserType']], $userTypesByAppIds[$cwa['getUserAppId']]));
  3586. //                $userTypesByAppIds[$cwa['getUserAppId']] = [$cwa['getUserType']];
  3587.                 $userFullName $cwa['getName'];
  3588.                 $userFullNameArr explode(' '$cwa['getName']);
  3589.                 $userFirstName = isset($userFullNameArr[0]) ? $userFullNameArr[0] : '';
  3590.                 $userLastName '';
  3591.                 if (isset($userFullNameArr[1])) {
  3592.                     foreach ($userFullNameArr as $kunky => $chunky) {
  3593.                         if ($kunky != 0) {
  3594.                             $userLastName .= $chunky;
  3595.                         }
  3596.                         if ($kunky count($userFullNameArr) - 1) {
  3597.                             $userLastName .= ' ';
  3598.                         }
  3599.                     }
  3600.                 }
  3601.                 $centralUser->setUserAppIds(json_encode($userAppIds));
  3602.                 $centralUser->setFirstname($userFirstName);
  3603.                 $centralUser->setLastname($userLastName);
  3604.                 $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  3605.                 $em_goc->persist($centralUser);
  3606.                 $em_goc->flush();
  3607.                 $uploadedFile $request->files->get('file_' $cwa['getUserAppId'] . '_' $cwa['getUserId'], null);
  3608.                 {
  3609.                     //            if($uploadedFile->getImage())
  3610.                     //                var_dump($uploadedFile->getFile());
  3611.                     //                var_dump($uploadedFile);
  3612.                     if ($uploadedFile != null) {
  3613.                         $fileName 'user_image' $centralUser->getApplicantId() . '.' $uploadedFile->guessExtension();
  3614.                         $path $fileName;
  3615.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
  3616.                         if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage())) {
  3617.                             unlink($this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage());
  3618.                         }
  3619.                         if (!file_exists($upl_dir)) {
  3620.                             mkdir($upl_dir0777true);
  3621.                         }
  3622.                         $file $uploadedFile->move($upl_dir$path);
  3623.                         if ($path != "")
  3624.                             $centralUser->setImage('uploads/UserImage/' $path);
  3625.                     }
  3626.                 }
  3627.                 $em_goc->flush();
  3628.                 if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
  3629.                     $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
  3630.                 $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
  3631.                     array(
  3632.                         'gid' => $centralUser->getApplicantId()
  3633.                     );
  3634.                 $companies $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
  3635.                     'appId' => $userAppIds
  3636.                 ]);
  3637.                 $globalId $cwa['getGlobalId'];
  3638.                 $userData $userDataList;
  3639.                 $dataByServerId = [];
  3640.                 $gocDataListByAppId = [];
  3641.                 foreach ($companies as $entry) {
  3642.                     $gocDataListByAppId[$entry->getAppId()] = [
  3643.                         'dbName' => $entry->getDbName(),
  3644.                         'dbUser' => $entry->getDbUser(),
  3645.                         'dbPass' => $entry->getDbPass(),
  3646.                         'dbHost' => $entry->getDbHost(),
  3647.                         'serverAddress' => $entry->getCompanyGroupServerAddress(),
  3648.                         'port' => $entry->getCompanyGroupServerPort() ?: 80,
  3649.                         'appId' => $entry->getAppId(),
  3650.                         'serverId' => $entry->getCompanyGroupServerId(),
  3651.                     ];
  3652.                     if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
  3653.                         $dataByServerId[$entry->getCompanyGroupServerId()] = array(
  3654.                             'serverId' => $entry->getCompanyGroupServerId(),
  3655.                             'serverAddress' => $entry->getCompanyGroupServerAddress(),
  3656.                             'port' => $entry->getCompanyGroupServerPort() ?: 80,
  3657.                             'appId' => $userAppIds,
  3658.                             'payload' => array(
  3659.                                 'globalId' => $globalId,
  3660.                                 'appId' => $userAppIds,
  3661.                                 'userData' => $userData,
  3662. //                                      'approvalHash' => $approvalHash
  3663.                             )
  3664.                         );
  3665.                 }
  3666.                 $urls = [];
  3667.                 foreach ($dataByServerId as $entry) {
  3668.                     $serverAddress $entry['serverAddress'];
  3669.                     if (!$serverAddress) continue;
  3670.                     $syncUrl $serverAddress '/ReceiveUserFromCentral';
  3671.                     $payload $entry['payload'];
  3672.                     $curl curl_init();
  3673.                     curl_setopt_array($curl, [
  3674.                         CURLOPT_RETURNTRANSFER => true,
  3675.                         CURLOPT_POST => true,
  3676.                         CURLOPT_URL => $syncUrl,
  3677.                         CURLOPT_CONNECTTIMEOUT => 10,
  3678.                         CURLOPT_SSL_VERIFYPEER => false,
  3679.                         CURLOPT_SSL_VERIFYHOST => false,
  3680.                         CURLOPT_HTTPHEADER => [
  3681.                             'Accept: application/json',
  3682.                             'Content-Type: application/json'
  3683.                         ],
  3684.                         CURLOPT_POSTFIELDS => json_encode($payload)
  3685.                     ]);
  3686.                     $response curl_exec($curl);
  3687.                     $err curl_error($curl);
  3688.                     $httpCode curl_getinfo($curlCURLINFO_HTTP_CODE);
  3689.                     curl_close($curl);
  3690.                     if ($err) {
  3691.                         error_log("ERP Sync Error [Server: {$entry['serverAddress']}]: $err");
  3692.                     } else {
  3693.                         error_log("ERP Sync Success [HTTP $httpCode]: $response");
  3694.                     }
  3695.                 }
  3696.             }
  3697.             return new JsonResponse(
  3698.                 array(
  3699.                     'globalIdsData' => $globalIdsByAppIdAndUser
  3700.                 )
  3701.             );
  3702.         } else {
  3703.             $em $this->getDoctrine()->getManager('company_group');
  3704.             $em->getConnection()->connect();
  3705.             $connected $em->getConnection()->isConnected();
  3706.             $gocDataList = [];
  3707.             $gocDataListByAppId = [];
  3708.             $retDataDebug = array();
  3709.             $appIds $request->get('appIds''_UNSET_');
  3710.             $userIds $request->get('userIds''_UNSET_');
  3711.             if ($connected) {
  3712.                 $findByQuery = array(
  3713.                     'active' => 1
  3714.                 );
  3715.                 if ($appIds !== '_UNSET_')
  3716.                     $findByQuery['appId'] = $appIds;
  3717.                 $gocList $this->getDoctrine()->getManager('company_group')
  3718.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3719.                     ->findBy($findByQuery);
  3720.                 foreach ($gocList as $entry) {
  3721.                     $d = array(
  3722.                         'name' => $entry->getName(),
  3723.                         'id' => $entry->getId(),
  3724.                         'image' => $entry->getImage(),
  3725.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3726.                         'dbName' => $entry->getDbName(),
  3727.                         'dbUser' => $entry->getDbUser(),
  3728.                         'dbPass' => $entry->getDbPass(),
  3729.                         'dbHost' => $entry->getDbHost(),
  3730.                         'appId' => $entry->getAppId(),
  3731.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3732.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3733.                     );
  3734.                     $gocDataList[$entry->getId()] = $d;
  3735.                     $gocDataListByAppId[$entry->getAppId()] = $d;
  3736.                 }
  3737.                 $debugCount 0;
  3738.                 foreach ($gocDataList as $gocId => $entry) {
  3739. //                    if($debugCount>0)
  3740. //                        continue;
  3741.                     $skipSend 1;
  3742.                     $connector $this->container->get('application_connector');
  3743.                     $connector->resetConnection(
  3744.                         'default',
  3745.                         $gocDataList[$gocId]['dbName'],
  3746.                         $gocDataList[$gocId]['dbUser'],
  3747.                         $gocDataList[$gocId]['dbPass'],
  3748.                         $gocDataList[$gocId]['dbHost'],
  3749.                         $reset true);
  3750.                     $em $this->getDoctrine()->getManager();
  3751.                     if ($userIds !== '_UNSET_')
  3752.                         $users $this->getDoctrine()
  3753.                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3754.                             ->findBy(
  3755.                                 array(
  3756.                                     'userId' => $userIds
  3757.                                 )
  3758.                             );
  3759.                     else
  3760.                         $users $this->getDoctrine()
  3761.                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3762.                             ->findBy(
  3763.                                 array()
  3764.                             );
  3765.                     $output '';
  3766.                     $userData = array();
  3767.                     $userFiles = array();
  3768.                     foreach ($users as $user) {
  3769.                         $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage(); //<-- Path could be relative
  3770. //                            $output=$file;
  3771.                         if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  3772. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  3773.                             $mime mime_content_type($file);
  3774.                             $info pathinfo($file);
  3775.                             $name $info['basename'];
  3776.                             if (strpos($mime'image') !== false) {
  3777.                                 $output = new \CURLFile($file$mime$name);
  3778.                             }
  3779.                             $skipSend 0;
  3780.                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  3781.                         } else {
  3782. //                                    unlink($this->container->getParameter('kernel.root_dir') . '/../web'. $centralUser->getImage());
  3783.                             $user->setImage(null);
  3784.                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  3785.                             $em->flush();
  3786.                         }
  3787.                         $getters array_filter(get_class_methods($user), function ($method) {
  3788.                             return 'get' === substr($method03);
  3789.                         });
  3790.                         $userDataSingle = array(//                                'file'=>$output
  3791.                         );
  3792.                         foreach ($getters as $getter) {
  3793.                             if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  3794.                                 continue;
  3795. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  3796. //                                {
  3797. //                                    $userDataSingle[$getter]= $user->{$getter}();
  3798. //                                }
  3799.                             if ($user->{$getter}() instanceof \DateTime) {
  3800.                                 $ggtd $user->{$getter}();
  3801.                                 $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  3802.                             } else
  3803.                                 $userDataSingle[$getter] = $user->{$getter}();
  3804.                         }
  3805.                         $userData[] = $userDataSingle;
  3806.                     }
  3807.                     $retDataDebug[$debugCount] = array(
  3808.                         'skipSend' => $skipSend
  3809.                     );
  3810.                     //now customers
  3811.                     $emailFieldName 'email';
  3812.                     $phoneFieldName 'contact_number';
  3813.                     $query "SELECT * from  acc_clients   where 1=1 ";
  3814.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  3815.                     $results $stmt;
  3816.                     if (!empty($results)) {
  3817.                         foreach ($results as $dt) {
  3818.                             $dt['company_id'] = "1";
  3819.                             $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3820.                             $userDataSingle = array(
  3821.                                 'getUserAppId' => strval(UserConstants::USER_TYPE_CLIENT),
  3822.                                 'getUserName' => 'CID-' str_pad($dt['client_id'], 8'0'STR_PAD_LEFT),
  3823.                                 'getUserId' => $dt['client_id']
  3824.                             );
  3825. //                            $userData[] = $userDataSingle;
  3826.                         }
  3827.                     }
  3828.                     //now suppliers
  3829.                     $emailFieldName 'email';
  3830.                     $phoneFieldName 'contact_number';
  3831.                     $query "SELECT * from  acc_suppliers   where 1=1 ";
  3832.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  3833.                     $results $stmt;
  3834.                     if (!empty($results)) {
  3835.                         foreach ($results as $dt) {
  3836.                             $dt['company_id'] = "1";
  3837.                             $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3838.                             $userDataSingle = array(
  3839.                                 'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
  3840.                                 'userName' => 'SID-' str_pad($dt['supplier_id'], 8'0'STR_PAD_LEFT),
  3841.                                 'userId' => $dt['supplier_id'],
  3842.                             );
  3843. //                            $userData[] = $userDataSingle;
  3844.                         }
  3845.                     }
  3846. //                    if ($skipSend == 0)
  3847.                     {
  3848.                         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  3849.                         $userFiles['userData'] = json_encode($userData);
  3850.                         $curl curl_init();
  3851.                         curl_setopt_array($curl, array(
  3852.                             CURLOPT_RETURNTRANSFER => 1,
  3853.                             CURLOPT_POST => 1,
  3854.                             CURLOPT_URL => $urlToCall,
  3855.                             CURLOPT_CONNECTTIMEOUT => 10,
  3856.                             CURLOPT_SSL_VERIFYPEER => false,
  3857.                             CURLOPT_SSL_VERIFYHOST => false,
  3858. //                            CURLOPT_SAFE_UPLOAD => false,
  3859.                             CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  3860.                             ),
  3861.                             //                        CURLOPT_USERAGENT => 'InnoPM',
  3862. //                            CURLOPT_POSTFIELDS => array(
  3863. //                                'userData'=>json_encode($userData),
  3864. //                                'userFiles'=>$userFiles
  3865. //                            ),
  3866.                             CURLOPT_POSTFIELDS => $userFiles
  3867.                         ));
  3868.                         $retData curl_exec($curl);
  3869.                         $errData curl_error($curl);
  3870.                         curl_close($curl);
  3871.                         $retDataObj json_decode($retDatatrue);
  3872.                         $retDataDebug[$debugCount] = $retDataObj;
  3873.                         if (isset($retDataObj['globalIdsData']))
  3874.                             foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  3875.                                 $connector $this->container->get('application_connector');
  3876.                                 $connector->resetConnection(
  3877.                                     'default',
  3878.                                     $gocDataListByAppId[$app_id]['dbName'],
  3879.                                     $gocDataListByAppId[$app_id]['dbUser'],
  3880.                                     $gocDataListByAppId[$app_id]['dbPass'],
  3881.                                     $gocDataListByAppId[$app_id]['dbHost'],
  3882.                                     $reset true);
  3883.                                 $em $this->getDoctrine()->getManager();
  3884.                                 foreach ($usrList as $sys_id => $globaldata) {
  3885.                                     $user $this->getDoctrine()
  3886.                                         ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3887.                                         ->findOneBy(
  3888.                                             array(
  3889.                                                 'userId' => $sys_id
  3890.                                             )
  3891.                                         );
  3892.                                     if ($user) {
  3893.                                         $user->setGlobalId($globaldata['gid']);
  3894.                                         $em->flush();
  3895.                                     }
  3896.                                 }
  3897.                             }
  3898.                     }
  3899.                     $debugCount++;
  3900.                 }
  3901.             }
  3902.             return new JsonResponse($retDataDebug);
  3903.         }
  3904.     }
  3905.     public function ReceiveUserFromCentralAction(Request $request)
  3906.     {
  3907.         $data json_decode($request->getContent(), true);
  3908.         if (
  3909.             !$data ||
  3910.             !isset($data['globalId']) ||
  3911.             !isset($data['appId']) ||
  3912.             !isset($data['userData'])
  3913.         ) {
  3914.             return new JsonResponse(['success' => false'message' => 'Missing required fields'], 400);
  3915.         }
  3916.         $globalId $data['globalId'];
  3917.         $userDataRaw $data['userData'];
  3918.         if (is_string($userDataRaw)) {
  3919.             $userDataRaw json_decode($userDataRawtrue);
  3920.         }
  3921.         if (!is_array($userDataRaw)) {
  3922.             return new JsonResponse(['success' => false'message' => 'Invalid userData format'], 400);
  3923.         }
  3924.         $userData is_array($userDataRaw[0] ?? null) ? $userDataRaw[0] : $userDataRaw;
  3925.         if (is_string($userData)) {
  3926.             $userData json_decode($userDatatrue);
  3927.         }
  3928.         if (!is_array($userData)) {
  3929.             return new JsonResponse(['success' => false'message' => 'Invalid userData format'], 400);
  3930.         }
  3931.         $companyIds is_array($data['appId']) ? $data['appId'] : [$data['appId']];
  3932.         $em_goc $this->getDoctrine()->getManager('company_group');
  3933.         $companies $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
  3934.             'appId' => $companyIds
  3935.         ]);
  3936.         foreach ($companies as $entry) {
  3937.             $goc = [
  3938.                 'dbName' => $entry->getDbName(),
  3939.                 'dbUser' => $entry->getDbUser(),
  3940.                 'dbPass' => $entry->getDbPass(),
  3941.                 'dbHost' => $entry->getDbHost(),
  3942.                 'serverAddress' => $entry->getCompanyGroupServerAddress(),
  3943.                 'port' => $entry->getCompanyGroupServerPort() ?: 80,
  3944.                 'appId' => $entry->getAppId(),
  3945. //                                 'serverId' => $entry->getServerId(),
  3946.             ];
  3947.             $connector $this->container->get('application_connector');
  3948.             $connector->resetConnection(
  3949.                 'default',
  3950.                 $goc['dbName'],
  3951.                 $goc['dbUser'],
  3952.                 $goc['dbPass'],
  3953.                 $goc['dbHost'],
  3954.                 $reset true
  3955.             );
  3956.             $em $this->getDoctrine()->getManager();
  3957.             $user $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $globalId]);
  3958.             if (!$user) {
  3959.                 return new JsonResponse(['success' => false'message' => 'User not found'], 404);
  3960.             }
  3961. //            $user = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['userId' => $user->getUserId()]);
  3962. //            if (!$user) {
  3963. //                $user = new \ApplicationBundle\Entity\EncryptedSignature();
  3964. //                $user->setUserId($user->getUserId());
  3965. //                $user->setCreatedAt(new \DateTime());
  3966. //            }
  3967.             if (!isset($userData['getFirstname']) && !isset($userData['getFirstName'])) {
  3968.                 if (isset($userData['getName'])) {
  3969.                     $nameStrArr explode(" "$userData['getName']);
  3970.                     $userData['getFirstname'] = isset($nameStrArr[0]) ? $nameStrArr[0] : '';
  3971.                     $userData['getLastname'] = isset($nameStrArr[1]) ? $nameStrArr[1] : '';
  3972.                 }
  3973.                 $userData['getFirstName'] = $userData['getFirstname'];
  3974.                 $userData['getLastName'] = $userData['getLastname'];
  3975.             } else if (!isset($userData['getFirstName'])) {
  3976.                 $userData['getFirstName'] = $userData['getFirstname'];
  3977.                 $userData['getLastName'] = $userData['getLastname'];
  3978.             } else if (!isset($userData['getFirstname'])) {
  3979.                 $userData['getFirstname'] = $userData['getFirstName'];
  3980.                 $userData['getLastname'] = $userData['getLastName'];
  3981.             }
  3982.             $user->setUserName($userData['getFirstname'] . ' ' $userData['getLastname']);
  3983.             $user->setUserCompanyId(1);
  3984.             $user->setGlobalId($globalId);
  3985.             $user->setUserName($userData['getName'] ?? null);
  3986.             $user->setUpdatedAt(new \DateTime());
  3987.             $em->persist($user);
  3988.             $em->flush();
  3989.             $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(['userId' => $user->getUserId()]);
  3990.             if ($employee) {
  3991.                 $employee->setFirstName($userData['getFirstname']);
  3992.                 $employee->setLastName($userData['getLastname']);
  3993.                 $employee->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  3994.                 $em->persist($employee);
  3995.             }
  3996.             if ($employee)
  3997.                 $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  3998.                     ->findOneBy(['id' => $employee->getEmployeeId()]);
  3999.             else
  4000.                 $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4001.                     ->findOneBy(['userId' => $user->getUserId()]);
  4002.             if ($employeeDetails) {
  4003.                 $employeeDetails->setFirstname($userData['getFirstname']);
  4004.                 $employeeDetails->setLastname($userData['getLastname']);
  4005.                 $employeeDetails->setEmail($userData['getEmail']);
  4006.                 $employeeDetails->setPhone($userData['getPhone'] ?? null);
  4007.                 $employeeDetails->setNid($userData['getNid'] ?? null);
  4008.                 $employeeDetails->setSex($userData['getSex'] ?? null);
  4009.                 $employeeDetails->setBlood($userData['getBlood'] ?? null);
  4010.                 $employeeDetails->setFather($userData['getFather'] ?? null);
  4011.                 $employeeDetails->setMother($userData['getMother'] ?? null);
  4012.                 $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  4013.                 $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  4014.                 $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  4015.                 $em->persist($employeeDetails);
  4016.             }
  4017.             $em->flush();
  4018.         }
  4019.         return new JsonResponse(['success' => true'message' => 'User, Employee, and EmployeeDetails updated in all ERP servers']);
  4020.     }
  4021.     public function MergeApplicantGlobalIdOnServerAction(Request $request)
  4022.     {
  4023.         $payload json_decode($request->getContent(), true);
  4024.         if (!is_array($payload)) {
  4025.             $payload $request->request->all();
  4026.         }
  4027.         $oldGlobalId = isset($payload['oldGlobalId']) ? (int)$payload['oldGlobalId'] : 0;
  4028.         $newGlobalId = isset($payload['newGlobalId']) ? (int)$payload['newGlobalId'] : 0;
  4029.         $appIds = isset($payload['appIds']) ? $payload['appIds'] : [];
  4030.         if (is_string($appIds)) {
  4031.             $decoded json_decode($appIdstrue);
  4032.             $appIds is_array($decoded) ? $decoded explode(','$appIds);
  4033.         }
  4034.         if (!is_array($appIds)) {
  4035.             $appIds = [];
  4036.         }
  4037.         $appIds array_values(array_unique(array_filter(array_map('intval'$appIds))));
  4038.         if ($oldGlobalId <= || $newGlobalId <= || empty($appIds)) {
  4039.             return new JsonResponse(['success' => false'message' => 'oldGlobalId, newGlobalId and appIds are required.'], 400);
  4040.         }
  4041.         $emGoc $this->getDoctrine()->getManager('company_group');
  4042.         $companies $emGoc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['appId' => $appIds]);
  4043.         $results = [];
  4044.         foreach ($companies as $entry) {
  4045.             $connector $this->container->get('application_connector');
  4046.             $connector->resetConnection(
  4047.                 'default',
  4048.                 $entry->getDbName(),
  4049.                 $entry->getDbUser(),
  4050.                 $entry->getDbPass(),
  4051.                 $entry->getDbHost(),
  4052.                 $reset true
  4053.             );
  4054.             $em $this->getDoctrine()->getManager();
  4055.             $oldUser $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $oldGlobalId]);
  4056.             $newUser $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $newGlobalId]);
  4057.             $appResult = [
  4058.                 'appId' => (int)$entry->getAppId(),
  4059.                 'oldFound' => $oldUser true false,
  4060.                 'newFound' => $newUser true false,
  4061.                 'mergedIntoExistingUser' => false,
  4062.                 'retaggedOldUser' => false,
  4063.             ];
  4064.             if ($oldUser && $newUser && (int)$oldUser->getUserId() !== (int)$newUser->getUserId()) {
  4065.                 if (!$newUser->getEmail() && $oldUser->getEmail()) {
  4066.                     $newUser->setEmail($oldUser->getEmail());
  4067.                 }
  4068.                 if (!$newUser->getImage() && $oldUser->getImage()) {
  4069.                     $newUser->setImage($oldUser->getImage());
  4070.                 }
  4071.                 if (!$newUser->getName() && $oldUser->getName()) {
  4072.                     $newUser->setName($oldUser->getName());
  4073.                 }
  4074.                 $conn $em->getConnection();
  4075.                 $conn->executeStatement('UPDATE employee SET user_id = :newUserId WHERE user_id = :oldUserId', [
  4076.                     'newUserId' => (int)$newUser->getUserId(),
  4077.                     'oldUserId' => (int)$oldUser->getUserId(),
  4078.                 ]);
  4079.                 $conn->executeStatement('UPDATE employee_details SET user_id = :newUserId WHERE user_id = :oldUserId', [
  4080.                     'newUserId' => (int)$newUser->getUserId(),
  4081.                     'oldUserId' => (int)$oldUser->getUserId(),
  4082.                 ]);
  4083.                 $oldUser->setGlobalId(null);
  4084.                 $oldUser->setStatus(0);
  4085.                 $oldUser->setUserName(($oldUser->getUserName() ?: 'merged_user') . '_merged_' $oldGlobalId);
  4086.                 if ($oldUser->getEmail()) {
  4087.                     $oldUser->setEmail('merged_' $oldGlobalId '_' time() . '@invalid.local');
  4088.                 }
  4089.                 $em->persist($newUser);
  4090.                 $em->persist($oldUser);
  4091.                 $em->flush();
  4092.                 $appResult['mergedIntoExistingUser'] = true;
  4093.             } elseif ($oldUser) {
  4094.                 $oldUser->setGlobalId($newGlobalId);
  4095.                 $em->persist($oldUser);
  4096.                 $em->flush();
  4097.                 $appResult['retaggedOldUser'] = true;
  4098.             }
  4099.             $results[] = $appResult;
  4100.         }
  4101.         return new JsonResponse([
  4102.             'success' => true,
  4103.             'results' => $results,
  4104.         ]);
  4105.     }
  4106.     public function SyncCentralUserToServerAction(Request $request)
  4107.     {
  4108.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4109.         $post $request;
  4110.         $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') : []);
  4111.         $globalIdsByAppIdAndUser = [];
  4112.         if ($systemType == '_CENTRAL_') {
  4113.             $userDataList = [];
  4114.             $retAppIds = [];
  4115.             $appIdList = [];
  4116.             $userIdList = [];
  4117.             $retDataDebug = [];
  4118.             $appIds $request->get('appIds''_UNSET_');
  4119.             if ($appIds != '_UNSET_') {
  4120.                 $appIdList $userIdList explode(','$appIds);;
  4121.                 if ($appIdList == null$appIdList = [];
  4122.             }
  4123.             $userIds $request->get('userIds''_UNSET_');
  4124.             if ($userIds != '_UNSET_') {
  4125.                 $userIdList explode(','$userIds);
  4126.                 if ($userIdList == null$userIdList = [];
  4127.             }
  4128.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  4129.             if ($userDataList == null$userDataList = [];
  4130.             $em_goc $this->getDoctrine()->getManager('company_group');
  4131.             $centralUserQry $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4132.                 ->createQueryBuilder('m')
  4133.                 ->where("1=1");
  4134.             if (!empty($userIdList))
  4135.                 $centralUserQry->andWhere("m.applicantId in (" implode(','$userIdList) . " )");
  4136.             $centralUsers $centralUserQry->getQuery()
  4137.                 ->setMaxResults(1)
  4138.                 ->getResult();
  4139.             ////ITEMGROUPS
  4140.             foreach ($centralUsers as $centralUser) {
  4141.                 if ($centralUser) {
  4142.                 } else {
  4143.                 }
  4144.                 $toSetUserData = [];
  4145.                 $userData = array();
  4146.                 $userFiles = array();
  4147.                 $file $this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage(); //<-- Path could be relative
  4148. //                            $output=$file;
  4149.                 if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($file)) {
  4150. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  4151.                     $mime mime_content_type($file);
  4152.                     $info pathinfo($file);
  4153.                     $name $info['basename'];
  4154.                     if (strpos($mime'image') !== false) {
  4155.                         $output = new \CURLFile($file$mime$name);
  4156.                     }
  4157.                     $skipSend 0;
  4158.                     $userFiles['file_' $centralUser->getApplicantId()] = $output;
  4159.                 } else {
  4160.                     $centralUser->setImage(null);
  4161.                     $userFiles['file_' $centralUser->getApplicantId()] = 'pika';
  4162.                     $em_goc->flush();
  4163.                 }
  4164. //
  4165.                 $getters array_filter(get_class_methods($centralUser), function ($method) {
  4166.                     return 'get' === substr($method03);
  4167.                 });
  4168.                 $userDataSingle = array();
  4169.                 foreach ($getters as $getter) {
  4170.                     if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  4171.                         continue;
  4172. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  4173. //                                {
  4174. //                                    $userDataSingle[$getter]= $user->{$getter}();
  4175. //                                }
  4176.                     if ($centralUser->{$getter}() instanceof \DateTime) {
  4177.                         $ggtd $centralUser->{$getter}();
  4178.                         $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  4179.                     } else
  4180.                         $userDataSingle[$getter] = $centralUser->{$getter}();
  4181.                 }
  4182.                 $userAppIds json_decode($centralUser->getUserAppIds(), true);
  4183.                 if ($userAppIds == null$userAppIds = [];
  4184.                 $appIdList array_merge($appIdListarray_diff($userAppIds$appIdList));
  4185.                 $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  4186.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  4187.                 $userDataSingle['userTypesByAppIds'] = $userTypesByAppIds;
  4188.                 $userDataList[] = $userDataSingle;
  4189.                 $em_goc->persist($centralUser);
  4190.                 $em_goc->flush();
  4191.             }
  4192.             $em_goc->flush();
  4193.             $serverIdsCalledAlready = [];
  4194.             $appList $this->getDoctrine()->getManager('company_group')
  4195.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4196.                 ->findBy(array(
  4197.                         'appId' => $appIdList
  4198.                     )
  4199.                 );
  4200.             $userFiles['userData'] = json_encode($userDataList);
  4201.             foreach ($appList as $app) {
  4202.                 if (!in_array($app->getCompanyGroupServerId(), $serverIdsCalledAlready)) {
  4203.                     if (isset($serverList[$app->getCompanyGroupServerId()])) {
  4204.                         //                    if ($skipSend == 0)
  4205.                         {
  4206.                             $urlToCall $serverList[$app->getCompanyGroupServerId()]['absoluteUrl'] . '/SyncCentralUserToServer';
  4207.                             $curl curl_init();
  4208.                             curl_setopt_array($curl, array(
  4209.                                 CURLOPT_RETURNTRANSFER => 1,
  4210.                                 CURLOPT_POST => 1,
  4211.                                 CURLOPT_URL => $urlToCall,
  4212.                                 CURLOPT_CONNECTTIMEOUT => 10,
  4213.                                 CURLOPT_SSL_VERIFYPEER => false,
  4214.                                 CURLOPT_SSL_VERIFYHOST => false,
  4215.                                 CURLOPT_HTTPHEADER => array(),
  4216.                                 CURLOPT_POSTFIELDS => $userFiles
  4217.                             ));
  4218.                             $retData curl_exec($curl);
  4219.                             $errData curl_error($curl);
  4220.                             curl_close($curl);
  4221.                             $retDataObj json_decode($retDatatrue);
  4222.                             $retDataDebug[] = $retDataObj;
  4223.                         }
  4224.                     }
  4225.                     $serverIdsCalledAlready[] = $app->getCompanyGroupServerId();
  4226.                 }
  4227.             }
  4228. //                if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
  4229. //                    $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
  4230. //
  4231. //                $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
  4232. //                    array(
  4233. //                        'gid' => $centralUser->getApplicantId()
  4234. //                    );
  4235.             return new JsonResponse(
  4236.                 array(
  4237.                     "success" => true,
  4238.                     "retDataDebug" => $retDataDebug,
  4239.                     "serverIdsCalledAlready" => $serverIdsCalledAlready,
  4240.                     "appIdList" => $appIdList,
  4241.                     "userFiles" => $userFiles,
  4242.                     "retAppIds" => $retAppIds,
  4243.                 )
  4244.             );
  4245.         } else {
  4246.             $userDataList $request->get('userData', []);
  4247.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  4248.             if ($userDataList == null$userDataList = [];
  4249.             foreach ($userDataList as $userData) {
  4250.                 $em_goc $this->getDoctrine()->getManager('company_group');
  4251.                 $em $this->getDoctrine()->getManager('company_group');
  4252.                 $em->getConnection()->connect();
  4253.                 $connected $em->getConnection()->isConnected();
  4254.                 $gocDataList = [];
  4255.                 $gocDataListByAppId = [];
  4256.                 $retDataDebug = array();
  4257.                 $appIds json_decode($userData['getUserAppIds'], true);
  4258.                 if ($appIds == null$appIds = [];
  4259.                 $userTypesByAppIds json_decode($userData['getUserTypesByAppIds'], true);
  4260.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  4261.                 $userIds $request->get('userIds''_UNSET_');
  4262.                 if ($connected && !empty($appIds)) {
  4263.                     $findByQuery = array(
  4264.                         'active' => 1
  4265.                     );
  4266.                     $findByQuery['appId'] = $appIds;
  4267.                     $gocList $this->getDoctrine()->getManager('company_group')
  4268.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4269.                         ->findBy($findByQuery);
  4270.                     $imagePathToSet '';
  4271.                     $uploadedFile $request->files->get('file_' $userData['getApplicantId'], null);
  4272.                     {
  4273.                         if ($uploadedFile != null) {
  4274.                             $fileName 'user_image' $userData['getApplicantId'] . '.' $uploadedFile->guessExtension();
  4275.                             $path $fileName;
  4276.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
  4277.                             if (!file_exists($upl_dir)) {
  4278.                                 mkdir($upl_dir0777true);
  4279.                             }
  4280.                             $file $uploadedFile->move($upl_dir$path);
  4281.                             $imagePathToSet 'uploads/UserImage/' $path;
  4282.                         }
  4283.                     }
  4284.                     foreach ($gocList as $entry) {
  4285.                         $d = array(
  4286.                             'name' => $entry->getName(),
  4287.                             'id' => $entry->getId(),
  4288.                             'image' => $entry->getImage(),
  4289.                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  4290.                             'dbName' => $entry->getDbName(),
  4291.                             'dbUser' => $entry->getDbUser(),
  4292.                             'dbPass' => $entry->getDbPass(),
  4293.                             'dbHost' => $entry->getDbHost(),
  4294.                             'appId' => $entry->getAppId(),
  4295.                             'companyRemaining' => $entry->getCompanyRemaining(),
  4296.                             'companyAllowed' => $entry->getCompanyAllowed(),
  4297.                         );
  4298.                         $gocDataList[$entry->getId()] = $d;
  4299.                         $gocDataListByAppId[$entry->getAppId()] = $d;
  4300.                     }
  4301.                     $debugCount 0;
  4302.                     foreach ($gocDataList as $gocId => $entry) {
  4303. //                    if($debugCount>0)
  4304. //                        continue;
  4305.                         $skipSend 1;
  4306.                         $connector $this->container->get('application_connector');
  4307.                         $connector->resetConnection(
  4308.                             'default',
  4309.                             $gocDataList[$gocId]['dbName'],
  4310.                             $gocDataList[$gocId]['dbUser'],
  4311.                             $gocDataList[$gocId]['dbPass'],
  4312.                             $gocDataList[$gocId]['dbHost'],
  4313.                             $reset true);
  4314.                         $em $this->getDoctrine()->getManager();
  4315.                         $user $this->getDoctrine()
  4316.                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  4317.                             ->findOneBy(
  4318.                                 array(
  4319.                                     'globalId' => $userData['getApplicantId']
  4320.                                 )
  4321.                             );
  4322.                         $output '';
  4323.                         if (!$user)
  4324.                             $user = new SysUser();
  4325.                         $user->setGlobalId($userData['getApplicantId']);
  4326.                         $user->setUserAppId($entry['appId']);
  4327.                         $user_type 1;
  4328.                         if (isset($userData['userTypesByAppIds'][$entry['appId']])) {
  4329.                             $user_type $userData['userTypesByAppIds'][$entry['appId']];
  4330.                         }
  4331.                         $user->setUserType($user_type);
  4332.                         $user->setUserAppIdList(json_encode($appIds));
  4333.                         $user->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  4334.                         $user->setStatus(UserConstants::ACTIVE_USER);
  4335.                         if (!isset($userData['getFirstname']) && !isset($userData['getFirstName'])) {
  4336.                             if (isset($userData['getName'])) {
  4337.                                 $nameStrArr explode(" "$userData['getName']);
  4338.                                 $userData['getFirstname'] = isset($nameStrArr[0]) ? $nameStrArr[0] : '';
  4339.                                 $userData['getLastname'] = isset($nameStrArr[1]) ? $nameStrArr[1] : '';
  4340.                             }
  4341.                             $userData['getFirstName'] = $userData['getFirstname'];
  4342.                             $userData['getLastName'] = $userData['getLastname'];
  4343.                         } else if (!isset($userData['getFirstName'])) {
  4344.                             $userData['getFirstName'] = $userData['getFirstname'];
  4345.                             $userData['getLastName'] = $userData['getLastname'];
  4346.                         } else if (!isset($userData['getFirstname'])) {
  4347.                             $userData['getFirstname'] = $userData['getFirstName'];
  4348.                             $userData['getLastname'] = $userData['getLastName'];
  4349.                         }
  4350.                         if (!isset($userData['getName'])) {
  4351.                             $userData['getName'] = $userData['getFirstname'] . ' ' $userData['getLastName'];
  4352.                         }
  4353.                         foreach ($userData as $getter => $value) {
  4354.                             if ($getter == 'getApplicantId')
  4355.                                 continue;
  4356.                             $setMethod str_replace('get''set'$getter);
  4357.                             if (method_exists($user$setMethod)) {
  4358.                                 if ($user->{$getter}() instanceof \DateTime)
  4359.                                     $user->{$setMethod}(new \DateTime($value)); // `foo!`
  4360.                                 else if ($setMethod == 'setUserAppIds') {
  4361.                                 } else
  4362.                                     $user->{$setMethod}($value); // `foo!`
  4363.                             }
  4364.                         }
  4365.                         if ($imagePathToSet != "") {
  4366.                             if ($user->getImage() != $imagePathToSet && $user->getImage() != '' && $user->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage())) {
  4367.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage());
  4368.                             }
  4369.                             $user->setImage($imagePathToSet);
  4370.                         }
  4371.                         $em->persist($user);
  4372.                         $em->flush();
  4373.                         ///new test add employee
  4374.                         ///
  4375.                         $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(['userId' => $user->getUserId()]);
  4376.                         if (!$employee)
  4377.                             $employee = new Employee();
  4378.                         if ($employee) {
  4379.                             $employee->setFirstName($userData['getFirstname']);
  4380.                             $employee->setLastName($userData['getLastname']);
  4381.                             $employee->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  4382.                             $employee->setUserId($user->getUserId());
  4383.                             $em->persist($employee);
  4384.                         }
  4385.                         $em->flush();
  4386.                         if ($employee)
  4387.                             $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4388.                                 ->findOneBy(['id' => $employee->getEmployeeId()]);
  4389.                         else
  4390.                             $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4391.                                 ->findOneBy(['userId' => $user->getUserId()]);
  4392.                         if (!$employeeDetails) {
  4393.                             $employeeDetails = new EmployeeDetails();
  4394.                             $employeeDetails->setEmpType(1);
  4395.                             $employeeDetails->setEmpStatus(1);
  4396.                         }
  4397.                         if ($employeeDetails) {
  4398.                             $employeeDetails->setFirstname($userData['getFirstname']);
  4399.                             $employeeDetails->setLastname($userData['getLastname']);
  4400.                             $employeeDetails->setUsername($userData['getUsername']);
  4401.                             $employeeDetails->setEmail($userData['getEmail']);
  4402.                             $employeeDetails->setPhone($userData['getPhone'] ?? null);
  4403.                             $employeeDetails->setNid($userData['getNid'] ?? null);
  4404.                             $employeeDetails->setSex($userData['getSex'] ?? null);
  4405.                             $employeeDetails->setBlood($userData['getBlood'] ?? null);
  4406.                             $employeeDetails->setFather($userData['getFather'] ?? null);
  4407.                             $employeeDetails->setMother($userData['getMother'] ?? null);
  4408.                             $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  4409.                             $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  4410.                             $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  4411.                             $employeeDetails->setUserId($user->getUserId());
  4412.                             $employeeDetails->setId($employee->getEmployeeId());
  4413.                             $em->persist($employeeDetails);
  4414.                         }
  4415.                         $em->flush();
  4416.                         /// new test end
  4417.                         $debugCount++;
  4418.                         $retDataDebug[$debugCount] = array(
  4419.                             'skipSend' => $skipSend,
  4420.                             'userId' => $user->getUserId(),
  4421.                             'appId' => $user->getUserAppId(),
  4422.                         );
  4423.                     }
  4424.                 }
  4425.             }
  4426.             return new JsonResponse($retDataDebug);
  4427.         }
  4428.     }
  4429.     public function GetUsersByQueryAction(Request $request$id 0)
  4430.     {
  4431.         $message "";
  4432.         $gocList = [];
  4433.         $outputList = [];
  4434.         $queryType '_ANY_';
  4435. //        if ($request->has('queryType'))
  4436.         $queryType $request->get('queryType''_ANY_');
  4437.         $returnData = [];
  4438.         $debugData = [];
  4439.         $returnDataArray = [];
  4440.         $returnDataByServerId = [];
  4441.         $serverId $request->get('serverId'4);
  4442.         $serverUrl $request->get('serverUrl''http://194.195.244.141');
  4443.         $serverPort $request->get('serverPort''');
  4444.         $queryStr $request->get('queryStr''');
  4445.         $queryStrEmail $request->get('quryStrEmail''');
  4446.         $queryStrPhone $request->get('quryStrPhone''');
  4447.         if ($queryStrEmail == '' && $queryStrPhone == '') {
  4448.             $queryStrEmail $queryStr;
  4449.         }
  4450. //        sample
  4451. //        data will be by company id
  4452.         $d = array(
  4453.             'userType' => 2,
  4454.             'userId' => 4,
  4455.             'userName' => 'abc',
  4456.             'loginUserName' => 'CID-abc',
  4457.             'serverId' => $serverId,
  4458.             'serverUrl' => $serverUrl,
  4459.             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4460.             'gocId' => 2,
  4461.             'companyId' => 1,
  4462.             'appId' => 45,
  4463.             'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  4464.             'companyName' => 'HoneyBee Iot Ltd.',
  4465.             'userCompanyIds' => [14],
  4466.             'userAppIds' => [140],
  4467.             'userCompanyList' => [
  4468.                 => [
  4469.                     'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  4470.                     'companyName' => 'HoneyBee IoT Ltd.',
  4471.                 ],
  4472.                 => [
  4473.                     'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  4474.                     'companyName' => 'Nastec Srl',
  4475.                 ]
  4476.             ]
  4477.         );
  4478. //        return new JsonResponse(array(
  4479. //            $d, $d
  4480. //        ));
  4481.         $em $this->getDoctrine()->getManager('company_group');
  4482.         $em->getConnection()->connect();
  4483.         $connected $em->getConnection()->isConnected();
  4484.         if ($connected)
  4485.             $gocList $this->getDoctrine()->getManager('company_group')
  4486.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4487.                 ->findBy(
  4488.                     array(
  4489.                         'active' => 1
  4490.                     )
  4491.                 );
  4492.         $gocDataList = [];
  4493.         foreach ($gocList as $entry) {
  4494.             $d = array(
  4495.                 'name' => $entry->getName(),
  4496.                 'id' => $entry->getId(),
  4497.                 'dbName' => $entry->getDbName(),
  4498.                 'dbUser' => $entry->getDbUser(),
  4499.                 'dbPass' => $entry->getDbPass(),
  4500.                 'dbHost' => $entry->getDbHost(),
  4501.                 'appId' => $entry->getAppId(),
  4502.                 'companyRemaining' => $entry->getCompanyRemaining(),
  4503.                 'companyAllowed' => $entry->getCompanyAllowed(),
  4504.             );
  4505.             $gocDataList[$entry->getId()] = $d;
  4506.         }
  4507.         $gocDbName '';
  4508.         $gocDbUser '';
  4509.         $gocDbPass '';
  4510.         $gocDbHost '';
  4511.         $gocId 0;
  4512. //        $web_root_dir = $this->container->getParameter('kernel.root_dir'). '/../web' ;
  4513.         $web_root_dir $url $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  4514. //        $root_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf';
  4515.         foreach ($gocDataList as $gocId => $entry) {
  4516.             $connector $this->container->get('application_connector');
  4517.             $connector->resetConnection(
  4518.                 'default',
  4519.                 $gocDataList[$gocId]['dbName'],
  4520.                 $gocDataList[$gocId]['dbUser'],
  4521.                 $gocDataList[$gocId]['dbPass'],
  4522.                 $gocDataList[$gocId]['dbHost'],
  4523.                 $reset true);
  4524.             $em $this->getDoctrine()->getManager();
  4525.             $companyList = [];
  4526.             $query "SELECT * from  company   where 1";
  4527.             $stmt $em->getConnection()->fetchAllAssociative($query);
  4528.             $results $stmt;
  4529.             if (!empty($results))
  4530.                 foreach ($results as $dt) {
  4531.                     $companyList[$dt['id']] = $dt;
  4532.                 }
  4533.             else
  4534.                 $companyList = array(
  4535.                     => [
  4536.                         'image' => '',
  4537.                         'name' => 'Company',
  4538.                     ]
  4539.                 );
  4540.             ///SysUSER
  4541.             $fieldName = ($queryType == '_EMAIL_' || $queryType == '_ANY_') ? 'email' 'phone_number';
  4542.             if ($queryStrEmail == '' && $queryStrPhone == '') {
  4543.             } else {
  4544.                 $emailFieldName 'email';
  4545.                 $phoneFieldName 'phone_number';
  4546.                 $userNameFieldName 'user_name';
  4547.                 $query "SELECT * from  sys_user   where 1=1 ";
  4548.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail' " '';
  4549.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%' " '';
  4550.                 $query .= ($queryStr != '') ? " or $userNameFieldName like '$queryStr' " '';
  4551.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  4552.                 $results $stmt;
  4553.                 if (!empty($results)) {
  4554.                     foreach ($results as $dt) {
  4555. //                        if($dt['company_id']==0 || $dt['company_id'] ==null)
  4556.                         $dt['company_id'] = "1";
  4557.                         $user_app_ids json_decode($dt['user_app_id_list'], true);
  4558.                         if ($user_app_ids == null$user_app_ids = [$dt['app_id']];
  4559.                         $user_company_ids json_decode($dt['user_company_id_list'], true);
  4560.                         if ($user_company_ids == null$user_company_ids = [$dt['company_id']];
  4561.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  4562.                         $d = array(
  4563.                             'userType' => $dt['user_type'],
  4564.                             'userName' => $dt['user_name'],
  4565.                             'userId' => $dt['user_id'],
  4566.                             'loginUserName' => $dt['user_name'],
  4567.                             'email' => $dt['email'],
  4568.                             'phone' => $dt['phone_number'],
  4569.                             'serverId' => $serverId,
  4570.                             'serverUrl' => $serverUrl,
  4571.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4572.                             'gocId' => $gocId,
  4573.                             'companyId' => $dt['company_id'],
  4574.                             'appId' => $dt['app_id'],
  4575.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  4576.                             'companyName' => $companyData['name'],
  4577.                             'userCompanyIds' => $user_company_ids,
  4578.                             'userAppIds' => $user_app_ids,
  4579.                             'userCompanyList' => [
  4580.                             ]
  4581.                         );
  4582.                         foreach ($user_company_ids as $cid) {
  4583.                             $d['userCompanyList'][$cid] = [
  4584.                                 'companyLogoUrl' => $web_root_dir $companyList[$cid]['image'],
  4585.                                 'companyName' => $companyList[$cid]['name'],
  4586.                             ];
  4587.                         }
  4588.                         $returnData[] = $d;
  4589.                         $returnDataByServerId[$serverId][] = $d;
  4590.                     }
  4591.                 }
  4592.                 //now customers
  4593.                 $emailFieldName 'email';
  4594.                 $phoneFieldName 'contact_number';
  4595.                 $query "SELECT * from  acc_clients   where 1=1 ";
  4596.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" '';
  4597.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" '';
  4598.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  4599.                 $results $stmt;
  4600.                 if (!empty($results)) {
  4601.                     foreach ($results as $dt) {
  4602.                         $dt['company_id'] = "1";
  4603.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  4604.                         $d = array(
  4605.                             'userType' => strval(UserConstants::USER_TYPE_CLIENT),
  4606.                             'userName' => 'CID-' str_pad($dt['client_id'], 8'0'STR_PAD_LEFT),
  4607.                             'userId' => $dt['client_id'],
  4608.                             'loginUserName' => $dt['username'],
  4609.                             'email' => $dt['email'],
  4610.                             'phone' => $dt['contact_number'],
  4611.                             'serverId' => $serverId,
  4612.                             'serverUrl' => $serverUrl,
  4613.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4614.                             'gocId' => $gocId,
  4615.                             'companyId' => $dt['company_id'],
  4616.                             'appId' => $dt['app_id'],
  4617.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  4618.                             'companyName' => $companyData['name'],
  4619.                             'userCompanyIds' => [],
  4620.                             'userAppIds' => [],
  4621.                             'userCompanyList' => [
  4622.                             ]
  4623.                         );
  4624.                         $returnData[] = $d;
  4625.                         $returnDataByServerId[$serverId][] = $d;
  4626.                     }
  4627.                 }
  4628.                 //now suppliers
  4629.                 $emailFieldName 'email';
  4630.                 $phoneFieldName 'contact_number';
  4631.                 $query "SELECT * from  acc_suppliers   where 1=1 ";
  4632.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" '';
  4633.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" '';
  4634.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  4635.                 $results $stmt;
  4636.                 if (!empty($results)) {
  4637.                     foreach ($results as $dt) {
  4638.                         $dt['company_id'] = "1";
  4639.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  4640.                         $d = array(
  4641.                             'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
  4642.                             'userName' => 'SID-' str_pad($dt['supplier_id'], 8'0'STR_PAD_LEFT),
  4643.                             'userId' => $dt['supplier_id'],
  4644.                             'loginUserName' => $dt['username'],
  4645.                             'email' => $dt['email'],
  4646.                             'phone' => $dt['contact_number'],
  4647.                             'serverId' => $serverId,
  4648.                             'serverUrl' => $serverUrl,
  4649.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4650.                             'gocId' => $gocId,
  4651.                             'companyId' => $dt['company_id'],
  4652.                             'appId' => $dt['app_id'],
  4653.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  4654.                             'companyName' => $companyData['name'],
  4655.                             'userCompanyIds' => [],
  4656.                             'userAppIds' => [],
  4657.                             'userCompanyList' => [
  4658.                             ]
  4659.                         );
  4660.                         $returnData[] = $d;
  4661.                         $returnDataByServerId[$serverId][] = $d;
  4662.                     }
  4663.                 }
  4664.             }
  4665.         }
  4666.         return new JsonResponse(array(
  4667.             'success' => true,
  4668.             'data' => $returnData,
  4669.             'debugData' => $debugData,
  4670.             'dataByServerId' => $returnDataByServerId,
  4671.             'queryType' => $queryType
  4672.         ));
  4673.     }
  4674.     public function GetHoneybeeServerListAction(Request $request$id 0)
  4675.     {
  4676.         $serverList GeneralConstant::$serverList;
  4677.         return new JsonResponse(array(
  4678.             'success' => true,
  4679.             'data' => $serverList,
  4680.         ));
  4681.     }
  4682.     public function ServerListAction()
  4683.     {
  4684.         $serverList GeneralConstant::$serverList;
  4685.         return new JsonResponse(
  4686.             $serverList
  4687.         );
  4688.     }
  4689.     public function widgetModuleListAction()
  4690.     {
  4691.         $widgetsModuleList = [
  4692.             [
  4693.                 'name' => 'Accounts',
  4694.                 'id' => 1,
  4695.                 'hash' => '_ACC_',
  4696.                 'enabled' => true,
  4697.                 'hidden' => true,
  4698.             ],
  4699.             [
  4700.                 'name' => 'Sales',
  4701.                 'id' => 2,
  4702.                 'hash' => '_SL_',
  4703.                 'enabled' => true,
  4704.                 'hidden' => true,
  4705.             ],
  4706.             [
  4707.                 'name' => 'Human Resource',
  4708.                 'id' => 3,
  4709.                 'hash' => '_HRM_',
  4710.                 'enabled' => true,
  4711.                 'hidden' => true,
  4712.             ],
  4713.             [
  4714.                 'name' => 'Admin',
  4715.                 'id' => 4,
  4716.                 'hash' => '_ADM_',
  4717.                 'enabled' => true,
  4718.                 'hidden' => true,
  4719.             ],
  4720.         ];
  4721.         return new JsonResponse(
  4722.             array(
  4723.                 'success' => true,
  4724.                 'widgetModuleList' => $widgetsModuleList
  4725.             )
  4726.         );
  4727.     }
  4728.     public function widgetListAction()
  4729.     {
  4730.         $widgetsList = [
  4731.             [
  4732.                 'id' => 1,
  4733.                 'name' => 'Expense',
  4734.                 'hash' => '_EXP_',
  4735.                 'widgetModuleId' => 1,
  4736.                 'widgetName' => 'Accounts',
  4737.                 'screenName' => '',
  4738.                 'hidden' => true,
  4739.                 'enabled' => true,
  4740.                 'image' => 'https://e7.pngegg.com/pngimages/640/646/png-clipart-expense-management-computer-icons-finance-others-miscellaneous-text.png',
  4741.                 'showOnHome' => true,
  4742.                 'routeList' => [
  4743.                 ]
  4744.             ],
  4745.             [
  4746.                 'id' => 2,
  4747.                 'name' => 'Attendance',
  4748.                 'hash' => '_ATD_',
  4749.                 'widgetModuleId' => 3,
  4750.                 'widgetName' => 'Human Resource',
  4751.                 'screenName' => '',
  4752.                 'hidden' => true,
  4753.                 'enabled' => true,
  4754.                 'image' => 'https://cdn.iconscout.com/icon/premium/png-256-thumb/biometric-attendance-1-1106795.png',
  4755.                 'showOnHome' => true,
  4756.                 'routeList' => [
  4757.                 ]
  4758.             ],
  4759.             [
  4760.                 'id' => 3,
  4761.                 'name' => 'Payment',
  4762.                 'hash' => '_PMT_',
  4763.                 'widgetModuleId' => 1,
  4764.                 'widgetName' => 'Accounts',
  4765.                 'screenName' => '',
  4766.                 'hidden' => true,
  4767.                 'enabled' => true,
  4768.                 'image' => 'https://banner2.cleanpng.com/20180628/gbi/kisspng-management-accounting-accountant-gestin-kontabil-contador-5b356a344f40d2.2788485015302272523246.jpg',
  4769.                 'showOnHome' => true,
  4770.                 'routeList' => [
  4771.                     ["id" => 3"route" => "create_payment_voucher""name" => "Make Payment""parentId" => 3,],
  4772.                     ["id" => 4"route" => "create_receipt_voucher""name" => "Make Receipt""parentId" => 3,],
  4773.                 ]
  4774.             ],
  4775.             [
  4776.                 'id' => 4,
  4777.                 'name' => 'Report',
  4778.                 'hash' => '_RPRT_',
  4779.                 'widgetModuleId' => 1,
  4780.                 'widgetName' => 'Accounts',
  4781.                 'screenName' => '',
  4782.                 'hidden' => true,
  4783.                 'enabled' => true,
  4784.                 'image' => 'https://cdn-icons-png.flaticon.com/512/3093/3093748.png',
  4785.                 'showOnHome' => true,
  4786.                 'routeList' => [
  4787.                 ]
  4788.             ],
  4789.             [
  4790.                 'id' => 5,
  4791.                 'name' => 'Leave Application',
  4792.                 'hash' => '_LEVAPP_',
  4793.                 'widgetModuleId' => 3,
  4794.                 'widgetName' => 'Human Resource',
  4795.                 'screenName' => '',
  4796.                 'hidden' => true,
  4797.                 'enabled' => true,
  4798.                 'image' => 'https://icons.veryicon.com/png/o/transport/easy-office-system-icon-library/leave-request.png',
  4799.                 'showOnHome' => true,
  4800.                 'routeList' => [
  4801.                 ]
  4802.             ],
  4803.             [
  4804.                 'id' => 6,
  4805.                 'name' => 'Fund Requisition',
  4806.                 'hash' => '_FR_',
  4807.                 'widgetModuleId' => 1,
  4808.                 'widgetName' => 'Accounts',
  4809.                 'screenName' => '',
  4810.                 'hidden' => true,
  4811.                 'enabled' => true,
  4812.                 'image' => 'https://www.pngall.com/wp-content/uploads/13/Fund-PNG-Image.png',
  4813.                 'showOnHome' => true,
  4814.                 'routeList' => [
  4815.                 ]
  4816.             ],
  4817.             [
  4818.                 'id' => 7,
  4819.                 'name' => 'My Task',
  4820.                 'hash' => '_MT_',
  4821.                 'widgetModuleId' => 3,
  4822.                 'widgetName' => 'Human Resource',
  4823.                 'screenName' => '',
  4824.                 'hidden' => true,
  4825.                 'enabled' => true,
  4826.                 'image' => 'https://st.depositphotos.com/44273736/54272/v/450/depositphotos_542726218-stock-illustration-premium-download-icon-task-management.jpg',
  4827.                 'showOnHome' => true,
  4828.                 'routeList' => [
  4829.                 ]
  4830.             ],
  4831.             [
  4832.                 'id' => 8,
  4833.                 'name' => 'Fund Transfer',
  4834.                 'hash' => '_FT_',
  4835.                 'widgetModuleId' => 3,
  4836.                 'widgetName' => 'Accounts',
  4837.                 'screenName' => '',
  4838.                 'hidden' => true,
  4839.                 'enabled' => true,
  4840.                 'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
  4841.                 'showOnHome' => true,
  4842.                 'routeList' => [
  4843.                 ]
  4844.             ],
  4845.             [
  4846.                 'id' => 9,
  4847.                 'name' => 'Stock Management',
  4848.                 'hash' => '_SM_',
  4849.                 'widgetModuleId' => 3,
  4850.                 'widgetName' => 'Inventory',
  4851.                 'screenName' => '',
  4852.                 'hidden' => true,
  4853.                 'enabled' => true,
  4854.                 'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
  4855.                 'showOnHome' => true,
  4856.                 'routeList' => [
  4857.                 ]
  4858.             ],
  4859.             [
  4860.                 'id' => 10,
  4861.                 'name' => 'Approval',
  4862.                 'hash' => '_ADM_',
  4863.                 'widgetModuleId' => 4,
  4864.                 'widgetName' => 'Inventory',
  4865.                 'screenName' => '',
  4866.                 'hidden' => true,
  4867.                 'enabled' => true,
  4868.                 'image' => 'https://cdn.icon-icons.com/icons2/907/PNG/512/approve-sign-in-a-black-rounded-square-shape_icon-icons.com_70558.png',
  4869.                 'showOnHome' => true,
  4870.                 'routeList' => [
  4871.                 ]
  4872.             ],
  4873.         ];
  4874.         return new JsonResponse(
  4875.             array(
  4876.                 'success' => true,
  4877.                 'widgetList' => $widgetsList
  4878.             )
  4879.         );
  4880.     }
  4881.     public function addRemoveWidgetAction(Request $request$id 0)
  4882.     {
  4883.         $em $this->getDoctrine()->getManager();
  4884. //        $user = $em->getRepository("ApplicationBundle\\Entity\\SysUser")
  4885. //            ->findBy();
  4886.         return new  JsonResponse(
  4887. //            $user
  4888.         );
  4889.     }
  4890.     public function EncryptParentModulesAction(Request $request$appId 0$companyId 0)
  4891.     {
  4892.         $message "";
  4893.         $gocList = [];
  4894.         $outputList = [];
  4895.         $pmodules = [];
  4896.         if ($request->query->has('modulesByComma'))
  4897.             $pmodules explode(','$request->query->get('modulesByComma'));
  4898.         $iv '1234567812345678';
  4899.         $pass $appId '_' $companyId;
  4900.         //        $method = 'aes-256-cbc';
  4901.         $str json_encode($pmodules);
  4902. //                        $str=$request->query->get('modulesByComma');
  4903.         $str $str 'YmLRocksLikeABoss';
  4904.         $data $str;
  4905.         $data openssl_encrypt($str"AES-128-CBC"$pass0$iv);
  4906.         //        $data=$str;
  4907. //                        $data = openssl_decrypt($data, "AES-128-CBC", $pass, 0, $iv);
  4908. //                        $data = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $pass, 0, $iv);
  4909.         return new Response($data);
  4910. //        return new JsonResponse(array(
  4911. //            'encData'=>$data
  4912. //        ));
  4913.     }
  4914.     public function PrepareDatabaseAction(Request $request)
  4915.     {
  4916.         $message "";
  4917.         $gocList = [];
  4918.         $outputList = [];
  4919.         $em $this->getDoctrine()->getManager('company_group');
  4920.         $em->getConnection()->connect();
  4921.         $connected $em->getConnection()->isConnected();
  4922.         if ($connected)
  4923.             $gocList $this->getDoctrine()->getManager('company_group')
  4924.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4925.                 ->findBy(
  4926.                     array(
  4927.                         'active' => 1
  4928.                     )
  4929.                 );
  4930.         $gocDataList = [];
  4931.         foreach ($gocList as $entry) {
  4932.             $d = array(
  4933.                 'name' => $entry->getName(),
  4934.                 'id' => $entry->getId(),
  4935.                 'dbName' => $entry->getDbName(),
  4936.                 'dbUser' => $entry->getDbUser(),
  4937.                 'dbPass' => $entry->getDbPass(),
  4938.                 'dbHost' => $entry->getDbHost(),
  4939.                 'appId' => $entry->getAppId(),
  4940.                 'companyRemaining' => $entry->getCompanyRemaining(),
  4941.                 'companyAllowed' => $entry->getCompanyAllowed(),
  4942.             );
  4943.             $gocDataList[$entry->getId()] = $d;
  4944.         }
  4945.         $gocDbName '';
  4946.         $gocDbUser '';
  4947.         $gocDbPass '';
  4948.         $gocDbHost '';
  4949.         $gocId 0;
  4950. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  4951.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  4952.         if (!file_exists($config_dir)) {
  4953.             mkdir($config_dir0777true);
  4954.         }
  4955. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  4956. //        $content = file_exists($path) ? file_get_contents($path) : null;
  4957.         $content = [];
  4958.         $configJson = array();
  4959.         if ($content)
  4960.             $configJson json_decode($contenttrue);
  4961.         $configJsonOld $configJson;
  4962. //        if($configJson)
  4963. //        {
  4964. //
  4965. //        }
  4966. //        else
  4967.         {
  4968.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  4969.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  4970.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  4971.             $configJson['initiateDataBaseFlagByGoc'] = array();
  4972.             $configJson['motherLode'] = "http://innobd.com";
  4973.             foreach ($gocDataList as $gocId => $entry) {
  4974.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  4975.             }
  4976.         }
  4977.         //now check if database shcema update is true
  4978. //        if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
  4979.         if (1//temporary overwrite all
  4980.         {
  4981.             //if goclist is not empty switch to each company dbase and schema update
  4982. //            if(!empty($gocDataList))
  4983.             if (1) {
  4984.                 foreach ($gocDataList as $gocId => $entry) {
  4985.                     if ($configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
  4986.                         $connector $this->container->get('application_connector');
  4987.                         $connector->resetConnection(
  4988.                             'default',
  4989.                             $gocDataList[$gocId]['dbName'],
  4990.                             $gocDataList[$gocId]['dbUser'],
  4991.                             $gocDataList[$gocId]['dbPass'],
  4992.                             $gocDataList[$gocId]['dbHost'],
  4993.                             true);
  4994.                         $em $this->getDoctrine()->getManager();
  4995.                         if ($em->getConnection()->isConnected()) {
  4996.                         } else {
  4997.                             $servername $gocDataList[$gocId]['dbHost'];
  4998.                             $username $gocDataList[$gocId]['dbUser'];
  4999.                             $password $gocDataList[$gocId]['dbPass'];
  5000. // Create connection
  5001.                             $conn = new \mysqli($servername$username$password);
  5002. // Check connection
  5003.                             if ($conn->connect_error) {
  5004.                                 die("Connection failed: " $conn->connect_error);
  5005.                             }
  5006. // Create database
  5007.                             $sql "CREATE DATABASE " $gocDataList[$gocId]['dbName'];
  5008.                             if ($conn->query($sql) === TRUE) {
  5009. //                                echo "Database created successfully";
  5010.                             } else {
  5011. //                                echo "Error creating database: " . $conn->error;
  5012.                             }
  5013.                             $conn->close();
  5014.                         }
  5015.                         $connector->resetConnection(
  5016.                             'default',
  5017.                             $gocDataList[$gocId]['dbName'],
  5018.                             $gocDataList[$gocId]['dbUser'],
  5019.                             $gocDataList[$gocId]['dbPass'],
  5020.                             $gocDataList[$gocId]['dbHost'],
  5021.                             true);
  5022.                         $em $this->getDoctrine()->getManager();
  5023.                         $tool = new SchemaTool($em);
  5024.                         $classes $em->getMetadataFactory()->getAllMetadata();
  5025. //                    $tool->createSchema($classes);
  5026.                         $tool->updateSchema($classes);
  5027.                         //new for updating app id
  5028.                         $get_kids_sql "UPDATE `company` set app_id=" $entry['appId'] . " ;
  5029.                                         UPDATE `sys_user` set app_id=" $entry['appId'] . " ;";
  5030.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  5031.                         $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  5032.                         //this is for large amount of goc we will see  later
  5033. //                        file_put_contents($path, json_encode($configJson));//overwrite
  5034. //                        return $this->redirectToRoute('update_database_schema');
  5035.                     }
  5036.                 }
  5037.             } else {
  5038.                 $em $this->getDoctrine()->getManager();
  5039.                 $tool = new SchemaTool($em);
  5040. //                    $classes = array(
  5041. //                        $em->getClassMetadata('Entities\User'),
  5042. //                        $em->getClassMetadata('Entities\Profile')
  5043. //                    );
  5044.                 $classes $em->getMetadataFactory()->getAllMetadata();
  5045. //                    $tool->createSchema($classes);
  5046.                 $tool->updateSchema($classes);
  5047.             }
  5048.         }
  5049.         $allSchemaUpdateDone 1;
  5050.         foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
  5051.             if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
  5052.                 $allSchemaUpdateDone 0;
  5053.         }
  5054.         if ($allSchemaUpdateDone == 1)
  5055.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  5056.         ///last
  5057. //        file_put_contents($path, json_encode($configJson));//overwrite
  5058.         return new Response(json_encode($configJsonOld));
  5059.     }
  5060.     public function ConvertSpecificationToSubCategoryAction(Request $request)
  5061.     {
  5062.         $message "";
  5063.         $gocList = [];
  5064.         $outputList = [];
  5065.         $em $this->getDoctrine()->getManager('company_group');
  5066.         $em->getConnection()->connect();
  5067.         $connected $em->getConnection()->isConnected();
  5068.         if ($connected)
  5069.             $gocList $this->getDoctrine()->getManager('company_group')
  5070.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  5071.                 ->findBy(
  5072.                     array(
  5073.                         'active' => 1
  5074.                     )
  5075.                 );
  5076.         $gocDataList = [];
  5077.         foreach ($gocList as $entry) {
  5078.             $d = array(
  5079.                 'name' => $entry->getName(),
  5080.                 'id' => $entry->getId(),
  5081.                 'dbName' => $entry->getDbName(),
  5082.                 'dbUser' => $entry->getDbUser(),
  5083.                 'dbPass' => $entry->getDbPass(),
  5084.                 'dbHost' => $entry->getDbHost(),
  5085.                 'appId' => $entry->getAppId(),
  5086.                 'companyRemaining' => $entry->getCompanyRemaining(),
  5087.                 'companyAllowed' => $entry->getCompanyAllowed(),
  5088.             );
  5089.             $gocDataList[$entry->getId()] = $d;
  5090.         }
  5091.         $gocDbName '';
  5092.         $gocDbUser '';
  5093.         $gocDbPass '';
  5094.         $gocDbHost '';
  5095.         $gocId 0;
  5096. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  5097.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  5098.         if (!file_exists($config_dir)) {
  5099.             mkdir($config_dir0777true);
  5100.         }
  5101. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  5102. //        $content = file_exists($path) ? file_get_contents($path) : null;
  5103.         $content = [];
  5104.         $configJson = array();
  5105.         if ($content)
  5106.             $configJson json_decode($contenttrue);
  5107.         $configJsonOld $configJson;
  5108. //        if($configJson)
  5109. //        {
  5110. //
  5111. //        }
  5112. //        else
  5113.         {
  5114.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  5115.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  5116.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  5117.             $configJson['initiateDataBaseFlagByGoc'] = array();
  5118.             $configJson['motherLode'] = "http://innobd.com";
  5119.             foreach ($gocDataList as $gocId => $entry) {
  5120.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  5121.             }
  5122.         }
  5123.         $foundClasses = [];
  5124.         if (1) {
  5125.             foreach ($gocDataList as $gocId => $entry) {
  5126.                 $connector $this->container->get('application_connector');
  5127.                 $connector->resetConnection(
  5128.                     'default',
  5129.                     $gocDataList[$gocId]['dbName'],
  5130.                     $gocDataList[$gocId]['dbUser'],
  5131.                     $gocDataList[$gocId]['dbPass'],
  5132.                     $gocDataList[$gocId]['dbHost'],
  5133.                     $reset true);
  5134.                 $em $this->getDoctrine()->getManager();
  5135. /////////////////////////////Now get all entity and if entity has specificationId (and subcatid) the asssign
  5136.                 $query "show tables;";
  5137.                 $query "SELECT DISTINCT TABLE_NAME
  5138.     FROM INFORMATION_SCHEMA.COLUMNS
  5139.     WHERE COLUMN_NAME IN ('specification_id','sub_category_id')
  5140.         AND TABLE_SCHEMA='" $gocDataList[$gocId]['dbName'] . "' ;";
  5141.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  5142.                 $tables $stmt;
  5143.                 foreach ($tables as $tablename) {
  5144. //                        $theClass=new $entity;
  5145.                     $foundClasses[] = $tablename['TABLE_NAME'];
  5146.                     $query "UPDATE " $tablename['TABLE_NAME'] . " set sub_category_id=specification_id where 1;";
  5147.                     $stmt $em->getConnection()->executeStatement($query);
  5148.                     $query "UPDATE " $tablename['TABLE_NAME'] . " set specification_id=null;";
  5149.                     $stmt $em->getConnection()->executeStatement($query);
  5150.                 }
  5151.                 //now add all spec to cat table
  5152.                 $query "TRUNCATE  inv_product_sub_categories";
  5153.                 $stmt $em->getConnection()->executeStatement($query);
  5154.                 $query "SELECT * FROM inv_product_specifications WHERE 1;";
  5155.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  5156.                 $results $stmt;
  5157.                 foreach ($results as $result) {
  5158.                     foreach ($result as $k => $res) {
  5159.                         if ($res == '')
  5160.                             $result[$k] = 'NULL';
  5161.                     }
  5162.                     $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`)
  5163. 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'] . "')";
  5164.                     $stmt $em->getConnection()->executeStatement($query);
  5165.                 }
  5166.                 $query "TRUNCATE  inv_product_specifications";
  5167.                 $stmt $em->getConnection()->executeStatement($query);
  5168.             }
  5169.         }
  5170.         return new Response(json_encode($foundClasses));
  5171.     }
  5172.     public function initiateAdminAction(Request $request)
  5173.     {
  5174.         $em $this->getDoctrine()->getManager();
  5175.         $em_goc $this->getDoctrine()->getManager('company_group');
  5176.         $em_goc->getConnection()->connect();
  5177.         $gocId 0;
  5178.         $appId 0;
  5179.         $gocEnabled 0;
  5180.         if ($this->container->hasParameter('entity_group_enabled'))
  5181.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  5182.         if ($gocEnabled == 1)
  5183.             $connected $em_goc->getConnection()->isConnected();
  5184.         else
  5185.             $connected false;
  5186.         if ($connected)
  5187.             $gocList $em_goc
  5188.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  5189.                 ->findBy(
  5190.                     array(
  5191.                         'active' => 1
  5192.                     )
  5193.                 );
  5194.         $gocDataList = [];
  5195.         $gocDataListForLoginWeb = [];
  5196.         $gocDataListByAppId = [];
  5197.         foreach ($gocList as $entry) {
  5198.             $d = array(
  5199.                 'name' => $entry->getName(),
  5200.                 'id' => $entry->getId(),
  5201.                 'appId' => $entry->getAppId(),
  5202.                 'skipInWebFlag' => $entry->getSkipInWebFlag(),
  5203.                 'skipInAppFlag' => $entry->getSkipInAppFlag(),
  5204.                 'dbName' => $entry->getDbName(),
  5205.                 'dbUser' => $entry->getDbUser(),
  5206.                 'dbPass' => $entry->getDbPass(),
  5207.                 'dbHost' => $entry->getDbHost(),
  5208.                 'companyRemaining' => $entry->getCompanyRemaining(),
  5209.                 'companyAllowed' => $entry->getCompanyAllowed(),
  5210.             );
  5211.             $gocDataList[$entry->getId()] = $d;
  5212.             if (in_array($entry->getSkipInWebFlag(), [0null]))
  5213.                 $gocDataListForLoginWeb[$entry->getId()] = $d;
  5214.             $gocDataListByAppId[$entry->getAppId()] = $d;
  5215.         }
  5216.         if ($request->request->has('gocId') || $request->query->has('gocId')) {
  5217.             $hasGoc 1;
  5218.             $gocId $request->request->get('gocId');
  5219.         }
  5220.         if ($request->request->has('appId') || $request->query->has('appId')) {
  5221.             $hasGoc 1;
  5222.             $appId $request->request->get('appId');
  5223.         }
  5224.         $refRoute $request->request->get('refRoute'$request->query->get('refRoute'''));
  5225.         if ($hasGoc == 1) {
  5226.             if ($gocId != && $gocId != "") {
  5227.                 $appId $gocDataList[$gocId]['appId'];
  5228.                 $connector $this->container->get('application_connector');
  5229.                 $connector->resetConnection(
  5230.                     'default',
  5231.                     $gocDataList[$gocId]['dbName'],
  5232.                     $gocDataList[$gocId]['dbUser'],
  5233.                     $gocDataList[$gocId]['dbPass'],
  5234.                     $gocDataList[$gocId]['dbHost'],
  5235.                     $reset true
  5236.                 );
  5237.             } else if ($appId != && $appId != "") {
  5238.                 $gocDbName $gocDataListByAppId[$appId]['dbName'];
  5239.                 $gocDbUser $gocDataListByAppId[$appId]['dbUser'];
  5240.                 $gocDbPass $gocDataListByAppId[$appId]['dbPass'];
  5241.                 $gocDbHost $gocDataListByAppId[$appId]['dbHost'];
  5242.                 $gocId $gocDataListByAppId[$appId]['id'];
  5243.                 $connector $this->container->get('application_connector');
  5244.                 $connector->resetConnection(
  5245.                     'default',
  5246.                     $gocDbName,
  5247.                     $gocDbUser,
  5248.                     $gocDbPass,
  5249.                     $gocDbHost,
  5250.                     $reset true
  5251.                 );
  5252.             }
  5253.         }
  5254.         $userName $request->request->get('username'$request->query->get('username''admin'));
  5255.         $name $request->request->get('name'$request->query->get('name''System Admin'));
  5256.         $password $request->request->get('password'$request->query->get('password''admin'));
  5257.         $email $request->request->get('email'$request->query->get('email''admin'));
  5258.         $encodedPassword $this->container->get('app.legacy_password_service')->hashWithSalt($password$userName);
  5259.         $companyIds $request->request->get('companyIds'$request->query->get('companyIds', [1]));
  5260.         $branchIds $request->request->get('branchIds'$request->query->get('branchIds', [1]));
  5261.         $appIds $request->request->get('appIds'$request->query->get('appIds', [$appId]));
  5262.         $freshFlag $request->request->get('fresh'$request->query->get('fresh'1));
  5263.         if ($freshFlag == 1) {
  5264.             $query "DELETE FROM sys_user WHERE user_type=1";
  5265.             $stmt $em->getConnection()->executeStatement($query);
  5266.         }
  5267.         $message $this->get('user_module')->addNewUser(
  5268.             $name,
  5269.             $email,
  5270.             $userName,
  5271.             $password,
  5272.             '',
  5273.             0,
  5274.             1,
  5275.             UserConstants::USER_TYPE_SYSTEM,
  5276.             $companyIds,
  5277.             $branchIds,
  5278.             '',
  5279.             "",
  5280.             1
  5281.         );
  5282.         $companyData $message[2];
  5283.         if ($message[0] == 'success') {
  5284.             $oAuthData = [
  5285.                 'email' => $email,
  5286.                 'uniqueId' => '',
  5287.                 'image' => '',
  5288.                 'emailVerified' => '',
  5289.                 'name' => $name,
  5290.                 'type' => '0',
  5291.                 'token' => '',
  5292.             ];
  5293.             if (GeneralConstant::EMAIL_ENABLED == 1) {
  5294.                 $bodyHtml '';
  5295.                 $bodyTemplate '@Application/email/templates/userRegistrationCompleteHoneybee.html.twig';
  5296.                 $bodyData = array(
  5297.                     'name' => $name,
  5298.                     'email' => $email,
  5299.                     'password' => $password,
  5300.                 );
  5301.                 $attachments = [];
  5302.                 $forwardToMailAddress $email;
  5303.                 if (filter_var($forwardToMailAddressFILTER_VALIDATE_EMAIL)) {
  5304. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  5305.                     $new_mail $this->get('mail_module');
  5306.                     $new_mail->sendMyMail(array(
  5307.                         'senderHash' => '_CUSTOM_',
  5308.                         //                        'senderHash'=>'_CUSTOM_',
  5309.                         'forwardToMailAddress' => $forwardToMailAddress,
  5310.                         'subject' => 'Welcome to Honeybee Ecosystem ',
  5311. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  5312.                         'attachments' => $attachments,
  5313.                         'toAddress' => $forwardToMailAddress,
  5314.                         'fromAddress' => 'accounts@ourhoneybee.eu',
  5315.                         'userName' => 'accounts@ourhoneybee.eu',
  5316.                         'password' => 'Honeybee@0112',
  5317.                         'smtpServer' => 'smtp.hostinger.com',
  5318.                         'smtpPort' => 465,
  5319. //                            'emailBody' => $bodyHtml,
  5320.                         'mailTemplate' => $bodyTemplate,
  5321.                         'templateData' => $bodyData,
  5322. //                        'embedCompanyImage' => 1,
  5323. //                        'companyId' => $companyId,
  5324. //                        'companyImagePath' => $company_data->getImage()
  5325.                     ));
  5326.                 }
  5327.             }
  5328. //            if ($request->request->get('remoteVerify', 0) == 1)
  5329. ////                if(1)
  5330. //                return new JsonResponse(array(
  5331. //                    'success' => true,
  5332. //                    'successStr' => 'Account Created Successfully',
  5333. //                    'id' => $newApplicant->getApplicantId(),
  5334. //                    'oAuthData' => $oAuthData,
  5335. //                    'refRoute' => $refRoute,
  5336. //                    'remoteVerify' => 1,
  5337. //                ));
  5338. //            else
  5339. //                return $this->redirectToRoute("user_login", [
  5340. //                    'id' => $newApplicant->getApplicantId(),
  5341. //                    'oAuthData' => $oAuthData,
  5342. //                    'refRoute' => $refRoute,
  5343. //
  5344. //                ]);
  5345.             $bodyHtml '';
  5346.             $bodyTemplate '@Application/email/user/registration.html.twig';
  5347.             $bodyData = array(
  5348.                 'name' => $request->request->get('name'),
  5349.                 'companyData' => $companyData,
  5350.                 'userName' => $request->request->get('username'),
  5351.                 'password' => $request->request->get('password'),
  5352.             );
  5353.             $attachments = [];
  5354. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  5355.             $new_mail $this->get('mail_module');
  5356.             $new_mail->sendMyMail(array(
  5357.                 'senderHash' => '_USER_MANAGEMENT_',
  5358.                 //                        'senderHash'=>'_CUSTOM_',
  5359.                 'forwardToMailAddress' => $request->request->get('email'),
  5360.                 'subject' => 'User Registration on HoneyBee Ecosystem under Company ' $companyData->getName(),
  5361.                 'fileName' => '',
  5362.                 'attachments' => $attachments,
  5363.                 'toAddress' => $request->request->get('email'),
  5364. //                        'fromAddress'=>'sales@entity.innobd.com',
  5365. //                        'userName'=>'sales@entity.innobd.com',
  5366. //                        'password'=>'Y41dh8g0112',
  5367. //                        'smtpServer'=>'smtp.hostinger.com',
  5368. //                        'smtpPort'=>587,
  5369. //                        'emailBody'=>$bodyHtml,
  5370.                 'mailTemplate' => $bodyTemplate,
  5371.                 'templateData' => $bodyData,
  5372.                 'embedCompanyImage' => 1,
  5373.                 'companyId' => $request->request->get('company'),
  5374.                 'companyImagePath' => $companyData->getImage()
  5375.             ));
  5376. //                $emailmessage = (new \Swift_Message('Registration to Entity'))
  5377. //                    ->setFrom('registration@entity.innobd.com')
  5378. //                    ->setTo($request->request->get('email'))
  5379. //                    ->setBody(
  5380. //                        $this->renderView(
  5381. //                            'ApplicationBundle:email/user:registration.html.twig',
  5382. //                            array('name' => $request->request->get('name'),
  5383. //                                'companyData' => $companyData,
  5384. //                                'userName' => $request->request->get('email'),
  5385. //                                'password' => $request->request->get('password'),
  5386. //                            )
  5387. //                        ),
  5388. //                        'text/html'
  5389. //                    );
  5390. //                /*
  5391. //                 * If you also want to include a plaintext version of the message
  5392. //                ->addPart(
  5393. //                    $this->renderView(
  5394. //                        'Emails/registration.txt.twig',
  5395. //                        array('name' => $name)
  5396. //                    ),
  5397. //                    'text/plain'
  5398. //                )
  5399. //                */
  5400. ////            ;
  5401. //                $this->get('mailer')->send($emailmessage);
  5402.         }
  5403.         $this->addFlash(
  5404.             $message[0],
  5405.             $message[1]
  5406.         );
  5407. //        MiscActions::initiateAdminUser($em,$freshFlag,$userName,$name,$email,$encodedPassword,$appIds,$companyIds);
  5408.         $this->addFlash(
  5409.             'success',
  5410.             'The Action was Successful.'
  5411.         );
  5412.         return $this->redirectToRoute('user_login');
  5413.     }
  5414.     public function DumpCurrModulesAction(Request $request)
  5415.     {
  5416.         $em $this->getDoctrine()->getManager();
  5417.         $modules $em->getRepository("ApplicationBundle\\Entity\\SysModule")
  5418.             ->findBy(
  5419.                 array(//                    'active'=>1
  5420.                 )
  5421.             );
  5422.         $module_data = [];
  5423.         foreach ($modules as $entry) {
  5424.             $dt = array(
  5425.                 'id' => $entry->getModuleId(),
  5426.                 'route' => $entry->getModuleRoute(),
  5427.                 'name' => $entry->getModuleName(),
  5428.                 'parentId' => $entry->getParentId(),
  5429.                 'level' => $entry->getLevel(),
  5430.                 'eFA' => $entry->getEnabledForAll(),
  5431.             );
  5432.             $module_data[$entry->getModuleId()] = $dt;
  5433.         }
  5434.         return new JsonResponse(
  5435.             $module_data
  5436.         );
  5437.     }
  5438.     public function GetTenantDashboardMetricsAction(Request $request)
  5439.     {
  5440.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  5441.         if ($systemType === '_CENTRAL_') {
  5442.             return new JsonResponse([
  5443.                 'success' => false,
  5444.                 'message' => 'Tenant metrics are available only on ERP servers.',
  5445.             ], 400);
  5446.         }
  5447.         $days max(1, (int)$request->get('days'30));
  5448.         $requestedAppIds $this->normalizeTenantAppIds($request);
  5449.         $em $this->getDoctrine()->getManager();
  5450.         $conn $em->getConnection();
  5451.         $companyRows $this->loadTenantCompanyRows($conn$requestedAppIds);
  5452.         if (empty($companyRows)) {
  5453.             $companyRows = [
  5454.                 [
  5455.                     'id' => 0,
  5456.                     'appId' => $requestedAppIds[0] ?? 0,
  5457.                     'name' => 'Company',
  5458.                     'email' => '',
  5459.                     'company_status' => 'active',
  5460.                     'package_type' => null,
  5461.                     'subscription_expiry' => null,
  5462.                     'last_activity_at' => null,
  5463.                 ],
  5464.             ];
  5465.         }
  5466.         $userCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_user');
  5467.         $activeUserCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_user WHERE status = 1 OR account_status IN (1, 2, 3)');
  5468.         $loginCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_login_log');
  5469.         $pageVisitCount = (int)$conn->fetchOne("SELECT COUNT(*) FROM user_activity_logs WHERE action_type = 'page_visit'");
  5470.         $apiCallCount = (int)$conn->fetchOne("SELECT COUNT(*) FROM user_activity_logs WHERE action_type = 'api_call'");
  5471.         $salesOrderCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sales_order');
  5472.         $salesInvoiceCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sales_invoice');
  5473.         $purchaseOrderCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM purchase_order');
  5474.         $purchaseInvoiceCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM purchase_invoice');
  5475.         $salesInvoiceTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM sales_invoice");
  5476.         $salesPaidTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) FROM sales_invoice");
  5477.         $purchaseInvoiceTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM purchase_invoice");
  5478.         $purchasePaidTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) FROM purchase_invoice");
  5479.         $activityTrend $conn->fetchAllAssociative('
  5480.             SELECT DATE(created_at) AS day, action_type AS activity_type, COUNT(*) AS total
  5481.             FROM user_activity_logs
  5482.             WHERE created_at >= DATE_SUB(NOW(), INTERVAL :days DAY)
  5483.               AND action_type IN (\'page_visit\', \'api_call\')
  5484.             GROUP BY DATE(created_at), action_type
  5485.             ORDER BY day ASC
  5486.         ', ['days' => $days], ['days' => \PDO::PARAM_INT]);
  5487.         $loginTrend $conn->fetchAllAssociative('
  5488.             SELECT DATE(log_time) AS day, COUNT(*) AS total
  5489.             FROM sys_login_log
  5490.             WHERE log_time >= DATE_SUB(NOW(), INTERVAL :days DAY)
  5491.             GROUP BY DATE(log_time)
  5492.             ORDER BY day ASC
  5493.         ', ['days' => $days], ['days' => \PDO::PARAM_INT]);
  5494.         $revenueTrend $conn->fetchAllAssociative("
  5495.             SELECT DATE(sales_invoice_date) AS day, COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) AS total
  5496.             FROM sales_invoice
  5497.             WHERE sales_invoice_date >= DATE_SUB(NOW(), INTERVAL :days DAY)
  5498.             GROUP BY DATE(sales_invoice_date)
  5499.             ORDER BY day ASC
  5500.         ", ['days' => $days], ['days' => \PDO::PARAM_INT]);
  5501.         $recentActivity $conn->fetchAllAssociative('
  5502.             SELECT
  5503.                 id,
  5504.                 user_id AS userId,
  5505.                 session_id AS sessionId,
  5506.                 route,
  5507.                 action_type AS activityType,
  5508.                 metadata,
  5509.                 duration_seconds AS durationSeconds,
  5510.                 created_at AS createdAt
  5511.             FROM user_activity_logs
  5512.             ORDER BY created_at DESC
  5513.             LIMIT 10
  5514.         ');
  5515.         $recentLogins $conn->fetchAllAssociative('
  5516.             SELECT
  5517.                 login_id AS loginId,
  5518.                 user_id AS userId,
  5519.                 position_id AS positionId,
  5520.                 log_time AS logTime,
  5521.                 log_status AS logStatus
  5522.             FROM sys_login_log
  5523.             ORDER BY log_time DESC
  5524.             LIMIT 10
  5525.         ');
  5526.         $recentSales $conn->fetchAllAssociative('
  5527.             SELECT
  5528.                 sales_invoice_id AS salesInvoiceId,
  5529.                 sales_invoice_number AS salesInvoiceNumber,
  5530.                 company_id AS companyId,
  5531.                 sales_invoice_date AS salesInvoiceDate,
  5532.                 invoice_amount AS invoiceAmount,
  5533.                 received_amount AS paidAmount,
  5534.                 due_amount AS dueAmount
  5535.             FROM sales_invoice
  5536.             ORDER BY sales_invoice_date DESC
  5537.             LIMIT 10
  5538.         ');
  5539.         $firstActivityAt $recentActivity[0]['createdAt'] ?? null;
  5540.         $firstLoginAt $recentLogins[0]['logTime'] ?? null;
  5541.         $firstSalesAt $recentSales[0]['salesInvoiceDate'] ?? null;
  5542.         $companySnapshots = [];
  5543.         $totalLastActivity null;
  5544.         foreach ($companyRows as $row) {
  5545.             $companyLastActivity $this->maxTenantActivityTimestamp(
  5546.                 $row['last_activity_at'] ?? null,
  5547.                 $firstActivityAt,
  5548.                 $firstLoginAt,
  5549.                 $firstSalesAt
  5550.             );
  5551.             $companySnapshots[(int)($row['appId'] ?? 0)] = [
  5552.                 'id' => $row['id'] ?? 0,
  5553.                 'appId' => (int)($row['appId'] ?? 0),
  5554.                 'name' => $row['name'] ?? 'Company',
  5555.                 'email' => $row['email'] ?? '',
  5556.                 'company_status' => $row['company_status'] ?? 'active',
  5557.                 'package_type' => $row['package_type'] ?? null,
  5558.                 'subscription_expiry' => $row['subscription_expiry'] ?? null,
  5559.                 'last_activity_at' => $companyLastActivity,
  5560.                 'user_count' => $userCount,
  5561.                 'active_user_count' => $activeUserCount,
  5562.                 'login_count' => $loginCount,
  5563.                 'page_visit_count' => $pageVisitCount,
  5564.                 'api_call_count' => $apiCallCount,
  5565.                 'sales_order_count' => $salesOrderCount,
  5566.                 'sales_invoice_count' => $salesInvoiceCount,
  5567.                 'purchase_order_count' => $purchaseOrderCount,
  5568.                 'purchase_invoice_count' => $purchaseInvoiceCount,
  5569.                 'sales_invoice_total' => $salesInvoiceTotal,
  5570.                 'sales_paid_total' => $salesPaidTotal,
  5571.                 'purchase_invoice_total' => $purchaseInvoiceTotal,
  5572.                 'purchase_paid_total' => $purchasePaidTotal,
  5573.                 'recent_activity' => $recentActivity,
  5574.                 'recent_logins' => $recentLogins,
  5575.                 'recent_sales' => $recentSales,
  5576.             ];
  5577.             $totalLastActivity $this->maxTenantActivityTimestamp($totalLastActivity$companyLastActivity);
  5578.         }
  5579.         return new JsonResponse([
  5580.             'success' => true,
  5581.             'system_type' => $systemType,
  5582.             'days' => $days,
  5583.             'requested_app_ids' => $requestedAppIds,
  5584.             'company_count' => count($companySnapshots),
  5585.             'companies' => $companySnapshots,
  5586.             'totals' => [
  5587.                 'user_count' => $userCount,
  5588.                 'active_user_count' => $activeUserCount,
  5589.                 'login_count' => $loginCount,
  5590.                 'page_visit_count' => $pageVisitCount,
  5591.                 'api_call_count' => $apiCallCount,
  5592.                 'sales_order_count' => $salesOrderCount,
  5593.                 'sales_invoice_count' => $salesInvoiceCount,
  5594.                 'purchase_order_count' => $purchaseOrderCount,
  5595.                 'purchase_invoice_count' => $purchaseInvoiceCount,
  5596.                 'sales_invoice_total' => $salesInvoiceTotal,
  5597.                 'sales_paid_total' => $salesPaidTotal,
  5598.                 'purchase_invoice_total' => $purchaseInvoiceTotal,
  5599.                 'purchase_paid_total' => $purchasePaidTotal,
  5600.                 'last_activity_at' => $totalLastActivity,
  5601.             ],
  5602.             'trend_rows' => [
  5603.                 'activity' => $activityTrend,
  5604.                 'login' => $loginTrend,
  5605.                 'revenue' => $revenueTrend,
  5606.             ],
  5607.         ]);
  5608.     }
  5609.     private function normalizeTenantAppIds(Request $request)
  5610.     {
  5611.         $appIds $request->get('appIds', []);
  5612.         $appId = (int)$request->get('appId'0);
  5613.         if (is_string($appIds)) {
  5614.             $decoded json_decode($appIdstrue);
  5615.             if (is_array($decoded)) {
  5616.                 $appIds $decoded;
  5617.             } else {
  5618.                 $appIds = [$appIds];
  5619.             }
  5620.         }
  5621.         if (!is_array($appIds)) {
  5622.             $appIds = [];
  5623.         }
  5624.         if ($appId 0) {
  5625.             $appIds[] = $appId;
  5626.         }
  5627.         return array_values(array_unique(array_filter(array_map('intval'$appIds))));
  5628.     }
  5629.     private function loadTenantCompanyRows($conn, array $appIds = [])
  5630.     {
  5631.         $sql '
  5632.             SELECT
  5633.                 id,
  5634.                 app_id AS appId,
  5635.                 name,
  5636.                 email,
  5637.                 company_status,
  5638.                 package_type,
  5639.                 subscription_expiry,
  5640.                 last_activity_at
  5641.             FROM company
  5642.         ';
  5643.         if (!empty($appIds)) {
  5644.             $sql .= ' WHERE app_id IN (' implode(','array_map('intval'$appIds)) . ')';
  5645.         }
  5646.         $sql .= ' ORDER BY id ASC';
  5647.         return $conn->fetchAllAssociative($sql);
  5648.     }
  5649.     private function maxTenantActivityTimestamp(...$values)
  5650.     {
  5651.         $maxTs null;
  5652.         $maxValue null;
  5653.         foreach ($values as $value) {
  5654.             if (empty($value)) {
  5655.                 continue;
  5656.             }
  5657.             $ts strtotime((string)$value);
  5658.             if ($ts === false) {
  5659.                 continue;
  5660.             }
  5661.             if ($maxTs === null || $ts $maxTs) {
  5662.                 $maxTs $ts;
  5663.                 $maxValue is_string($value) ? $value : (string)$value;
  5664.             }
  5665.         }
  5666.         return $maxValue;
  5667.     }
  5668.     private function populateEmployeeCoreFromDetails(Employee $employeeEmployeeDetails $details, array &$stats null)
  5669.     {
  5670.         $changed false;
  5671.         $assignIfEmpty = function ($setter$value$label null) use ($employee, &$changed, &$stats) {
  5672.             if ($value === null || $value === '') {
  5673.                 return;
  5674.             }
  5675.             $getter 'get' substr($setter3);
  5676.             if (method_exists($employee$getter)) {
  5677.                 $current $employee->{$getter}();
  5678.                 if ($current !== null && $current !== '') {
  5679.                     if ($stats !== null && $label !== null && (string)$current !== (string)$value) {
  5680.                         if (!isset($stats['conflict_count'])) {
  5681.                             $stats['conflict_count'] = 0;
  5682.                         }
  5683.                         if (!isset($stats['conflict_fields'])) {
  5684.                             $stats['conflict_fields'] = array();
  5685.                         }
  5686.                         $stats['conflict_count']++;
  5687.                         $stats['conflict_fields'][] = $label;
  5688.                     }
  5689.                     return;
  5690.                 }
  5691.             }
  5692.             if (method_exists($employee$setter)) {
  5693.                 $employee->{$setter}($value);
  5694.                 $changed true;
  5695.             }
  5696.         };
  5697.         $firstName method_exists($details'getFirstname') ? $details->getFirstname() : null;
  5698.         $lastName method_exists($details'getLastname') ? $details->getLastname() : null;
  5699.         $name trim((string)$firstName ' ' . (string)$lastName);
  5700.         if ($name === '') {
  5701.             $name null;
  5702.         }
  5703.         $assignIfEmpty('setFirstName'$firstName'firstName');
  5704.         $assignIfEmpty('setLastName'$lastName'lastName');
  5705.         $assignIfEmpty('setName'$name'name');
  5706.         $assignIfEmpty('setEmail'method_exists($details'getEmail') ? $details->getEmail() : null'email');
  5707.         $phone null;
  5708.         if (method_exists($details'getPhone')) {
  5709.             $phone $details->getPhone();
  5710.         }
  5711.         if (($phone === null || $phone === '') && method_exists($details'getOfficialPhone')) {
  5712.             $phone $details->getOfficialPhone();
  5713.         }
  5714.         $assignIfEmpty('setContactNumber'$phone'contactNumber');
  5715.         $assignIfEmpty('setCurrentAddress'method_exists($details'getCurrAddr') ? $details->getCurrAddr() : null'currentAddress');
  5716.         $assignIfEmpty('setPermanentAddress'method_exists($details'getPermAddr') ? $details->getPermAddr() : null'permanentAddress');
  5717.         $assignIfEmpty('setImage'method_exists($details'getImage') ? $details->getImage() : null'image');
  5718.         $assignIfEmpty('setIdsByDevice'method_exists($details'getIdsByDevice') ? $details->getIdsByDevice() : null'idsByDevice');
  5719.         $assignIfEmpty('setEmployeeCode'method_exists($details'getEmpCode') ? $details->getEmpCode() : null'employeeCode');
  5720.         $assignIfEmpty('setEmployeeLevel'method_exists($details'getEmployeeLevel') ? $details->getEmployeeLevel() : null'employeeLevel');
  5721.         $assignIfEmpty('setUserId'method_exists($details'getUserId') ? $details->getUserId() : null'userId');
  5722.         if (method_exists($details'getEmpStatus')) {
  5723.             $status $details->getEmpStatus();
  5724.             if ($status !== null && $status !== '') {
  5725.                 $assignIfEmpty('setStatus', (string)$status'status');
  5726.             }
  5727.         }
  5728.         if (method_exists($details'getJoiningDate')) {
  5729.             $joiningDate $details->getJoiningDate();
  5730.             if ($joiningDate !== null && method_exists($employee'getJoiningDate')) {
  5731.                 $currentJoiningDate $employee->getJoiningDate();
  5732.                 if ($currentJoiningDate === null || $currentJoiningDate === '') {
  5733.                     if (method_exists($employee'setJoiningDate')) {
  5734.                         $employee->setJoiningDate($joiningDate);
  5735.                         $changed true;
  5736.                     } elseif ($stats !== null) {
  5737.                         if (!isset($stats['conflict_count'])) {
  5738.                             $stats['conflict_count'] = 0;
  5739.                         }
  5740.                         if (!isset($stats['conflict_fields'])) {
  5741.                             $stats['conflict_fields'] = array();
  5742.                         }
  5743.                         $stats['conflict_count']++;
  5744.                         $stats['conflict_fields'][] = 'joiningDate';
  5745.                     }
  5746.                 }
  5747.             }
  5748.         }
  5749.         return $changed;
  5750.     }
  5751.     private function migrateEmployeeDetailsToProfile($em)
  5752.     {
  5753.         $stats = array(
  5754.             'supported' => true,
  5755.             'skipped' => false,
  5756.             'created_profile_table' => false,
  5757.             'profile_rows_synced' => 0,
  5758.             'profile_rows_rekeyed' => 0,
  5759.             'employee_rows_synced' => 0,
  5760.             'created_employee_shells' => 0,
  5761.             'conflict_count' => 0,
  5762.             'conflict_fields' => array(),
  5763.             'messages' => array(),
  5764.         );
  5765.         $conn $em->getConnection();
  5766.         $platformName strtolower((string)$conn->getDatabasePlatform()->getName());
  5767.         if ($platformName !== 'mysql') {
  5768.             $stats['supported'] = false;
  5769.             $stats['skipped'] = true;
  5770.             $stats['messages'][] = 'employee migration is mysql-only';
  5771.             return $stats;
  5772.         }
  5773.         $tableExists = function ($tableName) use ($conn) {
  5774.             $rows $conn->fetchAllAssociative(
  5775.                 "SELECT COUNT(*) AS table_count
  5776.                  FROM INFORMATION_SCHEMA.TABLES
  5777.                  WHERE TABLE_SCHEMA = DATABASE()
  5778.                    AND TABLE_NAME = '" str_replace("'""''"$tableName) . "'"
  5779.             );
  5780.             return isset($rows[0]['table_count']) && (int)$rows[0]['table_count'] > 0;
  5781.         };
  5782.         if (!$tableExists('employee_details')) {
  5783.             $stats['skipped'] = true;
  5784.             $stats['messages'][] = 'employee_details table was not found';
  5785.             return $stats;
  5786.         }
  5787.         if (!$tableExists('employee_profile')) {
  5788.             $ddlRows $conn->fetchAllAssociative('SHOW CREATE TABLE `employee_details`');
  5789.             if (!empty($ddlRows[0])) {
  5790.                 $createSql '';
  5791.                 $rowValues array_values($ddlRows[0]);
  5792.                 foreach ($rowValues as $value) {
  5793.                     if (is_string($value) && stripos($value'CREATE TABLE') === 0) {
  5794.                         $createSql $value;
  5795.                         break;
  5796.                     }
  5797.                 }
  5798.                 if ($createSql === '' && isset($rowValues[1])) {
  5799.                     $createSql $rowValues[1];
  5800.                 }
  5801.                 if ($createSql !== '') {
  5802.                     $createSql str_replace('CREATE TABLE `employee_details`''CREATE TABLE `employee_profile`'$createSql);
  5803.                     $createSql str_replace('`id`''`employee_id`'$createSql);
  5804.                     $conn->executeStatement($createSql);
  5805.                     $stats['created_profile_table'] = true;
  5806.                 }
  5807.             }
  5808.         }
  5809.         $copyColumns = array();
  5810.         $columnRows $conn->fetchAllAssociative('SHOW COLUMNS FROM `employee_details`');
  5811.         foreach ($columnRows as $columnRow) {
  5812.             if (!isset($columnRow['Field'])) {
  5813.                 continue;
  5814.             }
  5815.             if ($columnRow['Field'] === 'id') {
  5816.                 continue;
  5817.             }
  5818.             $copyColumns[] = $columnRow['Field'];
  5819.         }
  5820.         if (!empty($copyColumns) && $tableExists('employee_profile')) {
  5821.             $insertColumns array_merge(array('employee_id'), $copyColumns);
  5822.             $insertColumnsSql = array();
  5823.             foreach ($insertColumns as $columnName) {
  5824.                 $insertColumnsSql[] = '`' $columnName '`';
  5825.             }
  5826.             $selectColumnsSql = array('`id` AS `employee_id`');
  5827.             foreach ($copyColumns as $columnName) {
  5828.                 $selectColumnsSql[] = '`' $columnName '`';
  5829.             }
  5830.             $updateColumnsSql = array();
  5831.             foreach ($copyColumns as $columnName) {
  5832.                 $updateColumnsSql[] = '`' $columnName '` = VALUES(`' $columnName '`)';
  5833.             }
  5834.             $syncSql 'INSERT INTO `employee_profile` (' implode(', '$insertColumnsSql) . ')
  5835.                         SELECT ' implode(', '$selectColumnsSql) . '
  5836.                         FROM `employee_details`
  5837.                         ON DUPLICATE KEY UPDATE ' implode(', '$updateColumnsSql);
  5838.             $conn->executeStatement($syncSql);
  5839.             $stats['profile_rows_synced'] = (int)$conn->fetchOne('SELECT COUNT(*) FROM `employee_profile`');
  5840.         }
  5841.         $detailsRows $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findBy(array(), array('id' => 'ASC'));
  5842.         $employeeRepo $em->getRepository('ApplicationBundle\\Entity\\Employee');
  5843.         foreach ($detailsRows as $details) {
  5844.             $employee $employeeRepo->findOneBy(array('employeeId' => $details->getId()));
  5845.             if (!$employee && method_exists($details'getUserId') && $details->getUserId()) {
  5846.                 $employee $employeeRepo->findOneBy(array('userId' => $details->getUserId()));
  5847.             }
  5848.             $oldEmployeeId null;
  5849.             if ($employee) {
  5850.                 $oldEmployeeId $employee->getEmployeeId();
  5851.             } else {
  5852.                 $employee = new Employee();
  5853.                 $stats['created_employee_shells']++;
  5854.             }
  5855.             $changed $this->populateEmployeeCoreFromDetails($employee$details$stats);
  5856.             if (!$oldEmployeeId && method_exists($details'getUserId') && $details->getUserId() && method_exists($employee'setUserId')) {
  5857.                 $employee->setUserId($details->getUserId());
  5858.                 $changed true;
  5859.             }
  5860.             if ($changed || !$oldEmployeeId) {
  5861.                 $em->persist($employee);
  5862.                 $em->flush();
  5863.                 $stats['employee_rows_synced']++;
  5864.             } else {
  5865.                 $em->persist($employee);
  5866.             }
  5867.             $newEmployeeId $employee->getEmployeeId();
  5868.             if ((int)$details->getId() !== (int)$newEmployeeId && $tableExists('employee_profile')) {
  5869.                 $conn->executeStatement(
  5870.                     'UPDATE `employee_profile` SET `employee_id` = :new_id WHERE `employee_id` = :old_id',
  5871.                     array(
  5872.                         'new_id' => $newEmployeeId,
  5873.                         'old_id' => $details->getId(),
  5874.                     )
  5875.                 );
  5876.                 $stats['profile_rows_rekeyed']++;
  5877.             }
  5878.         }
  5879.         return $stats;
  5880.     }
  5881.     // =========================================================================
  5882.     // OWNER DASHBOARD SNAPSHOT
  5883.     // Called by the central server's OwnerDashboardService::curlErpSnapshot().
  5884.     // Returns a JSON snapshot of financials + KPIs for the company owner portal.
  5885.     // No session required — this is a server-to-server call.
  5886.     // =========================================================================
  5887.     public function GetOwnerDashboardSnapshotAction(Request $request)
  5888.     {
  5889.         $systemType $this->container->hasParameter('system_type')
  5890.             ? $this->container->getParameter('system_type')
  5891.             : '_ERP_';
  5892.         if ($systemType === '_CENTRAL_') {
  5893.             return new JsonResponse([
  5894.                 'success' => false,
  5895.                 'message' => 'Owner snapshot only available on ERP servers.',
  5896.             ], 400);
  5897.         }
  5898.         $em $this->getDoctrine()->getManager();
  5899.         $conn $em->getConnection();
  5900.         // ── Financial data ────────────────────────────────────────────────────
  5901.         $revenueThisMonth 0.0;
  5902.         $revenueLast 0.0;
  5903.         $expensesThisMonth 0.0;
  5904.         $receivables 0.0;
  5905.         $payables 0.0;
  5906.         try {
  5907.             $revenueThisMonth = (float)$conn->fetchOne("
  5908.                 SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
  5909.                 FROM sales_invoice
  5910.                 WHERE YEAR(sales_invoice_date)  = YEAR(NOW())
  5911.                   AND MONTH(sales_invoice_date) = MONTH(NOW())
  5912.             ");
  5913.             $revenueLast = (float)$conn->fetchOne("
  5914.                 SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
  5915.                 FROM sales_invoice
  5916.                 WHERE sales_invoice_date >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01')
  5917.                   AND sales_invoice_date <  DATE_FORMAT(NOW(), '%Y-%m-01')
  5918.             ");
  5919.             $expensesThisMonth = (float)$conn->fetchOne("
  5920.                 SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
  5921.                 FROM purchase_invoice
  5922.                 WHERE YEAR(invoice_date)  = YEAR(NOW())
  5923.                   AND MONTH(invoice_date) = MONTH(NOW())
  5924.             ");
  5925.             $receivables = (float)$conn->fetchOne("
  5926.                 SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0)
  5927.                 FROM sales_invoice
  5928.                 WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')
  5929.             ");
  5930.             $payables = (float)$conn->fetchOne("
  5931.                 SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0)
  5932.                 FROM purchase_invoice
  5933.                 WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')
  5934.             ");
  5935.         } catch (\Exception $e) {
  5936.             // Tables may not exist on all ERP versions — skip gracefully
  5937.         }
  5938.         $profitThisMonth $revenueThisMonth $expensesThisMonth;
  5939.         // Monthly revenue trend (last 6 months)
  5940.         $monthlyTrend = [];
  5941.         try {
  5942.             $trendRows $conn->fetchAllAssociative("
  5943.                 SELECT DATE_FORMAT(sales_invoice_date, '%Y-%m') AS month,
  5944.                        COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0) AS amount
  5945.                 FROM sales_invoice
  5946.                 WHERE sales_invoice_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
  5947.                 GROUP BY DATE_FORMAT(sales_invoice_date, '%Y-%m')
  5948.                 ORDER BY month ASC
  5949.             ");
  5950.             foreach ($trendRows as $row) {
  5951.                 $monthlyTrend[] = ['month' => $row['month'], 'amount' => (float)$row['amount']];
  5952.             }
  5953.         } catch (\Exception $e) {
  5954.             // Skip
  5955.         }
  5956.         // ── KPI data ──────────────────────────────────────────────────────────
  5957.         $totalEmployees 0;
  5958.         $presentToday 0;
  5959.         $attendancePct 0.0;
  5960.         $tasksTotal 0;
  5961.         $tasksCompleted 0;
  5962.         $tasksOverdue 0;
  5963.         $taskRate 0.0;
  5964.         $openInvoices 0;
  5965.         $overdueInvoices 0;
  5966.         $totalInvoiceAmt 0.0;
  5967.         try {
  5968.             $totalEmployees = (int)$conn->fetchOne(
  5969.                 "SELECT COUNT(*) FROM employee WHERE status = 1 OR status IS NULL"
  5970.             );
  5971.         } catch (\Exception $e) {
  5972.             try {
  5973.                 $totalEmployees = (int)$conn->fetchOne(
  5974.                     "SELECT COUNT(*) FROM sys_user WHERE status = 1"
  5975.                 );
  5976.             } catch (\Exception $ex) {
  5977.             }
  5978.         }
  5979.         // Attendance: try common table names used by the ERP HR module
  5980.         try {
  5981.             $today date('Y-m-d');
  5982.             $presentToday = (int)$conn->fetchOne(
  5983.                 "SELECT COUNT(DISTINCT employee_id) FROM employee_daily_log
  5984.                  WHERE log_date = :d AND in_time IS NOT NULL",
  5985.                 ['d' => $today]
  5986.             );
  5987.         } catch (\Exception $e) {
  5988.             try {
  5989.                 $today date('Y-m-d');
  5990.                 $presentToday = (int)$conn->fetchOne(
  5991.                     "SELECT COUNT(DISTINCT user_id) FROM user_activity_logs
  5992.                      WHERE DATE(created_at) = :d AND action_type = 'page_visit'",
  5993.                     ['d' => $today]
  5994.                 );
  5995.             } catch (\Exception $ex) {
  5996.             }
  5997.         }
  5998.         if ($totalEmployees 0) {
  5999.             $attendancePct round(($presentToday $totalEmployees) * 1001);
  6000.         }
  6001.         // Tasks: try common task table names
  6002.         try {
  6003.             $tasksTotal = (int)$conn->fetchOne("SELECT COUNT(*) FROM task");
  6004.             $tasksCompleted = (int)$conn->fetchOne("SELECT COUNT(*) FROM task WHERE status IN ('done','completed','closed')");
  6005.             $tasksOverdue = (int)$conn->fetchOne("SELECT COUNT(*) FROM task WHERE due_date < NOW() AND status NOT IN ('done','completed','closed')");
  6006.         } catch (\Exception $e) {
  6007.             try {
  6008.                 $tasksTotal = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task");
  6009.                 $tasksCompleted = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task WHERE status IN ('done','completed','closed')");
  6010.                 $tasksOverdue = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task WHERE due_date < NOW() AND status NOT IN ('done','completed','closed')");
  6011.             } catch (\Exception $ex) {
  6012.             }
  6013.         }
  6014.         if ($tasksTotal 0) {
  6015.             $taskRate round(($tasksCompleted $tasksTotal) * 1001);
  6016.         }
  6017.         // Invoice KPIs
  6018.         try {
  6019.             $openInvoices = (int)$conn->fetchOne("SELECT COUNT(*) FROM sales_invoice WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')");
  6020.             $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'))");
  6021.             $totalInvoiceAmt = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM sales_invoice");
  6022.         } catch (\Exception $e) {
  6023.         }
  6024.         // ── Recent activity ───────────────────────────────────────────────────
  6025.         $recentActivity = [];
  6026.         try {
  6027.             $rows $conn->fetchAllAssociative("
  6028.                 SELECT action_type AS action, route AS description, created_at AS at
  6029.                 FROM user_activity_logs
  6030.                 ORDER BY created_at DESC
  6031.                 LIMIT 10
  6032.             ");
  6033.             foreach ($rows as $row) {
  6034.                 $recentActivity[] = [
  6035.                     'action' => $row['action'] ?? 'activity',
  6036.                     'description' => $row['description'] ?? '',
  6037.                     'at' => $row['at'] ?? '',
  6038.                 ];
  6039.             }
  6040.         } catch (\Exception $e) {
  6041.         }
  6042.         return new JsonResponse([
  6043.             'success' => true,
  6044.             'fetched_at' => (new \DateTime())->format('c'),
  6045.             'financials' => [
  6046.                 'revenue_this_month' => $revenueThisMonth,
  6047.                 'revenue_last_month' => $revenueLast,
  6048.                 'expenses_this_month' => $expensesThisMonth,
  6049.                 'profit_this_month' => $profitThisMonth,
  6050.                 'outstanding_receivables' => $receivables,
  6051.                 'outstanding_payables' => $payables,
  6052.                 'monthly_revenue_trend' => $monthlyTrend,
  6053.             ],
  6054.             'kpis' => [
  6055.                 'total_employees' => $totalEmployees,
  6056.                 'present_today' => $presentToday,
  6057.                 'attendance_rate_percent' => $attendancePct,
  6058.                 'tasks_total' => $tasksTotal,
  6059.                 'tasks_completed' => $tasksCompleted,
  6060.                 'tasks_overdue' => $tasksOverdue,
  6061.                 'task_completion_rate_percent' => $taskRate,
  6062.                 'open_sales_invoices' => $openInvoices,
  6063.                 'overdue_sales_invoices' => $overdueInvoices,
  6064.                 'total_sales_invoices_amount' => $totalInvoiceAmt,
  6065.             ],
  6066.             'alerts' => [],
  6067.             'recent_activity' => $recentActivity,
  6068.         ]);
  6069.     }
  6070.     // =========================================================================
  6071.     // CENTRAL SSO ENTRY POINT
  6072.     // The central server redirects the company owner here after generating an
  6073.     // SSO token. This action validates the token with the central server and
  6074.     // auto-logs the user in to the ERP.
  6075.     // =========================================================================
  6076.     public function CentralSsoAction(Request $request)
  6077.     {
  6078.         $token = (string)$request->query->get('token''');
  6079.         $returnUrl = (string)$request->query->get('returnUrl''');
  6080.         if ($token === '') {
  6081.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6082.                 'message' => 'Invalid SSO token.',
  6083.             ]);
  6084.         }
  6085.         // Ask the central server to validate the token
  6086.         $centralBase $this->container->hasParameter('central_server_url')
  6087.             ? rtrim($this->container->getParameter('central_server_url'), '/')
  6088.             : '';
  6089.         if ($centralBase === '') {
  6090.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6091.                 'message' => 'Central server URL not configured on this ERP instance.',
  6092.             ]);
  6093.         }
  6094.         $validateUrl $centralBase '/my/sso/validate';
  6095.         $body http_build_query(['token' => $token]);
  6096.         $curl curl_init();
  6097.         curl_setopt_array($curl, [
  6098.             CURLOPT_RETURNTRANSFER => true,
  6099.             CURLOPT_POST => true,
  6100.             CURLOPT_URL => $validateUrl,
  6101.             CURLOPT_CONNECTTIMEOUT => 8,
  6102.             CURLOPT_TIMEOUT => 8,
  6103.             CURLOPT_SSL_VERIFYPEER => false,
  6104.             CURLOPT_SSL_VERIFYHOST => false,
  6105.             CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
  6106.             CURLOPT_POSTFIELDS => $body,
  6107.         ]);
  6108.         $raw curl_exec($curl);
  6109.         curl_close($curl);
  6110.         if (!$raw) {
  6111.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6112.                 'message' => 'Could not reach the central server for SSO validation.',
  6113.             ]);
  6114.         }
  6115.         $payload json_decode($rawtrue);
  6116.         if (!is_array($payload) || empty($payload['success'])) {
  6117.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6118.                 'message' => 'SSO token is invalid or has expired. Please try again.',
  6119.             ]);
  6120.         }
  6121.         $email = (string)($payload['email'] ?? '');
  6122.         if ($email === '') {
  6123.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6124.                 'message' => 'No email returned from SSO validation.',
  6125.             ]);
  6126.         }
  6127.         // Find the local user by email
  6128.         $em $this->getDoctrine()->getManager();
  6129.         $conn $em->getConnection();
  6130.         $userRow null;
  6131.         try {
  6132.             $userRow $conn->fetchAssociative(
  6133.                 "SELECT * FROM sys_user WHERE email = :email AND status = 1 LIMIT 1",
  6134.                 ['email' => $email]
  6135.             );
  6136.         } catch (\Exception $e) {
  6137.         }
  6138.         if (!$userRow) {
  6139.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6140.                 'message' => 'No matching active user found in this ERP for email: ' htmlspecialchars($email),
  6141.             ]);
  6142.         }
  6143.         // Auto-login: populate session exactly as the normal login flow does
  6144.         $session $request->getSession();
  6145.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_ID$userRow['user_id'] ?? $userRow['id'] ?? 0);
  6146.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_NAME$userRow['name'] ?? $payload['name'] ?? '');
  6147.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_TYPE$userRow['user_type'] ?? 0);
  6148.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_COMPANY_ID$userRow['user_company_id'] ?? $userRow['company_id'] ?? 0);
  6149.         // Redirect to ERP dashboard or the requested returnUrl
  6150.         if ($returnUrl !== '' && strpos($returnUrl'http') === 0) {
  6151.             return $this->redirect($returnUrl);
  6152.         }
  6153.         return $this->redirectToRoute('central_landing');
  6154.     }
  6155. }