src/ApplicationBundle/Controller/ApplicationManagementController.php line 4097

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