src/Command/SendMannedAlertsCommand.php line 210

Open in your IDE?
  1. <?php
  2. namespace App\Command;
  3. use App\Model\UserModel;
  4. use Datetime;
  5. use Pimcore\Db;
  6. use GuzzleHttp\Client;
  7. use Pimcore\Log\Simple;
  8. use App\Service\RedisCache;
  9. use App\Model\LocationModel;
  10. use GuzzleHttp\Psr7\Request;
  11. use App\Service\EmailService;
  12. use Pimcore\Model\DataObject;
  13. use App\Model\EwsNotificationModel;
  14. use App\Service\NCMWeatherAPIService;
  15. use App\Service\MeteomaticsWeatherService;
  16. use Symfony\Component\Console\Command\Command;
  17. use Symfony\Component\Templating\EngineInterface;
  18. use Symfony\Component\Console\Input\InputArgument;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Output\OutputInterface;
  21. use App\C2IntegrationBundle\Service\C2Service;
  22. use App\Service\RichService;
  23. use Symfony\Contracts\HttpClient\HttpClientInterface;
  24. class SendMannedAlertsCommand extends Command
  25. {
  26. protected static $defaultName = 'app:get-manned-alerts';
  27. const HOURS = 24;
  28. var $emailService = null;
  29. private $templating;
  30. private $nCMWeatherAPIService;
  31. private $redisCache;
  32. private $locationModel;
  33. private $userModel;
  34. private $ewsNotificationModel;
  35. private $c2Service;
  36. private $richService;
  37. private $httpClient;
  38. public function __construct(EngineInterface $templating, RedisCache $redisCache, RichService $richService, HttpClientInterface $httpClient)
  39. {
  40. parent::__construct();
  41. $this->templating = $templating;
  42. $this->nCMWeatherAPIService = new NCMWeatherAPIService($redisCache,$httpClient);
  43. $this->redisCache = $redisCache;
  44. $this->locationModel = new LocationModel();
  45. $this->userModel = new UserModel();
  46. $this->ewsNotificationModel = new EwsNotificationModel();
  47. $this->c2Service = new C2Service();
  48. $this->richService = $richService;
  49. }
  50. protected function configure()
  51. {
  52. $this->setDescription('Retrieve manned alerts by location');
  53. }
  54. protected function execute(InputInterface $input, OutputInterface $output)
  55. { date_default_timezone_set(TIMEZONE);
  56. $this->emailService = new EmailService();
  57. $mateoMaticsService = new MeteomaticsWeatherService($this->redisCache);
  58. $db = DB::get();
  59. $localities = [];
  60. $loopCount = 5;
  61. $distincLocalities = $db->fetchAll("SELECT GROUP_CONCAT(DISTINCT addressValue) as localities FROM `object_collection_AddressComponents_location` WHERE `addressKey` = 'locality'");
  62. if ($distincLocalities) {
  63. $localities = explode(",", $distincLocalities[0]['localities']);
  64. }
  65. // Fetching alerts
  66. $alerts = $this->nCMWeatherAPIService->getAlerts();
  67. if ($alerts) {
  68. foreach ($alerts as $alert) {
  69. try {
  70. // Create update alert
  71. $mannedAlert = $this->createUpdateAlertNotification($alert, $output);
  72. if (!$mannedAlert) {
  73. $output->writeln('Nothing updated on notification = ' . $alert['id']);
  74. continue;
  75. }
  76. if ($_ENV['SEND_EMAIL_NOTIFICATION'] == "false") {
  77. $output->writeln('Email is not allowed on this environment');
  78. continue;
  79. }
  80. if (!$mannedAlert->getIsSent()) {
  81. $mannedAlertSubscription = new DataObject\MannedAlertSubscription\Listing();
  82. $mannedAlertSubscription->setOrderKey("o_creationDate");
  83. $mannedAlertSubscription->setOrder("desc");
  84. foreach ($mannedAlertSubscription as $subscription) {
  85. if ($subscription->getIsPublic() == false) {
  86. # code...
  87. // $subscriptionRegion = $subscription->getIsPublic() ?? false;
  88. $subscriptionRegion = false;
  89. if ($subscription->getRegion()) {
  90. if ($subscription->getRegion()->getRegionId() == $alert['regionID']) {
  91. $subscriptionRegion = true;
  92. }
  93. }
  94. // $alertType = $subscription->getIsPublic() ?? false;
  95. $alertType = false;
  96. if ($subscription->getAlertType()) {
  97. foreach ($subscription->getAlertType() as $alertType) {
  98. if ($alertType->getAlertTypeId() == $alert['alertType']) {
  99. $alertType = true;
  100. break;
  101. }
  102. }
  103. }
  104. // $alertGovernorate = $subscription->getIsPublic() ?? false;
  105. $alertGovernorate = false;
  106. $alertGovernoratesIds = array_column($alert['governorates'], 'id');
  107. if ($subscription->getGovernorate()) {
  108. foreach ($subscription->getGovernorate() as $governorate) {
  109. if (in_array($governorate->getGovernoteId(), $alertGovernoratesIds)) {
  110. $alertGovernorate = true;
  111. break;
  112. }
  113. }
  114. }
  115. // $phenomena = $subscription->getIsPublic() ?? false;
  116. $phenomena = false;
  117. $phenomenaIds = array_column($alert['alertHazards'], 'id');
  118. if ($subscription->getPhenomena()) {
  119. foreach ($subscription->getPhenomena() as $phenomenas) {
  120. if (in_array($phenomenas->getPhenomenaListId(), $phenomenaIds)) {
  121. $phenomena = true;
  122. break;
  123. }
  124. }
  125. }
  126. if ($subscriptionRegion && $alertType && $alertGovernorate && $phenomena) {
  127. // if (!empty($subscription->getEmail())) {
  128. // $user_name = explode('@', $subscription->getEmail());
  129. // $email = $this->sendEmailNotification($user_name[0], $alert, $subscription->getEmail(), $actualUser = false);
  130. // // continue;
  131. // }
  132. if (!empty($subscription->getCreator())) {
  133. $user = $subscription->getCreator();
  134. $entityUserSubscription = $this->userModel->getEntitySubscription($user);
  135. $packageExpired = $entityUserSubscription ? (new \DateTime() > $entityUserSubscription->getEndDate() ? true : false) : false;
  136. $subActive = $entityUserSubscription ? $entityUserSubscription->getIsActive() : false;
  137. $nonSubUser = $subActive && !$packageExpired;
  138. if ($user->getSevereWeatherAlert() && $nonSubUser) {
  139. $email = $this->sendEmailNotification($user, $alert, null , true);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. // if (in_array($alert['regionEn'], $localities)) {
  146. // // SELECT olqre.name as region,olqge.name as governate,olqwfc.name as municipality FROM object_region ore LEFT JOIN object_governorate ogo ON ore.oo_id = ogo.regionId__id LEFT JOIN object_weather_forecasting_city owfc ON owfc.MappedGovernorateId__id = ogo.oo_id LEFT JOIN object_localized_query_region_en olqre ON ore.oo_id = olqre.ooo_id LEFT JOIN object_localized_query_governorate_en olqge ON ogo.oo_id = olqge.ooo_id LEFT JOIN object_localized_query_weather_forecasting_city_en olqwfc ON owfc.oo_id = olqwfc.ooo_id
  147. // // Fetching user fall in found localities
  148. // $selectedLocalities = $this->ewsNotificationModel->getEwsNotificationByByRegionName($alert['regionEn']);
  149. // if ($selectedLocalities) {
  150. // $totalIterations = count($selectedLocalities);
  151. // $iterations = 0;
  152. // foreach ($selectedLocalities as $locality) {
  153. // $locality = \Pimcore\Model\DataObject::getById($locality['o_id']);
  154. // $users = $locality->getUser();
  155. // // $email = $this->sendEmailNotification($users, $alert);
  156. // // Increment the iteration count
  157. // $iterations++;
  158. // // Check if 5 iterations have passed
  159. // if ($iterations % $loopCount === 0 && $iterations !== $totalIterations) {
  160. // // If 5 iterations have passed and it's not the last iteration, sleep for 65 seconds
  161. // sleep(65);
  162. // }
  163. // }
  164. // }
  165. // }
  166. }
  167. $mannedAlert->setIsSent(true);
  168. $mannedAlert->save();
  169. } catch (\Exception $ex) {
  170. p_r($ex->getMessage());
  171. }
  172. }
  173. }
  174. return 0;
  175. }
  176. private function sendEmailNotification($users, $alert, $email = null, $actualUser)
  177. {
  178. $mailSent = null;
  179. if ($alert) {
  180. $governatesArr = $alert['governorates'];
  181. $governates = [];
  182. if ($governatesArr) {
  183. foreach ($governatesArr as $gov) {
  184. $governates[] = $gov['nameEn'];
  185. }
  186. }
  187. $alertHazardsArr = $alert['alertHazards'];
  188. $alertHazards = [];
  189. $alertHazards_ar = [];
  190. if ($alertHazardsArr) {
  191. foreach ($alertHazardsArr as $alertHazard) {
  192. $alertHazards[] = $alertHazard['descriptionEn'];
  193. $alertHazards_ar[] = ['nameAr' =>$alertHazard['descriptionAr']];
  194. }
  195. }
  196. $alertActionsArr = $alert['alertActions'];
  197. $alertActions = [];
  198. if ($alertActionsArr) {
  199. foreach ($alertActionsArr as $alertAction) {
  200. $alertActions[] = $alertAction['descriptionEn'];
  201. }
  202. }
  203. $data = $alert;
  204. $data['sender'] = 'National Center for Meteorology';
  205. // $subject =$alert['searchEwsIdAr'] ??'Severe Weather Alert - ' . $alert['regionEn'];
  206. $subject = $alert['alertStatusAr'] . ' - ' . $alert['regionAR'];
  207. //sending an email document (pimcore document)
  208. $emailAlertTemplate = '/email/alert_notification';
  209. if ($users) {
  210. $data['name'] = $email ? $users : $users->getName();
  211. // extra param js
  212. $alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  213. $alertName = $alertObj->getColor() ? $alertObj->getColor() : '';
  214. $alert['user_name'] = $email ? $users : $users->getName();
  215. $alert['host'] = API_BASE_URL;
  216. $alert['alertColor'] = $alertName;
  217. $backgroundColor = '#fcb82526';
  218. $borderColor = '#000000';
  219. $textColor = '#000000';
  220. if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  221. $alertColorLower = strtolower(trim($alert['alertColor']));
  222. if ($alertColorLower === 'red') {
  223. $backgroundColor = '#f6000017';
  224. $borderColor = '#F60000';
  225. $textColor = '#F60000';
  226. } elseif ($alertColorLower === 'orange') {
  227. $backgroundColor = '#ff66001f';
  228. $borderColor = '#FF6600';
  229. $textColor = '#FF6600';
  230. } elseif ($alertColorLower === 'yellow') {
  231. $backgroundColor = '#fcb82526';
  232. $borderColor = '#FCB825';
  233. $textColor = '#FCB825';
  234. }
  235. }
  236. $alert['backgroundColor'] = $backgroundColor;
  237. $alert['borderColor'] = $borderColor;
  238. $alert['textColor'] = $textColor;
  239. $currentDate = new \DateTime($alert['fromDate']);
  240. $searchIdAr= 'النظام الالي للإنذار المبكر | '.$currentDate->format('dmY').'-'.$alert['id'].' | '.$alert['alertTypeAr'].' | '.$alert['alertStatusAr'];
  241. $alert['searchEwsIdAr'] = $searchIdAr;
  242. $alert['alertHazard'] = $alertHazards_ar;
  243. $alert['last_modified_date'] = $alert['lastModified'];
  244. $alert['tokenURL'] = null; // for now this is null but we have to develop unsubscribe functionality for this as well
  245. if ($actualUser) {
  246. // general un subscribe function
  247. $token = \App\Lib\Utility::getUnSubscribeToken($users->getId());
  248. $alert['tokenURL'] = BASE_URL . '/unsubscribe/email?token=' . $token;
  249. }
  250. $alert['mannedAlertDatailUrl'] = "https://ncm.gov.sa/Ar/alert/Pages/MapDetail.aspx?AlertId=".$alert['id'];
  251. $html = $this->templating->render('web2print/_manned_alert_notification_ar.html.twig', $alert);
  252. $mannedAlert = \Pimcore\Model\DataObject\MannedAlertNotification::getByAlertId($alert['id'], true);
  253. $purpose = MANNED_ALERT_MESSAGE;
  254. if ($email) {
  255. $mailSent = $this->c2Service->sendDefaultEmail($_ENV['EWS_MAIL_TEMPLATE'], $mannedAlert->getId(), $email, $html, $subject, $purpose);
  256. } else {
  257. $mailSent = $this->c2Service->sendNotificationEmail($_ENV['EWS_MAIL_TEMPLATE'], $mannedAlert->getId(), $users->getId(), $html, $subject, $purpose);
  258. }
  259. if ($users->getPhoneNo() && strlen($users->getPhoneNo()) == 9) {
  260. $messageSMS = sprintf(SMS_MESSAGE["MANNED_ALERT"], strtoupper($alertName) . " alert raised in " . $alert['regionAR'] . ' for ' . $alert['alertStatusAr'] . " event");
  261. $this->richService->sendSms(SAUDI_CALL_CODE.$users->getPhoneNo(), $messageSMS);
  262. }
  263. // $html = $this->templating->render('web2print/_manned_alert_notification_ar.html.twig', $alert);
  264. // $response['message_en'] = $html;
  265. // $email = $users->getEmail();
  266. // $param = ['user' => $users, 'message' => $html, 'url' => null];
  267. // $mailSent = $this->emailService->sendMail($param, $email, $emailAlertTemplate, $subject);
  268. }
  269. // if ($users) {
  270. // foreach ($users as $user) {
  271. // $data['name'] = $user->getName();
  272. // $html = $this->templating->render('web2print/_manned_alert_notification_ar.html.twig', $data);
  273. // $currentUser = $user->getObject();
  274. // $data = $user->getData();
  275. // if (isset($data['get_severe_alert']) && $data['get_severe_alert']) {
  276. // $email = $currentUser->getEmail();
  277. // $param = ['user' => $currentUser, 'message' => $html, 'url' => null];
  278. // $mailSent = $this->emailService->sendMail($param, $email, $emailAlertTemplate, $subject);
  279. // }
  280. // }
  281. // }
  282. }
  283. return $mailSent;
  284. }
  285. private function createUpdateAlertNotification($alert, $output)
  286. {
  287. // Generate the hash for the current alert data
  288. $alertHash = md5(json_encode($alert));
  289. // Retrieve the existing MannedAlertNotification object by alert ID
  290. $mannedAlert = \Pimcore\Model\DataObject\MannedAlertNotification::getByAlertId($alert['id'], true);
  291. // Check if the alert already exists
  292. if ($mannedAlert) {
  293. // Compare the old hash with the new hash
  294. if ($mannedAlert->getHash() === $alertHash) {
  295. // If the hashes match, the alert has not changed; ignore it
  296. return null;
  297. }
  298. } else {
  299. // If the alert does not exist, create a new MannedAlertNotification object
  300. $mannedAlert = new DataObject\MannedAlertNotification();
  301. $mannedAlert->setKey($alert['id']);
  302. $date = date('Y-m-d', strtotime($alert['fromDate']));
  303. $mannedAlert->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/Notification/' . $date));
  304. $mannedAlert->setPublished(TRUE);
  305. }
  306. // Update the MannedAlertNotification object with the new alert data
  307. $mannedAlert->setAlertId($alert['id']);
  308. $mannedAlert->setTitle($alert['title']);
  309. $mannedAlert->setAlertType($this->getAlertType($alert['alertType'], $alert['alertTypeAr'], $alert['alertTypeEn']));
  310. $fromDate = \Carbon\Carbon::createFromFormat('m/d/Y h:i:s A', $alert['fromDate']);
  311. $toDate = \Carbon\Carbon::createFromFormat('m/d/Y h:i:s A', $alert['toDate']);
  312. $lastModified = \Carbon\Carbon::createFromFormat('m/d/Y h:i:s A', $alert['lastModified']);
  313. $mannedAlert->setFromDate($fromDate);
  314. $mannedAlert->setToDate($toDate);
  315. $mannedAlert->setLastModifiedDate($lastModified);
  316. $mannedAlert->setAlertStatusCategory($this->getAlertStatusCategory($alert['alertStatusCategory']));
  317. $mannedAlert->setAlertStatus($this->getAlertStatus($alert['alertStatusID'], $alert['alertStatusAr'], $alert['alertStatusEn']));
  318. $alertHazardArr = [];
  319. if ($alert['alertHazards']) {
  320. foreach ($alert['alertHazards'] as $alertHazard) {
  321. $alertHazardArr[] = $this->getAlertHazard($alertHazard['id'], $alertHazard['descriptionAr'], $alertHazard['descriptionEn']);
  322. }
  323. $mannedAlert->setAlertHazards(array_filter($alertHazardArr));
  324. }
  325. $mannedAlert->setRegion($this->getRegion($alert['regionID'], $alert['regionAR'], $alert['regionEn']));
  326. $alertGovernorateArr = [];
  327. if ($alert['governorates']) {
  328. foreach ($alert['governorates'] as $alertGovernorate) {
  329. $alertGovernorateArr[] = $this->getGovernorates($alertGovernorate['id'], $alertGovernorate['nameAr'], $alertGovernorate['nameEn'], $alertGovernorate['longitude'], $alertGovernorate['latitude']);
  330. }
  331. $mannedAlert->setGovernorates(array_filter($alertGovernorateArr));
  332. }
  333. $mannedAlert->setOtherLocation($alert['otherLocationsEn'], 'en');
  334. $mannedAlert->setOtherLocation($alert['otherLocationsAr'], 'ar');
  335. $mannedAlert->settweetID($alert['tweetID']);
  336. $alertAlertActionArr = [];
  337. if ($alert['alertActions']) {
  338. foreach ($alert['alertActions'] as $alertAlertAction) {
  339. $alertAlertActionArr[] = $this->getAlertAction($alertAlertAction['id'], $alertAlertAction['descriptionAr'], $alertAlertAction['descriptionEn']);
  340. }
  341. $mannedAlert->setAlertAction(array_filter($alertAlertActionArr));
  342. }
  343. // Set the hash for the alert
  344. $mannedAlert->setHash($alertHash);
  345. $mannedAlert->setRawText(json_encode($alert));
  346. $mannedAlert->setIsSent(false);
  347. // Save the updated MannedAlertNotification object
  348. $mannedAlert->save();
  349. return $mannedAlert;
  350. }
  351. private function getAlertType($id, $nameAr, $nameEn)
  352. {
  353. $alertType = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($id, true);
  354. if (!$alertType) {
  355. $alertType = new \Pimcore\Model\DataObject\AlertType();
  356. $alertType->setKey($id);
  357. $alertType->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/AlertType'));
  358. $alertType->setAlertTypeId($id);
  359. $alertType->setName($nameAr, "en");
  360. $alertType->setName($nameEn, "ar");
  361. $alertType->setPublished(true);
  362. $alertType->save();
  363. }
  364. return $alertType;
  365. }
  366. private function getAlertStatusCategory($name)
  367. {
  368. $alertStatusCategory = \Pimcore\Model\DataObject\AlertStatusCategory::getByName($name, true);
  369. if (!$alertStatusCategory) {
  370. $alertStatusCategory = new \Pimcore\Model\DataObject\AlertStatusCategory();
  371. $alertStatusCategory->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/AlertStatusCategory'));
  372. $alertStatusCategory->setKey($name);
  373. $alertStatusCategory->setName($name);
  374. $alertStatusCategory->setPublished(true);
  375. $alertStatusCategory->save();
  376. }
  377. return $alertStatusCategory;
  378. }
  379. private function getAlertStatus($id, $nameAr, $nameEn)
  380. {
  381. $alertStatus = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($id, true);
  382. if (!$alertStatus) {
  383. $alertStatus = new \Pimcore\Model\DataObject\AlertStatus();
  384. $alertStatus->setKey($id);
  385. $alertStatus->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/AlertStatus'));
  386. $alertStatus->setAlertStatusId($id);
  387. $alertStatus->setName($nameAr, 'ar');
  388. $alertStatus->setName($nameEn, 'en');
  389. $alertStatus->setPublished(true);
  390. $alertStatus->save();
  391. }
  392. return $alertStatus;
  393. }
  394. private function getAlertHazard($id, $descriptionAr, $descriptionEn)
  395. {
  396. $alertHazard = \Pimcore\Model\DataObject\AlertHazard::getByAlertHazardId($id, true);
  397. if (!$alertHazard) {
  398. $alertHazard = new \Pimcore\Model\DataObject\AlertHazard();
  399. $alertHazard->setKey($id);
  400. $alertHazard->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/AlertHazard'));
  401. $alertHazard->setAlertHazardId($id);
  402. $alertHazard->setName($descriptionAr, "ar");
  403. $alertHazard->setName($descriptionEn, "en");
  404. $alertHazard->setPublished(true);
  405. $alertHazard->save();
  406. } else {
  407. $alertHazard->setName($descriptionAr, "ar");
  408. $alertHazard->setName($descriptionEn, "en");
  409. $alertHazard->save();
  410. }
  411. return $alertHazard;
  412. }
  413. private function getRegion($id, $nameAr, $nameEn)
  414. {
  415. $region = \Pimcore\Model\DataObject\Region::getByRegionId($id, true);
  416. if (!$region) {
  417. $region = new \Pimcore\Model\DataObject\Region();
  418. $region->setKey($id);
  419. $region->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/Region'));
  420. $region->setRegionId($id);
  421. $region->setName($nameAr, 'ar');
  422. $region->setName($nameEn, 'en');
  423. $region->setPublished(true);
  424. $region->save();
  425. }
  426. return $region;
  427. }
  428. private function getGovernorates($id, $nameAr, $nameEn, $longitude, $latitude)
  429. {
  430. $governorate = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($id, true);
  431. if (!$governorate) {
  432. $governorate = new \Pimcore\Model\DataObject\Governorate();
  433. $governorate->setKey($id);
  434. $governorate->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/Governorate'));
  435. $governorate->setGovernoteId($id);
  436. $governorate->setName($nameAr, "ar");
  437. $governorate->setName($nameEn, "en");
  438. $governorate->setLongitude($longitude);
  439. $governorate->setLatitude($latitude);
  440. $governorate->setPublished(true);
  441. $governorate->save();
  442. }
  443. return $governorate;
  444. }
  445. private function getAlertAction($id, $descriptionAr, $descriptionEn)
  446. {
  447. $alertAction = \Pimcore\Model\DataObject\AlertAction::getByAlertActionId($id, true);
  448. if (!$alertAction) {
  449. $alertAction = new \Pimcore\Model\DataObject\AlertAction();
  450. $alertAction->setKey($id);
  451. $alertAction->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Master/AlertAction'));
  452. $alertAction->setAlertActionId($id);
  453. $alertAction->setName($descriptionAr, "ar");
  454. $alertAction->setName($descriptionEn, "en");
  455. $alertAction->setPublished(true);
  456. $alertAction->save();
  457. }
  458. return $alertAction;
  459. }
  460. }