<?php
namespace App\Service;
use Pimcore\Db;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\Customer;
use Pimcore\Model\DataObject\Location;
use Pimcore\Model\DataObject\AlertType;
use Pimcore\Model\DataObject\AlertMaster;
use App\Model\CustomNotificationLog\Listing;
use Pimcore\Model\DataObject\AbstractObject;
use Pimcore\Model\DataObject\CustomNotification;
use Pimcore\Model\DataObject\AdvanceCustomNotification;
use Pimcore\Model\DataObject\Data\ObjectMetadata;
use Symfony\Component\Templating\EngineInterface;
use Pimcore\Model\DataObject\MannedAlertSubscription;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Pimcore\Model\DataObject\UserGroup;
use Carbon\Carbon;
class CustomNotificationService
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function subscribeAlerts($customer, $locationIds, $alertType, $title, $color, $units, $minValue, $maxValue, $weatherModel, $alertOnEmail, $alertOnSMS, $calculate, $duration,$frequency=1, $logger, $translator, $mateoMaticsService=null)
{
// try {
// retrieve customer by userId
if (!$customer instanceof Customer) {
throw new \Exception('Customer not found for userId:');
}
// retrieve location by locationId
// $location = DataObject::getById($locationId);
// if (!$location) {
// throw new \Exception('Location not found for locationId: ' . $locationId);
// }
// retrieve alertType by alertType
$alertTypes = new AlertMaster\Listing();
$alertTypes->addConditionParam("alertKey = ? AND units = ?", [$alertType, $units]);
$alertType = $alertTypes->current();
// $alertType = AlertMaster::getByAlertKey($alertType, true);
if (!$alertType) {
throw new \Exception('Alert type not found: ' . $alertType);
}
if (count($locationIds)) {
$notificationIds = [];
foreach ($locationIds as $locationId) {
$location = DataObject::getById($locationId);
if (!$location) {
throw new \Exception('Location not found for locationId: ' . $locationId);
}
$nowRiyadh = Carbon::now('Asia/Riyadh');
$coOrdinates = json_decode($location->getCoOrdinates(), true);
$startDateUtc = $nowRiyadh->copy()->setTimezone('UTC')->format('Y-m-d\TH:00:00\Z');
if (stripos($duration, 'hours') !== false) {
$hours = (int) filter_var($duration, FILTER_SANITIZE_NUMBER_INT);
$durationInterval = $hours;
$endDateRiyadh = $nowRiyadh->copy()->addHours($hours);
} else {
$days = (int) filter_var($duration, FILTER_SANITIZE_NUMBER_INT);
$durationInterval = $days * 24;
$endDateRiyadh = $nowRiyadh->copy()->addDays($days);
}
$endDateUtc = $endDateRiyadh->copy()->setTimezone('UTC')->format('Y-m-d\TH:00:00\Z');
$parameter = $alertType->getMeteoMaticsKey();
$hour = 1;
$model = $weatherModel;
$timezone = new \DateTimeZone("Asia/Riyadh");
try {
$response = $mateoMaticsService->getTempratureByParamsHourly(
$coOrdinates,
$startDateUtc,
$endDateUtc,
$parameter,
$hour,
$model,
$timezone
);
} catch (\Exception $e) {
return [
"success" => false,
"message" => "Parameter {$parameter} is not available in model {$model}"
];
}
$key = \Pimcore\Model\Element\Service::getValidKey($alertType->getAlertKey(), 'object');
// $customNotification = \Pimcore\Model\DataObject::getByPath('/CustomNotification/'.$customer->getEmail().'/'.$key.time());
// if(!$customNotification){
// }
$customNotification = new CustomNotification();
$customNotification->setKey($key . time() . rand(0, 100));
$customNotification->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/Notification/CustomNotification/'));
$customNotification->setTitle($title);
$customNotification->setColor($color);
$customNotification->setUnits($units);
$customNotification->setMinValue($minValue);
$customNotification->setMaxValue($maxValue);
$customNotification->setWeatherModel($weatherModel);
$customNotification->setAlertOnEmail($alertOnEmail);
$customNotification->setAlertOnSMS($alertOnSMS);
$customNotification->setLocation($location);
// set metadata for user
$objectArray = [];
$objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email', 'alert_on_sms'], $customer);
$objectMetadata->setAlert_on_email($alertOnEmail);
$objectMetadata->setAlert_on_sms($alertOnSMS);
array_push($objectArray, $objectMetadata);
$customNotification->setUser($objectArray);
$customNotification->setAlert($alertType);
$customNotification->setStatus(true);
$customNotification->setPublished(true);
$customNotification->setCalculate($calculate);
$customNotification->setDuration($duration);
$customNotification->setFrequency($frequency);
$customNotification->save();
$notificationIds[] = $customNotification->getId();
// Execute notification command if alertOnEmail is true
// $hitCommand = $alertOnEmail == true || $alertOnEmail == '1' ? true : false;
// if ($hitCommand) {
// $commandArguments = ['php', 'bin/console', 'app:get-custom-notification'];
// if ($customNotification->getId()) {
// $commandArguments[] = (string) $customNotification->getId(); // Cast ID to string if needed
// }
// $process = new Process($commandArguments);
// $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
// $process->setTimeout(300); // Set timeout to 300 seconds (5 minutes)
// try {
// $process->mustRun();
// $logger->info("Custom Notification command executed successfully: " . $process->getOutput());
// $result['success'] = true;
// $result['message'] = $process->getOutput();
// } catch (ProcessFailedException $exception) {
// $logger->error("Custom Notification command failed: " . $exception->getMessage());
// $result['success'] = false;
// $result['message'] = "Failed to execute Custom notification command.";
// }
// }
}
\App\Lib\Utility::storeActivityLog($customNotification, $customer, $action = 'create-user-custom-notification', $translator);
return ["success" => true, "data" => $notificationIds, "message" => $translator->trans("alert_created_successfully")];
}
return ["success" => false, "data" => "Location is mandatory"];
// return ["success" => true, "data" => $customNotification->getId()];
// } catch (\Exception $ex) {
// throw new \Exception($ex->getMessage());
// }
}
public function subscribeAlertsByTag($customer, $tagIds, $alertType, $title, $color, $units, $minValue, $maxValue, $weatherModel, $alertOnEmail, $alertOnSMS, $calculate, $duration, $frequency=1, $logger, $translator, $mateoMaticsService=null)
{
if (!$customer instanceof Customer) {
throw new \Exception('Customer not found for userId:');
}
// retrieve alertType by alertType
$alertTypes = new AlertMaster\Listing();
$alertTypes->addConditionParam("alertKey = ? AND units = ?", [$alertType, $units]);
$alertType = $alertTypes->current();
if (!$alertType) {
throw new \Exception('Alert type not found: ' . $alertType);
}
$notificationIds = [];
// Ensure tagIds is an array
if (!is_array($tagIds)) {
$tagIds = [$tagIds];
}
if (count($tagIds)) {
foreach ($tagIds as $tagId) {
$tag = DataObject::getById($tagId);
if (!$tag) {
throw new \Exception('Tag not found for tagId: ' . $tagId);
}
// Assuming Location::getByTag($tag) retrieves multiple locations associated with the tag
$locations = Location::getByTag($tag);
foreach ($locations as $location) {
// Validate weather data availability before creating notification
if ($mateoMaticsService) {
$nowRiyadh = Carbon::now('Asia/Riyadh');
$coOrdinates = json_decode($location->getCoOrdinates(), true);
$startDateUtc = $nowRiyadh->copy()->setTimezone('UTC')->format('Y-m-d\TH:00:00\Z');
if (stripos($duration, 'hours') !== false) {
$hours = (int) filter_var($duration, FILTER_SANITIZE_NUMBER_INT);
$endDateRiyadh = $nowRiyadh->copy()->addHours($hours);
} else {
$days = (int) filter_var($duration, FILTER_SANITIZE_NUMBER_INT);
$endDateRiyadh = $nowRiyadh->copy()->addDays($days);
}
$endDateUtc = $endDateRiyadh->copy()->setTimezone('UTC')->format('Y-m-d\TH:00:00\Z');
$parameter = $alertType->getMeteoMaticsKey();
$hour = 1;
$model = $weatherModel;
$timezone = new \DateTimeZone("Asia/Riyadh");
try {
$response = $mateoMaticsService->getTempratureByParamsHourly(
$coOrdinates,
$startDateUtc,
$endDateUtc,
$parameter,
$hour,
$model,
$timezone
);
} catch (\Exception $e) {
return [
"success" => false,
"message" => "Parameter {$parameter} is not available in model {$model}"
];
}
}
$key = \Pimcore\Model\Element\Service::getValidKey($alertType->getAlertKey(), 'object');
$customNotification = new CustomNotification();
$customNotification->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/Notification/CustomNotification/'));
$customNotification->setKey($key . time() . rand(0, 100));
$customNotification->setTitle($title);
$customNotification->setColor($color);
$customNotification->setUnits($units);
$customNotification->setMinValue($minValue);
$customNotification->setMaxValue($maxValue);
$customNotification->setWeatherModel($weatherModel);
$customNotification->setAlertOnEmail($alertOnEmail);
$customNotification->setAlertOnSMS($alertOnSMS);
$customNotification->setTag($tag);
$customNotification->setLocation($location);
// set metadata for user
$objectArray = [];
$objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email', 'alert_on_sms'], $customer);
$objectMetadata->setAlert_on_email($alertOnEmail);
$objectMetadata->setAlert_on_sms($alertOnSMS);
array_push($objectArray, $objectMetadata);
$customNotification->setUser($objectArray);
$customNotification->setAlert($alertType);
$customNotification->setStatus(true);
$customNotification->setPublished(true);
$customNotification->setCalculate($calculate);
$customNotification->setDuration($duration);
$customNotification->setFrequency($frequency);
$customNotification->save();
$notificationIds[] = $customNotification->getId();
// Execute notification command if alertOnEmail is true
// $hitCommand = $alertOnEmail == true || $alertOnEmail == '1' ? true : false;
// if ($hitCommand) {
// $commandArguments = ['php', 'bin/console', 'app:get-custom-notification'];
// if ($customNotification->getId()) {
// $commandArguments[] = (string) $customNotification->getId(); // Cast ID to string if needed
// }
// $process = new Process($commandArguments);
// $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
// $process->setTimeout(300); // Set timeout to 300 seconds (5 minutes)
// try {
// $process->mustRun();
// $logger->info("Custom Notification command executed successfully: " . $process->getOutput());
// $result['success'] = true;
// $result['message'] = $process->getOutput();
// } catch (ProcessFailedException $exception) {
// $logger->error("Custom Notification command failed: " . $exception->getMessage());
// $result['success'] = false;
// $result['message'] = "Failed to execute Custom notification command.";
// }
// }
}
return ["success" => true, "data" => $notificationIds, "message" => $translator->trans("alert_created_successfully")];
}
return ["success" => false, "data" => "Tag id is mandatory"];
}
}
public function unSubscribeAlerts($customer, $locationId, $alertType, $translator)
{
try {
// retrieve customer by userId
if (!$customer instanceof \Pimcore\Model\DataObject) {
throw new \Exception('Customer not found');
}
// retrieve location by locationId
$location = DataObject::getById($locationId);
if (!$location) {
throw new \Exception('Location not found for locationId: ' . $locationId);
}
// retrieve alertType by alertType
$alertType = AlertMaster::getByAlertKey($alertType, true);
if (!$alertType) {
throw new \Exception('Alert type not found: ' . $alertType);
}
$customNotification = new CustomNotification\Listing();
// $customNotification->filterByUser($customer);
$customNotification->addConditionParam("user like '%," . $customer->getId() . ",%'");
$customNotification->filterByLocation($location);
$customNotification->filterByAlert($alertType);
$customNotifications = $customNotification->load();
if ($customNotifications) {
foreach ($customNotifications as $customNotification) {
$objectArray = ($customNotification) ? $customNotification->getUser() : [];
if ($objectArray) {
foreach ($objectArray as $key => $objUser) {
// added below new line to remove the user from the array
$currentUser = $objUser->getObject();
if ($currentUser->getId() == $customer->getId()) {
unset($objectArray[$key]);
}
}
}
// If no other users left, delete the customNotification
if (empty($objectArray)) {
$customNotification->delete();
return ["success" => true, "message" => $translator->trans("customer_notification_removed")];
}
$customNotification->setUser($objectArray);
$customNotification->save();
return ["success" => true, "message" => $translator->trans("customer_notification_removed")];
}
} else {
return ["success" => false, "message" => $translator->trans("notification_not_found")];
}
// if ($customNotifications) {
// $customNotifications[0]->setStatus(false);
// $customNotification = $customNotifications[0]->save();
// $customNotification->delete();
// return ["success" => true, "message" => $translator->trans("customer_notification_removed")];
// } else {
// return ["success" => false, "message" => $translator->trans("notification_not_found")];
// }
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
}
public function unSubscribeAlertsBulk($customer, $notificationIds, $translator)
{
$userId = $customer->getId();
// retrieve customer by userId
if (!$customer instanceof Customer) {
return ["success" => false, "message" => $translator->trans("customer_not_found")];
}
foreach ($notificationIds as $notificationId) {
$notification = CustomNotification::getById($notificationId);
if (!$notification) {
return ["success" => false, "message" => $translator->trans('notification_not_found') . " {$notificationId}"];
}
$existingUsers = $notification->getUser();
$remainingUsers = [];
$userFound = false;
foreach ($existingUsers as $user) {
// print_r($user->getObjectId());
if ($user->getObjectId() && $user->getObjectId() == $userId) {
$userFound = true;
continue; // skip this user (removing)
}
$remainingUsers[] = $user;
}
// Only act if the user was part of this notification
if ($userFound) {
if (count($remainingUsers) === 0) {
// No other users — delete the notification
$notification->delete();
\App\Lib\Utility::storeActivityLog($notification, $user, $action = 'delete-notification', $translator);
} else {
// Save updated user list
$notification->setUser($remainingUsers);
$notification->save();
}
}
}
return ["success" => true, "message" => $translator->trans("customer_notifications_removed")];
}
public function getUserAlerts($userId, $locationId, $params, $paginator)
{
$response = [];
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
// retrieve customer by userId
$customer = DataObject::getById($userId);
if (!$customer) {
throw new \Exception('Customer not found for userId: ' . $userId);
}
$customerId = $customer->getId();
if ($locationId > 0) {
$locationId = DataObject::getById($locationId);
if (!$locationId) {
throw new \Exception('Location not found for userId: ' . $locationId);
}
}
// Get All the Classes
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$custom_notification = $class->getDao()->getIdByName('CustomNotification');
$customer = $class->getDao()->getIdByName('Customer');
$location = $class->getDao()->getIdByName('Location');
$tag = $class->getDao()->getIdByName('Tags');
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('notification.oo_id');
$select->from('object_' . $custom_notification, 'notification');
//$select->leftJoin('notification', 'object_query_' . $customer, 'customer', 'customer.oo_id = notification.user__id');
$select->leftJoin('notification', 'object_query_' . $location, 'location', 'location.oo_id = notification.location__id');
$select->leftJoin('location', 'object_query_' . $tag, 'tag', 'tag.oo_id = location.Tag');
if (isset($params['title']) && !empty($params['title'])) {
$select->andWhere("notification.title LIKE " . $db->quote("%" . $params['title'] . "%"));
}
if (isset($params['color']) && !empty($params['color'])) {
$select->andWhere("notification.color LIKE " . $db->quote("%" . $params['color'] . "%"));
}
if (isset($params['calculation']) && !empty($params['calculation'])) {
$select->andWhere("notification.calculate LIKE " . $db->quote("%" . $params['calculation'] . "%"));
}
if (isset($params['weatherModel']) && !empty($params['weatherModel'])) {
$select->andWhere("notification.weatherModel LIKE " . $db->quote("%" . $params['weatherModel'] . "%"));
}
if (isset($params['tagId']) && !empty($params['tagId'])) {
$tagConditions = [];
foreach ($params['tagId'] as $tag) {
$tagConditions[] = "location.Tag LIKE " . $db->quote("%" . $tag . "%");
}
$select->andWhere(implode(' OR ', $tagConditions));
}
$select->andWhere("notification.user like " . $db->quote("%" . $customerId . "%"));
$select->andWhere("o_published = 1");
// $select->andWhere("notification.user__id = ".$db->quote($userId));
$select->orderBy('oo_id', 'DESC');
$select->groupBy(array('oo_id'));
// Bind parameters
$paginator = $paginator->paginate(
$select,
$page,
$pageSize
);
if ($select) {
foreach ($paginator as $customNotification) {
$customNotification = DataObject\CustomNotification::getById($customNotification['oo_id'], true);
if ($customNotification instanceof \Pimcore\Model\DataObject\CustomNotification) {
if ($customNotification->getLocation() && $customNotification->getAlert()) {
$tags = [];
if ($customNotification->getLocation()) {
foreach ($customNotification->getLocation()->getTag() as $tag) {
$tags[] = [
"id" => $tag->getId(),
"nameEn" => ($tag->getTagName('en') == "" || $tag->getTagName('en') == null) ? null : $tag->getTagName('en'),
"nameAr" => ($tag->getTagName('ar') == "" || $tag->getTagName('ar') == null) ? null : $tag->getTagName('ar'),
"metaDataEn" => ($tag->getMetaData('en') == "" || $tag->getMetaData('en') == null) ? null : $tag->getMetaData('en'),
"metaDataAr" => ($tag->getMetaData('ar') == "" || $tag->getMetaData('ar') == null) ? null : $tag->getMetaData('ar'),
];
}
}
$objectArray = ($customNotification) ? $customNotification->getUser() : [];
$userMetaData = [];
if ($objectArray) {
foreach ($objectArray as $key => $objUser) {
$currentUser = $objUser->getObject();
if ($currentUser->getId() == $userId) {
$userData = $objUser->getData();
$userMetaData['alert_on_email'] = isset($userData['alert_on_email']) && $userData['alert_on_email'] == '1' ? true : false;
$userMetaData['alert_on_sms'] = isset($userData['alert_on_sms']) && $userData['alert_on_sms'] == '1' ? true : false;
break; // Stop the loop once a match is found
}
}
}
$userGroups = [];
if ($customNotification->getUserGroup()) {
foreach ($customNotification->getUserGroup() as $userGroup) {
$userGroups[] = [
"id" => $userGroup->getId(),
"groupName_en" => $userGroup->getGroupName("en"),
"groupName_ar" => $userGroup->getGroupName("ar"),
];
}
}
$response[] = [
"id" => $customNotification->getId(),
'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
"alert_type" => $customNotification->getAlert()->getName(),
"alert_key" => $customNotification->getAlert()->getAlertKey(),
"parameter_name_en" => $customNotification->getAlert()->getName("en"),
"parameter_name_ar" => $customNotification->getAlert()->getName("ar"),
"location_name" => $customNotification->getLocation()->getTitle(),
"title" => $customNotification->gettitle(),
"color" => $customNotification->getColor(),
"color_ar" => (\App\Lib\Utility::getArabicTranslation($customNotification->getColor(), CUSTOM_NOTIFICATION_COLORS) ? \App\Lib\Utility::getArabicTranslation($customNotification->getColor(), CUSTOM_NOTIFICATION_COLORS) : ''),
"units" => $customNotification->getunits(),
"units_ar" => (\App\Lib\Utility::getArabicTranslationUnits($customNotification->getunits()) ? \App\Lib\Utility::getArabicTranslationUnits($customNotification->getunits()) : ''),
"min_value" => $customNotification->getMinValue(),
"max_value" => $customNotification->getMaxValue(),
"weather_model" => $customNotification->getWeatherModel(),
"alert_on_email" => $userMetaData['alert_on_email'],
"alert_on_sms" => $userMetaData['alert_on_sms'],
"calculation" => $customNotification->getCalculate(),
"calculation_ar" => (\App\Lib\Utility::getArabicTranslation($customNotification->getCalculate(), CUSTOM_NOTIFICATION_CONDITION) ? \App\Lib\Utility::getArabicTranslation($customNotification->getCalculate(), CUSTOM_NOTIFICATION_CONDITION) : ''),
"duration" => $customNotification->getDuration(),
"frequency" => $customNotification->getFrequency(),
"tags" => $tags,
"userGroups" => $userGroups
];
}
}
}
}
return ["success" => true, "data" => $response, 'paginationVariables' => $paginator->getPaginationData()];
}
public function getAlertMaster()
{
$response = [];
$alertMaster = new DataObject\AlertMaster\Listing();
$alertMaster->addConditionParam("isHidden is null OR isHidden = 0");
$alertMaster->setOrderKey("order");
$alertMaster->setOrder("asc");
$alertMasters = $alertMaster->load();
if ($alertMasters) {
foreach ($alertMasters as $alertMaster) {
$response[] = ["id" => $alertMaster->getId(), "name_en" => $alertMaster->getName('en'), "name_ar" => $alertMaster->getName('ar'), "alert_key" => $alertMaster->getAlertKey(), "meteo_matics_key" => $alertMaster->getMeteoMaticsKey(), "units" => $alertMaster->getUnits(), "unit_title" => $alertMaster->getUnitTitle('en'), "unit_title_ar" => $alertMaster->getUnitTitle('ar')];
}
}
return ["success" => true, "data" => $response];
}
public function mannedAlertFilters()
{
$response = [];
$alertMaster = new DataObject\AlertStatus\Listing();
$alertMasters = $alertMaster->load();
$imageTemplate = [];
if ($alertMasters) {
foreach ($alertMasters as $alertMaster) {
//if(!in_array($alertMaster->getImageTemplate(),$imageTemplate)){
$response['alert_status'][] = ["id" => $alertMaster->getAlertStatusId(), "name_en" => $alertMaster->getName('en'), "name_ar" => $alertMaster->getName('ar')];
// $imageTemplate[] = $alertMaster->getName('en');
// }
}
}
$regionMaster = new DataObject\Region\Listing();
$regionMasters = $regionMaster->load();
if ($regionMasters) {
foreach ($regionMasters as $regionMaster) {
$response['regions'][] = ["id" => $regionMaster->getRegionId(), "name_en" => $regionMaster->getName('en'), "name_ar" => $regionMaster->getName('ar')];
}
}
$alertHazardMaster = new DataObject\AlertHazard\Listing();
$alertHazardMasters = $alertHazardMaster->load();
if ($alertHazardMasters) {
foreach ($alertHazardMasters as $alertHazardMaster) {
$response['alert_hazards'][] = ["id" => $alertHazardMaster->getAlertHazardId(), "name_en" => $alertHazardMaster->getName('en'), "name_ar" => $alertHazardMaster->getName('ar')];
}
}
$alertTypeMaster = new DataObject\AlertType\Listing();
$alertTypeMasters = $alertTypeMaster->load();
if ($alertTypeMasters) {
foreach ($alertTypeMasters as $alertTypeMaster) {
$response['alert_type'][] = ["id" => $alertTypeMaster->getAlertTypeId(), "name_en" => $alertTypeMaster->getName('en'), "name_ar" => $alertTypeMaster->getName('ar')];
}
}
$alertActionMaster = new DataObject\AlertAction\Listing();
$alertActionMasters = $alertActionMaster->load();
if ($alertActionMasters) {
$alertActionArr = [];
foreach ($alertActionMasters as $alertActionMaster) {
//if(!in_array($alertActionMaster->getSeverity(),$alertActionArr)){
$response['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "severity" => ucwords($alertActionMaster->getName('en'))];
// $alertActionArr[] = $alertActionMaster->getSeverity();
//}
}
}
return ["success" => true, "data" => $response];
}
// public function getMannedAlerts($params, $paginator)
// {
// $response = [];
// $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
// $page = isset($params['page']) ? $params['page'] : 1;
// $mannedAlert = new DataObject\MannedAlertNotification\Listing();
// //$mannedAlert->setCondition("o_creationDate > " . strtotime('-2 days'));
// if (!empty($params['alert_status'])) {
// $alertStatusSql = null;
// foreach ($params['alert_status'] as $alertStatus) {
// $alertStatus = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatus, true);
// if ($alertStatus) {
// $alertStatusSql .= "alertStatus__id = " . $alertStatus->getId() . " OR ";
// }
// }
// $mannedAlert->addConditionParam("(" . substr($alertStatusSql, 0, -3) . ")");
// }
// if (isset($params['id']) && !empty($params['id'])) {
// $idSql = '';
// $idSql .= "alertId = " . $params['id'] . " OR ";
// $mannedAlert->addConditionParam("(" . substr($idSql, 0, -3) . ")");
// }
// if (!empty($params['alert_region'])) {
// $alertRegionSql = null;
// foreach ($params['alert_region'] as $alertRegionId) {
// $alertRegion = \Pimcore\Model\DataObject\Region::getByRegionId($alertRegionId, true);
// if ($alertRegion) {
// $alertRegionSql .= "region__id = " . $alertRegion->getId() . " OR ";
// }
// }
// if (!empty($alertRegion)) {
// $mannedAlert->addConditionParam("(" . substr($alertRegionSql, 0, -3) . ")");
// }
// }
// // added filter for public portal
// if (isset($params['governorate_id']) && !empty($params['governorate_id'])) {
// $alertGovernorateSql = null;
// foreach ($params['governorate_id'] as $alertGovernorateId) {
// $alertGovernorate = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($alertGovernorateId, true);
// if ($alertGovernorate) {
// $alertGovernorateSql .= "governorates LIKE '%," . $alertGovernorate->getId() . ",%' OR ";
// }
// }
// if (!empty($alertGovernorateSql)) {
// $mannedAlert->addConditionParam("(" . substr($alertGovernorateSql, 0, -3) . ")");
// }
// }
// if (!empty($params['alert_type'])) {
// $alertTypeSql = null;
// foreach ($params['alert_type'] as $alertTypeId) {
// $alertType = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alertTypeId, true);
// if ($alertType) {
// $alertTypeSql .= "alertType__id = " . $alertType->getId() . " OR ";
// }
// }
// if (!empty($alertTypeSql)) {
// $mannedAlert->addConditionParam("(" . substr($alertTypeSql, 0, -3) . ")");
// }
// }
// if (!empty($params['alert_actions'])) {
// $alertActionIdSql = "";
// foreach ($params['alert_actions'] as $alertAction) {
// $alertAction = \Pimcore\Model\DataObject\AlertAction::getByAlertActionId($alertAction, true);
// if ($alertAction) {
// $alertActionIdSql .= "alertAction LIKE '%," . $alertAction->getId() . ",%' OR ";
// }
// }
// if (!empty($alertActionIdSql)) {
// $mannedAlert->addConditionParam("(" . substr($alertActionIdSql, 0, -3) . ")");
// }
// }
// if (!empty($params['from_date']) && !empty($params['to_date'])) {
// // $mannedAlert->filterByFromDate($params['from_date'], ">=");
// // $mannedAlert->filterByToDate($params['to_date'], "<=");
// // $mannedAlert->filterByFromDate(strtotime($params['from_date']), ">=");
// $mannedAlert->filterByToDate(time(), ">=");
// }
// $mannedAlert->setOrderKey("lastModifiedDate");
// $mannedAlert->setOrder("desc");
// $mannedAlerts = $mannedAlert->load();
// // code for devide api which does not need pagination
// if ($paginator == null) {
// $count = 0;
// foreach ($mannedAlerts as $mannedAlert) {
// $response[$count] = [
// "id" => $mannedAlert->getAlertId(),
// "title" => $mannedAlert->getTitle(),
// "other_locations" => [
// "en" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('en') : null,
// "ar" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('ar') : null
// ],
// "alert_type" => [
// "id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
// "en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
// "ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
// "color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
// ],
// "fromDate" => $mannedAlert->getFromDate()->toDateTimeString(),
// "toDate" => $mannedAlert->getToDate()->toDateTimeString(),
// "lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
// "rawData" => $mannedAlert->getRawText(),
// "region" => [
// "id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
// "en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
// "ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
// ],
// "alert_status" => [
// "id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
// "en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
// "ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
// ]
// ];
// $alertHazards = $mannedAlert->getalertHazards();
// if ($alertHazards) {
// foreach ($alertHazards as $alertHazard) {
// $response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
// }
// }
// $governorates = $mannedAlert->getGovernorates();
// if ($governorates) {
// $alertJsonDecodeData = json_decode($mannedAlert->getRawText());
// $governoratesData = $alertJsonDecodeData->governorates;
// foreach ($governorates as $governorate) {
// $isEnrireGovernorate = false;
// foreach ($governoratesData as $governorateData) {
// if ($governorateData->id == $governorate->getGovernoteId()) {
// if (count($governorateData->municipalities) == 0) {
// $isEnrireGovernorate = true;
// break;
// }
// }
// }
// $response[$count]['governorates'][] = ["id" => $governorate->getGovernoteId(), "name_en" => $governorate->getName('en'), "name_ar" => $governorate->getName('ar'), 'isEnrireGovernorate' => $isEnrireGovernorate];
// }
// }
// $alertActionMasters = $mannedAlert->getAlertAction();
// if ($alertActionMasters) {
// foreach ($alertActionMasters as $alertActionMaster) {
// $response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
// }
// }
// $alert = json_decode($mannedAlert->getRawText(), true);
// // extra param js
// $alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
// $alertName = $alertObj->getName() ? $alertObj->getName() : '';
// $alert['host'] = API_BASE_URL;
// $alert['alertColor'] = $alertName;
// $backgroundColor = '#fcb82526';
// $borderColor = '#000000';
// $textColor = '#000000';
// if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
// $alertColorLower = strtolower(trim($alert['alertColor']));
// if ($alertColorLower === 'red') {
// $backgroundColor = '#f6000017';
// $borderColor = '#F60000';
// $textColor = '#F60000';
// } elseif ($alertColorLower === 'orange') {
// $backgroundColor = '#ff66001f';
// $borderColor = '#FF6600';
// $textColor = '#FF6600';
// } elseif ($alertColorLower === 'yellow') {
// $backgroundColor = '#fcb82526';
// $borderColor = '#FCB825';
// $textColor = '#FCB825';
// }
// }
// $alert['backgroundColor'] = $backgroundColor;
// $alert['borderColor'] = $borderColor;
// $alert['textColor'] = $textColor;
// $alert['name'] = ""; // ned to fiex this
// if ($mannedAlert->getRawText()) {
// $html = $this->templating->render('web2print/_manned_alert_notification_en.html.twig', $alert);
// $response[$count]['message_en'] = $html;
// $html = $this->templating->render('web2print/_manned_alert_notification.html.twig', $alert);
// $response[$count]['message_ar'] = $html;
// } else {
// $response[$count]['message'] = [];
// }
// $count++;
// }
// return ["success" => true, "data" => $response];
// }
// $paginator = $paginator->paginate(
// $mannedAlerts,
// $page,
// $pageSize
// );
// if ($paginator) {
// $count = 0;
// foreach ($paginator as $mannedAlert) {
// $response[$count] = [
// "id" => $mannedAlert->getAlertId(),
// "title" => $mannedAlert->getTitle(),
// "other_locations" => [
// "en" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('en') : null,
// "ar" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('ar') : null
// ],
// "alert_type" => [
// "id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
// "en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
// "ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
// "color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
// ],
// "fromDate" => $mannedAlert->getFromDate()->toDateTimeString(),
// "toDate" => $mannedAlert->getToDate()->toDateTimeString(),
// "lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
// "region" => [
// "id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
// "en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
// "ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
// ],
// "alert_status" => [
// "id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
// "en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
// "ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
// ]
// ];
// $alertHazards = $mannedAlert->getalertHazards();
// if ($alertHazards) {
// foreach ($alertHazards as $alertHazard) {
// $response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
// }
// }
// $governorates = $mannedAlert->getGovernorates();
// if ($governorates) {
// foreach ($governorates as $governorate) {
// $response[$count]['governorates'][] = ["id" => $governorate->getGovernoteId(), "name_en" => $governorate->getName('en'), "name_ar" => $governorate->getName('ar')];
// }
// }
// $alertActionMasters = $mannedAlert->getAlertAction();
// if ($alertActionMasters) {
// foreach ($alertActionMasters as $alertActionMaster) {
// $response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
// }
// }
// $alert = json_decode($mannedAlert->getRawText(), true);
// // extra param js
// $alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
// $alertName = $alertObj->getName() ? $alertObj->getName() : '';
// $alert['host'] = API_BASE_URL;
// $alert['alertColor'] = $alertName;
// $backgroundColor = '#fcb82526';
// $borderColor = '#000000';
// $textColor = '#000000';
// if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
// $alertColorLower = strtolower(trim($alert['alertColor']));
// if ($alertColorLower === 'red') {
// $backgroundColor = '#f6000017';
// $borderColor = '#F60000';
// $textColor = '#F60000';
// } elseif ($alertColorLower === 'orange') {
// $backgroundColor = '#ff66001f';
// $borderColor = '#FF6600';
// $textColor = '#FF6600';
// } elseif ($alertColorLower === 'yellow') {
// $backgroundColor = '#fcb82526';
// $borderColor = '#FCB825';
// $textColor = '#FCB825';
// }
// }
// $alert['backgroundColor'] = $backgroundColor;
// $alert['borderColor'] = $borderColor;
// $alert['textColor'] = $textColor;
// $alert['name'] = ""; // ned to fiex this
// if ($mannedAlert->getRawText()) {
// $html = $this->templating->render('web2print/_manned_alert_notification_en.html.twig', $alert);
// $response[$count]['message_en'] = $html;
// $html = $this->templating->render('web2print/_manned_alert_notification.html.twig', $alert);
// $response[$count]['message_ar'] = $html;
// } else {
// $response[$count]['message'] = [];
// }
// $count++;
// }
// }
// return ["success" => true, "total" => count($mannedAlerts), "data" => $response, "paginationVariables" => $paginator->getPaginationData()];
// }
public function getMannedAlerts($params, $paginator)
{
$response = [];
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$mannedAlert = new DataObject\EwsNotification\Listing();
$mannedAlert->filterByIsManned(1);
//$mannedAlert->setCondition("o_creationDate > " . strtotime('-2 days'));
if (!empty($params['alert_status'])) {
$alertStatusSql = null;
foreach ($params['alert_status'] as $alertStatus) {
$alertStatus = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatus, true);
if ($alertStatus) {
$alertStatusSql .= "alertStatus__id = " . $alertStatus->getId() . " OR ";
}
}
$mannedAlert->addConditionParam("(" . substr($alertStatusSql, 0, -3) . ")");
}
if (isset($params['id']) && !empty($params['id'])) {
$idSql = '';
$idSql .= "alertId = " . $params['id'] . " OR ";
$mannedAlert->addConditionParam("(" . substr($idSql, 0, -3) . ")");
}
if (!empty($params['alert_region'])) {
$alertRegionSql = null;
foreach ($params['alert_region'] as $alertRegionId) {
$alertRegion = \Pimcore\Model\DataObject\Region::getByRegionId($alertRegionId, true);
if ($alertRegion) {
$alertRegionSql .= "region__id = " . $alertRegion->getId() . " OR ";
}
}
if (!empty($alertRegion)) {
$mannedAlert->addConditionParam("(" . substr($alertRegionSql, 0, -3) . ")");
}
}
// added filter for public portal
if (isset($params['governorate_id']) && !empty($params['governorate_id'])) {
$alertGovernorateSql = null;
foreach ($params['governorate_id'] as $alertGovernorateId) {
$alertGovernorate = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($alertGovernorateId, true);
if ($alertGovernorate) {
$alertGovernorateSql .= "governorate LIKE '%," . $alertGovernorate->getId() . ",%' OR ";
}
}
if (!empty($alertGovernorateSql)) {
$mannedAlert->addConditionParam("(" . substr($alertGovernorateSql, 0, -3) . ")");
}
}
if (!empty($params['alert_type'])) {
$alertTypeSql = null;
foreach ($params['alert_type'] as $alertTypeId) {
$alertType = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alertTypeId, true);
if ($alertType) {
$alertTypeSql .= "alertType__id = " . $alertType->getId() . " OR ";
}
}
if (!empty($alertTypeSql)) {
$mannedAlert->addConditionParam("(" . substr($alertTypeSql, 0, -3) . ")");
}
}
if (!empty($params['alert_actions'])) {
$alertActionIdSql = "";
foreach ($params['alert_actions'] as $alertAction) {
$alertAction = \Pimcore\Model\DataObject\AlertAction::getByAlertActionId($alertAction, true);
if ($alertAction) {
$alertActionIdSql .= "alertAction LIKE '%," . $alertAction->getId() . ",%' OR ";
}
}
if (!empty($alertActionIdSql)) {
$mannedAlert->addConditionParam("(" . substr($alertActionIdSql, 0, -3) . ")");
}
}
if (!empty($params['from_date']) && !empty($params['to_date'])) {
// $mannedAlert->filterByFromDate($params['from_date'], ">=");
// $mannedAlert->filterByToDate($params['to_date'], "<=");
// $mannedAlert->filterByFromDate(strtotime($params['from_date']), ">=");
$mannedAlert->filterByEndDate(time(), ">=");
}
$mannedAlert->setOrderKey("lastModifiedDate");
$mannedAlert->setOrder("desc");
$mannedAlerts = $mannedAlert->load();
$timezone = new \DateTimeZone(TIMEZONE);
// code for devide api which does not need pagination
if ($paginator == null) {
$count = 0;
foreach ($mannedAlerts as $mannedAlert) {
$response[$count] = [
"id" => $mannedAlert->getAlertId(),
"title" => $mannedAlert->getTitle(),
"other_locations" => [
"en" => $mannedAlert->getOtherLocation(),
"ar" => $mannedAlert->getOtherLocation()
],
"alert_type" => [
"id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
"en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
"ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
"color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
],
"fromDate" => $mannedAlert->getStartDate()->setTimezone($timezone)->toDateTimeString(),
"toDate" => $mannedAlert->getEndDate()->setTimezone($timezone)->toDateTimeString(),
"lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
"rawData" => $mannedAlert->getRawText(),
"region" => [
"id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
"en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
"ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
],
"alert_status" => [
"id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
"en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
"ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
]
];
$alertHazards = $mannedAlert->getalertHazard();
if ($alertHazards) {
foreach ($alertHazards as $alertHazard) {
$response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
}
}
$governorates = $mannedAlert->getGovernorate();
if ($governorates) {
$alertJsonDecodeData = json_decode($mannedAlert->getRawText());
$governoratesData = $alertJsonDecodeData->governorates;
foreach ($governorates as $governorate) {
$isEnrireGovernorate = false;
$municipalities = [];
foreach ($governoratesData as $governorateData) {
if ($governorateData->id == $governorate->getGovernoteId()) {
if (count($governorateData->municipalities) == 0) {
$isEnrireGovernorate = true;
} else {
foreach ($governorateData->municipalities as $municipality) {
$municipalities[] = [
"id" => $municipality->id,
"name_en" => $municipality->nameEn,
"name_ar" => $municipality->nameAr,
"longitude" => $municipality->longitude,
"latitude" => $municipality->latitude
];
}
}
break;
}
}
$response[$count]['governorates'][] = [
"id" => $governorate->getGovernoteId(),
"name_en" => $governorate->getName('en'),
"name_ar" => $governorate->getName('ar'),
'isEnrireGovernorate' => $isEnrireGovernorate,
'municipalities' => $municipalities
];
}
}
$alertActionMasters = $mannedAlert->getAlertAction();
if ($alertActionMasters) {
foreach ($alertActionMasters as $alertActionMaster) {
$response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
}
}
$alert = json_decode($mannedAlert->getRawText(), true);
// extra param js
$alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
$alertName = $alertObj->getName() ? $alertObj->getName() : '';
$alert['host'] = API_BASE_URL;
$alert['alertColor'] = $alertName;
$backgroundColor = '#fcb82526';
$borderColor = '#000000';
$textColor = '#000000';
if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
$alertColorLower = strtolower(trim($alert['alertColor']));
if ($alertColorLower === 'red') {
$backgroundColor = '#f6000017';
$borderColor = '#F60000';
$textColor = '#F60000';
} elseif ($alertColorLower === 'orange') {
$backgroundColor = '#ff66001f';
$borderColor = '#FF6600';
$textColor = '#FF6600';
} elseif ($alertColorLower === 'yellow') {
$backgroundColor = '#fcb82526';
$borderColor = '#FCB825';
$textColor = '#FCB825';
}
}
$alert['backgroundColor'] = $backgroundColor;
$alert['borderColor'] = $borderColor;
$alert['textColor'] = $textColor;
$alert['name'] = ""; // ned to fiex this
if ($mannedAlert->getRawText()) {
$html = $this->templating->render('web2print/_manned_alert_notification_en.html.twig', $alert);
$response[$count]['message_en'] = $html;
$html = $this->templating->render('web2print/_manned_alert_notification.html.twig', $alert);
$response[$count]['message_ar'] = $html;
} else {
$response[$count]['message'] = [];
}
$count++;
}
return ["success" => true, "data" => $response];
}
$paginator = $paginator->paginate(
$mannedAlerts,
$page,
$pageSize
);
if ($paginator) {
$count = 0;
foreach ($paginator as $mannedAlert) {
$response[$count] = [
"id" => $mannedAlert->getAlertId(),
"title" => $mannedAlert->getTitle(),
"other_locations" => [
"en" => $mannedAlert->getOtherLocation(),
"ar" => $mannedAlert->getOtherLocation()
],
"alert_type" => [
"id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
"en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
"ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
"color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
],
"fromDate" => $mannedAlert->getStartDate()->toDateTimeString(),
"toDate" => $mannedAlert->getEndDate()->toDateTimeString(),
"lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
"region" => [
"id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
"en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
"ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
],
"alert_status" => [
"id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
"en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
"ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
]
];
$alertHazards = $mannedAlert->getalertHazard();
if ($alertHazards) {
foreach ($alertHazards as $alertHazard) {
$response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
}
}
$governorates = $mannedAlert->getGovernorate();
if ($governorates) {
foreach ($governorates as $governorate) {
$response[$count]['governorates'][] = ["id" => $governorate->getGovernoteId(), "name_en" => $governorate->getName('en'), "name_ar" => $governorate->getName('ar')];
}
}
$alertActionMasters = $mannedAlert->getAlertAction();
if ($alertActionMasters) {
foreach ($alertActionMasters as $alertActionMaster) {
$response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
}
}
$alert = json_decode($mannedAlert->getRawText(), true);
// extra param js
$alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
$alertName = $alertObj->getName() ? $alertObj->getName() : '';
$alert['host'] = API_BASE_URL;
$alert['alertColor'] = $alertName;
$backgroundColor = '#fcb82526';
$borderColor = '#000000';
$textColor = '#000000';
if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
$alertColorLower = strtolower(trim($alert['alertColor']));
if ($alertColorLower === 'red') {
$backgroundColor = '#f6000017';
$borderColor = '#F60000';
$textColor = '#F60000';
} elseif ($alertColorLower === 'orange') {
$backgroundColor = '#ff66001f';
$borderColor = '#FF6600';
$textColor = '#FF6600';
} elseif ($alertColorLower === 'yellow') {
$backgroundColor = '#fcb82526';
$borderColor = '#FCB825';
$textColor = '#FCB825';
}
}
$alert['backgroundColor'] = $backgroundColor;
$alert['borderColor'] = $borderColor;
$alert['textColor'] = $textColor;
$alert['name'] = ""; // ned to fiex this
if ($mannedAlert->getRawText()) {
$html = $this->templating->render('web2print/_manned_alert_notification_en.html.twig', $alert);
$response[$count]['message_en'] = $html;
$html = $this->templating->render('web2print/_manned_alert_notification.html.twig', $alert);
$response[$count]['message_ar'] = $html;
} else {
$response[$count]['message'] = [];
}
$count++;
}
}
return ["success" => true, "total" => count($mannedAlerts), "data" => $response, "paginationVariables" => $paginator->getPaginationData()];
}
public function getAlertHistory($user, $params)
{
$response = [];
$alertHistory = new DataObject\AlertHistory\Listing();
$alertHistory->filterByUser($user);
if (!empty($params['location_id'])) {
$location_id = $params['location_id'];
$alertHistory->addConditionParam("Location__id = ?", $location_id, "AND");
}
if (!empty($params['title'])) {
$title = $params['title'];
$alertHistory->addConditionParam("AdministrativeTitle LIKE ?", "%$title%", "AND");
}
$alertHistory->setOffset(!empty($params['offset']) ? $params['offset'] : 0);
$alertHistory->setLimit(!empty($params['limit']) ? $params['limit'] : LIMIT_PER_PAGE);
$alertHistory->setOrderKey("o_creationDate");
$alertHistory->setOrder("desc");
$alertHistorys = $alertHistory->load();
if ($alertHistorys) {
foreach ($alertHistorys as $alertHistory) {
$response[] = [
"id" => $alertHistory->getId(),
"modification_date" => $alertHistory->getModificaitonDate()->toDateTimeString(),
"title" => $alertHistory->getAdministrativeTitle(),
"color" => $alertHistory->getColorCode(),
"units" => $alertHistory->getUnits(),
"min_value" => $alertHistory->getMinValue(),
"max_value" => $alertHistory->getMaxValue(),
"weather_model" => $alertHistory->getWeatherModel(),
"alert_enable" => $alertHistory->getAlertEnable(),
"alert_type" => $alertHistory->getAlertType(),
"location" => ($alertHistory->getLocation()) ? $alertHistory->getLocation()->getName() : '',
"user" => $alertHistory->getUser()->getEmail(),
"is_sent" => $alertHistory->getisSent(),
];
}
}
return ["success" => true, "total" => count($alertHistorys), "data" => $response];
}
public function getCustomNotificationLog($id)
{
$notificationArr = [];
$notificationLog = new Listing();
if ($id) {
$notificationLog->setCondition("customNotificationId = {$id}");
}
$notifications = $notificationLog->load();
if ($notifications) {
$count = 0;
foreach ($notifications as $notification) {
$customNotification = \Pimcore\Model\DataObject::getById($notification->getcustomNotificationId());
if ($customNotification) {
$notificationArr[$count]['id'] = $notification->getId();
$notificationArr[$count]['customNotificationId'] = $notification->getcustomNotificationId();
$notificationArr[$count]['datetime'] = $notification->getDatetime();
$notificationArr[$count]['thresholdValue'] = $notification->getthresholdValue();
$notificationArr[$count]['color'] = $notification->getColor();
$notificationArr[$count]['customNotificaiton'] = [
"id" => $customNotification->getId(),
'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
"alert_type" => $customNotification->getAlert()->getName(),
"alert_key" => $customNotification->getAlert()->getAlertKey(),
"location_name" => $customNotification->getLocation()->getName(),
"title" => $customNotification->gettitle(),
"color" => $customNotification->getColor(),
"units" => $customNotification->getunits(),
"min_value" => $customNotification->getMinValue(),
"max_value" => $customNotification->getMaxValue(),
"weather_model" => $customNotification->getWeatherModel(),
"alert_on_email" => $customNotification->getalertOnEmail(),
"alert_on_sms" => $customNotification->getalertOnSMS(),
"calculation" => $customNotification->getCalculate()
];
}
}
}
return $notificationArr;
}
public function getUserCustomNotificationByOrganization($params, $organizationId, $loggedInUser, $paginator)
{
// try {
$response = [];
$pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
$page = isset($params['page']) ? $params['page'] : 1;
$organization = \Pimcore\Model\DataObject::getById($organizationId);
if (!$organization instanceof \Pimcore\Model\DataObject\Organization) {
throw new \Exception("Organization does not exists");
}
// retrieve customer by userId
$customers = new Customer\Listing();
$customers->filterByOrganization($organization);
if ($customers->getCount() == 0) {
throw new \Exception("Customer does not exists in this organization");
}
foreach ($customers as $customer) {
$customNotifications = new CustomNotification\Listing();
$customNotifications->addConditionParam("user like '%," . $customer->getId() . ",%'");
//filter by Name
if (isset($params['search']) && !empty($params['search'])) {
$customNotifications->addConditionParam("title like '%" . $params['search'] . "%'");
}
//filter by color
if (isset($params['color']) && !empty($params['color'])) {
$customNotifications->addConditionParam("color like '%" . $params['color'] . "%'");
}
//filter by calculation
if (isset($params['calculation']) && !empty($params['calculation'])) {
$customNotifications->addConditionParam("calculate like '%" . $params['calculation'] . "%'");
}
//$customNotifications->filterByUser($customer);
if ($customNotifications->getCount() > 0) {
foreach ($customNotifications as $customNotification) {
// p_r($customNotification->getAlert());exit;
if (count($customNotification->getUser()) > 0) {
foreach ($customNotification->getUser() as $user) {
$user = $user->getObject();
if ($user instanceof Customer && $user->getId() != $loggedInUser->getId()) {
if ($customNotification->getLocation() && $customNotification->getAlert()) {
// Check if the entry already exists for this customer and notification
$existingEntry = array_filter(
$response,
function ($entry) use ($customNotification, $user) {
return (
$entry['id'] == $customNotification->getId() &&
$entry['customerId'] == $user->getId()
);
}
);
// Add the entry only if it doesn't exist
if (empty($existingEntry)) {
$response[] = [
"id" => $customNotification->getId(),
'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
"alert_type" => $customNotification->getAlert()->getName(),
"alert_key" => $customNotification->getAlert()->getAlertKey(),
"location_name" => $customNotification->getLocation()->getName(),
"title" => $customNotification->gettitle(),
"color" => $customNotification->getColor(),
"units" => $customNotification->getunits(),
"min_value" => $customNotification->getMinValue(),
"max_value" => $customNotification->getMaxValue(),
"weather_model" => $customNotification->getWeatherModel(),
"alert_on_email" => $customNotification->getalertOnEmail(),
"alert_on_sms" => $customNotification->getalertOnSMS(),
"calculation" => $customNotification->getCalculate(),
"duration" => $customNotification->getDuration(),
"customerId" => $user->getId(),
"customerName" => $user->getName(),
"customerEmail" => $user->getEmail()
];
}
}
}
}
}
}
}
}
$paginator = $paginator->paginate(
$response,
$page,
$pageSize
);
// } catch (\Exception $e) {
// throw new \Exception($e->getMessage());
// }
return ["success" => true, "data" => $paginator, 'paginationVariables' => $paginator->getPaginationData()];
}
public function updateSubscribeAlerts($customer, $notificationId, $locationId, $alertType, $title, $color, $units, $minValue, $maxValue, $weatherModel, $alertOnEmail, $alertOnSMS, $calculate, $duration, $frequency=1, $translator, $mateoMaticsService=null)
{
// retrieve customer by userId
if (!$customer instanceof Customer) {
throw new \Exception('Customer not found for userId:');
}
// retrieve location by locationId
$location = DataObject::getById($locationId);
if (!$location) {
throw new \Exception('Location not found for locationId: ' . $locationId);
}
// retrieve alertType by alertType
$alertType = AlertMaster::getByAlertKey($alertType, true);
if (!$alertType) {
throw new \Exception('Alert type not found: ' . $alertType);
}
// Validate weather data availability before updating notification
if ($mateoMaticsService) {
$nowRiyadh = Carbon::now('Asia/Riyadh');
$coOrdinates = json_decode($location->getCoOrdinates(), true);
$startDateUtc = $nowRiyadh->copy()->setTimezone('UTC')->format('Y-m-d\TH:00:00\Z');
if (stripos($duration, 'hours') !== false) {
$hours = (int) filter_var($duration, FILTER_SANITIZE_NUMBER_INT);
$endDateRiyadh = $nowRiyadh->copy()->addHours($hours);
} else {
$days = (int) filter_var($duration, FILTER_SANITIZE_NUMBER_INT);
$endDateRiyadh = $nowRiyadh->copy()->addDays($days);
}
$endDateUtc = $endDateRiyadh->copy()->setTimezone('UTC')->format('Y-m-d\TH:00:00\Z');
$parameter = $alertType->getMeteoMaticsKey();
$hour = 1;
$model = $weatherModel;
$timezone = new \DateTimeZone("Asia/Riyadh");
try {
$response = $mateoMaticsService->getTempratureByParamsHourly(
$coOrdinates,
$startDateUtc,
$endDateUtc,
$parameter,
$hour,
$model,
$timezone
);
} catch (\Exception $e) {
return [
"success" => false,
"message" => "Parameter {$parameter} is not available in model {$model}"
];
}
}
$customNotification = \Pimcore\Model\DataObject::getById($notificationId, true);
if (!$customNotification instanceof CustomNotification) {
throw new \Exception('Custom notification not found with id.');
}
$customNotification->setTitle($title);
$customNotification->setColor($color);
$customNotification->setUnits($units);
$customNotification->setMinValue($minValue);
$customNotification->setMaxValue($maxValue);
$customNotification->setWeatherModel($weatherModel);
$customNotification->setLocation($location);
$objectArray = ($customNotification) ? $customNotification->getUser() : [];
if ($objectArray) {
foreach ($objectArray as $key => $objUser) {
$currentUser = $objUser->getObject();
if ($currentUser->getId() == $customer->getId()) {
unset($objectArray[$key]);
break; // Stop the loop once a match is found
}
}
$objectMetadata = new DataObject\Data\ObjectMetadata('user', ['token', 'alert_on_email', 'alert_on_sms'], $customer);
$objectMetadata->setToken("");
$objectMetadata->setAlert_on_email($alertOnEmail);
$objectMetadata->setAlert_on_sms($alertOnSMS);
array_push($objectArray, $objectMetadata);
$customNotification->setUser($objectArray);
}
$customNotification->setAlert($alertType);
$customNotification->setStatus(true);
$customNotification->setPublished(true);
$customNotification->setCalculate($calculate);
$customNotification->setDuration($duration);
$customNotification->setFrequency($frequency);
$customNotification->save();
return [
"success" => true,
"data" => [
"id" => $customNotification->getId()
],
"message" => $translator->trans("update_successfully")
];
}
public function getCustomNotificationAlerts($params, $paginator)
{
$response = [];
$customNotifications = [];
$customNotificationQuery = new CustomNotification\Listing();
$color = '';
$condition = '';
$model = '';
if (!empty($params['color'])) {
$color = $params['color'];
$customNotificationQuery->addConditionParam("color = ?", $color, "AND");
}
if (!empty($params['condition'])) {
$condition = $params['condition'];
$customNotificationQuery->addConditionParam("calculate = ?", $condition, "AND");
}
if (!empty($params['model'])) {
$model = $params['model'];
$customNotificationQuery->addConditionParam("weatherModel = ?", $model, "AND");
}
$customNotificationQuery->setOffset(!empty($params['offset']) ? $params['offset'] : 0);
$customNotificationQuery->setLimit(!empty($params['limit']) ? $params['limit'] : LIMIT_PER_PAGE);
$customNotificationQuery->setOrder("desc");
$customNotifications = $customNotificationQuery->load();
if (!empty($customNotifications)) {
foreach ($customNotifications as $customNotification) {
$response[] = [
"id" => $customNotification->getId(),
'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
"alert_type" => $customNotification->getAlert()->getName(),
"alert_key" => $customNotification->getAlert()->getAlertKey(),
"location_name" => ($customNotification->getLocation()) ? $customNotification->getLocation()->getTitle() : '',
"title" => $customNotification->getTitle(),
"color" => $customNotification->getColor(),
"units" => $customNotification->getunits(),
"min_value" => $customNotification->getMinValue(),
"max_value" => $customNotification->getMaxValue(),
"weather_model" => $customNotification->getWeatherModel(),
"alert_on_email" => $customNotification->getalertOnEmail(),
"alert_on_sms" => $customNotification->getalertOnSMS(),
"calculation" => $customNotification->getCalculate(),
];
}
}
return ["success" => true, "total" => count($customNotifications), "data" => $response];
}
public function customNotificationFilters($translator)
{
$response = [];
$response[] = [
"model" => \App\Lib\Utility::customNotificationWeatherModelList(),
"parameters" => \App\Lib\Utility::customNotificationParametersList(),
"colors" => \App\Lib\Utility::customNotificationConfigColorsList(),
"condition" => \App\Lib\Utility::customNotificationConditionList(),
"durations" => \App\Lib\Utility::customNotificationDurationsList($translator)
];
return ["success" => true, "data" => $response];
}
public function updateSubscribeNotification($token, $translator)
{
$db = Db::get();
$select = $db->createQueryBuilder();
$select->select('cn.o_id AS cn_id', 'cn.dest_id AS user_id', 'cn.auto_id AS id')
->from('object_metadata_custom_notification', 'cn')
->andwhere('cn.column = :type')
->andwhere('cn.data = :token')
->setParameter('token', $token)
->setParameter('type', 'token');
$result = $select->execute()->fetchAllAssociative();
if (empty($result)) {
return ["success" => false, "message" => $translator->trans("invalid_token")];
}
$result = $result[0];
$user = \Pimcore\Model\DataObject\Customer::getById($result['user_id']);
$customNotification = \Pimcore\Model\DataObject\CustomNotification::getById($result['cn_id']);
if ($customNotification instanceof \Pimcore\Model\DataObject\CustomNotification && $user instanceof \Pimcore\Model\DataObject\Customer) {
$objectArray = ($customNotification) ? $customNotification->getUser() : [];
if ($objectArray) {
foreach ($objectArray as $key => $objUser) {
$currentUser = $objUser->getObject();
if ($currentUser->getId() == $user->getId()) {
unset($objectArray[$key]);
break; // Stop the loop once a match is found
}
}
$objectMetadata = new DataObject\Data\ObjectMetadata('user', ['token', 'alert_on_email', 'alert_on_sms'], $user);
$objectMetadata->setToken("");
$objectMetadata->setAlert_on_email(false);
$objectMetadata->setAlert_on_sms(false);
array_push($objectArray, $objectMetadata);
$customNotification->setUser($objectArray);
$customNotification->save();
}
return ["success" => true, "message" => $translator->trans("you_have_successfully_unsubscribed_that_notification")];
} else {
return ["success" => false, "message" => $translator->trans("notification_not_found")];
}
}
public function unSubscribeEwsNotification($token, $translator)
{
$user = \Pimcore\Model\DataObject\Customer::getByEwsNotificationToken($token, true);
if ($user) {
$user->setEwsNotificationToken("");
$user->setSendEwsEmail(false);
$user->save();
return ["success" => true, "message" => $translator->trans("you_have_successfully_unsubscribed_that_notification")];
} else {
return ["success" => false, "message" => $translator->trans("user_not_found")];
}
}
public function mannedAlertSubscription($customer, $params, $translator)
{
$region_id = isset($params['region_id']) ? $params['region_id'] : null;
$governorate_ids = isset($params['governorate_id']) ? (array)$params['governorate_id'] : [];
$alert_status_id = isset($params['alert_status_id']) ? $params['alert_status_id'] : 0;
$alert_type_ids = isset($params['alert_type_id']) ? $params['alert_type_id'] : [];
$phenomena_ids = isset($params['phenomena_id']) ? $params['phenomena_id'] : [];
$is_public = isset($params['is_public']) ? $params['is_public'] : false;
$email = isset($params['email']) ? strtolower($params['email']) : '';
$notifyEmail = isset($params['notifyEmail']) ? $params['notifyEmail'] : true;
$notifySMS = isset($params['notifySMS']) ? $params['notifySMS'] : true;
if (!$customer instanceof Customer) {
return ["success" => false, "message" => $translator->trans("customer_not_found_for_" . $customer->getId())];
}
$alertRegion = null;
if ($region_id) {
$alertRegion = \Pimcore\Model\DataObject\Region::getByRegionId($region_id, true);
if (!$alertRegion) {
return ["success" => false, "message" => $translator->trans("region_not_found_for_" . $region_id)];
}
}
// $alertStatus = \Pimcore\Model\DataObject\AlertStatus::getById($alert_status_id, true);
// if (!$alertStatus) {
// return ["success" => false, "message" => $translator->trans("alert_status_not_found_for_".$alert_status_id)];
// }
$alertTypeIDS = [];
foreach ($alert_type_ids as $alert_type_id) {
$alertType = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert_type_id, true);
if (!$alertType) {
return ["success" => false, "message" => $translator->trans("alert_type_not_found_for_" . $alert_type_id)];
}
$alertTypeIDS[] = $alertType->getId();
}
$governateIDS = [];
$governorate = null;
foreach ($governorate_ids as $govId) {
$governorate = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govId, true);
if (!$governorate) {
return ["success" => false, "message" => $translator->trans("governorate_not_found_for_" . $govId)];
}
$governateIDS[] = $governorate->getId();
}
$phenomenaIDS = [];
foreach ($phenomena_ids as $phenomena_id) {
$phenomena = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($phenomena_id, true);
if (!$phenomena) {
return ["success" => false, "message" => $translator->trans("alert_status_not_found_for_" . $phenomena_id)];
}
$phenomenaIDS[] = $phenomena->getId();
}
$govID = implode(',', $governateIDS);
$alertID = implode(',', $alertTypeIDS);
$phenomenaID = implode(',', $phenomenaIDS);
$existingSubscription = new DataObject\MannedAlertSubscription\Listing();
if ($alertRegion) {
$existingSubscription->addConditionParam("region__id = ?", [$alertRegion->getId()]);
}
$existingSubscription->addConditionParam("governorate = ? ", [',' . $govID . ',']);
$existingSubscription->addConditionParam("alertType = ? ", [',' . $alertID . ',']);
$existingSubscription->addConditionParam("alertStatus = ? ", [',' . $phenomenaID . ',']);
if ($is_public) {
$existingSubscription->addConditionParam("LOWER(email) = ?", [$email]);
} else {
$existingSubscription->addConditionParam("creator__id = ?", [$customer->getId()]);
}
$existingSubscription->setOrderKey("oo_id");
$existingSubscription->setOrder("desc");
$existingSubscription->load();
if (count($existingSubscription) > 0) {
return ["success" => false, "message" => $translator->trans("manned_alert_subscription_already_exists")];
}
// Create the subscription if it doesn't exist
if ($governorate !== null) {
$key = \Pimcore\Model\Element\Service::getValidKey($governorate->getId(), 'object');
} else {
$key = \Pimcore\Model\Element\Service::getValidKey($email, 'object');
}
$mannedSubscription = new \Pimcore\Model\DataObject\MannedAlertSubscription();
$mannedSubscription->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Subscription/' . $customer->getEmail()));
$mannedSubscription->setKey($key . time() . rand(0, 100));
$mannedSubscription->setRegion($alertRegion);
$governorateOBJ = [];
foreach ($governorate_ids as $govId) {
$governorateOBJ[] = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govId, true);
}
$alert_typeOBJ = [];
foreach ($alert_type_ids as $alert_type_id) {
$alert_typeOBJ[] = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert_type_id, true);
}
$phenomenaOBJ = [];
foreach ($phenomena_ids as $phenomena_id) {
$phenomenaOBJ[] = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($phenomena_id, true);
}
$mannedSubscription->setGovernorate($governorateOBJ);
$mannedSubscription->setAlertType($alert_typeOBJ);
$mannedSubscription->setAlertStatus($phenomenaOBJ);
$mannedSubscription->setCreator($customer);
$mannedSubscription->setIsSubscribed($notifyEmail);
$mannedSubscription->setNotifyEmail($notifyEmail);
$mannedSubscription->setNotifySMS($notifySMS);
$mannedSubscription->setIsPublic($is_public);
$mannedSubscription->setEmail($email);
$mannedSubscription->setPublished(true);
$mannedSubscription->save();
return ["success" => true, "message" => $translator->trans("manned_alert_subscription_created")];
}
public function mannedAlertSubscriber($params, $user, $translator)
{
$subscription_id = isset($params['subscription_id']) ? (int)$params['subscription_id'] : 0;
$isOwner = isset($params['isOwner']) ? (bool)$params['isOwner'] : false;
// Permission check: only client admin can assign
if (!empty($user->getRole()) && $user->getRole()->getName() !== USER_ROLES['CLIENT_ADMIN']) {
return ["success" => false, "message" => $translator->trans("you_are_not_allowed_to_assign_subscription")];
}
// Load and validate subscription once
$subscription = \Pimcore\Model\DataObject\MannedAlertSubscription::getById($subscription_id, true);
if (!$subscription instanceof \Pimcore\Model\DataObject\MannedAlertSubscription) {
return ["success" => false, "message" => $translator->trans("subscription_not_found_for_subscription_id_" . $subscription_id)];
}
// Normalize user ids: user_id can be scalar or array
$userIds = [];
if (isset($params['user_id'])) {
if (is_array($params['user_id'])) {
$userIds = array_values(array_unique(array_map('intval', array_filter($params['user_id']))));
} else {
$userIds = [ (int)$params['user_id'] ];
}
}
$added = 0;
$keyBase = \Pimcore\Model\Element\Service::getValidKey($subscription->getId(), 'object');
foreach ($userIds as $user_id) {
if (!$user_id) {
continue;
}
$customer = \Pimcore\Model\DataObject\Customer::getById($user_id, true);
if (!$customer instanceof Customer) {
continue; // skip invalid user ids
}
// Check for existing assignment
$existingSubscriber = new DataObject\MannedAlertSubscriber\Listing();
$existingSubscriber->addConditionParam("userId__id = ?", [$customer->getId()]);
$existingSubscriber->addConditionParam("subscriptionId__id = ?", [$subscription->getId()]);
$existingSubscriber->setOrderKey("o_id");
$existingSubscriber->setOrder("desc");
$existingSubscriber->load();
if (count($existingSubscriber) > 0) {
continue; // skip duplicates
}
// Create subscription assignment
$mannedSubscriber = new \Pimcore\Model\DataObject\MannedAlertSubscriber();
$mannedSubscriber->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Subscriber/' . $customer->getEmail()));
$mannedSubscriber->setKey($keyBase . time() . rand(0, 100));
$mannedSubscriber->setUserId($customer);
$mannedSubscriber->setSubscriptionId($subscription);
$mannedSubscriber->setIsOwner($isOwner);
$mannedSubscriber->setPublished(true);
$mannedSubscriber->save();
// Also add to subscription subscribers relation (avoid duplicates)
$currentSubscribers = $subscription->getSubscribers();
$updatedSubscribers = [];
if ($currentSubscribers instanceof \Traversable || is_array($currentSubscribers)) {
foreach ($currentSubscribers as $existing) {
$updatedSubscribers[] = $existing;
}
}
$alreadyRelated = false;
foreach ($updatedSubscribers as $existing) {
if (method_exists($existing, 'getId') && $existing->getId() === $customer->getId()) {
$alreadyRelated = true;
break;
}
}
if (!$alreadyRelated) {
$updatedSubscribers[] = $customer;
$subscription->setSubscribers($updatedSubscribers);
$subscription->save();
}
$added++;
}
if (count($userIds) > 1) {
// Collective response for multiple users
return ["success" => $added > 0, "message" => $translator->trans("subscription_assigned_successfully") . ": " . $added];
}
// Single user response
if ($added === 1) {
return ["success" => true, "message" => $translator->trans("subscription_assigned_successfully")];
}
return ["success" => false, "message" => $translator->trans("this_subscription_already_assigned_to_this_user")];
}
public function listMannedAlertSubscription($params, $user, $paginator)
{
$pageSize = $params['page_size'] ?? LIMIT_PER_PAGE;
$page = $params['page'] ?? 1;
$mannedAlertSubscription = new DataObject\MannedAlertSubscription\Listing();
if (isset($params['isAssigned'])) {
$isAssignedParam = $params['isAssigned'];
$truthyValues = [true, 1, '1', 'true', 'TRUE', 'True'];
$falsyValues = [false, 0, '0', 'false', 'FALSE', 'False'];
if (in_array($isAssignedParam, $truthyValues, true)) {
// Only subscriptions assigned to the user (not created by them)
$mannedAlertSubscription->addConditionParam("FIND_IN_SET(?, subscribers) > 0 AND creator__id != ?", [$user->getId(), $user->getId()]);
} elseif (in_array($isAssignedParam, $falsyValues, true)) {
// Only subscriptions created by the user
$mannedAlertSubscription->addConditionParam("creator__id = ?", [$user->getId()]);
} else {
// Fallback to default behavior if param is malformed
$mannedAlertSubscription->addConditionParam("creator__id = ? OR FIND_IN_SET(?, subscribers) > 0", [$user->getId(), $user->getId()]);
}
} else {
// Default: include subscriptions created by the user OR assigned to the user
$mannedAlertSubscription->addConditionParam("creator__id = ? OR FIND_IN_SET(?, subscribers) > 0", [$user->getId(), $user->getId()]);
}
if (isset($params['region_id']) && !empty($params['region_id'])) {
$region_ids = $params['region_id'];
$regionIDS = [];
foreach ($region_ids as $regionId) {
$region = \Pimcore\Model\DataObject\Region::getByRegionId($regionId, true);
$regionIDS[] = $region->getId();
}
// Use placeholders for each region ID
$placeholders = implode(',', array_fill(0, count($regionIDS), '?'));
$mannedAlertSubscription->addConditionParam('region__id IN (' . $placeholders . ')', $regionIDS);
}
if (isset($params['alert_id']) && !empty($params['alert_id'])) {
$alertIds = $params['alert_id'];
$alertTypeIDS = [];
foreach ($alertIds as $alert_type_id) {
$alertType = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert_type_id, true);
$alertTypeIDS[] = $alertType->getId();
}
$alertTypeID = implode(',', $alertTypeIDS);
// $mannedAlertSubscription->addConditionParam("alertType = ? ", [','.$alertTypeID.',']);
$mannedAlertSubscription->addConditionParam("alertType REGEXP CONCAT('(^|,)(', REPLACE('$alertTypeID',',', '|'), ')(,|$)')");
}
if (isset($params['phenomena_id']) && !empty($params['phenomena_id'])) {
$alertStatusIds = $params['phenomena_id'];
$alertStatusIDS = [];
foreach ($alertStatusIds as $alertStatusId) {
$alertStatus = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatusId, true);
$alertStatusIDS[] = $alertStatus->getId();
}
$alertStatusID = implode(',', $alertStatusIDS);
// $mannedAlertSubscription->addConditionParam("phenomena = ? ", [','.$phenomenaID.',']);
$mannedAlertSubscription->addConditionParam("alertStatus REGEXP CONCAT('(^|,)(', REPLACE('$alertStatusID',',', '|'), ')(,|$)')");
}
$mannedAlertSubscription->setOrderKey("oo_id");
$mannedAlertSubscription->setOrder("desc");
$paginator = $paginator->paginate(
$mannedAlertSubscription,
$page,
$pageSize
);
$response = [];
foreach ($paginator as $subscription) {
if ($subscription) {
$governorates = [];
foreach ($subscription->getGovernorate() as $governorate) {
$governorates[] = [
"id" => $governorate->getGovernoteId(),
"en" => $governorate->getName('en'),
"ar" => $governorate->getName('ar')
];
}
$alert_types = [];
foreach ($subscription->getAlertType() as $alert_type) {
$alert_types[] = [
"id" => $alert_type->getAlertTypeId(),
"color" => $alert_type->getColor(),
"en" => $alert_type->getName('en'),
"ar" => $alert_type->getName('ar')
];
}
$phenomenas = [];
if ($subscription->getAlertStatus()) {
foreach ($subscription->getAlertStatus() as $subscriptionAlertStatus) {
$phenomenas[] = [
"id" => $subscriptionAlertStatus->getAlertStatusId(),
"en" => $subscriptionAlertStatus->getName('en'),
"ar" => $subscriptionAlertStatus->getName('ar')
];
}
}
$response[] = [
"id" => $subscription->getId(),
"region" => [
[
"id" => $subscription->getRegion()->getRegionId(),
"en" => $subscription->getRegion()->getName('en'),
"ar" => $subscription->getRegion()->getName('ar')
]
],
"alertType" => $alert_types,
"governorate" => $governorates,
"phenomena" => $phenomenas,
"notifyEmail" => $subscription->getNotifyEmail() == null ? false : $subscription->getNotifyEmail(),
"notifySMS" => $subscription->getNotifySMS() == null ? false : $subscription->getNotifySMS(),
"creator" => $subscription->getCreator()?->getEmail(),
"isAssigned" => $subscription->getCreator()?->getEmail() !== $user->getEmail() ? true : false
];
}
}
return [
"success" => true,
"data" => $response,
'paginationVariables' => $paginator->getPaginationData()
];
}
public function deleteMannedAlertSubscription($request, $params, $user, $translator)
{
$subscription_id = isset($params['subscription_id']) ? $params['subscription_id'] : null;
$alertSubscription = \Pimcore\Model\DataObject\MannedAlertSubscription::getById($subscription_id, true);
if (!$alertSubscription) {
return ["success" => false, "message" => $translator->trans("alert_subscription_not_found")];
}
if ($alertSubscription->getCreator() == $user) {
if ($alertSubscription instanceof \Pimcore\Model\DataObject\MannedAlertSubscription) {
$alertSubscription->delete();
return ["success" => true, "message" => $translator->trans("subscription_deleted")];
}
} else {
$subscribedUser = [];
$message = "user_not_found_in_this_subscription";
foreach ($alertSubscription->getSubscribers() as $assignUser) {
if ($assignUser == $user) {
$message = "subscription_deleted";
} else {
$subscribedUser[] = $assignUser;
}
$alertSubscription->setSubscribers($subscribedUser);
$alertSubscription->save();
}
return ["success" => true, "message" => $translator->trans($message)];
}
}
public function mannedAlertSubscribe($request, $params, $user, $translator)
{
$subscription_id = isset($params['subscription_id']) ? $params['subscription_id'] : null;
$notifyEmail = isset($params['notifyEmail']) ? $params['notifyEmail'] : false;
$notifySMS = isset($params['notifySMS']) ? $params['notifySMS'] : false;
$subscription = new DataObject\MannedAlertSubscription\Listing();
$subscription->setCondition("oo_id = ?", [$subscription_id]);
$subscription->filterByCreator($user);
$subscriptionData = $subscription->current();
if ($subscriptionData instanceof \Pimcore\Model\DataObject\MannedAlertSubscription) {
try {
// Get current state before updating
$currentNotifyEmail = $subscriptionData->getNotifyEmail();
$currentNotifySMS = $subscriptionData->getNotifySMS();
// Determine message based on state changes
$message = '';
if ($notifyEmail === true && $currentNotifyEmail === false) {
$message = "subscribed for email notification";
} elseif ($notifyEmail === false && $currentNotifyEmail === true) {
$message = "Unsubscribed for email notification";
} elseif ($notifySMS === true && $currentNotifySMS === false) {
$message = "subscribed for SMS notification";
} elseif ($notifySMS === false && $currentNotifySMS === true) {
$message = "Unsubscribed for SMS notification";
} else {
$message = $translator->trans('Subscription_unsubscribed_successfully');
}
$subscriptionData->setIsSubscribed($notifyEmail);
$subscriptionData->setNotifyEmail($notifyEmail);
$subscriptionData->setNotifySMS($notifySMS);
$subscriptionData->save();
return ["success" => true, "message" => $translator->trans($message)];
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}
return ["success" => false, "message" => $translator->trans("subscription_not_found_for_id_" . $subscription_id)];
}
public function assignUsersWithCustomNotification($request, $userIdsArray, $notificationId, $translator)
{
$users = [];
$customNotification = CustomNotification::getById($notificationId);
if (!$customNotification) {
return ["success" => false, "message" => $translator->trans("custom_notification_not_found_for_id_" . $notificationId)];
}
$objectArray = ($customNotification) ? $customNotification->getUser() : [];
if ($objectArray) {
foreach ($objectArray as $key => $objUser) {
$users[] = $objUser->getObject();
}
}
if (count($userIdsArray) > 0) {
// validate if users are available to given ids
foreach ($userIdsArray as $userId) {
$user = Customer::getById($userId);
if (!$user) {
return ["success" => false, "message" => $translator->trans("user_not_found_for_id_" . $userId)];
} else {
if (!in_array($user, $users)) {
$objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email', 'alert_on_sms'], $user);
$objectMetadata->setAlert_on_email(true);
$objectMetadata->setAlert_on_sms(true);
array_push($objectArray, $objectMetadata);
}
}
}
$customNotification->setUser($objectArray);
$customNotification->save();
return ["success" => true, "message" => $translator->trans("custom_notification_assigned_successfully")];
} else {
return ["success" => false, "message" => $translator->trans("user_id_array_is_empty")];
}
}
public function unSubscribeNotification($customer, $translator)
{
$ownerNotifications = new AdvanceCustomNotification\Listing();
// $$ownerNotification=->filterByUser($customer);
$ownerNotifications->setCondition("owner__id =?", [$customer->getId()]);
$ownerNotifications->load();
if ($ownerNotifications) {
foreach ($ownerNotifications as $ownerNotification) {
// Assuming 'getAlerts' is the name of your multi-selection field
$sendNotificationAlertTypes = $ownerNotification->getAlerts();
// Check if 'email' is currently selected
if (is_array($sendNotificationAlertTypes)) {
if (in_array('email', $sendNotificationAlertTypes)) {
// Remove 'email' from the selection
$updatedMethods = array_filter($sendNotificationAlertTypes, function ($method) {
return $method !== 'email';
});
// Set the updated selection without 'email'
$ownerNotification->setAlerts(array_values($updatedMethods)); // Ensure array is reindexed if necessary
}
}
$ownerNotification->save();
}
}
$customer->setUnSubscribeCustomNotificationToken("");
$customer->save();
/* DO NOT REMOVE BELOW CODE */
// $customNotifications = new AdvanceCustomNotification\Listing();
// $userGroup = $customer->getUserGroup(); // getUserGroup method based on your relation name
// $userGroupId = null;
// $likePatternUserGroup=null;
// if ($userGroup) {
// $userGroupId = $userGroup->getId();
// $likePatternUserGroup = '%,' . $userGroupId . ',%';
// }
// $likePatternUser = '%,' . $customer->getId() . ',%';
// $condition = "(user LIKE ? OR usergroup LIKE ?)";
// $customNotifications->setCondition($condition, [$likePatternUser, $likePatternUserGroup]);
// if ($customNotifications) {
// foreach ($customNotifications as $customNotification) {
// $objectArray = $customNotification->getUnSubscriber();
// // Flag to check if the customer is already in the unsubscriber list
// $isAlreadyUnsubscribed = false;
// // Step 2: Check if the customer is already in that list
// foreach ($objectArray as $objectMetadata) {
// if ($objectMetadata->getObject() instanceof \Pimcore\Model\DataObject\Customer && $objectMetadata->getObject()->getId() == $customer->getId()) {
// // The customer is already an unsubscriber
// $isAlreadyUnsubscribed = true;
// break; // No need to check further
// }
// }
// // Step 3: If not already unsubscribed, add the customer to the list
// if (!$isAlreadyUnsubscribed) {
// // Create a new ObjectMetadata instance for the new unsubscriber
// // Assuming you don't need to add specific metadata here, otherwise include those fields in the array
// $newUnsubscriber = new ObjectMetadata('unSubscriber', ['date'], $customer);
// // Set the current date for the 'date' metadata field
// $currentDate = new \DateTime();
// $newUnsubscriber->setDate($currentDate->format('Y-m-d H:i:s'));
// // $newUnsubscriber->setMetadata('date', 'text', $currentDate->format('Y-m-d H:i:s'));
// // Add the new unsubscriber to the objectArray
// $objectArray[] = $newUnsubscriber;
// // Set the updated array back to the CustomNotification object
// $customNotification->setUnSubscriber($objectArray);
// // Save the CustomNotification object
// $customNotification->save();
// }
// }
// $customer->setUnSubscribeCustomNotificationToken("");
// $customer->save();
// return ["success" => true, "message" => $translator->trans("You have successfully unsubscribed to all notifications")];
// }
return ["success" => true, "message" => $translator->trans("You have successfully unsubscribed to all notifications")];
// else {
// return ["success" => false, "message" => $translator->trans("Notifications Not Found")];
// }
}
public function assignAlertSubscription($customer, $params, $translator)
{
$alert_subscription_id = isset($params['AlertSubscriptionId']) ? $params['AlertSubscriptionId'] : null;
$user_ids = isset($params['UserId']) ? $params['UserId'] : 0;
$alertSubscription = \Pimcore\Model\DataObject\MannedAlertSubscription::getById($alert_subscription_id, true);
if (!$alertSubscription) {
return ["success" => false, "message" => $translator->trans("alert_subscription_not_found")];
}
if ($alertSubscription->getCreator() !== $customer) {
return ["success" => false, "message" => $translator->trans("alert_does_not_create_by_login_user")];
}
$message = [];
foreach ($user_ids as $user_id) {
$assignedUser = DataObject\Customer::getById($user_id);
if ($assignedUser) {
if (!($customer->getOrganization() == $assignedUser->getOrganization())) {
// return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_same_organization")];
$message[] = $translator->trans("user_does_not_belongs_to_same_organization");
}
$subscribedUser = [];
foreach ($alertSubscription->getSubscribers() as $user) {
if ($user == $assignedUser) {
$message[] = $translator->trans("user_already_assigned");
} else {
$subscribedUser[] = $user;
}
}
$subscribedUser[] = $assignedUser;
$alertSubscription->setSubscribers($subscribedUser);
$alertSubscription->save();
}
}
return ["success" => true, "message" => $translator->trans("manned_alert_subscription_assigned")];
}
public function assignUserGroupWithCustomNotification($request, $userGroupIdsArray, $notificationId, $translator)
{
$customNotification = CustomNotification::getById($notificationId);
if (!$customNotification) {
return ["success" => false, "message" => $translator->trans("custom_notification_not_found_for_id_" . $notificationId)];
}
if (count($userGroupIdsArray) > 0) {
$selectedUserGroups = [];
$newObjectArray = [];
$processedUserIds = [];
// Get existing users (retain all and avoid duplicates)
$existingUsers = [];
if ($customNotification) {
try {
$existingUsers = $customNotification->getUser();
} catch (\Throwable $e) {
// In case of broken relation IDs, proceed with empty existing users
$existingUsers = [];
}
}
if ($existingUsers) {
foreach ($existingUsers as $existingUserMetadata) {
if (!$existingUserMetadata) {
continue;
}
// If metadata exists, keep users that are not from user groups
if ($existingUserMetadata instanceof \Pimcore\Model\DataObject\Data\ObjectMetadata) {
// Only keep if the underlying object still exists
$related = $existingUserMetadata->getObject();
if ($related) {
$newObjectArray[] = $existingUserMetadata;
$processedUserIds[] = $related->getId();
}
continue;
}
// If item is a plain Customer (no metadata), wrap into metadata for the 'user' field
if ($existingUserMetadata instanceof Customer) {
$wrapped = new DataObject\Data\ObjectMetadata('user', ['alert_on_email', 'alert_on_sms', 'is_group_user','group_id'], $existingUserMetadata);
$wrapped->setAlert_on_email(true);
$wrapped->setAlert_on_sms(true);
$wrapped->setIs_group_user(false);
$wrapped->setGroup_id(null);
$newObjectArray[] = $wrapped;
$processedUserIds[] = $existingUserMetadata->getId();
}
}
}
// Process new user groups
if (!empty($userGroupIdsArray)) {
foreach ($userGroupIdsArray as $userGroup) {
$UserGroupObject = UserGroup::getById($userGroup, true);
if ($UserGroupObject) {
$selectedUserGroups[] = $UserGroupObject;
$userGroupUsers = Customer::getByUserGroup($UserGroupObject);
foreach ($userGroupUsers as $userGroupUser) {
// Check if user is not already processed to avoid duplicates
if (!in_array($userGroupUser->getId(), $processedUserIds)) {
$objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email', 'alert_on_sms', 'is_group_user','group_id'], $userGroupUser);
$objectMetadata->setAlert_on_email(true);
$objectMetadata->setAlert_on_sms(true);
$objectMetadata->setIs_group_user(true);
$objectMetadata->setGroup_id($UserGroupObject->getId());
$newObjectArray[] = $objectMetadata;
$processedUserIds[] = $userGroupUser->getId();
}
}
}
}
}
// Update the notification with new user groups and users
$customNotification->setUserGroup($selectedUserGroups);
$customNotification->setUser($newObjectArray);
$customNotification->save();
return ["success" => true, "message" => $translator->trans("custom_notification_assigned_successfully")];
} else {
return ["success" => false, "message" => $translator->trans("user_group_array_is_empty")];
}
}
public function assignUserGroupWithAlertSubscription($request, $userGroupIdsArray, $notificationId, $translator)
{
$alertSubscription = MannedAlertSubscription::getById($notificationId, true);
if (!$alertSubscription) {
return ["success" => false, "message" => $translator->trans("custom_notification_not_found_for_id_" . $notificationId)];
}
if (count($userGroupIdsArray) > 0) {
$selectedUserGroups = [];
$newObjectArray = [];
$processedUserIds = [];
// Get existing subscribers (retain all and avoid duplicates). This relation does NOT support metadata.
$existingUsers = [];
if ($alertSubscription) {
try {
$existingUsers = $alertSubscription->getSubscribers();
} catch (\Throwable $e) {
// In case of broken relation IDs, proceed with empty existing users
$existingUsers = [];
}
}
if ($existingUsers) {
foreach ($existingUsers as $existingUserMetadata) {
if (!$existingUserMetadata) {
continue;
}
// Subscribers is many-to-many without metadata: keep customers directly
if ($existingUserMetadata instanceof Customer) {
$newObjectArray[] = $existingUserMetadata;
$processedUserIds[] = $existingUserMetadata->getId();
}
}
}
// Process new user groups
if (!empty($userGroupIdsArray)) {
foreach ($userGroupIdsArray as $userGroup) {
$UserGroupObject = UserGroup::getById($userGroup, true);
if ($UserGroupObject) {
$selectedUserGroups[] = $UserGroupObject;
$userGroupUsers = Customer::getByUserGroup($UserGroupObject);
foreach ($userGroupUsers as $userGroupUser) {
// Check if user is not already processed to avoid duplicates
if (!in_array($userGroupUser->getId(), $processedUserIds)) {
$newObjectArray[] = $userGroupUser;
$processedUserIds[] = $userGroupUser->getId();
}
}
}
}
}
// Update the notification with new user groups and users
$alertSubscription->setUserGroup($selectedUserGroups);
$alertSubscription->setSubscribers($newObjectArray);
$alertSubscription->save();
return ["success" => true, "message" => $translator->trans("custom_notification_assigned_successfully")];
} else {
return ["success" => false, "message" => $translator->trans("user_group_array_is_empty")];
}
}
}