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.         // L3 (S-2) — the CLI orchestrator `inno:fleet-migrate` is now the safe path (lock, canary,
  1610.         // staged rollout, per-tenant version tracking). Refuse this legacy web loop while the
  1611.         // orchestrator holds the fleet lock so the two can NEVER migrate the fleet concurrently.
  1612.         try {
  1613.             $fleetConn $this->getDoctrine()->getManager('company_group')->getConnection();
  1614.             if (\ApplicationBundle\TimeService\SchedulerLockService::isHeld($fleetConn'fleet-migrate')) {
  1615.                 $msg 'A CLI fleet migration (inno:fleet-migrate) is currently running. The web schema updater is disabled until it finishes.';
  1616.                 if ($request->query->get('returnJson'0) == 1) {
  1617.                     return new \Symfony\Component\HttpFoundation\JsonResponse(array('success' => false'message' => $msg), 423);
  1618.                 }
  1619.                 return new \Symfony\Component\HttpFoundation\Response($msg423);
  1620.             }
  1621.         } catch (\Throwable $e) {
  1622.             // central registry unreachable — fall through to the legacy behaviour unchanged
  1623.         }
  1624.         $dtHere = array(
  1625.             'autoStartUpdateHit' => $request->query->get('autoStartUpdateHit'0),
  1626.             'page_title' => 'Server Actions',
  1627.         );
  1628.         if ($request->query->get('returnJson'0) == 1) {
  1629.             $message "";
  1630.             $gocList = [];
  1631.             $outputList = [];
  1632.             $configJson = array();
  1633.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  1634.             $configJson['success'] = false;
  1635.             $configJson['debugData'] = [];
  1636.             $configJson['pending_doc_count'] = 0;
  1637.             $configJson['initiateDataBaseFlagByGoc'] = array();
  1638.             $configJson['motherLode'] = "http://erp.ourhoneybee.eu";
  1639.             $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1640.             $thisMomentNow = new \DateTime();
  1641.             $currTimeTs $thisMomentNow->format('U');
  1642.             $em $this->getDoctrine()->getManager('company_group');
  1643.             $em_local_default $this->getDoctrine()->getManager();
  1644.             $em_goc $this->getDoctrine()->getManager('company_group');
  1645.             $em->getConnection()->connect();
  1646.             $connected $em->getConnection()->isConnected();
  1647.             $serverId $this->container->hasParameter('server_id') ? $this->container->getParameter('server_id') : '_ALL_';
  1648.             if ($connected) {
  1649.                 if ($request->query->get('prepareEntityGroup'0) == 1) {
  1650.                     $tool = new SchemaTool($em);
  1651.                     $classes $em->getMetadataFactory()->getAllMetadata();
  1652. //                    $tool->createSchema($classes);
  1653.                     $tool->updateSchema($classes);
  1654.                     $em_local_default->getConnection()->connect();
  1655.                     $em_local_default_connected $em_local_default->getConnection()->isConnected();
  1656.                     if ($em_local_default_connected) {
  1657.                         $tool = new SchemaTool($em_local_default);
  1658.                         $classes $em_local_default->getMetadataFactory()->getAllMetadata();
  1659. //                    $tool->createSchema($classes);
  1660.                         $tool->updateSchema($classes);
  1661.                     }
  1662.                     if ($request->query->get('fixEmptyPassword'0) == 1) {
  1663.                         $query "SELECT * from  entity_applicant_details   where password not like '##UNLOCKED##'";
  1664.                         $stmt $em_goc->getConnection()->fetchAllAssociative($query);
  1665.                         $results $stmt;
  1666.                         foreach ($results as $qpo) {
  1667.                             if ($this->container->get('app.legacy_password_service')->verifyWithSalt($qpo['password'], ''$qpo['salt'])
  1668.                                 || $this->container->get('app.legacy_password_service')->verifyWithSalt($qpo['password'], null$qpo['salt'])
  1669.                             ) {
  1670.                                 $queryGG "update entity_applicant_details set password ='##UNLOCKED##' and trigger_reset_password=1 where applicant_id=" $qpo['applicant_id'];
  1671.                                 $stmt $em_goc->getConnection()->executeStatement($queryGG);
  1672.                             }
  1673.                         }
  1674.                     }
  1675.                     if ($request->query->get('triggerReferScore'0) == 1) {
  1676.                         $query "SELECT * from  entity_meeting_session   where booked_by_id !=0 and booked_by_id is not NULL and booked_by_id !=student_id";
  1677.                         $stmt $em_goc->getConnection()->fetchAllAssociative($query);
  1678.                         $results $stmt;
  1679.                         foreach ($results as $qpo) {
  1680.                             MiscActions::updateEntityPerformanceIndex($em_goc, [
  1681.                                 'targetId' => $qpo['booked_by_id'],
  1682.                                 'conversionData' => [
  1683.                                     'count' => 1,
  1684.                                     'score' => 10,
  1685.                                 ]
  1686.                             ],
  1687.                                 new \DateTime($qpo['created_at']));
  1688.                         }
  1689.                         $query "SELECT * from  entity_meeting_session   where booking_referer_id !=0 and booking_referer_id is not NULL and booking_referer_id !=student_id";
  1690.                         $stmt $em_goc->getConnection()->fetchAllAssociative($query);
  1691.                         $results $stmt;
  1692.                         foreach ($results as $qpo) {
  1693.                             MiscActions::updateEntityPerformanceIndex($em_goc, [
  1694.                                 'targetId' => $qpo['booking_referer_id'],
  1695.                                 'referData' => [
  1696.                                     'count' => 1,
  1697.                                     'score' => 10,
  1698.                                 ]
  1699.                             ],
  1700.                                 new \DateTime($qpo['created_at'])
  1701.                             );
  1702.                         }
  1703.                     }
  1704.                     if ($request->query->get('refreshBuddyBeeSalt'0) == 1) {
  1705.                         $query "
  1706.                         UPDATE entity_applicant_details set temp_password=''  where 1;
  1707.                         UPDATE entity_applicant_details set salt=username  where username != '' and username is not NULL and (salt ='' or salt is  NULL);
  1708.                         UPDATE entity_applicant_details set salt='beesalt'  where (salt ='' or salt is  NULL) and (username ='' or username is  NULL);
  1709.                       ";
  1710.                         $stmt $em_goc->getConnection()->executeStatement($query);
  1711.                     }
  1712.                     if ($request->query->get('refreshLastSettingsUpdatedTs'0) == 1) {
  1713.                         $query "
  1714.               
  1715.                         UPDATE entity_user set last_settings_updated_ts=$currTimeTs  where 1;
  1716.                         UPDATE entity_applicant_details set last_settings_updated_ts=$currTimeTs  where 1;
  1717.                      
  1718.                       ";
  1719.                         $stmt $em_goc->getConnection()->executeStatement($query);
  1720.                     }
  1721.                     $get_kids_sql "update `company_group` set `schema_update_pending_flag` =1 where 1;";
  1722.                     $stmt $em_goc->getConnection()->executeStatement($get_kids_sql);
  1723.                     $stmt $em_goc->getConnection()->fetchAllAssociative("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
  1724. //                    
  1725.                     $check_here $stmt;
  1726.                     $pending_id_count 0;
  1727.                     if (isset($check_here[0]))
  1728.                         $pending_id_count $check_here[0]['id_count'];
  1729.                     return new JsonResponse(array(
  1730.                         'pending_doc_count' => $pending_id_count,
  1731.                         'success' => true
  1732.                     ));
  1733.                 } else
  1734.                     if ($systemType != '_CENTRAL_') {
  1735.                         $stmt $em_goc->getConnection()->fetchAllAssociative("select count(id) id_count from company_group where active=1 and schema_update_pending_flag=1;");
  1736. //                        
  1737.                         $check_here $stmt;
  1738.                         if (isset($check_here[0]))
  1739.                             $configJson['pending_doc_count'] = $check_here[0]['id_count'];
  1740. //                        if($serverId!='_ALL_')
  1741.                         $gocList $this->getDoctrine()->getManager('company_group')
  1742.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  1743.                             ->findBy(
  1744.                                 array(
  1745.                                     'active' => 1,
  1746. //                                    'serverId' => 1,
  1747.                                     'schemaUpdatePendingFlag' => 1
  1748.                                 ), array(), 1
  1749.                             );
  1750.                     }
  1751.             }
  1752.             $gocDataList = [];
  1753.             $gocEntryObjectList = [];
  1754.             foreach ($gocList as $entry) {
  1755.                 $d = array(
  1756.                     'name' => $entry->getName(),
  1757.                     'image' => $entry->getImage(),
  1758.                     'shippingAddress' => $entry->getShippingAddress(),
  1759.                     'billingAddress' => $entry->getBillingAddress(),
  1760.                     'id' => $entry->getId(),
  1761.                     'dbName' => $entry->getDbName(),
  1762.                     'dbUser' => $entry->getDbUser(),
  1763.                     'dbPass' => $entry->getDbPass(),
  1764.                     'dbHost' => $entry->getDbHost(),
  1765.                     'appId' => $entry->getAppId(),
  1766.                     'companyRemaining' => $entry->getCompanyRemaining(),
  1767.                     'companyAllowed' => $entry->getCompanyAllowed(),
  1768.                 );
  1769.                 $gocDataList[$entry->getId()] = $d;
  1770.                 $gocEntryObjectList[$entry->getId()] = $entry;
  1771.             }
  1772.             $gocDbName '';
  1773.             $gocDbUser '';
  1774.             $gocDbPass '';
  1775.             $gocDbHost '';
  1776.             $gocId 0;
  1777.             foreach ($gocDataList as $gocId => $entry) {
  1778.                 $connector $this->container->get('application_connector');
  1779.                 $connector->resetConnection(
  1780.                     'default',
  1781.                     $gocDataList[$gocId]['dbName'],
  1782.                     $gocDataList[$gocId]['dbUser'],
  1783.                     $gocDataList[$gocId]['dbPass'],
  1784.                     $gocDataList[$gocId]['dbHost'],
  1785.                     $reset true);
  1786.                 $em $this->getDoctrine()->getManager();
  1787.                 $em->getConnection()->connect();
  1788.                 $indConnected $em->getConnection()->isConnected();
  1789.                 if ($indConnected) {
  1790.                     $configJson['name'] = $entry['name'];
  1791.                     $configJson['image'] = $entry['image'];
  1792.                     $configJson['appId'] = $entry['appId'];
  1793.                     if ($request->query->get('delTable''') != '') {
  1794.                         $get_kids_sql "DROP TABLE " $request->query->get('delTable') . "  ;";
  1795.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  1796.                     }
  1797.                     $tool = new SchemaTool($em);
  1798.                     $classes $em->getMetadataFactory()->getAllMetadata();
  1799. //                    $tool->createSchema($classes);
  1800.                     $tool->updateSchema($classes);
  1801.                     //temp
  1802.                     //temp end
  1803.                     if ($request->query->get('refreshLastSettingsUpdatedTs'0) == 1) {
  1804.                         $query "
  1805.                                     UPDATE sys_user set last_settings_updated_ts=$currTimeTs  where 1;
  1806.                                     UPDATE acc_clients set last_settings_updated_ts=$currTimeTs  where 1;
  1807.                                     UPDATE acc_suppliers set last_settings_updated_ts=$currTimeTs  where 1;
  1808.                      
  1809.                       ";
  1810.                         $stmt $em->getConnection()->executeStatement($query);
  1811.                     }
  1812.                     if ($request->query->get('optimizeJunkAttendanceTable'0) == 1) {
  1813.                         $query "
  1814.                                     OPTIMIZE TABLE employee_attendance_log;
  1815.                      
  1816.                       ";
  1817.                         $stmt $em->getConnection()->executeStatement($query);
  1818.                     }
  1819.                     if ($request->query->get('encryptTrans'0) == 1) {
  1820.                         MiscActions::encryptTrans($em'_ALL_'0);
  1821.                     }
  1822.                     if ($request->query->get('decryptTrans'0) == 1) {
  1823.                         MiscActions::decryptTrans($em'_ALL_'0);
  1824.                     }
  1825.                     if ($request->query->get('createdByRefresh'0) == 1) {
  1826.                         foreach (GeneralConstant::$Entity_list as $entity => $entityName) {
  1827.                             if (in_array($entity, [54]))
  1828.                                 continue;
  1829.                             if (!$em->getMetadataFactory()->isTransient('ApplicationBundle\\Entity\\' $entityName)) {
  1830. //                                $className = ('\\ApplicationBundle\\Entity\\') . $entityName;
  1831. //                                $theEntity = new $className();
  1832. //                                $test_now=$theEntity->getCreatedUserId();
  1833.                                 //if its approval decode signature and add it to dbase and pass the id
  1834.                                 $sigId null;
  1835.                                 $doc null;
  1836.                                 $docList $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  1837.                                     ->findBy(
  1838.                                         array(//                                        GeneralConstant::$Entity_id_field_list[$entity] => $entity_id,
  1839.                                         )
  1840.                                     );
  1841.                                 foreach ($docList as $doc) {
  1842.                                     $notYetAdded 1;
  1843.                                     foreach ([12] as $approveRole) {
  1844.                                         $getIdfunc GeneralConstant::$Entity_id_get_method_list[$entity];
  1845.                                         $entity_id $doc->$getIdfunc();
  1846.                                         $loginId null;
  1847.                                         $sigId null;
  1848.                                         $user_data = [];
  1849.                                         if ($approveRole == 1//created
  1850.                                         {
  1851.                                             $loginId $doc->getCreatedLoginId();
  1852.                                             $notYetAdded $doc->getCreatedUserId() == null 0;
  1853.                                             $sigId $doc->getCreatedSigId();
  1854.                                             $user_data Users::getUserInfoByLoginId($em$loginId);
  1855.                                             if (isset($user_data['id'])) {
  1856.                                                 $doc->setCreatedUserId($user_data['id']);
  1857.                                                 $doc->setCreatedSigId(null);
  1858.                                             }
  1859.                                             $em->flush();
  1860.                                         }
  1861.                                         if ($approveRole == 2//edited
  1862.                                         {
  1863.                                             $loginId $doc->getEditedLoginId();
  1864.                                             $sigId $doc->getEditedSigId();
  1865.                                             $notYetAdded $doc->getEditedUserId() == null 0;
  1866.                                             $user_data Users::getUserInfoByLoginId($em$loginId);
  1867.                                             $doc->setEditedSigId($sigId);
  1868.                                             if (isset($user_data['id'])) {
  1869.                                                 $doc->setEditedUserId($user_data['id']);
  1870.                                                 $doc->setEditedSigId(null);
  1871.                                                 $doc->setLastModifiedDate(new \DateTime());
  1872.                                             }
  1873.                                             $em->flush();
  1874.                                         }
  1875.                                         if (isset($user_data['id']) && $notYetAdded == 1) {
  1876.                                             $new = new Approval();
  1877.                                             $new->setEntity($entity);
  1878.                                             $new->setEntityId($entity_id);
  1879.                                             $new->setPositionId(null);
  1880.                                             $new->setSequence(0);
  1881.                                             $new->setSkipPrintFlag(0);
  1882.                                             $new->setUserAssignType(1);
  1883.                                             $new->setDocumentHash($doc->getDocumentHash());
  1884.                                             //            $new->setUserIds($value->getUserId()); //<-----
  1885.                                             $new->setRoleType($approveRole);
  1886.                                             $new->setRequired(0);
  1887.                                             $new->setSuccession(0);
  1888.                                             $new->setAction(1); //pending status
  1889.                                             $new->setLoginId($loginId); //pending status
  1890.                                             $new->setCurrent(GeneralConstant::CURRENTLY_NON_PENDING_APPROVAL);
  1891.                                             $new->setSuccessionTimeout(0);
  1892.                                             $new->setSigId($sigId);
  1893.                                             $new->setNote('');
  1894.                                             $new->setUserIds(json_encode([$user_data['id']])); //<-----
  1895.                                             $em->persist($new);
  1896.                                             $em->flush();
  1897.                                         }
  1898.                                     }
  1899.                                 }
  1900.                             }
  1901.                         }
  1902.                     }
  1903.                     if ($request->query->get('rectifyOldBoq'0) == 1) {
  1904.                         $boqs $em
  1905.                             ->getRepository('ApplicationBundle\\Entity\\ProjectBoq')
  1906.                             ->findby(array(//                                    'projectId'=>$projectId
  1907.                             ));
  1908.                         foreach ($boqs as $boq) {
  1909. //
  1910. //                            //now the data
  1911. //                            $data = [];
  1912. //                            $newData = [];
  1913. //                            if ($boq)
  1914. //                                $data = json_decode($boq->getData(), true);
  1915. //                            if ($data == null)
  1916. //                                $data = [];
  1917. //                            $defValuesProduct = array(
  1918. //                                'product_note' => '',
  1919. //                                'product_alias' => '',
  1920. //                                'is_foreign_item' => 0,
  1921. //                                'product_segmentIndex' => 0,
  1922. //                                'product_currency_id' => 0,
  1923. //                                'product_currency_text' => '',
  1924. //                                'product_currency_multiply_rate' => 1,
  1925. //                                'product_scope' => 1,
  1926. //                                'product_scopeHolderId' => 0,
  1927. //                                'product_scopeHolderName' => '',
  1928. //                                'product_scopeDescription' => '',
  1929. //                            );
  1930. //                            $defValuesService = array(
  1931. //                                'service_note' => '',
  1932. //                                'service_alias' => '',
  1933. //                                'is_foreign_service' => 0,
  1934. //                                'service_segmentIndex' => 0,
  1935. //                                'service_currency_id' => 0,
  1936. //                                'service_currency_text' => '',
  1937. //                                'service_currency_multiply_rate' => 1,
  1938. //                                'service_scope' => 1,
  1939. //                                'service_scopeHolderId' => 0,
  1940. //                                'service_scopeHolderName' => '',
  1941. //                                'service_scopeDescription' => '',
  1942. //                            );
  1943. //
  1944. //
  1945. //                            if (!empty($data)) {
  1946. //                                $last_key = array_key_last($data);
  1947. ////                                if (isset($data[$last_key]['Products']['product_scope']))
  1948. ////                                    continue;
  1949. ////                                    if (count($data[$last_key]['Products']['products'])==count($data[$last_key]['Products']['is_foreign_item']) )
  1950. //
  1951. //
  1952. //                                $kho = 0;
  1953. //                                $dt_poka = $data[0];
  1954. //                                foreach ($data as $kho => $dt_poka) {
  1955. //
  1956. //
  1957. //                                    if (isset($dt_poka['Products']['products']))
  1958. //                                        foreach ($defValuesProduct as $gopaa => $boka) {
  1959. //                                            if (!isset($dt_poka['Products'][$gopaa]))
  1960. //                                                $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
  1961. //                                            else if ($dt_poka['Products'][$gopaa] == null)
  1962. //                                                $dt_poka['Products'][$gopaa] = array_fill(0, count($dt_poka['Products']['products']), $boka);
  1963. //
  1964. //
  1965. //                                        }
  1966. //                                    if (isset($dt_poka['Services']['services']))
  1967. //                                        foreach ($defValuesService as $gopaa => $boka) {
  1968. //                                            if (!isset($dt_poka['Services'][$gopaa]))
  1969. //                                                $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
  1970. //                                            else if ($dt_poka['Services'][$gopaa] == null)
  1971. //                                                $dt_poka['Services'][$gopaa] = array_fill(0, count($dt_poka['Services']['services']), $boka);
  1972. //
  1973. //                                        }
  1974. //
  1975. //                                    if (!isset($dt_poka['serviceSegmentData']))
  1976. //                                        $dt_poka['serviceSegmentData'] = [
  1977. //                                            array(
  1978. //                                                "title" => "General Services",
  1979. //                                                "index" => 0,
  1980. //                                            )
  1981. //                                        ];
  1982. //                                    else if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
  1983. //                                        $dt_poka['serviceSegmentData'] = [
  1984. //                                            array(
  1985. //                                                "title" => "General Services",
  1986. //                                                "index" => 0,
  1987. //                                            )
  1988. //                                        ];
  1989. //
  1990. //                                    if (!isset($dt_poka['productSegmentData']))
  1991. //                                        $dt_poka['productSegmentData'] = [
  1992. //                                            array(
  1993. //                                                "title" => "General Items",
  1994. //                                                "index" => 0,
  1995. //                                            )
  1996. //                                        ];
  1997. //                                    else if ($dt_poka['productSegmentData'] == null || empty($dt_poka['productSegmentData']))
  1998. //                                        $dt_poka['productSegmentData'] = [
  1999. //                                            array(
  2000. //                                                "title" => "General Items",
  2001. //                                                "index" => 0,
  2002. //                                            )
  2003. //                                        ];
  2004. //
  2005. //
  2006. //                                    $newData[$kho] = $dt_poka;
  2007. //                                }
  2008. //
  2009. //
  2010. //                                $boq->setData(json_encode($newData));
  2011. //                                $em->flush();
  2012. //
  2013. //
  2014. //                            }
  2015.                             $theProj $em->getRepository('ApplicationBundle\\Entity\\Project')
  2016.                                 ->findOneBy(
  2017.                                     array(
  2018.                                         'projectId' => $boq->getProjectId()
  2019.                                     )
  2020.                                 );
  2021.                             if ($theProj)
  2022.                                 $theProj->setDocumentDataId($boq->getDocumentDataId());
  2023.                             $em->flush();
  2024.                         }
  2025.                     }
  2026.                     if ($request->query->get('oldBoqToNewSystem'0) == 1) {
  2027.                         $entitiesGG = [
  2028.                             array_flip(GeneralConstant::$Entity_list)['ProjectBoq'],
  2029.                             array_flip(GeneralConstant::$Entity_list)['ProjectMaterial'],
  2030.                             array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  2031.                             array_flip(GeneralConstant::$Entity_list)['Opportunity'],
  2032.                             array_flip(GeneralConstant::$Entity_list)['ProjectOffer'],
  2033.                             array_flip(GeneralConstant::$Entity_list)['ProjectProposal'],
  2034.                         ];
  2035.                         foreach ($entitiesGG as $ent) {
  2036.                             $entityNameHere GeneralConstant::$Entity_list[$ent];
  2037.                             $the_actual_docs $em->getRepository('ApplicationBundle\\Entity\\' GeneralConstant::$Entity_list[$ent])
  2038.                                 ->findBy(
  2039.                                     array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  2040.                                     )
  2041.                                 );
  2042.                             foreach ($the_actual_docs as $the_actual_doc) {
  2043.                                 //now the data
  2044.                                 //first find the docData if available
  2045.                                 $theDocData null;
  2046.                                 if ($entityNameHere == 'SalesProposal' || $entityNameHere == 'Opportunity') {
  2047.                                     $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2048.                                         ->findOneBy(
  2049.                                             array(
  2050.                                                 'id' => $the_actual_doc->getDocumentDataId()
  2051.                                             )
  2052.                                         );
  2053.                                     if (!$theDocData)
  2054.                                         if ($the_actual_doc->getSalesProposalId() != null && $the_actual_doc->getSalesProposalId() != 0)
  2055.                                             $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2056.                                                 ->findOneBy(
  2057.                                                     array(
  2058.                                                         'proposalId' => $the_actual_doc->getSalesProposalId()
  2059.                                                     )
  2060.                                                 );
  2061.                                     if (!$theDocData)
  2062.                                         if ($the_actual_doc->getOpportunityId() != null && $the_actual_doc->getOpportunityId() != 0)
  2063.                                             $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2064.                                                 ->findOneBy(
  2065.                                                     array(
  2066.                                                         'opportunityId' => $the_actual_doc->getOpportunityId()
  2067.                                                     )
  2068.                                                 );
  2069.                                     if (!$theDocData)
  2070.                                         if ($the_actual_doc->getProjectId() != null && $the_actual_doc->getProjectId() != 0)
  2071.                                             $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2072.                                                 ->findOneBy(
  2073.                                                     array(
  2074.                                                         'projectId' => $the_actual_doc->getProjectId()
  2075.                                                     )
  2076.                                                 );
  2077.                                     if (!$theDocData) {
  2078.                                         $theDocData = new DocumentData();
  2079.                                         if ($entityNameHere == 'SalesProposal')
  2080.                                             $theDocData->setProposalId($the_actual_doc->getSalesProposalId());
  2081.                                         if ($entityNameHere == 'Opportunity')
  2082.                                             $theDocData->setOpportunityId($the_actual_doc->getOpportunityId());
  2083.                                     }
  2084.                                 } else {
  2085.                                     $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2086.                                         ->findOneBy(
  2087.                                             array(
  2088.                                                 'id' => $the_actual_doc->getDocumentDataId()
  2089.                                             )
  2090.                                         );
  2091.                                     if (!$theDocData)
  2092.                                         $theDocData $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2093.                                             ->findOneBy(
  2094.                                                 array(
  2095.                                                     'projectId' => $the_actual_doc->getProjectId()
  2096.                                                 )
  2097.                                             );
  2098.                                     if (!$theDocData) {
  2099.                                         $theDocData = new DocumentData();
  2100.                                         $theDocData->setProjectId($the_actual_doc->getProjectId());
  2101.                                     }
  2102.                                 }
  2103.                                 if ($entityNameHere == 'ProjectBoq' || $entityNameHere == 'Opportunity' || $entityNameHere == 'SalesProposal') {
  2104.                                     $data = [];
  2105.                                     $newData = [];
  2106.                                     $data json_decode($the_actual_doc->getData(), true);
  2107.                                     if ($data == null)
  2108.                                         $data = [];
  2109.                                     if (!empty($data)) {
  2110.                                         $last_key array_key_last($data);
  2111.                                         $lastIndex 0;
  2112.                                         foreach ($data as $kho => $dt_poka) {
  2113.                                             $cur_date = new \DateTime();
  2114.                                             $lead_date = new \DateTime(isset($dt_poka['lead_date']) ? $dt_poka['lead_date'] : '');
  2115.                                             $newSingleSet = array(
  2116.                                                 'refPoNumber' => isset($dt_poka['refPoNumber']) ? $dt_poka['refPoNumber'] : '',
  2117.                                                 'segmentData' => isset($dt_poka['segmentData']) ? $dt_poka['segmentData'] : [],
  2118.                                                 'proposal_title' => isset($dt_poka['proposal_title']) ? $dt_poka['proposal_title'] : '',
  2119.                                                 'to_position' => isset($dt_poka['to_position']) ? $dt_poka['to_position'] : '',
  2120.                                                 'system_subCategory' => isset($dt_poka['system_subCategory']) ? $dt_poka['system_subCategory'] : '',
  2121.                                                 'system_size' => isset($dt_poka['system_size']) ? $dt_poka['system_size'] : '',
  2122.                                                 'system_unit' => isset($dt_poka['system_unit']) ? $dt_poka['system_unit'] : '',
  2123.                                                 'system_price' => isset($dt_poka['system_price']) ? $dt_poka['system_price'] : '',
  2124.                                                 'msaTotal' => isset($dt_poka['msaTotal']) ? $dt_poka['msaTotal'] : 0,
  2125.                                                 'totalProjectValue' => isset($dt_poka['totalProjectValue']) ? $dt_poka['totalProjectValue'] : 0,
  2126.                                                 'cl_subject' => isset($dt_poka['cl_subject']) ? $dt_poka['cl_subject'] : '',
  2127.                                                 'cl_body' => isset($dt_poka['cl_body']) ? $dt_poka['cl_body'] : '',
  2128.                                                 'vatPercentage' => isset($dt_poka['vatPercentage']) ? $dt_poka['vatPercentage'] : '',
  2129.                                                 'aitPercentage' => isset($dt_poka['aitPercentage']) ? $dt_poka['aitPercentage'] : '',
  2130.                                                 'proposalSalesValue' => isset($dt_poka['proposalSalesValue']) ? $dt_poka['proposalSalesValue'] : '',
  2131.                                                 'combined_proposal_item_name' => isset($dt_poka['combined_proposal_item_name']) ? $dt_poka['combined_proposal_item_name'] : '',
  2132.                                                 'combined_proposal_details_price' => isset($dt_poka['combined_proposal_details_price']) ? $dt_poka['combined_proposal_details_price'] : '',
  2133.                                                 'check_boq' => isset($dt_poka['check_boq']) ? $dt_poka['check_boq'] : 0,
  2134.                                                 'check_boq_individual_price' => isset($dt_poka['check_boq_individual_price']) ? $dt_poka['check_boq_individual_price'] : 0,
  2135.                                                 'check_show_combined_only' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
  2136.                                                 'check_override_markup' => isset($dt_poka['check_show_combined_only']) ? $dt_poka['check_show_combined_only'] : 0,
  2137.                                                 'clientId' => isset($dt_poka['client_id']) ? $dt_poka['client_id'] : 0,
  2138.                                                 'salesPersonId' => isset($dt_poka['salesPersonID']) ? $dt_poka['salesPersonID'] : 0,
  2139.                                                 'clientName' => isset($dt_poka['clientName']) ? $dt_poka['clientName'] : '',
  2140.                                                 'ClientContactPerson' => isset($dt_poka['ClientContactPerson']) ? $dt_poka['ClientContactPerson'] : '',
  2141.                                                 'ClientContactNumber' => isset($dt_poka['ClientContactNumber']) ? $dt_poka['ClientContactNumber'] : '',
  2142.                                                 'ClientDeliveryAddress' => isset($dt_poka['ClientDeliveryAddress']) ? $dt_poka['ClientDeliveryAddress'] : '',
  2143.                                                 'ClientBillingAddress' => isset($dt_poka['ClientBillingAddress']) ? $dt_poka['ClientBillingAddress'] : '',
  2144.                                                 'leadDate' => $lead_date->format('Y-m-d'),
  2145.                                                 'date' => $cur_date->format('Y-m-d'),
  2146.                                             );
  2147.                                             $newSegmentData = array();
  2148.                                             $oldSegmentSystem 0;
  2149.                                             if (isset($dt_poka['productSegmentData']) || isset($dt_poka['serviceSegmentData']))
  2150.                                                 $oldSegmentSystem 1;
  2151.                                             if ($oldSegmentSystem == 1) {
  2152.                                                 //unify the ids of segmnent. services will start from 1000+service segmentId for unification
  2153.                                                 if (isset($dt_poka['productSegmentData']))
  2154.                                                     foreach ($dt_poka['productSegmentData'] as $supu => $gupu) {
  2155.                                                         $newModSeg $gupu;
  2156.                                                         $newModSeg['index'] = $gupu['index'];
  2157.                                                         $newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Items';
  2158.                                                         $newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
  2159.                                                         $newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
  2160.                                                         $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  2161.                                                         $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  2162.                                                         $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  2163.                                                         $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  2164.                                                         $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  2165.                                                         $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  2166.                                                         $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  2167.                                                         $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  2168.                                                         $newSegmentData[] = $newModSeg;
  2169.                                                     }
  2170.                                                 if (isset($dt_poka['serviceSegmentData']))
  2171.                                                     if ($dt_poka['serviceSegmentData'] == null || empty($dt_poka['serviceSegmentData']))
  2172.                                                         foreach ($dt_poka['serviceSegmentData'] as $supu => $gupu) {
  2173.                                                             if ($gupu['index'] == 'undefined'$gupu['index'] = 0;
  2174.                                                             if (!is_numeric($gupu['index'])) $gupu['index'] = 0;
  2175.                                                             $newModSeg $gupu;
  2176.                                                             $newModSeg['index'] = 1000 $gupu['index'];
  2177.                                                             $newModSeg['title'] = isset($gupu['title']) ? $gupu['title'] : 'Services';
  2178.                                                             $newModSeg['scfc'] = isset($gupu['scfc']) ? $gupu['scfc'] : 0;
  2179.                                                             $newModSeg['uomCust'] = isset($gupu['uomCust']) ? $gupu['uomCust'] : '';
  2180.                                                             $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  2181.                                                             $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  2182.                                                             $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  2183.                                                             $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  2184.                                                             $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  2185.                                                             $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  2186.                                                             $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  2187.                                                             $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  2188.                                                             $newSegmentData[] = $newModSeg;
  2189.                                                         }
  2190.                                                 $newSingleSet['itemSegmentData'] = $newSegmentData;
  2191.                                             }
  2192.                                             $lastSequenceBySegment = array();
  2193.                                             //now modify Services or products
  2194.                                             $oldProductSystem 0;
  2195.                                             if (!isset($dt_poka['rowData']))
  2196.                                                 $dt_poka['rowData'] = array();
  2197.                                             if (isset($dt_poka['Products']) || isset($dt_poka['Services']) || isset($dt_poka['ArCosts'])) {
  2198.                                                 $oldProductSystem 1;
  2199.                                             }
  2200.                                             if ($oldProductSystem == 1) {
  2201.                                                 $theDt = array(
  2202.                                                     'products' => [],
  2203.                                                     'services' => [],
  2204.                                                     'ar_heads' => [],
  2205.                                                 );
  2206.                                                 if (isset($dt_poka['Products']))
  2207.                                                     $theDt $dt_poka['Products'];
  2208.                                                 if (isset($theDt['products']))
  2209.                                                     foreach ($theDt['products'] as $f => $pid) {
  2210.                                                         $unit = isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0;
  2211.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  2212.                                                         if ($indexForThis == -1) {
  2213.                                                             $indexForThis $lastIndex;
  2214.                                                             $lastIndex++;
  2215.                                                         }
  2216.                                                         $unitPrice = isset($theDt['product_unit_price'][$f]) ? $theDt['product_unit_price'][$f] : 0;
  2217.                                                         if ($unit == ''$unit 0;
  2218.                                                         if ($unitPrice == ''$unitPrice 0;
  2219.                                                         $totalPrice $unit $unitPrice;
  2220.                                                         $segmentIndex = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : 0;
  2221.                                                         $sequence = isset($theDt['product_segmentIndex'][$f]) ? $theDt['product_segmentIndex'][$f] : '_UNSET_';
  2222.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  2223.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  2224.                                                         if ($sequence == '_UNSET_')
  2225.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2226.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  2227.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2228.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  2229.                                                         $unitSalesPrice = isset($theDt['product_unit_sales_price'][$f]) ? $theDt['product_unit_sales_price'][$f] : $unitPrice;
  2230.                                                         if ($unitSalesPrice == ''$unitSalesPrice 0;
  2231.                                                         $totalSalesPrice $unit $unitSalesPrice;
  2232.                                                         $marginAmount = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitSalesPrice $unitPrice);
  2233.                                                         $marginRate = isset($theDt['product_ma'][$f]) ? $theDt['product_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  2234.                                                         $discountAmount = isset($theDt['product_dr'][$f]) ? $theDt['product_dr'][$f] : 0;
  2235.                                                         $discountRate = isset($theDt['product_da'][$f]) ? $theDt['product_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  2236.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  2237.                                                         $taxRate = isset($theDt['product_tax_percentage'][$f]) ? $theDt['product_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  2238.                                                         $taxAmount = isset($theDt['product_tax_amount'][$f]) ? $theDt['product_tax_amount'][$f] : 0;
  2239.                                                         $finalAmount $discountedAmount $taxAmount;
  2240.                                                         $row = array(
  2241.                                                             'type' => 1,//1:product 2=service 4=tools 5:text 6: expense against head
  2242.                                                             'id' => $pid,
  2243.                                                             'index' => $indexForThis,
  2244.                                                             'isForeign' => isset($theDt['is_foreign_item'][$f]) ? $theDt['is_foreign_item'][$f] : 0,
  2245.                                                             'sequence' => $sequence,
  2246.                                                             'segmentIndex' => $segmentIndex,
  2247.                                                             'soItemId' => isset($theDt['product_soItemId'][$f]) ? $theDt['product_soItemId'][$f] : 0,
  2248.                                                             'soItemDelivered' => isset($theDt['product_soItemDelivered'][$f]) ? $theDt['product_soItemDelivered'][$f] : 0,
  2249.                                                             'soItemFound' => isset($theDt['product_soItemFound'][$f]) ? $theDt['product_soItemFound'][$f] : 0,
  2250.                                                             'alias' => isset($theDt['product_alias'][$f]) ? $theDt['product_alias'][$f] : '',
  2251.                                                             'name' => isset($theDt['product_name'][$f]) ? $theDt['product_name'][$f] : '',
  2252.                                                             'note' => isset($theDt['product_note'][$f]) ? $theDt['product_note'][$f] : '',
  2253.                                                             'fdm' => isset($theDt['product_fdm'][$f]) ? $theDt['product_fdm'][$f] : null,
  2254.                                                             'unit' => isset($theDt['product_units'][$f]) ? $theDt['product_units'][$f] : 0,
  2255.                                                             'unitTypeId' => isset($theDt['product_unit_type'][$f]) ? $theDt['product_unit_type'][$f] : 0,
  2256.                                                             'unitPrice' => $unitPrice,
  2257.                                                             'totalPrice' => $totalPrice,
  2258.                                                             'unitSalesPrice' => $unitSalesPrice,
  2259.                                                             'totalSalesPrice' => $totalSalesPrice,
  2260.                                                             'marginRate' => $marginRate,
  2261.                                                             'marginAmount' => $marginAmount,
  2262.                                                             'discountRate' => $discountRate,
  2263.                                                             'discountAmount' => $discountAmount,
  2264.                                                             'discountedAmount' => $discountedAmount,
  2265.                                                             'taxRate' => $taxRate,
  2266.                                                             'taxAmount' => $taxAmount,
  2267.                                                             'finalAmount' => $finalAmount,
  2268.                                                             'recurring' => isset($theDt['product_recurring'][$f]) ? $theDt['product_recurring'][$f] : 0,
  2269.                                                             'currency' => isset($theDt['product_currency_id'][$f]) ? $theDt['product_currency_id'][$f] : 0,
  2270.                                                             'currencyText' => isset($theDt['product_currency_text'][$f]) ? $theDt['product_currency_text'][$f] : '',
  2271.                                                             'currencyMultiplyRate' => isset($theDt['product_currency_multiply_rate'][$f]) ? $theDt['product_currency_multiply_rate'][$f] : 1,
  2272.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  2273.                                                             'taxId' => isset($theDt['product_tax_config_id'][$f]) ? $theDt['product_tax_config_id'][$f] : 0,
  2274.                                                             'taxName' => isset($theDt['product_tax_config_text'][$f]) ? $theDt['product_tax_config_text'][$f] : '',
  2275.                                                             'dependencyOnIndex' => isset($theDt['product_dependency_of_index'][$f]) ? $theDt['product_dependency_of_index'][$f] : 0,
  2276.                                                             'dependencyOnPid' => isset($theDt['product_dependency_of_product_id'][$f]) ? $theDt['product_dependency_of_product_id'][$f] : 0,
  2277.                                                             'dependencyOnSid' => isset($theDt['product_dependency_of_service_id'][$f]) ? $theDt['product_dependency_of_service_id'][$f] : 0,
  2278.                                                             'dependencyOnSegment' => isset($theDt['product_dependency_of_product_index'][$f]) ? $theDt['product_dependency_of_product_index'][$f] : 0,
  2279.                                                             'warranty' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : 0,
  2280.                                                             'origin' => isset($theDt['product_origin'][$f]) ? $theDt['product_origin'][$f] : 0,
  2281.                                                             'origins' => isset($theDt['product_origin'][$f]) ? [$theDt['product_origin'][$f]] : [],
  2282.                                                             'scope' => isset($theDt['product_scope'][$f]) ? $theDt['product_scope'][$f] : 0,
  2283.                                                             'scopeId' => isset($theDt['product_scopeHolderId'][$f]) ? [$theDt['product_scopeHolderId'][$f]] : 0,
  2284.                                                             'scopeName' => isset($theDt['product_scopeHolderName'][$f]) ? [$theDt['product_scopeHolderName'][$f]] : '',
  2285.                                                             'scopeDescription' => isset($theDt['product_scopeDescription'][$f]) ? [$theDt['product_scopeDescription'][$f]] : '',
  2286.                                                             'deliverySchedule' => isset($theDt['product_delivery_schedule'][$f]) ? $theDt['product_delivery_schedule'][$f] : [],
  2287.                                                             'deliveryPorts' => isset($theDt['product_delivery_ports'][$f]) ? $theDt['product_delivery_ports'][$f] : [],
  2288.                                                             'billingSchedule' => isset($theDt['product_billing_schedule'][$f]) ? $theDt['product_billing_schedule'][$f] : [],
  2289.                                                             'referenceNo' => isset($theDt['product_reference_price'][$f]) ? $theDt['product_reference_price'][$f] : '',
  2290.                                                             'referenceFiles' => isset($theDt['product_reference_price_file'][$f]) ? $theDt['product_reference_price_file'][$f] : '',
  2291.                                                         );
  2292.                                                         $dt_poka['rowData'][] = $row;
  2293.                                                     }
  2294.                                                 //now the services
  2295.                                                 $theDt = array(
  2296.                                                     'products' => [],
  2297.                                                     'services' => [],
  2298.                                                     'ar_heads' => [],
  2299.                                                 );
  2300.                                                 if (isset($dt_poka['Services']))
  2301.                                                     $theDt $dt_poka['Services'];
  2302.                                                 if (isset($theDt['services']))
  2303.                                                     foreach ($theDt['services'] as $f => $pid) {
  2304.                                                         $unit = isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0;
  2305.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  2306.                                                         if ($indexForThis == -1) {
  2307.                                                             $indexForThis $lastIndex;
  2308.                                                             $lastIndex++;
  2309.                                                         }
  2310.                                                         $unitPrice = isset($theDt['service_unit_price'][$f]) ? $theDt['service_unit_price'][$f] : 0;
  2311.                                                         $totalPrice $unit $unitPrice;
  2312.                                                         $segmentIndex = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : 0;
  2313.                                                         if ($segmentIndex == 'undefined'$segmentIndex 0;
  2314.                                                         if (!is_numeric($segmentIndex)) $segmentIndex 0;
  2315.                                                         if ($oldSegmentSystem == 1)
  2316.                                                             $segmentIndex 1000 $segmentIndex;
  2317.                                                         $sequence = isset($theDt['service_segmentIndex'][$f]) ? $theDt['service_segmentIndex'][$f] : '_UNSET_';
  2318.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  2319.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  2320.                                                         if ($sequence == '_UNSET_')
  2321.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2322.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  2323.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2324.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  2325.                                                         $unitSalesPrice = isset($theDt['service_unit_sales_price'][$f]) ? $theDt['service_unit_sales_price'][$f] : $unitPrice;
  2326.                                                         $totalSalesPrice $unit $unitSalesPrice;
  2327.                                                         $marginAmount = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitSalesPrice $unitPrice);
  2328.                                                         $marginRate = isset($theDt['service_ma'][$f]) ? $theDt['service_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  2329.                                                         $discountAmount = isset($theDt['service_dr'][$f]) ? $theDt['service_dr'][$f] : 0;
  2330.                                                         $discountRate = isset($theDt['service_da'][$f]) ? $theDt['service_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  2331.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  2332.                                                         $taxRate = isset($theDt['service_tax_percentage'][$f]) ? $theDt['service_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  2333.                                                         $taxAmount = isset($theDt['service_tax_amount'][$f]) ? $theDt['service_tax_amount'][$f] : 0;
  2334.                                                         $finalAmount $discountedAmount $taxAmount;
  2335.                                                         $row = array(
  2336.                                                             'type' => 2,//1:product 2=service 4=tools 5:text 6: expense against head
  2337.                                                             'id' => $pid,
  2338.                                                             'index' => $indexForThis,
  2339.                                                             'isForeign' => isset($theDt['is_foreign_service'][$f]) ? $theDt['is_foreign_service'][$f] : 0,
  2340.                                                             'sequence' => $sequence,
  2341.                                                             'segmentIndex' => $segmentIndex,
  2342.                                                             'soItemId' => isset($theDt['service_soItemId'][$f]) ? $theDt['service_soItemId'][$f] : 0,
  2343.                                                             'soItemDelivered' => isset($theDt['service_soItemDelivered'][$f]) ? $theDt['service_soItemDelivered'][$f] : 0,
  2344.                                                             'soItemFound' => isset($theDt['service_soItemFound'][$f]) ? $theDt['service_soItemFound'][$f] : 0,
  2345.                                                             'alias' => isset($theDt['service_alias'][$f]) ? $theDt['service_alias'][$f] : '',
  2346.                                                             'name' => isset($theDt['service_name'][$f]) ? $theDt['service_name'][$f] : '',
  2347.                                                             'note' => isset($theDt['service_note'][$f]) ? $theDt['service_note'][$f] : '',
  2348.                                                             'fdm' => isset($theDt['service_fdm'][$f]) ? $theDt['service_fdm'][$f] : null,
  2349.                                                             'unit' => isset($theDt['service_units'][$f]) ? $theDt['service_units'][$f] : 0,
  2350.                                                             'unitTypeId' => isset($theDt['service_unit_type'][$f]) ? $theDt['service_unit_type'][$f] : 0,
  2351.                                                             'unitPrice' => $unitPrice,
  2352.                                                             'totalPrice' => $totalPrice,
  2353.                                                             'unitSalesPrice' => $unitSalesPrice,
  2354.                                                             'totalSalesPrice' => $totalSalesPrice,
  2355.                                                             'marginRate' => $marginRate,
  2356.                                                             'marginAmount' => $marginAmount,
  2357.                                                             'discountRate' => $discountRate,
  2358.                                                             'discountAmount' => $discountAmount,
  2359.                                                             'discountedAmount' => $discountedAmount,
  2360.                                                             'taxRate' => $taxRate,
  2361.                                                             'taxAmount' => $taxAmount,
  2362.                                                             'finalAmount' => $finalAmount,
  2363.                                                             'recurring' => isset($theDt['service_recurring'][$f]) ? $theDt['service_recurring'][$f] : 0,
  2364.                                                             'currency' => isset($theDt['service_currency_id'][$f]) ? $theDt['service_currency_id'][$f] : 0,
  2365.                                                             'currencyText' => isset($theDt['service_currency_text'][$f]) ? $theDt['service_currency_text'][$f] : '',
  2366.                                                             'currencyMultiplyRate' => isset($theDt['service_currency_multiply_rate'][$f]) ? $theDt['service_currency_multiply_rate'][$f] : 1,
  2367.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  2368.                                                             'taxId' => isset($theDt['service_tax_config_id'][$f]) ? $theDt['service_tax_config_id'][$f] : 0,
  2369.                                                             'taxName' => isset($theDt['service_tax_config_text'][$f]) ? $theDt['service_tax_config_text'][$f] : '',
  2370.                                                             'dependencyOnIndex' => isset($theDt['service_dependency_of_index'][$f]) ? $theDt['service_dependency_of_index'][$f] : 0,
  2371.                                                             'dependencyOnPid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
  2372.                                                             'dependencyOnSid' => isset($theDt['service_dependency_of_service_id'][$f]) ? $theDt['service_dependency_of_service_id'][$f] : 0,
  2373.                                                             'dependencyOnSegment' => isset($theDt['service_dependency_of_service_index'][$f]) ? $theDt['service_dependency_of_service_index'][$f] : 0,
  2374.                                                             'warranty' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : 0,
  2375.                                                             'origin' => isset($theDt['service_origin'][$f]) ? $theDt['service_origin'][$f] : 0,
  2376.                                                             'origins' => isset($theDt['service_origin'][$f]) ? [$theDt['service_origin'][$f]] : [],
  2377.                                                             'scope' => isset($theDt['service_scope'][$f]) ? $theDt['service_scope'][$f] : 0,
  2378.                                                             'scopeId' => isset($theDt['service_scopeHolderId'][$f]) ? [$theDt['service_scopeHolderId'][$f]] : 0,
  2379.                                                             'scopeName' => isset($theDt['service_scopeHolderName'][$f]) ? [$theDt['service_scopeHolderName'][$f]] : '',
  2380.                                                             'scopeDescription' => isset($theDt['service_scopeDescription'][$f]) ? [$theDt['service_scopeDescription'][$f]] : '',
  2381.                                                             'deliverySchedule' => isset($theDt['service_delivery_schedule'][$f]) ? $theDt['service_delivery_schedule'][$f] : [],
  2382.                                                             'deliveryPorts' => isset($theDt['service_delivery_ports'][$f]) ? $theDt['service_delivery_ports'][$f] : [],
  2383.                                                             'billingSchedule' => isset($theDt['service_billing_schedule'][$f]) ? $theDt['service_billing_schedule'][$f] : [],
  2384.                                                             'referenceNo' => isset($theDt['service_reference_price'][$f]) ? $theDt['service_reference_price'][$f] : '',
  2385.                                                             'referenceFiles' => isset($theDt['service_reference_price_file'][$f]) ? $theDt['service_reference_price_file'][$f] : '',
  2386.                                                         );
  2387.                                                         $dt_poka['rowData'][] = $row;
  2388.                                                     }
  2389.                                                 //now accounts /Cost
  2390.                                                 $theDt = array(
  2391.                                                     'products' => [],
  2392.                                                     'services' => [],
  2393.                                                     'ar_heads' => [],
  2394.                                                 );
  2395.                                                 if (isset($dt_poka['ArCosts']))
  2396.                                                     $theDt $dt_poka['ArCosts'];
  2397.                                                 if (isset($theDt['ar_heads']))
  2398.                                                     foreach ($theDt['ar_heads'] as $f => $pid) {
  2399.                                                         $unit = isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0;
  2400.                                                         if (!is_numeric($unit)) $unit 0;
  2401.                                                         $indexForThis = isset($theDt['index'][$f]) ? $theDt['index'][$f] : -1;
  2402.                                                         if ($indexForThis == -1) {
  2403.                                                             $indexForThis $lastIndex;
  2404.                                                             $lastIndex++;
  2405.                                                         }
  2406.                                                         $unitPrice = isset($theDt['ar_unit_price'][$f]) ? $theDt['ar_unit_price'][$f] : 0;
  2407.                                                         if (!is_numeric($unitPrice)) $unitPrice 0;
  2408.                                                         $totalPrice $unit $unitPrice;
  2409.                                                         $segmentIndex = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : 0;
  2410.                                                         if ($oldSegmentSystem == 1)
  2411.                                                             $segmentIndex 1000 $segmentIndex;
  2412.                                                         $sequence = isset($theDt['ar_segmentIndex'][$f]) ? $theDt['ar_segmentIndex'][$f] : '_UNSET_';
  2413.                                                         if (!isset($lastSequenceBySegment[$segmentIndex]))
  2414.                                                             $lastSequenceBySegment[$segmentIndex] = -1;
  2415.                                                         if ($sequence == '_UNSET_')
  2416.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2417.                                                         else if ($sequence == $lastSequenceBySegment[$segmentIndex])
  2418.                                                             $sequence $lastSequenceBySegment[$segmentIndex] + 1;
  2419.                                                         $lastSequenceBySegment[$segmentIndex] = $sequence;
  2420.                                                         $unitSalesPrice = isset($theDt['ar_unit_sales_price'][$f]) ? $theDt['ar_unit_sales_price'][$f] : $unitPrice;
  2421.                                                         $totalSalesPrice $unit $unitSalesPrice;
  2422.                                                         $marginAmount = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitSalesPrice $unitPrice);
  2423.                                                         $marginRate = isset($theDt['ar_ma'][$f]) ? $theDt['ar_ma'][$f] : ($unitPrice == : (100 $marginAmount $unitPrice));
  2424.                                                         $discountAmount = isset($theDt['ar_dr'][$f]) ? $theDt['ar_dr'][$f] : 0;
  2425.                                                         $discountRate = isset($theDt['ar_da'][$f]) ? $theDt['ar_da'][$f] : ($totalSalesPrice == : (100 $discountAmount $totalSalesPrice));
  2426.                                                         $discountedAmount $totalSalesPrice $discountAmount;
  2427.                                                         $taxRate = isset($theDt['ar_tax_percentage'][$f]) ? $theDt['ar_tax_percentage'][$f] : ($unitPrice == : (100 $discountAmount $unitPrice));
  2428.                                                         $taxAmount = isset($theDt['ar_tax_amount'][$f]) ? $theDt['ar_tax_amount'][$f] : 0;
  2429.                                                         $finalAmount $discountedAmount $taxAmount;
  2430.                                                         $row = array(
  2431.                                                             'type' => 6,//1:product 2=service 4=tools 5:text 6: expense against head
  2432.                                                             'id' => $pid,
  2433.                                                             'index' => $indexForThis,
  2434.                                                             'isForeign' => isset($theDt['is_foreign_cost'][$f]) ? $theDt['is_foreign_cost'][$f] : 0,
  2435.                                                             'sequence' => $sequence,
  2436.                                                             'segmentIndex' => $segmentIndex,
  2437.                                                             'soItemId' => isset($theDt['ar_soItemId'][$f]) ? $theDt['ar_soItemId'][$f] : 0,
  2438.                                                             'soItemDelivered' => isset($theDt['ar_soItemDelivered'][$f]) ? $theDt['ar_soItemDelivered'][$f] : 0,
  2439.                                                             'soItemFound' => isset($theDt['ar_soItemFound'][$f]) ? $theDt['ar_soItemFound'][$f] : 0,
  2440.                                                             'alias' => isset($theDt['ar_alias'][$f]) ? $theDt['ar_alias'][$f] : '',
  2441.                                                             'name' => isset($theDt['ar_name'][$f]) ? $theDt['ar_name'][$f] : '',
  2442.                                                             'note' => isset($theDt['ar_note'][$f]) ? $theDt['ar_note'][$f] : '',
  2443.                                                             'fdm' => isset($theDt['ar_fdm'][$f]) ? $theDt['ar_fdm'][$f] : null,
  2444.                                                             'unit' => isset($theDt['ar_units'][$f]) ? $theDt['ar_units'][$f] : 0,
  2445.                                                             'unitTypeId' => isset($theDt['ar_unit_type'][$f]) ? $theDt['ar_unit_type'][$f] : 0,
  2446.                                                             'unitPrice' => $unitPrice,
  2447.                                                             'totalPrice' => $totalPrice,
  2448.                                                             'unitSalesPrice' => $unitSalesPrice,
  2449.                                                             'totalSalesPrice' => $totalSalesPrice,
  2450.                                                             'marginRate' => $marginRate,
  2451.                                                             'marginAmount' => $marginAmount,
  2452.                                                             'discountRate' => $discountRate,
  2453.                                                             'discountAmount' => $discountAmount,
  2454.                                                             'discountedAmount' => $discountedAmount,
  2455.                                                             'taxRate' => $taxRate,
  2456.                                                             'taxAmount' => $taxAmount,
  2457.                                                             'finalAmount' => $finalAmount,
  2458.                                                             'recurring' => isset($theDt['ar_recurring'][$f]) ? $theDt['ar_recurring'][$f] : 0,
  2459.                                                             'currency' => isset($theDt['ar_currency_id'][$f]) ? $theDt['ar_currency_id'][$f] : 0,
  2460.                                                             'currencyText' => isset($theDt['ar_currency_text'][$f]) ? $theDt['ar_currency_text'][$f] : '',
  2461.                                                             'currencyMultiplyRate' => isset($theDt['ar_currency_multiply_rate'][$f]) ? $theDt['ar_currency_multiply_rate'][$f] : 1,
  2462.                                                             'incoterm' => isset($theDt['incoterm'][$f]) ? $theDt['incoterm'][$f] : '',
  2463.                                                             'taxId' => isset($theDt['ar_tax_config_id'][$f]) ? $theDt['ar_tax_config_id'][$f] : 0,
  2464.                                                             'taxName' => isset($theDt['ar_tax_config_text'][$f]) ? $theDt['ar_tax_config_text'][$f] : '',
  2465.                                                             'dependencyOnIndex' => isset($theDt['ar_dependency_of_index'][$f]) ? $theDt['ar_dependency_of_index'][$f] : 0,
  2466.                                                             'dependencyOnPid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
  2467.                                                             'dependencyOnSid' => isset($theDt['ar_dependency_of_ar_id'][$f]) ? $theDt['ar_dependency_of_ar_id'][$f] : 0,
  2468.                                                             'dependencyOnSegment' => isset($theDt['ar_dependency_of_ar_index'][$f]) ? $theDt['ar_dependency_of_ar_index'][$f] : 0,
  2469.                                                             'warranty' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : 0,
  2470.                                                             'origin' => isset($theDt['ar_origin'][$f]) ? $theDt['ar_origin'][$f] : 0,
  2471.                                                             'origins' => isset($theDt['ar_origin'][$f]) ? [$theDt['ar_origin'][$f]] : [],
  2472.                                                             'scope' => isset($theDt['ar_scope'][$f]) ? $theDt['ar_scope'][$f] : 0,
  2473.                                                             'scopeId' => isset($theDt['ar_scopeHolderId'][$f]) ? [$theDt['ar_scopeHolderId'][$f]] : 0,
  2474.                                                             'scopeName' => isset($theDt['ar_scopeHolderName'][$f]) ? [$theDt['ar_scopeHolderName'][$f]] : '',
  2475.                                                             'scopeDescription' => isset($theDt['ar_scopeDescription'][$f]) ? [$theDt['ar_scopeDescription'][$f]] : '',
  2476.                                                             'deliverySchedule' => isset($theDt['ar_delivery_schedule'][$f]) ? $theDt['ar_delivery_schedule'][$f] : [],
  2477.                                                             'deliveryPorts' => isset($theDt['ar_delivery_ports'][$f]) ? $theDt['ar_delivery_ports'][$f] : [],
  2478.                                                             'billingSchedule' => isset($theDt['ar_billing_schedule'][$f]) ? $theDt['ar_billing_schedule'][$f] : [],
  2479.                                                             'referenceNo' => isset($theDt['ar_reference_price'][$f]) ? $theDt['ar_reference_price'][$f] : '',
  2480.                                                             'referenceFiles' => isset($theDt['ar_reference_price_file'][$f]) ? $theDt['ar_reference_price_file'][$f] : '',
  2481.                                                         );
  2482.                                                         $dt_poka['rowData'][] = $row;
  2483.                                                     }
  2484. //                                                $configJson['debugData'][]=$dt_poka;
  2485.                                             }
  2486.                                             $newSingleSet['rowData'] = $dt_poka['rowData'];
  2487.                                             unset($dt_poka['productSegmentData']);
  2488.                                             unset($dt_poka['serviceSegmentData']);
  2489.                                             unset($dt_poka['Products']);
  2490.                                             unset($dt_poka['Services']);
  2491.                                             $newData[$kho] = $newSingleSet;
  2492.                                         }
  2493.                                         $theDocData->setData(json_encode($newData));
  2494.                                         $em->persist($theDocData);
  2495.                                         $em->flush();
  2496.                                     }
  2497.                                     $tempId 0;
  2498.                                     if ($entityNameHere == 'SalesProposal'$tempId $the_actual_doc->getSalesProposalId();
  2499.                                     if ($entityNameHere == 'ProjectBoq'$tempId $the_actual_doc->getProjectId();
  2500.                                     if ($entityNameHere == 'Opportunity'$tempId $the_actual_doc->getOpportunityId();
  2501.                                     $configJson['debugData'][] = array(
  2502.                                         'entityNameHere' => $entityNameHere,
  2503.                                         'entityId' => $tempId,
  2504.                                         'dt' => $newData,
  2505.                                     );
  2506.                                 }
  2507.                                 $the_actual_doc->setData(null);
  2508.                                 $the_actual_doc->setDocumentDataId($theDocData->getId());
  2509.                                 $em->flush();
  2510.                                 if ($entityNameHere == 'ProjectBoq') {
  2511.                                     $theProj $em->getRepository('ApplicationBundle\\Entity\\Project')
  2512.                                         ->findOneBy(
  2513.                                             array(
  2514.                                                 'projectId' => $the_actual_doc->getProjectId()
  2515.                                             )
  2516.                                         );
  2517.                                     if ($theProj)
  2518.                                         $theProj->setDocumentDataId($the_actual_doc->getDocumentDataId());
  2519.                                     $em->flush();
  2520.                                 }
  2521.                             }
  2522.                         }
  2523.                     }
  2524.                     if ($request->query->get('newDocDataItemSegmentFix'0) == 1) {
  2525.                         $the_actual_docs $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2526.                             ->findBy(
  2527.                                 array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  2528.                                 )
  2529.                             );
  2530.                         foreach ($the_actual_docs as $the_actual_doc) {
  2531.                             //now the data
  2532.                             //first find the docData if available
  2533.                             $theDocData $the_actual_doc;
  2534.                                 $data = [];
  2535.                                 $newData = [];
  2536.                                 $data json_decode($the_actual_doc->getData(), true);
  2537.                                 if ($data == null)
  2538.                                     $data = [];
  2539.                                 if (!empty($data)) {
  2540.                                     $last_key array_key_last($data);
  2541.                                     $lastIndex 0;
  2542.                                     foreach ($data as $kho => $dt_poka) {
  2543.                                         $newSingleSet $dt_poka;
  2544.                                         $newSegmentData = array();
  2545.                                         //unify the ids of segmnent. services will start from 1000+service segmentId for unification
  2546.                                         if (!isset($newSingleSet['itemSegmentData'])) {
  2547.                                             $newSingleSet['itemSegmentData'] = [];
  2548.                                         }
  2549.                                         if ($newSingleSet['itemSegmentData'] == null) {
  2550.                                             $newSingleSet['itemSegmentData'] = [];
  2551.                                         }
  2552.                                         if (empty($newSingleSet['itemSegmentData'])) {
  2553.                                             $gupu = [];
  2554.                                             $newModSeg $gupu;
  2555.                                             $newModSeg['index'] = 0;
  2556.                                             $newModSeg['title'] = 'Items & Services';
  2557.                                             $newModSeg['scfc'] = 0;
  2558.                                             $newModSeg['uomCust'] = '';
  2559.                                             $newModSeg['unitCust'] = isset($gupu['unitCust']) ? $gupu['unitCust'] : '';
  2560.                                             $newModSeg['priceCust'] = isset($gupu['priceCust']) ? $gupu['priceCust'] : '';
  2561.                                             $newModSeg['currCust'] = isset($gupu['currCust']) ? $gupu['currCust'] : '';
  2562.                                             $newModSeg['descCust'] = isset($gupu['descCust']) ? $gupu['descCust'] : '';
  2563.                                             $newModSeg['scope'] = isset($gupu['scope']) ? $gupu['scope'] : 0;
  2564.                                             $newModSeg['scopeId'] = isset($gupu['scopeId']) ? $gupu['scopeId'] : 0;
  2565.                                             $newModSeg['scopeName'] = isset($gupu['scopeName']) ? $gupu['scopeName'] : '';
  2566.                                             $newModSeg['scopeDescription'] = isset($gupu['scopeDescription']) ? $gupu['scopeDescription'] : '';
  2567.                                             $newSegmentData[] = $newModSeg;
  2568.                                             $newSingleSet['itemSegmentData'] = $newSegmentData;
  2569.                                         }
  2570.                                         $newData[$kho] = $newSingleSet;
  2571.                                     }
  2572.                                     $theDocData->setData(json_encode($newData));
  2573.                                     $em->persist($theDocData);
  2574.                                     $em->flush();
  2575.                                 }
  2576.                             $em->flush();
  2577.                         }
  2578.                     }
  2579.                     if ($request->query->get('convertMarginToMarkupOldDocumentData'0) == 1) {
  2580.                         $the_actual_docs $em->getRepository('ApplicationBundle\\Entity\\DocumentData')
  2581.                             ->findBy(
  2582.                                 array(//                                        GeneralConstant::$Entity_id_field_list[$ent] => $entity_id,
  2583.                                 )
  2584.                             );
  2585.                         foreach ($the_actual_docs as $the_actual_doc) {
  2586.                             //now the data
  2587.                             //first find the docData if available
  2588.                             $theDocData = [];
  2589.                             $theDocData json_decode($the_actual_doc->getData(), true);
  2590.                             if ($theDocData == null)
  2591.                                 $theDocData = [];
  2592.                             $entries $theDocData;
  2593.                             foreach ($entries as $jojo => $mod) {
  2594.                                 if (isset($mod['rowData'])) {
  2595.                                     $rows $mod['rowData'];
  2596.                                     if (is_string($rows))
  2597.                                         $rows json_decode($rowstrue);
  2598.                                     if ($rows == null)
  2599.                                         $rows = [];
  2600.                                     foreach ($rows as $indu => $row) {
  2601.                                         if (!is_numeric($row['unitSalesPrice'])) $row['unitSalesPrice'] = 0;
  2602.                                         if (!is_numeric($row['unitPrice'])) $row['unitPrice'] = 0;
  2603.                                         if (!is_numeric($row['marginAmount'])) $row['marginAmount'] = 0;
  2604.                                         if (!isset($row['markupRate'])) {
  2605.                                             $rows[$indu]['markupRate'] = $row['marginRate'];
  2606.                                         }
  2607.                                         $rows[$indu]['marginRate'] = $row['unitSalesPrice'] != 100 $row['marginAmount'] / $row['unitSalesPrice'] : 0;
  2608.                                     }
  2609.                                     $entries[$jojo]['rowData'] = $rows;
  2610.                                 }
  2611.                             }
  2612.                             $the_actual_doc->setData(json_encode($entries));
  2613. //                                $the_actual_doc->setDocumentDataId($theDocData->getId());
  2614.                             $em->flush();
  2615.                         }
  2616.                     }
  2617.                     if ($request->query->get('rectifyTransCurr'0) == 1) {
  2618.                         $query "
  2619.                                     UPDATE `acc_transaction_details` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  2620.                                     UPDATE `acc_transaction_details` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  2621.                                     UPDATE `acc_transactions` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  2622.                                     UPDATE `acc_transactions` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  2623.                                     UPDATE `expense_invoice` SET currency_multiply_rate=1 WHERE currency_multiply_rate is NULL or currency_multiply_rate=0 ;
  2624.                                     UPDATE `expense_invoice` SET currency_multiply=1 WHERE currency_multiply is NULL or currency_multiply=0 ;
  2625.   
  2626.                      
  2627.                       ";
  2628.                         $stmt $em->getConnection()->executeStatement($query);
  2629.                     }
  2630.                     if ($request->query->get('deepRefresh'0) == 1) {
  2631.                         //new for updating app id
  2632.                         $get_kids_sql "UPDATE `company` set app_id=" $entry['appId'] . " ;
  2633.                         UPDATE `sys_user` set app_id=" $entry['appId'] . " ;";
  2634.                         $get_kids_sql .= "
  2635.                                       UPDATE `inv_products` set default_color_id=0  where default_color_id ='' or default_color_id is null ;
  2636.                                       UPDATE `inv_products` set default_size=0  where default_size ='' or default_size is null ;
  2637.                                         UPDATE `inventory_storage` set color= (select default_color_id from inv_products where inv_products.id=inventory_storage.product_id)
  2638.                                          where inventory_storage.color =0 or inventory_storage.color is null or inventory_storage.color ='' ;
  2639.                                          UPDATE `inventory_storage` set owner_type= 0 where inventory_storage.owner_type is null or inventory_storage.owner_type ='' ;
  2640.                                          UPDATE `inventory_storage` set owner_id= 0 where inventory_storage.owner_id is null or inventory_storage.owner_id ='' ;
  2641.                                          UPDATE `acc_clients` set client_level= 1 where client_level is null or client_level ='' or client_level=0 ;
  2642.                                          UPDATE `acc_clients` set parent_id= 0 where parent_id is null or parent_id ='' ;
  2643.                                          UPDATE `sales_order` set sales_level= 0 where sales_level is null or sales_level ='' ;
  2644.                                          ";
  2645.                         $get_kids_sql .= "                UPDATE `inventory_storage` set color=0 where color='' or color is null;
  2646.                                         UPDATE `inventory_storage` set `size`=0 where `size`='' or size is null;
  2647.                                         UPDATE `inv_item_transaction` set color=0 where color='' or color is null;
  2648.                                         UPDATE `inv_item_transaction` set `size`=0 where `size`='' or size is null;
  2649.                                         UPDATE `inv_closing_balance` set color=0 where color='' or color is null;
  2650.                                         UPDATE `inv_closing_balance` set `size`=0 where `size`='' or size is null;
  2651.                                         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);
  2652.                                         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);
  2653.                                         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);
  2654.                                         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);
  2655.                                         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);
  2656.                                         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);
  2657.                                         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);
  2658.                                         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);
  2659.                                         UPDATE `inventory_storage` set curr_purchase_price= (select curr_purchase_price from inv_products where inv_products.id=inventory_storage.product_id)
  2660.                                          where inventory_storage.curr_purchase_price=0 or inventory_storage.curr_purchase_price is null;
  2661.                                        delete TABLE service_opearation;
  2662.                                        delete TABLE assesment_and_confirmation;
  2663.                                        ";
  2664.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2665.                         $query "SELECT * from  company   where 1";
  2666.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2667. //                        
  2668.                         $results $stmt;
  2669.                         if (empty($results)) {
  2670.                             //insert client level query here
  2671.                             $createdDate = new \DateTime();
  2672.                             $cgEntry $gocEntryObjectList[$gocId];
  2673.                             $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
  2674. (1, '" $cgEntry->getName() . "', '" $cgEntry->getImage() . "'," $cgEntry->getAppId() . ",'" $createdDate->format('Y-m-d H:i:s') . "', '" $cgEntry->getCompanyGroupHash() . "','" $cgEntry->getCompanyGroupUniqueCode() . "',NULL, NULL,1);";
  2675.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2676.                         }
  2677.                         $query "SELECT * from  client_level   where 1";
  2678.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2679. //                        
  2680.                         $results $stmt;
  2681.                         if (empty($results)) {
  2682.                             //insert client level query here
  2683.                             $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
  2684. (1, 'Primary',1, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2685. (2, 'Secondary',2, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2686. (3, 'Tertiary',3, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)
  2687. ;";
  2688.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2689. //                            
  2690.                         }
  2691.                         $query "SELECT * from  sales_level   where 1";
  2692.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2693.                         $results $stmt;
  2694.                         if (empty($results)) {
  2695.                             //insert client level query here
  2696.                             $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
  2697. (1, 'Primary',0, 1, 0, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2698. (2, 'Secondary',1, 1, 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL),
  2699. (3, 'Tertiary',2, 1, 2, 1, '2022-02-22 20:58:51', NULL, NULL, NULL);";
  2700.                             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2701.                         }
  2702.                         $services $em->getRepository('ApplicationBundle\\Entity\\AccService')->findBy(array(
  2703. //                            'serviceId' => $ex_id//for now for stock of goods
  2704. //                    'opening_locked'=>0
  2705.                         ));
  2706.                         foreach ($services as $service) {
  2707.                             $productFdm $service->getProductFdm();
  2708.                             if (strpos($productFdm'P_') !== false)
  2709.                                 $productFdm str_replace('P_''P' $service->getServiceId() . '_'$productFdm);
  2710.                             $service->setProductFdm($productFdm);
  2711.                             $em->flush();
  2712.                         }
  2713.                         $query "SELECT * from  warehouse_action   where 1";
  2714.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  2715.                         $results $stmt;
  2716.                         if (!empty($results)) {
  2717.                             //insert client level query here
  2718.                             foreach ($results as $qryResult) {
  2719.                                 $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'];
  2720.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2721.                             }
  2722.                         } else {
  2723.                             foreach (GeneralConstant::$warehouse_action_list as $dt_pika) {
  2724.                                 $get_kids_sql "INSERT INTO `warehouse_action` (`id`, `name`,`company_id`,  `status`, `created_at`, `updated_at`, `doc_booked_flag`, `time_stamp_of_form`)
  2725. VALUES(" $dt_pika['id'] . ", '" $dt_pika['name'] . "', 1, 1, '2022-02-22 20:58:51', NULL, NULL, NULL)";
  2726.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2727.                             }
  2728. //
  2729.                             $query "SELECT * from  warehouse_action   where 1";
  2730.                             $stmt $em->getConnection()->fetchAllAssociative($query);
  2731.                             $newresults $stmt;
  2732.                             foreach ($newresults as $qryResult) {
  2733.                                 $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'];
  2734.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2735.                             }
  2736.                         }
  2737.                         $modify_product_by_code_ids_table_list = [
  2738.                             'stock_transfer_item',
  2739.                         ];
  2740.                         $modify_product_by_code_ids_field_list = [
  2741.                             'product_by_code_ids'
  2742.                         ];
  2743.                         $modify_product_by_code_sales_code_field_list = [
  2744.                             'sales_code_range'
  2745.                         ];
  2746.                         $modify_product_by_code_item_id_field_list = [
  2747.                             'id'
  2748.                         ];
  2749.                         foreach ($modify_product_by_code_ids_table_list as $mindex => $dt_table_name) {
  2750.                             $get_kids_sql "select * from " $dt_table_name " where " .
  2751.                                 $modify_product_by_code_ids_field_list[$mindex] . " is null  or " .
  2752.                                 $modify_product_by_code_ids_field_list[$mindex] . " =''  or " .
  2753.                                 $modify_product_by_code_ids_field_list[$mindex] . " ='[]' ;";
  2754.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2755.                             $dataList $stmt;
  2756.                             foreach ($dataList as $mdt) {
  2757.                                 $sales_code_range_str $mdt[$modify_product_by_code_sales_code_field_list[$mindex]];
  2758.                                 $sales_code_range = [];
  2759.                                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  2760.                                     $sales_code_range json_decode($sales_code_range_strtrue512JSON_BIGINT_AS_STRING);
  2761.                                 } else {
  2762.                                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  2763.                                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$sales_code_range_str);
  2764.                                     $sales_code_range json_decode($json_without_bigintstrue);
  2765.                                 }
  2766. //                    $sales_code_range= json_decode($entry->getSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  2767.                                 $pbcIds = [];
  2768.                                 if ($sales_code_range == null)
  2769.                                     $sales_code_range = [];
  2770.                                 if (empty($sales_code_range)) {
  2771.                                 } else {
  2772.                                     $get_kids_sql_2 "select * from  product_by_code  where sales_code in ('" implode("','"$sales_code_range) . "');";
  2773.                                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  2774.                                     $dataList $stmt;
  2775.                                     foreach ($dataList as $pbc) {
  2776.                                         $pbcIds[] = $pbc['product_by_code_id'];
  2777.                                     }
  2778.                                 }
  2779.                                 $get_kids_sql_3 "update " $dt_table_name .
  2780.                                     " set  " $modify_product_by_code_ids_field_list[$mindex] . "='" json_encode($pbcIds) . "'" .
  2781.                                     " where " $modify_product_by_code_item_id_field_list[$mindex] . "=" $mdt[$modify_product_by_code_item_id_field_list[$mindex]] . ";";
  2782.                                 $stmt $em->getConnection()->executeStatement($get_kids_sql_3);
  2783.                             }
  2784.                         }
  2785.                         $modify_voucher_date_table_list = [
  2786. //                            'stock_received_note',
  2787. //                            'stock_transfer',
  2788. //                            'stock_consumption_note',
  2789. //                            'fixed_asset_conversion_note',
  2790. //                            'fixed_asset_product'
  2791.                         ];
  2792.                         $modify_date_field_list = [
  2793. //                            'stock_received_note_date',
  2794. //                            'stock_transfer_date',
  2795. //                            'stock_consumption_note_date',
  2796. //                            'fixed_asset_conversion_note_date',
  2797. //                            'fixed_asset_product'
  2798.                         ];
  2799.                         foreach ($modify_voucher_date_table_list as $mindex => $dt_table_name) {
  2800.                             $get_kids_sql "select * from " $dt_table_name " where 1;";
  2801.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2802.                             $dataList $stmt;
  2803.                             foreach ($dataList as $mdt) {
  2804.                                 $curr_v_ids json_decode($mdt['voucher_ids'], true);
  2805.                                 if ($curr_v_ids == null)
  2806.                                     $curr_v_ids = [];
  2807.                                 $date_for_this $mdt[$modify_date_field_list[$mindex]];
  2808.                                 foreach ($curr_v_ids as $vid) {
  2809.                                     //new for updating app id
  2810.                                     $get_kids_sql "UPDATE `acc_transactions`
  2811.                                                           set transaction_date='" $date_for_this "',
  2812.                                                               ledger_hit_date='" $date_for_this "'
  2813.                                                           where transaction_id=" $vid ";
  2814.                                         UPDATE `acc_transactions_details`
  2815.                                                           set transaction_date='" $date_for_this "',
  2816.                                                               ledger_hit_date='" $date_for_this "'
  2817.                                                           where transaction_id=" $vid ";";
  2818.                                     $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2819.                                 }
  2820.                             }
  2821.                         }
  2822.                         $modify_voucher_narration_table_list = [
  2823. //                            'expense_invoice',
  2824. //                            'stock_transfer',
  2825. //                            'stock_consumption_note',
  2826. //                            'fixed_asset_conversion_note',
  2827. //                            'fixed_asset_product'
  2828.                         ];
  2829.                         $modify_narr_field_list = [
  2830. //                            'description',
  2831. //                            'stock_transfer_date',
  2832. //                            'stock_consumption_note_date',
  2833. //                            'fixed_asset_conversion_note_date',
  2834. //                            'fixed_asset_product'
  2835.                         ];
  2836.                         foreach ($modify_voucher_narration_table_list as $mindex => $dt_table_name) {
  2837.                             $get_kids_sql "select * from " $dt_table_name " where 1;";
  2838.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  2839.                             $dataList $stmt;
  2840.                             foreach ($dataList as $mdt) {
  2841.                                 $curr_v_ids json_decode($mdt['voucher_ids'], true);
  2842.                                 if ($curr_v_ids == null)
  2843.                                     $curr_v_ids = [];
  2844.                                 $narr_for_this $mdt[$modify_narr_field_list[$mindex]];
  2845.                                 foreach ($curr_v_ids as $vid) {
  2846.                                     //new for updating app id
  2847.                                     $get_kids_sql "UPDATE `acc_transactions`
  2848.                                                           set description='" $narr_for_this "'
  2849.                                                           where transaction_id=" $vid "; ";
  2850.                                     $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2851.                                 }
  2852.                             }
  2853.                         }
  2854.                     }
  2855.                     if ($request->query->get('employeeDetailsToProfile'0) == 1) {
  2856.                         $migrationStats $this->migrateEmployeeDetailsToProfile($em);
  2857.                         $configJson['employeeDetailsToProfile'] = $migrationStats;
  2858.                     }
  2859.                     $get_kids_sql "update `company_group` set `schema_update_pending_flag` =0 where `id`=$gocId;";
  2860.                     $stmt $em_goc->getConnection()->executeStatement($get_kids_sql);
  2861.                     $configJson['success'] = true;
  2862.                     //this is for large amount of goc we will see  later
  2863. //                        file_put_contents($path, json_encode($configJson));//overwrite
  2864. //                        return $this->redirectToRoute('update_database_schema');
  2865.                 }
  2866.             }
  2867.             return new JsonResponse($configJson);
  2868.         } else {
  2869.             return $this->render(
  2870.                 '@System/pages/server_actions.html.twig',
  2871.                 $dtHere
  2872.             );
  2873.         }
  2874.     }
  2875.     public function UpdateRoutesAction(Request $request)
  2876.     {
  2877.         $message "";
  2878.         $gocList = [];
  2879.         $outputList = [];
  2880.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2881.         $appIdFilter = (int)$request->get('appId'$request->get('app_id'0));
  2882.         $em $this->getDoctrine()->getManager('company_group');
  2883.         $em->getConnection()->connect();
  2884.         $connected $em->getConnection()->isConnected();
  2885.         if ($connected)
  2886.             if ($systemType != '_CENTRAL_') {
  2887.                 $findByQuery = array(
  2888.                     'active' => 1
  2889.                 );
  2890.                 if ($appIdFilter 0) {
  2891.                     $findByQuery['appId'] = $appIdFilter;
  2892.                 }
  2893.                 $gocList $this->getDoctrine()->getManager('company_group')
  2894.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  2895.                     ->findBy($findByQuery);
  2896.             }
  2897.         $gocDataList = [];
  2898.         foreach ($gocList as $entry) {
  2899.             $d = array(
  2900.                 'name' => $entry->getName(),
  2901.                 'id' => $entry->getId(),
  2902.                 'dbName' => $entry->getDbName(),
  2903.                 'dbUser' => $entry->getDbUser(),
  2904.                 'dbPass' => $entry->getDbPass(),
  2905.                 'dbHost' => $entry->getDbHost(),
  2906.                 'appId' => $entry->getAppId(),
  2907.                 'companyRemaining' => $entry->getCompanyRemaining(),
  2908.                 'companyAllowed' => $entry->getCompanyAllowed(),
  2909.                 'enabledModuleIdList' => $entry->getEnabledModuleIdList(),
  2910.             );
  2911.             $gocDataList[$entry->getId()] = $d;
  2912.         }
  2913.         $gocDbName '';
  2914.         $gocDbUser '';
  2915.         $gocDbPass '';
  2916.         $gocDbHost '';
  2917.         $gocId 0;
  2918. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  2919.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  2920.         if (!file_exists($config_dir)) {
  2921.             mkdir($config_dir0777true);
  2922.         }
  2923. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  2924. //        $content = file_exists($path) ? file_get_contents($path) : null;
  2925.         $content = [];
  2926.         $configJson = array();
  2927.         if ($content)
  2928.             $configJson json_decode($contenttrue);
  2929.         $configJsonOld $configJson;
  2930. //        if($configJson)
  2931. //        {
  2932. //
  2933. //        }
  2934. //        else
  2935.         {
  2936.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  2937.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  2938.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  2939.             $configJson['initiateDataBaseFlagByGoc'] = array();
  2940.             $configJson['motherLode'] = "http://innobd.com";
  2941.             foreach ($gocDataList as $gocId => $entry) {
  2942.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  2943.             }
  2944.         }
  2945.         //now check if database shcema update is true
  2946. //        if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
  2947.         if (1//temporary overwrite all
  2948.         {
  2949.             //if goclist is not empty switch to each company dbase and schema update
  2950. //            if(!empty($gocDataList))
  2951.             if (1) {
  2952.                 foreach ($gocDataList as $gocId => $entry) {
  2953.                     if ($configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
  2954.                         $connector $this->container->get('application_connector');
  2955.                         $connector->resetConnection(
  2956.                             'default',
  2957.                             $gocDataList[$gocId]['dbName'],
  2958.                             $gocDataList[$gocId]['dbUser'],
  2959.                             $gocDataList[$gocId]['dbPass'],
  2960.                             $gocDataList[$gocId]['dbHost'],
  2961.                             $reset true);
  2962.                         $em $this->getDoctrine()->getManager();
  2963. //                        $iv = '1234567812345678';
  2964. //                        $pass = $hash;
  2965. //
  2966. //                        $str = $str . 'YmLRocksLikeABoss';
  2967. //                        $data = openssl_encrypt($str, "AES-128-CBC", $pass, OPENSSL_RAW_DATA, $iv);
  2968. //
  2969. //                        $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $hash, OPENSSL_RAW_DATA, $iv);
  2970. //
  2971.                         //now 1st of all lets get the Existing routes
  2972.                         $extRoutesById = [];
  2973.                         $extRoutesByRoute = [];
  2974.                         $modules $em->getRepository("ApplicationBundle\\Entity\\SysModule")
  2975.                             ->findBy(
  2976.                                 array()
  2977.                             );
  2978.                         $module_data = [];
  2979.                         foreach ($modules as $mod) {
  2980.                             $dt = array(
  2981.                                 'id' => $mod->getModuleId(),
  2982.                                 'route' => $mod->getModuleRoute(),
  2983.                                 'name' => $mod->getModuleName(),
  2984.                                 'parentId' => $mod->getParentId(),
  2985.                                 'level' => $mod->getLevel(),
  2986.                                 'eFA' => $mod->getEnabledForAll(),
  2987.                             );
  2988.                             $extRoutesById[$mod->getModuleId()] = $dt;
  2989.                             $extRoutesByRoute[$mod->getModuleRoute()] = $dt;
  2990.                         }
  2991.                         //now clear the module table
  2992.                         $get_kids_sql "truncate `sys_module` ; ";
  2993.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  2994.                         $enabledModuleIds $this->getEnabledModuleIdsForCompanyRouteSync($entry$systemType);
  2995.                         $newRoutes $this->filterModuleRoutesForCompany($enabledModuleIds);
  2996.                         $newRoutesByRoute = [];
  2997.                         foreach ($newRoutes as $mod) {
  2998.                             $new = new SysModule();
  2999.                             $new->setModuleId($mod['id']);
  3000.                             $new->setModuleRoute($mod['route']);
  3001.                             $new->setModuleName($mod['name']);
  3002.                             $new->setParentId($mod['parentId']);
  3003.                             $new->setlevel($mod['level']);
  3004.                             $new->setEnabledForAll($mod['eFA']);
  3005.                             $new->setStatus(isset($mod['status']) ? $mod['status'] : GeneralConstant::ACTIVE);
  3006. //                $new->set(GeneralConstant::ACTIVE);
  3007.                             $em->persist($new);
  3008.                             $newRoutesByRoute[$mod['route']] = $mod;
  3009.                         }
  3010.                         $em->flush();
  3011.                         //now lets get the ext modules for positions
  3012.                         $depPosDefModules $em->getRepository("ApplicationBundle\\Entity\\SysDeptPositionDefaultModule")
  3013.                             ->findBy(
  3014.                                 array()
  3015.                             );
  3016.                         foreach ($depPosDefModules as $defmod) {
  3017.                             $moduleList json_decode($defmod->getModuleIds());
  3018.                             $newModuleList = [];
  3019.                             foreach ($moduleList as $oldId) {
  3020.                                 $newId 0;
  3021.                                 if (isset($extRoutesById[$oldId])) {
  3022.                                     if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
  3023.                                         $newModuleList[] = $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
  3024.                                     }
  3025.                                 }
  3026.                             }
  3027.                             $defmod->setModuleIds(json_encode($newModuleList));
  3028.                             $em->flush();
  3029.                         }
  3030.                         //now users
  3031.                         $users $em->getRepository("ApplicationBundle\\Entity\\SysUser")
  3032.                             ->findBy(
  3033.                                 array()
  3034.                             );
  3035.                         foreach ($users as $defmod) {
  3036.                             $moduleList json_decode($defmod->getModuleIds());
  3037.                             if ($moduleList == null)
  3038.                                 continue;
  3039.                             $newModuleList = [];
  3040.                             foreach ($moduleList as $oldId) {
  3041.                                 $newId 0;
  3042.                                 if (isset($extRoutesById[$oldId])) {
  3043.                                     if (isset($newRoutesByRoute[$extRoutesById[$oldId]['route']])) {
  3044.                                         $newModuleList[] = $newRoutesByRoute[$extRoutesById[$oldId]['route']]['id'];
  3045.                                     }
  3046.                                 }
  3047.                             }
  3048.                             $defmod->setModuleIds(json_encode($newModuleList));
  3049.                             $em->flush();
  3050.                         }
  3051.                         $module_data = [];
  3052. //                        $tool = new SchemaTool($em);
  3053. //
  3054. //                        $classes = $em->getMetadataFactory()->getAllMetadata();
  3055. ////                    $tool->createSchema($classes);
  3056. //                        $tool->updateSchema($classes);
  3057. //
  3058. //                        //new for updating app id
  3059. //                        $get_kids_sql = "UPDATE `company` set app_id=".$entry['appId']." ;
  3060. //                                        UPDATE `sys_user` set app_id=".$entry['appId']." ;";
  3061. //                        $stmt = $em->getConnection()->executeStatement($get_kids_sql);
  3062. //                        
  3063. //                        
  3064. //
  3065. //                        $configJson['initiateDataBaseFlagByGoc'][$gocId."_".$entry['appId']]=GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3066.                         //this is for large amount of goc we will see  later
  3067. //                        file_put_contents($path, json_encode($configJson));//overwrite
  3068. //                        return $this->redirectToRoute('update_database_schema');
  3069.                     }
  3070.                 }
  3071.             } else {
  3072.                 $em $this->getDoctrine()->getManager();
  3073.                 $tool = new SchemaTool($em);
  3074. //                    $classes = array(
  3075. //                        $em->getClassMetadata('Entities\User'),
  3076. //                        $em->getClassMetadata('Entities\Profile')
  3077. //                    );
  3078.                 $classes $em->getMetadataFactory()->getAllMetadata();
  3079. //                    $tool->createSchema($classes);
  3080.                 $tool->updateSchema($classes);
  3081.             }
  3082.         }
  3083.         $allSchemaUpdateDone 1;
  3084.         foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
  3085.             if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
  3086.                 $allSchemaUpdateDone 0;
  3087.         }
  3088.         if ($allSchemaUpdateDone == 1)
  3089.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  3090.         ///last
  3091. //        file_put_contents($path, json_encode($configJson));//overwrite
  3092.         return new Response(json_encode($configJsonOld));
  3093.     }
  3094.     public function CheckTimeStampAction(Request $request)
  3095.     {
  3096.         $message "";
  3097.         $gocList = [];
  3098.         $outputList = [];
  3099.         $toConvertDateStrFromQry $request->query->get('convDate''');
  3100.         $currentRegionalDateStrFromQry $request->query->get('currDate''');
  3101.         $convertedTime MiscActions::ConvertRegionalTimeToServerTime($currentRegionalDateStrFromQry$toConvertDateStrFromQry);
  3102.         $currentServerTime = new \DateTime();
  3103.         $em $this->getDoctrine()->getManager('company_group');
  3104.         $em->getConnection()->connect();
  3105.         ///last
  3106. //        file_put_contents($path, json_encode($configJson));//overwrite
  3107.         return new Response(json_encode(array(
  3108.             'convertedTime' => $convertedTime->format('Y-m-d h:i:s'),
  3109.             'convertedTimeUnix' => $convertedTime->format('U'),
  3110.             'convertedTimeRFC' => $convertedTime->format(DATE_RFC822),
  3111.             'currentServerTime' => $currentServerTime->format('Y-m-d h:i:s'),
  3112.             'currentServerTimeRFC' => $currentServerTime->format(DATE_RFC822),
  3113.             'currentServerTimeUnix' => $currentServerTime->format('U'),
  3114.         )));
  3115.     }
  3116.     public function GetUsersFromCentralServerAction(Request $request$id 0)
  3117.     {
  3118.     }
  3119.     public function UpdateCompanyDataToCentralServerAction(Request $request$id 0)
  3120.     {
  3121.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3122.         $post $request;
  3123.         $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') : []);
  3124.         if ($systemType == '_CENTRAL_') {
  3125.             $em_goc $this->getDoctrine()->getManager('company_group');
  3126.             //            'company_id' => $company->getId(),
  3127.             //                            'app_id' => $entry['appId'],
  3128.             //                            'dark_vibrant' => $company->getDarkVibrant(),
  3129.             //                            'light_vibrant' => $company->getLightVibrant(),
  3130.             //                            'vibrant' => $company->getVibrant(),
  3131.             //                            'company_type' => $company->getCompanyType(),
  3132.             //                            'company_name' => $company->getName(),
  3133.             //                            'company_address' => $company->getAddress(),
  3134.             //                            'company_s_address' => $company->getShippingAddress(),
  3135.             //                            'company_b_address' => $company->getBillingAddress(),
  3136.             //                            'company_image' => $company->getImage(),
  3137.             //                            'company_motto' => $company->getMotto(),
  3138.             //                            'company_i_footer' => $company->getInvoiceFooter(),
  3139.             //                            'company_g_footer' => $company->getGeneralFooter(),
  3140.             //                            'company_tin' => $company->getCompanyTin(),
  3141.             //                            'company_bin' => $company->getCompanyBin(),
  3142.             //                            'company_reg' => $company->getCompanyReg(),
  3143.             //                            'company_tl' => $company->getCompanyTl(),
  3144.             //                            'sms_enabled' => $company->getSmsNotificationEnabled(),
  3145.             //                            'sms_settings' => $company->getSmsSettings(),
  3146.             //                            'file'=>$output
  3147.             $findByQuery = array(
  3148. //                'active' => 1
  3149.                 'appId' => $post->get('app_id')
  3150.             );
  3151.             $goc $em_goc->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3152.                 ->findOneBy($findByQuery);
  3153.             if (!$goc)
  3154.                 $goc = new CompanyGroup();
  3155.             $goc->setName($post->get('company_name'));
  3156.             $goc->setAppId($post->get('app_id'));
  3157. //            $goc->setCompanyType($post->get('company_type'));
  3158.             $goc->setAddress($post->get('address'));
  3159. //            $goc->setDarkVibrant($post->get('dark_vibrant'));
  3160. //            $goc->setLightVibrant($post->get('light_vibrant'));
  3161. //            $goc->setVibrant($post->get('vibrant'));
  3162.             $goc->setShippingAddress($post->get('s_address'));
  3163.             $goc->setBillingAddress($post->get('b_address'));
  3164.             $goc->setMotto($post->get('motto'));
  3165.             $goc->setInvoiceFooter($post->get('i_footer'));
  3166.             $goc->setGeneralFooter($post->get('g_footer'));
  3167.             $goc->setCompanyReg($post->get('company_reg'''));
  3168.             $goc->setCompanyTin($post->get('company_tin'''));
  3169.             $goc->setCompanyBin($post->get('company_bin'''));
  3170.             $goc->setCompanyTl($post->get('company_tl'''));
  3171.             $goc->setCompanyGroupServerId($post->get('companyGroupServerId'''));
  3172.             $goc->setCompanyGroupServerAddress($post->get('companyGroupServerAddress'''));
  3173.             $goc->setCompanyGroupServerPort($post->get('companyGroupServerPort'''));
  3174.             $goc->setCompanyGroupServerHash($post->get('companyGroupServerHash'''));
  3175. //            $goc->setSmsNotificationEnabled($post->get('sms_enabled'));
  3176. //            $goc->setSmsSettings($post->get('sms_settings'));
  3177.             foreach ($request->files as $uploadedFile) {
  3178. //            if($uploadedFile->getImage())
  3179. //                var_dump($uploadedFile->getFile());
  3180. //                var_dump($uploadedFile);
  3181.                 if ($uploadedFile != null) {
  3182.                     $fileName 'company_image' $post->get('app_id') . '.' $uploadedFile->guessExtension();
  3183.                     $path $fileName;
  3184.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
  3185.                     if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage())) {
  3186.                         unlink($this->container->getParameter('kernel.root_dir') . '/../web' $goc->getImage());
  3187.                     }
  3188.                     if (!file_exists($upl_dir)) {
  3189.                         mkdir($upl_dir0777true);
  3190.                     }
  3191.                     $file $uploadedFile->move($upl_dir$path);
  3192.                     if ($path != "")
  3193.                         $goc->setImage('/uploads/CompanyImage/' $path);
  3194.                 }
  3195.             }
  3196.             $em_goc->persist($goc);
  3197.             $em_goc->flush();
  3198.             return new JsonResponse([]);
  3199.         } else {
  3200.             $em $this->getDoctrine()->getManager('company_group');
  3201.             $em->getConnection()->connect();
  3202.             $connected $em->getConnection()->isConnected();
  3203.             $gocDataList = [];
  3204.             if ($connected) {
  3205.                 $findByQuery = array(
  3206.                     'active' => 1
  3207.                 );
  3208.                 $gocList $this->getDoctrine()->getManager('company_group')
  3209.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3210.                     ->findBy($findByQuery);
  3211.                 foreach ($gocList as $entry) {
  3212.                     $d = array(
  3213.                         'name' => $entry->getName(),
  3214.                         'id' => $entry->getId(),
  3215.                         'image' => $entry->getImage(),
  3216.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3217.                         'companyGroupServerId' => $entry->getCompanyGroupServerId(),
  3218.                         'dbName' => $entry->getDbName(),
  3219.                         'dbUser' => $entry->getDbUser(),
  3220.                         'dbPass' => $entry->getDbPass(),
  3221.                         'dbHost' => $entry->getDbHost(),
  3222.                         'appId' => $entry->getAppId(),
  3223.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3224.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3225.                         'enabledModuleIdList' => $entry->getEnabledModuleIdList(),
  3226.                     );
  3227.                     $gocDataList[$entry->getId()] = $d;
  3228.                 }
  3229.                 foreach ($gocDataList as $gocId => $entry) {
  3230.                     $connector $this->container->get('application_connector');
  3231.                     $connector->resetConnection(
  3232.                         'default',
  3233.                         $gocDataList[$gocId]['dbName'],
  3234.                         $gocDataList[$gocId]['dbUser'],
  3235.                         $gocDataList[$gocId]['dbPass'],
  3236.                         $gocDataList[$gocId]['dbHost'],
  3237.                         $reset true);
  3238.                     $em $this->getDoctrine()->getManager();
  3239.                     $company $this->getDoctrine()
  3240.                         ->getRepository('ApplicationBundle\\Entity\\Company')
  3241.                         ->findOneBy(
  3242.                             array()
  3243.                         );
  3244.                     $output '';
  3245.                     $file $this->container->getParameter('kernel.root_dir') . '/../web' $company->getImage(); //<-- Path could be relative
  3246.                     if (file_exists($file)) {
  3247. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  3248.                         $mime mime_content_type($file);
  3249.                         $info pathinfo($file);
  3250.                         $name $info['basename'];
  3251.                         if (strpos($mime'image') !== false) {
  3252.                             $output = new \CURLFile($file$mime$name);
  3253.                         }
  3254.                     }
  3255.                     $post_fields = array(
  3256.                         'company_id' => $company->getId(),
  3257.                         'app_id' => $entry['appId'],
  3258.                         'dark_vibrant' => $company->getDarkVibrant(),
  3259.                         'light_vibrant' => $company->getLightVibrant(),
  3260.                         'vibrant' => $company->getVibrant(),
  3261.                         'company_type' => $company->getCompanyType(),
  3262.                         'company_name' => $company->getName(),
  3263.                         'address' => $company->getAddress(),
  3264.                         's_address' => $company->getShippingAddress(),
  3265.                         'b_address' => $company->getBillingAddress(),
  3266.                         'company_image' => $company->getImage(),
  3267.                         'motto' => $company->getMotto(),
  3268.                         'i_footer' => $company->getInvoiceFooter(),
  3269.                         'g_footer' => $company->getGeneralFooter(),
  3270.                         'company_tin' => $company->getCompanyTin(),
  3271.                         'company_bin' => $company->getCompanyBin(),
  3272.                         'company_reg' => $company->getCompanyReg(),
  3273.                         'company_tl' => $company->getCompanyTl(),
  3274.                         'sms_enabled' => $company->getSmsNotificationEnabled(),
  3275.                         'sms_settings' => $company->getSmsSettings(),
  3276.                         'companyGroupHash' => $company->getCompanyHash(),
  3277.                         'currentSubscriptionPackageId' => $company->getCurrentSubscriptionPackageId(),
  3278.                         'companyGroupServerId' => $entry['companyGroupServerId'],
  3279.                         'companyGroupServerAddress' => $serverList[$entry['companyGroupServerId']]['absoluteUrl'],
  3280.                         'companyGroupServerHash' => $serverList[$entry['companyGroupServerId']]['serverMarker'],
  3281.                         'companyGroupServerPort' => $request->server->get("SERVER_PORT"),
  3282.                         'file' => $output
  3283.                     );
  3284.                     $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/UpdateCompanyDataToCentralServer';
  3285.                     $curl curl_init();
  3286.                     curl_setopt_array($curl, array(
  3287.                         CURLOPT_RETURNTRANSFER => 1,
  3288.                         CURLOPT_POST => 1,
  3289.                         CURLOPT_URL => $urlToCall,
  3290.                         CURLOPT_CONNECTTIMEOUT => 10,
  3291.                         CURLOPT_SSL_VERIFYPEER => false,
  3292.                         CURLOPT_SSL_VERIFYHOST => false,
  3293.                         CURLOPT_HTTPHEADER => array(),
  3294.                         CURLOPT_POSTFIELDS => $post_fields
  3295.                     ));
  3296.                     $retData curl_exec($curl);
  3297.                     $errData curl_error($curl);
  3298.                     curl_close($curl);
  3299.                 }
  3300.             }
  3301.             return new JsonResponse([]);
  3302.         }
  3303.     }
  3304.     public function GetAppListFromCentralServerAction(Request $request$id 0)
  3305.     {
  3306.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3307.         $appIds $request->get('appIds', []);
  3308.         $appId $request->get('appId'0);
  3309.         if (is_string($appIds)) $appIds json_decode($appIdstrue);
  3310.         if ($appIds == null$appIds = [];
  3311.         if ($appId != 0)
  3312.             $appIds[] = $appId;
  3313.         if ($systemType == '_CENTRAL_') {
  3314.             $em $this->getDoctrine()->getManager('company_group');
  3315.             $em->getConnection()->connect();
  3316.             $connected $em->getConnection()->isConnected();
  3317.             $gocDataList = [];
  3318.             if ($connected) {
  3319.                 $findByQuery = array(
  3320.                     'active' => 1
  3321.                 );
  3322.                 if ($appIds != '_ALL_' && $appIds != [])
  3323.                     $findByQuery['appId'] = $appIds;
  3324.                 $gocList $this->getDoctrine()->getManager('company_group')
  3325.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3326.                     ->findBy($findByQuery);
  3327.                 foreach ($gocList as $entry) {
  3328.                     $d = array(
  3329.                         'name' => $entry->getName(),
  3330.                         'id' => $entry->getId(),
  3331.                         'image' => $entry->getImage(),
  3332.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3333.                         'dbName' => $entry->getDbName(),
  3334.                         'dbUser' => $entry->getDbUser(),
  3335.                         'dbPass' => $entry->getDbPass(),
  3336.                         'dbHost' => $entry->getDbHost(),
  3337.                         'appId' => $entry->getAppId(),
  3338.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3339.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3340.                     );
  3341.                     $gocDataList[$entry->getId()] = $d;
  3342.                 }
  3343.             }
  3344.             return new JsonResponse($gocDataList);
  3345.         } else {
  3346.             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/GetAppListFromCentralServer';
  3347.             $curl curl_init();
  3348.             curl_setopt_array($curl, array(
  3349.                 CURLOPT_RETURNTRANSFER => 1,
  3350.                 CURLOPT_URL => $urlToCall,
  3351.                 CURLOPT_CONNECTTIMEOUT => 10,
  3352.                 CURLOPT_SSL_VERIFYPEER => false,
  3353.                 CURLOPT_SSL_VERIFYHOST => false,
  3354.                 CURLOPT_HTTPHEADER => array(
  3355.                     "Accept: application/json",
  3356.                 ),
  3357.                 //                        CURLOPT_USERAGENT => 'InnoPM',
  3358.                 CURLOPT_POSTFIELDS => http_build_query([
  3359.                     'appIds' => $appIds
  3360.                 ])
  3361.             ));
  3362. //        $headers = array(
  3363. //            "Accept: application/json",
  3364. //        );
  3365. //        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  3366. ////for debug only!
  3367. //        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  3368. //        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  3369.             $retData curl_exec($curl);
  3370.             $errData curl_error($curl);
  3371.             curl_close($curl);
  3372.             return new JsonResponse(json_decode($retDatatrue));
  3373.         }
  3374.     }
  3375.     public function GetTaskListForMenuAction(Request $request$id 0)
  3376.     {
  3377.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3378.         $session $request->getSession();
  3379.         $appIds $request->get('appIds', []);
  3380.         $appId $request->get('appId'0);
  3381.         if (is_string($appIds)) $appIds json_decode($appIdstrue);
  3382.         if ($appIds == null$appIds = [];
  3383.         if ($appId != 0)
  3384.             $appIds[] = $appId;
  3385.         if ($systemType == '_CENTRAL_') {
  3386.             $em $this->getDoctrine()->getManager('company_group');
  3387.             $em->getConnection()->connect();
  3388.             $connected $em->getConnection()->isConnected();
  3389.             $gocDataList = [];
  3390.             if ($connected) {
  3391.                 $findByQuery = array(
  3392.                     'active' => 1
  3393.                 );
  3394.                 if ($appIds != '_ALL_' && $appIds != [])
  3395.                     $findByQuery['appId'] = $appIds;
  3396.                 $gocList $this->getDoctrine()->getManager('company_group')
  3397.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3398.                     ->findBy($findByQuery);
  3399.                 foreach ($gocList as $entry) {
  3400.                     $d = array(
  3401.                         'name' => $entry->getName(),
  3402.                         'id' => $entry->getId(),
  3403.                         'image' => $entry->getImage(),
  3404.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3405.                         'dbName' => $entry->getDbName(),
  3406.                         'dbUser' => $entry->getDbUser(),
  3407.                         'dbPass' => $entry->getDbPass(),
  3408.                         'dbHost' => $entry->getDbHost(),
  3409.                         'appId' => $entry->getAppId(),
  3410.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3411.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3412.                     );
  3413.                     $gocDataList[$entry->getId()] = $d;
  3414.                 }
  3415.             }
  3416.             return new JsonResponse($gocDataList);
  3417.         } else {
  3418.             $findByQuery = array(
  3419.                 'userId' => $session->get(UserConstants::USER_ID0)
  3420.             );
  3421.             $employee $this->getDoctrine()->getManager()
  3422.                 ->getRepository("ApplicationBundle\\Entity\\Employee")
  3423.                 ->findOneBy($findByQuery);
  3424.             $assignedTaskList = array();
  3425.             $currentlyWorkingTaskList = array();
  3426.             if ($employee) {
  3427.                 $findByQuery = array(
  3428.                     'assignedTo' => $employee->getEmployeeId(),
  3429.                     'hasChild' => [0null]
  3430.                 );
  3431.                 $assignedTaskListData $this->getDoctrine()->getManager()
  3432.                     ->getRepository("ApplicationBundle\\Entity\\PlanningItem")
  3433.                     ->findBy($findByQuery);
  3434.                 $findByQuery = array(
  3435.                     'employeeId' => $employee->getEmployeeId(),
  3436.                 );
  3437.                 $currentlyWorkingTaskListData $this->getDoctrine()->getManager()
  3438.                     ->getRepository("ApplicationBundle\\Entity\\TaskLog")
  3439.                     ->findBy($findByQuery);
  3440.                 foreach ($assignedTaskListData as $entry) {
  3441.                     $dt = array(
  3442.                         'description' => $entry->getDescription(),
  3443.                         'urgency' => $entry->getUrgency()
  3444.                     );
  3445.                     $assignedTaskList[] = $dt;
  3446.                 }
  3447.                 foreach ($currentlyWorkingTaskListData as $entry) {
  3448.                     $dt = array();
  3449.                     $currentlyWorkingTaskList[] = $dt;
  3450.                 }
  3451.             }
  3452.             return new JsonResponse(array(
  3453.                 'assignedTaskList' => $assignedTaskList,
  3454.                 'currentlyWorkingTaskList' => $currentlyWorkingTaskList,
  3455.             ));
  3456.         }
  3457.     }
  3458.     public function SyncUserToCentralUserAction(Request $request)
  3459.     {
  3460.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3461.         $post $request;
  3462.         $globalIdsByAppIdAndUser = [];
  3463.         if ($systemType == '_CENTRAL_') {
  3464.             $userDataList $request->get('userData', []);
  3465.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  3466.             if ($userDataList == null$userDataList = [];
  3467.             $em_goc $this->getDoctrine()->getManager('company_group');
  3468.             //1st step get all company item ids and then check for global id null if its null then the
  3469. //            return new JsonResponse(
  3470. //                array(
  3471. //                    'userDataList' => $userDataList
  3472. //                )
  3473. //            );
  3474.             ////ITEMGROUPS
  3475.             foreach ($userDataList as $k => $cwa) {
  3476.                 $centralUser $em_goc
  3477.                     ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  3478.                     ->findOneBy(
  3479.                         array(
  3480.                             'applicantId' => $cwa['getGlobalId']
  3481.                         )
  3482.                     );
  3483.                 if ($centralUser) {
  3484.                     $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  3485.                     $centralUser->setLastname($cwa['getLastname'] ?? null);
  3486.                     $centralUser->setEmail($cwa['getEmail'] ?? null);
  3487.                     $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  3488.                     $centralUser->setPhone($cwa['getPhone'] ?? null);
  3489.                     $centralUser->setNid($cwa['getNid'] ?? null);
  3490.                     $centralUser->setSex($cwa['getSex'] ?? null);
  3491.                     $centralUser->setBlood($cwa['getBlood'] ?? null);
  3492.                     $centralUser->setFather($cwa['getFather'] ?? null);
  3493.                     $centralUser->setMother($cwa['getMother'] ?? null);
  3494.                     $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  3495.                     $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  3496.                     $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  3497.                     $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  3498.                     $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  3499.                     $centralUser->setTin($cwa['getTin'] ?? null);
  3500.                     $centralUser->setDept($cwa['getDept'] ?? null);
  3501.                     $centralUser->setDesg($cwa['getDesg'] ?? null);
  3502.                     $centralUser->setBranch($cwa['getBranch'] ?? null);
  3503.                     $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  3504.                     $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  3505.                     $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  3506.                     $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  3507.                     $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  3508.                     $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  3509.                     $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  3510.                 } else {
  3511.                     $qry $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3512.                         ->createQueryBuilder('m')
  3513.                         ->where("m.email like '" $cwa['getEmail'] . "'");
  3514.                     if ($cwa['getOAuthEmail'] != '' && $cwa['getOAuthEmail'] != null)
  3515.                         $qry->orWhere("m.oAuthEmail like '" $cwa['getOAuthEmail'] . "'");
  3516.                     if ($cwa['getPhoneNumber'] != '' && $cwa['getPhoneNumber'] != null)
  3517.                         $qry->orWhere("m.phone like '" $cwa['getPhoneNumber'] . "'");
  3518.                     $targets $qry->getQuery()
  3519.                         ->setMaxResults(1)
  3520.                         ->getResult();
  3521.                     if (!empty($targets))
  3522.                         $centralUser $targets[0];
  3523.                 }
  3524.                 if ($centralUser) {
  3525.                     $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  3526.                     $centralUser->setLastname($cwa['getLastname'] ?? null);
  3527.                     $centralUser->setEmail($cwa['getEmail'] ?? null);
  3528.                     $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  3529.                     $centralUser->setPhone($cwa['getPhone'] ?? null);
  3530.                     $centralUser->setNid($cwa['getNid'] ?? null);
  3531.                     $centralUser->setSex($cwa['getSex'] ?? null);
  3532.                     $centralUser->setBlood($cwa['getBlood'] ?? null);
  3533.                     $centralUser->setFather($cwa['getFather'] ?? null);
  3534.                     $centralUser->setMother($cwa['getMother'] ?? null);
  3535.                     $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  3536.                     $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  3537.                     $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  3538.                     $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  3539.                     $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  3540.                     $centralUser->setTin($cwa['getTin'] ?? null);
  3541.                     $centralUser->setDept($cwa['getDept'] ?? null);
  3542.                     $centralUser->setDesg($cwa['getDesg'] ?? null);
  3543.                     $centralUser->setBranch($cwa['getBranch'] ?? null);
  3544.                     $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  3545.                     $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  3546.                     $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  3547.                     $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  3548.                     $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  3549.                     $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  3550.                     $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  3551.                 } else
  3552.                     $centralUser = new EntityApplicantDetails();
  3553. //
  3554. //                $getters = array_filter(get_class_methods($data), function ($method) {
  3555. //                    return 'get' === substr($method, 0, 3);
  3556. //                });
  3557.                 // Manual mapping starts here
  3558.                 $centralUser->setFirstname($cwa['getFirstname'] ?? null);
  3559.                 $centralUser->setLastname($cwa['getLastname'] ?? null);
  3560.                 $centralUser->setEmail($cwa['getEmail'] ?? null);
  3561.                 $centralUser->setOAuthEmail($cwa['getOAuthEmail'] ?? null);
  3562.                 $centralUser->setPhone($cwa['getPhone'] ?? null);
  3563.                 $centralUser->setNid($cwa['getNid'] ?? null);
  3564.                 $centralUser->setSex($cwa['getSex'] ?? null);
  3565.                 $centralUser->setBlood($cwa['getBlood'] ?? null);
  3566.                 $centralUser->setFather($cwa['getFather'] ?? null);
  3567.                 $centralUser->setMother($cwa['getMother'] ?? null);
  3568.                 $centralUser->setSpouse($cwa['getSpouse'] ?? null);
  3569.                 $centralUser->setCurrAddr($cwa['getCurrAddr'] ?? null);
  3570.                 $centralUser->setPermAddr($cwa['getPermAddr'] ?? null);
  3571.                 $centralUser->setPhoneCountryCode($cwa['getPhoneCountryCode'] ?? null);
  3572.                 $centralUser->setEmpType($cwa['getEmpType'] ?? null);
  3573.                 $centralUser->setTin($cwa['getTin'] ?? null);
  3574.                 $centralUser->setDept($cwa['getDept'] ?? null);
  3575.                 $centralUser->setDesg($cwa['getDesg'] ?? null);
  3576.                 $centralUser->setBranch($cwa['getBranch'] ?? null);
  3577.                 $centralUser->setWeeklyHoliday($cwa['getWeeklyHoliday'] ?? null);
  3578.                 $centralUser->setSupervisor($cwa['getSupervisor'] ?? null);
  3579. // Date fields
  3580.                 $centralUser->setDob(!empty($cwa['getDob']) ? new \DateTime($cwa['getDob']) : null);
  3581.                 $centralUser->setJoiningDate(!empty($cwa['getJoiningDate']) ? new \DateTime($cwa['getJoiningDate']) : null);
  3582.                 $centralUser->setEmpValidTill(!empty($cwa['getEmpValidTill']) ? new \DateTime($cwa['getEmpValidTill']) : null);
  3583.                 $centralUser->setTinValidTill(!empty($cwa['getTinValidTill']) ? new \DateTime($cwa['getTinValidTill']) : null);
  3584.                 $centralUser->setMedInsValidTill(!empty($cwa['getMedInsValidTill']) ? new \DateTime($cwa['getMedInsValidTill']) : null);
  3585. // Continue mapping more fields as needed...
  3586.                 $userAppIds json_decode($centralUser->getUserAppIds(), true);
  3587.                 $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  3588.                 if ($userAppIds == null$userAppIds = [];
  3589.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  3590.                 $userAppIds array_merge($userAppIdsarray_diff([$cwa['getUserAppId']], $userAppIds));
  3591.                 if (!isset($userTypesByAppIds[$cwa['getUserAppId']])) {
  3592.                     $userTypesByAppIds[$cwa['getUserAppId']] = [];
  3593.                 }
  3594.                 if (in_array(1$userTypesByAppIds[$cwa['getUserAppId']]) && $cwa['getUserType'] == 2) {
  3595.                     $userTypesByAppIds[$cwa['getUserAppId']] = array_diff($userTypesByAppIds[$cwa['getUserAppId']], [1]);
  3596.                 }
  3597.                 if (in_array(2$userTypesByAppIds[$cwa['getUserAppId']]) && $cwa['getUserType'] == 1) {
  3598.                     $userTypesByAppIds[$cwa['getUserAppId']] = array_diff($userTypesByAppIds[$cwa['getUserAppId']], [2]);
  3599.                 }
  3600.                 $userTypesByAppIds[$cwa['getUserAppId']] = array_merge($userTypesByAppIds[$cwa['getUserAppId']], array_diff([$cwa['getUserType']], $userTypesByAppIds[$cwa['getUserAppId']]));
  3601. //                $userTypesByAppIds[$cwa['getUserAppId']] = [$cwa['getUserType']];
  3602.                 $userFullName $cwa['getName'];
  3603.                 $userFullNameArr explode(' '$cwa['getName']);
  3604.                 $userFirstName = isset($userFullNameArr[0]) ? $userFullNameArr[0] : '';
  3605.                 $userLastName '';
  3606.                 if (isset($userFullNameArr[1])) {
  3607.                     foreach ($userFullNameArr as $kunky => $chunky) {
  3608.                         if ($kunky != 0) {
  3609.                             $userLastName .= $chunky;
  3610.                         }
  3611.                         if ($kunky count($userFullNameArr) - 1) {
  3612.                             $userLastName .= ' ';
  3613.                         }
  3614.                     }
  3615.                 }
  3616.                 $centralUser->setUserAppIds(json_encode($userAppIds));
  3617.                 $centralUser->setFirstname($userFirstName);
  3618.                 $centralUser->setLastname($userLastName);
  3619.                 $centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
  3620.                 $em_goc->persist($centralUser);
  3621.                 $em_goc->flush();
  3622.                 $uploadedFile $request->files->get('file_' $cwa['getUserAppId'] . '_' $cwa['getUserId'], null);
  3623.                 {
  3624.                     //            if($uploadedFile->getImage())
  3625.                     //                var_dump($uploadedFile->getFile());
  3626.                     //                var_dump($uploadedFile);
  3627.                     if ($uploadedFile != null) {
  3628.                         $fileName 'user_image' $centralUser->getApplicantId() . '.' $uploadedFile->guessExtension();
  3629.                         $path $fileName;
  3630.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
  3631.                         if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage())) {
  3632.                             unlink($this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage());
  3633.                         }
  3634.                         if (!file_exists($upl_dir)) {
  3635.                             mkdir($upl_dir0777true);
  3636.                         }
  3637.                         $file $uploadedFile->move($upl_dir$path);
  3638.                         if ($path != "")
  3639.                             $centralUser->setImage('uploads/UserImage/' $path);
  3640.                     }
  3641.                 }
  3642.                 $em_goc->flush();
  3643.                 if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
  3644.                     $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
  3645.                 $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
  3646.                     array(
  3647.                         'gid' => $centralUser->getApplicantId()
  3648.                     );
  3649.                 $companies $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
  3650.                     'appId' => $userAppIds
  3651.                 ]);
  3652.                 $globalId $cwa['getGlobalId'];
  3653.                 $userData $userDataList;
  3654.                 $dataByServerId = [];
  3655.                 $gocDataListByAppId = [];
  3656.                 foreach ($companies as $entry) {
  3657.                     $gocDataListByAppId[$entry->getAppId()] = [
  3658.                         'dbName' => $entry->getDbName(),
  3659.                         'dbUser' => $entry->getDbUser(),
  3660.                         'dbPass' => $entry->getDbPass(),
  3661.                         'dbHost' => $entry->getDbHost(),
  3662.                         'serverAddress' => $entry->getCompanyGroupServerAddress(),
  3663.                         'port' => $entry->getCompanyGroupServerPort() ?: 80,
  3664.                         'appId' => $entry->getAppId(),
  3665.                         'serverId' => $entry->getCompanyGroupServerId(),
  3666.                     ];
  3667.                     if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
  3668.                         $dataByServerId[$entry->getCompanyGroupServerId()] = array(
  3669.                             'serverId' => $entry->getCompanyGroupServerId(),
  3670.                             'serverAddress' => $entry->getCompanyGroupServerAddress(),
  3671.                             'port' => $entry->getCompanyGroupServerPort() ?: 80,
  3672.                             'appId' => $userAppIds,
  3673.                             'payload' => array(
  3674.                                 'globalId' => $globalId,
  3675.                                 'appId' => $userAppIds,
  3676.                                 'userData' => $userData,
  3677. //                                      'approvalHash' => $approvalHash
  3678.                             )
  3679.                         );
  3680.                 }
  3681.                 $urls = [];
  3682.                 foreach ($dataByServerId as $entry) {
  3683.                     $serverAddress $entry['serverAddress'];
  3684.                     if (!$serverAddress) continue;
  3685.                     $syncUrl $serverAddress '/ReceiveUserFromCentral';
  3686.                     $payload $entry['payload'];
  3687.                     $curl curl_init();
  3688.                     curl_setopt_array($curl, [
  3689.                         CURLOPT_RETURNTRANSFER => true,
  3690.                         CURLOPT_POST => true,
  3691.                         CURLOPT_URL => $syncUrl,
  3692.                         CURLOPT_CONNECTTIMEOUT => 10,
  3693.                         CURLOPT_SSL_VERIFYPEER => false,
  3694.                         CURLOPT_SSL_VERIFYHOST => false,
  3695.                         CURLOPT_HTTPHEADER => [
  3696.                             'Accept: application/json',
  3697.                             'Content-Type: application/json'
  3698.                         ],
  3699.                         CURLOPT_POSTFIELDS => json_encode($payload)
  3700.                     ]);
  3701.                     $response curl_exec($curl);
  3702.                     $err curl_error($curl);
  3703.                     $httpCode curl_getinfo($curlCURLINFO_HTTP_CODE);
  3704.                     curl_close($curl);
  3705.                     if ($err) {
  3706.                         error_log("ERP Sync Error [Server: {$entry['serverAddress']}]: $err");
  3707.                     } else {
  3708.                         error_log("ERP Sync Success [HTTP $httpCode]: $response");
  3709.                     }
  3710.                 }
  3711.             }
  3712.             return new JsonResponse(
  3713.                 array(
  3714.                     'globalIdsData' => $globalIdsByAppIdAndUser
  3715.                 )
  3716.             );
  3717.         } else {
  3718.             $em $this->getDoctrine()->getManager('company_group');
  3719.             $em->getConnection()->connect();
  3720.             $connected $em->getConnection()->isConnected();
  3721.             $gocDataList = [];
  3722.             $gocDataListByAppId = [];
  3723.             $retDataDebug = array();
  3724.             $appIds $request->get('appIds''_UNSET_');
  3725.             $userIds $request->get('userIds''_UNSET_');
  3726.             if ($connected) {
  3727.                 $findByQuery = array(
  3728.                     'active' => 1
  3729.                 );
  3730.                 if ($appIds !== '_UNSET_')
  3731.                     $findByQuery['appId'] = $appIds;
  3732.                 $gocList $this->getDoctrine()->getManager('company_group')
  3733.                     ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3734.                     ->findBy($findByQuery);
  3735.                 foreach ($gocList as $entry) {
  3736.                     $d = array(
  3737.                         'name' => $entry->getName(),
  3738.                         'id' => $entry->getId(),
  3739.                         'image' => $entry->getImage(),
  3740.                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  3741.                         'dbName' => $entry->getDbName(),
  3742.                         'dbUser' => $entry->getDbUser(),
  3743.                         'dbPass' => $entry->getDbPass(),
  3744.                         'dbHost' => $entry->getDbHost(),
  3745.                         'appId' => $entry->getAppId(),
  3746.                         'companyRemaining' => $entry->getCompanyRemaining(),
  3747.                         'companyAllowed' => $entry->getCompanyAllowed(),
  3748.                     );
  3749.                     $gocDataList[$entry->getId()] = $d;
  3750.                     $gocDataListByAppId[$entry->getAppId()] = $d;
  3751.                 }
  3752.                 $debugCount 0;
  3753.                 foreach ($gocDataList as $gocId => $entry) {
  3754. //                    if($debugCount>0)
  3755. //                        continue;
  3756.                     $skipSend 1;
  3757.                     $connector $this->container->get('application_connector');
  3758.                     $connector->resetConnection(
  3759.                         'default',
  3760.                         $gocDataList[$gocId]['dbName'],
  3761.                         $gocDataList[$gocId]['dbUser'],
  3762.                         $gocDataList[$gocId]['dbPass'],
  3763.                         $gocDataList[$gocId]['dbHost'],
  3764.                         $reset true);
  3765.                     $em $this->getDoctrine()->getManager();
  3766.                     if ($userIds !== '_UNSET_')
  3767.                         $users $this->getDoctrine()
  3768.                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3769.                             ->findBy(
  3770.                                 array(
  3771.                                     'userId' => $userIds
  3772.                                 )
  3773.                             );
  3774.                     else
  3775.                         $users $this->getDoctrine()
  3776.                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3777.                             ->findBy(
  3778.                                 array()
  3779.                             );
  3780.                     $output '';
  3781.                     $userData = array();
  3782.                     $userFiles = array();
  3783.                     foreach ($users as $user) {
  3784.                         $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage(); //<-- Path could be relative
  3785. //                            $output=$file;
  3786.                         if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  3787. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  3788.                             $mime mime_content_type($file);
  3789.                             $info pathinfo($file);
  3790.                             $name $info['basename'];
  3791.                             if (strpos($mime'image') !== false) {
  3792.                                 $output = new \CURLFile($file$mime$name);
  3793.                             }
  3794.                             $skipSend 0;
  3795.                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  3796.                         } else {
  3797. //                                    unlink($this->container->getParameter('kernel.root_dir') . '/../web'. $centralUser->getImage());
  3798.                             $user->setImage(null);
  3799.                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  3800.                             $em->flush();
  3801.                         }
  3802.                         $getters array_filter(get_class_methods($user), function ($method) {
  3803.                             return 'get' === substr($method03);
  3804.                         });
  3805.                         $userDataSingle = array(//                                'file'=>$output
  3806.                         );
  3807.                         foreach ($getters as $getter) {
  3808.                             if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  3809.                                 continue;
  3810. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  3811. //                                {
  3812. //                                    $userDataSingle[$getter]= $user->{$getter}();
  3813. //                                }
  3814.                             if ($user->{$getter}() instanceof \DateTime) {
  3815.                                 $ggtd $user->{$getter}();
  3816.                                 $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  3817.                             } else
  3818.                                 $userDataSingle[$getter] = $user->{$getter}();
  3819.                         }
  3820.                         $userData[] = $userDataSingle;
  3821.                     }
  3822.                     $retDataDebug[$debugCount] = array(
  3823.                         'skipSend' => $skipSend
  3824.                     );
  3825.                     //now customers
  3826.                     $emailFieldName 'email';
  3827.                     $phoneFieldName 'contact_number';
  3828.                     $query "SELECT * from  acc_clients   where 1=1 ";
  3829.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  3830.                     $results $stmt;
  3831.                     if (!empty($results)) {
  3832.                         foreach ($results as $dt) {
  3833.                             $dt['company_id'] = "1";
  3834.                             $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3835.                             $userDataSingle = array(
  3836.                                 'getUserAppId' => strval(UserConstants::USER_TYPE_CLIENT),
  3837.                                 'getUserName' => 'CID-' str_pad($dt['client_id'], 8'0'STR_PAD_LEFT),
  3838.                                 'getUserId' => $dt['client_id']
  3839.                             );
  3840. //                            $userData[] = $userDataSingle;
  3841.                         }
  3842.                     }
  3843.                     //now suppliers
  3844.                     $emailFieldName 'email';
  3845.                     $phoneFieldName 'contact_number';
  3846.                     $query "SELECT * from  acc_suppliers   where 1=1 ";
  3847.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  3848.                     $results $stmt;
  3849.                     if (!empty($results)) {
  3850.                         foreach ($results as $dt) {
  3851.                             $dt['company_id'] = "1";
  3852.                             $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  3853.                             $userDataSingle = array(
  3854.                                 'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
  3855.                                 'userName' => 'SID-' str_pad($dt['supplier_id'], 8'0'STR_PAD_LEFT),
  3856.                                 'userId' => $dt['supplier_id'],
  3857.                             );
  3858. //                            $userData[] = $userDataSingle;
  3859.                         }
  3860.                     }
  3861. //                    if ($skipSend == 0)
  3862.                     {
  3863.                         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  3864.                         $userFiles['userData'] = json_encode($userData);
  3865.                         $curl curl_init();
  3866.                         curl_setopt_array($curl, array(
  3867.                             CURLOPT_RETURNTRANSFER => 1,
  3868.                             CURLOPT_POST => 1,
  3869.                             CURLOPT_URL => $urlToCall,
  3870.                             CURLOPT_CONNECTTIMEOUT => 10,
  3871.                             CURLOPT_SSL_VERIFYPEER => false,
  3872.                             CURLOPT_SSL_VERIFYHOST => false,
  3873. //                            CURLOPT_SAFE_UPLOAD => false,
  3874.                             CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  3875.                             ),
  3876.                             //                        CURLOPT_USERAGENT => 'InnoPM',
  3877. //                            CURLOPT_POSTFIELDS => array(
  3878. //                                'userData'=>json_encode($userData),
  3879. //                                'userFiles'=>$userFiles
  3880. //                            ),
  3881.                             CURLOPT_POSTFIELDS => $userFiles
  3882.                         ));
  3883.                         $retData curl_exec($curl);
  3884.                         $errData curl_error($curl);
  3885.                         curl_close($curl);
  3886.                         $retDataObj json_decode($retDatatrue);
  3887.                         $retDataDebug[$debugCount] = $retDataObj;
  3888.                         if (isset($retDataObj['globalIdsData']))
  3889.                             foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  3890.                                 $connector $this->container->get('application_connector');
  3891.                                 $connector->resetConnection(
  3892.                                     'default',
  3893.                                     $gocDataListByAppId[$app_id]['dbName'],
  3894.                                     $gocDataListByAppId[$app_id]['dbUser'],
  3895.                                     $gocDataListByAppId[$app_id]['dbPass'],
  3896.                                     $gocDataListByAppId[$app_id]['dbHost'],
  3897.                                     $reset true);
  3898.                                 $em $this->getDoctrine()->getManager();
  3899.                                 foreach ($usrList as $sys_id => $globaldata) {
  3900.                                     $user $this->getDoctrine()
  3901.                                         ->getRepository('ApplicationBundle\\Entity\\SysUser')
  3902.                                         ->findOneBy(
  3903.                                             array(
  3904.                                                 'userId' => $sys_id
  3905.                                             )
  3906.                                         );
  3907.                                     if ($user) {
  3908.                                         $user->setGlobalId($globaldata['gid']);
  3909.                                         $em->flush();
  3910.                                     }
  3911.                                 }
  3912.                             }
  3913.                     }
  3914.                     $debugCount++;
  3915.                 }
  3916.             }
  3917.             return new JsonResponse($retDataDebug);
  3918.         }
  3919.     }
  3920.     public function ReceiveUserFromCentralAction(Request $request)
  3921.     {
  3922.         $data json_decode($request->getContent(), true);
  3923.         if (
  3924.             !$data ||
  3925.             !isset($data['globalId']) ||
  3926.             !isset($data['appId']) ||
  3927.             !isset($data['userData'])
  3928.         ) {
  3929.             return new JsonResponse(['success' => false'message' => 'Missing required fields'], 400);
  3930.         }
  3931.         $globalId $data['globalId'];
  3932.         $userDataRaw $data['userData'];
  3933.         if (is_string($userDataRaw)) {
  3934.             $userDataRaw json_decode($userDataRawtrue);
  3935.         }
  3936.         if (!is_array($userDataRaw)) {
  3937.             return new JsonResponse(['success' => false'message' => 'Invalid userData format'], 400);
  3938.         }
  3939.         $userData is_array($userDataRaw[0] ?? null) ? $userDataRaw[0] : $userDataRaw;
  3940.         if (is_string($userData)) {
  3941.             $userData json_decode($userDatatrue);
  3942.         }
  3943.         if (!is_array($userData)) {
  3944.             return new JsonResponse(['success' => false'message' => 'Invalid userData format'], 400);
  3945.         }
  3946.         $companyIds is_array($data['appId']) ? $data['appId'] : [$data['appId']];
  3947.         $em_goc $this->getDoctrine()->getManager('company_group');
  3948.         $companies $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
  3949.             'appId' => $companyIds
  3950.         ]);
  3951.         foreach ($companies as $entry) {
  3952.             $goc = [
  3953.                 'dbName' => $entry->getDbName(),
  3954.                 'dbUser' => $entry->getDbUser(),
  3955.                 'dbPass' => $entry->getDbPass(),
  3956.                 'dbHost' => $entry->getDbHost(),
  3957.                 'serverAddress' => $entry->getCompanyGroupServerAddress(),
  3958.                 'port' => $entry->getCompanyGroupServerPort() ?: 80,
  3959.                 'appId' => $entry->getAppId(),
  3960. //                                 'serverId' => $entry->getServerId(),
  3961.             ];
  3962.             $connector $this->container->get('application_connector');
  3963.             $connector->resetConnection(
  3964.                 'default',
  3965.                 $goc['dbName'],
  3966.                 $goc['dbUser'],
  3967.                 $goc['dbPass'],
  3968.                 $goc['dbHost'],
  3969.                 $reset true
  3970.             );
  3971.             $em $this->getDoctrine()->getManager();
  3972.             $user $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $globalId]);
  3973.             if (!$user) {
  3974.                 return new JsonResponse(['success' => false'message' => 'User not found'], 404);
  3975.             }
  3976. //            $user = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['userId' => $user->getUserId()]);
  3977. //            if (!$user) {
  3978. //                $user = new \ApplicationBundle\Entity\EncryptedSignature();
  3979. //                $user->setUserId($user->getUserId());
  3980. //                $user->setCreatedAt(new \DateTime());
  3981. //            }
  3982.             if (!isset($userData['getFirstname']) && !isset($userData['getFirstName'])) {
  3983.                 if (isset($userData['getName'])) {
  3984.                     $nameStrArr explode(" "$userData['getName']);
  3985.                     $userData['getFirstname'] = isset($nameStrArr[0]) ? $nameStrArr[0] : '';
  3986.                     $userData['getLastname'] = isset($nameStrArr[1]) ? $nameStrArr[1] : '';
  3987.                 }
  3988.                 $userData['getFirstName'] = $userData['getFirstname'];
  3989.                 $userData['getLastName'] = $userData['getLastname'];
  3990.             } else if (!isset($userData['getFirstName'])) {
  3991.                 $userData['getFirstName'] = $userData['getFirstname'];
  3992.                 $userData['getLastName'] = $userData['getLastname'];
  3993.             } else if (!isset($userData['getFirstname'])) {
  3994.                 $userData['getFirstname'] = $userData['getFirstName'];
  3995.                 $userData['getLastname'] = $userData['getLastName'];
  3996.             }
  3997.             $user->setUserName($userData['getFirstname'] . ' ' $userData['getLastname']);
  3998.             $user->setUserCompanyId(1);
  3999.             $user->setGlobalId($globalId);
  4000.             $user->setUserName($userData['getName'] ?? null);
  4001.             $user->setUpdatedAt(new \DateTime());
  4002.             $em->persist($user);
  4003.             $em->flush();
  4004.             $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(['userId' => $user->getUserId()]);
  4005.             if ($employee) {
  4006.                 $employee->setFirstName($userData['getFirstname']);
  4007.                 $employee->setLastName($userData['getLastname']);
  4008.                 $employee->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  4009.                 $em->persist($employee);
  4010.             }
  4011.             if ($employee)
  4012.                 $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4013.                     ->findOneBy(['id' => $employee->getEmployeeId()]);
  4014.             else
  4015.                 $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4016.                     ->findOneBy(['userId' => $user->getUserId()]);
  4017.             if ($employeeDetails) {
  4018.                 $employeeDetails->setFirstname($userData['getFirstname']);
  4019.                 $employeeDetails->setLastname($userData['getLastname']);
  4020.                 $employeeDetails->setEmail($userData['getEmail']);
  4021.                 $employeeDetails->setPhone($userData['getPhone'] ?? null);
  4022.                 $employeeDetails->setNid($userData['getNid'] ?? null);
  4023.                 $employeeDetails->setSex($userData['getSex'] ?? null);
  4024.                 $employeeDetails->setBlood($userData['getBlood'] ?? null);
  4025.                 $employeeDetails->setFather($userData['getFather'] ?? null);
  4026.                 $employeeDetails->setMother($userData['getMother'] ?? null);
  4027.                 $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  4028.                 $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  4029.                 $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  4030.                 $em->persist($employeeDetails);
  4031.             }
  4032.             $em->flush();
  4033.         }
  4034.         return new JsonResponse(['success' => true'message' => 'User, Employee, and EmployeeDetails updated in all ERP servers']);
  4035.     }
  4036.     public function MergeApplicantGlobalIdOnServerAction(Request $request)
  4037.     {
  4038.         $payload json_decode($request->getContent(), true);
  4039.         if (!is_array($payload)) {
  4040.             $payload $request->request->all();
  4041.         }
  4042.         $oldGlobalId = isset($payload['oldGlobalId']) ? (int)$payload['oldGlobalId'] : 0;
  4043.         $newGlobalId = isset($payload['newGlobalId']) ? (int)$payload['newGlobalId'] : 0;
  4044.         $appIds = isset($payload['appIds']) ? $payload['appIds'] : [];
  4045.         if (is_string($appIds)) {
  4046.             $decoded json_decode($appIdstrue);
  4047.             $appIds is_array($decoded) ? $decoded explode(','$appIds);
  4048.         }
  4049.         if (!is_array($appIds)) {
  4050.             $appIds = [];
  4051.         }
  4052.         $appIds array_values(array_unique(array_filter(array_map('intval'$appIds))));
  4053.         if ($oldGlobalId <= || $newGlobalId <= || empty($appIds)) {
  4054.             return new JsonResponse(['success' => false'message' => 'oldGlobalId, newGlobalId and appIds are required.'], 400);
  4055.         }
  4056.         $emGoc $this->getDoctrine()->getManager('company_group');
  4057.         $companies $emGoc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy(['appId' => $appIds]);
  4058.         $results = [];
  4059.         foreach ($companies as $entry) {
  4060.             $connector $this->container->get('application_connector');
  4061.             $connector->resetConnection(
  4062.                 'default',
  4063.                 $entry->getDbName(),
  4064.                 $entry->getDbUser(),
  4065.                 $entry->getDbPass(),
  4066.                 $entry->getDbHost(),
  4067.                 $reset true
  4068.             );
  4069.             $em $this->getDoctrine()->getManager();
  4070.             $oldUser $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $oldGlobalId]);
  4071.             $newUser $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $newGlobalId]);
  4072.             $appResult = [
  4073.                 'appId' => (int)$entry->getAppId(),
  4074.                 'oldFound' => $oldUser true false,
  4075.                 'newFound' => $newUser true false,
  4076.                 'mergedIntoExistingUser' => false,
  4077.                 'retaggedOldUser' => false,
  4078.             ];
  4079.             if ($oldUser && $newUser && (int)$oldUser->getUserId() !== (int)$newUser->getUserId()) {
  4080.                 if (!$newUser->getEmail() && $oldUser->getEmail()) {
  4081.                     $newUser->setEmail($oldUser->getEmail());
  4082.                 }
  4083.                 if (!$newUser->getImage() && $oldUser->getImage()) {
  4084.                     $newUser->setImage($oldUser->getImage());
  4085.                 }
  4086.                 if (!$newUser->getName() && $oldUser->getName()) {
  4087.                     $newUser->setName($oldUser->getName());
  4088.                 }
  4089.                 $conn $em->getConnection();
  4090.                 $conn->executeStatement('UPDATE employee SET user_id = :newUserId WHERE user_id = :oldUserId', [
  4091.                     'newUserId' => (int)$newUser->getUserId(),
  4092.                     'oldUserId' => (int)$oldUser->getUserId(),
  4093.                 ]);
  4094.                 $conn->executeStatement('UPDATE employee_details SET user_id = :newUserId WHERE user_id = :oldUserId', [
  4095.                     'newUserId' => (int)$newUser->getUserId(),
  4096.                     'oldUserId' => (int)$oldUser->getUserId(),
  4097.                 ]);
  4098.                 $oldUser->setGlobalId(null);
  4099.                 $oldUser->setStatus(0);
  4100.                 $oldUser->setUserName(($oldUser->getUserName() ?: 'merged_user') . '_merged_' $oldGlobalId);
  4101.                 if ($oldUser->getEmail()) {
  4102.                     $oldUser->setEmail('merged_' $oldGlobalId '_' time() . '@invalid.local');
  4103.                 }
  4104.                 $em->persist($newUser);
  4105.                 $em->persist($oldUser);
  4106.                 $em->flush();
  4107.                 $appResult['mergedIntoExistingUser'] = true;
  4108.             } elseif ($oldUser) {
  4109.                 $oldUser->setGlobalId($newGlobalId);
  4110.                 $em->persist($oldUser);
  4111.                 $em->flush();
  4112.                 $appResult['retaggedOldUser'] = true;
  4113.             }
  4114.             $results[] = $appResult;
  4115.         }
  4116.         return new JsonResponse([
  4117.             'success' => true,
  4118.             'results' => $results,
  4119.         ]);
  4120.     }
  4121.     public function SyncCentralUserToServerAction(Request $request)
  4122.     {
  4123.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4124.         $post $request;
  4125.         $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') : []);
  4126.         $globalIdsByAppIdAndUser = [];
  4127.         if ($systemType == '_CENTRAL_') {
  4128.             $userDataList = [];
  4129.             $retAppIds = [];
  4130.             $appIdList = [];
  4131.             $userIdList = [];
  4132.             $retDataDebug = [];
  4133.             $appIds $request->get('appIds''_UNSET_');
  4134.             if ($appIds != '_UNSET_') {
  4135.                 $appIdList $userIdList explode(','$appIds);;
  4136.                 if ($appIdList == null$appIdList = [];
  4137.             }
  4138.             $userIds $request->get('userIds''_UNSET_');
  4139.             if ($userIds != '_UNSET_') {
  4140.                 $userIdList explode(','$userIds);
  4141.                 if ($userIdList == null$userIdList = [];
  4142.             }
  4143.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  4144.             if ($userDataList == null$userDataList = [];
  4145.             $em_goc $this->getDoctrine()->getManager('company_group');
  4146.             $centralUserQry $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4147.                 ->createQueryBuilder('m')
  4148.                 ->where("1=1");
  4149.             if (!empty($userIdList))
  4150.                 $centralUserQry->andWhere("m.applicantId in (" implode(','$userIdList) . " )");
  4151.             $centralUsers $centralUserQry->getQuery()
  4152.                 ->setMaxResults(1)
  4153.                 ->getResult();
  4154.             ////ITEMGROUPS
  4155.             foreach ($centralUsers as $centralUser) {
  4156.                 if ($centralUser) {
  4157.                 } else {
  4158.                 }
  4159.                 $toSetUserData = [];
  4160.                 $userData = array();
  4161.                 $userFiles = array();
  4162.                 $file $this->container->getParameter('kernel.root_dir') . '/../web/' $centralUser->getImage(); //<-- Path could be relative
  4163. //                            $output=$file;
  4164.                 if ($centralUser->getImage() != '' && $centralUser->getImage() != null && file_exists($file)) {
  4165. //                        $file = new \CURLFile($this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/' . $company->getImage()); //<-- Path could be relative
  4166.                     $mime mime_content_type($file);
  4167.                     $info pathinfo($file);
  4168.                     $name $info['basename'];
  4169.                     if (strpos($mime'image') !== false) {
  4170.                         $output = new \CURLFile($file$mime$name);
  4171.                     }
  4172.                     $skipSend 0;
  4173.                     $userFiles['file_' $centralUser->getApplicantId()] = $output;
  4174.                 } else {
  4175.                     $centralUser->setImage(null);
  4176.                     $userFiles['file_' $centralUser->getApplicantId()] = 'pika';
  4177.                     $em_goc->flush();
  4178.                 }
  4179. //
  4180.                 $getters array_filter(get_class_methods($centralUser), function ($method) {
  4181.                     return 'get' === substr($method03);
  4182.                 });
  4183.                 $userDataSingle = array();
  4184.                 foreach ($getters as $getter) {
  4185.                     if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  4186.                         continue;
  4187. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  4188. //                                {
  4189. //                                    $userDataSingle[$getter]= $user->{$getter}();
  4190. //                                }
  4191.                     if ($centralUser->{$getter}() instanceof \DateTime) {
  4192.                         $ggtd $centralUser->{$getter}();
  4193.                         $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  4194.                     } else
  4195.                         $userDataSingle[$getter] = $centralUser->{$getter}();
  4196.                 }
  4197.                 $userAppIds json_decode($centralUser->getUserAppIds(), true);
  4198.                 if ($userAppIds == null$userAppIds = [];
  4199.                 $appIdList array_merge($appIdListarray_diff($userAppIds$appIdList));
  4200.                 $userTypesByAppIds json_decode($centralUser->getUserTypesByAppIds(), true);
  4201.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  4202.                 $userDataSingle['userTypesByAppIds'] = $userTypesByAppIds;
  4203.                 $userDataList[] = $userDataSingle;
  4204.                 $em_goc->persist($centralUser);
  4205.                 $em_goc->flush();
  4206.             }
  4207.             $em_goc->flush();
  4208.             $serverIdsCalledAlready = [];
  4209.             $appList $this->getDoctrine()->getManager('company_group')
  4210.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4211.                 ->findBy(array(
  4212.                         'appId' => $appIdList
  4213.                     )
  4214.                 );
  4215.             $userFiles['userData'] = json_encode($userDataList);
  4216.             foreach ($appList as $app) {
  4217.                 if (!in_array($app->getCompanyGroupServerId(), $serverIdsCalledAlready)) {
  4218.                     if (isset($serverList[$app->getCompanyGroupServerId()])) {
  4219.                         //                    if ($skipSend == 0)
  4220.                         {
  4221.                             $urlToCall $serverList[$app->getCompanyGroupServerId()]['absoluteUrl'] . '/SyncCentralUserToServer';
  4222.                             $curl curl_init();
  4223.                             curl_setopt_array($curl, array(
  4224.                                 CURLOPT_RETURNTRANSFER => 1,
  4225.                                 CURLOPT_POST => 1,
  4226.                                 CURLOPT_URL => $urlToCall,
  4227.                                 CURLOPT_CONNECTTIMEOUT => 10,
  4228.                                 CURLOPT_SSL_VERIFYPEER => false,
  4229.                                 CURLOPT_SSL_VERIFYHOST => false,
  4230.                                 CURLOPT_HTTPHEADER => array(),
  4231.                                 CURLOPT_POSTFIELDS => $userFiles
  4232.                             ));
  4233.                             $retData curl_exec($curl);
  4234.                             $errData curl_error($curl);
  4235.                             curl_close($curl);
  4236.                             $retDataObj json_decode($retDatatrue);
  4237.                             $retDataDebug[] = $retDataObj;
  4238.                         }
  4239.                     }
  4240.                     $serverIdsCalledAlready[] = $app->getCompanyGroupServerId();
  4241.                 }
  4242.             }
  4243. //                if (!isset($globalIdsByAppIdAndUser[$cwa['getUserAppId']]))
  4244. //                    $globalIdsByAppIdAndUser[$cwa['getUserAppId']] = array();
  4245. //
  4246. //                $globalIdsByAppIdAndUser[$cwa['getUserAppId']][$cwa['getUserId']] =
  4247. //                    array(
  4248. //                        'gid' => $centralUser->getApplicantId()
  4249. //                    );
  4250.             return new JsonResponse(
  4251.                 array(
  4252.                     "success" => true,
  4253.                     "retDataDebug" => $retDataDebug,
  4254.                     "serverIdsCalledAlready" => $serverIdsCalledAlready,
  4255.                     "appIdList" => $appIdList,
  4256.                     "userFiles" => $userFiles,
  4257.                     "retAppIds" => $retAppIds,
  4258.                 )
  4259.             );
  4260.         } else {
  4261.             $userDataList $request->get('userData', []);
  4262.             if (is_string($userDataList)) $userDataList json_decode($userDataListtrue);
  4263.             if ($userDataList == null$userDataList = [];
  4264.             foreach ($userDataList as $userData) {
  4265.                 $em_goc $this->getDoctrine()->getManager('company_group');
  4266.                 $em $this->getDoctrine()->getManager('company_group');
  4267.                 $em->getConnection()->connect();
  4268.                 $connected $em->getConnection()->isConnected();
  4269.                 $gocDataList = [];
  4270.                 $gocDataListByAppId = [];
  4271.                 $retDataDebug = array();
  4272.                 $appIds json_decode($userData['getUserAppIds'], true);
  4273.                 if ($appIds == null$appIds = [];
  4274.                 $userTypesByAppIds json_decode($userData['getUserTypesByAppIds'], true);
  4275.                 if ($userTypesByAppIds == null$userTypesByAppIds = [];
  4276.                 $userIds $request->get('userIds''_UNSET_');
  4277.                 if ($connected && !empty($appIds)) {
  4278.                     $findByQuery = array(
  4279.                         'active' => 1
  4280.                     );
  4281.                     $findByQuery['appId'] = $appIds;
  4282.                     $gocList $this->getDoctrine()->getManager('company_group')
  4283.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4284.                         ->findBy($findByQuery);
  4285.                     $imagePathToSet '';
  4286.                     $uploadedFile $request->files->get('file_' $userData['getApplicantId'], null);
  4287.                     {
  4288.                         if ($uploadedFile != null) {
  4289.                             $fileName 'user_image' $userData['getApplicantId'] . '.' $uploadedFile->guessExtension();
  4290.                             $path $fileName;
  4291.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/UserImage/';
  4292.                             if (!file_exists($upl_dir)) {
  4293.                                 mkdir($upl_dir0777true);
  4294.                             }
  4295.                             $file $uploadedFile->move($upl_dir$path);
  4296.                             $imagePathToSet 'uploads/UserImage/' $path;
  4297.                         }
  4298.                     }
  4299.                     foreach ($gocList as $entry) {
  4300.                         $d = array(
  4301.                             'name' => $entry->getName(),
  4302.                             'id' => $entry->getId(),
  4303.                             'image' => $entry->getImage(),
  4304.                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  4305.                             'dbName' => $entry->getDbName(),
  4306.                             'dbUser' => $entry->getDbUser(),
  4307.                             'dbPass' => $entry->getDbPass(),
  4308.                             'dbHost' => $entry->getDbHost(),
  4309.                             'appId' => $entry->getAppId(),
  4310.                             'companyRemaining' => $entry->getCompanyRemaining(),
  4311.                             'companyAllowed' => $entry->getCompanyAllowed(),
  4312.                         );
  4313.                         $gocDataList[$entry->getId()] = $d;
  4314.                         $gocDataListByAppId[$entry->getAppId()] = $d;
  4315.                     }
  4316.                     $debugCount 0;
  4317.                     foreach ($gocDataList as $gocId => $entry) {
  4318. //                    if($debugCount>0)
  4319. //                        continue;
  4320.                         $skipSend 1;
  4321.                         $connector $this->container->get('application_connector');
  4322.                         $connector->resetConnection(
  4323.                             'default',
  4324.                             $gocDataList[$gocId]['dbName'],
  4325.                             $gocDataList[$gocId]['dbUser'],
  4326.                             $gocDataList[$gocId]['dbPass'],
  4327.                             $gocDataList[$gocId]['dbHost'],
  4328.                             $reset true);
  4329.                         $em $this->getDoctrine()->getManager();
  4330.                         $user $this->getDoctrine()
  4331.                             ->getRepository('ApplicationBundle\\Entity\\SysUser')
  4332.                             ->findOneBy(
  4333.                                 array(
  4334.                                     'globalId' => $userData['getApplicantId']
  4335.                                 )
  4336.                             );
  4337.                         $output '';
  4338.                         if (!$user)
  4339.                             $user = new SysUser();
  4340.                         $user->setGlobalId($userData['getApplicantId']);
  4341.                         $user->setUserAppId($entry['appId']);
  4342.                         $user_type 1;
  4343.                         if (isset($userData['userTypesByAppIds'][$entry['appId']])) {
  4344.                             $user_type $userData['userTypesByAppIds'][$entry['appId']];
  4345.                         }
  4346.                         $user->setUserType($user_type);
  4347.                         $user->setUserAppIdList(json_encode($appIds));
  4348.                         $user->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  4349.                         $user->setStatus(UserConstants::ACTIVE_USER);
  4350.                         if (!isset($userData['getFirstname']) && !isset($userData['getFirstName'])) {
  4351.                             if (isset($userData['getName'])) {
  4352.                                 $nameStrArr explode(" "$userData['getName']);
  4353.                                 $userData['getFirstname'] = isset($nameStrArr[0]) ? $nameStrArr[0] : '';
  4354.                                 $userData['getLastname'] = isset($nameStrArr[1]) ? $nameStrArr[1] : '';
  4355.                             }
  4356.                             $userData['getFirstName'] = $userData['getFirstname'];
  4357.                             $userData['getLastName'] = $userData['getLastname'];
  4358.                         } else if (!isset($userData['getFirstName'])) {
  4359.                             $userData['getFirstName'] = $userData['getFirstname'];
  4360.                             $userData['getLastName'] = $userData['getLastname'];
  4361.                         } else if (!isset($userData['getFirstname'])) {
  4362.                             $userData['getFirstname'] = $userData['getFirstName'];
  4363.                             $userData['getLastname'] = $userData['getLastName'];
  4364.                         }
  4365.                         if (!isset($userData['getName'])) {
  4366.                             $userData['getName'] = $userData['getFirstname'] . ' ' $userData['getLastName'];
  4367.                         }
  4368.                         foreach ($userData as $getter => $value) {
  4369.                             if ($getter == 'getApplicantId')
  4370.                                 continue;
  4371.                             $setMethod str_replace('get''set'$getter);
  4372.                             if (method_exists($user$setMethod)) {
  4373.                                 if ($user->{$getter}() instanceof \DateTime)
  4374.                                     $user->{$setMethod}(new \DateTime($value)); // `foo!`
  4375.                                 else if ($setMethod == 'setUserAppIds') {
  4376.                                 } else
  4377.                                     $user->{$setMethod}($value); // `foo!`
  4378.                             }
  4379.                         }
  4380.                         if ($imagePathToSet != "") {
  4381.                             if ($user->getImage() != $imagePathToSet && $user->getImage() != '' && $user->getImage() != null && file_exists($this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage())) {
  4382.                                 unlink($this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage());
  4383.                             }
  4384.                             $user->setImage($imagePathToSet);
  4385.                         }
  4386.                         $em->persist($user);
  4387.                         $em->flush();
  4388.                         ///new test add employee
  4389.                         ///
  4390.                         $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(['userId' => $user->getUserId()]);
  4391.                         if (!$employee)
  4392.                             $employee = new Employee();
  4393.                         if ($employee) {
  4394.                             $employee->setFirstName($userData['getFirstname']);
  4395.                             $employee->setLastName($userData['getLastname']);
  4396.                             $employee->setName($userData['getFirstname'] . ' ' $userData['getLastname']);
  4397.                             $employee->setUserId($user->getUserId());
  4398.                             $em->persist($employee);
  4399.                         }
  4400.                         $em->flush();
  4401.                         if ($employee)
  4402.                             $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4403.                                 ->findOneBy(['id' => $employee->getEmployeeId()]);
  4404.                         else
  4405.                             $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')
  4406.                                 ->findOneBy(['userId' => $user->getUserId()]);
  4407.                         if (!$employeeDetails) {
  4408.                             $employeeDetails = new EmployeeDetails();
  4409.                             $employeeDetails->setEmpType(1);
  4410.                             $employeeDetails->setEmpStatus(1);
  4411.                         }
  4412.                         if ($employeeDetails) {
  4413.                             $employeeDetails->setFirstname($userData['getFirstname']);
  4414.                             $employeeDetails->setLastname($userData['getLastname']);
  4415.                             $employeeDetails->setUsername($userData['getUsername']);
  4416.                             $employeeDetails->setEmail($userData['getEmail']);
  4417.                             $employeeDetails->setPhone($userData['getPhone'] ?? null);
  4418.                             $employeeDetails->setNid($userData['getNid'] ?? null);
  4419.                             $employeeDetails->setSex($userData['getSex'] ?? null);
  4420.                             $employeeDetails->setBlood($userData['getBlood'] ?? null);
  4421.                             $employeeDetails->setFather($userData['getFather'] ?? null);
  4422.                             $employeeDetails->setMother($userData['getMother'] ?? null);
  4423.                             $employeeDetails->setSpouse($userData['getSpouse'] ?? null);
  4424.                             $employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
  4425.                             $employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
  4426.                             $employeeDetails->setUserId($user->getUserId());
  4427.                             $employeeDetails->setId($employee->getEmployeeId());
  4428.                             $em->persist($employeeDetails);
  4429.                         }
  4430.                         $em->flush();
  4431.                         /// new test end
  4432.                         $debugCount++;
  4433.                         $retDataDebug[$debugCount] = array(
  4434.                             'skipSend' => $skipSend,
  4435.                             'userId' => $user->getUserId(),
  4436.                             'appId' => $user->getUserAppId(),
  4437.                         );
  4438.                     }
  4439.                 }
  4440.             }
  4441.             return new JsonResponse($retDataDebug);
  4442.         }
  4443.     }
  4444.     public function GetUsersByQueryAction(Request $request$id 0)
  4445.     {
  4446.         $message "";
  4447.         $gocList = [];
  4448.         $outputList = [];
  4449.         $queryType '_ANY_';
  4450. //        if ($request->has('queryType'))
  4451.         $queryType $request->get('queryType''_ANY_');
  4452.         $returnData = [];
  4453.         $debugData = [];
  4454.         $returnDataArray = [];
  4455.         $returnDataByServerId = [];
  4456.         $serverId $request->get('serverId'4);
  4457.         $serverUrl $request->get('serverUrl''http://194.195.244.141');
  4458.         $serverPort $request->get('serverPort''');
  4459.         $queryStr $request->get('queryStr''');
  4460.         $queryStrEmail $request->get('quryStrEmail''');
  4461.         $queryStrPhone $request->get('quryStrPhone''');
  4462.         if ($queryStrEmail == '' && $queryStrPhone == '') {
  4463.             $queryStrEmail $queryStr;
  4464.         }
  4465. //        sample
  4466. //        data will be by company id
  4467.         $d = array(
  4468.             'userType' => 2,
  4469.             'userId' => 4,
  4470.             'userName' => 'abc',
  4471.             'loginUserName' => 'CID-abc',
  4472.             'serverId' => $serverId,
  4473.             'serverUrl' => $serverUrl,
  4474.             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4475.             'gocId' => 2,
  4476.             'companyId' => 1,
  4477.             'appId' => 45,
  4478.             'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  4479.             'companyName' => 'HoneyBee Iot Ltd.',
  4480.             'userCompanyIds' => [14],
  4481.             'userAppIds' => [140],
  4482.             'userCompanyList' => [
  4483.                 => [
  4484.                     'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  4485.                     'companyName' => 'HoneyBee IoT Ltd.',
  4486.                 ],
  4487.                 => [
  4488.                     'companyLogoUrl' => '/uploads/CompanyImage/4c48d9d0f26918c8bd866a197e50e15e.png',
  4489.                     'companyName' => 'Nastec Srl',
  4490.                 ]
  4491.             ]
  4492.         );
  4493. //        return new JsonResponse(array(
  4494. //            $d, $d
  4495. //        ));
  4496.         $em $this->getDoctrine()->getManager('company_group');
  4497.         $em->getConnection()->connect();
  4498.         $connected $em->getConnection()->isConnected();
  4499.         if ($connected)
  4500.             $gocList $this->getDoctrine()->getManager('company_group')
  4501.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4502.                 ->findBy(
  4503.                     array(
  4504.                         'active' => 1
  4505.                     )
  4506.                 );
  4507.         $gocDataList = [];
  4508.         foreach ($gocList as $entry) {
  4509.             $d = array(
  4510.                 'name' => $entry->getName(),
  4511.                 'id' => $entry->getId(),
  4512.                 'dbName' => $entry->getDbName(),
  4513.                 'dbUser' => $entry->getDbUser(),
  4514.                 'dbPass' => $entry->getDbPass(),
  4515.                 'dbHost' => $entry->getDbHost(),
  4516.                 'appId' => $entry->getAppId(),
  4517.                 'companyRemaining' => $entry->getCompanyRemaining(),
  4518.                 'companyAllowed' => $entry->getCompanyAllowed(),
  4519.             );
  4520.             $gocDataList[$entry->getId()] = $d;
  4521.         }
  4522.         $gocDbName '';
  4523.         $gocDbUser '';
  4524.         $gocDbPass '';
  4525.         $gocDbHost '';
  4526.         $gocId 0;
  4527. //        $web_root_dir = $this->container->getParameter('kernel.root_dir'). '/../web' ;
  4528.         $web_root_dir $url $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  4529. //        $root_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf';
  4530.         foreach ($gocDataList as $gocId => $entry) {
  4531.             $connector $this->container->get('application_connector');
  4532.             $connector->resetConnection(
  4533.                 'default',
  4534.                 $gocDataList[$gocId]['dbName'],
  4535.                 $gocDataList[$gocId]['dbUser'],
  4536.                 $gocDataList[$gocId]['dbPass'],
  4537.                 $gocDataList[$gocId]['dbHost'],
  4538.                 $reset true);
  4539.             $em $this->getDoctrine()->getManager();
  4540.             $companyList = [];
  4541.             $query "SELECT * from  company   where 1";
  4542.             $stmt $em->getConnection()->fetchAllAssociative($query);
  4543.             $results $stmt;
  4544.             if (!empty($results))
  4545.                 foreach ($results as $dt) {
  4546.                     $companyList[$dt['id']] = $dt;
  4547.                 }
  4548.             else
  4549.                 $companyList = array(
  4550.                     => [
  4551.                         'image' => '',
  4552.                         'name' => 'Company',
  4553.                     ]
  4554.                 );
  4555.             ///SysUSER
  4556.             $fieldName = ($queryType == '_EMAIL_' || $queryType == '_ANY_') ? 'email' 'phone_number';
  4557.             if ($queryStrEmail == '' && $queryStrPhone == '') {
  4558.             } else {
  4559.                 $emailFieldName 'email';
  4560.                 $phoneFieldName 'phone_number';
  4561.                 $userNameFieldName 'user_name';
  4562.                 $query "SELECT * from  sys_user   where 1=1 ";
  4563.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail' " '';
  4564.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%' " '';
  4565.                 $query .= ($queryStr != '') ? " or $userNameFieldName like '$queryStr' " '';
  4566.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  4567.                 $results $stmt;
  4568.                 if (!empty($results)) {
  4569.                     foreach ($results as $dt) {
  4570. //                        if($dt['company_id']==0 || $dt['company_id'] ==null)
  4571.                         $dt['company_id'] = "1";
  4572.                         $user_app_ids json_decode($dt['user_app_id_list'], true);
  4573.                         if ($user_app_ids == null$user_app_ids = [$dt['app_id']];
  4574.                         $user_company_ids json_decode($dt['user_company_id_list'], true);
  4575.                         if ($user_company_ids == null$user_company_ids = [$dt['company_id']];
  4576.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  4577.                         $d = array(
  4578.                             'userType' => $dt['user_type'],
  4579.                             'userName' => $dt['user_name'],
  4580.                             'userId' => $dt['user_id'],
  4581.                             'loginUserName' => $dt['user_name'],
  4582.                             'email' => $dt['email'],
  4583.                             'phone' => $dt['phone_number'],
  4584.                             'serverId' => $serverId,
  4585.                             'serverUrl' => $serverUrl,
  4586.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4587.                             'gocId' => $gocId,
  4588.                             'companyId' => $dt['company_id'],
  4589.                             'appId' => $dt['app_id'],
  4590.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  4591.                             'companyName' => $companyData['name'],
  4592.                             'userCompanyIds' => $user_company_ids,
  4593.                             'userAppIds' => $user_app_ids,
  4594.                             'userCompanyList' => [
  4595.                             ]
  4596.                         );
  4597.                         foreach ($user_company_ids as $cid) {
  4598.                             $d['userCompanyList'][$cid] = [
  4599.                                 'companyLogoUrl' => $web_root_dir $companyList[$cid]['image'],
  4600.                                 'companyName' => $companyList[$cid]['name'],
  4601.                             ];
  4602.                         }
  4603.                         $returnData[] = $d;
  4604.                         $returnDataByServerId[$serverId][] = $d;
  4605.                     }
  4606.                 }
  4607.                 //now customers
  4608.                 $emailFieldName 'email';
  4609.                 $phoneFieldName 'contact_number';
  4610.                 $query "SELECT * from  acc_clients   where 1=1 ";
  4611.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" '';
  4612.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" '';
  4613.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  4614.                 $results $stmt;
  4615.                 if (!empty($results)) {
  4616.                     foreach ($results as $dt) {
  4617.                         $dt['company_id'] = "1";
  4618.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  4619.                         $d = array(
  4620.                             'userType' => strval(UserConstants::USER_TYPE_CLIENT),
  4621.                             'userName' => 'CID-' str_pad($dt['client_id'], 8'0'STR_PAD_LEFT),
  4622.                             'userId' => $dt['client_id'],
  4623.                             'loginUserName' => $dt['username'],
  4624.                             'email' => $dt['email'],
  4625.                             'phone' => $dt['contact_number'],
  4626.                             'serverId' => $serverId,
  4627.                             'serverUrl' => $serverUrl,
  4628.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4629.                             'gocId' => $gocId,
  4630.                             'companyId' => $dt['company_id'],
  4631.                             'appId' => $dt['app_id'],
  4632.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  4633.                             'companyName' => $companyData['name'],
  4634.                             'userCompanyIds' => [],
  4635.                             'userAppIds' => [],
  4636.                             'userCompanyList' => [
  4637.                             ]
  4638.                         );
  4639.                         $returnData[] = $d;
  4640.                         $returnDataByServerId[$serverId][] = $d;
  4641.                     }
  4642.                 }
  4643.                 //now suppliers
  4644.                 $emailFieldName 'email';
  4645.                 $phoneFieldName 'contact_number';
  4646.                 $query "SELECT * from  acc_suppliers   where 1=1 ";
  4647.                 $query .= ($queryStrEmail != '') ? "and $emailFieldName like '$queryStrEmail'" '';
  4648.                 $query .= ($queryStrPhone != '') ? "and $phoneFieldName like '%$queryStrPhone%'" '';
  4649.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  4650.                 $results $stmt;
  4651.                 if (!empty($results)) {
  4652.                     foreach ($results as $dt) {
  4653.                         $dt['company_id'] = "1";
  4654.                         $companyData = isset($companyList[$dt['company_id']]) ? $companyList[$dt['company_id']] : [];
  4655.                         $d = array(
  4656.                             'userType' => strval(UserConstants::USER_TYPE_SUPPLIER),
  4657.                             'userName' => 'SID-' str_pad($dt['supplier_id'], 8'0'STR_PAD_LEFT),
  4658.                             'userId' => $dt['supplier_id'],
  4659.                             'loginUserName' => $dt['username'],
  4660.                             'email' => $dt['email'],
  4661.                             'phone' => $dt['contact_number'],
  4662.                             'serverId' => $serverId,
  4663.                             'serverUrl' => $serverUrl,
  4664.                             'systemType' => $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_',
  4665.                             'gocId' => $gocId,
  4666.                             'companyId' => $dt['company_id'],
  4667.                             'appId' => $dt['app_id'],
  4668.                             'companyLogoUrl' => $web_root_dir $companyData['image'],
  4669.                             'companyName' => $companyData['name'],
  4670.                             'userCompanyIds' => [],
  4671.                             'userAppIds' => [],
  4672.                             'userCompanyList' => [
  4673.                             ]
  4674.                         );
  4675.                         $returnData[] = $d;
  4676.                         $returnDataByServerId[$serverId][] = $d;
  4677.                     }
  4678.                 }
  4679.             }
  4680.         }
  4681.         return new JsonResponse(array(
  4682.             'success' => true,
  4683.             'data' => $returnData,
  4684.             'debugData' => $debugData,
  4685.             'dataByServerId' => $returnDataByServerId,
  4686.             'queryType' => $queryType
  4687.         ));
  4688.     }
  4689.     public function GetHoneybeeServerListAction(Request $request$id 0)
  4690.     {
  4691.         $serverList GeneralConstant::$serverList;
  4692.         return new JsonResponse(array(
  4693.             'success' => true,
  4694.             'data' => $serverList,
  4695.         ));
  4696.     }
  4697.     public function ServerListAction()
  4698.     {
  4699.         $serverList GeneralConstant::$serverList;
  4700.         return new JsonResponse(
  4701.             $serverList
  4702.         );
  4703.     }
  4704.     public function widgetModuleListAction()
  4705.     {
  4706.         $widgetsModuleList = [
  4707.             [
  4708.                 'name' => 'Accounts',
  4709.                 'id' => 1,
  4710.                 'hash' => '_ACC_',
  4711.                 'enabled' => true,
  4712.                 'hidden' => true,
  4713.             ],
  4714.             [
  4715.                 'name' => 'Sales',
  4716.                 'id' => 2,
  4717.                 'hash' => '_SL_',
  4718.                 'enabled' => true,
  4719.                 'hidden' => true,
  4720.             ],
  4721.             [
  4722.                 'name' => 'Human Resource',
  4723.                 'id' => 3,
  4724.                 'hash' => '_HRM_',
  4725.                 'enabled' => true,
  4726.                 'hidden' => true,
  4727.             ],
  4728.             [
  4729.                 'name' => 'Admin',
  4730.                 'id' => 4,
  4731.                 'hash' => '_ADM_',
  4732.                 'enabled' => true,
  4733.                 'hidden' => true,
  4734.             ],
  4735.         ];
  4736.         return new JsonResponse(
  4737.             array(
  4738.                 'success' => true,
  4739.                 'widgetModuleList' => $widgetsModuleList
  4740.             )
  4741.         );
  4742.     }
  4743.     public function widgetListAction()
  4744.     {
  4745.         $widgetsList = [
  4746.             [
  4747.                 'id' => 1,
  4748.                 'name' => 'Expense',
  4749.                 'hash' => '_EXP_',
  4750.                 'widgetModuleId' => 1,
  4751.                 'widgetName' => 'Accounts',
  4752.                 'screenName' => '',
  4753.                 'hidden' => true,
  4754.                 'enabled' => true,
  4755.                 'image' => 'https://e7.pngegg.com/pngimages/640/646/png-clipart-expense-management-computer-icons-finance-others-miscellaneous-text.png',
  4756.                 'showOnHome' => true,
  4757.                 'routeList' => [
  4758.                 ]
  4759.             ],
  4760.             [
  4761.                 'id' => 2,
  4762.                 'name' => 'Attendance',
  4763.                 'hash' => '_ATD_',
  4764.                 'widgetModuleId' => 3,
  4765.                 'widgetName' => 'Human Resource',
  4766.                 'screenName' => '',
  4767.                 'hidden' => true,
  4768.                 'enabled' => true,
  4769.                 'image' => 'https://cdn.iconscout.com/icon/premium/png-256-thumb/biometric-attendance-1-1106795.png',
  4770.                 'showOnHome' => true,
  4771.                 'routeList' => [
  4772.                 ]
  4773.             ],
  4774.             [
  4775.                 'id' => 3,
  4776.                 'name' => 'Payment',
  4777.                 'hash' => '_PMT_',
  4778.                 'widgetModuleId' => 1,
  4779.                 'widgetName' => 'Accounts',
  4780.                 'screenName' => '',
  4781.                 'hidden' => true,
  4782.                 'enabled' => true,
  4783.                 'image' => 'https://banner2.cleanpng.com/20180628/gbi/kisspng-management-accounting-accountant-gestin-kontabil-contador-5b356a344f40d2.2788485015302272523246.jpg',
  4784.                 'showOnHome' => true,
  4785.                 'routeList' => [
  4786.                     ["id" => 3"route" => "create_payment_voucher""name" => "Make Payment""parentId" => 3,],
  4787.                     ["id" => 4"route" => "create_receipt_voucher""name" => "Make Receipt""parentId" => 3,],
  4788.                 ]
  4789.             ],
  4790.             [
  4791.                 'id' => 4,
  4792.                 'name' => 'Report',
  4793.                 'hash' => '_RPRT_',
  4794.                 'widgetModuleId' => 1,
  4795.                 'widgetName' => 'Accounts',
  4796.                 'screenName' => '',
  4797.                 'hidden' => true,
  4798.                 'enabled' => true,
  4799.                 'image' => 'https://cdn-icons-png.flaticon.com/512/3093/3093748.png',
  4800.                 'showOnHome' => true,
  4801.                 'routeList' => [
  4802.                 ]
  4803.             ],
  4804.             [
  4805.                 'id' => 5,
  4806.                 'name' => 'Leave Application',
  4807.                 'hash' => '_LEVAPP_',
  4808.                 'widgetModuleId' => 3,
  4809.                 'widgetName' => 'Human Resource',
  4810.                 'screenName' => '',
  4811.                 'hidden' => true,
  4812.                 'enabled' => true,
  4813.                 'image' => 'https://icons.veryicon.com/png/o/transport/easy-office-system-icon-library/leave-request.png',
  4814.                 'showOnHome' => true,
  4815.                 'routeList' => [
  4816.                 ]
  4817.             ],
  4818.             [
  4819.                 'id' => 6,
  4820.                 'name' => 'Fund Requisition',
  4821.                 'hash' => '_FR_',
  4822.                 'widgetModuleId' => 1,
  4823.                 'widgetName' => 'Accounts',
  4824.                 'screenName' => '',
  4825.                 'hidden' => true,
  4826.                 'enabled' => true,
  4827.                 'image' => 'https://www.pngall.com/wp-content/uploads/13/Fund-PNG-Image.png',
  4828.                 'showOnHome' => true,
  4829.                 'routeList' => [
  4830.                 ]
  4831.             ],
  4832.             [
  4833.                 'id' => 7,
  4834.                 'name' => 'My Task',
  4835.                 'hash' => '_MT_',
  4836.                 'widgetModuleId' => 3,
  4837.                 'widgetName' => 'Human Resource',
  4838.                 'screenName' => '',
  4839.                 'hidden' => true,
  4840.                 'enabled' => true,
  4841.                 'image' => 'https://st.depositphotos.com/44273736/54272/v/450/depositphotos_542726218-stock-illustration-premium-download-icon-task-management.jpg',
  4842.                 'showOnHome' => true,
  4843.                 'routeList' => [
  4844.                 ]
  4845.             ],
  4846.             [
  4847.                 'id' => 8,
  4848.                 'name' => 'Fund Transfer',
  4849.                 'hash' => '_FT_',
  4850.                 'widgetModuleId' => 3,
  4851.                 'widgetName' => 'Accounts',
  4852.                 'screenName' => '',
  4853.                 'hidden' => true,
  4854.                 'enabled' => true,
  4855.                 'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
  4856.                 'showOnHome' => true,
  4857.                 'routeList' => [
  4858.                 ]
  4859.             ],
  4860.             [
  4861.                 'id' => 9,
  4862.                 'name' => 'Stock Management',
  4863.                 'hash' => '_SM_',
  4864.                 'widgetModuleId' => 3,
  4865.                 'widgetName' => 'Inventory',
  4866.                 'screenName' => '',
  4867.                 'hidden' => true,
  4868.                 'enabled' => true,
  4869.                 'image' => 'https://l450v.alamy.com/450v/r1r4rx/money-transfer-vector-icon-isolated-on-transparent-background-money-transfer-transparency-logo-concept-r1r4rx.jpg',
  4870.                 'showOnHome' => true,
  4871.                 'routeList' => [
  4872.                 ]
  4873.             ],
  4874.             [
  4875.                 'id' => 10,
  4876.                 'name' => 'Approval',
  4877.                 'hash' => '_ADM_',
  4878.                 'widgetModuleId' => 4,
  4879.                 'widgetName' => 'Inventory',
  4880.                 'screenName' => '',
  4881.                 'hidden' => true,
  4882.                 'enabled' => true,
  4883.                 'image' => 'https://cdn.icon-icons.com/icons2/907/PNG/512/approve-sign-in-a-black-rounded-square-shape_icon-icons.com_70558.png',
  4884.                 'showOnHome' => true,
  4885.                 'routeList' => [
  4886.                 ]
  4887.             ],
  4888.         ];
  4889.         return new JsonResponse(
  4890.             array(
  4891.                 'success' => true,
  4892.                 'widgetList' => $widgetsList
  4893.             )
  4894.         );
  4895.     }
  4896.     public function addRemoveWidgetAction(Request $request$id 0)
  4897.     {
  4898.         $em $this->getDoctrine()->getManager();
  4899. //        $user = $em->getRepository("ApplicationBundle\\Entity\\SysUser")
  4900. //            ->findBy();
  4901.         return new  JsonResponse(
  4902. //            $user
  4903.         );
  4904.     }
  4905.     public function EncryptParentModulesAction(Request $request$appId 0$companyId 0)
  4906.     {
  4907.         $message "";
  4908.         $gocList = [];
  4909.         $outputList = [];
  4910.         $pmodules = [];
  4911.         if ($request->query->has('modulesByComma'))
  4912.             $pmodules explode(','$request->query->get('modulesByComma'));
  4913.         $iv '1234567812345678';
  4914.         $pass $appId '_' $companyId;
  4915.         //        $method = 'aes-256-cbc';
  4916.         $str json_encode($pmodules);
  4917. //                        $str=$request->query->get('modulesByComma');
  4918.         $str $str 'YmLRocksLikeABoss';
  4919.         $data $str;
  4920.         $data openssl_encrypt($str"AES-128-CBC"$pass0$iv);
  4921.         //        $data=$str;
  4922. //                        $data = openssl_decrypt($data, "AES-128-CBC", $pass, 0, $iv);
  4923. //                        $data = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", $pass, 0, $iv);
  4924.         return new Response($data);
  4925. //        return new JsonResponse(array(
  4926. //            'encData'=>$data
  4927. //        ));
  4928.     }
  4929.     public function PrepareDatabaseAction(Request $request)
  4930.     {
  4931.         $message "";
  4932.         $gocList = [];
  4933.         $outputList = [];
  4934.         $em $this->getDoctrine()->getManager('company_group');
  4935.         $em->getConnection()->connect();
  4936.         $connected $em->getConnection()->isConnected();
  4937.         if ($connected)
  4938.             $gocList $this->getDoctrine()->getManager('company_group')
  4939.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  4940.                 ->findBy(
  4941.                     array(
  4942.                         'active' => 1
  4943.                     )
  4944.                 );
  4945.         $gocDataList = [];
  4946.         foreach ($gocList as $entry) {
  4947.             $d = array(
  4948.                 'name' => $entry->getName(),
  4949.                 'id' => $entry->getId(),
  4950.                 'dbName' => $entry->getDbName(),
  4951.                 'dbUser' => $entry->getDbUser(),
  4952.                 'dbPass' => $entry->getDbPass(),
  4953.                 'dbHost' => $entry->getDbHost(),
  4954.                 'appId' => $entry->getAppId(),
  4955.                 'companyRemaining' => $entry->getCompanyRemaining(),
  4956.                 'companyAllowed' => $entry->getCompanyAllowed(),
  4957.             );
  4958.             $gocDataList[$entry->getId()] = $d;
  4959.         }
  4960.         $gocDbName '';
  4961.         $gocDbUser '';
  4962.         $gocDbPass '';
  4963.         $gocDbHost '';
  4964.         $gocId 0;
  4965. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  4966.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  4967.         if (!file_exists($config_dir)) {
  4968.             mkdir($config_dir0777true);
  4969.         }
  4970. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  4971. //        $content = file_exists($path) ? file_get_contents($path) : null;
  4972.         $content = [];
  4973.         $configJson = array();
  4974.         if ($content)
  4975.             $configJson json_decode($contenttrue);
  4976.         $configJsonOld $configJson;
  4977. //        if($configJson)
  4978. //        {
  4979. //
  4980. //        }
  4981. //        else
  4982.         {
  4983.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  4984.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  4985.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  4986.             $configJson['initiateDataBaseFlagByGoc'] = array();
  4987.             $configJson['motherLode'] = "http://innobd.com";
  4988.             foreach ($gocDataList as $gocId => $entry) {
  4989.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  4990.             }
  4991.         }
  4992.         //now check if database shcema update is true
  4993. //        if($configJson['dataBaseSchemaUpdateFlag']==GeneralConstant::ENTITY_APP_FLAG_TRUE)
  4994.         if (1//temporary overwrite all
  4995.         {
  4996.             //if goclist is not empty switch to each company dbase and schema update
  4997. //            if(!empty($gocDataList))
  4998.             if (1) {
  4999.                 foreach ($gocDataList as $gocId => $entry) {
  5000.                     if ($configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] == GeneralConstant::ENTITY_APP_FLAG_TRUE) {
  5001.                         $connector $this->container->get('application_connector');
  5002.                         $connector->resetConnection(
  5003.                             'default',
  5004.                             $gocDataList[$gocId]['dbName'],
  5005.                             $gocDataList[$gocId]['dbUser'],
  5006.                             $gocDataList[$gocId]['dbPass'],
  5007.                             $gocDataList[$gocId]['dbHost'],
  5008.                             true);
  5009.                         $em $this->getDoctrine()->getManager();
  5010.                         if ($em->getConnection()->isConnected()) {
  5011.                         } else {
  5012.                             $servername $gocDataList[$gocId]['dbHost'];
  5013.                             $username $gocDataList[$gocId]['dbUser'];
  5014.                             $password $gocDataList[$gocId]['dbPass'];
  5015. // Create connection
  5016.                             $conn = new \mysqli($servername$username$password);
  5017. // Check connection
  5018.                             if ($conn->connect_error) {
  5019.                                 die("Connection failed: " $conn->connect_error);
  5020.                             }
  5021. // Create database
  5022.                             $sql "CREATE DATABASE " $gocDataList[$gocId]['dbName'];
  5023.                             if ($conn->query($sql) === TRUE) {
  5024. //                                echo "Database created successfully";
  5025.                             } else {
  5026. //                                echo "Error creating database: " . $conn->error;
  5027.                             }
  5028.                             $conn->close();
  5029.                         }
  5030.                         $connector->resetConnection(
  5031.                             'default',
  5032.                             $gocDataList[$gocId]['dbName'],
  5033.                             $gocDataList[$gocId]['dbUser'],
  5034.                             $gocDataList[$gocId]['dbPass'],
  5035.                             $gocDataList[$gocId]['dbHost'],
  5036.                             true);
  5037.                         $em $this->getDoctrine()->getManager();
  5038.                         $tool = new SchemaTool($em);
  5039.                         $classes $em->getMetadataFactory()->getAllMetadata();
  5040. //                    $tool->createSchema($classes);
  5041.                         $tool->updateSchema($classes);
  5042.                         //new for updating app id
  5043.                         $get_kids_sql "UPDATE `company` set app_id=" $entry['appId'] . " ;
  5044.                                         UPDATE `sys_user` set app_id=" $entry['appId'] . " ;";
  5045.                         $stmt $em->getConnection()->executeStatement($get_kids_sql);
  5046.                         $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  5047.                         //this is for large amount of goc we will see  later
  5048. //                        file_put_contents($path, json_encode($configJson));//overwrite
  5049. //                        return $this->redirectToRoute('update_database_schema');
  5050.                     }
  5051.                 }
  5052.             } else {
  5053.                 $em $this->getDoctrine()->getManager();
  5054.                 $tool = new SchemaTool($em);
  5055. //                    $classes = array(
  5056. //                        $em->getClassMetadata('Entities\User'),
  5057. //                        $em->getClassMetadata('Entities\Profile')
  5058. //                    );
  5059.                 $classes $em->getMetadataFactory()->getAllMetadata();
  5060. //                    $tool->createSchema($classes);
  5061.                 $tool->updateSchema($classes);
  5062.             }
  5063.         }
  5064.         $allSchemaUpdateDone 1;
  5065.         foreach ($configJson['initiateDataBaseFlagByGoc'] as $flag) {
  5066.             if ($flag == GeneralConstant::ENTITY_APP_FLAG_TRUE)
  5067.                 $allSchemaUpdateDone 0;
  5068.         }
  5069.         if ($allSchemaUpdateDone == 1)
  5070.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  5071.         ///last
  5072. //        file_put_contents($path, json_encode($configJson));//overwrite
  5073.         return new Response(json_encode($configJsonOld));
  5074.     }
  5075.     public function ConvertSpecificationToSubCategoryAction(Request $request)
  5076.     {
  5077.         $message "";
  5078.         $gocList = [];
  5079.         $outputList = [];
  5080.         $em $this->getDoctrine()->getManager('company_group');
  5081.         $em->getConnection()->connect();
  5082.         $connected $em->getConnection()->isConnected();
  5083.         if ($connected)
  5084.             $gocList $this->getDoctrine()->getManager('company_group')
  5085.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  5086.                 ->findBy(
  5087.                     array(
  5088.                         'active' => 1
  5089.                     )
  5090.                 );
  5091.         $gocDataList = [];
  5092.         foreach ($gocList as $entry) {
  5093.             $d = array(
  5094.                 'name' => $entry->getName(),
  5095.                 'id' => $entry->getId(),
  5096.                 'dbName' => $entry->getDbName(),
  5097.                 'dbUser' => $entry->getDbUser(),
  5098.                 'dbPass' => $entry->getDbPass(),
  5099.                 'dbHost' => $entry->getDbHost(),
  5100.                 'appId' => $entry->getAppId(),
  5101.                 'companyRemaining' => $entry->getCompanyRemaining(),
  5102.                 'companyAllowed' => $entry->getCompanyAllowed(),
  5103.             );
  5104.             $gocDataList[$entry->getId()] = $d;
  5105.         }
  5106.         $gocDbName '';
  5107.         $gocDbUser '';
  5108.         $gocDbPass '';
  5109.         $gocDbHost '';
  5110.         $gocId 0;
  5111. //        $path = $this->container->get('templating.helper.assets')->getUrl('bundles/tlfront/js/channels.json');
  5112.         $config_dir $this->container->getParameter('kernel.root_dir') . '/gifnoc/';
  5113.         if (!file_exists($config_dir)) {
  5114.             mkdir($config_dir0777true);
  5115.         }
  5116. //        $path = $this->container->getParameter('kernel.root_dir') . '/gifnoc/givnocppa.json';
  5117. //        $content = file_exists($path) ? file_get_contents($path) : null;
  5118.         $content = [];
  5119.         $configJson = array();
  5120.         if ($content)
  5121.             $configJson json_decode($contenttrue);
  5122.         $configJsonOld $configJson;
  5123. //        if($configJson)
  5124. //        {
  5125. //
  5126. //        }
  5127. //        else
  5128.         {
  5129.             $configJson['appVersion'] = GeneralConstant::ENTITY_APP_VERSION;
  5130.             $configJson['dataBaseSchemaUpdateFlag'] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  5131.             $configJson['initiateDataBaseFlag'] = GeneralConstant::ENTITY_APP_FLAG_FALSE;
  5132.             $configJson['initiateDataBaseFlagByGoc'] = array();
  5133.             $configJson['motherLode'] = "http://innobd.com";
  5134.             foreach ($gocDataList as $gocId => $entry) {
  5135.                 $configJson['initiateDataBaseFlagByGoc'][$gocId "_" $entry['appId']] = GeneralConstant::ENTITY_APP_FLAG_TRUE;
  5136.             }
  5137.         }
  5138.         $foundClasses = [];
  5139.         if (1) {
  5140.             foreach ($gocDataList as $gocId => $entry) {
  5141.                 $connector $this->container->get('application_connector');
  5142.                 $connector->resetConnection(
  5143.                     'default',
  5144.                     $gocDataList[$gocId]['dbName'],
  5145.                     $gocDataList[$gocId]['dbUser'],
  5146.                     $gocDataList[$gocId]['dbPass'],
  5147.                     $gocDataList[$gocId]['dbHost'],
  5148.                     $reset true);
  5149.                 $em $this->getDoctrine()->getManager();
  5150. /////////////////////////////Now get all entity and if entity has specificationId (and subcatid) the asssign
  5151.                 $query "show tables;";
  5152.                 $query "SELECT DISTINCT TABLE_NAME
  5153.     FROM INFORMATION_SCHEMA.COLUMNS
  5154.     WHERE COLUMN_NAME IN ('specification_id','sub_category_id')
  5155.         AND TABLE_SCHEMA='" $gocDataList[$gocId]['dbName'] . "' ;";
  5156.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  5157.                 $tables $stmt;
  5158.                 foreach ($tables as $tablename) {
  5159. //                        $theClass=new $entity;
  5160.                     $foundClasses[] = $tablename['TABLE_NAME'];
  5161.                     $query "UPDATE " $tablename['TABLE_NAME'] . " set sub_category_id=specification_id where 1;";
  5162.                     $stmt $em->getConnection()->executeStatement($query);
  5163.                     $query "UPDATE " $tablename['TABLE_NAME'] . " set specification_id=null;";
  5164.                     $stmt $em->getConnection()->executeStatement($query);
  5165.                 }
  5166.                 //now add all spec to cat table
  5167.                 $query "TRUNCATE  inv_product_sub_categories";
  5168.                 $stmt $em->getConnection()->executeStatement($query);
  5169.                 $query "SELECT * FROM inv_product_specifications WHERE 1;";
  5170.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  5171.                 $results $stmt;
  5172.                 foreach ($results as $result) {
  5173.                     foreach ($result as $k => $res) {
  5174.                         if ($res == '')
  5175.                             $result[$k] = 'NULL';
  5176.                     }
  5177.                     $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`)
  5178. 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'] . "')";
  5179.                     $stmt $em->getConnection()->executeStatement($query);
  5180.                 }
  5181.                 $query "TRUNCATE  inv_product_specifications";
  5182.                 $stmt $em->getConnection()->executeStatement($query);
  5183.             }
  5184.         }
  5185.         return new Response(json_encode($foundClasses));
  5186.     }
  5187.     public function initiateAdminAction(Request $request)
  5188.     {
  5189.         $em $this->getDoctrine()->getManager();
  5190.         $em_goc $this->getDoctrine()->getManager('company_group');
  5191.         $em_goc->getConnection()->connect();
  5192.         $gocId 0;
  5193.         $appId 0;
  5194.         $gocEnabled 0;
  5195.         if ($this->container->hasParameter('entity_group_enabled'))
  5196.             $gocEnabled $this->container->getParameter('entity_group_enabled');
  5197.         if ($gocEnabled == 1)
  5198.             $connected $em_goc->getConnection()->isConnected();
  5199.         else
  5200.             $connected false;
  5201.         if ($connected)
  5202.             $gocList $em_goc
  5203.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  5204.                 ->findBy(
  5205.                     array(
  5206.                         'active' => 1
  5207.                     )
  5208.                 );
  5209.         $gocDataList = [];
  5210.         $gocDataListForLoginWeb = [];
  5211.         $gocDataListByAppId = [];
  5212.         foreach ($gocList as $entry) {
  5213.             $d = array(
  5214.                 'name' => $entry->getName(),
  5215.                 'id' => $entry->getId(),
  5216.                 'appId' => $entry->getAppId(),
  5217.                 'skipInWebFlag' => $entry->getSkipInWebFlag(),
  5218.                 'skipInAppFlag' => $entry->getSkipInAppFlag(),
  5219.                 'dbName' => $entry->getDbName(),
  5220.                 'dbUser' => $entry->getDbUser(),
  5221.                 'dbPass' => $entry->getDbPass(),
  5222.                 'dbHost' => $entry->getDbHost(),
  5223.                 'companyRemaining' => $entry->getCompanyRemaining(),
  5224.                 'companyAllowed' => $entry->getCompanyAllowed(),
  5225.             );
  5226.             $gocDataList[$entry->getId()] = $d;
  5227.             if (in_array($entry->getSkipInWebFlag(), [0null]))
  5228.                 $gocDataListForLoginWeb[$entry->getId()] = $d;
  5229.             $gocDataListByAppId[$entry->getAppId()] = $d;
  5230.         }
  5231.         if ($request->request->has('gocId') || $request->query->has('gocId')) {
  5232.             $hasGoc 1;
  5233.             $gocId $request->request->get('gocId');
  5234.         }
  5235.         if ($request->request->has('appId') || $request->query->has('appId')) {
  5236.             $hasGoc 1;
  5237.             $appId $request->request->get('appId');
  5238.         }
  5239.         $refRoute $request->request->get('refRoute'$request->query->get('refRoute'''));
  5240.         if ($hasGoc == 1) {
  5241.             if ($gocId != && $gocId != "") {
  5242.                 $appId $gocDataList[$gocId]['appId'];
  5243.                 $connector $this->container->get('application_connector');
  5244.                 $connector->resetConnection(
  5245.                     'default',
  5246.                     $gocDataList[$gocId]['dbName'],
  5247.                     $gocDataList[$gocId]['dbUser'],
  5248.                     $gocDataList[$gocId]['dbPass'],
  5249.                     $gocDataList[$gocId]['dbHost'],
  5250.                     $reset true
  5251.                 );
  5252.             } else if ($appId != && $appId != "") {
  5253.                 $gocDbName $gocDataListByAppId[$appId]['dbName'];
  5254.                 $gocDbUser $gocDataListByAppId[$appId]['dbUser'];
  5255.                 $gocDbPass $gocDataListByAppId[$appId]['dbPass'];
  5256.                 $gocDbHost $gocDataListByAppId[$appId]['dbHost'];
  5257.                 $gocId $gocDataListByAppId[$appId]['id'];
  5258.                 $connector $this->container->get('application_connector');
  5259.                 $connector->resetConnection(
  5260.                     'default',
  5261.                     $gocDbName,
  5262.                     $gocDbUser,
  5263.                     $gocDbPass,
  5264.                     $gocDbHost,
  5265.                     $reset true
  5266.                 );
  5267.             }
  5268.         }
  5269.         $userName $request->request->get('username'$request->query->get('username''admin'));
  5270.         $name $request->request->get('name'$request->query->get('name''System Admin'));
  5271.         $password $request->request->get('password'$request->query->get('password''admin'));
  5272.         $email $request->request->get('email'$request->query->get('email''admin'));
  5273.         $encodedPassword $this->container->get('app.legacy_password_service')->hashWithSalt($password$userName);
  5274.         $companyIds $request->request->get('companyIds'$request->query->get('companyIds', [1]));
  5275.         $branchIds $request->request->get('branchIds'$request->query->get('branchIds', [1]));
  5276.         $appIds $request->request->get('appIds'$request->query->get('appIds', [$appId]));
  5277.         $freshFlag $request->request->get('fresh'$request->query->get('fresh'1));
  5278.         if ($freshFlag == 1) {
  5279.             $query "DELETE FROM sys_user WHERE user_type=1";
  5280.             $stmt $em->getConnection()->executeStatement($query);
  5281.         }
  5282.         $message $this->get('user_module')->addNewUser(
  5283.             $name,
  5284.             $email,
  5285.             $userName,
  5286.             $password,
  5287.             '',
  5288.             0,
  5289.             1,
  5290.             UserConstants::USER_TYPE_SYSTEM,
  5291.             $companyIds,
  5292.             $branchIds,
  5293.             '',
  5294.             "",
  5295.             1
  5296.         );
  5297.         $companyData $message[2];
  5298.         if ($message[0] == 'success') {
  5299.             $oAuthData = [
  5300.                 'email' => $email,
  5301.                 'uniqueId' => '',
  5302.                 'image' => '',
  5303.                 'emailVerified' => '',
  5304.                 'name' => $name,
  5305.                 'type' => '0',
  5306.                 'token' => '',
  5307.             ];
  5308.             if (GeneralConstant::EMAIL_ENABLED == 1) {
  5309.                 $bodyHtml '';
  5310.                 $bodyTemplate '@Application/email/templates/userRegistrationCompleteHoneybee.html.twig';
  5311.                 $bodyData = array(
  5312.                     'name' => $name,
  5313.                     'email' => $email,
  5314.                     'password' => $password,
  5315.                 );
  5316.                 $attachments = [];
  5317.                 $forwardToMailAddress $email;
  5318.                 if (filter_var($forwardToMailAddressFILTER_VALIDATE_EMAIL)) {
  5319. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  5320.                     $new_mail $this->get('mail_module');
  5321.                     $new_mail->sendMyMail(array(
  5322.                         'senderHash' => '_CUSTOM_',
  5323.                         //                        'senderHash'=>'_CUSTOM_',
  5324.                         'forwardToMailAddress' => $forwardToMailAddress,
  5325.                         'subject' => 'Welcome to Honeybee Ecosystem ',
  5326. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  5327.                         'attachments' => $attachments,
  5328.                         'toAddress' => $forwardToMailAddress,
  5329.                         'fromAddress' => 'accounts@ourhoneybee.eu',
  5330.                         'userName' => 'accounts@ourhoneybee.eu',
  5331.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  5332.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  5333.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  5334. //                            'emailBody' => $bodyHtml,
  5335.                         'mailTemplate' => $bodyTemplate,
  5336.                         'templateData' => $bodyData,
  5337. //                        'embedCompanyImage' => 1,
  5338. //                        'companyId' => $companyId,
  5339. //                        'companyImagePath' => $company_data->getImage()
  5340.                     ));
  5341.                 }
  5342.             }
  5343. //            if ($request->request->get('remoteVerify', 0) == 1)
  5344. ////                if(1)
  5345. //                return new JsonResponse(array(
  5346. //                    'success' => true,
  5347. //                    'successStr' => 'Account Created Successfully',
  5348. //                    'id' => $newApplicant->getApplicantId(),
  5349. //                    'oAuthData' => $oAuthData,
  5350. //                    'refRoute' => $refRoute,
  5351. //                    'remoteVerify' => 1,
  5352. //                ));
  5353. //            else
  5354. //                return $this->redirectToRoute("user_login", [
  5355. //                    'id' => $newApplicant->getApplicantId(),
  5356. //                    'oAuthData' => $oAuthData,
  5357. //                    'refRoute' => $refRoute,
  5358. //
  5359. //                ]);
  5360.             $bodyHtml '';
  5361.             $bodyTemplate '@Application/email/user/registration.html.twig';
  5362.             $bodyData = array(
  5363.                 'name' => $request->request->get('name'),
  5364.                 'companyData' => $companyData,
  5365.                 'userName' => $request->request->get('username'),
  5366.                 'password' => $request->request->get('password'),
  5367.             );
  5368.             $attachments = [];
  5369. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  5370.             $new_mail $this->get('mail_module');
  5371.             $new_mail->sendMyMail(array(
  5372.                 'senderHash' => '_USER_MANAGEMENT_',
  5373.                 //                        'senderHash'=>'_CUSTOM_',
  5374.                 'forwardToMailAddress' => $request->request->get('email'),
  5375.                 'subject' => 'User Registration on HoneyBee Ecosystem under Company ' $companyData->getName(),
  5376.                 'fileName' => '',
  5377.                 'attachments' => $attachments,
  5378.                 'toAddress' => $request->request->get('email'),
  5379. //                        'fromAddress'=>'sales@entity.innobd.com',
  5380. //                        'userName'=>'sales@entity.innobd.com',
  5381. //                        'password'=>'Y41dh8g0112',
  5382. //                        'smtpServer'=>'smtp.hostinger.com',
  5383. //                        'smtpPort'=>587,
  5384. //                        'emailBody'=>$bodyHtml,
  5385.                 'mailTemplate' => $bodyTemplate,
  5386.                 'templateData' => $bodyData,
  5387.                 'embedCompanyImage' => 1,
  5388.                 'companyId' => $request->request->get('company'),
  5389.                 'companyImagePath' => $companyData->getImage()
  5390.             ));
  5391. //                $emailmessage = (new \Swift_Message('Registration to Entity'))
  5392. //                    ->setFrom('registration@entity.innobd.com')
  5393. //                    ->setTo($request->request->get('email'))
  5394. //                    ->setBody(
  5395. //                        $this->renderView(
  5396. //                            'ApplicationBundle:email/user:registration.html.twig',
  5397. //                            array('name' => $request->request->get('name'),
  5398. //                                'companyData' => $companyData,
  5399. //                                'userName' => $request->request->get('email'),
  5400. //                                'password' => $request->request->get('password'),
  5401. //                            )
  5402. //                        ),
  5403. //                        'text/html'
  5404. //                    );
  5405. //                /*
  5406. //                 * If you also want to include a plaintext version of the message
  5407. //                ->addPart(
  5408. //                    $this->renderView(
  5409. //                        'Emails/registration.txt.twig',
  5410. //                        array('name' => $name)
  5411. //                    ),
  5412. //                    'text/plain'
  5413. //                )
  5414. //                */
  5415. ////            ;
  5416. //                $this->get('mailer')->send($emailmessage);
  5417.         }
  5418.         $this->addFlash(
  5419.             $message[0],
  5420.             $message[1]
  5421.         );
  5422. //        MiscActions::initiateAdminUser($em,$freshFlag,$userName,$name,$email,$encodedPassword,$appIds,$companyIds);
  5423.         $this->addFlash(
  5424.             'success',
  5425.             'The Action was Successful.'
  5426.         );
  5427.         return $this->redirectToRoute('user_login');
  5428.     }
  5429.     public function DumpCurrModulesAction(Request $request)
  5430.     {
  5431.         $em $this->getDoctrine()->getManager();
  5432.         $modules $em->getRepository("ApplicationBundle\\Entity\\SysModule")
  5433.             ->findBy(
  5434.                 array(//                    'active'=>1
  5435.                 )
  5436.             );
  5437.         $module_data = [];
  5438.         foreach ($modules as $entry) {
  5439.             $dt = array(
  5440.                 'id' => $entry->getModuleId(),
  5441.                 'route' => $entry->getModuleRoute(),
  5442.                 'name' => $entry->getModuleName(),
  5443.                 'parentId' => $entry->getParentId(),
  5444.                 'level' => $entry->getLevel(),
  5445.                 'eFA' => $entry->getEnabledForAll(),
  5446.             );
  5447.             $module_data[$entry->getModuleId()] = $dt;
  5448.         }
  5449.         return new JsonResponse(
  5450.             $module_data
  5451.         );
  5452.     }
  5453.     public function GetTenantDashboardMetricsAction(Request $request)
  5454.     {
  5455.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  5456.         if ($systemType === '_CENTRAL_') {
  5457.             return new JsonResponse([
  5458.                 'success' => false,
  5459.                 'message' => 'Tenant metrics are available only on ERP servers.',
  5460.             ], 400);
  5461.         }
  5462.         $days max(1, (int)$request->get('days'30));
  5463.         $requestedAppIds $this->normalizeTenantAppIds($request);
  5464.         $em $this->getDoctrine()->getManager();
  5465.         $conn $em->getConnection();
  5466.         $companyRows $this->loadTenantCompanyRows($conn$requestedAppIds);
  5467.         if (empty($companyRows)) {
  5468.             $companyRows = [
  5469.                 [
  5470.                     'id' => 0,
  5471.                     'appId' => $requestedAppIds[0] ?? 0,
  5472.                     'name' => 'Company',
  5473.                     'email' => '',
  5474.                     'company_status' => 'active',
  5475.                     'package_type' => null,
  5476.                     'subscription_expiry' => null,
  5477.                     'last_activity_at' => null,
  5478.                 ],
  5479.             ];
  5480.         }
  5481.         $userCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_user');
  5482.         $activeUserCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_user WHERE status = 1 OR account_status IN (1, 2, 3)');
  5483.         $loginCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sys_login_log');
  5484.         $pageVisitCount = (int)$conn->fetchOne("SELECT COUNT(*) FROM user_activity_logs WHERE action_type = 'page_visit'");
  5485.         $apiCallCount = (int)$conn->fetchOne("SELECT COUNT(*) FROM user_activity_logs WHERE action_type = 'api_call'");
  5486.         $salesOrderCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sales_order');
  5487.         $salesInvoiceCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM sales_invoice');
  5488.         $purchaseOrderCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM purchase_order');
  5489.         $purchaseInvoiceCount = (int)$conn->fetchOne('SELECT COUNT(*) FROM purchase_invoice');
  5490.         $salesInvoiceTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM sales_invoice");
  5491.         $salesPaidTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) FROM sales_invoice");
  5492.         $purchaseInvoiceTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM purchase_invoice");
  5493.         $purchasePaidTotal = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) FROM purchase_invoice");
  5494.         $activityTrend $conn->fetchAllAssociative('
  5495.             SELECT DATE(created_at) AS day, action_type AS activity_type, COUNT(*) AS total
  5496.             FROM user_activity_logs
  5497.             WHERE created_at >= DATE_SUB(NOW(), INTERVAL :days DAY)
  5498.               AND action_type IN (\'page_visit\', \'api_call\')
  5499.             GROUP BY DATE(created_at), action_type
  5500.             ORDER BY day ASC
  5501.         ', ['days' => $days], ['days' => \PDO::PARAM_INT]);
  5502.         $loginTrend $conn->fetchAllAssociative('
  5503.             SELECT DATE(log_time) AS day, COUNT(*) AS total
  5504.             FROM sys_login_log
  5505.             WHERE log_time >= DATE_SUB(NOW(), INTERVAL :days DAY)
  5506.             GROUP BY DATE(log_time)
  5507.             ORDER BY day ASC
  5508.         ', ['days' => $days], ['days' => \PDO::PARAM_INT]);
  5509.         $revenueTrend $conn->fetchAllAssociative("
  5510.             SELECT DATE(sales_invoice_date) AS day, COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount, ''), invoice_amount) AS DECIMAL(15,2))), 0) AS total
  5511.             FROM sales_invoice
  5512.             WHERE sales_invoice_date >= DATE_SUB(NOW(), INTERVAL :days DAY)
  5513.             GROUP BY DATE(sales_invoice_date)
  5514.             ORDER BY day ASC
  5515.         ", ['days' => $days], ['days' => \PDO::PARAM_INT]);
  5516.         $recentActivity $conn->fetchAllAssociative('
  5517.             SELECT
  5518.                 id,
  5519.                 user_id AS userId,
  5520.                 session_id AS sessionId,
  5521.                 route,
  5522.                 action_type AS activityType,
  5523.                 metadata,
  5524.                 duration_seconds AS durationSeconds,
  5525.                 created_at AS createdAt
  5526.             FROM user_activity_logs
  5527.             ORDER BY created_at DESC
  5528.             LIMIT 10
  5529.         ');
  5530.         $recentLogins $conn->fetchAllAssociative('
  5531.             SELECT
  5532.                 login_id AS loginId,
  5533.                 user_id AS userId,
  5534.                 position_id AS positionId,
  5535.                 log_time AS logTime,
  5536.                 log_status AS logStatus
  5537.             FROM sys_login_log
  5538.             ORDER BY log_time DESC
  5539.             LIMIT 10
  5540.         ');
  5541.         $recentSales $conn->fetchAllAssociative('
  5542.             SELECT
  5543.                 sales_invoice_id AS salesInvoiceId,
  5544.                 sales_invoice_number AS salesInvoiceNumber,
  5545.                 company_id AS companyId,
  5546.                 sales_invoice_date AS salesInvoiceDate,
  5547.                 invoice_amount AS invoiceAmount,
  5548.                 received_amount AS paidAmount,
  5549.                 due_amount AS dueAmount
  5550.             FROM sales_invoice
  5551.             ORDER BY sales_invoice_date DESC
  5552.             LIMIT 10
  5553.         ');
  5554.         $firstActivityAt $recentActivity[0]['createdAt'] ?? null;
  5555.         $firstLoginAt $recentLogins[0]['logTime'] ?? null;
  5556.         $firstSalesAt $recentSales[0]['salesInvoiceDate'] ?? null;
  5557.         $companySnapshots = [];
  5558.         $totalLastActivity null;
  5559.         foreach ($companyRows as $row) {
  5560.             $companyLastActivity $this->maxTenantActivityTimestamp(
  5561.                 $row['last_activity_at'] ?? null,
  5562.                 $firstActivityAt,
  5563.                 $firstLoginAt,
  5564.                 $firstSalesAt
  5565.             );
  5566.             $companySnapshots[(int)($row['appId'] ?? 0)] = [
  5567.                 'id' => $row['id'] ?? 0,
  5568.                 'appId' => (int)($row['appId'] ?? 0),
  5569.                 'name' => $row['name'] ?? 'Company',
  5570.                 'email' => $row['email'] ?? '',
  5571.                 'company_status' => $row['company_status'] ?? 'active',
  5572.                 'package_type' => $row['package_type'] ?? null,
  5573.                 'subscription_expiry' => $row['subscription_expiry'] ?? null,
  5574.                 'last_activity_at' => $companyLastActivity,
  5575.                 'user_count' => $userCount,
  5576.                 'active_user_count' => $activeUserCount,
  5577.                 'login_count' => $loginCount,
  5578.                 'page_visit_count' => $pageVisitCount,
  5579.                 'api_call_count' => $apiCallCount,
  5580.                 'sales_order_count' => $salesOrderCount,
  5581.                 'sales_invoice_count' => $salesInvoiceCount,
  5582.                 'purchase_order_count' => $purchaseOrderCount,
  5583.                 'purchase_invoice_count' => $purchaseInvoiceCount,
  5584.                 'sales_invoice_total' => $salesInvoiceTotal,
  5585.                 'sales_paid_total' => $salesPaidTotal,
  5586.                 'purchase_invoice_total' => $purchaseInvoiceTotal,
  5587.                 'purchase_paid_total' => $purchasePaidTotal,
  5588.                 'recent_activity' => $recentActivity,
  5589.                 'recent_logins' => $recentLogins,
  5590.                 'recent_sales' => $recentSales,
  5591.             ];
  5592.             $totalLastActivity $this->maxTenantActivityTimestamp($totalLastActivity$companyLastActivity);
  5593.         }
  5594.         return new JsonResponse([
  5595.             'success' => true,
  5596.             'system_type' => $systemType,
  5597.             'days' => $days,
  5598.             'requested_app_ids' => $requestedAppIds,
  5599.             'company_count' => count($companySnapshots),
  5600.             'companies' => $companySnapshots,
  5601.             'totals' => [
  5602.                 'user_count' => $userCount,
  5603.                 'active_user_count' => $activeUserCount,
  5604.                 'login_count' => $loginCount,
  5605.                 'page_visit_count' => $pageVisitCount,
  5606.                 'api_call_count' => $apiCallCount,
  5607.                 'sales_order_count' => $salesOrderCount,
  5608.                 'sales_invoice_count' => $salesInvoiceCount,
  5609.                 'purchase_order_count' => $purchaseOrderCount,
  5610.                 'purchase_invoice_count' => $purchaseInvoiceCount,
  5611.                 'sales_invoice_total' => $salesInvoiceTotal,
  5612.                 'sales_paid_total' => $salesPaidTotal,
  5613.                 'purchase_invoice_total' => $purchaseInvoiceTotal,
  5614.                 'purchase_paid_total' => $purchasePaidTotal,
  5615.                 'last_activity_at' => $totalLastActivity,
  5616.             ],
  5617.             'trend_rows' => [
  5618.                 'activity' => $activityTrend,
  5619.                 'login' => $loginTrend,
  5620.                 'revenue' => $revenueTrend,
  5621.             ],
  5622.         ]);
  5623.     }
  5624.     private function normalizeTenantAppIds(Request $request)
  5625.     {
  5626.         $appIds $request->get('appIds', []);
  5627.         $appId = (int)$request->get('appId'0);
  5628.         if (is_string($appIds)) {
  5629.             $decoded json_decode($appIdstrue);
  5630.             if (is_array($decoded)) {
  5631.                 $appIds $decoded;
  5632.             } else {
  5633.                 $appIds = [$appIds];
  5634.             }
  5635.         }
  5636.         if (!is_array($appIds)) {
  5637.             $appIds = [];
  5638.         }
  5639.         if ($appId 0) {
  5640.             $appIds[] = $appId;
  5641.         }
  5642.         return array_values(array_unique(array_filter(array_map('intval'$appIds))));
  5643.     }
  5644.     private function loadTenantCompanyRows($conn, array $appIds = [])
  5645.     {
  5646.         $sql '
  5647.             SELECT
  5648.                 id,
  5649.                 app_id AS appId,
  5650.                 name,
  5651.                 email,
  5652.                 company_status,
  5653.                 package_type,
  5654.                 subscription_expiry,
  5655.                 last_activity_at
  5656.             FROM company
  5657.         ';
  5658.         if (!empty($appIds)) {
  5659.             $sql .= ' WHERE app_id IN (' implode(','array_map('intval'$appIds)) . ')';
  5660.         }
  5661.         $sql .= ' ORDER BY id ASC';
  5662.         return $conn->fetchAllAssociative($sql);
  5663.     }
  5664.     private function maxTenantActivityTimestamp(...$values)
  5665.     {
  5666.         $maxTs null;
  5667.         $maxValue null;
  5668.         foreach ($values as $value) {
  5669.             if (empty($value)) {
  5670.                 continue;
  5671.             }
  5672.             $ts strtotime((string)$value);
  5673.             if ($ts === false) {
  5674.                 continue;
  5675.             }
  5676.             if ($maxTs === null || $ts $maxTs) {
  5677.                 $maxTs $ts;
  5678.                 $maxValue is_string($value) ? $value : (string)$value;
  5679.             }
  5680.         }
  5681.         return $maxValue;
  5682.     }
  5683.     private function populateEmployeeCoreFromDetails(Employee $employeeEmployeeDetails $details, array &$stats null)
  5684.     {
  5685.         $changed false;
  5686.         $assignIfEmpty = function ($setter$value$label null) use ($employee, &$changed, &$stats) {
  5687.             if ($value === null || $value === '') {
  5688.                 return;
  5689.             }
  5690.             $getter 'get' substr($setter3);
  5691.             if (method_exists($employee$getter)) {
  5692.                 $current $employee->{$getter}();
  5693.                 if ($current !== null && $current !== '') {
  5694.                     if ($stats !== null && $label !== null && (string)$current !== (string)$value) {
  5695.                         if (!isset($stats['conflict_count'])) {
  5696.                             $stats['conflict_count'] = 0;
  5697.                         }
  5698.                         if (!isset($stats['conflict_fields'])) {
  5699.                             $stats['conflict_fields'] = array();
  5700.                         }
  5701.                         $stats['conflict_count']++;
  5702.                         $stats['conflict_fields'][] = $label;
  5703.                     }
  5704.                     return;
  5705.                 }
  5706.             }
  5707.             if (method_exists($employee$setter)) {
  5708.                 $employee->{$setter}($value);
  5709.                 $changed true;
  5710.             }
  5711.         };
  5712.         $firstName method_exists($details'getFirstname') ? $details->getFirstname() : null;
  5713.         $lastName method_exists($details'getLastname') ? $details->getLastname() : null;
  5714.         $name trim((string)$firstName ' ' . (string)$lastName);
  5715.         if ($name === '') {
  5716.             $name null;
  5717.         }
  5718.         $assignIfEmpty('setFirstName'$firstName'firstName');
  5719.         $assignIfEmpty('setLastName'$lastName'lastName');
  5720.         $assignIfEmpty('setName'$name'name');
  5721.         $assignIfEmpty('setEmail'method_exists($details'getEmail') ? $details->getEmail() : null'email');
  5722.         $phone null;
  5723.         if (method_exists($details'getPhone')) {
  5724.             $phone $details->getPhone();
  5725.         }
  5726.         if (($phone === null || $phone === '') && method_exists($details'getOfficialPhone')) {
  5727.             $phone $details->getOfficialPhone();
  5728.         }
  5729.         $assignIfEmpty('setContactNumber'$phone'contactNumber');
  5730.         $assignIfEmpty('setCurrentAddress'method_exists($details'getCurrAddr') ? $details->getCurrAddr() : null'currentAddress');
  5731.         $assignIfEmpty('setPermanentAddress'method_exists($details'getPermAddr') ? $details->getPermAddr() : null'permanentAddress');
  5732.         $assignIfEmpty('setImage'method_exists($details'getImage') ? $details->getImage() : null'image');
  5733.         $assignIfEmpty('setIdsByDevice'method_exists($details'getIdsByDevice') ? $details->getIdsByDevice() : null'idsByDevice');
  5734.         $assignIfEmpty('setEmployeeCode'method_exists($details'getEmpCode') ? $details->getEmpCode() : null'employeeCode');
  5735.         $assignIfEmpty('setEmployeeLevel'method_exists($details'getEmployeeLevel') ? $details->getEmployeeLevel() : null'employeeLevel');
  5736.         $assignIfEmpty('setUserId'method_exists($details'getUserId') ? $details->getUserId() : null'userId');
  5737.         if (method_exists($details'getEmpStatus')) {
  5738.             $status $details->getEmpStatus();
  5739.             if ($status !== null && $status !== '') {
  5740.                 $assignIfEmpty('setStatus', (string)$status'status');
  5741.             }
  5742.         }
  5743.         if (method_exists($details'getJoiningDate')) {
  5744.             $joiningDate $details->getJoiningDate();
  5745.             if ($joiningDate !== null && method_exists($employee'getJoiningDate')) {
  5746.                 $currentJoiningDate $employee->getJoiningDate();
  5747.                 if ($currentJoiningDate === null || $currentJoiningDate === '') {
  5748.                     if (method_exists($employee'setJoiningDate')) {
  5749.                         $employee->setJoiningDate($joiningDate);
  5750.                         $changed true;
  5751.                     } elseif ($stats !== null) {
  5752.                         if (!isset($stats['conflict_count'])) {
  5753.                             $stats['conflict_count'] = 0;
  5754.                         }
  5755.                         if (!isset($stats['conflict_fields'])) {
  5756.                             $stats['conflict_fields'] = array();
  5757.                         }
  5758.                         $stats['conflict_count']++;
  5759.                         $stats['conflict_fields'][] = 'joiningDate';
  5760.                     }
  5761.                 }
  5762.             }
  5763.         }
  5764.         return $changed;
  5765.     }
  5766.     private function migrateEmployeeDetailsToProfile($em)
  5767.     {
  5768.         $stats = array(
  5769.             'supported' => true,
  5770.             'skipped' => false,
  5771.             'created_profile_table' => false,
  5772.             'profile_rows_synced' => 0,
  5773.             'profile_rows_rekeyed' => 0,
  5774.             'employee_rows_synced' => 0,
  5775.             'created_employee_shells' => 0,
  5776.             'conflict_count' => 0,
  5777.             'conflict_fields' => array(),
  5778.             'messages' => array(),
  5779.         );
  5780.         $conn $em->getConnection();
  5781.         $platformName strtolower((string)$conn->getDatabasePlatform()->getName());
  5782.         if ($platformName !== 'mysql') {
  5783.             $stats['supported'] = false;
  5784.             $stats['skipped'] = true;
  5785.             $stats['messages'][] = 'employee migration is mysql-only';
  5786.             return $stats;
  5787.         }
  5788.         $tableExists = function ($tableName) use ($conn) {
  5789.             $rows $conn->fetchAllAssociative(
  5790.                 "SELECT COUNT(*) AS table_count
  5791.                  FROM INFORMATION_SCHEMA.TABLES
  5792.                  WHERE TABLE_SCHEMA = DATABASE()
  5793.                    AND TABLE_NAME = '" str_replace("'""''"$tableName) . "'"
  5794.             );
  5795.             return isset($rows[0]['table_count']) && (int)$rows[0]['table_count'] > 0;
  5796.         };
  5797.         if (!$tableExists('employee_details')) {
  5798.             $stats['skipped'] = true;
  5799.             $stats['messages'][] = 'employee_details table was not found';
  5800.             return $stats;
  5801.         }
  5802.         if (!$tableExists('employee_profile')) {
  5803.             $ddlRows $conn->fetchAllAssociative('SHOW CREATE TABLE `employee_details`');
  5804.             if (!empty($ddlRows[0])) {
  5805.                 $createSql '';
  5806.                 $rowValues array_values($ddlRows[0]);
  5807.                 foreach ($rowValues as $value) {
  5808.                     if (is_string($value) && stripos($value'CREATE TABLE') === 0) {
  5809.                         $createSql $value;
  5810.                         break;
  5811.                     }
  5812.                 }
  5813.                 if ($createSql === '' && isset($rowValues[1])) {
  5814.                     $createSql $rowValues[1];
  5815.                 }
  5816.                 if ($createSql !== '') {
  5817.                     $createSql str_replace('CREATE TABLE `employee_details`''CREATE TABLE `employee_profile`'$createSql);
  5818.                     $createSql str_replace('`id`''`employee_id`'$createSql);
  5819.                     $conn->executeStatement($createSql);
  5820.                     $stats['created_profile_table'] = true;
  5821.                 }
  5822.             }
  5823.         }
  5824.         $copyColumns = array();
  5825.         $columnRows $conn->fetchAllAssociative('SHOW COLUMNS FROM `employee_details`');
  5826.         foreach ($columnRows as $columnRow) {
  5827.             if (!isset($columnRow['Field'])) {
  5828.                 continue;
  5829.             }
  5830.             if ($columnRow['Field'] === 'id') {
  5831.                 continue;
  5832.             }
  5833.             $copyColumns[] = $columnRow['Field'];
  5834.         }
  5835.         if (!empty($copyColumns) && $tableExists('employee_profile')) {
  5836.             $insertColumns array_merge(array('employee_id'), $copyColumns);
  5837.             $insertColumnsSql = array();
  5838.             foreach ($insertColumns as $columnName) {
  5839.                 $insertColumnsSql[] = '`' $columnName '`';
  5840.             }
  5841.             $selectColumnsSql = array('`id` AS `employee_id`');
  5842.             foreach ($copyColumns as $columnName) {
  5843.                 $selectColumnsSql[] = '`' $columnName '`';
  5844.             }
  5845.             $updateColumnsSql = array();
  5846.             foreach ($copyColumns as $columnName) {
  5847.                 $updateColumnsSql[] = '`' $columnName '` = VALUES(`' $columnName '`)';
  5848.             }
  5849.             $syncSql 'INSERT INTO `employee_profile` (' implode(', '$insertColumnsSql) . ')
  5850.                         SELECT ' implode(', '$selectColumnsSql) . '
  5851.                         FROM `employee_details`
  5852.                         ON DUPLICATE KEY UPDATE ' implode(', '$updateColumnsSql);
  5853.             $conn->executeStatement($syncSql);
  5854.             $stats['profile_rows_synced'] = (int)$conn->fetchOne('SELECT COUNT(*) FROM `employee_profile`');
  5855.         }
  5856.         $detailsRows $em->getRepository('ApplicationBundle\\Entity\\EmployeeDetails')->findBy(array(), array('id' => 'ASC'));
  5857.         $employeeRepo $em->getRepository('ApplicationBundle\\Entity\\Employee');
  5858.         foreach ($detailsRows as $details) {
  5859.             $employee $employeeRepo->findOneBy(array('employeeId' => $details->getId()));
  5860.             if (!$employee && method_exists($details'getUserId') && $details->getUserId()) {
  5861.                 $employee $employeeRepo->findOneBy(array('userId' => $details->getUserId()));
  5862.             }
  5863.             $oldEmployeeId null;
  5864.             if ($employee) {
  5865.                 $oldEmployeeId $employee->getEmployeeId();
  5866.             } else {
  5867.                 $employee = new Employee();
  5868.                 $stats['created_employee_shells']++;
  5869.             }
  5870.             $changed $this->populateEmployeeCoreFromDetails($employee$details$stats);
  5871.             if (!$oldEmployeeId && method_exists($details'getUserId') && $details->getUserId() && method_exists($employee'setUserId')) {
  5872.                 $employee->setUserId($details->getUserId());
  5873.                 $changed true;
  5874.             }
  5875.             if ($changed || !$oldEmployeeId) {
  5876.                 $em->persist($employee);
  5877.                 $em->flush();
  5878.                 $stats['employee_rows_synced']++;
  5879.             } else {
  5880.                 $em->persist($employee);
  5881.             }
  5882.             $newEmployeeId $employee->getEmployeeId();
  5883.             if ((int)$details->getId() !== (int)$newEmployeeId && $tableExists('employee_profile')) {
  5884.                 $conn->executeStatement(
  5885.                     'UPDATE `employee_profile` SET `employee_id` = :new_id WHERE `employee_id` = :old_id',
  5886.                     array(
  5887.                         'new_id' => $newEmployeeId,
  5888.                         'old_id' => $details->getId(),
  5889.                     )
  5890.                 );
  5891.                 $stats['profile_rows_rekeyed']++;
  5892.             }
  5893.         }
  5894.         return $stats;
  5895.     }
  5896.     // =========================================================================
  5897.     // OWNER DASHBOARD SNAPSHOT
  5898.     // Called by the central server's OwnerDashboardService::curlErpSnapshot().
  5899.     // Returns a JSON snapshot of financials + KPIs for the company owner portal.
  5900.     // No session required — this is a server-to-server call.
  5901.     // =========================================================================
  5902.     public function GetOwnerDashboardSnapshotAction(Request $request)
  5903.     {
  5904.         $systemType $this->container->hasParameter('system_type')
  5905.             ? $this->container->getParameter('system_type')
  5906.             : '_ERP_';
  5907.         if ($systemType === '_CENTRAL_') {
  5908.             return new JsonResponse([
  5909.                 'success' => false,
  5910.                 'message' => 'Owner snapshot only available on ERP servers.',
  5911.             ], 400);
  5912.         }
  5913.         $em $this->getDoctrine()->getManager();
  5914.         $conn $em->getConnection();
  5915.         // ── Financial data ────────────────────────────────────────────────────
  5916.         $revenueThisMonth 0.0;
  5917.         $revenueLast 0.0;
  5918.         $expensesThisMonth 0.0;
  5919.         $receivables 0.0;
  5920.         $payables 0.0;
  5921.         try {
  5922.             $revenueThisMonth = (float)$conn->fetchOne("
  5923.                 SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
  5924.                 FROM sales_invoice
  5925.                 WHERE YEAR(sales_invoice_date)  = YEAR(NOW())
  5926.                   AND MONTH(sales_invoice_date) = MONTH(NOW())
  5927.             ");
  5928.             $revenueLast = (float)$conn->fetchOne("
  5929.                 SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
  5930.                 FROM sales_invoice
  5931.                 WHERE sales_invoice_date >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01')
  5932.                   AND sales_invoice_date <  DATE_FORMAT(NOW(), '%Y-%m-01')
  5933.             ");
  5934.             $expensesThisMonth = (float)$conn->fetchOne("
  5935.                 SELECT COALESCE(SUM(CAST(COALESCE(NULLIF(paid_amount,''), invoice_amount) AS DECIMAL(15,2))), 0)
  5936.                 FROM purchase_invoice
  5937.                 WHERE YEAR(invoice_date)  = YEAR(NOW())
  5938.                   AND MONTH(invoice_date) = MONTH(NOW())
  5939.             ");
  5940.             $receivables = (float)$conn->fetchOne("
  5941.                 SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0)
  5942.                 FROM sales_invoice
  5943.                 WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')
  5944.             ");
  5945.             $payables = (float)$conn->fetchOne("
  5946.                 SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0)
  5947.                 FROM purchase_invoice
  5948.                 WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')
  5949.             ");
  5950.         } catch (\Exception $e) {
  5951.             // Tables may not exist on all ERP versions — skip gracefully
  5952.         }
  5953.         $profitThisMonth $revenueThisMonth $expensesThisMonth;
  5954.         // Monthly revenue trend (last 6 months)
  5955.         $monthlyTrend = [];
  5956.         try {
  5957.             $trendRows $conn->fetchAllAssociative("
  5958.                 SELECT DATE_FORMAT(sales_invoice_date, '%Y-%m') AS month,
  5959.                        COALESCE(SUM(CAST(COALESCE(NULLIF(received_amount,''), invoice_amount) AS DECIMAL(15,2))), 0) AS amount
  5960.                 FROM sales_invoice
  5961.                 WHERE sales_invoice_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
  5962.                 GROUP BY DATE_FORMAT(sales_invoice_date, '%Y-%m')
  5963.                 ORDER BY month ASC
  5964.             ");
  5965.             foreach ($trendRows as $row) {
  5966.                 $monthlyTrend[] = ['month' => $row['month'], 'amount' => (float)$row['amount']];
  5967.             }
  5968.         } catch (\Exception $e) {
  5969.             // Skip
  5970.         }
  5971.         // ── KPI data ──────────────────────────────────────────────────────────
  5972.         $totalEmployees 0;
  5973.         $presentToday 0;
  5974.         $attendancePct 0.0;
  5975.         $tasksTotal 0;
  5976.         $tasksCompleted 0;
  5977.         $tasksOverdue 0;
  5978.         $taskRate 0.0;
  5979.         $openInvoices 0;
  5980.         $overdueInvoices 0;
  5981.         $totalInvoiceAmt 0.0;
  5982.         try {
  5983.             $totalEmployees = (int)$conn->fetchOne(
  5984.                 "SELECT COUNT(*) FROM employee WHERE status = 1 OR status IS NULL"
  5985.             );
  5986.         } catch (\Exception $e) {
  5987.             try {
  5988.                 $totalEmployees = (int)$conn->fetchOne(
  5989.                     "SELECT COUNT(*) FROM sys_user WHERE status = 1"
  5990.                 );
  5991.             } catch (\Exception $ex) {
  5992.             }
  5993.         }
  5994.         // Attendance: try common table names used by the ERP HR module
  5995.         try {
  5996.             $today date('Y-m-d');
  5997.             $presentToday = (int)$conn->fetchOne(
  5998.                 "SELECT COUNT(DISTINCT employee_id) FROM employee_daily_log
  5999.                  WHERE log_date = :d AND in_time IS NOT NULL",
  6000.                 ['d' => $today]
  6001.             );
  6002.         } catch (\Exception $e) {
  6003.             try {
  6004.                 $today date('Y-m-d');
  6005.                 $presentToday = (int)$conn->fetchOne(
  6006.                     "SELECT COUNT(DISTINCT user_id) FROM user_activity_logs
  6007.                      WHERE DATE(created_at) = :d AND action_type = 'page_visit'",
  6008.                     ['d' => $today]
  6009.                 );
  6010.             } catch (\Exception $ex) {
  6011.             }
  6012.         }
  6013.         if ($totalEmployees 0) {
  6014.             $attendancePct round(($presentToday $totalEmployees) * 1001);
  6015.         }
  6016.         // Tasks: try common task table names
  6017.         try {
  6018.             $tasksTotal = (int)$conn->fetchOne("SELECT COUNT(*) FROM task");
  6019.             $tasksCompleted = (int)$conn->fetchOne("SELECT COUNT(*) FROM task WHERE status IN ('done','completed','closed')");
  6020.             $tasksOverdue = (int)$conn->fetchOne("SELECT COUNT(*) FROM task WHERE due_date < NOW() AND status NOT IN ('done','completed','closed')");
  6021.         } catch (\Exception $e) {
  6022.             try {
  6023.                 $tasksTotal = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task");
  6024.                 $tasksCompleted = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task WHERE status IN ('done','completed','closed')");
  6025.                 $tasksOverdue = (int)$conn->fetchOne("SELECT COUNT(*) FROM project_task WHERE due_date < NOW() AND status NOT IN ('done','completed','closed')");
  6026.             } catch (\Exception $ex) {
  6027.             }
  6028.         }
  6029.         if ($tasksTotal 0) {
  6030.             $taskRate round(($tasksCompleted $tasksTotal) * 1001);
  6031.         }
  6032.         // Invoice KPIs
  6033.         try {
  6034.             $openInvoices = (int)$conn->fetchOne("SELECT COUNT(*) FROM sales_invoice WHERE payment_status IS NULL OR payment_status NOT IN ('paid','fully_paid')");
  6035.             $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'))");
  6036.             $totalInvoiceAmt = (float)$conn->fetchOne("SELECT COALESCE(SUM(CAST(invoice_amount AS DECIMAL(15,2))), 0) FROM sales_invoice");
  6037.         } catch (\Exception $e) {
  6038.         }
  6039.         // ── Recent activity ───────────────────────────────────────────────────
  6040.         $recentActivity = [];
  6041.         try {
  6042.             $rows $conn->fetchAllAssociative("
  6043.                 SELECT action_type AS action, route AS description, created_at AS at
  6044.                 FROM user_activity_logs
  6045.                 ORDER BY created_at DESC
  6046.                 LIMIT 10
  6047.             ");
  6048.             foreach ($rows as $row) {
  6049.                 $recentActivity[] = [
  6050.                     'action' => $row['action'] ?? 'activity',
  6051.                     'description' => $row['description'] ?? '',
  6052.                     'at' => $row['at'] ?? '',
  6053.                 ];
  6054.             }
  6055.         } catch (\Exception $e) {
  6056.         }
  6057.         return new JsonResponse([
  6058.             'success' => true,
  6059.             'fetched_at' => (new \DateTime())->format('c'),
  6060.             'financials' => [
  6061.                 'revenue_this_month' => $revenueThisMonth,
  6062.                 'revenue_last_month' => $revenueLast,
  6063.                 'expenses_this_month' => $expensesThisMonth,
  6064.                 'profit_this_month' => $profitThisMonth,
  6065.                 'outstanding_receivables' => $receivables,
  6066.                 'outstanding_payables' => $payables,
  6067.                 'monthly_revenue_trend' => $monthlyTrend,
  6068.             ],
  6069.             'kpis' => [
  6070.                 'total_employees' => $totalEmployees,
  6071.                 'present_today' => $presentToday,
  6072.                 'attendance_rate_percent' => $attendancePct,
  6073.                 'tasks_total' => $tasksTotal,
  6074.                 'tasks_completed' => $tasksCompleted,
  6075.                 'tasks_overdue' => $tasksOverdue,
  6076.                 'task_completion_rate_percent' => $taskRate,
  6077.                 'open_sales_invoices' => $openInvoices,
  6078.                 'overdue_sales_invoices' => $overdueInvoices,
  6079.                 'total_sales_invoices_amount' => $totalInvoiceAmt,
  6080.             ],
  6081.             'alerts' => [],
  6082.             'recent_activity' => $recentActivity,
  6083.         ]);
  6084.     }
  6085.     // =========================================================================
  6086.     // CENTRAL SSO ENTRY POINT
  6087.     // The central server redirects the company owner here after generating an
  6088.     // SSO token. This action validates the token with the central server and
  6089.     // auto-logs the user in to the ERP.
  6090.     // =========================================================================
  6091.     public function CentralSsoAction(Request $request)
  6092.     {
  6093.         $token = (string)$request->query->get('token''');
  6094.         $returnUrl = (string)$request->query->get('returnUrl''');
  6095.         if ($token === '') {
  6096.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6097.                 'message' => 'Invalid SSO token.',
  6098.             ]);
  6099.         }
  6100.         // Ask the central server to validate the token
  6101.         $centralBase $this->container->hasParameter('central_server_url')
  6102.             ? rtrim($this->container->getParameter('central_server_url'), '/')
  6103.             : '';
  6104.         if ($centralBase === '') {
  6105.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6106.                 'message' => 'Central server URL not configured on this ERP instance.',
  6107.             ]);
  6108.         }
  6109.         $validateUrl $centralBase '/my/sso/validate';
  6110.         $body http_build_query(['token' => $token]);
  6111.         $curl curl_init();
  6112.         curl_setopt_array($curl, [
  6113.             CURLOPT_RETURNTRANSFER => true,
  6114.             CURLOPT_POST => true,
  6115.             CURLOPT_URL => $validateUrl,
  6116.             CURLOPT_CONNECTTIMEOUT => 8,
  6117.             CURLOPT_TIMEOUT => 8,
  6118.             CURLOPT_SSL_VERIFYPEER => false,
  6119.             CURLOPT_SSL_VERIFYHOST => false,
  6120.             CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
  6121.             CURLOPT_POSTFIELDS => $body,
  6122.         ]);
  6123.         $raw curl_exec($curl);
  6124.         curl_close($curl);
  6125.         if (!$raw) {
  6126.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6127.                 'message' => 'Could not reach the central server for SSO validation.',
  6128.             ]);
  6129.         }
  6130.         $payload json_decode($rawtrue);
  6131.         if (!is_array($payload) || empty($payload['success'])) {
  6132.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6133.                 'message' => 'SSO token is invalid or has expired. Please try again.',
  6134.             ]);
  6135.         }
  6136.         $email = (string)($payload['email'] ?? '');
  6137.         if ($email === '') {
  6138.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6139.                 'message' => 'No email returned from SSO validation.',
  6140.             ]);
  6141.         }
  6142.         // Find the local user by email
  6143.         $em $this->getDoctrine()->getManager();
  6144.         $conn $em->getConnection();
  6145.         $userRow null;
  6146.         try {
  6147.             $userRow $conn->fetchAssociative(
  6148.                 "SELECT * FROM sys_user WHERE email = :email AND status = 1 LIMIT 1",
  6149.                 ['email' => $email]
  6150.             );
  6151.         } catch (\Exception $e) {
  6152.         }
  6153.         if (!$userRow) {
  6154.             return $this->render('@Application/pages/error/generic_error.html.twig', [
  6155.                 'message' => 'No matching active user found in this ERP for email: ' htmlspecialchars($email),
  6156.             ]);
  6157.         }
  6158.         // Auto-login: populate session exactly as the normal login flow does
  6159.         $session $request->getSession();
  6160.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_ID$userRow['user_id'] ?? $userRow['id'] ?? 0);
  6161.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_NAME$userRow['name'] ?? $payload['name'] ?? '');
  6162.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_TYPE$userRow['user_type'] ?? 0);
  6163.         $session->set(\ApplicationBundle\Modules\Authentication\Constants\UserConstants::USER_COMPANY_ID$userRow['user_company_id'] ?? $userRow['company_id'] ?? 0);
  6164.         // Redirect to ERP dashboard or the requested returnUrl
  6165.         if ($returnUrl !== '' && strpos($returnUrl'http') === 0) {
  6166.             return $this->redirect($returnUrl);
  6167.         }
  6168.         return $this->redirectToRoute('central_landing');
  6169.     }
  6170. }