<?php
namespace App\Model;
use Pimcore\Db;
use Carbon\Carbon;
use App\Lib\Utility;
use App\Lib\ExcelGenerator;
use App\Service\EmailService;
use Pimcore\Model\DataObject;
use App\Service\UserPermission;
use Pimcore\Model\DataObject\Customer;
use Pimcore\Model\DataObject\Location;
use Pimcore\Model\DataObject\Tags;
use Pimcore\Model\DataObject\UserGroup;
use Pimcore\Model\DataObject\UserSMSGroup;
use Symfony\Component\HttpFoundation\Request;
use App\C2IntegrationBundle\Service\C2Service;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use DateTime;
use Pimcore\Model\Asset\MetaData\ClassDefinition\Data\DataObject as DataDataObject;
use Pimcore\Model\DataObject\Subscription;
use Pimcore\Model\DataObject\UserTag;
use App\Model\ReportingPortalModel;
use App\Model\EwsPortalModel;
use Pimcore\Model\DataObject\PermissionGroup;
class UserModel
{
public $emailService;
public $userPermission;
private $locationModel;
private $c2Service;
private $reportingPortalModel;
private $ewsPortalModel;
function __construct()
{
$this->emailService = new EmailService();
$this->userPermission = new UserPermission();
$this->locationModel = new LocationModel();
$this->c2Service = new C2Service();
$this->reportingPortalModel = new ReportingPortalModel();
$this->ewsPortalModel = new EwsPortalModel();
}
public function register($request, $params, $translator): array
{
$result = [];
try {
Utility::validateEmail($params['email']);
Utility::validateName($params['name']);
if (!$params['organization'] instanceof \Pimcore\Model\DataObject\Organization) {
return ["success" => false, "message" => $translator->trans("invalid_organization_passed")];
}
if (!$params['role'] instanceof \Pimcore\Model\DataObject\UserRole) {
return ["success" => false, "message" => $translator->trans("invalid_user_role")];
}
$user = DataObject\Customer::getByEmail($params['email'], true);
if ($user instanceof \Pimcore\Model\DataObject\Customer) {
return ["success" => false, "message" => $translator->trans("user_already_exists")];
}
$userGroup = DataObject\UserGroup::getById($params['groupId'], true);
$registerUser = new DataObject\Customer();
$registerUser->setParent(DataObject\Service::createFolderByPath('/UserManagement/Users'));
$registerUser->setKey(trim(strip_tags($params['email'])));
$registerUser->setName(strip_tags($params['name']));
$registerUser->setEmail(trim(strip_tags($params['email'])));
if ((isset($params['published'])) && ($params['published'] == false)) {
# code...
$registerUser->setToken((isset($params['token'])) ? $params['token'] : '');
}
$registerUser->setRole($params['role']);
if ($userGroup instanceof \Pimcore\Model\DataObject\UserGroup) {
$registerUser->setUserGroup($userGroup);
}
// assign user permissions to user
if (isset($params['permissionUserGroupIds']) && !empty($params['permissionUserGroupIds']) && is_array($params['permissionUserGroupIds'])) {
$permissionGroups = [];
foreach ($params['permissionUserGroupIds'] as $groupId) {
$permissionGroup = PermissionGroup::getById($groupId);
if ($permissionGroup) {
$permissionGroups[] = $permissionGroup;
}
}
$registerUser->setPermissionGroups($permissionGroups);
}
$registerUser->setOrganization($params['organization']);
$registerUser->setPassword($params['password']);
$registerUser->setTitle((isset($params['title'])) ? $params['title'] : '');
$registerUser->setDepartment((isset($params['department'])) ? $params['department'] : '');
$registerUser->setCreatedBy($params['createdBy']);
// Set created-by snapshot fields for future reference even if relation is removed
if (isset($params['createdBy']) && $params['createdBy'] instanceof DataObject\Customer) {
$creator = $params['createdBy'];
$registerUser->setCreatedByUserName($creator->getName());
$registerUser->setCreatedByUserEmail($creator->getEmail());
$registerUser->setCreatedByUserStatus($creator->getIsDeleted() ? 'deleted' : 'active');
} else {
$registerUser->setCreatedByUserStatus('deleted');
}
$registerUser->setPublished((isset($params['published'])) ? $params['published'] : true);
$registerUser->setIsActive(true);
$registerUser->setphoneNo(isset($params['phone']) ? $params['phone'] : '');
if ($params['role']->getName() == USER_ROLES['CLIENT_ADMIN'] || $params['role']->getName() == USER_ROLES['CLIENT_USER']) {
$registerUser->setTwoFactorAuth(true);
}
$registerUser->save();
// assign default subscription based on role
if ($params['role']->getName() !== USER_ROLES['NCM_IT'] && $params['role']->getName() !== USER_ROLES['NCM_OPERATOR']) {
# code...
$this->createSubscription($translator, $registerUser, $params['role'], isset($params['isNoExpiry']) ? $params['isNoExpiry'] : false);
}
return ["success" => true, "message" => $translator->trans("user_registered_success"), 'data' => $registerUser];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Create Subscritpion
*/
public function createSubscription($translator, $user, $role, $isNoExpiry = false): array
{
$result = [];
try {
$subscriptionsArray = [];
if ($role instanceof DataObject\UserRole) {
$packages = $role->getDefaultPackages();
if ($packages) {
foreach ($packages as $key => $package) {
if ($package instanceof DataObject\Package) {
if ($user instanceof DataObject\Customer) {
$subscription = $this->setSubscription($package, $user, null, "default", true);
if ($subscription instanceof DataObject\Subscription) {
$subscriptionsArray[] = [
"id" => $subscription->getId(),
"key" => $subscription->getKey(),
];
}
}
}
}
return ["success" => true, "data" => $subscriptionsArray];
}
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function editUser($params, $translator): array
{
$updateUser = DataObject\Customer::getById($params['id'], true);
if ($updateUser instanceof DataObject\Customer && !$updateUser->getIsDeleted()) {
$loggedInUserRole = $params['loggedInUser']->getRole() ? $params['loggedInUser']->getRole()->getName() : null;
$updateOrganization = $updateUser->getOrganization();
// Update client type for NCM_IT role
if (!empty($params['client_type'])) {
if ($loggedInUserRole == USER_ROLES['NCM_IT'] || $loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && $updateOrganization) {
$updateOrganization->setCilent_type($params['client_type']);
$updateOrganization->setClientType($params['client_type']);
$updateOrganization->save();
} else {
return [
"success" => false,
"message" => $translator->trans("access_denied_to_update_organization_client_type")
];
}
}
// Update entity status with validation
if (!empty($params['entity_status'])) {
$allowedStatuses = ['paid', 'trial', 'expired'];
if (in_array($params['entity_status'], $allowedStatuses)) {
if (in_array($loggedInUserRole, [USER_ROLES['NCM_IT'], USER_ROLES['NCM_OPERATOR']]) && $updateOrganization) {
if ($params['client_type'] == "government") {
$updateOrganization->setStatus("paid");
} else {
$updateOrganization->setStatus($params['entity_status']);
}
if ($params['entity_status'] == "trial") {
if (empty($params['trialLimit'])) {
return [
"success" => false,
"message" => $translator->trans("trial_limit_is_required")
];
}
if ($updateOrganization->getStatus() == "expired") {
$updateOrganization->setPackageActivationDate(Carbon::now());
}
$updateOrganization->setTrialLimit($params['trialLimit']);
}
$updateOrganization->save();
}
}
}
// Update company name in English
if (!empty($params['company_name_en'])) {
if ($loggedInUserRole == USER_ROLES['NCM_IT'] || $loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && $updateOrganization) {
// Check if the name already exists for another organization
$existingOrganization = DataObject\Organization::getByName($params['company_name_en'], 'en', ['limit' => 1, 'unpublished' => true]);
if ($existingOrganization && $existingOrganization->getId() !== $updateOrganization->getId()) {
return [
"success" => false,
"message" => $translator->trans("organization_already_exists") . " : " . $params['company_name_en']
];
}
$updateOrganization->setName($params['company_name_en'], 'en');
$updateOrganization->setKey(trim(strip_tags($params['company_name_en']))); // Update key to match new name
$updateOrganization->save();
} else {
return [
"success" => false,
"message" => $translator->trans("access_denied_to_update_organization_company_name_en")
];
}
}
// Update company name in Arabic
if (!empty($params['company_name_ar'])) {
if ($loggedInUserRole == USER_ROLES['NCM_IT'] || $loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && $updateOrganization) {
$updateOrganization->setName($params['company_name_ar'], 'ar');
$updateOrganization->save();
} else {
return [
"success" => false,
"message" => $translator->trans("access_denied_to_update_organization_company_name_ar")
];
}
}
// Update user details (name, password, phone, etc.)
if (!empty($params['name'])) {
$updateUser->setName(strip_tags($params['name']));
}
if (!empty($params['password'])) {
$updateUser->setPassword(strip_tags($params['password']));
}
// update phone number
if (!empty($params['phone'])) {
$phone = trim($params['phone']);
if (strlen($phone) !== 9) {
return ["success" => false, "message" => $translator->trans("phone_no_must_be_9_digits")];
} elseif (!ctype_digit($phone)) {
return ["success" => false, "message" => $translator->trans("phone_no_must_be_numeric")];
} else {
$updateUser->setPhoneNo($phone);
}
} else if (empty($params['phone']) && isset($params['phone'])) {
$updateUser->setPhoneNo("");
}
// Set user role if provided
if (!empty($params['role'])) {
$userRole = DataObject\UserRole::getByName(USER_ROLES[$params['role']], true);
if ($userRole instanceof DataObject\UserRole) {
// Prevent role update if it would leave no admin in the organization
if ($params['role'] == USER_ROLES['CLIENT_USER'] && $updateUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN']) {
$adminRole = DataObject\UserRole::getByName(USER_ROLES['CLIENT_ADMIN'], true);
$adminCount = new DataObject\Customer\Listing();
$adminCount->filterByOrganization($updateUser->getOrganization());
$adminCount->filterByRole($adminRole);
$adminCount->filterByIsActive(true);
if ($adminCount->getCount() <= 1) {
return [
"success" => false,
"message" => $translator->trans('atleast_one_admin_required')
];
}
}
$updateUser->setRole($userRole);
// Update default Package according to role
$rolePackage = $userRole->getDefaultPackages();
if ($rolePackage) {
foreach ($rolePackage as $package) {
if ($package instanceof DataObject\Package) {
$this->updateSubscription($package, $updateUser, null, "default");
}
}
}
}
}
// Set department and title if provided
if (!empty($params['department'])) {
$updateUser->setDepartment(strip_tags($params['department']));
}
if (!empty($params['title'])) {
$updateUser->setTitle(strip_tags($params['title']));
}
// Assign location by location tag id to user
if (!empty($params['location_tag_ids'])) {
$this->assignLocationToUser($params['loggedInUser'], null, $params['location_tag_ids'], [$updateUser->getId()], null, false, false, $translator);
}
$updateUser->save();
// Add updated user to updated permissions
$params['user'] = $updateUser;
// Package subscription update
if (!empty($params['package_id'])) {
$package = DataObject\Package::getById($params['package_id'], true);
if ($package instanceof DataObject\Package) {
$this->updateSubscription($package, $params['user'], null, "custom");
}
}
if (isset($params['disallowedApiGroups'])) {
$this->disallowApiGroups($params['user'], $params['disallowedApiGroups'], "custom");
}
// Handle location assignment for CLIENT_ADMIN or CLIENT_USER roles
if (in_array($params['role'], [USER_ROLES['CLIENT_ADMIN'], USER_ROLES['CLIENT_USER']])) {
if (isset($params['location'])) {
foreach ($params['location'] as $value) {
$location = DataObject\Location::getById($value, true);
if ($location) {
$this->locationModel->locationMetaData($location, $updateUser);
}
}
}
}
return [
"success" => true,
"message" => $translator->trans("user_updated_successfully")
];
}
return [
"success" => false,
"message" => $translator->trans("user_does_not_exist")
];
}
public function editNCMUser($params, $translator): array
{
$result = [];
// try {
$updateUser = DataObject\Customer::getById($params['id'], true);
if ($updateUser instanceof DataObject\Customer && $updateUser->getIsDeleted() != true) {
$loggedInUserRole = $params['loggedInUser']->getRole() ? $params['loggedInUser']->getRole()->getName() : null;
if (isset($params['name']) && !empty($params['name'])) {
$updateUser->setName(strip_tags($params['name']));
}
// Set Role if $UserRole is provided
if (isset($params['role']) && !empty($params['role'])) {
$UserRole = DataObject\UserRole::getByName(USER_ROLES[$params['role']], true);
if ($UserRole instanceof DataObject\UserRole) {
$updateUser->setRole($UserRole);
// Update default Package according to role
$rolePackage = $UserRole->getDefaultPackages();
if ($rolePackage) {
foreach ($rolePackage as $key => $package) {
if ($package instanceof DataObject\Package) {
$this->updateSubscription($package, $updateUser, null, "default");
}
}
}
}
}
// update password
if (isset($params['password']) && !empty($params['password'])) {
$updateUser->setPassword(strip_tags($params['password']));
}
// updated permissions
if (isset($params['allowedApiGrpups']) && !empty($params['allowedApiGrpups'])) {
$this->updateNCMUserSubscription($updateUser, $params['allowedApiGrpups']);
}
// update permission user groups
if (isset($params['permissionUserGroupIds']) && !empty($params['permissionUserGroupIds'])) {
// Validate and prepare permission groups
$permissionGroups = [];
foreach ($params['permissionUserGroupIds'] as $groupId) {
$permissionGroup = PermissionGroup::getById($groupId);
if ($permissionGroup) {
$permissionGroups[] = $permissionGroup;
}
}
$updateUser->setPermissionGroups($permissionGroups);
}
// assign user tag to user
if (isset($params['tagId']) && !empty($params['tagId'])) {
$tage = UserTag::getById($params['tagId']);
if ($tage instanceof UserTag) {
$updateUser->setTag($tage);
}
}
if (isset($params['phone']) && !empty($params['phone'])) {
$updateUser->setPhoneNo(strip_tags($params['phone']));
}
$updateUser->save();
// unset($params["Authorization"]);
// $params["loggedInUserEmail"] = $loggedInUserRole = $params['loggedInUser']->getEmail();
// $ncmReportingUser = $this->reportingPortalModel->updateNcmUser($params);
// $ewsPortalUser = $this->ewsPortalModel->updateNcmUser($params);
return ["success" => true, "message" => $translator->trans("user_updated_successifully")];
}
return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
// } catch (\Exception $ex) {
// throw new \Exception($ex->getMessage());
// }
return $result;
}
public function disallowApiGroups($user, $disallowedApiGroups, $type)
{
$result = [];
if (!$user instanceof DataObject\Customer) {
return ["success" => false, "message" => "User is not available"];
}
$customSubscriptions = new DataObject\Subscription\Listing();
$customSubscriptions->filterBySubscribedUser($user);
$customSubscriptions->filterBySubscriptionType("custom");
$customSubscriptions->filterByIsActive(true);
$updateSubscription = $customSubscriptions->current();
if ($updateSubscription instanceof DataObject\Subscription) {
//Set Disallowed ApiGroups
if ($disallowedApiGroups != null) {
$disallowedApiGroupsArr = [];
foreach ($disallowedApiGroups as $disallowedApiGroupsId) {
$apiGroup = DataObject\APIGroup::getById($disallowedApiGroupsId, true);
$disallowedApiGroupsArr[] = $apiGroup;
}
$updateSubscription->setDisallowedApiGroups($disallowedApiGroupsArr);
} else {
$updateSubscription->setDisallowedApiGroups(null);
}
$updateSubscription->save();
}
return $updateSubscription;
}
public function updateUserGroupData(
$loggedInUser,
$locations,
$locationTagIds,
$userGroupId,
$userIds,
$request,
$lang,
$translator
): array {
$result = [];
try {
$userGroup = DataObject\UserGroup::getById($userGroupId, true);
if (!$userGroup instanceof DataObject\UserGroup) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_available")];
}
if (count($userIds) > 0) {
foreach ($userIds as $key => $userId) {
$user = DataObject\Customer::getById($userId, true);
$userGroupArr[] = $userGroup;
foreach ($user->getUserGroup() as $group) {
$userGroupArr[] = $group;
}
$userGroupArr = array_unique($userGroupArr);
if ($user instanceof DataObject\Customer) {
$user->setUserGroup($userGroupArr);
$user->save();
}
}
// Assign location by location tag id to user
if (isset($locationTagIds) && !empty($locationTagIds)) {
$assignLocationByLocationTagId = $this->assignLocationToUser($loggedInUser, $locations, $locationTagIds, $userIds, null, false, false, $translator);
if (isset($assignLocationByLocationTagId['success']) && $assignLocationByLocationTagId['success'] == false) {
return $assignLocationByLocationTagId;
}
}
return ["success" => true, "message" => $translator->trans("user_group_are_updated_successfully ")];
}
return ["success" => false, "message" => $translator->trans("user_group_not_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function createUserGroupData($user, $groupNameEn, $groupNameAr, $detailEn, $detailAr, $groupId, $request, $lang, $translator): array
{
$result = [];
try {
$organization = $user->getOrganization();
if (!$organization instanceof DataObject\Organization) {
return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_organization ")];
}
$userGroup = new DataObject\UserGroup\Listing();
$userGroup->setLocale($lang);
$userGroup->setCondition("groupName = ? ", [$groupNameEn]);
$userGroup->filterByOrganization($organization);
$userGroup = $userGroup->current();
if ($userGroup instanceof DataObject\UserGroup) {
return ["success" => false, "message" => $translator->trans("user_group_name_already_available")];
}
if (!empty($groupId)) {
$userGroup = DataObject\UserGroup::getById($groupId, true);
if (!$userGroup instanceof DataObject\UserGroup) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_available")];
}
$userGroup->setKey(trim(strip_tags($groupNameEn)));
$userGroup->setGroupName($groupNameEn, 'en');
$userGroup->setGroupName($groupNameAr, 'ar');
$userGroup->setDetail($detailEn, 'en');
$userGroup->setDetail($detailAr, 'ar');
$userGroup->save();
if ($userGroup) {
return ["success" => true, "message" => $translator->trans("user_group_updated_successfully")];
}
}
$userGroup = new DataObject\UserGroup();
$userGroup->setParent(DataObject\Service::createFolderByPath('/UserManagement/UserGroups/' . $organization->getName()));
$userGroup->setKey(trim(strip_tags($groupNameEn)));
$userGroup->setGroupName($groupNameEn, 'en');
$userGroup->setGroupName($groupNameAr, 'ar');
$userGroup->setDetail($detailEn, 'en');
$userGroup->setDetail($detailAr, 'ar');
$userGroup->setOrganization($organization);
$userGroup->setPublished(true);
$userGroup->save();
if ($userGroup) {
return ["success" => true, "message" => $translator->trans("user_group_created_successfully"), "user_group_id" => $userGroup->getId()];
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function editUserGroupData($id, $groupNameEn, $groupNameAr, $detailEn, $detailAr, $request, $lang, $translator): array
{
$result = [];
try {
$userGroup = DataObject\UserGroup::getById($id, true);
if (!$userGroup instanceof DataObject\UserGroup) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_available")];
}
if (isset($groupNameEn) && !empty($groupNameEn)) {
$userGroup->setGroupName($groupNameEn, 'en');
}
if (isset($groupNameAr) && !empty($groupNameAr)) {
$userGroup->setGroupName($groupNameAr, 'ar');
}
if (isset($detailEn) && !empty($detailEn)) {
$userGroup->setDetail($detailEn, 'en');
}
if (isset($detailAr) && !empty($detailAr)) {
$userGroup->setDetail($detailAr, 'ar');
}
$userGroup->save();
if ($userGroup) {
return ["success" => true, "message" => $translator->trans("user_group_updated_successfully")];
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function deleteUserGroup($user, $id, $request, $translator): array
{
$result = [];
try {
$userGroup = DataObject\UserGroup::getById($id, true);
if (!$userGroup instanceof DataObject\UserGroup) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_available")];
}
if (!$userGroup->getOrganization()) {
return ["success" => false, "message" => $translator->trans("no_organization_is_assigned_to_this_user_group")];
}
$loggedInUserOrganizationName = $user->getOrganization() ? $user->getOrganization()->getName() : '';
if ($userGroup->getOrganization()->getName("en") != $loggedInUserOrganizationName) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_assigned_to_your_organization")];
}
$userGroup->delete();
return ["success" => true, "message" => $translator->trans("user_group_deleted_successifully")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function userGroupListing($user, $translator, $paginator, $params): array
{
$result = [];
try {
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$lang = isset($params['lang']) ? $params['lang'] : 'en';
$organization = $user->getOrganization();
if (!$organization instanceof DataObject\Organization) {
return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_organization ")];
}
// Load LocationGroup listing
$userGroupList = new DataObject\UserGroup\Listing();
$userGroupList->filterByOrganization($organization);
$userGroupList->setLocale($lang);
if (isset($params['search']) && !empty($params['search'])) {
$userGroupList->addConditionParam('(groupName LIKE ? OR detail LIKE ?)', ['%' . $params['search'] . '%', '%' . $params['search'] . '%']);
}
$userGroupList->setOrderKey("oo_id");
$userGroupList->setOrder("desc");
$paginator = $paginator->paginate(
$userGroupList,
$page,
$pageSize
);
if ($paginator->getTotalItemCount() > 0) {
$userGroupListData = [];
foreach ($paginator as $key => $userGroup) {
$userListData = [];
$usersList = new DataObject\Customer\Listing();
$usersList->filterByUserGroup($userGroup);
$usersList->setOrderKey("oo_id");
$usersList->setOrder("desc");
if ($usersList) {
foreach ($usersList as $user) {
$userListData[] = [
'id' => $user->getId(),
'name' => $user->getName(),
'email' => $user->getEmail(),
'role' => $user->getRole() ? $user->getRole()->getName() : '',
'organization' => $user->getOrganization() ? $user->getOrganization()->getName() : '',
];
}
}
$userGroupListData[] = [
'id' => $userGroup->getId(),
'groupName_en' => $userGroup->getGroupName("en"),
'detail_en' => $userGroup->getDetail("en"),
'groupName_ar' => $userGroup->getGroupName("ar"),
'detail_ar' => $userGroup->getDetail("ar"),
'usersData' => $userListData
];
}
if (!empty($userGroupListData) && count($userGroupListData) > 0) {
return ["success" => true, "data" => $userGroupListData, "paginationVariables" => $paginator->getPaginationData()];
}
}
return ["success" => false, "message" => $translator->trans("user_groups_are_not_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function userGroupDetail($user, $userGroupId, $translator): array
{
$result = [];
try {
$organization = $user->getOrganization();
if (!$organization instanceof DataObject\Organization) {
return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_organization")];
}
$userGroupData = [];
$userListData = [];
$data = [];
$totalUsers = 0;
//load user group
$userGroup = new DataObject\UserGroup\Listing();
$userGroup->setCondition("oo_id = ? ", [$userGroupId]);
$userGroup->filterByOrganization($organization);
$userGroup = $userGroup->current();
if ($userGroup instanceof DataObject\UserGroup) {
//get user group data
$userGroupData[] = [
'id' => $userGroup->getId(),
'groupName_en' => $userGroup->getGroupName("en"),
'detail_en' => $userGroup->getDetail("en"),
'groupName_ar' => $userGroup->getGroupName("ar"),
'detail_ar' => $userGroup->getDetail("ar"),
];
//get all users available in above user group
$customers = new DataObject\Customer\Listing();
$customers->filterByOrganization($organization);
$customers->filterByUserGroup($userGroup);
$customers->filterByIsActive(true);
if ($customers->getCount() > 0) {
$totalUsers = $customers->getCount();
foreach ($customers as $key => $customer) {
if ($customer instanceof DataObject\Customer) {
//get user data
$userListData[] = [
'id' => $customer->getId(),
'name' => $customer->getName(),
'email' => $customer->getEmail(),
'role' => $customer->getRole() ? $customer->getRole()->getName() : null,
'department' => $customer->getDepartment(),
'titile' => $customer->getTitle()
];
}
}
// store all data in data array
$data[] = [
"userGroupData" => $userGroupData,
"totalUsers" => $totalUsers,
"users" => $userListData
];
if (!empty($data) && count($data) > 0) {
return ["success" => true, "data" => $data];
}
}
}
return ["success" => false, "message" => $translator->trans("user_group_is_not_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function updateProfile($params, $translator): array
{
$result = [];
try {
$updateUser = DataObject\Customer::getById($params['id'], true);
if ($updateUser) {
try {
$updateUser->setName(strip_tags($params['name']));
$updateUser->setDepartment(strip_tags($params['department']));
$updateUser->setTitle(strip_tags($params['title']));
if (isset($params['isTwoFactorAuth'])) {
if ($params['isTwoFactorAuth'] == true) {
$updateUser->setTwoFactorAuth(true);
} else {
$updateUser->setTwoFactorAuth(false);
}
}
if (isset($params['iqamaId']) && !empty($params['iqamaId'])) {
if (\App\Lib\Utility::validateIqamaId($params['iqamaId'])) {
$updateUser->setIqamaId($params['iqamaId']);
} else {
return ["success" => false, "message" => $translator->trans("iqama_id_is_invalid")];
}
}
if (!empty($params['phoneno'])) {
$phoneNo = trim($params['phoneno']);
if (strlen($phoneNo) !== 9) {
return ["success" => false, "message" => $translator->trans("phone_no_must_be_9_digits")];
} elseif (!ctype_digit($phoneNo)) {
return ["success" => false, "message" => $translator->trans("phone_no_must_be_numeric")];
} else {
$updateUser->setPhoneNo($phoneNo);
}
}
$updateUser->save();
if (!isset($params['from_ews']) && !isset($params['from_reporting'])) {
unset($params["Authorization"]);
$params["userEmail"] = $updateUser->getEmail();
$params["from_portal"] = true;
// Inform other systems
// $this->ewsPortalModel->updateProfile($params);
// $this->reportingPortalModel->updateProfile($params);
}
return ["success" => true, "message" => $translator->trans("user_updated_successfully")];
} catch (\Exception $ex) {
return ["success" => false, "message" => $translator->trans("user_not_updated_successfully")];
}
}
return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* forget user password
*/
public function forgotPassword($request, $email, $httpOrigin, $translator, $templating)
{
$result = [];
try {
$lang = $translator->getLocale();
$user = DataObject\Customer::getByEmail($email, true);
if ($user instanceof \Pimcore\Model\DataObject\Customer) {
//generate token
$token = md5($user->getId() . time() . uniqid());
$user->setResetPasswordToken($token);
//$user->setPasswordRecoveryTokenDate(Carbon::now());
$user->save();
$role = ($user->getRole()) ? $user->getRole()->getName() : null;
$hostName = $httpOrigin . "/auth/reset-password?token=";
if ($role == 'CLIENT_ADMIN' || $role == 'CLIENT_USER') {
$subject = $translator->trans("Reset Password to Join NCM Business Portal");
$title = $translator->trans("Meteo KSA");
} else {
$subject = $translator->trans("Reset Password to Join NCM Admin Portal");
$title = $translator->trans("Meteo KSA Admin");
}
$param = [
'userName' => $user->getName(),
'tokenLink' => $hostName . $token,
'title' => $title,
];
$html = $templating->render('web2print/generic_mail.html.twig', $param);
$templateId = $_ENV['RESET_PASSWORD_TEMPLATE'];
$purpose = RESET_PASSWORD_MESSAGE;
$result = $this->c2Service->sendNotificationEmail($templateId, $user->getId(), $user->getId(), $html, $subject, $purpose);
//$result = $this->emailService->sendMail($param, $user->getEmail(), PASSWORD_RECOVERY_EMAIL_DOCUMENT_PATH, $subject);
$translator->setLocale($lang);
if ($result) {
return ["success" => true, "message" => $translator->trans("account_reset_mail_sent_when_possible")];
}
return ["success" => false, "message" => $translator->trans("an_error_occured_while_sending_mail")];
} else {
return ["success" => false, "message" => $translator->trans("user_not_found")];
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Reset user password
*/
public function resetPassword($request, $token, $newPassword, $conformNewPassword, $translator): array
{
$result = [];
try {
//check if the token is valid
$user = DataObject\Customer::getByResetPasswordToken($token, true);
if ($user instanceof \Pimcore\Model\DataObject\Customer) {
if ($newPassword != $conformNewPassword) {
return ["success" => false, "message" => $translator->trans("new_password_and_conformNewPassword_not_matching")];
}
$user->setPassword($newPassword);
$user->setResetPasswordToken(null);
$user->save();
if ($user) {
return ["success" => true, "message" => $translator->trans("password_updated_successifully")];
}
} else {
return ["success" => false, "message" => $translator->trans("user_not_found_token_is_not_valid")];
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Reset user password
*/
public function changePassword($user, $params, $translator): array
{
$result = [];
try {
if ($params['newPassword'] != $params['confirmNewPassword']) {
return ["success" => false, "message" => $translator->trans("new_password_and_conformNewPassword_not_matching")];
}
if ($user) {
if (password_verify(trim($params['oldPassword']), $user->getPassword())) {
$user->setPassword($params['newPassword']);
$user->save();
if (!isset($params['from_ews']) && !isset($params['from_reporting'])) {
unset($params["Authorization"]);
$params["userEmail"] = $user->getEmail();
$params["from_portal"] = true;
// Inform other systems
// $this->ewsPortalModel->changePassword($params);
// $this->reportingPortalModel->changePassword($params);
}
return ["success" => true, "message" => $translator->trans("password_updated_successifully")];
} else {
return ["success" => false, "message" => $translator->trans("old_password_is_not_correct")];
}
}
return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Get Public User Premissions
*/
public function publicUserPermissions($translator): array
{
$result = [];
try {
$db = Db::get();
$permissions = $db->fetchAll("SELECT * FROM `policy`");
return ["success" => true, "data" => $permissions];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Create Public User
*/
public function addPublicUser($request, $params, $translator): array
{
$result = [];
try {
$user = DataObject\PublicUser::getByName($params['name'], true);
if ($user instanceof DataObject\PublicUser) {
return ["success" => false, "message" => $translator->trans("This public user already exists.")];
}
$addPublicUser = new DataObject\PublicUser();
$addPublicUser->setParent(DataObject\Service::createFolderByPath('/UserManagement/PublicUsers/'));
$addPublicUser->setKey($params['name']);
$addPublicUser->setName($params['name']);
$addPublicUser->setStartDate(Carbon::parse($params['startDate']));
$addPublicUser->setEndDate(Carbon::parse($params['endDate']));
$addPublicUser->setPublished(true);
$addPublicUser->save();
if (!$addPublicUser->getId()) {
throw new \Exception("Failed to create public user.");
}
$db = Db::get();
foreach ($params['permissions'] as $parameter) {
$permission = $db->fetchOne("SELECT id FROM policy WHERE parameter = ?", $parameter);
if ($permission) {
$data = array(
'user_id' => $addPublicUser->getId(),
'policy_id' => $permission,
'is_allowed' => 1
);
$insertResult = $db->insert("user_policy", $data);
if (!$insertResult) {
throw new \Exception($translator->trans("Failed to associate permissions with the public user."));
}
} else {
throw new \Exception($translator->trans("Permission not found for parameter: " . $parameter));
}
}
return ["success" => true, "message" => $translator->trans("Public user created successfully.")];
} catch (\Exception $ex) {
return ["success" => false, "message" => $ex->getMessage()];
}
return $result;
}
// public function deleteUser($request, $params, $translator): array
// {
// $result = [];
// // try {
// $user = DataObject\Customer::getById($params['id'], true);
// if ($user) {
// // Deleting user location
// $locations = $this->locationModel->getLocationsByUserId($user->getId());
// if ($locations) {
// foreach ($locations as $location) {
// if ($location instanceof \Pimcore\Model\DataObject\Location) {
// $this->locationModel->deAssociateUserLocation($location, $user, $translator);
// }
// }
// }
// // Deleting user custom notification
// $customNotification = new \Pimcore\Model\DataObject\CustomNotification\Listing();
// $customNotification->filterByUser($user);
// foreach ($customNotification as $notification) {
// $notification->delete();
// }
// $user->delete();
// return ["success" => true, "message" => $translator->trans("user_deleted_successifully")];
// }
// return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
// // } catch (\Exception $ex) {
// // throw new \Exception($ex->getMessage());
// // }
// return $result;
// }
public function deleteUser($request, $params, $loggedInUser, $translator): array
{
$result = [];
// Check if the user is already deleted
$deletedUsers = new DataObject\DeletedUsersData\Listing();
$deletedUsers->filterByPimId($params['id']);
$deletedUsers->filterByIsDeleted(false);
$check = $deletedUsers->current();
if ($check instanceof DataObject\DeletedUsersData) {
return ["success" => false, "message" => $translator->trans("user_already_deleted")];
}
// Fetch the user by ID
$user = DataObject\Customer::getById($params['id'], true);
if (!$user) {
return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
}
// Deactivate and save the user
$user->setToken(null);
$user->setIsDeleted(true);
$user->setPublished(false);
$user->save();
// Update created-by references: mark status as deleted and clear relation
$createdUsers = new DataObject\Customer\Listing();
$createdUsers->filterByCreatedBy($user);
foreach ($createdUsers as $createdUser) {
if ($createdUser instanceof DataObject\Customer) {
$createdUser->setCreatedBy(null);
$createdUser->setCreatedByUserStatus('deleted');
$createdUser->save();
}
}
// Create a deleted user record
$deleteUserRecord = new DataObject\DeletedUsersData();
$deleteUserRecord->setParent(DataObject\Service::createFolderByPath('/UserManagement/DeletedUsers/'));
$deleteUserRecord->setKey($user->getName() . strtotime("now") . rand(0, 100));
$deleteUserRecord->setName($user->getName());
$deleteUserRecord->setEmail($user->getEmail());
$deleteUserRecord->setPimId($user->getId());
$deleteUserRecord->setOrganizationName($user->getOrganization() ? $user->getOrganization()->getName() : '');
$deleteUserRecord->setRole($user->getRole() ? $user->getRole()->getName() : '');
$deleteUserRecord->setIsDeleted(false);
$deleteUserRecord->setDeletedBy($loggedInUser->getEmail());
$deleteUserRecord->setPublished(true);
$deleteUserRecord->save();
// Delete user dependencies (locations)
$locations = $this->locationModel->getLocationsByUserId($user->getId());
if ($locations) {
foreach ($locations as $location) {
if ($location instanceof \Pimcore\Model\DataObject\Location) {
$this->locationModel->deAssociateUserLocation($location, $user, $translator);
}
}
}
// Delete user custom notifications
$customNotification = new \Pimcore\Model\DataObject\CustomNotification\Listing();
$customNotification->filterByUser($user);
foreach ($customNotification as $notification) {
$notification->delete();
}
// Delete user dashboard
$dashboard = new DataObject\Dashboard\Listing();
$dashboard->setCondition('user__id = ?', [$user->getId()]);
if ($dashboard->current() instanceof DataObject\Dashboard) {
$dashboard->current()->delete();
}
// Delete user subscriptions
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->setCondition('subscribedUser__id = ?', [$user->getId()]);
foreach ($subscriptions as $subscription) {
if ($subscription instanceof DataObject\Subscription) {
$subscription->delete();
}
}
// Finalize user deletion
$user->delete();
// Mark the deleted user record as deleted
$deleteUserRecord->setIsDeleted(true);
$deleteUserRecord->save();
return ["success" => true, "message" => $translator->trans("user_deleted_successfully")];
}
/**
* Get Client User Organization List
*/
public function getClientUsers($request, $user, $params, $paginator, $translator)
{
$result = [];
$userData = [];
// try {
// Get All the Classes
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customer = $class->getDao()->getIdByName('Customer');
$subscription = $class->getDao()->getIdByName('Subscription');
$userRole = $class->getDao()->getIdByName('UserRole');
$organization = $class->getDao()->getIdByName('Organization');
$package = $class->getDao()->getIdByName('Package');
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('customer.oo_id');
$select->from('object_' . $customer, 'customer');
// Use LEFT JOIN for subscriptions to handle suspended users (users without subscriptions)
$select->leftJoin('customer', 'object_' . $subscription, 'subscription', 'customer.oo_id = subscription.subscribedUser__id');
$select->leftJoin('subscription', 'object_' . $package, 'package', 'package.oo_id = subscription.subscribedPackage__id');
$select->innerJoin('customer', 'object_' . $organization, 'organization', 'organization.oo_id = customer.organization__id');
$select->innerJoin('customer', 'object_' . $userRole, 'userRole', 'userRole.oo_id = customer.role__id');
// Use placeholders to prevent SQL injection
if (isset($params['clientType']) && !empty($params['clientType'])) {
$select->Where("organization.clientType = " . $db->quote($params['clientType']));
}
if (isset($params['organization_id']) && !empty($params['organization_id'])) {
$select->andWhere("organization.oo_id = " . $db->quote($params['organization_id']));
}
if (isset($params['package_id']) && !empty($params['package_id'])) {
$select->andWhere("package.oo_id = " . $db->quote($params['package_id']));
}
if (isset($params['search']) && !empty($params['search'])) {
$select->andWhere("customer.name LIKE " . $db->quote("%" . $params['search'] . "%") . " OR customer.email LIKE " . $db->quote("%" . $params['search'] . "%"));
}
if (isset($params['userStatus']) && !empty($params['userStatus'])) {
$filterStatus = strtolower(trim($params['userStatus']));
// Validate that the filter status is one of the allowed values
$allowedStatuses = ['pending', 'active', 'suspended', 'activepending'];
if (in_array($filterStatus, $allowedStatuses)) {
switch ($filterStatus) {
case 'pending':
// Pending: user is unpublished, no custom subscription, has default subscription
$select->andWhere("customer.o_published = 0");
$select->andWhere("subscription.subscriptionType != 'custom'");
$select->andWhere("subscription.subscribedUser__id IS NOT NULL");
$select->andWhere("subscription.isWso IS NULL OR subscription.isWso = 0");
$select->andWhere("userRole.name IN ('CLIENT_USER', 'CLIENT_ADMIN')");
break;
case 'active':
// Active: user is published, has custom subscription, isActive = true
$select->andWhere("customer.o_published = 1");
$select->andWhere("subscription.subscriptionType = 'custom'");
$select->andWhere("subscription.subscribedUser__id IS NOT NULL");
$select->andWhere("subscription.isActive = 1");
$select->andWhere("subscription.isWso IS NULL OR subscription.isWso = 0");
$select->andWhere("userRole.name IN ('CLIENT_USER', 'CLIENT_ADMIN')");
break;
case 'suspended':
// Suspended: user is published, has custom subscription, isActive = false
$select->andWhere("customer.o_published = 1");
$select->andWhere("subscription.subscriptionType = 'custom'");
$select->andWhere("subscription.subscribedUser__id IS NOT NULL");
$select->andWhere("subscription.isActive = 0");
break;
case 'activepending':
// Active OR Pending
$select->andWhere("((customer.o_published = 0 AND subscription.subscriptionType != 'custom' AND subscription.subscribedUser__id IS NOT NULL) OR (customer.o_published = 1 AND subscription.subscriptionType = 'custom' AND subscription.subscribedUser__id IS NOT NULL AND subscription.isActive = 1))");
$select->andWhere("subscription.isWso IS NULL OR subscription.isWso = 0");
$select->andWhere("userRole.name IN ('CLIENT_USER', 'CLIENT_ADMIN')");
break;
}
}
}
$select->andWhere("userRole.name = " . $db->quote(USER_ROLES['CLIENT_ADMIN']) . " OR userRole.name = " . $db->quote(USER_ROLES['CLIENT_USER']));
$select->andWhere("customer.oo_id != " . $db->quote($user->getId()));
$select->andWhere("customer.isDeleted != 1 OR customer.isDeleted IS NULL");
$select->andWhere("customer.organization__id IS NOT NULL");
$groupByFields = ['customer.oo_id'];
$hasSorting = false;
// Dynamic sorting logic with orderKey and order
$orderKey = $params['orderKey'] ?? null;
$order = $params['order'] ?? 'asc';
// Validate order parameter
if (!in_array(strtolower($order), ['asc', 'desc'])) {
$order = 'asc';
}
// Map orderKey to database fields
$sortingMap = [
'created' => 'customer.o_creationDate',
'username' => 'customer.name',
'email' => 'customer.email',
'role' => 'userRole.name',
'entityType' => 'organization.clientType',
'packageExpiry' => 'subscription.endDate',
'packageName' => 'localized_package.packageName',
'entityName' => 'localized_organization.name'
];
if ($orderKey && isset($sortingMap[$orderKey])) {
$field = $sortingMap[$orderKey];
// Handle special cases that require joins
if ($orderKey === 'packageName') {
$localizedPackageTable = 'object_localized_packages_' . ($params['lang'] ?? 'en');
$select->leftJoin('package', $localizedPackageTable, 'localized_package', 'localized_package.ooo_id = package.oo_id');
$groupByFields[] = 'localized_package.packageName';
} elseif ($orderKey === 'entityName') {
$localizedOrgTable = 'object_localized_organization_' . ($params['lang'] ?? 'en');
$select->leftJoin('organization', $localizedOrgTable, 'localized_organization', 'localized_organization.ooo_id = organization.oo_id');
$groupByFields[] = 'localized_organization.name';
} else {
$groupByFields[] = $field;
}
$select->orderBy($field, strtoupper($order));
$hasSorting = true;
}
// If no sort param given, apply default sort and group
if (!$hasSorting) {
$select->orderBy('customer.oo_id', 'DESC');
$groupByFields = ['customer.oo_id'];
}
// Final groupBy
$select->groupBy(array_unique($groupByFields));
// dd( $select->getSQL());
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$paginator = $paginator->paginate(
$select,
$page,
$pageSize
);
foreach ($paginator as $usersId) {
$usersData = DataObject\Customer::getById($usersId['oo_id'], true);
if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
// Get Custom Subscription of the organization and package
$customSubscriptions = new DataObject\Subscription\Listing();
$customSubscriptions->filterBySubscribedUser($usersData);
$customSubscriptions->filterByIsActive(true);
$status = "Pending";
if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
if ($customSubscriptions->count() > 0) {
$status = "Active";
} else {
$status = "Suspended";
}
} elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
if ($customSubscriptions->count() > 0) {
$status = "Pending";
} else {
$status = "Suspended";
}
}
$customSubscriptions->filterBySubscriptionType("custom");
$customSubscriptions->setOrderKey("o_modificationDate");
$customSubscriptions->setOrder("desc");
$packageData = [];
$userPackage = null;
if ($customSubscriptions->count() > 0) {
foreach ($customSubscriptions as $key => $customSubscription) {
if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
$package = $customSubscription->getSubscribedPackage();
$userPackage = $package;
if ($package) {
$packageData[] = [
"id" => $package->getId(),
"name" => $package->getPackageName('en'),
"name_ar" => $package->getPackageName('ar'),
"package_expiry" => $customSubscription->getEndDate(date("M d, Y"))
];
}
}
}
}
$permissionObj = $this->getUserPermissionInfo($usersData, $translator);
$userPermissions = $permissionObj['success'] ? $permissionObj['grants'] : null;
$organization = $usersData->getOrganization();
$clientType = $organization ? $organization->getClientType() : '';
$clientTypeArray = [
"key" => $clientType,
'name_en' => $clientType === 'organization' ? 'Entity' : ($clientType ? $translator->trans($clientType, [], null, 'en') : ''),
'name_ar' => $clientType === 'organization' ? 'الجهة' : ($clientType ? $translator->trans($clientType, [], null, 'ar') : ''),
];
$roleArray = [
"key" => ($usersData->getRole()) ? $usersData->getRole()->getName() : null,
'name_en' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'en') : null,
'name_ar' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'ar') : null,
];
// If user is pending, get invitation duration from MannedAlertLog
if ($status === "Pending") {
$invitationDuration = $this->getInvitationDate($usersData);
$statusArray = [
"key" => $status,
'name_en' => $translator->trans($status, [], null, 'en'),
'name_ar' => $translator->trans($status, [], null, 'ar'),
'pendingDuration' => $invitationDuration // Add this field
];
} else {
$statusArray = [
"key" => $status,
'name_en' => $translator->trans($status, [], null, 'en'),
'name_ar' => $translator->trans($status, [], null, 'ar'),
];
}
// $statusArray = [
// "key" => $status,
// 'name_en' => $translator->trans($status, [], null, 'en'),
// 'name_ar' => $translator->trans($status, [], null, 'ar'),
// ];
$userData[] = [
'id' => $usersData->getId(),
'name' => $usersData->getName(),
'title' => $usersData->getTitle(),
'email' => $usersData->getEmail(),
'phone' => $usersData->getPhoneNo(),
'department' => $usersData->getDepartment(),
'role' => $roleArray,
'company_name_en' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName("en") : null,
'company_name_ar' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName("ar") : null,
'packageData' => $packageData,
'organizationId' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getId() : null,
'location' => $this->getLocationList($usersData),
'allowCustomNotification' => ($permissionObj['success'] && isset($userPermissions['get_custom_notification'])) ? $userPermissions['get_custom_notification'] : false,
'allowAddLocation' => ($permissionObj['success'] && isset($userPermissions['create_location'])) ? $userPermissions['create_location'] : false,
'allowForecast' => ($permissionObj['success'] && isset($userPermissions['get_weather'])) ? $userPermissions['get_weather'] : false,
'allowAlertHistoryForCustomAlerts' => ($permissionObj['success'] && isset($userPermissions['alert_history'])) ? $userPermissions['alert_history'] : false,
'automotive' => ($permissionObj['success'] && isset($userPermissions['automotive'])) ? $userPermissions['automotive'] : false,
'aviation' => ($permissionObj['success'] && isset($userPermissions['aviation'])) ? $userPermissions['aviation'] : false,
'shippingAndOffshore' => ($permissionObj['success'] && isset($userPermissions['shipping_and_offshore'])) ? $userPermissions['shipping_and_offshore'] : false,
'insurance' => ($permissionObj['success'] && isset($userPermissions['insurance'])) ? $userPermissions['insurance'] : false,
'energy' => ($permissionObj['success'] && isset($userPermissions['energy'])) ? $userPermissions['energy'] : false,
'client_type' => $clientTypeArray,
'status' => $statusArray,
'createdBy' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
'createdAt' => date('Y-m-d H:i:s', $usersData->getCreationDate()),
'iqamaId' => $usersData->getIqamaId() ? (string) $usersData->getIqamaId() : null,
//'token' => $status == "Pending" ? $usersData->getToken() : '',
'entity_status' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getStatus() : null,
'entity_status_en' => ($usersData->getOrganization() && $usersData->getOrganization()->getStatus()) ? $translator->trans($usersData->getOrganization()->getStatus(), [], null, 'en') : null,
'entity_status_ar' => ($usersData->getOrganization() && $usersData->getOrganization()->getStatus()) ? $translator->trans($usersData->getOrganization()->getStatus(), [], null, 'ar') : null,
'trialLeftDays' => $usersData->getOrganization() ?
\App\Lib\Utility::getTrialLeftDays(
$usersData->getOrganization()->getPackageActivationDate(),
$usersData->getOrganization()->getTrialLimit()
) : null,
'isSMSEnabled' => $organization ? $organization->getIsSMSEnabled() : false,
'SMSLimit' => $userPackage?->getSMSLimit(),
'SMSConsumption' => $organization ? $organization->getSmsConsumption() : 0,
];
if (isset($params['sortByStatus']) && !empty($params['sortByStatus'])) {
$statusFilter = strtoupper($params['sortByStatus']);
usort($userData, function ($a, $b) use ($statusFilter) {
$statusKeyA = $a['status']['key'];
$statusKeyB = $b['status']['key'];
if ($statusFilter === 'ASC') {
if ($statusKeyA === 'Active' && $statusKeyB !== 'Active') {
return -1;
}
if ($statusKeyA !== 'Active' && $statusKeyB === 'Active') {
return 1;
}
} else if ($statusFilter === 'DESC') {
if ($statusKeyA === 'Pending' && $statusKeyB !== 'Pending') {
return -1;
}
if ($statusKeyA !== 'Pending' && $statusKeyB === 'Pending') {
return 1;
}
}
return 0; // They are equal in terms of status priority
});
}
}
}
if (!$paginator->count()) {
return ["success" => false, "message" => $translator->trans("no_user_available_to_this_organization")];
}
return ["success" => TRUE, "data" => $userData, "paginationVariables" => $paginator->getPaginationData()];
// } catch (\Exception $ex) {
// throw new \Exception($ex->getMessage());
// }
return $result;
}
/**
* Get NCM User List
*/
public function getNCMUsers($request, $user, $params, $paginator, $translator)
{
$result = [];
try {
$userData = [];
// if ($user->getOrganization() === null) {
// return ["success" => false, "message" => $translator->trans("organization_does_not_exists")];
// }
// $organizationId = $user->getOrganization()->getId();
// Get All the Classes
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customer = $class->getDao()->getIdByName('Customer');
$subscription = $class->getDao()->getIdByName('Subscription');
$userRole = $class->getDao()->getIdByName('UserRole');
$userTag = $class->getDao()->getIdByName('UserTag');
$organization = $class->getDao()->getIdByName('Organization');
$package = $class->getDao()->getIdByName('Package');
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('customer.oo_id');
$select->from('object_' . $customer, 'customer');
$select->leftJoin('customer', 'object_' . $subscription, 'subscription', 'customer.oo_id = subscription.subscribedUser__id');
$select->leftJoin('subscription', 'object_' . $package, 'package', 'package.oo_id = subscription.subscribedPackage__id');
$select->leftJoin('customer', 'object_' . $organization, 'organization', 'organization.oo_id = customer.organization__id');
$select->leftJoin('customer', 'object_' . $userRole, 'userRole', 'userRole.oo_id = customer.role__id');
$select->leftJoin('customer', 'object_' . $userTag, 'userTage', 'userTage.oo_id = customer.tag__id');
if (isset($params['search']) && !empty($params['search'])) {
$select->andWhere("customer.name LIKE " . $db->quote("%" . $params['search'] . "%") . " OR customer.email LIKE " . $db->quote("%" . $params['search'] . "%"));
}
if (isset($params['searchByTag']) && !empty($params['searchByTag'])) {
$select->andWhere("customer.tag__id = " . $db->quote($params['searchByTag']));
}
$select->andWhere("userRole.name = " . $db->quote(USER_ROLES['NCM_IT']) . " OR userRole.name = " . $db->quote(USER_ROLES['NCM_OPERATOR']));
$select->andWhere("customer.oo_id != " . $db->quote($user->getId()));
$select->andWhere("customer.isDeleted != 1 or customer.isDeleted IS NULL");
//$select->andWhere("organization.oo_id = ".$db->quote($organizationId));
// if (isset($params['status']) && !empty($params['status'])) {
// $statusFilter = ucfirst($params['status']);
// if ($statusFilter == 'Active') {
// $select->andWhere("customer.token IS NULL AND customer.o_published = 1 AND subscription.subscribedUser__id IS NOT NULL");
// } elseif ($statusFilter == 'Suspended') {
// $select->andWhere("customer.token IS NULL AND customer.o_published = 1 AND subscription.subscribedUser__id IS NULL");
// } elseif ($statusFilter == 'Pending') {
// $select->andWhere("customer.token != '' AND customer.o_published = 0");
// }
// }
// Dynamic sorting logic
$orderKey = isset($params['orderKey']) ? $params['orderKey'] : null;
$order = isset($params['order']) ? strtoupper($params['order']) : 'ASC';
// Validate order parameter
if (!in_array(strtoupper($order), ['ASC', 'DESC'])) {
$order = 'ASC';
}
// Map orderKey to database fields
$fieldMapping = [
'username' => 'customer.name',
'email' => 'customer.email',
'userTag' => 'userTage.name',
'createdBy' => 'createdBy.name',
'role' => 'userRole.name',
'status' => 'status', // This will be handled separately as it's computed
'createdOn' => 'customer.o_creationDate'
];
if ($orderKey && isset($fieldMapping[$orderKey])) {
$field = $fieldMapping[$orderKey];
if ($orderKey === 'createdBy') {
$select->leftJoin('customer', 'object_' . $customer, 'createdBy', 'createdBy.oo_id = customer.createdBy__id');
}
if ($orderKey === 'status') {
$needStatusSort = true;
} else {
$select->orderBy($field, $order);
}
} else {
// Default sorting
$select->orderBy('customer.o_creationDate', 'DESC');
}
$select->groupBy(array('oo_id'));
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$paginator = $paginator->paginate(
$select,
$page,
$pageSize
);
foreach ($paginator as $usersId) {
$usersData = DataObject\Customer::getById($usersId['oo_id'], true);
if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
// Get Custom Subscription of the organization and package
$customSubscriptions = new DataObject\Subscription\Listing();
$customSubscriptions->filterBySubscribedUser($usersData);
$customSubscriptions->filterByIsActive(true);
$status = "Pending";
if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
if ($usersData->getPermissionGroups() && count($usersData->getPermissionGroups()) > 0) {
$status = "Active";
} else {
$status = "Suspended";
}
} elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
$status = "Pending";
}
$permissionObj = $this->getUserPermissionInfo($usersData, $translator);
$userPermissions = $permissionObj['success'] ? $permissionObj['grants'] : null;
//$customSubscriptions->filterBySubscriptionType("custom");
$customSubscriptions->setOrderKey("o_modificationDate");
$customSubscriptions->setOrder("desc");
$apiGroupData = [];
$packageData = [];
$assignedApiGroupIds = [];
if ($customSubscriptions->count() > 0) {
foreach ($customSubscriptions as $key => $customSubscription) {
if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
$package = $customSubscription->getSubscribedPackage();
$disallowedApiGroups = $customSubscription->getDisallowedApiGroups();
// get all allowed API Group IDs for the user
$allowedApiGroups = $customSubscription->getAllowedApiGroups();
if (count($allowedApiGroups) > 0) {
foreach ($allowedApiGroups as $allowedApiGroup) {
if ($allowedApiGroup instanceof \Pimcore\Model\DataObject\ApiGroup) {
# code...
$assignedApiGroupIds[] = [
"id" => $allowedApiGroup->getId(),
"name" => $allowedApiGroup->getGroupName(),
];
}
}
}
if ($package) {
$packageData[] = [
"id" => $package->getId(),
"name" => $package->getName(),
"package_expiry" => $customSubscription->getEndDate(date("M d, Y")),
"is_no_expiry" => $customSubscription->getIsNoExpiry() == null ? false : $customSubscription->getIsNoExpiry()
];
$apiGroups = $package->getApiGroups();
if ($apiGroups) {
foreach ($apiGroups as $apiGroup) {
$apiGroupId = $apiGroup->getId();
$apiGroupNameEn = $apiGroup->getApiGroupName('en');
$apiGroupNameAr = $apiGroup->getApiGroupName('ar');
$isDisallowed = false;
// Check if the current API group is disallowed
foreach ($disallowedApiGroups as $disallowedApiGroup) {
if ($apiGroupId == $disallowedApiGroup->getId()) {
$isDisallowed = true;
break;
}
}
// Only add the API group if it's not disallowed
if (!$isDisallowed) {
$apiGroupData[] = [
"id" => $apiGroupId,
"name" => $apiGroupNameEn,
"name_ar" => $apiGroupNameAr
];
}
}
}
}
}
}
}
$typeArray = [
"key" => 'user',
'name_en' => $translator->trans('user', [], null, 'en'),
'name_ar' => $translator->trans('user', [], null, 'ar'),
];
$roleArray = [
"key" => ($usersData->getRole()) ? $usersData->getRole()->getName() : null,
'name_en' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'en') : null,
'name_ar' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'ar') : null,
];
$statusArray = [
"key" => $status,
'name_en' => $translator->trans($status, [], null, 'en'),
'name_ar' => $translator->trans($status, [], null, 'ar'),
];
// Fetch Permission Groups Data
$permissionGroups = $usersData->getPermissionGroups();
$permissionGroupsData = [];
if ($permissionGroups) {
foreach ($permissionGroups as $permissionGroup) {
if ($permissionGroup instanceof \Pimcore\Model\DataObject\PermissionGroup) {
$permissionGroupsData[] = [
'id' => $permissionGroup->getId(),
'nameEn' => $permissionGroup->getName('en'),
'nameAr' => $permissionGroup->getName('ar'),
'descriptionEn' => $permissionGroup->getDescription('en'),
'descriptionAr' => $permissionGroup->getDescription('ar'),
'apiGroups' => array_map(function ($group) {
return ['id' => $group->getId(), 'nameEn' => $group->getApiGroupName('en'), 'nameAr' => $group->getApiGroupName('ar')];
}, $permissionGroup->getApiGroups() ?? []),
];
}
}
}
$userData[] = [
'id' => $usersData->getId(),
'name' => $usersData->getName(),
'title' => $usersData->getTitle(),
'email' => $usersData->getEmail(),
'department' => $usersData->getDepartment(),
'role' => $roleArray,
'organization' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName() : null,
'organizationId' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getId() : null,
'location' => $this->getLocationList($usersData),
'invite_user' => ($permissionObj['success'] && isset($userPermissions['invite_user'])) ? $userPermissions['invite_user'] : false,
'edit_user' => ($permissionObj['success'] && isset($userPermissions['edit_user'])) ? $userPermissions['edit_user'] : false,
'delete_user' => ($permissionObj['success'] && isset($userPermissions['delete_user'])) ? $userPermissions['delete_user'] : false,
'invite_ncm_user' => ($permissionObj['success'] && isset($userPermissions['invite_ncm_user'])) ? $userPermissions['invite_ncm_user'] : false,
'edit_ncm_user' => ($permissionObj['success'] && isset($userPermissions['edit_ncm_user'])) ? $userPermissions['edit_ncm_user'] : false,
'delete_ncm_user' => ($permissionObj['success'] && isset($userPermissions['delete_ncm_user'])) ? $userPermissions['delete_ncm_user'] : false,
'type' => $typeArray,
'status' => $statusArray,
'apiGroups' => $apiGroupData,
'assignedApiGroupIds' => $assignedApiGroupIds,
'packageData' => $packageData,
'createdBy' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
'creationDate' => $usersData->getCreationDate() ? date('Y-m-d', $usersData->getCreationDate()) : null,
'iqamaId' => $usersData->getIqamaId() ? (string) $usersData->getIqamaId() : null,
'tag' => $usersData->getTag() ? ['id' => $usersData->getTag()->getId(), 'name' => $usersData->getTag()->getName()] : null,
'permissionGroupsData' => $permissionGroupsData,
'dualMode' => $usersData->getDualMode() ? true : false,
//'token' => $usersData->getToken(),
];
}
}
if (!$userData) {
return ["success" => false, "message" => $translator->trans("no_user_available_in_NCM")];
}
// Handle status sorting if needed
if (isset($needStatusSort) && $needStatusSort && $orderKey === 'status') {
usort($userData, function ($a, $b) use ($order) {
$statusA = $a['status']['key'];
$statusB = $b['status']['key'];
if ($order === 'ASC') {
return strcmp($statusA, $statusB);
} else {
return strcmp($statusB, $statusA);
}
});
}
return ["success" => TRUE, "data" => $userData, "paginationVariables" => $paginator->getPaginationData()];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Get User List
*/
public function getUsers($request, $user, $translator, $params, $paginator)
{
$result = [];
$userData = [];
try {
if ($user->getOrganization() === null) {
return ["success" => false, "message" => $translator->trans("organization_does_not_exists")];
}
$organizationId = $user->getOrganization()->getId();
// Get All the Classes
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customer = $class->getDao()->getIdByName('Customer');
$subscription = $class->getDao()->getIdByName('Subscription');
$userRole = $class->getDao()->getIdByName('UserRole');
$organization = $class->getDao()->getIdByName('Organization');
$package = $class->getDao()->getIdByName('Package');
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('customer.oo_id');
$select->from('object_' . $customer, 'customer');
$select->innerJoin('customer', 'object_' . $subscription, 'subscription', 'customer.oo_id = subscription.subscribedUser__id');
$select->innerJoin('subscription', 'object_' . $package, 'package', 'package.oo_id = subscription.subscribedPackage__id');
$select->innerJoin('customer', 'object_' . $organization, 'organization', 'organization.oo_id = customer.organization__id');
$select->innerJoin('customer', 'object_' . $userRole, 'userRole', 'userRole.oo_id = customer.role__id');
if (isset($params['search']) && !empty($params['search'])) {
$select->andWhere("customer.name LIKE " . $db->quote("%" . $params['search'] . "%") . " OR customer.email LIKE " . $db->quote("%" . $params['search'] . "%"));
}
$select->andWhere("userRole.name = " . $db->quote(USER_ROLES['CLIENT_ADMIN']) . " OR userRole.name = " . $db->quote(USER_ROLES['CLIENT_USER']));
$select->andWhere("customer.oo_id != " . $db->quote($user->getId()));
$select->andWhere("organization.oo_id = " . $db->quote($organizationId));
$select->andWhere("customer.isDeleted != 1 or customer.isDeleted IS NULL");
if (isset($params['status']) && $params['status'] == true) {
$select->andWhere("customer.o_published = 1");
}
$select->orderBy('oo_id', 'DESC');
$select->groupBy(array('oo_id'));
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$paginator = $paginator->paginate(
$select,
$page,
$pageSize
);
foreach ($paginator as $usersId) {
$usersData = DataObject\Customer::getById($usersId['oo_id'], true);
if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
// Get Custom Subscription of the organization and package
$customSubscriptions = new DataObject\Subscription\Listing();
$customSubscriptions->filterBySubscribedUser($usersData);
$customSubscriptions->filterByIsActive(true);
$status = "Pending";
if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
if ($customSubscriptions->count() > 0) {
$status = "Active";
} else {
$status = "Suspended";
}
} elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
$status = "Pending";
}
$permissionObj = $this->getUserPermissionInfo($usersData, $translator);
$userPermissions = $permissionObj['success'] ? $permissionObj['grants'] : null;
$customSubscriptions->filterBySubscriptionType("custom");
$customSubscriptions->setOrderKey("o_modificationDate");
$customSubscriptions->setOrder("desc");
$apiGroupData = [];
$packageData = [];
$dissAllowedApiGroupID = [];
if ($customSubscriptions->count() > 0) {
foreach ($customSubscriptions as $key => $customSubscription) {
if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
$package = $customSubscription->getSubscribedPackage();
if ($package) {
$packageData[] = [
"id" => $package->getId(),
"name" => $package->getName(),
"package_expiry" => $customSubscription->getEndDate(date("M d, Y"))
];
}
$disallowedApiGroups = $customSubscription->getDisallowedApiGroups();
if (count($disallowedApiGroups) > 0) {
foreach ($disallowedApiGroups as $value) {
$dissAllowedApiGroupID[] = $value->getId();
}
}
if ($package) {
$apiGroups = $package->getApiGroups();
if ($apiGroups) {
foreach ($apiGroups as $apiGroup) {
if (!in_array($apiGroup->getId(), $dissAllowedApiGroupID)) {
$apiGroupData[] = [
"id" => $apiGroup->getId(),
"name" => $apiGroup->getApiGroupName('en'),
"name_ar" => $apiGroup->getApiGroupName('ar')
];
}
}
}
}
}
}
}
$typeArray = [
"key" => 'user',
'name_en' => $translator->trans('user', [], null, 'en'),
'name_ar' => $translator->trans('user', [], null, 'ar'),
];
$roleArray = [
"key" => ($usersData->getRole()) ? $usersData->getRole()->getName() : null,
'name_en' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'en') : null,
'name_ar' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'ar') : null,
];
$statusArray = [
"key" => $status,
'name_en' => $translator->trans($status, [], null, 'en'),
'name_ar' => $translator->trans($status, [], null, 'ar'),
];
$userData[] = [
'id' => $usersData->getId(),
'name' => $usersData->getName(),
'title' => $usersData->getTitle(),
'email' => $usersData->getEmail(),
'phone' => $usersData->getPhoneNo(),
'department' => $usersData->getDepartment(),
'role' => $roleArray,
'organization' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName() : null,
'organizationId' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getId() : null,
'location' => $this->getLocationList($usersData),
'allowCustomNotification' => ($permissionObj['success']) ? $userPermissions['get_custom_notification'] : false,
'allowAddLocation' => ($permissionObj['success']) ? $userPermissions['create_location'] : false,
'allowForecast' => ($permissionObj['success']) ? $userPermissions['get_weather'] : false,
'allowAlertHistoryForCustomAlerts' => ($permissionObj['success']) ? $userPermissions['alert_history'] : false,
'automotive' => ($permissionObj['success']) ? $userPermissions['automotive'] : false,
'aviation' => ($permissionObj['success']) ? $userPermissions['aviation'] : false,
'shippingAndOffshore' => ($permissionObj['success']) ? $userPermissions['shipping_and_offshore'] : false,
'insurance' => ($permissionObj['success']) ? $userPermissions['insurance'] : false,
'energy' => ($permissionObj['success']) ? $userPermissions['energy'] : false,
'type' => $typeArray,
'status' => $statusArray,
'packageData' => $packageData,
'apiGroups' => $apiGroupData,
'createdBy' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
'iqamaId' => $usersData->getIqamaId() ? (string) $usersData->getIqamaId() : null,
//'token' => $status == "Pending" ? $usersData->getToken() : '',
];
}
}
if (!$paginator->count()) {
return ["success" => false, "message" => $translator->trans("no_user_available_to_this_organization.")];
}
return ["success" => TRUE, "data" => $userData, 'paginationVariables' => $paginator->getPaginationData()];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
// /**
// * set package subscription
// */
// public function setPcakageSubscription($params)
// {
// $result = [];
// try {
// $apiGroup = $this->createApiGrpup($params);
// $package = new DataObject\Package();
// $package->setParent(DataObject\Service::createFolderByPath('/UserManagement/Packages/CustomPackages/'));
// $package->setKey(\Pimcore\Model\Element\Service::getValidKey($apiGroup->getId() . time(), 'object'));
// $package->setApiGroups([$apiGroup]);
// $package->setTenure(1);
// $package->setMaxLocation(100);
// $package->setMaxUsers(100);
// $package->setIsActive(true);
// $package->setPublished(true);
// $package->save();
// $subscription = $this->setSubscription($package, $params['user']);
// if ($subscription instanceof DataObject\Subscription) {
// return ["success" => true, "message" => "set_subscription."];
// }
// //return $subscription;
// } catch (\Exception $ex) {
// throw new \Exception($ex->getMessage());
// }
// return $result;
// }
/**
* set create subscription
*/
public function setSubscription($package, $user, $disallowedApiGroupsArray, $subscriptionType, $isNoExpiry = false)
{
$result = [];
try {
if (!$package instanceof DataObject\Package) {
return ["success" => false, "message" => "Package is not available"];
}
if (!$user instanceof DataObject\Customer) {
return ["success" => false, "message" => "User is not available"];
}
$organization = $user->getOrganization();
if (!$organization instanceof DataObject\Organization) {
return ["success" => false, "message" => "Organization is not available"];
}
$packageActivationDate = $organization->getPackageActivationDate();
if (!$packageActivationDate || strtotime($packageActivationDate) === false) {
$packageActivationDate = date('Y-m-d');
} else {
$packageActivationDate = date('Y-m-d', strtotime($packageActivationDate));
}
// Set Subscription Expiry
$subscriptionExpiry = date('Y-m-d', strtotime('+' . $organization->getTrialLimit() . ' days', strtotime($packageActivationDate)));
$subscription = new DataObject\Subscription();
$subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' . $user->getEmail()));
$subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(1000, 10000), 'object'));
$subscription->setSubscribedPackage($package);
$subscription->setSubscribedUser($user);
//Set Disallowed ApiGroups
if ($disallowedApiGroupsArray != null) {
$disallowedApiGroups = [];
foreach ($disallowedApiGroupsArray as $disallowedApiGroupsId) {
$apiGroup = DataObject\APIGroup::getById($disallowedApiGroupsId, true);
$disallowedApiGroups[] = $apiGroup;
}
$subscription->setDisallowedApiGroups($disallowedApiGroups);
}
//$subscription->setDisallowedApis($disAllowPermissions);
$subscription->setSubscriptionType($subscriptionType);
$subscription->setStartDate(Carbon::parse(new \Datetime(date('Y-m-d'))));
$subscription->setEndDate(Carbon::parse(new \Datetime($subscriptionExpiry)));
$subscription->setIsNoExpiry($isNoExpiry);
$subscription->setIsActive(true);
$subscription->setPublished(true);
$subscription->save();
return $subscription;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* set NCM User subscription
*/
public function setNcmUserSubscription($role, $user, $allowedApiGrpups, $isNoExpiry = false)
{
$result = [];
try {
if ($role instanceof DataObject\UserRole) {
$packages = $role->getDefaultPackages();
if ($packages) {
$defaultPackage = $packages[0];
if ($defaultPackage instanceof DataObject\Package) {
$subscription = new DataObject\Subscription();
$subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/NCM Users/' . $user->getEmail()));
$subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($defaultPackage->getId() . time() . uniqid(), 'object'));
$subscription->setSubscribedPackage($defaultPackage);
$subscription->setSubscribedUser($user);
//Set allowed ApiGroups
if ($allowedApiGrpups != null) {
$allowedApiGrpupsArray = [];
foreach ($allowedApiGrpups as $allowedApiGrpupId) {
$apiGroup = DataObject\APIGroup::getById($allowedApiGrpupId, true);
if ($apiGroup) {
$allowedApiGrpupsArray[] = $apiGroup;
}
}
$subscription->setAllowedApiGroups($allowedApiGrpupsArray);
}
$subscriptionExpiry = date('Y-m-d', strtotime('+' . $defaultPackage->getTenure() . ' days'));
$subscription->setSubscriptionType("default");
$subscription->setStartDate(Carbon::parse(new \Datetime(date('Y-m-d'))));
$subscription->setEndDate(Carbon::parse(new \Datetime($subscriptionExpiry)));
$subscription->setIsNoExpiry($isNoExpiry);
$subscription->setIsActive(true);
$subscription->setPublished(true);
$subscription->save();
return $subscription;
}
}
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* set create subscription
*/
public function updateSubscription($package, $user, $disAllowPermissions, $subscriptionType = "custom")
{
$result = [];
try {
if (!$package instanceof DataObject\Package) {
return ["success" => false, "message" => "Package is not available"];
}
if (!$user instanceof DataObject\Customer) {
return ["success" => false, "message" => "User is not available"];
}
$subscriptionExpiry = date('Y-m-d', strtotime('+' . $package->getTenure() . ' days'));
$customSubscriptions = new DataObject\Subscription\Listing();
$customSubscriptions->filterBySubscribedUser($user);
$customSubscriptions->filterBySubscriptionType($subscriptionType);
//$customSubscriptions->filterByIsActive(true);
$updateSubscription = $customSubscriptions->current();
if (!$updateSubscription instanceof DataObject\Subscription) {
$updateSubscription = new DataObject\Subscription();
$updateSubscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' . $user->getEmail()));
$updateSubscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(1000, 10000), 'object'));
$updateSubscription->setStartDate(Carbon::parse(new \Datetime(date('Y-m-d'))));
$updateSubscription->setEndDate(Carbon::parse(new \Datetime($subscriptionExpiry)));
$updateSubscription->setIsActive(true);
$updateSubscription->setSubscriptionType($subscriptionType);
$updateSubscription->setPublished(true);
$updateSubscription->setSubscribedUser($user);
}
$updateSubscription->setSubscribedPackage($package);
if ($subscriptionType == 'default') {
$updateSubscription->setIsNoExpiry(true);
}
$updateSubscription->save();
return $updateSubscription;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Update NCM User Subscription
*/
public function updateNCMUserSubscription($user, $allowedApiGroups)
{
$result = [];
try {
if (!$user instanceof DataObject\Customer) {
return ["success" => false, "message" => "User is not available"];
}
$subscriptionListing = new DataObject\Subscription\Listing();
$subscriptionListing->filterBySubscribedUser($user);
$subscriptionListing->filterByIsActive(true);
// Fetch all active subscriptions
$activeSubscriptions = iterator_to_array($subscriptionListing);
if (count($activeSubscriptions) === 0) {
$defaultPackage = $user->getRole()?->getDefaultPackages()[0] ?? null;
if ($defaultPackage instanceof DataObject\Package) {
$subscription = new DataObject\Subscription();
$subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/NCM Users/' . $user->getEmail()));
$subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($defaultPackage->getId() . time() . uniqid(), 'object'));
$subscription->setSubscribedPackage($defaultPackage);
$subscription->setSubscribedUser($user);
$subscription->setStartDate(Carbon::parse(new \DateTime(date('Y-m-d'))));
// Set end date to one month from today
$subscription->setEndDate(Carbon::now()->addMonth());
$subscription->setIsNoExpiry(true);
$subscription->setIsActive(true);
$subscription->setPublished(false);
$subscription->save();
$activeSubscriptions = [$subscription];
}
}
// Unpublish all active subscriptions except the first one
foreach ($activeSubscriptions as $index => $subscription) {
if ($index > 0) {
$subscription->setPublished(false);
$subscription->save();
}
}
// Update the first subscription if it exists
$updateSubscription = $activeSubscriptions[0] ?? null;
if ($updateSubscription instanceof DataObject\Subscription) {
// Set allowed ApiGroups
if (!empty($allowedApiGroups)) {
$allowedApiGroupsArray = [];
foreach ($allowedApiGroups as $allowedApiGroupId) {
$apiGroup = DataObject\APIGroup::getById($allowedApiGroupId, true);
if ($apiGroup) {
$allowedApiGroupsArray[] = $apiGroup;
}
}
$updateSubscription->setAllowedApiGroups($allowedApiGroupsArray);
}
$updateSubscription->setSubscriptionType("default");
$updateSubscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/NCM Users/' . $user->getEmail()));
$updateSubscription->save();
return $updateSubscription;
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* set package subscription
*/
public function createApiGrpup($params)
{
$result = [];
try {
$mergedArray = [];
if (isset($params['allowAddLocation']) && $params['allowAddLocation'] === true) {
foreach (USER_PERMISSIONS['is_allow_location'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_user']) && $params['is_allow_user'] === true) {
foreach (USER_PERMISSIONS['is_allow_user'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_ncm_user']) && $params['is_allow_ncm_user'] === true) {
foreach (USER_PERMISSIONS['is_allow_ncm_user'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_organization']) && $params['is_allow_organization'] === true) {
foreach (USER_PERMISSIONS['is_allow_organization'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_ncm_organization']) && $params['is_allow_ncm_organization'] === true) {
foreach (USER_PERMISSIONS['is_allow_ncm_organization'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_custom_notification']) && $params['is_allow_custom_notification'] === true) {
foreach (USER_PERMISSIONS['is_allow_custom_notification'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_weather_forecast']) && $params['is_allow_weather_forecast'] === true) {
foreach (USER_PERMISSIONS['is_allow_weather_forecast'] as $key => $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_alert']) && $params['is_allow_alert'] === true) {
foreach (USER_PERMISSIONS['is_allow_alert'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_report']) && $params['is_allow_report'] === true) {
foreach (USER_PERMISSIONS['is_allow_report'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_allow_weather_warnings']) && $params['is_allow_weather_warnings'] === true) {
foreach (USER_PERMISSIONS['is_allow_weather_warnings'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_energy']) && $params['is_energy'] === true) {
foreach (USER_PERMISSIONS['is_energy'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_insurance']) && $params['is_insurance'] === true) {
foreach (USER_PERMISSIONS['is_insurance'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_shippingAndOffshore']) && $params['is_shippingAndOffshore'] === true) {
foreach (USER_PERMISSIONS['is_shippingAndOffshore'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_automotive']) && $params['is_automotive'] === true) {
foreach (USER_PERMISSIONS['is_automotive'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_aviation']) && $params['is_aviation'] === true) {
foreach (USER_PERMISSIONS['is_aviation'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['is_agriculture']) && $params['is_agriculture'] === true) {
foreach (USER_PERMISSIONS['is_agriculture'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['invitingClients']) && $params['invitingClients'] === true) {
foreach (USER_PERMISSIONS['invitingClients'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['managingClients']) && $params['managingClients'] === true) {
foreach (USER_PERMISSIONS['managingClients'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['deletingClients']) && $params['deletingClients'] === true) {
foreach (USER_PERMISSIONS['deletingClients'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['invitingNCMAdmin']) && $params['invitingNCMAdmin'] === true) {
foreach (USER_PERMISSIONS['invitingNCMAdmin'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['managingNCMAdmin']) && $params['managingNCMAdmin'] === true) {
foreach (USER_PERMISSIONS['managingNCMAdmin'] as $value) {
$mergedArray[] = $value;
}
}
if (isset($params['deletingNCMAdmin']) && $params['deletingNCMAdmin'] === true) {
foreach (USER_PERMISSIONS['deletingNCMAdmin'] as $value) {
$mergedArray[] = $value;
}
}
// Get unique values using array_unique()
$uniqueValues = array_unique(array_values($mergedArray));
$userPermission = array_values($uniqueValues);
$apiGroup = new DataObject\APIGroup();
$apiGroup->setParent(DataObject\Service::createFolderByPath('/UserManagement/APIGroups/CustomAPIGroups/'));
$apiGroup->setKey(\Pimcore\Model\Element\Service::getValidKey($userPermission[0] . time(), 'object'));
$apiGroup->setIsActive(true);
$apiGroup->setAllowedApis($userPermission);
$apiGroup->setPublished(true);
$apiGroup->save();
return $apiGroup;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* set User Permissions
*/
public function setUserPermissions($params)
{
$result = [];
try {
// check if all permissions are given than now need to create seperate role
$loggedInUserRole = ($params['loggedInUser']->getRole() ? $params['loggedInUser']->getRole()->getName() : null);
$invitedUserRoleName = ($params['user']->getRole() ? $params['user']->getRole()->getName() : null);
if ($loggedInUserRole == USER_ROLES['NCM_OPERATOR'] || $loggedInUserRole == USER_ROLES['NCM_IT']) {
if ($params['allowCustomNotification'] == true && $params['allowAddLocation'] == true && $params['allowAlertHistoryForCustomAlerts'] == true && $params['allowForecast'] == true && $params['allowOrganizationAdminToInviteUsers'] == true) {
// delete specific role if all permission are given
$permission = DataObject\Permission::getByAllowedUserRole($params['user'], true);
if ($permission instanceof \Pimcore\Model\DataObject\Permission) {
$permission->delete();
}
return ["success" => true, "message" => "Set Permission."];
}
} else {
if (
$params['allowCustomNotification'] == true &&
$params['allowAddLocation'] == true &&
$params['allowAlertHistoryForCustomAlerts'] == true &&
$params['allowForecast'] == true &&
$params['automotive'] == true &&
$params['aviation'] == true &&
$params['insurance'] == true &&
$params['energy'] == true
) {
// delete specific role if all permission are given
$permission = DataObject\Permission::getByAllowedUserRole($params['user'], true);
if ($permission instanceof \Pimcore\Model\DataObject\Permission) {
$permission->delete();
}
return ["success" => true, "message" => "set_permission"];
}
}
$permission = DataObject\Permission::getByAllowedUserRole($params['user'], true);
if ($permission) {
// $permission->setDepartment($allowAlertHistoryForCustomAlerts);
$permission->setAlert_history($params['allowAlertHistoryForCustomAlerts']);
$permission->setGet_custom_notification($params['allowCustomNotification']);
$permission->setCreate_location($params['allowAddLocation']);
$permission->setGet_weather($params['allowForecast']);
// set Industry permissions
$permission->setAutomotive($params['automotive'] == false ? false : true);
$permission->setAviation($params['aviation'] == false ? false : true);
$permission->setShipping_and_offshore($params['shippingAndOffshore'] == false ? false : true);
$permission->setInsurance($params['insurance'] == false ? false : true);
$permission->setEnergy($params['energy'] == false ? false : true);
// default permission on the basis of add location
if (false == $params['allowAddLocation']) {
$permission->setEdit_location(false);
$permission->setDelete_location(false);
$permission->setSearch_location(false);
$permission->setCompare_location(false);
} else {
$permission->setEdit_location(true);
$permission->setDelete_location(true);
$permission->setSearch_location(true);
$permission->setCompare_location(true);
}
// default permission on the basis of add invite user
if ($params['allowOrganizationAdminToInviteUsers'] == true || $invitedUserRoleName == USER_ROLES['CLIENT_ADMIN']) {
$permission->setEdit_user(true);
$permission->setDelete_user(true);
$permission->setList_user(true);
$permission->setSuspend_user(true);
$permission->setInvite_user(true);
$permission->setResend_invite(true);
$permission->setCreate_user(true);
} else {
$permission->setEdit_user(false);
$permission->setDelete_user(false);
$permission->setList_user(false);
$permission->setSuspend_user(false);
$permission->setInvite_user(false);
$permission->setResend_invite(false);
$permission->setCreate_user(false);
}
// default permission to any user
$permission->setGet_profile(true);
$permission->setUpdate_profile(true);
$permission->setChange_password(true);
$permission->setView_user(true);
$permission->setList_location(true);
$permission->setView_location(true);
$permission->setAllowedUserRole($params['user']);
$permission->save();
} else {
$permissions = new DataObject\Permission();
$permissions->setParent(DataObject\Service::createFolderByPath('/UserManagement/Permission/User'));
$permissions->setKey($params['user']->getEmail());
// $permissions->setDepartment($allowAlertHistoryForCustomAlerts);
$permissions->setAlert_history($params['allowAlertHistoryForCustomAlerts']);
$permissions->setGet_custom_notification($params['allowCustomNotification']);
$permissions->setInvite_user($params['allowOrganizationAdminToInviteUsers']);
$permissions->setCreate_location($params['allowAddLocation']);
$permissions->setGet_weather($params['allowForecast']);
// set Industry permissions
$permissions->setAutomotive($params['automotive'] == false ? false : true);
$permissions->setAviation($params['aviation'] == false ? false : true);
$permissions->setShipping_and_offshore($params['shippingAndOffshore'] == false ? false : true);
$permissions->setInsurance($params['insurance'] == false ? false : true);
$permissions->setEnergy($params['energy'] == false ? false : true);
// default permission on the basis of add location
if ($params['allowAddLocation'] == true) {
$permissions->setEdit_location(true);
$permissions->setDelete_location(true);
$permissions->setSearch_location(true);
$permissions->setCompare_location(true);
} else {
$permissions->setEdit_location(false);
$permissions->setDelete_location(false);
$permissions->setSearch_location(false);
$permissions->setCompare_location(false);
}
// default permission on the basis of add invite user
if ($params['allowOrganizationAdminToInviteUsers'] == true || $invitedUserRoleName == USER_ROLES['CLIENT_ADMIN']) {
$permissions->setEdit_user(true);
$permissions->setDelete_user(true);
$permissions->setList_user(true);
$permissions->setSuspend_user(true);
$permissions->setInvite_user(true);
$permissions->setResend_invite(true);
$permissions->setCreate_user(true);
} else {
$permissions->setEdit_user(false);
$permissions->setDelete_user(false);
$permissions->setList_user(false);
$permissions->setSuspend_user(false);
$permissions->setInvite_user(false);
$permissions->setResend_invite(false);
$permissions->setCreate_user(false);
}
// default permission to any user
$permissions->setGet_profile(true);
$permissions->setUpdate_profile(true);
$permissions->setChange_password(true);
$permissions->setView_user(true);
$permissions->setList_location(true);
$permissions->setView_location(true);
$permissions->setAllowedUserRole($params['user']);
$permissions->setPublished(true);
$permissions->save();
}
return ["success" => true, "message" => "set_permission."];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* set NCM Admin User Permissions
*/
public function setNCMAdminUserPermissions($params)
{
$result = [];
try {
if ($params['invitingClients'] == false || $params['managingClients'] == false || $params['deletingClients'] == false || $params['invitingNCMAdmin'] == false || $params['managingNCMAdmin'] == false || $params['deletingNCMAdmin'] == false) {
$permission = DataObject\Permission::getByAllowedUserRole($params['user'], true);
if ($permission) {
// default permission to any user
$permission->setGet_profile(true);
$permission->setUpdate_profile(true);
$permission->setChange_password(true);
$permission->setView_user(true);
$permission->setList_location(true);
$permission->setView_location(true);
$permission->setEdit_location(true);
$permission->setDelete_location(true);
$permission->setSearch_location(true);
$permission->setCompare_location(true);
$permission->setList_ncm_user(true);
$permission->setList_user(true);
// set Industry permissions
$permission->setAutomotive(true);
$permission->setAviation(true);
$permission->setShipping_and_offshore(true);
$permission->setInsurance(true);
$permission->setEnergy(true);
// set invitingClients permissions
$permission->setInvite_user($params['invitingClients'] == false ? false : true);
$permission->setInvite_organization($params['invitingClients'] == false ? false : true);
$permission->setResend_invite($params['invitingClients'] == false ? false : true);
// set managingClients permissions
$permission->setEdit_user($params['managingClients'] == false ? false : true);
// set deletingClients permissions
$permission->setDelete_user($params['deletingClients'] == false ? false : true);
// set invitingNCMAdmin permissions
$permission->setInvite_ncm_user($params['invitingNCMAdmin'] == false ? false : true);
// set managingNCMAdmin permissions
$permission->setEdit_ncm_user($params['managingNCMAdmin'] == false ? false : true);
// set deletingNCMAdmin permissions
$permission->setDelete_ncm_user($params['deletingNCMAdmin'] == false ? false : true);
$permission->setAllowedUserRole($params['user']);
$permission->save();
} else {
$permissions = new DataObject\Permission();
$permissions->setParent(DataObject\Service::createFolderByPath('/UserManagement/Permission/User'));
$permissions->setKey($params['user']->getEmail());
// $permissions->setDepartment($allowAlertHistoryForCustomAlerts);
// default permission to any user
$permissions->setGet_profile(true);
$permissions->setUpdate_profile(true);
$permissions->setChange_password(true);
$permissions->setView_user(true);
$permissions->setList_location(true);
$permissions->setView_location(true);
$permissions->setList_ncm_user(true);
$permissions->setList_user(true);
// set Industry permissions
$permissions->setAutomotive(true);
$permissions->setAviation(true);
$permissions->setShipping_and_offshore(true);
$permissions->setInsurance(true);
$permissions->setEnergy(true);
// set invitingClients permissions
$permissions->setInvite_user($params['invitingClients'] == false ? false : true);
$permissions->setInvite_organization($params['invitingClients'] == false ? false : true);
$permissions->setResend_invite($params['invitingClients'] == false ? false : true);
// set managingClients permissions
$permissions->setEdit_user($params['managingClients'] == false ? false : true);
// set deletingClients permissions
$permissions->setDelete_user($params['deletingClients'] == false ? false : true);
// set invitingNCMAdmin permissions
$permissions->setInvite_ncm_user($params['invitingNCMAdmin'] == false ? false : true);
// set managingNCMAdmin permissions
$permissions->setEdit_ncm_user($params['managingNCMAdmin'] == false ? false : true);
// set deletingNCMAdmin permissions
$permissions->setDelete_ncm_user($params['deletingNCMAdmin'] == false ? false : true);
$permissions->setAllowedUserRole($params['user']);
$permissions->setPublished(true);
$permissions->save();
}
return ["success" => true, "message" => "set_permission"];
} else {
// delete specific role if all permission are given
$permission = DataObject\Permission::getByAllowedUserRole($params['user'], true);
if ($permission instanceof \Pimcore\Model\DataObject\Permission) {
$permission->delete();
}
return ["success" => true, "message" => "set_permission"];
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function getUserPermissionInfo($user, $translator)
{
$userEmail = [];
$userEmail['username'] = $user->getEmail();
// return $permission = DataObject\Permission::getByAllowedUserRole($user, true);
return $permission = $this->userPermission->getUserPermissions($userEmail, $translator);
}
public function getLocationList($user)
{
try {
$entries = new DataObject\Location\Listing();
$entries->setCondition("user LIKE " . $entries->quote("%," . $user->getId() . ",%"));
$entries->load();
$tempArr = [];
if (!empty($entries)) {
foreach ($entries as $object) {
array_push($tempArr, $object->getId());
}
}
return $tempArr;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
public function assignLocationToUser($loggedInUser, $locationIds, $locationTagIds, $targetUsers, $targetUserGroups, $weatherSevereAlert, $customNotificationAlert, $translator)
{
$assignedLocationArr = [];
// Validate all users and user groups upfront
$validatedUsers = [];
if ($targetUsers) {
foreach ($targetUsers as $userId) {
$user = \Pimcore\Model\DataObject::getById($userId);
if (!$user instanceof Customer) {
return ["success" => false, "message" => $translator->trans("Invalid User ID"), "userId" => $userId];
}
$organizationMatch = \App\Lib\Utility::matchOrganization($user, $loggedInUser);
if (!$organizationMatch["success"]) {
return ["success" => false, "message" => $translator->trans("User ID does not belong to your organization."), "userId" => $userId];
}
$validatedUsers[] = $user;
}
}
$validatedUserGroups = [];
if ($targetUserGroups) {
foreach ($targetUserGroups as $userGroupId) {
$userGroup = \Pimcore\Model\DataObject::getById($userGroupId);
if (!$userGroup instanceof UserGroup) {
return ["success" => false, "message" => $translator->trans("Invalid User Group ID"), "userGroupId" => $userGroupId];
}
$targetUsersInGroup = new DataObject\Customer\Listing();
$targetUsersInGroup->filterByUserGroup($userGroup);
foreach ($targetUsersInGroup as $user) {
$organizationMatch = \App\Lib\Utility::matchOrganization($user, $loggedInUser);
if (!$organizationMatch["success"]) {
return ["success" => false, "message" => $translator->trans("A user in group ID does not belong to your organization."), "userGroupId" => $userGroupId];
}
}
$validatedUserGroups[] = $userGroup;
}
}
// Process Locations by Location IDs
if ($locationIds) {
foreach ($locationIds as $locationID) {
$location = \Pimcore\Model\DataObject::getById($locationID);
if ($location instanceof Location) {
// Assign to validated users
foreach ($validatedUsers as $user) {
$this->locationModel->locationMetaData($location, $user, $weatherSevereAlert, $customNotificationAlert);
$assignedLocationArr[] = $location->getId();
}
// Assign to validated user groups
foreach ($validatedUserGroups as $userGroup) {
$targetUsersInGroup = new DataObject\Customer\Listing();
$targetUsersInGroup->filterByUserGroup($userGroup);
foreach ($targetUsersInGroup as $user) {
$this->locationModel->locationMetaData($location, $user, $weatherSevereAlert, $customNotificationAlert);
$assignedLocationArr[] = $location->getId();
}
}
} else {
return ["success" => false, "message" => $translator->trans("Invalid Location ID"), "locationId" => $locationID];
}
}
}
// Process Locations by Location Tag IDs
if ($locationTagIds) {
foreach ($locationTagIds as $locationTagId) {
$locationTag = \Pimcore\Model\DataObject::getById($locationTagId);
if ($locationTag instanceof Tags) {
$locations = new DataObject\Location\Listing();
$locations->setCondition("Tag LIKE " . $locations->quote("%," . $locationTag->getId() . ",%"));
$locations->load();
foreach ($locations as $location) {
if ($location instanceof Location) {
// Assign to validated users
foreach ($validatedUsers as $user) {
$this->locationModel->locationMetaData($location, $user, $weatherSevereAlert, $customNotificationAlert);
$assignedLocationArr[] = $location->getId();
}
// Assign to validated user groups
foreach ($validatedUserGroups as $userGroup) {
$targetUsersInGroup = new DataObject\Customer\Listing();
$targetUsersInGroup->filterByUserGroup($userGroup);
foreach ($targetUsersInGroup as $user) {
$this->locationModel->locationMetaData($location, $user, $weatherSevereAlert, $customNotificationAlert);
$assignedLocationArr[] = $location->getId();
}
}
}
}
} else {
return ["success" => false, "message" => $translator->trans("Invalid Location Tag ID"), 'locationId' => $locationTagId];
}
}
}
return array_values(array_unique($assignedLocationArr));
}
public function getUserLocations($user)
{
try {
$locationData = [];
$locations = $this->getLocationList($user);
if ($locations) {
foreach ($locations as $locationId) {
$location = \Pimcore\Model\DataObject::getById($locationId);
if ($location instanceof Location) {
$alertConfig = $this->locationModel->getUserSevereAlertAndCustomNotification($location, $user);
$locationData[] = [
'id' => $location->getId(),
'name' => $location->getName(),
'title' => $location->getTitle(),
'coordinates' => $location->getCoordinates(),
'severeWeatherAlert' => isset($alertConfig['get_severe_alert']) && ($alertConfig['get_severe_alert'] == true) ?? false,
'customNotificationAlert' => isset($alertConfig['get_custom_notification']) && ($alertConfig['get_custom_notification'] == true) ?? false,
];
}
}
}
return $locationData;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
public function getUsersLocationByOrganizationId($organizationId)
{
// try {
$organization = \Pimcore\Model\DataObject::getById($organizationId);
if (!$organization instanceof \Pimcore\Model\DataObject\Organization) {
throw new \Exception("Organization not found");
}
$customers = new \Pimcore\Model\DataObject\Customer\Listing();
$customers->filterByOrganization($organization);
if ($customers->getCount() == 0) {
throw new \Exception("Customers does not exists in this organization");
}
$locationData = [];
foreach ($customers as $customer) {
$locations = $this->getLocationList($customer);
if ($locations) {
foreach ($locations as $locationId) {
$location = \Pimcore\Model\DataObject::getById($locationId);
if ($location instanceof Location) {
$alertConfig = $this->locationModel->getUserSevereAlertAndCustomNotification($location, $customer);
$locationData[] = [
'id' => $location->getId(),
'name' => $location->getName(),
'title' => $location->getTitle(),
'coordinates' => $location->getCoordinates(),
'severeWeatherAlert' => isset($alertConfig['get_severe_alert']) && ($alertConfig['get_severe_alert'] == true) ?? false,
'customNotificationAlert' => isset($alertConfig['get_custom_notification']) && ($alertConfig['get_custom_notification'] == true) ?? false,
"customerId" => $customer->getId(),
"customerName" => $customer->getName(),
"customerEmail" => $customer->getEmail()
];
}
}
}
}
return $locationData;
// } catch (\Exception $ex) {
// throw new \Exception($ex->getMessage());
// }
}
/**
* Get User Assigned API Groups
*
*/
public function getUserApiGroups($user)
{
$apiGroups = [];
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($user);
$currentDate = date('Y-m-d'); // Assuming the date and time format is 'YYYY-MM-DD'
$subscriptions->filterByEndDate(strtotime($currentDate), ">=");
$subscriptions->filterBySubscriptionType("custom");
$subscriptions->filterByIsActive(true);
$subscriptions->load();
foreach ($subscriptions as $subscription) {
$package = $subscription->getSubscribedPackage();
if ($package instanceof DataObject\Package) {
if ($package->getApiGroups()) {
foreach ($package->getApiGroups() as $key => $ApiGroup) {
$apiGroups[] = [
"apiGroupId" => $ApiGroup->getId(),
"type" => $ApiGroup->getApiGroupType(),
"name" => $ApiGroup->getApiGroupName('en'),
"name_ar" => $ApiGroup->getApiGroupName('ar'),
];
}
}
}
}
return $apiGroups;
}
/**
* generate unsubscribe token user
*/
public function unSubscribeGenerateToken($email)
{
$token = '';
try {
//generate token
$user = DataObject\Customer::getByEmail($email, true);
// $token = md5($user->getEmail() . time() . uniqid());
$token = base64_encode($user->getEmail() . time() . uniqid());
$user->setunSubscribeToken($token);
$user->save();
return $token;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $token;
}
/**
* generate unsubscribe ews notification token user
*/
public function unSubscribeEwsGenerateToken($email)
{
$token = '';
try {
//generate token
$user = DataObject\Customer::getByEmail($email, true);
// $token = md5($user->getEmail() . time() . uniqid());
$token = base64_encode($user->getEmail() . time() . uniqid());
$user->setEwsNotificationToken($token);
$user->save();
return $token;
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $token;
}
/**
* Get NCM User List
*/
public function getAllActiveUsersInExcelData($params, $user, $translator)
{
$result = [];
try {
$userDataEn = [];
// Get All the Classes
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customer = $class->getDao()->getIdByName('Customer');
$subscription = $class->getDao()->getIdByName('Subscription');
$userRole = $class->getDao()->getIdByName('UserRole');
$organization = $class->getDao()->getIdByName('Organization');
$package = $class->getDao()->getIdByName('Package');
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('customer.oo_id');
$select->from('object_' . $customer, 'customer');
$select->innerJoin('customer', 'object_' . $subscription, 'subscription', 'customer.oo_id = subscription.subscribedUser__id');
$select->innerJoin('subscription', 'object_' . $package, 'package', 'package.oo_id = subscription.subscribedPackage__id');
$select->innerJoin('customer', 'object_' . $organization, 'organization', 'organization.oo_id = customer.organization__id');
$select->innerJoin('customer', 'object_' . $userRole, 'userRole', 'userRole.oo_id = customer.role__id');
// if (isset($params['search']) && !empty($params['search'])) {
// $select->andWhere("customer.name LIKE " . $db->quote("%" . $params['search'] . "%") . " OR customer.email LIKE " . $db->quote("%" . $params['search'] . "%"));
// }
if (isset($params['type']) && !empty($params['type'])) {
if ($params['type'] == 'client') {
$select->andWhere("userRole.name = " . $db->quote(USER_ROLES['CLIENT_ADMIN']) . " OR userRole.name = " . $db->quote(USER_ROLES['CLIENT_USER']));
} elseif ($params['type'] == 'ncm') {
$select->andWhere("userRole.name = " . $db->quote(USER_ROLES['NCM_IT']) . " OR userRole.name = " . $db->quote(USER_ROLES['NCM_OPERATOR']));
}
}
$select->andWhere("customer.oo_id != " . $db->quote($user->getId()));
$select->andWhere("customer.isDeleted != 1 or customer.isDeleted IS NULL");
if (!empty($params["entityId"])) {
$select->andWhere("organization.oo_id = " . $db->quote($params["entityId"]));
}
$select->orderBy('oo_id', 'DESC');
$select->groupBy(array('oo_id'));
$select = $select->execute();
$usersIds = $select->fetchAllAssociative();
if (count($usersIds) == 0) {
return ["success" => false, "message" => $translator->trans("no_user_available_in_NCM")];
}
$userDataEn[] = [
'S. No' => 'S. No',
'Username' => 'Username',
'Entity' => 'Entity',
'Entity AR' => 'Entity AR',
'Email Address' => 'Email Address',
'Type' => 'Type',
'Role' => 'Role',
'Created By' => 'Created By',
'Created On' => 'Created On',
'Package' => 'Package',
'Package Expiry' => 'Package Expiry',
'Status' => 'Status',
];
foreach ($usersIds as $userKey => $usersId) {
$usersData = DataObject\Customer::getById($usersId['oo_id'], true);
if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
// Get Custom Subscription of the organization and package
$customSubscriptions = new DataObject\Subscription\Listing();
$customSubscriptions->filterBySubscribedUser($usersData);
$customSubscriptions->filterByIsActive(true);
$status = "";
if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
if ($customSubscriptions->count() > 0) {
$status = "Active";
} else {
$status = "Suspended";
}
} elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
$status = "Pending";
}
$permissionObj = $this->getUserPermissionInfo($usersData, $translator);
$userPermissions = $permissionObj['success'] ? $permissionObj['grants'] : null;
$customSubscriptions->filterBySubscriptionType("custom");
$customSubscriptions->setOrderKey("o_modificationDate");
$customSubscriptions->setOrder("desc");
$apiGroupData = [];
$packageData = [];
if ($customSubscriptions->count() > 0) {
foreach ($customSubscriptions as $key => $customSubscription) {
if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
$package = $customSubscription->getSubscribedPackage();
$disallowedApiGroups = $customSubscription->getDisallowedApiGroups();
if ($package) {
$packageData[] = [
"id" => $package->getId(),
"name" => $package->getPackageName("en"),
"package_expiry" => $customSubscription->getEndDate(date("M d, Y"))
];
$apiGroups = $package->getApiGroups();
if ($apiGroups) {
foreach ($apiGroups as $apiGroup) {
$apiGroupId = $apiGroup->getId();
$apiGroupNameEn = $apiGroup->getApiGroupName('en');
$apiGroupNameAr = $apiGroup->getApiGroupName('ar');
$isDisallowed = false;
// Check if the current API group is disallowed
foreach ($disallowedApiGroups as $disallowedApiGroup) {
if ($apiGroupId == $disallowedApiGroup->getId()) {
$isDisallowed = true;
break;
}
}
// Only add the API group if it's not disallowed
if (!$isDisallowed) {
$apiGroupData[] = [
"id" => $apiGroupId,
"name" => $apiGroupNameEn,
"name_ar" => $apiGroupNameAr
];
}
}
}
}
}
}
}
$userDataEn[] = [
'S. No' => $userKey + 1,
'Username' => $usersData->getName(),
'Entity' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName() : null,
'Entity AR' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName('ar') : null,
'Email Address' => $usersData->getEmail(),
'Type' => $translator->trans('user', [], null, 'en'),
'Role' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null, 'en') : null,
'Created By' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
'Created On' => $usersData->getCreationDate() ? date('Y-m-d', $usersData->getCreationDate()) : null,
'Package' => isset($packageData[0]['name']) ? $packageData[0]['name'] : null,
'Package Expiry' => isset($packageData[0]['package_expiry']) ? date("M d, Y", strtotime($packageData[0]['package_expiry'])) : null,
'Status' => $translator->trans($status, [], null, 'en'),
];
}
}
$excelData = ExcelGenerator::createAndSaveXlsx($userDataEn, $params['type'] . "_users_data", true, '/users/excel/');
return ["success" => true, "message" => $translator->trans("excel_generated"), "data" => $excelData];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
public function createWsoUser($name, $email, $translator): array
{
try {
Utility::validateEmail($email);
Utility::validateName($name);
$user = DataObject\Customer::getByEmail($email, true);
if ($user instanceof \Pimcore\Model\DataObject\Customer) {
return ["success" => false, "message" => $translator->trans("user_already_exists")];
}
$registerUser = new DataObject\Customer();
$registerUser->setParent(DataObject\Service::createFolderByPath('/UserManagement/WsoUsers'));
$registerUser->setKey(trim(strip_tags($email)));
$registerUser->setUserType('public');
$registerUser->setName(strip_tags($name));
$registerUser->setEmail(trim(strip_tags($email)));
$registerUser->setPublished(true);
$registerUser->setIsActive(true);
$registerUser->setSendEwsEmail(false);
$registerUser->setOmitMandatoryCheck(true);
$registerUser->save();
return ["success" => true, "message" => $translator->trans("user_registered_success"), 'data' => $registerUser->getId()];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return [];
}
/**
* Create User Tag
*/
public function createUserTag($user, $name, $request, $lang, $translator, $organization = false)
{
$result = [];
try {
$userTag = new DataObject\UserTag();
if ($organization) {
$userTag->setParent(DataObject\Service::createFolderByPath('/Organization/tags/'));
} else {
$userTag->setParent(DataObject\Service::createFolderByPath('/UserManagement/user tags/'));
}
$userTag->setKey(\Pimcore\Model\Element\Service::getValidKey($name . '_' . uniqid(), 'object'));
$userTag->setName(strip_tags($name));
$userTag->setOrganization($organization);
$userTag->setPublished(true);
$userTag->save();
if ($userTag) {
return ["success" => true, "message" => $translator->trans("user_tag_created_successfully"), "user_tag_id" => $userTag->getId()];
}
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* User Tag Listing
*/
public function userTagListing($user, $translator, $paginator, $params)
{
$result = [];
try {
$tagData = [];
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$tagList = new DataObject\UserTag\Listing();
// Check if organization parameter is set and not empty
if (isset($params['organization']) && !empty($params['organization'])) {
$organization = $params['organization'];
$tagList->setCondition("organization = true");
} else {
$tagList->setCondition("(organization = false OR organization is null)");
}
if (isset($params['search']) && !empty($params['search'])) {
$tagList->setCondition("name LIKE " . $tagList->quote("%" . $params['search'] . "%"));
}
$allowed = [
'name'
];
if ($params['sortBy'] && in_array($params['sortBy'], $allowed, true)) {
$tagList->setOrderKey($params['sortBy']);
$tagList->setOrder($params['sortDir'] === 'DESC' ? 'DESC' : 'ASC');
}
$paginator = $paginator->paginate(
$tagList,
$page,
$pageSize
);
if ($paginator->getTotalItemCount() > 0) {
foreach ($paginator as $key => $tag) {
$tagData[] = [
'id' => $tag->getId(),
'name' => $tag->getName()
];
}
if (!empty($tagData) && count($tagData) > 0) {
return ["success" => true, "data" => $tagData, "paginationVariables" => $paginator->getPaginationData()];
}
}
return ["success" => false, "message" => $translator->trans("user_groups_are_not_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Validate the unsubscribe token
*
* @param string $token
* @param Translator $translator
* @return array
*/
public function unsubscribeTokenValidate($token, $translator)
{
// Fetch user by unsubscribe token
$user = Customer::getByUnSubToken($token, true);
if (!$user) {
return [
"success" => false,
"message" => $translator->trans("invalid_token")
];
}
// Prepare the data
$data = [
"success" => true,
"id" => $user->getId(),
"email" => $user->getEmail(),
"customNotification" => $user->getCustomNotification(),
"earlyWarningNotification" => $user->getEarlyWarningNotification(),
"advanceCustomNotification" => $user->getAdvanceCustomNotification(),
"severeWeatherAlert" => $user->getSevereWeatherAlert()
];
return $data;
}
/**
* update user Subscription
*
* @param string $params
* @param Translator $translator
* @return array
*/
public function updateUserSubscription($params, $translator)
{
// Fetch user by unsubscribe token
$user = Customer::getById($params['id'], true);
if (!$user) {
return [
"success" => false,
"message" => $translator->trans("invalid_user_id")
];
}
if (isset($params['customNotification'])) {
$user->setCustomNotification($params['customNotification']);
}
if (isset($params['earlyWarningNotification'])) {
$user->setEarlyWarningNotification($params['earlyWarningNotification']);
}
if (isset($params['advanceCustomNotification'])) {
$user->setAdvanceCustomNotification($params['advanceCustomNotification']);
}
if (isset($params['severeWeatherAlert'])) {
$user->setSevereWeatherAlert($params['severeWeatherAlert']);
}
$user->save();
// Prepare the data
$data = [
"success" => true,
"message" => $translator->trans("subscription_updated")
];
return $data;
}
public function saveBulkUserInviteLog($user, $data, $organizationId)
{
$bulkUserInviteLog = new DataObject\BulkInviteUserReport();
$bulkUserInviteLog->setParent(DataObject\Service::createFolderByPath('/UserManagement/BulkUserInviteLog'));
$bulkUserInviteLog->setKey(\Pimcore\Model\Element\Service::getValidKey(uniqid(), 'object'));
$bulkUserInviteLog->setPublished(true);
$bulkUserInviteLog->setJsonData(json_encode($data));
$organization = DataObject\Organization::getById($organizationId);
if ($organization) {
$bulkUserInviteLog->setOrganization($organization);
}
$bulkUserInviteLog->setCreatedBy($user);
$bulkUserInviteLog->save();
return $bulkUserInviteLog;
}
public function getEntitySubscription($user)
{
$package = null;
$subscriptions = new Subscription\Listing();
$subscriptions->filterBySubscribedUser($user);
$subscriptions->filterBySubscriptionType("custom");
$subscription = $subscriptions->current();
return $subscription;
}
public function getEntityPackage($user)
{
$package = null;
$subscriptions = new Subscription\Listing();
$subscriptions->filterBySubscribedUser($user);
$subscriptions->filterBySubscriptionType("custom");
$subscription = $subscriptions->current();
if ($subscription) {
$package = $subscription->getSubscribedPackage();
}
return $package;
}
private function getInvitationDate($user): string
{
try {
$token = $user->getToken();
if (empty($token)) {
$creationDate = $user->getCreationDate();
if ($creationDate) {
return date('Y-m-d H:i:s', $creationDate);
}
return "Unknown";
}
$tokenParts = explode('.', $token);
if (count($tokenParts) !== 3) {
$creationDate = $user->getCreationDate();
if ($creationDate) {
return date('Y-m-d H:i:s', $creationDate);
}
return "Invalid token";
}
$payload = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $tokenParts[1])), true);
if (!$payload || !isset($payload['time'])) {
$creationDate = $user->getCreationDate();
if ($creationDate) {
return date('Y-m-d H:i:s', $creationDate);
}
return "No invitation time found";
}
$invitationTime = $payload['time'];
return date('Y-m-d H:i:s', $invitationTime);
} catch (\Exception $e) {
$creationDate = $user->getCreationDate();
if ($creationDate) {
return date('Y-m-d H:i:s', $creationDate);
}
return "Error getting date";
}
}
public function listC2Users($params, $translator)
{
try {
$userData = [];
// Get class IDs for table names
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customerClassId = $class->getDao()->getIdByName('Customer');
$subscriptionClassId = $class->getDao()->getIdByName('Subscription');
$packageClassId = $class->getDao()->getIdByName('Package');
$db = Db::get();
$select = $db->createQueryBuilder();
// Select customer data and subscription/package info
$select->select([
'customer.oo_id AS customer_id',
'customer.name AS customer_name',
'customer.email AS customer_email',
'customer.phoneNo AS customer_phone',
'subscription.oo_id AS subscription_id',
'subscription.isActive AS subscription_is_active',
'subscription.endDate AS subscription_end_date',
'subscription.subscriptionType AS subscription_type'
]);
$select->from('object_' . $customerClassId, 'customer');
// INNER JOIN with Subscription to get only customers with subscriptions
// Then filter by active subscriptions
$select->innerJoin(
'customer',
'object_' . $subscriptionClassId,
'subscription',
'customer.oo_id = subscription.subscribedUser__id'
);
// Apply filters
// Phone number must exist and be exactly 9 digits
$select->where("customer.phoneNo IS NOT NULL AND customer.phoneNo != '' AND CHAR_LENGTH(customer.phoneNo) = 9");
// Customer must be published
$select->andWhere("customer.o_published = 1");
// Only active subscriptions
$select->andWhere("subscription.isActive = 1");
// Only 'custom' subscription type (matching the commented code pattern)
$select->andWhere("subscription.subscriptionType = " . $db->quote('custom'));
// Only subscriptions with end date in future (or no expiry)
// Pimcore stores dates as Unix timestamps, so compare with current timestamp
$currentTimestamp = time();
$select->andWhere("(subscription.endDate IS NULL OR subscription.endDate >= " . $currentTimestamp . ")");
// Execute query
$results = $select->execute()->fetchAllAssociative();
// Process results
foreach ($results as $row) {
// Parse endDate - Pimcore stores dates as Unix timestamps
$packageExpiry = null;
if (!empty($row['subscription_end_date'])) {
try {
// Check if it's a Unix timestamp (numeric) or date string
if (is_numeric($row['subscription_end_date'])) {
// Unix timestamp - use @ prefix to parse
$date = new \DateTime('@' . $row['subscription_end_date']);
$date->setTimezone(new \DateTimeZone('Asia/Riyadh'));
$packageExpiry = $date->format('M d, Y');
} else {
// Date string - parse directly
$date = new \DateTime($row['subscription_end_date']);
$packageExpiry = $date->format('M d, Y');
}
} catch (\Exception $e) {
// If parsing fails, log and continue
error_log('Error parsing subscription end date: ' . $e->getMessage() . ' - Value: ' . $row['subscription_end_date']);
$packageExpiry = null;
}
}
$userData[] = [
'id' => (int) $row['customer_id'],
'name' => $row['customer_name'] ?? '',
'email' => $row['customer_email'] ?? '',
'phoneNumber' => '+966' . $row['customer_phone'],
'package_expiry' => $packageExpiry,
'status' => $row['subscription_is_active'] ? 'Active' : 'Suspended',
];
}
return ["success" => true, "data" => $userData];
} catch (\Exception $e) {
error_log('Error in listC2Users: ' . $e->getMessage());
return ["success" => false, "error" => $e->getMessage(), "data" => []];
}
}
/**
* List user groups with simplified response (groupid, name, user_ids)
* Only includes users with mobile numbers (like listC2Users logic)
*/
public function listUserGroupsSimple($user, $translator): array
{
try {
$organization = $user->getOrganization();
if (!$organization instanceof DataObject\Organization) {
return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_organization")];
}
// Get class IDs for table names
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customerClassId = $class->getDao()->getIdByName('Customer');
$subscriptionClassId = $class->getDao()->getIdByName('Subscription');
$db = Db::get();
// Load UserGroup listing
$userGroupList = new DataObject\UserGroup\Listing();
$userGroupList->filterByOrganization($organization);
$userGroupList->setOrderKey("oo_id");
$userGroupList->setOrder("desc");
$userGroupListData = [];
foreach ($userGroupList as $userGroup) {
$groupId = $userGroup->getId();
// Use direct SQL to find users in this group
// Pimcore stores userGroup as comma-separated string: ",398039,398040,"
$select = $db->createQueryBuilder();
$select->select(['customer.oo_id AS customer_id', 'customer.phoneNo AS phone_no']);
$select->from('object_' . $customerClassId, 'customer');
// Filter by user group - format is ",groupId," to match exact group ID
$select->where("customer.userGroup LIKE :groupIdPattern");
$select->setParameter('groupIdPattern', '%,' . $groupId . ',%');
// Join with subscription to filter active subscriptions
$select->innerJoin(
'customer',
'object_' . $subscriptionClassId,
'subscription',
'customer.oo_id = subscription.subscribedUser__id'
);
// Apply mobile number filter (same as listC2Users)
$select->andWhere("customer.phoneNo IS NOT NULL AND customer.phoneNo != '' AND CHAR_LENGTH(customer.phoneNo) = 9");
// Customer must be published
$select->andWhere("customer.o_published = 1");
// Only active subscriptions
$select->andWhere("subscription.isActive = 1");
// Only 'custom' subscription type
$select->andWhere("subscription.subscriptionType = " . $db->quote('custom'));
// Only subscriptions with end date in future (or no expiry)
$currentTimestamp = time();
$select->andWhere("(subscription.endDate IS NULL OR subscription.endDate >= " . $currentTimestamp . ")");
$results = $select->execute()->fetchAllAssociative();
// Convert user_ids to phone numbers
$userPhones = [];
foreach ($results as $row) {
$phoneNo = $row['phone_no'];
if (!empty($phoneNo) && strlen($phoneNo) === 9) {
$userPhones[] = '+966' . $phoneNo;
}
}
$userGroupListData[] = [
'groupid' => $userGroup->getId(),
'name' => $userGroup->getGroupName("en") ?: $userGroup->getGroupName("ar") ?: '',
'user_phones' => $userPhones
];
}
// Also fetch UserSMSGroup objects
$userSMSGroupList = new DataObject\UserSMSGroup\Listing();
$userSMSGroupList->setOrderKey("oo_id");
$userSMSGroupList->setOrder("desc");
foreach ($userSMSGroupList as $userSMSGroup) {
// Extract phone numbers from groupData JSON
$groupData = $userSMSGroup->getGroupData();
$userPhones = [];
if (!empty($groupData)) {
try {
$userInfoArray = json_decode($groupData, true);
if (is_array($userInfoArray)) {
foreach ($userInfoArray as $userInfo) {
if (isset($userInfo['phoneNumber']) && !empty($userInfo['phoneNumber'])) {
$phoneNumber = $userInfo['phoneNumber'];
// Ensure phone number is in +966XXXXXXXXX format
if (!preg_match('/^\+966/', $phoneNumber)) {
// Remove +966 or 966 prefix to get 9 digits
$phoneDigits = preg_replace('/^\+966/', '', $phoneNumber);
$phoneDigits = preg_replace('/^966/', '', $phoneDigits);
$phoneDigits = preg_replace('/[^0-9]/', '', $phoneDigits);
if (strlen($phoneDigits) === 9) {
$phoneNumber = '+966' . $phoneDigits;
}
}
$userPhones[] = $phoneNumber;
}
}
}
} catch (\Exception $ex) {
// Skip invalid JSON
continue;
}
}
// Merge with existing UserGroup if same name, otherwise add as new entry
$groupName = $userSMSGroup->getGroupName("en") ?: $userSMSGroup->getGroupName("ar") ?: '';
$merged = false;
foreach ($userGroupListData as &$existingGroup) {
if ($existingGroup['name'] === $groupName) {
// Merge phone numbers (remove duplicates)
$existingGroup['user_phones'] = array_values(array_unique(array_merge($existingGroup['user_phones'], $userPhones)));
$merged = true;
break;
}
}
if (!$merged && !empty($userPhones)) {
// Add as new entry if not merged
$userGroupListData[] = [
'groupid' => $userSMSGroup->getId(),
'name' => $groupName,
'user_phones' => $userPhones
];
}
}
if (!empty($userGroupListData)) {
return ["success" => true, "data" => $userGroupListData];
}
return ["success" => false, "message" => $translator->trans("user_groups_are_not_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
/**
* Create or update user group with simplified parameters
* Only assigns users that have mobile numbers (like listC2Users logic)
*/
public function createUpdateUserGroupSimple($user, $groupName, $userIds, $groupId = null, $translator): array
{
try {
$organization = $user->getOrganization();
if (!$organization instanceof DataObject\Organization) {
return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_organization")];
}
// Get class IDs for table names
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customerClassId = $class->getDao()->getIdByName('Customer');
$subscriptionClassId = $class->getDao()->getIdByName('Subscription');
$db = Db::get();
// Validate and filter user_ids - only include users with mobile numbers
$validUserIds = [];
if (!empty($userIds)) {
$select = $db->createQueryBuilder();
$select->select(['customer.oo_id AS customer_id']);
$select->from('object_' . $customerClassId, 'customer');
// Join with subscription to filter active subscriptions
$select->innerJoin(
'customer',
'object_' . $subscriptionClassId,
'subscription',
'customer.oo_id = subscription.subscribedUser__id'
);
// Filter by provided user IDs
$select->where("customer.oo_id IN (:userIds)");
$select->setParameter('userIds', $userIds, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
// Apply mobile number filter (same as listC2Users)
$select->andWhere("customer.phoneNo IS NOT NULL AND customer.phoneNo != '' AND CHAR_LENGTH(customer.phoneNo) = 9");
// Customer must be published
$select->andWhere("customer.o_published = 1");
// Only active subscriptions
$select->andWhere("subscription.isActive = 1");
// Only 'custom' subscription type
$select->andWhere("subscription.subscriptionType = " . $db->quote('custom'));
// Only subscriptions with end date in future (or no expiry)
$currentTimestamp = time();
$select->andWhere("(subscription.endDate IS NULL OR subscription.endDate >= " . $currentTimestamp . ")");
$results = $select->execute()->fetchAllAssociative();
foreach ($results as $row) {
$validUserIds[] = (int) $row['customer_id'];
}
}
if (empty($validUserIds)) {
return ["success" => false, "message" => $translator->trans("no_valid_users_with_mobile_numbers_found")];
}
// Validate group name uniqueness when creating new group
if (!$groupId) {
// Check if group name already exists in the same organization
$existingGroupList = new DataObject\UserGroup\Listing();
$existingGroupList->filterByOrganization($organization);
$existingGroupList->setLocale('en');
foreach ($existingGroupList as $existingGroup) {
if ($existingGroup instanceof DataObject\UserGroup) {
$existingGroupNameEn = $existingGroup->getGroupName('en');
$existingGroupNameAr = $existingGroup->getGroupName('ar');
// Check if group name matches (case-insensitive)
if (strcasecmp(trim($existingGroupNameEn), trim($groupName)) === 0 ||
strcasecmp(trim($existingGroupNameAr), trim($groupName)) === 0) {
return ["success" => false, "message" => $translator->trans("group_name_already_exists")];
}
}
}
}
// Create or update user group
if ($groupId) {
// Update existing group
$userGroup = DataObject\UserGroup::getById($groupId, true);
if (!$userGroup instanceof DataObject\UserGroup) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_available")];
}
// Verify organization
if (!$userGroup->getOrganization() || $userGroup->getOrganization()->getId() != $organization->getId()) {
return ["success" => false, "message" => $translator->trans("user_group_is_not_assigned_to_your_organization")];
}
// Update group name
$userGroup->setGroupName($groupName, "en");
$userGroup->setGroupName($groupName, "ar");
} else {
// Create new group
$userGroup = new DataObject\UserGroup();
$userGroup->setParent(DataObject\Service::createFolderByPath('/UserManagement/UserGroups/' . $organization->getName()));
$userGroup->setKey(trim(strip_tags($groupName.'-'.uniqid())));
$userGroup->setGroupName($groupName, 'en');
$userGroup->setGroupName($groupName, 'ar');
$userGroup->setDetail($groupName, 'en');
$userGroup->setDetail($groupName, 'ar');
$userGroup->setOrganization($organization);
$userGroup->setPublished(true);
// dump($userGroup);
// die;
// $userGroup->setGroupName($groupName, "en");
// $userGroup->setGroupName($groupName, "ar");
// $userGroup->setOrganization($organization);
$userGroup->setIsActive(true);
}
$userGroup->save();
// Reload the group to ensure it has all necessary data
$userGroup = DataObject\UserGroup::getById($userGroup->getId(), true);
// Assign users to group
foreach ($validUserIds as $userId) {
$customer = DataObject\Customer::getById($userId, true);
if ($customer instanceof DataObject\Customer) {
// Get existing user groups for this customer
$existingGroups = [];
// Collect existing groups and their IDs
$currentGroups = $customer->getUserGroup();
if ($currentGroups) {
foreach ($currentGroups as $group) {
if ($group instanceof DataObject\UserGroup) {
$groupId = $group->getId();
// Skip if this is the same group we're adding
if ($groupId != $userGroup->getId()) {
$existingGroups[] = $group;
}
}
}
}
// Add the new/updated group
$existingGroups[] = $userGroup;
// Update customer's user groups
$customer->setUserGroup($existingGroups);
$customer->save();
}
}
// Remove users from group if they're not in the valid list
// Get all users currently in this group
$allUsersInGroup = new DataObject\Customer\Listing();
$allUsersInGroup->filterByUserGroup($userGroup);
foreach ($allUsersInGroup as $customer) {
if (!in_array($customer->getId(), $validUserIds)) {
// Get existing groups and remove this one
$existingGroups = [];
$currentGroups = $customer->getUserGroup();
if ($currentGroups) {
foreach ($currentGroups as $group) {
if ($group instanceof DataObject\UserGroup) {
// Only keep groups that are NOT the one we're removing
if ($group->getId() != $userGroup->getId()) {
$existingGroups[] = $group;
}
}
}
}
$customer->setUserGroup($existingGroups);
$customer->save();
}
}
$action = $groupId ? "updated" : "created";
return [
"success" => true,
"message" => $translator->trans("user_group_{$action}_successfully"),
"data" => [
"groupid" => $userGroup->getId(),
"name" => $groupName,
"user_ids" => $validUserIds
]
];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
/**
* Internal user dual mode
* @param array $params
* @param Translator $translator
* @return array
*/
public function internalUserDualMode($params, $translator): array
{
try {
$user = DataObject\Customer::getById($params['id'], true);
// check if user is internal user
if (!$user) {
return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
}
// get internal organization
$organization = new DataObject\Organization\Listing();
$organization->filterByIsInternal(true);
$entity = $organization->current();
if(!$entity) {
return ["success" => false, "message" => $translator->trans("internal_organization_does_not_exists")];
}
$package = $entity->getPackage();
if (!$package) {
return ["success" => false, "message" => $translator->trans("package_does_not_exists")];
}
if ($params['mode'] == true) {
$user->setDualMode(true);
$user->save();
// get existing subscription
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($user);
$subscriptions->filterBySubscriptionType('custom');
$subscriptions->filterBySubscribedPackage($package);
$subscription = $subscriptions->current();
if ($subscription) {
$subscription->setIsNoExpiry(true);
$subscription->setIsActive(true);
$subscription->setSubscriptionType('custom');
$subscription->setPublished(true);
$subscription->setSubscribedPackage($package);
$subscription->setSubscribedUser($user);
$subscription->save();
} else {
// create new subscription
$subscription = new DataObject\Subscription();
$subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' . $user->getEmail()));
$subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(1000, 10000), 'object'));
$subscription->setSubscribedPackage($package);
$subscription->setSubscribedUser($user);
$subscription->setSubscriptionType('custom');
$subscription->setIsNoExpiry(true);
$subscription->setIsActive(true);
$subscription->setPublished(true);
$subscription->save();
}
} else {
// disable dual mode
$user->setDualMode(false);
$user->save();
// get existing subscription
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($user);
$subscriptions->filterBySubscribedPackage($package);
$subscriptions->filterBySubscriptionType('custom');
$subscription = $subscriptions->current();
// delete subscription
if ($subscription) {
$subscription->delete();
}
}
return ["success" => true, "message" => $translator->trans("internal_user_dual_mode_updated_successfully")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
}