src/Model/OrganizationModel.php line 1211

Open in your IDE?
  1. <?php
  2. namespace App\Model;
  3. use Pimcore\Model\DataObject\Customer;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Pimcore\Model\DataObject;
  6. use App\Model\InvitationModel;
  7. use App\Model\UserModel;
  8. use App\Model\PackageModel;
  9. use App\Model\LocationModel;
  10. use App\Service\UserPermission;
  11. use Pimcore\Model\DataObject\UserRole;
  12. use Pimcore\Model\DataObject\UserTag;
  13. use Carbon\Carbon;
  14. use Psr\Log\LoggerInterface;
  15. use Doctrine\DBAL\Connection;
  16. use App\Service\NCMCRMIntegrationService;
  17. use App\Model\ReportingPortalModel;
  18. use App\Model\WeatherParameterModel;
  19. use App\Model\EwsPortalModel;
  20. use Pimcore\Model\DataObject\Organization;
  21. use Pimcore\Model\DataObject\PermissionGroup;
  22. class OrganizationModel
  23. {
  24.     public $userModel;
  25.     public $invitationModel;
  26.     public $organizationModel;
  27.     public $locationModel;
  28.     private $userPermission;
  29.     private $crmService;
  30.     private $reportingPortalModel;
  31.     private $ewsPortalModel;
  32.     private $parameterModel;
  33.     private $connection;
  34.     function __construct()
  35.     {
  36.         $this->userModel = new UserModel();
  37.         $this->invitationModel = new InvitationModel();
  38.         $this->locationModel  = new LocationModel();
  39.         $this->userPermission  = new UserPermission();
  40.         $this->crmService = new NCMCRMIntegrationService();
  41.         $this->reportingPortalModel = new ReportingPortalModel();
  42.         $this->ewsPortalModel = new EwsPortalModel();
  43.         $this->parameterModel = new WeatherParameterModel();
  44.     }
  45.     /**
  46.      * Create organization
  47.      * 
  48.      */
  49.     public function createOrganization($request$params$loggedInUser$translator): array
  50.     {
  51.         try {
  52.             $listing = new Organization\Listing();
  53.             $listing->setUnpublished(true); // Include unpublished
  54.             $listing->setOrderKey('o_id');
  55.             $listing->setOrder('DESC');
  56.             $listing->setLimit(1);
  57.             $last $listing->current();
  58.             $nextNumber 1;
  59.             if ($last instanceof Organization) {
  60.                 $lastId $last->getUniqueId(); // e.g. NCM-ENT-00023
  61.                 if (preg_match('/NCM-ENT-(\d+)/'$lastId$matches)) {
  62.                     $nextNumber = (int)$matches[1] + 1;
  63.                 }
  64.             }
  65.             // Format: NCM-ENT-00001
  66.             $newUniqueId 'NCM-ENT-' str_pad($nextNumber5'0'STR_PAD_LEFT);
  67.             $result = [];
  68.             $orgName trim(strip_tags($params['name']));
  69.             $orgNameAr trim(strip_tags($params['nameAr']));
  70.             $email trim($params['email']);
  71.             $orgCode trim(strip_tags($params['code']));
  72.             //$logo = trim(strip_tags($params['logo']));
  73.             $clientType trim(strip_tags($params['client_type']));
  74.             $organization = new DataObject\Organization();
  75.             $organization->setParent(DataObject\Service::createFolderByPath('/UserManagement/Organization'));
  76.             $organization->setKey($orgName);
  77.             $organization->setName($orgName'en');
  78.             $organization->setName($orgNameAr'ar');
  79.             $organization->setCode($orgCode);
  80.             $organization->setEmail($email);
  81.             //$organization->setImage($this->createAssetByURL($logo));
  82.             $organization->setCilent_type($clientType);
  83.             $organization->setClientType($clientType);
  84.             $organization->setStatus($params['entityStatus']);
  85.             $organization->setTrialLimit($params['trialLimit']);
  86.             $organization->setPackageActivationDate(Carbon::now());
  87.             $organization->setPackage($params['package'] ?? null);
  88.             $organization->setIsActive(true);
  89.             $organization->setCreatedBy($loggedInUser);
  90.             $organization->setPublished(true);
  91.             $organization->setUniqueId($newUniqueId);
  92.             $organization->save();
  93.             return ["success" => true"message" => $translator->trans("organization_created_successifully"), 'data' => $organization];
  94.         } catch (\Exception $ex) {
  95.             return ["success" => false"message" => $ex->getMessage()];
  96.         }
  97.         return $result;
  98.     }
  99.     /**
  100.      * Create Entity
  101.      * 
  102.      */
  103.     public function createEntity($request$params$user$translator): array
  104.     {
  105.         $package  DataObject\Package::getById($params['packageId'], true);
  106.         if (!$package instanceof DataObject\Package) {
  107.             return ["success" => false"message" => $translator->trans("package_not_found")];
  108.         }
  109.         $entity DataObject\Organization::getByName($params['name'], 'en', ['limit' => 1'unpublished' => true]);
  110.         if ($entity instanceof DataObject\Organization) {
  111.             return ["success" => false"message" => $translator->trans("entity_already_exists") . " : " $params['name']];
  112.         }
  113.         $createNameEn trim(strip_tags($params['name']));
  114.         $createNameAr = isset($params['nameAr']) ? trim(strip_tags($params['nameAr'])) : $createNameEn;
  115.         $orgCode = isset($params['code']) ? trim(strip_tags($params['code'])) : $params['name'];
  116.         $clientType trim(strip_tags($params['clientType']));
  117.         $listing = new Organization\Listing();
  118.         $listing->setUnpublished(true); // Include unpublished
  119.         $listing->setOrderKey('o_id');
  120.         $listing->setOrder('DESC');
  121.         $listing->setLimit(1);
  122.         $last $listing->current();
  123.         $nextNumber 1;
  124.         if ($last instanceof Organization) {
  125.             $lastId $last->getUniqueId(); // e.g. NCM-ENT-00023
  126.             if (preg_match('/NCM-ENT-(\d+)/'$lastId$matches)) {
  127.                 $nextNumber = (int)$matches[1] + 1;
  128.             }
  129.         }
  130.         // Format: NCM-ENT-00001
  131.         $newUniqueId 'NCM-ENT-' str_pad($nextNumber5'0'STR_PAD_LEFT);
  132.         // $result = $this->reportingPortalModel->createOrganization([
  133.         //     'name' => $params['name'],
  134.         //     'nameAr' => $params['nameAr'],
  135.         //     'code' => isset($params['code']) ? $params['code'] : null,
  136.         //     'packageName' => $package->getPackageName('en'),
  137.         //     'clientType' => $params['clientType'],
  138.         //     'trialLimit' => isset($params['trialLimit']) ? $params['trialLimit'] : null,
  139.         //     'status' => isset($params['status']) ? $params['status'] : null,
  140.         //     'userEmail' => $user->getEmail(),
  141.         //     'uniqueId' => $newUniqueId,
  142.         // ]);
  143.         $entity = new DataObject\Organization();
  144.         $entity->setParent(DataObject\Service::createFolderByPath('/UserManagement/Organization'));
  145.         $entity->setKey($createNameEn);
  146.         $entity->setName($createNameEn'en');
  147.         $entity->setName($createNameAr'ar');
  148.         $entity->setCode($orgCode);
  149.         $entity->setClientType($clientType);
  150.         $entity->setPackage($package);
  151.         if (isset($params['entityStatus']) && !empty($params['entityStatus'])) {
  152.             $entity->setStatus($params['entityStatus']);
  153.             if (!isset($params['trialLimit']) || empty($params['trialLimit'])) {
  154.                 if ($params['entityStatus'] === 'trial') {
  155.                     return ["success" => false"message" => $translator->trans("trial_limit_is_required")];
  156.                 } else {
  157.                     return ["success" => false"message" => $translator->trans("tenure_is_required")];
  158.                 }
  159.             }
  160.             $entity->setTrialLimit($params['trialLimit']);
  161.         } else {
  162.             // When entityStatus is not sent, set trial limit
  163.             if (!isset($params['trialLimit']) || empty($params['trialLimit'])) {
  164.                 return ["success" => false"message" => $translator->trans("tenure_is_required")];
  165.             }
  166.             $entity->setTrialLimit($params['trialLimit']);
  167.         }
  168.         $entityTag  DataObject\UserTag::getById($params['tagId'], true);
  169.         if (isset($params['tagId']) && !empty($params['tagId'])) {
  170.             $entity->setTag($entityTag);
  171.         }
  172.         $entity->setPackageActivationDate(Carbon::parse($params['startDate']));
  173.         $entity->setPublished(true);
  174.         $entity->setIsActive(false);
  175.         $entity->setCreatedBy($user);
  176.         $entity->setUniqueId($newUniqueId);
  177.         $entity->save();
  178.         return ["success" => true"message" => $translator->trans("entity_created")];
  179.     }
  180.     /**
  181.      * Edit organization
  182.      * 
  183.      */
  184.     public function editOrganization($request$params$packageModel$translator): array
  185.     {
  186.         $updateOrganization DataObject\Organization::getById($params['id'], true);
  187.         // $result = $this->reportingPortalModel->editOrganization([
  188.         //     'name' => $params['name'],
  189.         //     'nameAr' => $params['nameAr'],
  190.         //     'code' => isset($params['code']) ? $params['code'] : null,
  191.         //     'clientType' => isset($params['clientType']) ? $params['clientType'] : null,
  192.         //     'trialLimit' => isset($params['trialLimit']) ? $params['trialLimit'] : null,
  193.         //     'status' => isset($params['status']) ? $params['status'] : null,
  194.         //     'country' => isset($params['country']) ? $params['country'] : null,
  195.         //     'state' => isset($params['state']) ? $params['state'] : null,
  196.         //     'phone' => isset($params['phone']) ? $params['phone'] : null,
  197.         //     'packageId' => isset($params['packageId']) ? $params['packageId'] : null,
  198.         //     'uniqueId' => $updateOrganization->getUniqueId(),
  199.         // ]);
  200.         if ($updateOrganization) {
  201.             if (isset($params['name']) && !empty($params['name'])) {
  202.                 // Check if the name already exists for another organization
  203.                 $existingOrganization DataObject\Organization::getByName($params['name'], 'en', ['limit' => 1'unpublished' => true]);
  204.                 if ($existingOrganization && $existingOrganization->getId() !== $updateOrganization->getId()) {
  205.                     return ["success" => false"message" => $translator->trans("entity_already_exists") . " : " $params['name']];
  206.                 }
  207.                 $updateOrganization->setName(trim(strip_tags($params['name'])), 'en');
  208.                 $updateOrganization->setKey(trim(strip_tags($params['name']))); // Update key to match new name
  209.             }
  210.             if (isset($params['nameAr']) && !empty($params['nameAr'])) {
  211.                 $updateOrganization->setName(trim(strip_tags($params['nameAr'])), 'ar');
  212.             }
  213.             // if (isset($params['email']) && !empty($params['email'])) {
  214.             //     $updateOrganization->setEmail(trim(strip_tags($params['email'])));
  215.             // }
  216.             if (isset($params['clientType']) && !empty($params['clientType'])) {
  217.                 $updateOrganization->setClientType(trim(strip_tags($params['clientType'])));
  218.             }
  219.             if (isset($params['isActive']) && !empty($params['isActive'])) {
  220.                 $updateOrganization->setIsActive($params['isActive']);
  221.             }
  222.             if (isset($params['startDate']) && !empty($params['startDate'])) {
  223.                 $updateOrganization->setPackageActivationDate(Carbon::parse($params['startDate']));
  224.             }
  225.             if (isset($params['entityStatus']) && !empty($params['entityStatus'])) {
  226.                 $updateOrganization->setStatus($params['entityStatus']);
  227.                 if (!isset($params['trialLimit']) || empty($params['trialLimit'])) {
  228.                     if ($params['entityStatus'] === 'trial') {
  229.                         return ["success" => false"message" => $translator->trans("trial_limit_is_required")];
  230.                     } else {
  231.                         return ["success" => false"message" => $translator->trans("tenure_is_required")];
  232.                     }
  233.                 }
  234.                 $updateOrganization->setTrialLimit($params['trialLimit']);
  235.             } else {
  236.                 if (!isset($params['trialLimit']) || empty($params['trialLimit'])) {
  237.                     return ["success" => false"message" => $translator->trans("tenure_is_required")];
  238.                 }
  239.                 $updateOrganization->setTrialLimit($params['trialLimit']);
  240.             }
  241.             if (isset($params['isSMSEnabled']) && !empty($params['isSMSEnabled'])) {
  242.                 $updateOrganization->setIsSMSEnabled($params['isSMSEnabled']);
  243.             }
  244.             if (isset($params['code']) && !empty($params['code'])) {
  245.                 $updateOrganization->setCode(trim(strip_tags($params['code'])));
  246.             }
  247.             if (isset($params['country']) && !empty($params['country'])) {
  248.                 $updateOrganization->setCountry(trim(strip_tags($params['country'])));
  249.             }
  250.             if (isset($params['state']) && !empty($params['state'])) {
  251.                 $updateOrganization->setState(trim(strip_tags($params['state'])));
  252.             }
  253.             if (isset($params['phone']) && !empty($params['phone'])) {
  254.                 $updateOrganization->setPhone(trim(strip_tags($params['phone'])));
  255.             }
  256.             if (isset($params['packageId']) && !empty($params['packageId'])) {
  257.                 $package DataObject\Package::getById($params['packageId'], true);
  258.                 if ($package instanceof DataObject\Package) {
  259.                     $packageModel->updateEntityPackage($package$updateOrganization$translator);
  260.                 }
  261.             }
  262.             if (isset($params['tagId']) && !empty($params['tagId'])) {
  263.                 $entityTag  DataObject\UserTag::getById($params['tagId'], true);
  264.                 $updateOrganization->setTag($entityTag);
  265.             } else {
  266.                 $updateOrganization->setTag(null);
  267.             }
  268.             // if (isset($params['logo']) && !empty($params['logo'])) {
  269.             //     $updateOrganization->setImage($this->createAssetByURL($params['logo']));
  270.             // }
  271.             $updateOrganization->save();
  272.             return ["success" => true"message" => $translator->trans("organization_updated_successifully")];
  273.         }
  274.         return ["success" => false"message" => $translator->trans("organization_does_not_exists")];
  275.     }
  276.     /**
  277.      * List organization
  278.      * 
  279.      */
  280.     public function listOrganizations($request$params$translator$paginator): array
  281.     {
  282.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  283.         $page = isset($params['page']) ? $params['page'] : 1;
  284.         $organizations = new DataObject\Organization\Listing();
  285.         $organizations->addConditionParam("isInternal IS NULL OR isInternal = 0"); // Exclude internal organizations
  286.         if (isset($params['isArchived']) && !empty($params['isArchived'] && $params['isArchived'] == true)) {
  287.             $organizations->setUnpublished(true); // Include unpublished
  288.             $organizations->addConditionParam("o_published = 0"); // Filter only unpublished
  289.             $organizations->addConditionParam("isDeleted = 1"); // Filter only deleted
  290.         }
  291.         if (isset($params['search']) && !empty($params['search'])) {
  292.             $organizations->addConditionParam("name LIKE " $organizations->quote("%" $params['search'] . "%"));
  293.         }
  294.         if (isset($params['packageId']) && !empty($params['packageId'])) {
  295.             $organizations->addConditionParam("package__id =?", [$params['packageId']]);
  296.         }
  297.         if (isset($params['clientType']) && !empty($params['clientType'])) {
  298.             $organizations->filterByClientType($params['clientType']);
  299.         }
  300.         if (isset($params['isActive'])) {
  301.             $organizations->filterByIsActive($params['isActive']);
  302.         }
  303.         if (isset($params['status']) && !empty($params['status'])) {
  304.             $organizations->filterByStatus($params['status']);
  305.         }
  306.         if (isset($params['isSMSEnabled'])) {
  307.             $organizations->filterByIsSMSEnabled($params['isSMSEnabled'] ?? false);
  308.         }
  309.         if (isset($params['tagId'])) {
  310.             $tag DataObject\UserTag::getById($params['tagId']);
  311.             if ($tag) {
  312.                 $organizations->filterByTag($tag);
  313.             }
  314.         }
  315.         //get by customer name
  316.         if (isset($params['username'])) {
  317.             $organizations->addConditionParam("createdBy__id IN (SELECT u.oo_id FROM object_query_customer u WHERE u.name LIKE ?)", ['%' $params['username'] . '%']);
  318.         }
  319.         $orderKeyArray = ["clientType""o_creationDate""isSMSEnabled""isActive""name""packageExpiry""totalAdmins""totalUsers""createdBy"];
  320.         $orderArray = ["asc""desc"];
  321.         if (isset($params["orderKey"], $params["order"]) && in_array($params["orderKey"], $orderKeyArray) && in_array(strtolower($params["order"]), $orderArray)) {
  322.             if ($params["orderKey"] === "packageExpiry") {
  323.                 $sqlExpression "CASE 
  324.                     WHEN packageActivationDate IS NULL OR trialLimit IS NULL OR trialLimit <= 0 THEN NULL
  325.                     WHEN packageActivationDate REGEXP '^[0-9]+$' THEN 
  326.                         DATE_ADD(FROM_UNIXTIME(packageActivationDate), INTERVAL trialLimit DAY)
  327.                     ELSE 
  328.                         DATE_ADD(packageActivationDate, INTERVAL trialLimit DAY)
  329.                 END";
  330.                 $organizations->setOrderKey($sqlExpressionfalse);
  331.                 $organizations->setOrder($params["order"]);
  332.             } elseif ($params["orderKey"] === "totalAdmins") {
  333.                 // Order by total client admins per organization using a correlated subquery
  334.                 $clientAdminRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_ADMIN'], true);
  335.                 $clientAdminRoleId $clientAdminRole instanceof DataObject\UserRole ? (int)$clientAdminRole->getId() : 0;
  336.                 // Use the correct table reference for the outer query when localized tables are used
  337.                 $organizations->setOrderKey("
  338.                 (SELECT COUNT(*) 
  339.                  FROM object_customer c 
  340.                  WHERE c.organization__id = object_localized_organization_en.o_id AND c.role__id = {$clientAdminRoleId})
  341.             "false);
  342.                 $organizations->setOrder($params["order"]);
  343.             } elseif (($params["orderKey"] === "totalUsers")) {
  344.                 // Order by total client users per organization using a correlated subquery
  345.                 $clientUserRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_USER'], true);
  346.                 $clientUserRoleId $clientUserRole instanceof DataObject\UserRole ? (int)$clientUserRole->getId() : 0;
  347.                 // Use the correct table reference for the outer query when localized tables are used
  348.                 $organizations->setOrderKey("
  349.                 (SELECT COUNT(*) 
  350.                  FROM object_customer c 
  351.                  WHERE c.organization__id = object_localized_organization_en.o_id AND c.role__id = {$clientUserRoleId})
  352.             "false);
  353.                 $organizations->setOrder($params["order"]);
  354.             } elseif (($params["orderKey"] === "createdBy")) {
  355.                 $organizations->setOrderKey("
  356.             COALESCE(
  357.             (SELECT c.name
  358.              FROM object_customer c
  359.              WHERE c.oo_id = (
  360.                  SELECT o.createdBy__id
  361.                  FROM object_organization o
  362.                  WHERE o.o_id = object_localized_organization_en.o_id
  363.                  LIMIT 1
  364.              )
  365.              LIMIT 1),
  366.             ''
  367.             )
  368.             "false);
  369.                 $organizations->setOrder($params["order"]);
  370.             } else {
  371.                 $organizations->setOrderKey($params["orderKey"]);
  372.                 $organizations->setOrder($params["order"]);
  373.             }
  374.         }else{
  375.              $organizations->setOrderKey("o_creationDate");
  376.             $organizations->setOrder("desc");
  377.         }
  378.         $paginator $paginator->paginate(
  379.             $organizations,
  380.             $page,
  381.             $pageSize
  382.         );
  383.         $organizationsListData = [];
  384.         foreach ($paginator as $organization) {
  385.             $packageData = [];
  386.             $trialLeftDays null;
  387.             if ($organization instanceof DataObject\Organization) {
  388.                 if ($organization->getPackage() instanceof DataObject\Package) {
  389.                     $packageData = [
  390.                         "id" => $organization->getPackage()->getId(),
  391.                         "nameEn" => $organization->getPackage()->getPackageName("en"),
  392.                         "nameAr" => $organization->getPackage()->getPackageName("ar"),
  393.                         "packageExpiry" => $this->calculatePackageExpiry($organization)
  394.                     ];
  395.                 }
  396.                 // if ($organization->getIsActive()) {
  397.                 $trialLeftDays =   \App\Lib\Utility::getTrialLeftDays($organization->getPackageActivationDate(), $organization->getTrialLimit());
  398.                 // }
  399.                 $clientType $organization $organization->getClientType() : '';
  400.                 $entityTypeArray = [
  401.                     "key" => $clientType,
  402.                     'nameEn' => $clientType === 'organization' 'Entity' : ($clientType $translator->trans($clientType, [], null'en') : ''),
  403.                     'nameAr' => $clientType === 'organization' 'الجهة' : ($clientType $translator->trans($clientType, [], null'ar') : ''),
  404.                 ];
  405.                 $organizationsListData[] = [
  406.                     "id" => $organization->getId(),
  407.                     "nameEn" => $organization->getName("en"),
  408.                     "nameAr" => $organization->getName("ar"),
  409.                     "code" => $organization->getCode(),
  410.                     "city" => $organization->getCity(),
  411.                     "state" => $organization->getState(), // Province or Region
  412.                     "zip" => $organization->getZip(),
  413.                     "email" => $organization->getEmail(),
  414.                     "country" => $organization->getCountry(),
  415.                     "isActive" => !$organization->getIsSuspend() && $organization->getIsActive(),
  416.                     "isSuspended" => $organization->getIsSuspend() ? true false,
  417.                     "assignedPackage" => $packageData,
  418.                     "createdAt" => (new \DateTime())->setTimestamp($organization->getCreationDate())->format('Y-m-d H:i:s'),
  419.                     "updatedAt" => (new \DateTime())->setTimestamp($organization->getModificationDate())->format('Y-m-d H:i:s'),
  420.                     "adminUserCount" => $this->getUserCountByEntity($organizationUSER_ROLES['CLIENT_ADMIN']),
  421.                     "userCount" => $this->getUserCountByEntity($organizationUSER_ROLES['CLIENT_USER']),
  422.                     "status" => $organization->getStatus(),
  423.                     "isSMSEnabled" => $organization->getIsSMSEnabled() ? true false,
  424.                     "entityType" => $entityTypeArray,
  425.                     'trialLeftDays' =>  $organization->getTrialLimit() ? $organization->getTrialLimit() : null,
  426.                     "smsConsumption" => $organization->getSmsConsumption(),
  427.                     "SMSLimit" => $organization->getSmsLimit(),
  428.                     "createdBy" => $organization->getCreatedBy() ? $organization->getCreatedBy()->getName() : null,
  429.                     "startDate" => $organization->getPackageActivationDate() ? (new \DateTime($organization->getPackageActivationDate()))->setTimezone(new \DateTimeZone('Asia/Riyadh'))->format('Y-m-d') : null,
  430.                     "tag" => $organization->getTag() ? [
  431.                         "id" => $organization->getTag()->getId(),
  432.                         "name" => $organization->getTag()->getName()
  433.                     ] : null,
  434.                     "endDate" => $organization->getPackageActivationDate() && isset($trialLeftDays)
  435.                         ? (clone (new \DateTime($organization->getPackageActivationDate())))
  436.                         ->add(new \DateInterval('P' . (int)$organization->getTrialLimit() . 'D'))
  437.                         ->setTimezone(new \DateTimeZone('Asia/Riyadh'))
  438.                         ->format('Y-m-d')
  439.                         : null,
  440.                 ];
  441.             }
  442.         }
  443.         return ["success" => true"data" => $organizationsListData'paginationVariables' => $paginator->getPaginationData()];
  444.     }
  445.     private function getUserCountByEntity($organization$roleName null)
  446.     {
  447.         // force to return all objects including unpublished ones, even if setUnpublished is set to false
  448.         \Pimcore\Model\DataObject::setHideUnpublished(false);
  449.         $customers = new Customer\Listing();
  450.         $customers->filterByOrganization($organization);
  451.         if ($roleName) {
  452.             $role DataObject\UserRole::getByName($roleNametrue);
  453.             $customers->filterByRole($role);
  454.         }
  455.         return $customers->getCount();
  456.     }
  457.     /**
  458.      * Delete organization
  459.      * 
  460.      */
  461.     public function deleteOrganization($user$params$translator): array
  462.     {
  463.         $ids is_array($params['id']) ? $params['id'] : [$params['id']];
  464.         $results = [];
  465.         foreach ($ids as $orgId) {
  466.             $entity DataObject\Organization::getById($orgIdtrue);
  467.             if ($entity) {
  468.                 // $result = $this->reportingPortalModel->deleteOrganization([
  469.                 //     'uniqueId' => $entity->getUniqueId(),
  470.                 //     'userEmail' => $user->getEmail(),
  471.                 // ]);
  472.                 if ($this->getUserCountByEntity($entity) === 0) {
  473.                     $entity->setIsDeleted(true); // Custom field
  474.                     $entity->setDeletedBy($user);
  475.                     $entity->setDeletedAt(Carbon::now());
  476.                     $entity->setPublished(false);
  477.                     $entity->save();
  478.                     $results[] = ["id" => $orgId"success" => true"message" => $translator->trans("organization_deleted_successifully")];
  479.                 } else {
  480.                     $results[] = ["id" => $orgId"success" => false"message" => $translator->trans("organization_has_users")];
  481.                 }
  482.             } else {
  483.                 $results[] = ["id" => $orgId"success" => false"message" => $translator->trans("organization_does_not_exists")];
  484.             }
  485.         }
  486.         if (!is_array($params['id'])) {
  487.             $single $results[0] ?? ["success" => false"message" => $translator->trans("unknown_error")];
  488.             return ["success" => $single["success"], "message" => $single["message"]];
  489.         }
  490.         $successCount 0;
  491.         $failedCount 0;
  492.         $failedItems = [];
  493.         foreach ($results as $r) {
  494.             if (!empty($r['success'])) {
  495.                 $successCount++;
  496.             } else {
  497.                 $failedCount++;
  498.                 $failedItems[] = [
  499.                     'id' => $r['id'],
  500.                     'reason' => $r['message']
  501.                 ];
  502.             }
  503.         }
  504.         $message sprintf("%s: %d"$translator->trans("organization_deleted_successifully"), $successCount);
  505.         if ($failedCount 0) {
  506.             $message .= sprintf(", %s: %d"$translator->trans("failed"), $failedCount);
  507.         }
  508.         return [
  509.             "success" => true,
  510.             "message" => $message,
  511.             "processed" => $successCount,
  512.             "failed" => $failedCount,
  513.             "failedItems" => $failedItems
  514.         ];
  515.     }
  516.     /**
  517.      * Retrieve organization
  518.      * 
  519.      */
  520.     public function retrieveOrganization($user$params$translator): array
  521.     {
  522.         $entity DataObject\Organization::getById($params['id'], true);
  523.         if ($entity) {
  524.             $entity->setIsDeleted(false); // Custom field
  525.             $entity->setDeletedBy(null);
  526.             $entity->setDeletedAt(null);
  527.             $entity->setPublished(true);
  528.             $entity->save();
  529.             return ["success" => true"message" => $translator->trans("organization_retrieved_successifully")];
  530.         }
  531.         return ["success" => false"message" => $translator->trans("organization_does_not_exists")];
  532.     }
  533.     /**
  534.      * Send invite to NCM users
  535.      * 
  536.      */
  537.     public function adminInviteNCMUser($request$translator$email,  $fullName$role$userTagId$hostName$loggedInUser$allowedApiGroups$permissionUserGroupIds$templating$isNoExpiry false$phone null): array
  538.     {
  539.         $result = [];
  540.         // try {
  541.         $user  DataObject\Customer::getByEmail($email, ['limit' => 1'unpublished' => true]);
  542.         if ($user instanceof DataObject\Customer) {
  543.             if ($user->getRole()->getName() ==  USER_ROLES['CLIENT_ADMIN'] || $user->getRole()->getName() == USER_ROLES['CLIENT_USER']) {
  544.                 return ["success" => false"message" => $translator->trans("user_already_exists_in_external_user")];
  545.             } else {
  546.                 return ["success" => false"message" => $translator->trans("user_already_exists")];
  547.             }
  548.         }
  549.         $organization $loggedInUser->getOrganization();
  550.         if ($organization instanceof DataObject\Organization) {
  551.             // Register user if not exists
  552.             if ($loggedInUser->getRole()->getName() == USER_ROLES['NCM_OPERATOR'] && $role == USER_ROLES['NCM_IT']) {
  553.                 return ["success" => false"message" => $translator->trans("NCM_OPERATOR_can_not_invite_NCM_IT.")];
  554.             }
  555.             if ($loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN'] || $loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_USER']) {
  556.                 return ["success" => false"message" => $translator->trans(USER_ROLES[$loggedInUser->getRole()->getName()] . "_can_not_invite_" USER_ROLES[$role])];
  557.             }
  558.             $userRole DataObject\UserRole::getByName(USER_ROLES[$role], true);
  559.             if ($userRole instanceof DataObject\UserRole) {
  560.                 $package  $userRole->getCustomPackage();
  561.                 if (!$package instanceof DataObject\Package) {
  562.                     return ["success" => false"message" => $translator->trans("package_not_found")];
  563.                 }
  564.                 // // check package user limit
  565.                 // $subscriptionList = new DataObject\Subscription\Listing();
  566.                 // $subscriptionList->filterBySubscribedUser($loggedInUser);
  567.                 // // $subscriptionList->filterBySubscriptionType("custom");
  568.                 // $subscriptionList->filterByIsActive(true);
  569.                 // $subscriptionList->load();
  570.                 // $customerList = new DataObject\Customer\Listing();
  571.                 // $customerList->filterByOrganization($organization);
  572.                 // $customerList->setUnpublished(1);
  573.                 // $totalcustomer = $customerList->count();
  574.                 // $maxUser = 0;
  575.                 // foreach ($subscriptionList as $subscription) {
  576.                 //     $loggedInUserPackage = $subscription->getSubscribedPackage();
  577.                 //     if ($loggedInUserPackage instanceof DataObject\Package) {
  578.                 //         if ($loggedInUserPackage->getMaxUsers()) {
  579.                 //             $maxUser += (int) $loggedInUserPackage->getMaxUsers();
  580.                 //         }
  581.                 //     }
  582.                 // }
  583.                 // if ($totalcustomer >= $maxUser) {
  584.                 //     return ["success" => false, "message" => $translator->trans("invite_user_limit_exceeded_for_this_organization")];
  585.                 // }
  586.                 // // check package user limit
  587.                 $params = [
  588.                     'email' => $email,
  589.                     'organization' => $organization,
  590.                     'name' => $fullName,
  591.                     'groupId' => null,
  592.                     'createdBy' => $loggedInUser,
  593.                     'isNoExpiry' => $isNoExpiry,
  594.                     'phone' => $phone,
  595.                     'permissionUserGroupIds' => $permissionUserGroupIds
  596.                 ];
  597.                 $userResponse $this->createUser($userRole$params$translator);
  598.                 if ($userResponse['success'] == true) {
  599.                     $user $userResponse['data'];
  600.                     // assign user tag to user
  601.                     if (isset($userTagId) && !empty($userTagId)) {
  602.                         $tage  UserTag::getById($userTagId);
  603.                         if ($tage instanceof UserTag) {
  604.                             $user->setTag($tage);
  605.                             $user->save();
  606.                         }
  607.                     }
  608.                     // Send invite
  609.                     $permission = [];
  610.                     $params = [
  611.                         'user' => $user,
  612.                         'email' => $user->getEmail(),
  613.                         'userName' => $user->getName(),
  614.                         'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  615.                         'url' => $hostName $userResponse['token'],
  616.                         'clientType' => "NCM_admin",
  617.                         'inviteSenderName' => $loggedInUser->getName(),
  618.                         'permissions' => $permission,
  619.                         'subject' => "Invitation to Join Admin Portal as NCM Admin",
  620.                         'hostPath' => $request->getSchemeAndHttpHost(),
  621.                         'resend' => false,
  622.                     ];
  623.                     $inviteResponse $this->invitationModel->sendInvite($params$translator$templating);
  624.                     return $inviteResponse;
  625.                     // $ncmUserSubscription = $this->userModel->setNcmUserSubscription($userRole, $user, $allowedApiGroups, $isNoExpiry);
  626.                     // if ($ncmUserSubscription instanceof DataObject\Subscription) {
  627.                     //     // Send invite
  628.                     //     $permission = [];
  629.                     //     $params = [
  630.                     //         'user' => $user,
  631.                     //         'email' => $user->getEmail(),
  632.                     //         'userName' => $user->getName(),
  633.                     //         'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  634.                     //         'url' => $hostName . $userResponse['token'],
  635.                     //         'clientType' => "NCM_admin",
  636.                     //         'inviteSenderName' => $loggedInUser->getName(),
  637.                     //         'permissions' => $permission,
  638.                     //         'subject' => "Invitation to Join Admin Portal as NCM Admin",
  639.                     //         'hostPath' => $request->getSchemeAndHttpHost(),
  640.                     //         'resend' => false,
  641.                     //     ];
  642.                     //     $inviteResponse = $this->invitationModel->sendInvite($params, $translator, $templating);
  643.                     //     return $inviteResponse;
  644.                     // } else {
  645.                     //     return ["success" => false, "message" => $translator->trans("user_subscription_not_created")];
  646.                     // }
  647.                 } else {
  648.                     return $userResponse;
  649.                 }
  650.             } else {
  651.                 return ["success" => false"message" => $translator->trans("user_role_not_found")];
  652.             }
  653.         } else {
  654.             return ["success" => false"message" =>   $translator->trans("no_organization_is_associated_with_logged_in_user")];
  655.         }
  656.         // } catch (\Exception $ex) {
  657.         //     $result = ["success" => false, "message" => $ex->getMessage()];
  658.         // }
  659.         return $result;
  660.     }
  661.     /**
  662.      * Send invite to Organization and Individual users
  663.      * 
  664.      */
  665.     public function adminInvite(
  666.         $request,
  667.         $translator,
  668.         $email,
  669.         $name,
  670.         $role,
  671.         $logo,
  672.         $clientType,
  673.         $companyNameEn,
  674.         $companyNameAR,
  675.         $locations,
  676.         $loggedInUser,
  677.         $hostName,
  678.         $department,
  679.         $title,
  680.         $groupId,
  681.         $packageId,
  682.         $organizationId,
  683.         $templating,
  684.         $phone,
  685.         $entityStatus,
  686.         $trialLimit
  687.     ): array {
  688.         $result = [];
  689.         // try {
  690.         $user  DataObject\Customer::getByEmail($email, ['limit' => 1'unpublished' => true]);
  691.         if ($user instanceof DataObject\Customer) {
  692.             if ($user->getRole()->getName() == USER_ROLES['NCM_OPERATOR'] || $user->getRole()->getName() == USER_ROLES['NCM_IT']) {
  693.                 return ["success" => false"message" => $translator->trans("user_already_exists_in_internal_user")];
  694.             } else {
  695.                 $data = ['email' => $email'name' => $name,  'role' => $role];
  696.                 return ["success" => false"message" => $translator->trans("user_already_exists"), 'data' => $data];
  697.             }
  698.         }
  699.         switch ($clientType) {
  700.             case 'organization':
  701.             case 'government':
  702.                 // Register organization if not exists
  703.                 $package  DataObject\Package::getById($packageIdtrue);
  704.                 if (!$package instanceof DataObject\Package) {
  705.                     return ["success" => false"message" => $translator->trans("package_not_found")];
  706.                 }
  707.                 // Check if the name already exists for another organization
  708.                 $organization DataObject\Organization::getByName($companyNameEn'en', ['limit' => 1'unpublished' => true]);
  709.                 if ($organization instanceof DataObject\Organization) {
  710.                     return ["success" => false"message" => $translator->trans("organization_already_exists") . " : " $companyNameEn];
  711.                 }
  712.                 // $organizationByEmail = DataObject\Organization::getByEmail($email, true);
  713.                 // if ($organizationByEmail instanceof DataObject\Organization) {
  714.                 //     return ["success" => false, "message" => sprintf($translator->trans("organization_already_created_with_this: %s"), $email)];
  715.                 // }
  716.                 $allowedStatuses = ['paid''trial''expired'];
  717.                 if (!in_array($entityStatus$allowedStatuses)) {
  718.                     return ["success" => false"message" => $translator->trans("undefined_entity_status")];
  719.                 }
  720.                 $params = [
  721.                     'name' => $companyNameEn,
  722.                     'nameAr' => $companyNameAR,
  723.                     'code' => $companyNameEn,
  724.                     'client_type' => $clientType,
  725.                     'email' => $email,
  726.                     'phone' => $phone,
  727.                     'entityStatus' => $entityStatus,
  728.                     'trialLimit' => $trialLimit,
  729.                     'package' => $package,
  730.                     // 'logo'=>$logo
  731.                 ];
  732.                 $organization $this->createOrganization($request$params$loggedInUser$translator);
  733.                 if (isset($organization['data']) && $organization['data'] instanceof DataObject\Organization) {
  734.                     // check role of user before inviting 
  735.                     if ($loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN'] && ($role == USER_ROLES['NCM_IT'] || $role == USER_ROLES['NCM_OPERATOR'])) {
  736.                         return ["success" => false"message" => $translator->trans("CLIENT_ADMIN_can_not_invite_NCM_IT_or_NCM_OPERATOR")];
  737.                     }
  738.                     if ($loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN']) {
  739.                         return ["success" => false"message" => $translator->trans("CLIENT_USER_can_not_invite")];
  740.                     }
  741.                     $userRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_ADMIN'], true);
  742.                     if (!$userRole instanceof UserRole) {
  743.                         return ["success" => false"message" => $translator->trans("User_Role_Not_Found")];
  744.                     }
  745.                     $params = [
  746.                         'email' => $email,
  747.                         'organization' => $organization['data'],
  748.                         'name' => $name,
  749.                         'groupId' => $groupId,
  750.                         'createdBy' => $loggedInUser,
  751.                         'phone' => $phone
  752.                     ];
  753.                     $userResponse $this->createUser($userRole$params$translator);
  754.                     if ($userResponse['success'] != true) {
  755.                         return $userResponse;
  756.                     }
  757.                     // new invited user
  758.                     $user $userResponse['data'];
  759.                     $params = [
  760.                         'locations' => $locations,
  761.                         'loggedInUser' => $loggedInUser,
  762.                         'user' => $user,
  763.                         'package' => $package,
  764.                         'disallowedApiGroupsArray' => null,
  765.                         'subscriptionType' => 'custom'
  766.                     ];
  767.                     $assignPermission $this->assignPermissionAndLocation($user$userRole$params$translator);
  768.                     if ($assignPermission['success'] != true) {
  769.                         return $assignPermission;
  770.                     }
  771.                     // Send invite
  772.                     $permission = [
  773.                         'Allow Custom Notification' => "",
  774.                         'Allow Add Location' => "",
  775.                         'Allow AlertHistory For Custom Alerts' => "",
  776.                         'Allow Forecast' => "",
  777.                         'Allow Organization Admin To Invite Users' => "",
  778.                     ];
  779.                     $params = [
  780.                         'user' => $user,
  781.                         'email' => $user->getEmail(),
  782.                         'userName' => $user->getName(),
  783.                         'url' => $hostName $userResponse['token'],
  784.                         'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  785.                         'clientType' => $clientType,
  786.                         'inviteSenderName' => $loggedInUser->getName(),
  787.                         'organization_name' => ($user->getOrganization() ? $user->getOrganization()->getName() : null),
  788.                         'NCMItAdminsData' => $this->getNCMItData(),
  789.                         'entityAdminsData' => $this->getEntityAdminData($user->getOrganization()),
  790.                         'permissions' => $permission,
  791.                         'inviteSenderRole' => ($loggedInUser->getRole() ? $loggedInUser->getRole()->getName() : null),
  792.                         'subject' => "Invitation to Join NCM Business Portal",
  793.                         'NCMItAdminNotificationSubject' => "NCM Admin Invited Organization",
  794.                         'resend' => false,
  795.                         'hostPath' => $request->getSchemeAndHttpHost()
  796.                     ];
  797.                     $inviteResponse $this->invitationModel->sendInvite($params$translator$templating);
  798.                     return $inviteResponse;
  799.                 } else {
  800.                     return ["success" => false"message" =>  $translator->trans("Organization_does_not_created")];
  801.                 }
  802.                 break;
  803.             case 'individual':
  804.                 // Register user if not exists                                
  805.                 $organization['data'] = $loggedInUser->getOrganization();
  806.                 if (isset($organization['data']) && $organization['data'] instanceof \Pimcore\Model\DataObject\Organization) {
  807.                     // Register user if not exists
  808.                     $organization_users = new DataObject\Customer\Listing();
  809.                     $organization_users->filterByOrganization($organization['data']);
  810.                     $organization_users->load();
  811.                     if ($organization_users->getCount() >= $organization['data']->getLimit()) {
  812.                         throw new \Exception("Inivite Limit Exceeded");
  813.                     }
  814.                     $userRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_USER'], true);
  815.                     if (!$userRole instanceof UserRole) {
  816.                         throw new \Exception("User role not found");
  817.                     }
  818.                     $params = [
  819.                         'email' => $email,
  820.                         'organization' => $organization['data'],
  821.                         'name' => $name,
  822.                         'department' => $department,
  823.                         'title' => $title,
  824.                         'groupId' => $groupId,
  825.                         'createdBy' => $loggedInUser,
  826.                         'phone' => $phone
  827.                     ];
  828.                     // check package user limit
  829.                     $customSubscriptions = new DataObject\Subscription\Listing();
  830.                     $customSubscriptions->filterBySubscribedUser($loggedInUser);
  831.                     $customSubscriptions->filterByIsActive(true);
  832.                     $customSubscriptions->filterBySubscriptionType("custom");
  833.                     $customSubscription $customSubscriptions->current();
  834.                     if (!$customSubscription instanceof DataObject\Subscription) {
  835.                         return ["success" => false"message" => $translator->trans("no_custom_subscription_found_to_organization")];
  836.                     }
  837.                     $package $customSubscription->getSubscribedPackage();
  838.                     if (!$package instanceof DataObject\Package) {
  839.                         return ["success" => false"message" => $translator->trans("custom_package_not_found_to_organization")];
  840.                     }
  841.                     $customerList = new DataObject\Customer\Listing();
  842.                     $customerList->filterByOrganization($organization['data']);
  843.                     $customerList->setUnpublished(1);
  844.                     $totalcustomer $customerList->count();
  845.                     $maxUser 0;
  846.                     if ($package->getMaxUsers()) {
  847.                         $maxUser = (int) $package->getMaxUsers();
  848.                     }
  849.                     if ($totalcustomer >= $maxUser) {
  850.                         return ["success" => false"message" => $translator->trans("invite_user_limit_exceeded_for_this_organization")];
  851.                     }
  852.                     // check package user limit
  853.                     $userResponse $this->createUser($userRole$params$translator);
  854.                     if ($userResponse['success'] != true) {
  855.                         return $userResponse;
  856.                     }
  857.                     // new invited user
  858.                     $user $userResponse['data'];
  859.                     $params = [
  860.                         'locations' => $locations,
  861.                         'loggedInUser' => $loggedInUser,
  862.                         'user' => $user,
  863.                         'package' => $package,
  864.                         'disallowedApiGroupsArray' => null,
  865.                         'subscriptionType' => 'custom'
  866.                     ];
  867.                     $assignPermission $this->assignPermissionAndLocation($user$userRole$params$translator);
  868.                     if ($assignPermission['success'] != true) {
  869.                         return $assignPermission;
  870.                     }
  871.                     // Send invite
  872.                     $params = [
  873.                         'user' => $user,
  874.                         'email' => $user->getEmail(),
  875.                         'userName' => $user->getName(),
  876.                         'url' => $hostName $userResponse['token'],
  877.                         'role' => ($user->getRole() ? $loggedInUser->getRole()->getName() : null),
  878.                         'clientType' => "individual",
  879.                         'inviteSenderName' => $loggedInUser->getName(),
  880.                         'entityAdminsData' => $this->getEntityAdminData($user->getOrganization()),
  881.                         'subject' => "Invitation to Join NCM Business Portal",
  882.                         'hostPath' => $request->getSchemeAndHttpHost(),
  883.                         'phone' => $phone,
  884.                         'resend' => false,
  885.                         // 'invite_sender_organization_name' => ($loggedInUser->getOrganization() ? $loggedInUser->getOrganization()->getName() : null),
  886.                     ];
  887.                     $inviteResponse $this->invitationModel->sendInvite($params$translator$templating);
  888.                     return $inviteResponse;
  889.                 } else {
  890.                     return ["success" => false"message" =>  $translator->trans("no_organization_is_associated_with_logged_in_user")];
  891.                 }
  892.                 break;
  893.             case 'user':
  894.                 // Register user if not exists
  895.                 if ($organizationId != null) {
  896.                     $organization DataObject\Organization::getById($organizationIdtrue);
  897.                     if (!$organization instanceof DataObject\Organization) {
  898.                         return ["success" => false"message" =>  $translator->trans("organization_does_not_exists")];
  899.                     }
  900.                 }
  901.                 $organizationEmail $organization->getEmail();
  902.                 // if(substr(strrchr($organizationEmail, "@"), 1) != substr(strrchr($email, "@"), 1)){
  903.                 //     return ["success" => false, "message" =>  $translator->trans("email_does_not_belongs_to_organization")];
  904.                 // }
  905.                 // get organization package
  906.                 $package $organization->getPackage();
  907.                 if (!$package instanceof DataObject\Package) {
  908.                     $organizationUser DataObject\Customer::getByOrganization($organization, ['limit' => 1'unpublished' => true]);
  909.                     if (!$organizationUser instanceof DataObject\Customer) {
  910.                         return ["success" => false"message" =>  $translator->trans("organization_owner_not_exists")];
  911.                     }
  912.                     // Get Custom Subscription of the organization and package
  913.                     $customSubscriptions = new DataObject\Subscription\Listing();
  914.                     $customSubscriptions->filterBySubscribedUser($organizationUser);
  915.                     $customSubscriptions->filterByIsActive(true);
  916.                     $customSubscriptions->filterBySubscriptionType("custom");
  917.                     $customSubscription $customSubscriptions->current();
  918.                     if (!$customSubscription instanceof DataObject\Subscription) {
  919.                         return ["success" => false"message" => $translator->trans("no_custom_subscription_found_to_organization")];
  920.                     }
  921.                     $package $customSubscription->getSubscribedPackage();
  922.                     if (!$package instanceof DataObject\Package) {
  923.                         return ["success" => false"message" => $translator->trans("custom_package_not_found_to_organization")];
  924.                     }
  925.                 }
  926.                 // check package user limit
  927.                 $customerList = new DataObject\Customer\Listing();
  928.                 $customerList->filterByOrganization($organization);
  929.                 $customerList->setUnpublished(1);
  930.                 $totalcustomer $customerList->count();
  931.                 // get package user limit
  932.                 $maxUser = (int) $package->getMaxUsers();;
  933.                 if ($totalcustomer >= $maxUser) {
  934.                     return ["success" => false"message" => $translator->trans("invite_user_limit_exceeded_for_this_organization")];
  935.                 }
  936.                 // check package user limit
  937.                 $userRole DataObject\UserRole::getByName($roletrue);
  938.                 if (!$userRole instanceof UserRole) {
  939.                     throw new \Exception("User role not found");
  940.                 }
  941.                 $params = [
  942.                     'email' => $email,
  943.                     'organization' => $organization,
  944.                     'name' => $name,
  945.                     'department' => $department,
  946.                     'title' => $title,
  947.                     'groupId' => $groupId,
  948.                     'createdBy' => $loggedInUser,
  949.                     'phone' => $phone
  950.                 ];
  951.                 $userResponse $this->createUser($userRole$params$translator);
  952.                 if ($userResponse['success'] != true) {
  953.                     return $userResponse;
  954.                 }
  955.                 // new invited user
  956.                 $user $userResponse['data'];
  957.                 $params = [
  958.                     'locations' => $locations,
  959.                     'loggedInUser' => $loggedInUser,
  960.                     'user' => $user,
  961.                     'package' => $package,
  962.                     'disallowedApiGroupsArray' => null,
  963.                     'subscriptionType' => 'custom'
  964.                 ];
  965.                 $assignPermission $this->assignPermissionAndLocation($user$userRole$params$translator);
  966.                 if ($assignPermission['success'] != true) {
  967.                     return $assignPermission;
  968.                 }
  969.                 // Send invite
  970.                 $params = [
  971.                     'user' => $user,
  972.                     'email' => $user->getEmail(),
  973.                     'userName' => $user->getName(),
  974.                     'url' => $hostName $userResponse['token'],
  975.                     'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  976.                     'clientType' => "user",
  977.                     'inviteSenderName' => $loggedInUser->getName(),
  978.                     'entityAdminsData' => $this->getEntityAdminData($user->getOrganization()),
  979.                     'subject' => "Invitation to Join NCM Business Portal",
  980.                     'hostPath' => $request->getSchemeAndHttpHost(),
  981.                     'resend' => false,
  982.                     //'invite_sender_organization_name' => ($loggedInUser->getOrganization() ? $loggedInUser->getOrganization()->getName() : null),
  983.                 ];
  984.                 // Send invitation
  985.                 $inviteResponse $this->invitationModel->sendInvite($params$translator$templating);
  986.                 //set organization active if it is not active and total customer is less than 1
  987.                 if ($totalcustomer && !$organization->getIsActive()) {
  988.                     $organization->setIsActive(true);
  989.                     // assign package to organization if not assigned
  990.                     if (!$organization->getPackage() instanceof DataObject\Package) {
  991.                         $organization->setPackage($package);
  992.                     }
  993.                     $organization->setPackageActivationDate(Carbon::now());
  994.                     $organization->save();
  995.                 }
  996.                 return $inviteResponse;
  997.                 break;
  998.             default:
  999.                 return ["success" => false"message" => $translator->trans("invalid_client_type")];
  1000.         }
  1001.         // } catch (\Exception $ex) {
  1002.         //     // $result = ["success" => false, "message" => $ex->getMessage()];
  1003.         // }
  1004.         return $result;
  1005.     }
  1006.     /**
  1007.      * Create new user directly form admin and organization or user by NCM 
  1008.      * 
  1009.      */
  1010.     public function adminCreateUser(
  1011.         $request,
  1012.         $translator,
  1013.         $email,
  1014.         $name,
  1015.         $role,
  1016.         $logo null,
  1017.         $clientType,
  1018.         $companyNameEn,
  1019.         $companyNameAr,
  1020.         $locations,
  1021.         $loggedInUser,
  1022.         $department null,
  1023.         $title null,
  1024.         $groupId,
  1025.         $packageId,
  1026.         $organizationId,
  1027.         $password,
  1028.         $phone null,
  1029.         $entityStatus,
  1030.         $trialLimit,
  1031.         $templating
  1032.     ) {
  1033.         $result = [];
  1034.         $user  DataObject\Customer::getByEmail($email, ['limit' => 1'unpublished' => true]);
  1035.         if ($user instanceof DataObject\Customer) {
  1036.             if ($user->getRole()->getName() == USER_ROLES['NCM_OPERATOR'] || $user->getRole()->getName() == USER_ROLES['NCM_IT']) {
  1037.                 return ["success" => false"message" => $translator->trans("user_already_exists_in_internal_user")];
  1038.             } else {
  1039.                 return ["success" => false"message" => $translator->trans("user_already_exists")];
  1040.             }
  1041.         }
  1042.         switch ($clientType) {
  1043.             case 'organization':
  1044.             case 'government':
  1045.                 // Register organization if not exists
  1046.                 $package  DataObject\Package::getById($packageIdtrue);
  1047.                 if (!$package instanceof DataObject\Package) {
  1048.                     return ["success" => false"message" => $translator->trans("package_not_found")];
  1049.                 }
  1050.                 // Check if the name already exists for another organization
  1051.                 $organization DataObject\Organization::getByName($companyNameEn'en', ['limit' => 1'unpublished' => true]);
  1052.                 if ($organization instanceof DataObject\Organization) {
  1053.                     return ["success" => false"message" => $translator->trans("organization_already_exists") . " : " $companyNameEn];
  1054.                 }
  1055.                 // $organizationByEmail = DataObject\Organization::getByEmail($email, true);
  1056.                 // if ($organizationByEmail instanceof DataObject\Organization) {
  1057.                 //     return ["success" => false, "message" => sprintf($translator->trans("organization_already_created_with_this: %s"), $email)];
  1058.                 // }
  1059.                 $allowedStatuses = ['paid''trial''expired'];
  1060.                 if (!in_array($entityStatus$allowedStatuses)) {
  1061.                     return ["success" => false"message" => $translator->trans("undefined_entity_status")];
  1062.                 }
  1063.                 // set params to create organization
  1064.                 $params = [
  1065.                     'name' => $companyNameEn,
  1066.                     'nameAr' => $companyNameAr,
  1067.                     'code' => $companyNameEn,
  1068.                     'client_type' => $clientType,
  1069.                     'email' => $email,
  1070.                     'entityStatus' => $entityStatus,
  1071.                     'trialLimit' => $trialLimit,
  1072.                     'package' => $package
  1073.                     // 'logo'=>$logo
  1074.                 ];
  1075.                 $organization $this->createOrganization($request$params$loggedInUser$translator);
  1076.                 if (isset($organization['data']) && $organization['data'] instanceof DataObject\Organization) {
  1077.                     // check role of user before inviting 
  1078.                     if ($loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN'] && ($role == USER_ROLES['NCM_IT'] || $role == USER_ROLES['NCM_OPERATOR'])) {
  1079.                         return ["success" => false"message" => $translator->trans("CLIENT_ADMIN_can_not_invite_NCM_IT_or_NCM_OPERATOR")];
  1080.                     }
  1081.                     if ($loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN']) {
  1082.                         return ["success" => false"message" => $translator->trans("CLIENT_USER_can_not_invite")];
  1083.                     }
  1084.                     $userRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_ADMIN'], true);
  1085.                     if (!$userRole instanceof UserRole) {
  1086.                         return ["success" => false"message" => $translator->trans("User_Role_Not_Found")];
  1087.                     }
  1088.                     // set params to create user
  1089.                     $params = [
  1090.                         'email' => $email,
  1091.                         'organization' => $organization['data'],
  1092.                         'name' => $name,
  1093.                         'role' => $userRole,
  1094.                         'groupId' => $groupId,
  1095.                         'title' =>  $title,
  1096.                         'department' => $department,
  1097.                         'password' => $password,
  1098.                         'createdBy' => $loggedInUser,
  1099.                         'token' => null,
  1100.                         'published' => true,
  1101.                         'phone' =>  $phone
  1102.                     ];
  1103.                     $userResponse $this->userModel->register($request$params$translator);
  1104.                     if ($userResponse['success'] == true) {
  1105.                         $user $userResponse['data'];
  1106.                         if (empty($user->getNcmCRMId())) {
  1107.                             // Prepare contact data for CRM
  1108.                             $contactData = [
  1109.                                 "firstName" => $user->getName(),
  1110.                                 "lastName" => "",
  1111.                                 "fullName" => $user->getName(),
  1112.                                 "email" => $user->getEmail(),
  1113.                                 "businessPhone" => $user->getPhoneNo() ?? "",
  1114.                                 "address" => new \stdClass(),
  1115.                             ];
  1116.                             // Call CRM Service
  1117.                             $crmId $this->crmService->addContact($contactData);
  1118.                             if ($crmId) {
  1119.                                 $user->setNcmCRMId($crmId);
  1120.                                 $user->save();
  1121.                             }
  1122.                         }
  1123.                     }
  1124.                     if ($userResponse['success'] != true) {
  1125.                         return $userResponse;
  1126.                     }
  1127.                     // new invited user
  1128.                     $user $userResponse['data'];
  1129.                     $params = [
  1130.                         'locations' => $locations,
  1131.                         'loggedInUser' => $loggedInUser,
  1132.                         'user' => $user,
  1133.                         'package' => $package,
  1134.                         'disallowedApiGroupsArray' => null,
  1135.                         'subscriptionType' => 'custom'
  1136.                     ];
  1137.                     $assignPermission $this->assignPermissionAndLocation($user$userRole$params$translator);
  1138.                     if ($assignPermission['success'] != true) {
  1139.                         return $assignPermission;
  1140.                     }
  1141.                     return ["success" => true"message" =>  $translator->trans("organization_created_successfully")];
  1142.                 } else {
  1143.                     return ["success" => false"message" =>  $translator->trans("Organization_does_not_created")];
  1144.                 }
  1145.                 break;
  1146.             case 'user':
  1147.                 // Register user if not exists
  1148.                 if ($organizationId != null) {
  1149.                     $organization DataObject\Organization::getById($organizationIdtrue);
  1150.                     if (!$organization instanceof DataObject\Organization) {
  1151.                         return ["success" => false"message" =>  $translator->trans("organization_does_not_exists")];
  1152.                     }
  1153.                 }
  1154.                 $organizationEmail $organization->getEmail();
  1155.                 // if(substr(strrchr($organizationEmail, "@"), 1) != substr(strrchr($email, "@"), 1)){
  1156.                 //     return ["success" => false, "message" =>  $translator->trans("email_does_not_belongs_to_organization")];
  1157.                 // }
  1158.                 // get organization package
  1159.                 $package $organization->getPackage();
  1160.                 if (!$package instanceof DataObject\Package) {
  1161.                     $organizationUser DataObject\Customer::getByOrganization($organization, ['limit' => 1'unpublished' => true]);
  1162.                     if (!$organizationUser instanceof DataObject\Customer) {
  1163.                         return ["success" => false"message" =>  $translator->trans("organization_owner_not_exists")];
  1164.                     }
  1165.                     // Get Custom Subscription of the organization and package
  1166.                     $customSubscriptions = new DataObject\Subscription\Listing();
  1167.                     $customSubscriptions->filterBySubscribedUser($organizationUser);
  1168.                     $customSubscriptions->filterByIsActive(true);
  1169.                     $customSubscriptions->filterBySubscriptionType("custom");
  1170.                     $customSubscription $customSubscriptions->current();
  1171.                     if (!$customSubscription instanceof DataObject\Subscription) {
  1172.                         return ["success" => false"message" => $translator->trans("no_custom_subscription_found_to_organization")];
  1173.                     }
  1174.                     $package $customSubscription->getSubscribedPackage();
  1175.                     if (!$package instanceof DataObject\Package) {
  1176.                         return ["success" => false"message" => $translator->trans("custom_package_not_found_to_organization")];
  1177.                     }
  1178.                 }
  1179.                 // check package user limit
  1180.                 $customerList = new DataObject\Customer\Listing();
  1181.                 $customerList->filterByOrganization($organization);
  1182.                 $customerList->setUnpublished(1);
  1183.                 $totalcustomer $customerList->count();
  1184.                 // get package user limit
  1185.                 $maxUser = (int) $package->getMaxUsers();
  1186.                 if ($totalcustomer >= $maxUser) {
  1187.                     return ["success" => false"message" => $translator->trans("invite_user_limit_exceeded_for_this_organization")];
  1188.                 }
  1189.                 // check package user limit
  1190.                 $userRole DataObject\UserRole::getByName($roletrue);
  1191.                 if (!$userRole instanceof UserRole) {
  1192.                     return ["success" => false"message" => $translator->trans("User_Role_Not_Found")];
  1193.                 }
  1194.                 // set params to create user
  1195.                 $params = [
  1196.                     'email' => $email,
  1197.                     'organization' => $organization,
  1198.                     'name' => $name,
  1199.                     'role' => $userRole,
  1200.                     'groupId' => $groupId,
  1201.                     'title' =>  $title,
  1202.                     'department' => $department,
  1203.                     'password' => $password,
  1204.                     'createdBy' => $loggedInUser,
  1205.                     'token' => null,
  1206.                     'published' => true,
  1207.                     'phone' => $phone
  1208.                 ];
  1209.                 $userResponse $this->userModel->register($request$params$translator);
  1210.                 if ($userResponse['success'] != true) {
  1211.                     return $userResponse;
  1212.                 }
  1213.                 if ($userResponse['success'] == true) {
  1214.                     $user $userResponse['data'];
  1215.                     if (empty($user->getNcmCRMId())) {
  1216.                         $contactData = [
  1217.                             "firstName" => $user->getName(),
  1218.                             "lastName" => "",
  1219.                             "fullName" => $user->getName(),
  1220.                             "email" => $user->getEmail(),
  1221.                             "businessPhone" => $user->getPhoneNo() ?? "",
  1222.                             "address" => new \stdClass(),
  1223.                         ];
  1224.                         // Call CRM Service
  1225.                         $crmId $this->crmService->addContact($contactData);
  1226.                         if ($crmId) {
  1227.                             $user->setNcmCRMId($crmId);
  1228.                             $user->save();
  1229.                         }
  1230.                     }
  1231.                 }
  1232.                 // new invited user
  1233.                 $user $userResponse['data'];
  1234.                 $params = [
  1235.                     'locations' => $locations,
  1236.                     'loggedInUser' => $loggedInUser,
  1237.                     'user' => $user,
  1238.                     'package' => $package,
  1239.                     'disallowedApiGroupsArray' => null,
  1240.                     'subscriptionType' => 'custom'
  1241.                 ];
  1242.                 $assignPermission $this->assignPermissionAndLocation($user$userRole$params$translator);
  1243.                 if ($assignPermission['success'] != true) {
  1244.                     return $assignPermission;
  1245.                 }
  1246.                 $userData = [
  1247.                     'userId' => $user->getId(),
  1248.                     'email' => $user->getEmail(),
  1249.                     'name' => $user->getName(),
  1250.                     'role' => $role,
  1251.                     'type' => 'created',
  1252.                 ];
  1253.                 $entityAdminsData $this->getEntityAdminData($organization);
  1254.                 // Temporarily closed for testing purposes
  1255.                 // $this->invitationModel->notifyAdmins($userData, $entityAdminsData, $translator, $templating);
  1256.                 //set organization active if it is not active and total customer is less than 1
  1257.                 if ($totalcustomer && !$organization->getIsActive()) {
  1258.                     $organization->setIsActive(true);
  1259.                     // assign package to organization if not assigned
  1260.                     if (!$organization->getPackage() instanceof DataObject\Package) {
  1261.                         $organization->setPackage($package);
  1262.                     }
  1263.                     $organization->setPackageActivationDate(Carbon::now());
  1264.                     $organization->save();
  1265.                 }
  1266.                 return ["success" => true"message" =>  $translator->trans("user_created_successfully")];
  1267.                 break;
  1268.             default:
  1269.                 return ["success" => false"message" => $translator->trans("invalid_client_type")];
  1270.         }
  1271.         return $result;
  1272.     }
  1273.     /**
  1274.      * Send invite to Organization and Individual users
  1275.      * 
  1276.      */
  1277.     public function clientInvite(
  1278.         $request,
  1279.         $translator,
  1280.         $email,
  1281.         $name,
  1282.         $role,
  1283.         $clientType,
  1284.         $locations,
  1285.         $locationTagIds,
  1286.         $loggedInUser,
  1287.         $hostName,
  1288.         $department,
  1289.         $title,
  1290.         $groupId,
  1291.         $disallowedApiGroupsArray,
  1292.         $templating,
  1293.         $isNoExpiry false
  1294.     ) {
  1295.         $user  DataObject\Customer::getByEmail($email, ['limit' => 1'unpublished' => true]);
  1296.         if ($user instanceof DataObject\Customer) {
  1297.             if (($user->getRole()->getName() ==  USER_ROLES['CLIENT_ADMIN'] || $user->getRole()->getName() == USER_ROLES['CLIENT_USER']) && $user->getOrganization()->getId() == $loggedInUser->getOrganization()->getId()) {
  1298.                 return ["success" => false"message" => $translator->trans("user_already_exists")];
  1299.             } elseif (($user->getRole()->getName() ==  USER_ROLES['CLIENT_ADMIN'] || $user->getRole()->getName() == USER_ROLES['CLIENT_USER']) && $user->getOrganization()->getId() != $loggedInUser->getOrganization()->getId()) {
  1300.                 return ["success" => false"message" => $translator->trans("user_already_exists_in_different_organization")];
  1301.             } elseif ($user->getRole()->getName() == USER_ROLES['NCM_OPERATOR'] || $user->getRole()->getName() == USER_ROLES['NCM_IT']) {
  1302.                 return ["success" => false"message" => $translator->trans("user_already_exists_in_admin")];
  1303.             }
  1304.         }
  1305.         $organization $loggedInUser->getOrganization();
  1306.         if (!$organization instanceof DataObject\Organization) {
  1307.             return ["success" => false"message" => $translator->trans("no_organization_is_associated_with_logged_in_user")];
  1308.         }
  1309.         $organizationEmail $organization->getEmail();
  1310.         // Set organization email if not set 
  1311.         if (empty($organizationEmail)) {
  1312.             $organization->setEmail($email);
  1313.             $organization->save();
  1314.         } else {
  1315.             if (substr(strrchr($organizationEmail"@"), 1) != substr(strrchr($email"@"), 1)) {
  1316.                 return ["success" => false"message" =>  $translator->trans("email_does_not_belongs_to_organization")];
  1317.             }
  1318.         }
  1319.         $userRole DataObject\UserRole::getByName(USER_ROLES[$role], true);
  1320.         if (!$userRole instanceof UserRole) {
  1321.             return ["success" => false"message" => $translator->trans("User_role_not_found")];
  1322.         }
  1323.         $package $organization->getPackage();
  1324.         if (!$package instanceof DataObject\Package) {
  1325.             // Get Custom Subscription of the organization and package
  1326.             $customSubscriptions = new DataObject\Subscription\Listing();
  1327.             $customSubscriptions->filterBySubscribedUser($loggedInUser);
  1328.             $customSubscriptions->filterByIsActive(true);
  1329.             $customSubscriptions->filterBySubscriptionType("custom");
  1330.             $customSubscription $customSubscriptions->current();
  1331.             if (!$customSubscription instanceof DataObject\Subscription) {
  1332.                 return ["success" => false"message" => $translator->trans("no_custom_subscription_found_to_organization")];
  1333.             }
  1334.             $package $customSubscription->getSubscribedPackage();
  1335.             if (!$package instanceof DataObject\Package) {
  1336.                 return ["success" => false"message" => $translator->trans("custom_package_not_found_to_organization")];
  1337.             }
  1338.         }
  1339.         $customerList = new DataObject\Customer\Listing();
  1340.         $customerList->filterByOrganization($organization);
  1341.         $customerList->setUnpublished(1);
  1342.         $totalcustomer $customerList->count();
  1343.         $maxUser 0;
  1344.         if ($package->getMaxUsers()) {
  1345.             $maxUser = (int) $package->getMaxUsers();
  1346.         }
  1347.         if ($totalcustomer >= $maxUser) {
  1348.             return ["success" => false"message" => $translator->trans("invite_user_limit_exceeded_for_this_organization")];
  1349.         }
  1350.         $params = [
  1351.             'email' => $email,
  1352.             'organization' => $organization,
  1353.             'name' => $name,
  1354.             'department' => $department,
  1355.             'title' => $title,
  1356.             'groupId' => $groupId,
  1357.             'createdBy' => $loggedInUser,
  1358.             'isNoExpiry' => $isNoExpiry
  1359.         ];
  1360.         $userResponse $this->createUser($userRole$params$translator);
  1361.         if ($userResponse['success'] != true) {
  1362.             return $userResponse;
  1363.         }
  1364.         // new invited user
  1365.         $user $userResponse['data'];
  1366.         $params = [
  1367.             'locations' => $locations,
  1368.             'loggedInUser' => $loggedInUser,
  1369.             'user' => $user,
  1370.             'package' => $package,
  1371.             'disallowedApiGroupsArray' => $role == USER_ROLES['CLIENT_USER'] ? $disallowedApiGroupsArray null,
  1372.             'subscriptionType' => 'custom',
  1373.             'isNoExpiry' => $isNoExpiry,
  1374.         ];
  1375.         $assignPermission $this->assignPermissionAndLocation($user$userRole$params$translator);
  1376.         if ($assignPermission['success'] != true) {
  1377.             return $assignPermission;
  1378.         }
  1379.         // Assign location by location tag id to user
  1380.         if (isset($locationTagIds) && !empty($locationTagIds)) {
  1381.             $assignLocationByLocationTagId $this->userModel->assignLocationToUser($loggedInUsernull$locationTagIds, [$user->getId()], nullfalsefalse$translator);
  1382.             if (isset($assignLocationByLocationTagId['success']) && $assignLocationByLocationTagId['success'] == false) {
  1383.                 return $assignLocationByLocationTagId;
  1384.             }
  1385.         }
  1386.         // Send invite
  1387.         $params = [
  1388.             'user' => $user,
  1389.             'email' => $user->getEmail(),
  1390.             'userName' => $user->getName(),
  1391.             'url' => $hostName $userResponse['token'],
  1392.             'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  1393.             'clientType' => "user",
  1394.             'inviteSenderName' => $loggedInUser->getName(),
  1395.             // 'invite_sender_organization_name' => ($loggedInUser->getOrganization() ? $loggedInUser->getOrganization()->getName() : null),
  1396.             'subject' => "Invitation to Join NCM Business Portal",
  1397.             'hostPath' => $request->getSchemeAndHttpHost(),
  1398.             'entityAdminsData' => $this->getEntityAdminData($user->getOrganization()),
  1399.             'resend' => false,
  1400.         ];
  1401.         // Send invitation
  1402.         $inviteResponse $this->invitationModel->sendInvite($params$translator$templating);
  1403.         return $inviteResponse;
  1404.     }
  1405.     /**
  1406.      * Resend invite to Organization , NCM_users or Individual users
  1407.      * 
  1408.      */
  1409.     public function resendInvite($request$userIdOrIds$loggedInUser$translator$templating): array
  1410.     {
  1411.         $ids is_array($userIdOrIds) ? $userIdOrIds : [$userIdOrIds];
  1412.         $results = [];
  1413.         foreach ($ids as $userId) {
  1414.             $user DataObject\Customer::getById($userIdtrue);
  1415.             if ($user instanceof \Pimcore\Model\DataObject\Customer) {
  1416.                 if (!empty($user->getToken())) {
  1417.                     $organization $user->getOrganization();
  1418.                     if ($organization instanceof \Pimcore\Model\DataObject\Organization) {
  1419.                         $headers = array('alg' => 'HS256''typ' => 'JWT');
  1420.                         //create token for new user
  1421.                         $payload = array('email' => $user->getEmail(), 'org_id' => $organization->getId(), 'time' => time());
  1422.                         $newToken $this->invitationModel->generateJwtToken($headers$payload);
  1423.                         $user->setToken($newToken);
  1424.                         $user->save();
  1425.                         if ($user) {
  1426.                             $decodedJwtToken['username'] = $user->getEmail();
  1427.                             $userPermissions $this->userPermission->checkPermission($decodedJwtToken$translator);
  1428.                             $userPermission $userPermissions['success'] ? $userPermissions['grants'] : null;
  1429.                             $role = ($user->getRole()) ? $user->getRole()->getName() : null;
  1430.                             $clientType null;
  1431.                             if ($role == 'CLIENT_ADMIN' || $role == 'CLIENT_USER') {
  1432.                                 $hostName NCM_HOST_NAME;
  1433.                                 $subject "Invitation to Join NCM Business Portal";
  1434.                                 $clientOrganization DataObject\Organization::getByEmail($user->getEmail(), true);
  1435.                                 if ($clientOrganization instanceof \Pimcore\Model\DataObject\Organization) {
  1436.                                     $clientType $clientOrganization->getCilent_type();
  1437.                                 } else {
  1438.                                     $clientType "user";
  1439.                                 }
  1440.                             } else {
  1441.                                 $hostName NCM_ADMIN_HOST_NAME;
  1442.                                 $subject "Invitation to Join NCM Admin Portal";
  1443.                                 $clientType "NCM_admin";
  1444.                             }
  1445.                             if ($clientType == "NCM_admin") {
  1446.                                 $permission = [
  1447.                                     'Inviting Clients' => isset($userPermission['grants']['invite_user']) ? $userPermission['grants']['invite_user'] : false,
  1448.                                     'Managing Clients' => isset($userPermission['grants']['edit_user']) ? $userPermission['grants']['edit_user'] : false,
  1449.                                     'Deleting Clients' => isset($userPermission['grants']['delete_user']) ? $userPermission['grants']['delete_user'] : false,
  1450.                                     'Inviting NCM Admin' => isset($userPermission['grants']['invite_ncm_user']) ? $userPermission['grants']['invite_ncm_user'] : false,
  1451.                                     'Managing NCM Admin' => isset($userPermission['grants']['edit_ncm_user']) ? $userPermission['grants']['edit_ncm_user'] : false,
  1452.                                     'Deleting NCM Admin' => isset($userPermission['grants']['delete_ncm_user']) ? $userPermission['grants']['delete_ncm_user'] : false,
  1453.                                 ];
  1454.                                 $params = [
  1455.                                     'user' => $user,
  1456.                                     'email' => $user->getEmail(),
  1457.                                     'userName' => $user->getName(),
  1458.                                     'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  1459.                                     'url' => $hostName $newToken,
  1460.                                     'clientType' => "NCM_admin",
  1461.                                     'inviteSenderName' => $loggedInUser->getName(),
  1462.                                     'permissions' => $permission,
  1463.                                     'subject' => "Invitation to Join Admin Portal as NCM Admin",
  1464.                                     'resend' => true
  1465.                                 ];
  1466.                             } elseif ($clientType == "organization" || $clientType == "government") {
  1467.                                 $permission = [
  1468.                                     'Allow Custom Notification' => isset($userPermission['grants']['get_custom_notification']) ? $userPermission['grants']['get_custom_notification'] : false,
  1469.                                     'Allow Add Location' => isset($userPermission['grants']['compare_location']) ? $userPermission['grants']['compare_location'] : false,
  1470.                                     'Allow AlertHistory For Custom Alerts' => isset($userPermission['grants']['alert_history']) ? $userPermission['grants']['alert_history'] : false,
  1471.                                     'Allow Forecast' => isset($userPermission['grants']['get_weather']) ? $userPermission['grants']['get_weather'] : false,
  1472.                                     'Allow Organization Admin To Invite Users' => isset($userPermission['grants']['invite_user']) ? $userPermission['grants']['invite_user'] : false,
  1473.                                 ];
  1474.                                 $params = [
  1475.                                     'user' => $user,
  1476.                                     'email' => $user->getEmail(),
  1477.                                     'userName' => $user->getName(),
  1478.                                     'url' => $hostName $newToken,
  1479.                                     'role' => ($user->getRole() ? $user->getRole()->getName() : null),
  1480.                                     'clientType' => $clientType,
  1481.                                     'inviteSenderName' => $loggedInUser->getName(),
  1482.                                     'organization_name' => ($user->getOrganization() ? $user->getOrganization()->getName() : null),
  1483.                                     'NCMItAdminsData' => $this->getNCMItData(),
  1484.                                     'permissions' => $permission,
  1485.                                     'inviteSenderRole' => ($loggedInUser->getRole() ? $loggedInUser->getRole()->getName() : null),
  1486.                                     'subject' => "Invitation to Join NCM Business Portal",
  1487.                                     'NCMItAdminNotificationSubject' => "NCM Admin Invited Organization",
  1488.                                     'resend' => true
  1489.                                 ];
  1490.                             } elseif ($clientType == "individual" || $clientType == "user") {
  1491.                                 $params = [
  1492.                                     'user' => $user,
  1493.                                     'email' => $user->getEmail(),
  1494.                                     'userName' => $user->getName(),
  1495.                                     'url' => $hostName $newToken,
  1496.                                     'role' => ($user->getRole() ? $loggedInUser->getRole()->getName() : null),
  1497.                                     'clientType' => "user",
  1498.                                     'inviteSenderName' => $loggedInUser->getName(),
  1499.                                     // 'invite_sender_organization_name' => ($loggedInUser->getOrganization() ? $loggedInUser->getOrganization()->getName() : null),
  1500.                                     'subject' => "Invitation to Join NCM Business Portal",
  1501.                                     'resend' => true
  1502.                                 ];
  1503.                             }
  1504.                             // Send invitation
  1505.                             $inviteResponse $this->invitationModel->sendInvite($params$translator$templating);
  1506.                             $results[] = ["id" => $userId"success" => ($inviteResponse['success'] ?? false), "message" => ($inviteResponse['message'] ?? null)];
  1507.                         }
  1508.                     } else {
  1509.                         $results[] = ["id" => $userId"success" => false"message" => $translator->trans("no_organization_is_associated_with_logged_in_user")];
  1510.                     }
  1511.                 } else {
  1512.                     $results[] = ["id" => $userId"success" => false"message" => $translator->trans("user_token_is_invalid")];
  1513.                 }
  1514.             } else {
  1515.                 $results[] = ["id" => $userId"success" => false"message" => $translator->trans("user_is_not_available")];
  1516.             }
  1517.         }
  1518.         if (!is_array($userIdOrIds)) {
  1519.             $single $results[0] ?? ["success" => false"message" => $translator->trans("unknown_error")];
  1520.             return ["success" => $single["success"], "message" => $single["message"]];
  1521.         }
  1522.         $successCount 0;
  1523.         foreach ($results as $r) {
  1524.             if (!empty($r['success'])) {
  1525.                 $successCount++;
  1526.             }
  1527.         }
  1528.         return ["success" => true"message" => sprintf("%s: %d"$translator->trans("reinvite_email_sent"), $successCount)];
  1529.     }
  1530.     /**
  1531.      * Get NCM_IT Admins Data
  1532.      */
  1533.     public function getNCMItData()
  1534.     {
  1535.         $NCMItData = [];
  1536.         $NCMItRole DataObject\UserRole::getByName(USER_ROLES['NCM_IT'], true);
  1537.         $NCMItAdmins = new DataObject\Customer\Listing();
  1538.         $NCMItAdmins->filterByRole($NCMItRole);
  1539.         foreach ($NCMItAdmins as $NCMItAdminsData) {
  1540.             $NCMItData[] = [
  1541.                 'email' => $NCMItAdminsData->getEmail(),
  1542.                 'name' => $NCMItAdminsData->getName()
  1543.             ];
  1544.         }
  1545.         return $NCMItData;
  1546.     }
  1547.     /**
  1548.      * Get Entity Admins Data
  1549.      */
  1550.     public function getEntityAdminData(Organization $organization)
  1551.     {
  1552.         $entityAdminData = [];
  1553.         $entityAdminRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_ADMIN'], true);
  1554.         $entityAdmins = new DataObject\Customer\Listing();
  1555.         $entityAdmins->filterByRole($entityAdminRole);
  1556.         $entityAdmins->filterByOrganization($organization);
  1557.         foreach ($entityAdmins as $entityAdmin) {
  1558.             $entityAdminData[] = [
  1559.                 'id' => $entityAdmin->getId(),
  1560.                 'email' => $entityAdmin->getEmail(),
  1561.                 'name' => $entityAdmin->getName(),
  1562.                 'entityName' => $organization->getName(),
  1563.             ];
  1564.         }
  1565.         return $entityAdminData;
  1566.     }
  1567.     /**
  1568.      * Create asset
  1569.      */
  1570.     private function createAssetByURL($url)
  1571.     {
  1572.         $asset = new \Pimcore\Model\Asset\Image();
  1573.         $asset->setFilename(time() . '-' basename(parse_url($urlPHP_URL_PATH)));
  1574.         $asset->setData(file_get_contents($url));
  1575.         $asset->setParent(\Pimcore\Model\Asset\Service::createFolderByPath("organization_logo"));
  1576.         $asset->save();
  1577.         $advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
  1578.         $advancedImage->setImage($asset);
  1579.         return $advancedImage;
  1580.     }
  1581.     /**
  1582.      * Create user if not exists
  1583.      */
  1584.     private function createUser($userRole$params$translator)
  1585.     {
  1586.         $userResponse = [];
  1587.         if ($userRole instanceof \Pimcore\Model\DataObject\UserRole) {
  1588.             $headers = array('alg' => 'HS256''typ' => 'JWT');
  1589.             //create token for new user
  1590.             $payload = array('email' => $params['email'], 'org_id' => $params['organization']->getId(), 'time' => time());
  1591.             $token $this->invitationModel->generateJwtToken($headers$payload);
  1592.             $requestParam = [
  1593.                 'email' => $params['email'],
  1594.                 'organization' => $params['organization'],
  1595.                 'name' => $params['name'],
  1596.                 'role' => $userRole,
  1597.                 'groupId' => $params['groupId'],
  1598.                 'title' => (isset($params['title']) ? $params['title'] : ''),
  1599.                 'department' => (isset($params['department']) ? $params['department'] : ''),
  1600.                 'password' => (isset($params['password']) ? $params['password'] : ''),
  1601.                 'token' => $token,
  1602.                 'isNoExpiry' => (isset($params['isNoExpiry']) ? $params['isNoExpiry'] : false),
  1603.                 'createdBy' => $params['createdBy'],
  1604.                 'published' => (isset($params['published']) ? $params['published'] : false),
  1605.                 'phone' => isset($params['phone']) ? $params['phone'] : null,
  1606.                 'permissionUserGroupIds' => isset($params['permissionUserGroupIds']) ? $params['permissionUserGroupIds'] : []
  1607.             ];
  1608.             $userResponse $this->userModel->register(null$requestParam$translator);
  1609.             if ($userResponse['success'] == true) {
  1610.                 $user $userResponse['data'];
  1611.                 if ($user->getRole()->getName() !== USER_ROLES['NCM_IT']) {
  1612.                     if (empty($user->getNcmCRMId())) {
  1613.                         $contactData = [
  1614.                             "firstName" => $user->getName(),
  1615.                             "lastName" => "",
  1616.                             "fullName" => $user->getName(),
  1617.                             "email" => $user->getEmail(),
  1618.                             "businessPhone" => $user->getPhoneNo() ?? "",
  1619.                             "address" => new \stdClass(),
  1620.                         ];
  1621.                         $crmId $this->crmService->addContact($contactData);
  1622.                         if ($crmId) {
  1623.                             $user->setNcmCRMId($crmId);
  1624.                             $user->save();
  1625.                         }
  1626.                     }
  1627.                 }
  1628.             }
  1629.             $userResponse['token'] = $token;
  1630.         }
  1631.         return $userResponse;
  1632.     }
  1633.     /**
  1634.      * Assiging user permission
  1635.      */
  1636.     private function assignPermissionAndLocation($user$userRole$params$translator)
  1637.     {
  1638.         try {
  1639.             if (!$user instanceof \Pimcore\Model\DataObject\Customer) {
  1640.                 throw new \Exception($translator->trans("user_not_exists"));
  1641.             }
  1642.             // assign user to assigned locations
  1643.             if (!empty($params['locations']) && count($params['locations'][0]) > 0) {
  1644.                 foreach ($params['locations'][0] as $key => $value) {
  1645.                     $location DataObject\Location::getById($valuetrue);
  1646.                     if ($location) {
  1647.                         $this->locationModel->locationMetaData($location$user);
  1648.                     } else {
  1649.                         return ["success" => false"message" => $translator->trans("location_does_not_exists")];
  1650.                     }
  1651.                 }
  1652.             }
  1653.             $params = [
  1654.                 'user' => $user,
  1655.                 'userRole' => $userRole,
  1656.                 'loggedInUser' => $params['loggedInUser'],
  1657.                 'package' => $params['package'],
  1658.                 'disallowedApiGroupsArray' => $params['disallowedApiGroupsArray'],
  1659.                 'isNoExpiry' => (isset($params['isNoExpiry']) ? $params['isNoExpiry'] : false),
  1660.             ];
  1661.             //$userPermissionResponse = $this->userModel->setPcakageSubscription($params);
  1662.             $subscription $this->userModel->setSubscription($params['package'], $user,  $params['disallowedApiGroupsArray'], "custom"$params['isNoExpiry']);
  1663.             $result $this->parameterModel->riskCategoryBulkCreation($user$translator);
  1664.             if ($subscription && $result) {
  1665.                 return ["success" => true"message" => "set_subscription."];
  1666.             }
  1667.             //return $subscription;
  1668.         } catch (\Exception $ex) {
  1669.             return ["success" => false"message" => $ex->getMessage()];
  1670.         }
  1671.     }
  1672.     /**
  1673.      * add NCM user by admin
  1674.      * 
  1675.      */
  1676.     public function adminAddNCMUser($request$translator$email,  $fullName$role$userTagId$hostName$loggedInUser$allowedApiGroups$permissionUserGroupIds$templating$isNoExpiry false$phone null$password ""): array
  1677.     {
  1678.         $result = [];
  1679.         // try {
  1680.         $user  DataObject\Customer::getByEmail($email, ['limit' => 1'unpublished' => true]);
  1681.         if ($user instanceof DataObject\Customer) {
  1682.             if ($user->getRole()->getName() ==  USER_ROLES['CLIENT_ADMIN'] || $user->getRole()->getName() == USER_ROLES['CLIENT_USER']) {
  1683.                 return ["success" => false"message" => $translator->trans("user_already_exists_in_external_user")];
  1684.             } else {
  1685.                 return ["success" => false"message" => $translator->trans("user_already_exists")];
  1686.             }
  1687.         }
  1688.         $organization $loggedInUser->getOrganization();
  1689.         if ($organization instanceof DataObject\Organization) {
  1690.             // Register user if not exists
  1691.             if ($loggedInUser->getRole()->getName() == USER_ROLES['NCM_OPERATOR'] && $role == USER_ROLES['NCM_IT']) {
  1692.                 return ["success" => false"message" => $translator->trans("NCM_OPERATOR_can_not_invite_NCM_IT.")];
  1693.             }
  1694.             if ($loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN'] || $loggedInUser->getRole()->getName() == USER_ROLES['CLIENT_USER']) {
  1695.                 return ["success" => false"message" => $translator->trans(USER_ROLES[$loggedInUser->getRole()->getName()] . "_can_not_invite_" USER_ROLES[$role])];
  1696.             }
  1697.             $userRole DataObject\UserRole::getByName(USER_ROLES[$role], true);
  1698.             if ($userRole instanceof DataObject\UserRole) {
  1699.                 $package  $userRole->getCustomPackage();
  1700.                 if (!$package instanceof DataObject\Package) {
  1701.                     return ["success" => false"message" => $translator->trans("package_not_found")];
  1702.                 }
  1703.                 $params = [
  1704.                     'email' => $email,
  1705.                     'organization' => $organization,
  1706.                     'name' => $fullName,
  1707.                     'groupId' => null,
  1708.                     'createdBy' => $loggedInUser,
  1709.                     'isNoExpiry' => $isNoExpiry,
  1710.                     'phone' => $phone,
  1711.                     'published' => true,
  1712.                     "password" => $password,
  1713.                     'permissionUserGroupIds' => $permissionUserGroupIds
  1714.                 ];
  1715.                 $userResponse $this->createUser($userRole$params$translator);
  1716.                 if ($userResponse['success'] == true) {
  1717.                     $user $userResponse['data'];
  1718.                     // assign user tag to user
  1719.                     if (isset($userTagId) && !empty($userTagId)) {
  1720.                         $tage  UserTag::getById($userTagId);
  1721.                         if ($tage instanceof UserTag) {
  1722.                             $user->setTag($tage);
  1723.                             $user->save();
  1724.                         }
  1725.                     }
  1726.                     
  1727.                     return ["success" => true"message" => $translator->trans("user_created")];
  1728.                     // $ncmUserSubscription = $this->userModel->setNcmUserSubscription($userRole, $user, $allowedApiGroups, $isNoExpiry);
  1729.                     // if ($ncmUserSubscription instanceof DataObject\Subscription) {
  1730.                     //     $accessWRSIds = [];
  1731.                     //     $accessWRSApiGroups = new DataObject\APIGroup\Listing();
  1732.                     //     $accessWRSApiGroups->setCondition("groupName LIKE ?", ["weather_report%"]);
  1733.                     //     foreach ($accessWRSApiGroups as $Wrsgroup) {
  1734.                     //         $accessWRSIds[] = $Wrsgroup->getId();
  1735.                     //     }
  1736.                     //     $accessEWSIds = [];
  1737.                     //     $accessEWSApiGroups = new DataObject\APIGroup\Listing();
  1738.                     //     $accessEWSApiGroups->setCondition("groupName LIKE ?", ["ews_alert%"]);
  1739.                     //     foreach ($accessEWSApiGroups as $Ewsgroup) {
  1740.                     //         $accessEWSIds[] = $Ewsgroup->getId();
  1741.                     //     }
  1742.                     //     $matchedEWS = array_intersect($allowedApiGroups, $accessEWSIds);
  1743.                     //     $matchedWRS = array_intersect($allowedApiGroups, $accessWRSIds);
  1744.                     //     if ($matchedEWS) {
  1745.                     //         $ncmEwsUser = $this->ewsPortalModel->addNcmUser([
  1746.                     //             'name' => $fullName,
  1747.                     //             'email' => $email,
  1748.                     //             'role' => $role,
  1749.                     //             'allowedApiGroups' => $allowedApiGroups,
  1750.                     //             'hostName' => $hostName,
  1751.                     //             'isNoExpiry' => $isNoExpiry,
  1752.                     //             'phone' => $phone,
  1753.                     //             'password' => $password,
  1754.                     //         ]);
  1755.                     //     }
  1756.                     //     if ($matchedWRS) {
  1757.                     //         $ncmReportingUser = $this->reportingPortalModel->addNcmUser([
  1758.                     //             'name' => $fullName,
  1759.                     //             'email' => $email,
  1760.                     //             'role' => $role,
  1761.                     //             'allowedApiGroups' => $allowedApiGroups,
  1762.                     //             'hostName' => $hostName,
  1763.                     //             'isNoExpiry' => $isNoExpiry,
  1764.                     //             'phone' => $phone,
  1765.                     //             'password' => $password,
  1766.                     //         ]);
  1767.                     //     }
  1768.                     //     return ["success" => true, "message" => $translator->trans("user_created")];
  1769.                     // } else {
  1770.                     //     return ["success" => false, "message" => $translator->trans("user_subscription_not_created")];
  1771.                     // }
  1772.                 } else {
  1773.                     return $userResponse;
  1774.                 }
  1775.             } else {
  1776.                 return ["success" => false"message" => $translator->trans("user_role_not_found")];
  1777.             }
  1778.         } else {
  1779.             return ["success" => false"message" =>   $translator->trans("no_organization_is_associated_with_logged_in_user")];
  1780.         }
  1781.         // } catch (\Exception $ex) {
  1782.         //     $result = ["success" => false, "message" => $ex->getMessage()];
  1783.         // }
  1784.         return $result;
  1785.     }
  1786.     public function updateEntityStatus($params$loggedInUser$translator)
  1787.     {
  1788.         $ids is_array($params['organization_id']) ? $params['organization_id'] : [$params['organization_id']];
  1789.         $entityStatus $params['entity_status'] ?? null;
  1790.         $trialLimit   $params['trialLimit'] ?? null;
  1791.         if (!$entityStatus) {
  1792.             return [
  1793.                 'success' => false,
  1794.                 'message' => $translator->trans("invalid_entity_status"),
  1795.             ];
  1796.         }
  1797.         $userRole $loggedInUser->getRole()->getName();
  1798.         if (!in_array($userRole, [USER_ROLES['NCM_IT'], USER_ROLES['NCM_OPERATOR']])) {
  1799.             return [
  1800.                 'success' => false,
  1801.                 'message' => $translator->trans("%s_has_not_permission_change_entity_status", [
  1802.                     '%s' => $userRole,
  1803.                 ]),
  1804.             ];
  1805.         }
  1806.         $results = [];
  1807.         foreach ($ids as $orgId) {
  1808.             $organization DataObject\Organization::getById($orgId);
  1809.             if (!$organization instanceof DataObject\Organization) {
  1810.                 $results[] = [
  1811.                     'id' => $orgId,
  1812.                     'success' => false,
  1813.                     'message' => $translator->trans("organization_does_not_exist"),
  1814.                 ];
  1815.                 continue;
  1816.             }
  1817.             if ($entityStatus === "trial" && !empty($trialLimit)) {
  1818.                 $organization->setPackageActivationDate(Carbon::now());
  1819.                 $organization->setTrialLimit($trialLimit);
  1820.             }
  1821.             $organization->setStatus($entityStatus);
  1822.             $organization->save();
  1823.             $results[] = [
  1824.                 'id' => $orgId,
  1825.                 'success' => true,
  1826.                 'message' => $translator->trans("entity_status_updated"),
  1827.             ];
  1828.         }
  1829.         if (!is_array($params['organization_id'])) {
  1830.             $single $results[0] ?? [
  1831.                 'success' => false,
  1832.                 'message' => $translator->trans("unknown_error"),
  1833.             ];
  1834.             return [
  1835.                 'success' => $single['success'],
  1836.                 'message' => $single['message'],
  1837.             ];
  1838.         }
  1839.         $successCount 0;
  1840.         $failedCount 0;
  1841.         foreach ($results as $r) {
  1842.             if (!empty($r['success'])) {
  1843.                 $successCount++;
  1844.             } else {
  1845.                 $failedCount++;
  1846.             }
  1847.         }
  1848.         return [
  1849.             'success' => true,
  1850.             'processed' => $successCount,
  1851.             'failed' => $failedCount,
  1852.             'results' => $results,
  1853.             'message' => sprintf("%s: %d"$translator->trans("entity_status_updated"), $successCount),
  1854.         ];
  1855.     }
  1856.     public function updateEntitySmsConfig($request$params$translator)
  1857.     {
  1858.         $ids is_array($params['organizationId']) ? $params['organizationId'] : [$params['organizationId']];
  1859.         $results = [];
  1860.         foreach ($ids as $orgId) {
  1861.             $organization DataObject\Organization::getById($orgId,);
  1862.             if (!$organization instanceof DataObject\Organization) {
  1863.                 $results[] = ['id' => $orgId'success' => false'message' => $translator->trans("organization_does_not_exist")];
  1864.                 continue;
  1865.             }
  1866.             $organization->setIsSMSEnabled($params['isSmsEnabled']);
  1867.             $organization->save();
  1868.             $results[] = ['id' => $orgId'success' => true'message' => $translator->trans('sms_config_updated')];
  1869.         }
  1870.         if (!is_array($params['organizationId'])) {
  1871.             $single $results[0] ?? ['success' => false'message' => $translator->trans('unknown_error')];
  1872.             return ['success' => $single['success'], 'message' => $single['message']];
  1873.         }
  1874.         $successCount 0;
  1875.         foreach ($results as $r) {
  1876.             if (!empty($r['success'])) {
  1877.                 $successCount++;
  1878.             }
  1879.         }
  1880.         return ['success' => true'message' => sprintf("%s: %d"$translator->trans('sms_config_updated'), $successCount)];
  1881.     }
  1882.     public function renewEntitySMSConsumption($request$params$translator)
  1883.     {
  1884.         $ids is_array($params['organizationId']) ? $params['organizationId'] : [$params['organizationId']];
  1885.         $results = [];
  1886.         foreach ($ids as $orgId) {
  1887.             $organization DataObject\Organization::getById($orgId,);
  1888.             if (!$organization instanceof DataObject\Organization) {
  1889.                 $results[] = ['id' => $orgId'success' => false'message' => $translator->trans("organization_does_not_exist")];
  1890.                 continue;
  1891.             }
  1892.             $organization->setIsSMSEnabled(true);
  1893.             $organization->setSmsConsumption(0);
  1894.             $organization->save();
  1895.             $results[] = ['id' => $orgId'success' => true'message' => $translator->trans('sms_consumption_renewed')];
  1896.         }
  1897.         if (!is_array($params['organizationId'])) {
  1898.             $single $results[0] ?? ['success' => false'message' => $translator->trans('unknown_error')];
  1899.             return ['success' => $single['success'], 'message' => $single['message']];
  1900.         }
  1901.         $successCount 0;
  1902.         foreach ($results as $r) {
  1903.             if (!empty($r['success'])) {
  1904.                 $successCount++;
  1905.             }
  1906.         }
  1907.         return ['success' => true'message' => sprintf("%s: %d"$translator->trans('sms_consumption_renewed'), $successCount)];
  1908.     }
  1909.     public function bulkEntityAction($params$packageModel$user$translator)
  1910.     {
  1911.         $actionType $params['actionType'] ?? null;
  1912.         $entityIds $params['entityIds'] ?? [];
  1913.         $payload $params['payload'] ?? [];
  1914.         $processed 0;
  1915.         foreach ($entityIds as $id) {
  1916.             $entity DataObject\Organization::getById($id);
  1917.             if (!$entity instanceof DataObject\Organization) {
  1918.                 continue;
  1919.             }
  1920.             switch ($actionType) {
  1921.                 case 'update_status':
  1922.                     if (!empty($payload['status'])) {
  1923.                         $entity->setStatus($payload['status']); // Enum: Trial, Paid, Expired
  1924.                         $entity->save();
  1925.                         $processed++;
  1926.                     }
  1927.                     break;
  1928.                 case 'update_package':
  1929.                     if (!empty($payload['packageId'])) {
  1930.                         $package DataObject\Package::getById($payload['packageId']);
  1931.                         if ($package instanceof DataObject\Package) {
  1932.                             $packageModel->updateEntityPackage($entity$package$translator);
  1933.                             $entity->setPackage($package);
  1934.                             $entity->save();
  1935.                             $processed++;
  1936.                         }
  1937.                     }
  1938.                     break;
  1939.                 case 'edit':
  1940.                     // Update fields dynamically (only safe editable fields!)
  1941.                     foreach ($payload as $field => $value) {
  1942.                         $setter 'set' ucfirst($field);
  1943.                         if (method_exists($entity$setter)) {
  1944.                             $entity->$setter($value);
  1945.                         }
  1946.                     }
  1947.                     $entity->save();
  1948.                     $processed++;
  1949.                     break;
  1950.                 case 'soft_delete':
  1951.                     if ($this->getUserCountByEntity($entity) === 0) {
  1952.                         $entity->setIsDeleted(true); // Custom field
  1953.                         $entity->setDeletedBy($user);
  1954.                         $entity->setDeletedAt(Carbon::now());
  1955.                         $entity->setPublished(false);
  1956.                         $entity->save();
  1957.                         $processed++;
  1958.                     }
  1959.                     break;
  1960.             }
  1961.         }
  1962.         return [
  1963.             "success" => true,
  1964.             "processed" => $processed,
  1965.             "message" => $translator->trans("action_completed"),
  1966.         ];
  1967.     }
  1968.     private function calculatePackageExpiry($organization): ?string
  1969.     {
  1970.         try {
  1971.             $packageActivationDate $organization->getPackageActivationDate();
  1972.             if (!$packageActivationDate) {
  1973.                 return null;
  1974.             }
  1975.             $trialLimit $organization->getTrialLimit();
  1976.             if (!$trialLimit || $trialLimit <= 0) {
  1977.                 return null;
  1978.             }
  1979.             if (is_numeric($packageActivationDate)) {
  1980.                 $activationDate = new \DateTime();
  1981.                 $activationDate->setTimestamp($packageActivationDate);
  1982.             } else {
  1983.                 $activationDate $packageActivationDate;
  1984.             }
  1985.             $expiryDate = clone $activationDate;
  1986.             $expiryDate->add(new \DateInterval('P' $trialLimit 'D'));
  1987.             return $expiryDate->format('Y-m-d H:i:s');
  1988.         } catch (\Exception $e) {
  1989.             return null;
  1990.         }
  1991.     }
  1992.     public function suspendEntity($loggedInUser$params$translator)
  1993.     {
  1994.         $ids is_array($params['organization_id']) ? $params['organization_id'] : [$params['organization_id']];
  1995.         $userRole $loggedInUser->getRole()->getName();
  1996.         if (!in_array($userRole, [USER_ROLES['NCM_IT'], USER_ROLES['NCM_OPERATOR']])) {
  1997.             return [
  1998.                 'success' => false,
  1999.                 'message' => $translator->trans("%s_has_not_permission_change_entity_status", [
  2000.                     '%s' => $userRole,
  2001.                 ]),
  2002.             ];
  2003.         }
  2004.         $results = [];
  2005.         foreach ($ids as $orgId) {
  2006.             $organization DataObject\Organization::getById($orgId,);
  2007.             if (!$organization instanceof DataObject\Organization) {
  2008.                 $results[] = ['id' => $orgId'success' => false'message' => $translator->trans("organization_does_not_exist")];
  2009.                 continue;
  2010.             }
  2011.             $organization->setIsSuspend(true);
  2012.             $organization->save();
  2013.             $results[] = ['id' => $orgId'success' => true'message' => $translator->trans("entity_suspended")];
  2014.         }
  2015.         if (!is_array($params['organization_id'])) {
  2016.             $single $results[0] ?? ['success' => false'message' => $translator->trans("unknown_error")];
  2017.             return ['success' => $single['success'], 'message' => $single['message']];
  2018.         }
  2019.         $successCount 0;
  2020.         foreach ($results as $r) {
  2021.             if (!empty($r['success'])) {
  2022.                 $successCount++;
  2023.             }
  2024.         }
  2025.         return ['success' => true'message' => sprintf("%s: %d"$translator->trans("entity_suspended"), $successCount)];
  2026.     }
  2027.     public function resumeEntity($loggedInUser$params$translator)
  2028.     {
  2029.         $ids is_array($params['organization_id']) ? $params['organization_id'] : [$params['organization_id']];
  2030.         $userRole $loggedInUser->getRole()->getName();
  2031.         if (!in_array($userRole, [USER_ROLES['NCM_IT'], USER_ROLES['NCM_OPERATOR']])) {
  2032.             return [
  2033.                 'success' => false,
  2034.                 'message' => $translator->trans("%s_has_not_permission_change_entity_status", [
  2035.                     '%s' => $userRole,
  2036.                 ]),
  2037.             ];
  2038.         }
  2039.         $results = [];
  2040.         foreach ($ids as $orgId) {
  2041.             $organization DataObject\Organization::getById($orgId,);
  2042.             if (!$organization instanceof DataObject\Organization) {
  2043.                 $results[] = ['id' => $orgId'success' => false'message' => $translator->trans("organization_does_not_exist")];
  2044.                 continue;
  2045.             }
  2046.             $organization->setIsSuspend(false);
  2047.             $organization->save();
  2048.             $results[] = ['id' => $orgId'success' => true'message' => $translator->trans("entity_resumed")];
  2049.         }
  2050.         if (!is_array($params['organization_id'])) {
  2051.             $single $results[0] ?? ['success' => false'message' => $translator->trans("unknown_error")];
  2052.             return ['success' => $single['success'], 'message' => $single['message']];
  2053.         }
  2054.         $successCount 0;
  2055.         foreach ($results as $r) {
  2056.             if (!empty($r['success'])) {
  2057.                 $successCount++;
  2058.             }
  2059.         }
  2060.         return ['success' => true'message' => sprintf("%s: %d"$translator->trans("entity_resumed"), $successCount)];
  2061.     }
  2062. }