<?php
namespace App\Model;
use Symfony\Component\HttpFoundation\Request;
use Pimcore\Model\DataObject;
use App\Service\EmailService;
use Pimcore\Bundle\AdminBundle\GDPR\DataProvider\SentMail;
use App\Lib\Utility;
use Pimcore\Db;
use Pimcore\Model\DataObject\Package;
use Pimcore\Model\DataObject\WeatherStations;
use Pimcore\Model\DataObject\ThrottlingPolicy;
use Pimcore\Model\DataObject\Subscription;
use Carbon\Carbon;
use App\C2IntegrationBundle\Service\C2Service;
use Symfony\Component\Templating\EngineInterface;
use Pimcore\Model\DataObject\Customer;
use Pimcore\Model\DataObject\Organization;
use Pimcore\Model\Asset;
use Pimcore\Model\WebsiteSetting;
class PackageModel
{
private $templating;
private $c2Service;
private $db;
function __construct(EngineInterface $templating)
{
$this->c2Service = new C2Service();
$this->templating = $templating;
$this->db = \Pimcore\Db::get();
}
/**
* Create Package function
*/
public function createPackage($packageNameEn, $packageNameAr, $apiGroups, $price, $maxLocations, $maxUsers, $translator, $packageType = "public", $isAvailableOnWebsite = true, $isSMSEnabled, $isSMSEnableForCustomNotification, $isSMSEnableForMannedAlert, $isSMSEnableForOTP, $smsLimit, $weatherStationIds)
{
$apiGroupsArray = [];
// Utility::isValidTenure($tenure);
foreach ($apiGroups as $key => $apiGroupId) {
$apiGroup = DataObject\APIGroup::getById($apiGroupId, true);
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupsArray[] = $apiGroup;
}
}
if (count($apiGroupsArray) == 0) {
return ["success" => false, "message" => $translator->trans("no_api_group_available")];
}
$package = new DataObject\Package();
if ($packageType == "private") {
$package->setParent(DataObject\Service::createFolderByPath('/UserManagement/Packages/NCM Users/CustomPackages'));
$package->setPackagetype('private');
} else {
$package->setParent(DataObject\Service::createFolderByPath('/UserManagement/Packages/CustomPackages'));
$package->setPackagetype('public');
}
$weatherStations = [];
if (!empty($weatherStationIds)) {
foreach ($weatherStationIds as $stationId) {
$weatherStation = DataObject\WeatherStations::getById($stationId, true);
if ($weatherStation instanceof \Pimcore\Model\DataObject\WeatherStations) {
$weatherStations[] = $weatherStation;
}
}
}
$package->setWeatherStations($weatherStations);
$package->setKey(rand(1, 1000) . '-' . time());
$package->setPackageName(strip_tags($packageNameEn), 'en');
$package->setPackageName(strip_tags($packageNameAr), 'ar');
$quantityValue = new DataObject\Data\QuantityValue($price, 'SAR');
$package->setPrice($quantityValue);
$package->setApiGroups($apiGroupsArray);
// $package->setTenure(strip_tags($tenure));
$package->setMaxLocation(strip_tags($maxLocations));
$package->setMaxUsers(strip_tags($maxUsers));
$package->setIsActive(true);
$package->setIsApi(false);
$package->setIsAvailableOnWebsite($isAvailableOnWebsite ?? true);
$package->setIsSMSEnabled($isSMSEnabled);
$package->setIsSMSEnableForCustomNotification($isSMSEnableForCustomNotification);
$package->setIsSMSEnableForMannedAlert($isSMSEnableForMannedAlert);
$package->setIsSMSEnableForOTP($isSMSEnableForOTP);
$package->setSMSLimit($smsLimit);
$package->setPublished(true);
$package->Save();
if ($package) {
return ["success" => true, "data" => $package->getId(), "message" => $translator->trans("package_created")];
}
}
/**
* Update Package function
*/
public function updatePackage($params, $translator)
{
$updatePackage = DataObject\Package::getById($params["id"], true);
if (!$updatePackage instanceof DataObject\Package) {
return ["success" => false, "message" => $translator->trans("package_is_not_available")];
}
if (isset($params["api_groups"]) && !empty($params["api_groups"])) {
$apiGroupsArray = [];
foreach ($params["api_groups"] as $key => $apiGroupId) {
$apiGroup = DataObject\APIGroup::getById($apiGroupId, true);
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupsArray[] = $apiGroup;
}
}
if (count($apiGroupsArray) > 0) {
$updatePackage->setApiGroups($apiGroupsArray);
}
}
if (isset($params["name"]) && !empty($params["name"])) {
$updatePackage->setPackageName(strip_tags($params["name"]), 'en');
}
if (isset($params["name_ar"]) && !empty($params["name_ar"])) {
$updatePackage->setPackageName(strip_tags($params["name_ar"]), 'ar');
}
if (isset($params["price"]) && !empty($params["price"])) {
$quantityValue = new DataObject\Data\QuantityValue($params["price"], 'SAR');
$updatePackage->setPrice($quantityValue);
}
if (isset($params["tenure"]) && !empty($params["tenure"])) {
Utility::isValidTenure($params['tenure']);
$updatePackage->setTenure(strip_tags($params["tenure"]));
}
if (isset($params["max_locations"]) && !empty($params["max_locations"])) {
$updatePackage->setMaxLocation(strip_tags($params["max_locations"]));
}
if (isset($params["max_users"]) && !empty($params["max_users"])) {
$updatePackage->setMaxUsers(strip_tags($params["max_users"]));
}
if (isset($params['isSMSEnabled'])) {
$updatePackage->setIsSMSEnabled($params["isSMSEnabled"]);
}
if (isset($params['isSMSEnableForCustomNotification'])) {
$updatePackage->setIsSMSEnableForCustomNotification($params["isSMSEnableForCustomNotification"]);
}
if (isset($params['isSMSEnableForMannedAlert'])) {
$updatePackage->setIsSMSEnableForMannedAlert($params["isSMSEnableForMannedAlert"]);
}
if (isset($params['isSMSEnableForOTP'])) {
$updatePackage->setIsSMSEnableForOTP($params["isSMSEnableForOTP"]);
}
if (!empty($params['SMSLimit'])) {
$updatePackage->setSMSLimit($params["SMSLimit"]);
}
if (!empty($params['weatherStationIds']) && is_array($params['weatherStationIds'])) {
$weatherStations = [];
foreach ($params['weatherStationIds'] as $stationId) {
$weatherStation = \Pimcore\Model\DataObject\WeatherStations::getById((int)$stationId);
if ($weatherStation instanceof \Pimcore\Model\DataObject\WeatherStations) {
$weatherStations[] = $weatherStation;
}
}
$updatePackage->setWeatherStations($weatherStations);
}
$updatePackage->setIsApi(false);
$updatePackage->Save();
if ($updatePackage) {
return ["success" => true, "data" => $updatePackage->getId(), "message" => $translator->trans("package_updated")];
}
}
/**
* Delete Package function
*/
public function deletePackage($Id, $loggedinUser, $translator)
{
// Get package by ID
$package = DataObject\Package::getById($Id, true);
if (!$package instanceof DataObject\Package) {
return ["success" => false, "message" => $translator->trans("package_is_not_available")];
}
// Check for active subscriptions
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedPackage($package);
$subscriptions->addConditionParam("subscribedUser__id IS NOT NULL");
$subscriptionsCount = $subscriptions->count();
// Check for organizations assigned to the package
$organizations = new DataObject\Organization\Listing();
$organizations->addConditionParam("package__id = ?", [$package->getId()]);
$organizationsCount = $organizations->count();
// Handle the different scenarios based on counts
if ($subscriptionsCount == 0 && $organizationsCount == 0) {
$package->delete();
return ["success" => true, "message" => $translator->trans("package_is_deleted")];
}
if ($subscriptionsCount > 0 && $organizationsCount == 0) {
return ["success" => false, "message" => $translator->trans("package_is_subscribed_by_customer")];
}
if ($organizationsCount > 0 && $subscriptionsCount == 0) {
return ["success" => false, "message" => $translator->trans("package_is_assigned_to_organization")];
}
return ["success" => false, "message" => $translator->trans("package_is_subscribed_by_user_and_assigned_to_organization")];
}
/**
* List Package function
*/
public function listPackage($params, $paginator, $translator)
{
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$lang = isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE;
// Get class IDs
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customerClassId = $class->getDao()->getIdByName('Customer');
$subscriptionClassId = $class->getDao()->getIdByName('Subscription');
$packageClassId = $class->getDao()->getIdByName('Package');
$db = Db::get();
// Create QueryBuilder for the main query
$qb = $db->createQueryBuilder();
$qb->select([
'p.oo_id as id',
'p.packagetype as type',
'p.price__value as price',
'p.tenure',
'p.maxLocation as max_locations',
'p.maxUsers as max_users',
'p.isSMSEnabled',
'p.isSMSEnableForCustomNotification',
'p.isSMSEnableForMannedAlert',
'p.isSMSEnableForOTP',
'p.SMSLimit',
'p.isActive',
'p.o_published',
'p.isApi',
'p.isAvailableOnWebsite'
])
->from('object_' . $packageClassId, 'p')
->where('p.packagetype = :packagetype')
->andWhere('p.isAvailableOnWebsite = :isAvailableOnWebsite')
->andWhere('p.isActive = :isActive')
->andWhere('(p.isApi = 0 OR p.isApi IS NULL)')
->setParameter('packagetype', 'public')
->setParameter('isAvailableOnWebsite', 1)
->setParameter('isActive', 1);
// Join localized tables for packageName
$qb->leftJoin('p', 'object_localized_query_packages_en', 'p_en', 'p_en.ooo_id = p.oo_id')
->leftJoin('p', 'object_localized_query_packages_ar', 'p_ar', 'p_ar.ooo_id = p.oo_id')
->addSelect([
'p_en.packageName as name',
'p_ar.packageName as name_ar'
]);
// Add assign_users calculation as a subquery
$assignUsersSubquery = "(
SELECT COUNT(DISTINCT customer.oo_id)
FROM object_{$customerClassId} customer
INNER JOIN object_{$subscriptionClassId} subscription ON customer.oo_id = subscription.subscribedUser__id
WHERE subscription.subscribedPackage__id = p.oo_id
AND subscription.isActive = 1
AND subscription.o_published = 1
)";
$qb->addSelect($assignUsersSubquery . ' as assign_users');
// Handle single ID filter
if (isset($params['id']) && !empty($params['id'])) {
$qb->andWhere('p.oo_id = :id')
->setParameter('id', $params['id']);
}
// Handle search filter
if (isset($params['search']) && !empty($params['search'])) {
$qb->andWhere('(p_en.packageName LIKE :search OR p_ar.packageName LIKE :search)')
->setParameter('search', '%' . $params['search'] . '%');
}
// Handle API group filter
if (isset($params['api_group']) && !empty($params['api_group'])) {
$qb->andWhere('p.ApiGroups LIKE :api_group')
->setParameter('api_group', '%,' . $params['api_group'] . ',%');
}
// Handle sorting
$allowedOrderKeys = ['name', 'tenure', 'price', 'maxLocation', 'maxUser', 'smsLimit', 'assign_users'];
$allowedOrderDirections = ['asc', 'desc'];
if (
isset($params['orderKey']) && in_array($params['orderKey'], $allowedOrderKeys) &&
isset($params['order']) && in_array(strtolower($params['order']), $allowedOrderDirections)
) {
$orderKey = $params['orderKey'];
$orderDirection = strtolower($params['order']);
// Map the orderKey to the actual database field names
$fieldMapping = [
'name' => $lang === 'ar' ? 'p_ar.packageName' : 'p_en.packageName',
'tenure' => 'p.tenure',
'price' => 'p.price__value',
'maxLocation' => 'p.maxLocation',
'maxUser' => 'p.maxUsers',
'smsLimit' => 'p.SMSLimit',
'assign_users' => 'assign_users'
];
if (isset($fieldMapping[$orderKey])) {
$dbField = $fieldMapping[$orderKey];
$qb->orderBy($dbField, strtoupper($orderDirection));
}
} else {
// Default sorting
$qb->orderBy('p.oo_id', 'DESC');
}
// Use the paginator
$paginatorResult = $paginator->paginate(
$qb,
$page,
$pageSize
);
$totalPackages = $paginatorResult->count();
if ($totalPackages > 0) {
$packageDataArray = [];
foreach ($paginatorResult as $package) {
// Get API Groups for this package
$apiGroupDataArray = [];
$packageObj = DataObject\Package::getById($package['id']);
if ($packageObj) {
$apiGroups = $packageObj->getApiGroups();
if ($apiGroups) {
foreach ($apiGroups as $apiGroup) {
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupDataArray[] = [
"id" => $apiGroup->getId(),
"type" => $apiGroup->getApiGroupType(),
"name" => $apiGroup->getApiGroupName('en'),
"name_ar" => $apiGroup->getApiGroupName('ar')
];
}
}
}
// Get Weather Stations for this package
$weatherStationArray = [];
$weatherStations = $packageObj->getWeatherStations();
if ($weatherStations) {
foreach ($weatherStations as $weatherStation) {
$weatherStationArray[] = [
"id" => $weatherStation->getId(),
"name" => $weatherStation->getName("en"),
"name_ar" => $weatherStation->getName("ar"),
];
}
}
}
// Build package data array
$packageDataArray[] = [
"id" => $package['id'],
"assign_users" => (int)$package['assign_users'],
"type" => $package['type'],
"name" => $package['name'],
"name_ar" => $package['name_ar'],
"price" => $package['price'],
"tenure" => $package['tenure'],
"max_locations" => $package['max_locations'],
"max_users" => $package['max_users'],
"api_groups" => $apiGroupDataArray,
"isSMSEnabled" => (bool)$package['isSMSEnabled'],
"isSMSEnableForCustomNotification" => (bool)$package['isSMSEnableForCustomNotification'],
"isSMSEnableForMannedAlert" => (bool)$package['isSMSEnableForMannedAlert'],
"isSMSEnableForOTP" => (bool)$package['isSMSEnableForOTP'],
"SMSLimit" => $package['SMSLimit'],
"weatherStations" => $weatherStationArray,
];
}
return ["success" => true, "data" => $packageDataArray, "paginationVariables" => $paginatorResult->getPaginationData()];
}
return ["success" => false, "message" => $translator->trans("packages_are_not_available")];
}
/**
* List Package function
*/
public function listPackagesWithFilters($params, $paginator, $translator)
{
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$customer = $class->getDao()->getIdByName('Customer');
$subscription = $class->getDao()->getIdByName('Subscription');
$organization = $class->getDao()->getIdByName('Organization');
$package = $class->getDao()->getIdByName('Package');
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('package.oo_id');
$select->from('object_' . $package, 'package');
$select->leftJoin('package', 'object_' . $subscription, 'subscription', 'package.oo_id = subscription.subscribedPackage__id');
$select->leftJoin('subscription', 'object_' . $customer, 'customer', 'customer.oo_id = subscription.subscribedUser__id');
$select->leftJoin('customer', 'object_' . $organization, 'organization', 'organization.oo_id = customer.organization__id');
$select->where("package.packagetype = " . $db->quote("public"));
if (isset($params['clientType']) && !empty($params['clientType'])) {
$select->andWhere("organization.cilent_type = " . $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['search']) && !empty($params['search'])) {
// Join the localized fields table for the language
$select->leftJoin('package', 'object_localized_query_' . $package . '_' . $params['lang'], 'localized', 'localized.ooo_id = package.oo_id');
$select->andWhere("localized.packageName LIKE " . $db->quote("%" . $params['search'] . "%"));
}
$select->andWhere("package.isAvailableOnWebsite = 1");
$select->andWhere("package.isActive = 1");
$select->andWhere("package.isApi = 0 OR package.isApi IS NULL");
$select->andWhere("package.o_published = 1");
$allowed = [
'name',
'name_ar'
];
if (isset($params['sortBy']) && in_array($params['sortBy'], $allowed, true)) {
// decide language based on requested field
$sortAlias = 'localized_sort';
// ensure localized table is joined for sorting (avoids missing column error)
$select->leftJoin('package', 'object_localized_query_' . $package . '_' . $params['lang'], $sortAlias, $sortAlias . '.ooo_id = package.oo_id');
$direction = (isset($params['sortDir']) && strtoupper($params['sortDir']) === 'DESC') ? 'DESC' : 'ASC';
$select->orderBy($sortAlias . '.packageName', $direction);
} else {
$select->orderBy('package.oo_id', 'DESC');
}
// always group by package id to avoid duplicates from joins
$select->groupBy(['package.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
);
$totalPackages = $paginator->count();
if ($totalPackages > 0) {
foreach ($paginator as $key => $packageId) {
$package = Package::getById($packageId['oo_id'], true);
if ($package) {
$apiGroupDataArray = [];
// load all assigned APIGroups Data
$apiGroups = $package->getApiGroups();
if ($apiGroups) {
foreach ($apiGroups as $key => $apiGroup) {
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupDataArray[] = [
"id" => $apiGroup->getId(),
"type" => $apiGroup->getApiGroupType(),
"name" => $apiGroup->getApiGroupName('en'),
"name_ar" => $apiGroup->getApiGroupName('ar')
];
}
}
}
// Now, to get the price if it's set:
$price = null;
if ($package->getPrice()) {
$price .= $package->getPrice()->getValue(); // Accessing the value of the QuantityValue object
}
// Get All Packes data
$packageDataArray[] = [
"id" => $package->getId(),
"type" => $package->getPackagetype(),
"name" => $package->getPackageName('en'),
"name_ar" => $package->getPackageName('ar'),
"price" => $price,
"tenure" => $package->getTenure(),
"max_locations" => $package->getMaxLocation(),
"max_users" => $package->getMaxUsers(),
"api_groups" => $apiGroupDataArray
];
$apiGroupDataArray = [];
}
}
return ["success" => true, "data" => $packageDataArray, "paginationVariables" => $paginator->getPaginationData()];
}
return ["success" => false, "message" => $translator->trans("packages_are_not_available")];
}
/**
* List APIGroup function
*/
public function listApiGroup($params, $translator)
{
$apiGroupDataArray = [];
$apiGroups = new DataObject\APIGroup\Listing();
$apiGroups->filterByApiGroupType("public");
$apiGroups->filterByIsActive(true);
$apiGroups->setLocale($translator->getLocale());
if (isset($params['search']) && !empty(trim($params['search']))) {
$apiGroups->addConditionParam("apiGroupName LIKE " . $apiGroups->quote("%" . trim($params['search']) . "%"));
}
$allowed = [
'name',
'name_ar'
];
if ($params['sortBy'] && in_array($params['sortBy'], $allowed, true)) {
$apiGroups->setOrderKey("apiGroupName", $params['sortBy'] == "name_ar" ? 'ar' : 'en');
$apiGroups->setOrder($params['sortDir'] === 'DESC' ? 'DESC' : 'ASC');
}
$totalApiGroups = $apiGroups->count();
if ($totalApiGroups > 0) {
$apiGroupDataArray[] = [
"totalApiGroups" => $totalApiGroups
];
foreach ($apiGroups as $key => $apiGroup) {
// load all assigned APIGroups Data
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupDataArray[] = [
"id" => $apiGroup->getId(),
"type" => $apiGroup->getApiGroupType(),
"name" => $apiGroup->getApiGroupName('en'),
"name_ar" => $apiGroup->getApiGroupName('ar')
];
}
}
return ["success" => true, "data" => $apiGroupDataArray];
}
return ["success" => false, "message" => $translator->trans("api_groups_are_not_available")];
}
/**
* List Private APIGroup function
*/
public function listPrivateApiGroup($params, $user, $translator)
{
$apiGroupDataArray = [];
$apiGroups = new DataObject\APIGroup\Listing();
$apiGroups->filterByApiGroupType("private");
$apiGroups->filterByIsActive(true);
$apiGroups->setOrderKey("order");
$apiGroups->setOrder('ASC');
$apiGroups->setLocale($translator->getLocale());
if ($apiGroups) {
foreach ($apiGroups as $apiGroup) {
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupDataArray[] = [
"id" => $apiGroup->getId(),
"type" => $apiGroup->getApiGroupType(),
"group_name" => $apiGroup->getGroupName(),
"name" => $apiGroup->getApiGroupName('en'),
"name_ar" => $apiGroup->getApiGroupName('ar')
];
}
}
}
return ["success" => true, "data" => $apiGroupDataArray];
}
/**
* View APIGroup function
*/
public function viewApiGroup($Id, $loggedinUser, $translator)
{
$apiGroupDataArray = [];
$apiGroups = new DataObject\APIGroup\Listing();
$apiGroups->filterById($Id);
$apiGroups->filterByApiGroupType("public");
$apiGroups->filterByIsActive(true);
$apiGroup = $apiGroups->current();
// load all assigned APIGroups Data
if ($apiGroup instanceof DataObject\APIGroup) {
$apiGroupDataArray[] = [
"id" => $apiGroup->getId(),
"type" => $apiGroup->getApiGroupType(),
"name" => $apiGroup->getApiGroupName('en'),
"name_ar" => $apiGroup->getApiGroupName('ar'),
"permission" => $apiGroup->getAllowedApis()
];
return ["success" => true, "data" => $apiGroupDataArray];
}
return ["success" => false, "message" => $translator->trans("api_group_is_not_available")];
}
/**
* Suspend Package function
*/
public function suspendPackage($userIdOrIds, $loggedinUser, $translator)
{
$ids = is_array($userIdOrIds) ? $userIdOrIds : [$userIdOrIds];
$results = [];
foreach ($ids as $userId) {
$customer = DataObject\Customer::getById($userId, true);
if (!$customer) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("user_is_not_available")];
continue;
}
//validate Role first
$loggedInUserRole = $loggedinUser->getRole() ? $loggedinUser->getRole()->getName() : USER_ROLES['CLIENT_USER'];
$customerRole = $customer->getRole() ? $customer->getRole()->getName() : USER_ROLES['CLIENT_USER'];
if ($loggedInUserRole == USER_ROLES['CLIENT_USER'] && ($customerRole == USER_ROLES['NCM_OPERATOR'] || $customerRole == USER_ROLES['NCM_IT'] || $customerRole == USER_ROLES['CLIENT_ADMIN'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
} elseif ($loggedInUserRole == USER_ROLES['CLIENT_ADMIN'] && ($customerRole == USER_ROLES['NCM_IT'] || $customerRole == USER_ROLES['NCM_OPERATOR'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
} elseif ($loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && ($customerRole == USER_ROLES['NCM_IT'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
}
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($customer);
$subscriptions->filterByIsActive(true);
if ($subscriptions->count() > 0) {
foreach ($subscriptions as $subscription) {
if ($subscription) {
$subscription->setIsActive(false);
$subscription->save();
}
}
$results[] = ["id" => $userId, "success" => true, "message" => $translator->trans("package_suspended_successfully")];
} else {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("active_subscription_is_not_available")];
}
}
// Preserve backward compatibility: if input was scalar, return single-object style
if (!is_array($userIdOrIds)) {
$single = $results[0] ?? ["success" => false, "message" => $translator->trans("unknown_error")];
return ["success" => $single["success"], "message" => $single["message"]];
}
$successCount = 0;
foreach ($results as $r) {
if (!empty($r['success'])) {
$successCount++;
}
}
return ["success" => true, "message" => sprintf("%s: %d", $translator->trans("package_suspended_successfully"), $successCount)];
}
/**
* Resume Package function
*/
public function resumePackage($userIdOrIds, $loggedinUser, $translator)
{
$ids = is_array($userIdOrIds) ? $userIdOrIds : [$userIdOrIds];
$results = [];
foreach ($ids as $userId) {
$customer = DataObject\Customer::getById($userId, true);
if (!$customer) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("user_is_not_available")];
continue;
}
//validate Role first
$loggedInUserRole = $loggedinUser->getRole() ? $loggedinUser->getRole()->getName() : USER_ROLES['CLIENT_USER'];
$customerRole = $customer->getRole() ? $customer->getRole()->getName() : USER_ROLES['CLIENT_USER'];
if ($loggedInUserRole == USER_ROLES['CLIENT_USER'] && ($customerRole == USER_ROLES['NCM_OPERATOR'] || $customerRole == USER_ROLES['NCM_IT'] || $customerRole == USER_ROLES['CLIENT_ADMIN'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
} elseif ($loggedInUserRole == USER_ROLES['CLIENT_ADMIN'] && ($customerRole == USER_ROLES['NCM_IT'] || $customerRole == USER_ROLES['NCM_OPERATOR'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
} elseif ($loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && ($customerRole == USER_ROLES['NCM_IT'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
}
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($customer);
$subscriptions->filterByIsActive(false);
if ($subscriptions->count() > 0) {
foreach ($subscriptions as $subscription) {
if ($subscription) {
$subscription->setIsActive(true);
$subscription->save();
}
}
$results[] = ["id" => $userId, "success" => true, "message" => $translator->trans("package_resumed_successfully")];
} else {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("suspended_subscription_is_not_available")];
}
}
if (!is_array($userIdOrIds)) {
$single = $results[0] ?? ["success" => false, "message" => $translator->trans("unknown_error")];
return ["success" => $single["success"], "message" => $single["message"]];
}
$successCount = 0;
foreach ($results as $r) {
if (!empty($r['success'])) {
$successCount++;
}
}
return ["success" => true, "message" => sprintf("%s: %d", $translator->trans("package_resumed_successfully"), $successCount)];
}
/**
* Renew Package function for all users in organization
* $organization : organization object
*/
public function renewPackage($organization, $days, $loggedinUser, $translator)
{
$successCount = 0;
$failCount = 0;
$results = [];
$customers = new DataObject\Customer\Listing();
$customers->filterByOrganization($organization);
foreach ($customers as $customer) {
$userId = $customer->getId();
//validate Role first
$loggedInUserRole = $loggedinUser->getRole() ? $loggedinUser->getRole()->getName() : USER_ROLES['CLIENT_USER'];
$customerRole = $customer->getRole() ? $customer->getRole()->getName() : USER_ROLES['CLIENT_USER'];
if ($loggedInUserRole == USER_ROLES['CLIENT_USER'] && ($customerRole == USER_ROLES['NCM_OPERATOR'] || $customerRole == USER_ROLES['NCM_IT'] || $customerRole == USER_ROLES['CLIENT_ADMIN'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
} elseif ($loggedInUserRole == USER_ROLES['CLIENT_ADMIN'] && ($customerRole == USER_ROLES['NCM_IT'] || $customerRole == USER_ROLES['NCM_OPERATOR'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
} elseif ($loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && ($customerRole == USER_ROLES['NCM_IT'])) {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("permission_denied_to_role")];
continue;
}
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($customer);
// $subscriptions->filterByIsActive(true);
if ($subscriptions->count() > 0) {
$subscriptionExpiry = date('Y-m-d', strtotime('+' . $days . ' days'));
foreach ($subscriptions as $subscription) {
$subscription->setEndDate(\Carbon\Carbon::parse(new \Datetime($subscriptionExpiry)));
$subscription->save();
}
$results[] = ["id" => $userId, "success" => true, "message" => $translator->trans("package_renewed_successfully")];
$successCount++;
} else {
$results[] = ["id" => $userId, "success" => false, "message" => $translator->trans("subscription_is_not_available")];
$failCount++;
}
}
$organization->setPackageActivationDate(\Carbon\Carbon::parse(new \Datetime(date('Y-m-d'))));
$organization->setTrialLimit($days);
$organization->save();
return ["success" => true, "message" => sprintf("%s: %d", $translator->trans("package_renewed_successfully"), $successCount)];
}
/**
* Create Wso Package function
*/
public function createWsoPackage($packageNameEn, $price, $tenure, $throttling, $packageType = "public", $translator)
{
$package = DataObject\Package::getByName($packageNameEn, 'en');
if ($package->getCount() > 0) {
return ["success" => false, "message" => $translator->trans("package_with_this_name_exists")];
}
Utility::isValidTenure($tenure);
$throttling = DataObject\WSO2Policies::getById($throttling, true);
if (!$throttling) {
return ["success" => false, "message" => $translator->trans("throttling_is_not_available")];
}
$package = new DataObject\Package();
$package->setParent(DataObject\Service::createFolderByPath('/UserManagement/Packages/WSOPackages'));
$package->setPackagetype($packageType);
$package->setKey(rand(1, 1000) . '-' . time());
$package->setPackageCode(uniqid());
$package->setName(strip_tags($packageNameEn), 'en');
$package->setPackageName(strip_tags($packageNameEn), 'en');
// $package->setPackageName(strip_tags($packageNameAr), 'ar');
$quantityValue = new DataObject\Data\QuantityValue($price, 'SAR');
$package->setPrice($quantityValue);
$package->setTenure(strip_tags($tenure));
$package->setThrottlingPolicy($throttling->getId());
$package->setMaxLocation(0);
$package->setMaxUsers(0);
$package->setIsActive(true);
$package->setIsApi(true);
$package->setIsAvailableOnWebsite($isAvailableOnWebsite ?? false);
$package->setPublished(true);
$package->Save();
if ($package) {
return ["success" => true, "data" => $package->getId(), "message" => $translator->trans("package_created")];
}
}
/**
* Update Wso Package function
*/
public function updateWsoPackage($params, $translator)
{
$updatePackage = DataObject\Package::getById($params["id"], true);
if (!$updatePackage instanceof DataObject\Package) {
return ["success" => false, "message" => $translator->trans("package_is_not_available")];
}
$updatePackage->setIsApi(true);
if (isset($params["name"]) && !empty($params["name"])) {
$updatePackage->setName(strip_tags($params["name"]), 'en');
}
if (isset($params["name"]) && !empty($params["name"])) {
$updatePackage->setPackageName(strip_tags($params["name"]), 'en');
}
if (isset($params["name_ar"]) && !empty($params["name_ar"])) {
$updatePackage->setPackageName(strip_tags($params["name_ar"]), 'ar');
}
if (isset($params["price"]) && ($params["price"] != null || $params["price"] != '')) {
$quantityValue = new DataObject\Data\QuantityValue($params["price"], 'SAR');
$updatePackage->setPrice($quantityValue);
}
if (isset($params["tenure"]) && !empty($params["tenure"])) {
Utility::isValidTenure($params['tenure']);
$updatePackage->setTenure(strip_tags($params["tenure"]));
}
if (isset($params["throttling"]) && !empty($params["throttling"])) {
$updatePackage->setThrottlingPolicy($params["throttling"]);
}
$updatePackage->Save();
if ($updatePackage) {
return ["success" => true, "data" => $updatePackage->getId(), "message" => $translator->trans("package_updated")];
}
}
/**
* Inactive Wso Package function
*/
public function inactiveWsoPackage($Id, $status, $translator)
{
$package = DataObject\Package::getById($Id, true);
if (!$package instanceof DataObject\Package) {
return ["success" => false, "message" => $translator->trans("package_is_not_available")];
}
$package->setIsActive($status);
$package->save();
return ["success" => true, "message" => $translator->trans("package_status_updated")];
}
/**
* Delete Wso Package function
*/
public function deleteWsoPackage($Id, $translator)
{
$package = DataObject\Package::getById($Id, true);
if (!$package instanceof DataObject\Package) {
return ["success" => false, "message" => $translator->trans("package_is_not_available")];
}
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->addConditionParam('subscribedUser__id IS NOT NULL');
$subscriptions->filterBySubscribedPackage($package);
$subscriptions->filterByIsActive(true);
if ($subscriptions->count() == 0) {
$package->delete();
return ["success" => true, "message" => $translator->trans("package_is_deleted")];
} else {
return ["success" => false, "message" => $translator->trans("package_is_subscribed_by_customer")];
}
}
/**
* List Wso Package function
*/
public function listWsoPackage($params, $paginator, $translator)
{
$throttlingArr = [];
$policies = new DataObject\WSO2Policies\Listing();
foreach ($policies as $policie) {
$throttlingArr[$policie->getId()] = $policie->getPolicyName();
}
$packageDataArray = [];
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$lang = isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE;
$packages = new DataObject\Package\Listing();
$packages->filterByIsApi(true);
if (isset($params['search']) && !empty($params['search'])) {
$packages->addConditionParam("packageName LIKE " . $packages->quote("%" . $params['search'] . "%"));
}
$packages->filterByPackagetype("public");
$packages->addConditionParam("ThrottlingPolicy IS Not NULL");
// Dynamic sorting with orderKey and order
$orderKey = $params['orderKey'] ?? null;
$order = $params['order'] ?? 'desc';
// Validate order parameter
if (!in_array(strtolower($order), ['asc', 'desc'])) {
$order = 'desc';
}
// Map orderKey to database fields
$sortingMap = [
'name' => 'packageName',
'price' => 'price__value',
'tenure' => 'tenure',
'throttling' => 'ThrottlingPolicy',
'status' => 'isActive'
];
if ($orderKey && isset($sortingMap[$orderKey])) {
$field = $sortingMap[$orderKey];
$packages->setOrderKey($field);
$packages->setOrder(strtoupper($order));
} else {
// Default sorting
$packages->setOrderKey("oo_id");
$packages->setOrder('desc');
}
$paginator = $paginator->paginate(
$packages,
$page,
$pageSize
);
$totalPackages = $paginator->count();
foreach ($paginator as $key => $package) {
$price = null;
if ($package->getPrice()) {
$price .= $package->getPrice()->getValue(); // Accessing the value of the QuantityValue object
}
$throttlingPolicy = intval($package->getThrottlingPolicy());
// Get All Packes data
$packageDataArray[] = [
"id" => $package->getId(),
"type" => $package->getPackagetype(),
"name" => $package->getPackageName('en'),
"name_ar" => $package->getPackageName('ar'),
"price" => $price,
"tenure" => $package->getTenure(),
"throttling" => $throttling = $translator->trans($throttlingArr[$throttlingPolicy], [], null, "en"),
"throttling_ar" => $throttling = $translator->trans($throttlingArr[$throttlingPolicy], [], null, "ar")
];
}
if ($totalPackages > 0) {
return ["success" => true, "data" => $packageDataArray, "paginationVariables" => $paginator->getPaginationData()];
}
return ["success" => false, "message" => $translator->trans("packages_are_not_available")];
}
/**
* List Throttling function
*/
public function listThrottlingPolicies($params, $paginator, $translator)
{
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$lang = isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE;
$policesDataArray = [];
// $apiGroupDataArray = [];
$policies = new DataObject\WSO2Policies\Listing();
$policies->setOrderKey('policyName');
$policies->setOrder('asc');
$paginator = $paginator->paginate(
$policies,
$page,
$pageSize
);
if ($paginator->count() > 0) {
$policesDataArray = [];
foreach ($paginator as $policie) {
$policesDataArray[] = [
"id" => $policie->getId(),
"police_name" => $policie->getPolicyName(),
"police_display_name" => $translator->trans($policie->getDisplayName(), [], null, "en"),
"police_display_name_ar" => $translator->trans($policie->getDisplayName(), [], null, "ar"),
"description" => $policie->getDescription()
];
}
if (!empty($policesDataArray)) {
return ["success" => true, "data" => $policesDataArray, 'paginationVariables' => $paginator->getPaginationData()];
}
}
return ["success" => false, "message" => $translator->trans("throttling_policies_are_not_available")];
}
public function createWsoSubscription($params, $loggedInUser, $translator)
{
$result = [];
$subscriptionType = "default";
$disallowedApiGroupsArray = null;
$package = DataObject\Package::getById($params['package_id']);
if (!$package instanceof DataObject\Package) {
return ["success" => false, "message" => "Package is not available"];
}
$user = Customer::getByEmail($params['email'], true);
if (!$user) {
// register wso user
Utility::validateEmail($params['email']);
Utility::validateName($params['name']);
$user = new DataObject\Customer();
$user->setParent(DataObject\Service::createFolderByPath('/UserManagement/WsoUsers'));
$user->setKey(trim(strip_tags($params['email'])));
$user->setUserType('public');
$user->setName(strip_tags($params['name']));
$user->setEmail(trim(strip_tags($params['email'])));
$user->setIsActive(true);
$user->setSendEwsEmail(false);
$user->setPublished(true);
$user->setCreatedBy($loggedInUser);
$user->setOmitMandatoryCheck(true);
$user->save();
$user->save();
} else {
$user->setName(strip_tags($params['name']));
$user->setCreatedBy($loggedInUser);
$user->setOmitMandatoryCheck(true);
$user->save();
$user->save();
}
$returnMessage = '';
if (isset($params['subscription_id'])) {
$subscription = DataObject\Subscription::getById($params['subscription_id']);
if (!$subscription instanceof DataObject\Subscription) {
return ["success" => false, "message" => $translator->trans("invalid_subscription_id")];
}
$returnMessage = $translator->trans("wso_subscription_updated");
} else {
$subscription = new DataObject\Subscription();
$subscription->setParent(DataObject\Service::createFolderByPath('/WSO2/Subscription/' . $user->getEmail()));
$subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(1000, 10000), 'object'));
$subscription->setPublished(true);
$returnMessage = $translator->trans("wso_subscription_created");
}
$subscriptionExpiry = date('Y-m-d', strtotime('+' . $package->getTenure() . ' days'));
$subscription->setSubscribedPackage($package);
$subscription->setSubscribedUser($user);
$subscription->setIsWso(true);
//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->setIsActive(true);
$subscription->save();
$subscription->save();
// do not send email if subscription id is set
if (!isset($params['subscription_id'])) {
// send an email to the subscriber with the ClientID and Secret Key via C2.
$user->save();
$this->sendEmailSubscriber($subscription, $params['email']);
}
if ($subscription) {
return ["success" => true, "data" => $subscription->getId(), "message" => $returnMessage];
}
}
public function reinviteWsoSubscription($params, $translator)
{
$result = [];
$customer = Customer::getById($params['user_id']);
if (!$customer) {
return ["success" => false, "message" => $translator->trans("invalid_user_id")];
}
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($customer);
$subscriptions->filterByIsActive(true);
$subscription = $subscriptions->current();
$subscription->save();
if ($subscription instanceof DataObject\Subscription) {
$result = $this->sendEmailSubscriber($subscription, $customer->getEmail());
if ($result) {
return ["success" => true, "message" => $translator->trans("reinvite_email_sent")];
}
} else {
return ["success" => false, "message" => $translator->trans('subscription_is_not_available')];
}
}
public function sendEmailSubscriber($subscription, $email)
{
// dd($subscription->getConsumerKey(),$subscription->getId());
$purpose = WSO_SUBSCRIPTION_MESSAGE;
$templateId = $_ENV['WSO_SUBSCRIPTION_TEMPLATE'];
$subject = 'Wso Subscription Email';
$param = [
'name' => $subscription->getSubscribedUser()?->getName(),
'consumerKey' => $subscription->getConsumerKey(),
'consumerSecret' => $subscription->getConsumerSecret(),
'apiEndpointUrl' => $_ENV['WSO_API_ENDPOINT'],
'postmanCollectionUrl' => $_ENV['WSO_POSTMAN_COLLECTION'],
'apiToken' => base64_encode($subscription->getSubscribedUser()?->getUserId() . ':' . $subscription->getSubscribedUser()?->getSecretKey()),
'tenure' => $subscription->getSubscribedPackage()?->getTenure(),
'packageName' => $subscription->getSubscribedPackage()?->getPackageName('en'),
'subscriptionStartDate' => $subscription->getStartDate(),
'subscriptionEndDate' => $subscription->getEndDate(),
];
// Retrieve the PDF asset from website settings
$pdfAssetId = WebsiteSetting::getByName('wso_pdf_document')->getData();
$pdfAsset = Asset::getById($pdfAssetId->getId());
// Check if the asset exists and is a PDF
if ($pdfAsset && $pdfAsset instanceof Asset\Document) {
$pdfFile = $pdfAsset;
} else {
// Handle the case where the asset is not found or not a PDF
$pdfFile = null;
}
$html = $this->templating->render('web2print/wso_subscription_email.html.twig', $param);
$this->c2Service->sendCustomReportEmail($templateId, $subscription->getId(), $email, $html, $subject, [$pdfFile], $purpose);
return true;
}
public function listWsoSubscription($params, $paginator, $translator)
{
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$lang = isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE;
$subscriptionDataArray = [];
// Use raw SQL query with JOINs
$qb = $this->db->createQueryBuilder();
$qb->select([
's.oo_id as id',
's.subscribedUser__id as user_id',
'u.name as user_name',
'u.email as user_email',
's.subscribedPackage__id as package_id',
'p.packageName as package_name',
'p_ar.packageName as package_name_ar',
'creator.name as createdBy',
'u.o_creationDate as createdOn',
's.startDate as subscription_start_date',
's.endDate as subscription_end_date',
's.isActive as subscription_status',
's.subscriptionType as subscription_type'
])
->from('object_subscription', 's')
->leftJoin('s', 'object_customer', 'u', 's.subscribedUser__id = u.oo_id')
->leftJoin('u', 'object_customer', 'creator', 'u.createdBy__id = creator.oo_id')
->leftJoin('s', 'object_localized_query_packages_en', 'p', 's.subscribedPackage__id = p.ooo_id')
->leftJoin('s', 'object_localized_query_packages_ar', 'p_ar', 's.subscribedPackage__id = p_ar.ooo_id')
->where('s.subscribedPackage__id IS NOT NULL AND s.subscribedUser__id IS NOT NULL')
->andWhere('s.isWso = 1');
// Add package filter
if (isset($params['package_id']) && !empty($params['package_id'])) {
$package = DataObject\Package::getById($params['package_id']);
if ($package) {
$qb->andWhere('s.subscribedPackage__id = :package_id')
->setParameter('package_id', $package->getId());
}
}
// Add search filter
if (isset($params['search']) && !empty($params['search'])) {
$searchTerm = "%" . $params['search'] . "%";
$qb->andWhere('u.name LIKE :search OR u.email LIKE :search')
->setParameter('search', $searchTerm);
}
// Apply sorting
$orderKey = $params['orderKey'] ?? null;
$order = $params['order'] ?? 'desc';
// Validate order parameter
if (!in_array(strtolower($order), ['asc', 'desc'])) {
$order = 'desc';
}
// Map orderKey to database fields
$sortingMap = [
'username' => 'u.name',
'email' => 'u.email',
'createdBy' => 'creator.name',
'createdOn' => 'u.o_creationDate',
'packageName' => 'p.packageName',
'status' => 's.isActive',
'startDate' => 's.startDate',
'endDate' => 's.endDate'
];
if ($orderKey && isset($sortingMap[$orderKey])) {
$qb->orderBy($sortingMap[$orderKey], strtoupper($order));
} else {
// Default sorting
$qb->orderBy('s.o_creationDate', 'DESC');
}
// Legacy sorting support (for backward compatibility)
if (isset($params['start_date']) && in_array($params['start_date'], ['asc', 'desc'])) {
$qb->orderBy('s.startDate', strtoupper($params['start_date']));
}
if (isset($params['end_date']) && in_array($params['end_date'], ['asc', 'desc'])) {
$qb->orderBy('s.endDate', strtoupper($params['end_date']));
}
// Execute query and paginate
$paginator = $paginator->paginate($qb, $page, $pageSize);
if ($paginator->count() > 0) {
foreach ($paginator as $row) {
$subscriptionDataArray[] = [
"id" => $row['id'],
'user_id' => $row['user_id'],
'user_name' => $row['user_name'],
'user_email' => $row['user_email'],
"package_id" => $row['package_id'],
"package_name" => $row['package_name'],
"package_name_ar" => $row['package_name_ar'] ?: (function () use ($row) {
// Fallback: get Arabic name using Pimcore ORM
if ($row['package_id']) {
$package = DataObject\Package::getById($row['package_id']);
return $package ? $package->getPackageName('ar') : null;
}
return null;
})(),
'createdBy' => $row['createdBy'],
'createdOn' => $row['createdOn'] ? date('Y-m-d h:i:s', $row['createdOn']) : null,
"subscription_start_date" => $row['subscription_start_date'] ? (new \DateTime('@' . $row['subscription_start_date']))->setTimezone(new \DateTimeZone('Asia/Riyadh')) : null,
"subscription_end_date" => $row['subscription_end_date'] ? (new \DateTime('@' . $row['subscription_end_date']))->setTimezone(new \DateTimeZone('Asia/Riyadh')) : null,
"subscription_status" => (bool)$row['subscription_status'],
"subscription_type" => $row['subscription_type'],
"status" => [
"key" => !$row['subscription_status'] ? $translator->trans("suspended") : (($row['subscription_end_date'] && time() <= $row['subscription_end_date']) ? $translator->trans("active") : $translator->trans("expired")),
"name_en" => !$row['subscription_status'] ? $translator->trans("suspended") : (($row['subscription_end_date'] && time() <= $row['subscription_end_date']) ? $translator->trans("active") : $translator->trans("expired")),
"name_ar" => !$row['subscription_status'] ? $translator->trans("suspended") : (($row['subscription_end_date'] && time() <= $row['subscription_end_date']) ? $translator->trans("active") : $translator->trans("expired"))
]
];
}
if (!empty($subscriptionDataArray)) {
return ["success" => true, "data" => $subscriptionDataArray, 'paginationVariables' => $paginator->getPaginationData()];
}
}
return ["success" => true, "data" => [], 'paginationVariables' => $paginator->getPaginationData()];
}
/**
* Delete Wso Subscription function
*/
public function deleteWsoSubscription($params, $user, $translator)
{
$successDeletes = [];
$failedDeletes = [];
// Loop through each user ID to process deletion
foreach ($params['user_id'] as $userId) {
$customer = DataObject\Customer::getById($userId, true);
if ($customer instanceof DataObject\Customer) {
// Handle subscriptions
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($customer);
$subscriptions->filterByIsWso(true);
foreach ($subscriptions as $subscription) {
$subscription->delete();
\App\Lib\Utility::storeActivityLog($subscription, $user, 'temp user subscription delete', $translator);
}
// Handle customer deletion if they don't have a role or organization
if ($customer->getRole() === null && $customer->getOrganization() === null) {
$customer->delete();
\App\Lib\Utility::storeActivityLog($customer, $user, 'temp user delete', $translator);
}
$successDeletes[] = $userId; // Add user ID to success array
} else {
$failedDeletes[] = $userId; // Add user ID to failed array if customer not found
}
}
// Return the result
if (!empty($failedDeletes)) {
return [
"success" => false,
"message" => $translator->trans('some_users_failed_to_delete'),
'failed_users' => $failedDeletes,
'successful_deletions' => $successDeletes
];
}
// Success message if all deletions were successful
return [
"success" => true,
"message" => $translator->trans('subscriptions_and_temp_users_deleted_successfully'),
'deleted_users' => $successDeletes
];
}
public function updateEntityPackage($package, $organizations, $translator)
{
$totalUpdatedSubscriptions = 0;
$organizationsResult = [];
foreach ($organizations as $organization) {
if (!$organization instanceof DataObject\Organization) {
continue;
}
$activationDate = $organization->getPackageActivationDate() ?: Carbon::now();
$trialLimit = (int)$organization->getTrialLimit();
if ($trialLimit <= 0) {
// fallback to package tenure (days) if trial limit not set
$trialLimit = (int)$package->getTenure();
}
$orgUpdated = 0;
$customers = new DataObject\Customer\Listing();
$customers->setUnpublished(true);
$customers->filterByOrganization($organization);
foreach ($customers as $customer) {
$roleName = $customer->getRole()?->getName();
if (!in_array($roleName, [USER_ROLES['CLIENT_ADMIN'], USER_ROLES['CLIENT_USER']], true)) {
continue;
}
$subscriptions = new DataObject\Subscription\Listing();
$subscriptions->filterBySubscribedUser($customer);
$subscriptions->filterBySubscriptionType("custom");
$subscriptionExpiry = Carbon::parse($activationDate)->copy()->addDays($trialLimit)->format('Y-m-d');
if ($subscriptions->count() > 0) {
foreach ($subscriptions as $subscription) {
$subscription->setEndDate(Carbon::parse(new \DateTime($subscriptionExpiry)));
$subscription->setSubscribedPackage($package);
$subscription->setDisallowedApiGroups(null);
$subscription->save();
$orgUpdated++;
$totalUpdatedSubscriptions++;
}
} else {
$subscription = new DataObject\Subscription();
$subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' . $customer->getEmail()));
$subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(1000, 10000), 'object'));
$subscription->setSubscribedPackage($package);
$subscription->setSubscribedUser($customer);
$subscription->setSubscriptionType("custom");
$subscription->setStartDate(Carbon::parse($activationDate));
$subscription->setEndDate(Carbon::parse(new \DateTime($subscriptionExpiry)));
$subscription->setIsActive(true);
$subscription->setPublished(true);
$subscription->setDisallowedApiGroups(null);
$subscription->save();
$orgUpdated++;
$totalUpdatedSubscriptions++;
}
}
// Sync organization with package
$organization->setIsSMSEnabled((bool)$package->getIsSMSEnabled());
$organization->setPackage($package);
$organization->setIsActive(true);
$organization->save();
$organizationsResult[] = [
'organization_id' => $organization->getId(),
'updated_subscriptions' => $orgUpdated
];
}
return [
"success" => true,
"message" => $translator->trans("total_customer_subscription_updated") . ": " . $totalUpdatedSubscriptions,
"organizations" => $organizationsResult
];
}
/**
* List SMS function
*/
public function listSmsCofiguration($params, $paginator, $translator)
{
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$lang = isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE;
$smsConfigArray = [];
$smsConfig = new DataObject\SmsConfiguration\Listing();
$smsConfig->setOrderKey('order');
$smsConfig->setOrder('asc');
$paginator = $paginator->paginate(
$smsConfig,
$page,
$pageSize
);
if ($paginator->count() > 0) {
$smsConfigArray = [];
foreach ($paginator as $limit) {
$smsConfigArray[] = [
"id" => $limit->getId(),
"limit" => $limit->getLimit(),
];
}
if (!empty($smsConfigArray)) {
return ["success" => true, "data" => $smsConfigArray, 'paginationVariables' => $paginator->getPaginationData()];
}
}
return ["success" => false, "message" => $translator->trans("throttling_policies_are_not_available")];
}
}