<?php
namespace App\Controller;
use DateTime;
use Carbon\Carbon;
use Knp\Snappy\Pdf;
use App\Model\UserModel;
use Pimcore\Model\Asset;
use App\Service\RedisCache;
use App\Model\ReportLogModel;
use App\Service\EmailService;
use App\Service\ReportModerationEmailService;
use App\Service\ReportService;
use App\Service\UserPermission;
use App\Model\OrganizationModel;
use Pimcore\Log\ApplicationLogger;
use App\Service\NotificationService;
use Pimcore\Model\DataObject\Report;
use Pimcore\Model\DataObject\ReportType;
use Pimcore\Model\DataObject\Customer;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use App\Service\MeteomaticsWeatherService;
use App\Service\MarineReportService;
use Pimcore\Controller\FrontendController;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Pimcore\Model\DataObject\EwsNotification;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Model\EwsNotificationModel;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Matches
*
* @Route("/api/ncm/report")
*/
class ReportController extends FrontendController
{
private $organizationModel;
private $userModel;
private $lang;
private $reportModel;
public function __construct(
private TokenStorageInterface $tokenStorageInterface,
private JWTTokenManagerInterface $jwtManager,
private UserPermission $userPermission,
protected TranslatorInterface $translator,
private ApplicationLogger $logger,
private RedisCache $redisCache,
private MeteomaticsWeatherService $meteomaticsWeatherService,
private Pdf $snappy,
private ReportService $reportService,
private NotificationService $notificationService,
private EmailService $emailService,
private ReportModerationEmailService $reportModerationEmailService,
private HttpClientInterface $httpClient,
private MarineReportService $marineReportService
) {
$this->reportModel = new ReportLogModel();
// header('Content-Type: application/json; charset=UTF-8');
//header("Access-Control-Allow-Origin: *");
}
/**
* @Route("/weather_forecast_report", name="api_ncm_report_weather_forecast_report", methods={"POST"})
*/
public function weatherForecastReport(Request $request, UserInterface $user): JsonResponse
{
$response = [];
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['format'])) {
throw new \InvalidArgumentException('Missing "format" parameter');
}
if ($params['format'] == "json") {
if (
!isset($params['startdate']) ||
!isset($params['enddate']) ||
!isset($params['resolution']) ||
!isset($params['parameters']) ||
!isset($params['lat']) ||
!isset($params['lon']) ||
!isset($params['format'])
) {
throw new \Exception('Missing required parameters');
}
//$hour = $params['hour'];
$format = $params['format'];
$startDate = $params['startdate'];
$endDate = $params['enddate'];
$resolution = $params['resolution'];
$parameters = $params['parameters'];
$model = $params['model'];
$lat = $params['lat'];
$lon = $params['lon'];
$response = $this->reportService->getWeatherForecastReport(
$startDate,
$endDate,
$resolution,
$parameters,
$model,
$lat,
$lon,
$format,
$this->translator
);
}
return $this->json($response);
}
/**
* @Route("/special_report", name="api_ncm_report_special_report", methods={"POST"})
*/
public function specialReport(Request $request, UserInterface $user): JsonResponse
{
$response = [];
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['format'])) {
throw new \InvalidArgumentException('Missing "format" parameter');
}
if ($params['format'] == "json") {
if (
!isset($params['startdate']) ||
!isset($params['enddate']) ||
!isset($params['resolution']) ||
!isset($params['parameters']) ||
!isset($params['lat']) ||
!isset($params['lon']) ||
!isset($params['format'])
) {
throw new \Exception('Missing required parameters');
}
//$hour = $params['hour'];
$format = $params['format'];
$startDate = $params['startdate'];
$endDate = $params['enddate'];
$resolution = $params['resolution'];
$parameters = $params['parameters'];
$model = $params['model'];
$lat = $params['lat'];
$lon = $params['lon'];
$response = $this->reportService->getSpecialReport(
$startDate,
$endDate,
$resolution,
$parameters,
$model,
$lat,
$lon,
$format,
$this->translator
);
}
return $this->json($response);
}
/**
* @Route("/save_data", name="api_ncm_report_save_data", methods={"POST"})
*/
public function saveData(Request $request, UserInterface $user): JsonResponse
{
$response = [];
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['startdate']) ||
!isset($params['enddate']) ||
!isset($params['lat']) ||
!isset($params['lon']) ||
!isset($params['type_of_report']) ||
!isset($params['key']) ||
!isset($params['data'])
) {
throw new \Exception('Missing required parameters');
}
$startDate = $params['startdate'];
$endDate = $params['enddate'];
$typeOfReport = $params['type_of_report'];
$key = $params['key'];
$lat = $params['lat'];
$lon = $params['lon'];
$data = $params['data'];
$response = $this->reportService->saveData($key, $typeOfReport, $startDate, $endDate, $lat, $lon, $data);
} catch (\Exception $ex) {
$response = ["success" => false, "message" => $ex->getMessage()];
}
return $this->json($response);
}
/**
* @Route("/generate-report", name="api_ncm_report_generate_report", methods={"POST"})
*/
public function generateReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-arabian-gulf-report", name="api_ncm_report_create_arabian_gulf_report", methods={"POST"})
*/
public function createArabianGulfReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-today-weather-report", name="api_ncm_report_create_today_weather_report", methods={"POST"})
*/
public function createTodayWeatherReport(Request $request): JsonResponse
{
try {
$response = [];
// $permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
// if (isset($permissions['code']) && $permissions['code'] === 401) {
// return $this->json($permissions, 401);
// } elseif ($permissions['success'] === false) {
// return $this->json($permissions);
// }
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-red-sea-report", name="api_ncm_report_create_red_sea_report", methods={"POST"})
*/
public function createRedSeaReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-custom-weather-report", name="api_ncm_report_create_custom_weather_report", methods={"POST"})
*/
public function createCustomWeatherReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-mashaer-weather-report", name="api_ncm_report_create_mashaer_weather_report", methods={"POST"})
*/
public function createMashaerWeatherReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-10-day-forecast-report", name="api_ncm_report_create_10_day_forecast_report", methods={"POST"})
*/
public function create10DayForecastReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters_24h']) ||
!isset($params['parameters_12h']) ||
!isset($params['is_governate']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (!is_array($params['parameters_12h'])) {
throw new \Exception('Parameters 12 h should be array');
}
if (!is_array($params['parameters_24h'])) {
throw new \Exception('Parameters 24 h should be array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters_12h']) . '-' . implode('_', $params['parameters_24h']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
} else {
$citiesArr[$lat . '|' . $long]["id"] = $city->getId();
$citiesArr[$lat . '|' . $long]["en"] = $city->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
}
$result = $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model, $params['parameters_12h'], $params['parameters_24h'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
// throw new \Exception($ex);
// $this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/create-report", name="api_ncm_report_create_report", methods={"POST"})
*/
public function createReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-arabian-gulf-report", name="api_ncm_report_publish_arabian_gulf", methods={"POST"})
*/
public function publishArabianGulfReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-today-weather-report", name="api_ncm_report_publish_today_weather_report", methods={"POST"})
*/
public function publishTodayWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
// if (isset($permissions['code']) && $permissions['code'] === 401) {
// return $this->json($permissions, 401);
// } elseif ($permissions['success'] === false) {
// return $this->json($permissions);
// }
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['imageEn']) || !isset($params['imageAr'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->createTodayWeatherReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* Marine report payload (preferred): redSeaWind, redSeaWaveHight, redSeaStatus, arabianGulfWind, arabianGulfWaveHight, arabianGulfSeaStatus (non-empty strings).
* Alternate: redSea, arabianGulf objects (WindAr/WaveHightAr/SeaStatusAr or windSpeed, windDirection, waveHeight, visibility, weather).
* Optional weatherDate (UTC); display { dayNameArabic, gregorian, hijri } is built server-side via MarineReportService::buildDateDisplay (or "now" in Riyadh when omitted).
* Required infographicImageBase64: client image (PNG/JPEG/GIF/WebP), plain base64 or data:image/...;base64,.
* Optional apiUrl, lang, Authorization (JWT in body when validateAPI is enabled).
*
* @Route("/publish-marine-report", name="api_ncm_report_publish_marine_report", methods={"POST"})
*/
public function publishMarineReport(Request $request, UserInterface $user): JsonResponse
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
}
if (($permissions['success'] ?? false) === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
if (!\is_array($params)) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
$this->translator->setlocale($params['lang'] ?? DEFAULT_LOCALE);
$flatMarineKeys = [
'redSeaWind',
'redSeaWaveHight',
'redSeaStatus',
'arabianGulfWind',
'arabianGulfWaveHight',
'arabianGulfSeaStatus',
'infographicImageBase64',
'twitterDescription',
];
$useFlatPayload = true;
foreach ($flatMarineKeys as $key) {
if (!isset($params[$key]) || trim((string) $params[$key]) === '') {
$useFlatPayload = false;
break;
}
}
if ($useFlatPayload) {
$redSea = $this->marineReportService->normalizeMarineRegionForInfographic([
'WindAr' => trim((string) $params['redSeaWind']),
'WaveHightAr' => trim((string) $params['redSeaWaveHight']),
'SeaStatusAr' => trim((string) $params['redSeaStatus']),
]);
$gulf = $this->marineReportService->normalizeMarineRegionForInfographic([
'WindAr' => trim((string) $params['arabianGulfWind']),
'WaveHightAr' => trim((string) $params['arabianGulfWaveHight']),
'SeaStatusAr' => trim((string) $params['arabianGulfSeaStatus']),
]);
}
if (!$this->marineReportService->regionHasContent($redSea) && !$this->marineReportService->regionHasContent($gulf)) {
return $this->json([
'success' => true,
'message' => $this->translator->trans('marine_report_skipped_empty'),
'data' => null,
]);
}
$clientInfographicB64 = null;
if (isset($params['infographicImageBase64']) && trim((string) $params['infographicImageBase64']) !== '') {
$clientInfographicB64 = trim((string) $params['infographicImageBase64']);
}
if ($clientInfographicB64 === null) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
$decodedImage = $this->reportModel->decodeImageBase64String($clientInfographicB64);
if ($decodedImage === false || @getimagesizefromstring($decodedImage) === false) {
return $this->json(['success' => false, 'message' => $this->translator->trans('marine_report_invalid_image')]);
}
$result = $this->reportModel->createMarineReport($user, [
'redSea' => $redSea,
'gulf' => $gulf,
'weatherDate' => $params['weatherDate'] ?? null,
'infographicImageBase64' => $decodedImage,
'twitterDescription' => $params['twitterDescription'] ?? '',
], $this->translator, $this->marineReportService);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* Fetches upstream marine-reports JSON, then responds with { redSea, arabianGulf, display, apiUrl } (same shape as publish-marine-report body).
* Upstream may be a list of rows or already that object. Forwards query string to upstream (except lang). Optional ?lang= for error messages.
*
* @Route("/get-marine-reports", name="api_ncm_report_get_marine_reports", methods={"POST"})
*/
public function getMarineReports(Request $request, UserInterface $user): JsonResponse
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
}
if (($permissions['success'] ?? false) === false) {
return $this->json($permissions);
}
$this->translator->setlocale($request->query->get('lang') ?: DEFAULT_LOCALE);
$url = NCM_PUBLIC_PORTAL_URL . 'api/ncm/internal/marine-reports';
$forwardQuery = $request->query->all();
unset($forwardQuery['lang']);
if ($forwardQuery !== []) {
$url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($forwardQuery);
}
$response = $this->httpClient->request('GET', $url, [
'timeout' => 120,
'headers' => ['Accept' => 'application/json'],
]);
$status = $response->getStatusCode();
$body = $response->getContent(false);
if ($status < 200 || $status >= 300) {
$this->logger->error('Marine reports upstream HTTP ' . $status . ' for ' . $url);
return $this->json([
'success' => false,
'message' => $this->translator->trans('marine_reports_fetch_failed'),
'httpStatus' => $status,
], $status >= 400 && $status < 600 ? $status : 502);
}
$decoded = json_decode($body, true);
if (!\is_array($decoded)) {
return $this->json([
'success' => false,
'message' => $this->translator->trans('marine_reports_invalid_upstream_json'),
], 502);
}
$envelope = $this->marineReportService->buildEnvelope($decoded, $url);
if ($envelope === null) {
return $this->json([
'success' => false,
'message' => $this->translator->trans('marine_reports_envelope_failed'),
], 422);
}
return $this->json($envelope);
} catch (\Throwable $ex) {
$this->logger->error('Marine reports fetch: ' . $ex->getMessage());
return $this->json([
'success' => false,
'message' => $this->translator->trans('marine_reports_fetch_failed'),
], 502);
}
}
/**
* @Route("/publish-10-day-forecast-report", name="api_ncm_report_publish_10_day_forecast", methods={"POST"})
*/
public function publish10DayForecastReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-red-sea-report", name="api_ncm_report_publish_red_sea", methods={"POST"})
*/
public function publishRedSeaReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-custom-weather-report", name="api_ncm_report_publish_custom_weather", methods={"POST"})
*/
public function publishCustomWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-mashaer-weather-report", name="api_ncm_report_publish_mashaer_weather", methods={"POST"})
*/
public function publishMashaerWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
if (in_array('twitter', $params['channels'])) {
if (!isset($params['xCaption']) || empty($params['xCaption'])) {
throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-city-list", name="api_ncm_report_get_city_list")
*/
public function getCityListAction(Request $request)
{
try {
$result = [];
$lang = ($request->headers->has('lang')) ? $request->headers->get('lang') : "en";
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$reportTypeId = $params['report_type_id'] ?? null;
$cities = new \Pimcore\Model\DataObject\City\Listing();
if ($reportTypeId) {
$cities->setCondition("reportType REGEXP CONCAT('(^|,)', REPLACE('" . $reportTypeId . "', ',', '|'), '(,|$)')");
} else {
$db = \Pimcore\Db::get();
$selectedLocalities = $db->fetchAllAssociative("SELECT oo_id FROM `object_query_ReportType` WHERE (`isAutomaticReport` = 0)");
$ooIds = array_column($selectedLocalities, 'oo_id');
$cities->setCondition("reportType REGEXP CONCAT('(^|,)', REPLACE('" . implode(',', $ooIds) . "', ',', '|'), '(,|$)')");
}
$cities->setOrderKey('orderId');
$cities->setOrder('asc');
$cities->load();
if ($cities->getCount() > 0) {
foreach ($cities as $city) {
$result[] = [
"id" => $city->getId(),
"name" => $city->getCityName($lang),
"nameEn" => $city->getCityName('en'),
"nameAr" => $city->getCityName('ar'),
"lat" => $city->getLatitude(),
"long" => $city->getLongitude(),
"googlePlaceName" => $city->getGooglePlaceName(),
];
}
return $this->json(["success" => true, "data" => $result]);
}
return $this->json(["success" => false, "message" => $this->translator->trans("no_city_is_available")]);
} catch (\Exception $ex) {
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/list-report", name="api_ncm_report_list_report", methods={"POST"})
*/
public function getReportListAction(Request $request, PaginatorInterface $paginator, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit'])) {
throw new \Exception('Missing required page_no or page_limit');
}
$report_type = isset($params['report_type']) ? $params['report_type'] : null;
$lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
$page = $params['page'];
$limit = $params['limit'];
$result = $this->reportModel->reportList($params, $page, $limit, $this->translator, $paginator, $report_type, $user, $lang, false);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/list-reports-by-type", name="api_ncm_report_list_reports_by_type", methods={"POST"})
*/
public function listReportsByType(Request $request, PaginatorInterface $paginator, UserInterface $user)
{
try {
// $permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
// if (isset($permissions['code']) && $permissions['code'] === 401) {
// return $this->json($permissions, 401);
// } elseif ($permissions['success'] === false) {
// return $this->json($permissions);
// }
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit'])) {
throw new \Exception('Missing required page or limit');
}
// Getting current JWT Token
$decodedJwtToken = null;
if ($this->tokenStorageInterface->getToken()) {
$decodedJwtToken = $this->jwtManager->decode($this->tokenStorageInterface->getToken());
}
// Array to store permissions
$allowedReportTypes = [];
// Check if the permissions are true and store them in the array
$permissionsList = [
'view_red_sea_report',
'view_arabian_gulf_report',
'view_10_day_forecast_report',
'view_custom_weather_report',
'view_advance_custom_weather_report',
'view_mashaer_weather_report',
'view_today_weather_report',
'view_alert_forecast_report'
];
// Loop through each permission and check if it's true
foreach ($permissionsList as $permission) {
$permissionStatus = $this->userPermission->getUserPermissions($decodedJwtToken, $this->translator);
if (isset($permissionStatus['grants'][$permission]) && $permissionStatus['grants'][$permission] === true) {
// Convert permission names to report type keys
$reportTypeKey = '';
switch ($permission) {
case 'view_arabian_gulf_report':
$reportTypeKey = 'arabian-gulf-report';
break;
case 'view_red_sea_report':
$reportTypeKey = 'red-sea-report';
break;
case 'view_custom_weather_report':
$reportTypeKey = 'custom-weather-report';
break;
case 'view_10_day_forecast_report':
$reportTypeKey = '10-day-forecast-report';
break;
case 'view_mashaer_weather_report':
$reportTypeKey = 'mashaer-weather-report';
break;
case 'view_advance_custom_weather_report':
$reportTypeKey = 'advance-custom-weather-report';
break;
case 'view_today_weather_report':
$reportTypeKey = 'today-weather-report';
break;
case 'view_alert_forecast_report':
$reportTypeKey = ALERT_FORECAST_REPORT_TYPE_KEY;
break;
}
if (!empty($reportTypeKey)) {
$allowedReportTypes[] = $reportTypeKey;
}
}
}
$params['allowedReportTypes'] = $allowedReportTypes;
$params['decodedJwtToken'] = $decodedJwtToken;
$params['userPermission'] = $this->userPermission;
$result = $this->reportModel->listReportsByType($params, $this->translator, $paginator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/view-10-day-forecast-report", name="api_ncm_report_view_10_day_forecast_report", methods={"POST"})
*/
public function view10DayForecastReport(Request $request, PaginatorInterface $paginator, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit'])) {
throw new \Exception('Missing required page_no or page_limit');
}
$report_type = isset($params['report_type']) ? $params['report_type'] : null;
$lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
$page = $params['page'];
$limit = $params['limit'];
$result = $this->reportModel->reportList($params, $page, $limit, $this->translator, $paginator, $report_type, $user, $lang, false);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/view-red-sea-report", name="api_ncm_report_view_red_sea_report", methods={"POST"})
*/
public function viewRedSeaReport(Request $request, PaginatorInterface $paginator, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit'])) {
throw new \Exception('Missing required page_no or page_limit');
}
$report_type = isset($params['report_type']) ? $params['report_type'] : null;
$lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
$page = $params['page'];
$limit = $params['limit'];
$result = $this->reportModel->reportList($params, $page, $limit, $this->translator, $paginator, $report_type, $user, $lang, false);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/view-custom-weather-report", name="api_ncm_report_view_custom_weather_report", methods={"POST"})
*/
public function viewCustomWeatherReport(Request $request, PaginatorInterface $paginator, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit'])) {
throw new \Exception('Missing required page_no or page_limit');
}
$report_type = isset($params['report_type']) ? $params['report_type'] : null;
$lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
$page = $params['page'];
$limit = $params['limit'];
$result = $this->reportModel->reportList($params, $page, $limit, $this->translator, $paginator, $report_type, $user, $lang, false);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/view-mashaer-weather-report", name="api_ncm_report_view_mashaer_weather_report", methods={"POST"})
*/
public function viewMashaerWeatherReport(Request $request, PaginatorInterface $paginator, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit'])) {
throw new \Exception('Missing required page_no or page_limit');
}
$report_type = isset($params['report_type']) ? $params['report_type'] : null;
$lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
$page = $params['page'];
$limit = $params['limit'];
$result = $this->reportModel->reportList($params, $page, $limit, $this->translator, $paginator, $report_type, $user, $lang, false);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/generate-report-pdf", name="api_ncm_report_generate_report_pdf", methods={"POST"})
*/
public function generateReportPdf(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$result = $this->reportModel->generatePdfReport($request, $user, $this->snappy, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-report-types", name="api_ncm_report_get_report_types", methods={"POST"})
*/
public function getReportTypes(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['automatic'])) {
throw new \Exception('missing_required_parameters');
}
$result = [];
$automatic = $params['automatic'] ? true : false;
$reportTypes = new \Pimcore\Model\DataObject\ReportType\Listing();
$reportTypes->setCondition('isAutomaticReport = ?', [$automatic]);
$reportTypes->load();
if ($reportTypes->getCount() > 0) {
foreach ($reportTypes as $reportType) {
$result[] = [
"id" => $reportType->getId(),
"key" => $reportType->getReportKey(),
"nameEn" => $reportType->getName('en'),
"nameAr" => $reportType->getName('ar'),
"descriptionEn" => $reportType->getDescription('en'),
"descriptionAr" => $reportType->getDescription('ar'),
"titleEn" => $reportType->getTitle('en'),
"titleAr" => $reportType->getTitle('ar'),
"automatic" => $reportType->getIsAutomaticReport()
];
}
return $this->json(["success" => true, "data" => $result]);
}
return $this->json(["success" => false, "message" => $this->translator->trans("no_reportType_is_available")]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-weather-params-list", name="api_ncm_report_get_weather_params_list", methods={"POST"})
*/
public function getWeatherParamsListAction(Request $request)
{
try {
$result = [];
$lang = ($request->headers->has('lang')) ? $request->headers->get('lang') : "en";
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['report_type_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
$reportTypeId = $params['report_type_id'];
$parameters = new \Pimcore\Model\DataObject\ReportWeatherParameters\Listing();
$parameters->setCondition("reportType REGEXP CONCAT('(^|,)', REPLACE('" . $reportTypeId . "', ',', '|'), '(,|$)')");
$parameters->load();
if ($parameters->getCount() > 0) {
foreach ($parameters as $paramter) {
$result[] = [
"id" => $paramter->getId(),
"nameEn" => $paramter->getName('en'),
"nameAr" => $paramter->getName('ar'),
"meteoMaticsKey" => $paramter->getMeteoMaticsKey(),
"units" => $paramter->getUnits(),
"unitTitle" => $paramter->getUnitTitle()
];
}
return $this->json(["success" => true, "data" => $result]);
}
return $this->json(["success" => false, "message" => $this->translator->trans("no_weather_parameter_is_available")]);
} catch (\Exception $ex) {
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/generate-excel", name="api_ncm_report_generate_excel")
*/
public function generateExcelReport(Request $request, UserInterface $user)
{
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['id'])) {
throw new \Exception('missing_required_parameters');
}
$report = Report::getById($params['id'], true);
if (!$report instanceof Report) {
throw new \Exception('no_report_found');
}
// Replace this with the actual data you want to use
$jsonData = json_decode($report->getJsonData(), true);
// Create a new PhpSpreadsheet instance
$spreadsheet = new Spreadsheet();
// Create a worksheet
$sheet = $spreadsheet->getActiveSheet();
// Determine headers dynamically based on the first item in the data
$firstItem = reset($jsonData);
$parameters = $firstItem['parameters'] ?? [];
$headers = [$this->translator->trans('Location'), $this->translator->trans('Latitude'), $this->translator->trans('Longitude'), $this->translator->trans('Date')]; // Initialize headers with common columns
// Extract parameter names and add them to headers
foreach ($parameters as $parameter) {
if ($parameter['parameter'] == 'prob_precip_24h:p') {
$headers[] = $this->translator->trans('Precipitation Probability (%)');
} elseif ($parameter['parameter'] == 'precip_24h:mm') {
$headers[] = $this->translator->trans('Precipitation Amount (mm)');
} elseif ($parameter['parameter'] == 'wind_speed_mean_10m_24h:kmh') {
$headers[] = $this->translator->trans('Wind Speed (km/h)');
} elseif ($parameter['parameter'] == 't_2m:C') {
$headers[] = $this->translator->trans('Temperature (°C)');
} else {
$headers[] = $parameter['parameter'];
}
}
// Add headers to the worksheet
foreach ($headers as $index => $header) {
$sheet->setCellValueByColumnAndRow($index + 1, 1, $header);
}
// Style headers
$headerStyle = [
'font' => [
'bold' => true,
'color' => ['rgb' => 'FFFFFF'], // White text
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => '16365c'], // Blue background
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
],
];
$sheet->getStyle('A1:H1')->applyFromArray($headerStyle);
// Initialize row counter
$row = 2;
foreach ($jsonData as $item) {
// Extract city-related data
$cityData = [$item['city'] ?? '', $item['lat'] ?? '', $item['lon'] ?? ''];
// Loop through each date for all parameters
foreach ($item['parameters'][0]['dates'] as $dateIndex => $date) {
// Initialize row data with city-related data and date
$rowData = array_merge($cityData, [date('Y-m-d', strtotime($date['date']))]);
// Loop through each parameter
foreach ($item['parameters'] as $parameter) {
// Check if the value is set for the current date, otherwise set it to 0
$value = isset($parameter['dates'][$dateIndex]['value']) ? $parameter['dates'][$dateIndex]['value'] : 0;
// Add parameter value for the current date to the row data
$rowData[] = $value;
}
// Set cell values explicitly
foreach ($rowData as $colIndex => $cellValue) {
$sheet->setCellValueByColumnAndRow($colIndex + 1, $row, $cellValue);
}
// Increment the row counter
$row++;
}
}
foreach (range('A', $sheet->getHighestColumn()) as $columnID) {
$sheet->getColumnDimension($columnID)->setAutoSize(true);
}
// Save the Excel file to a temporary file
$tempFile = tempnam(sys_get_temp_dir(), 'weather_report');
$writer = new Xlsx($spreadsheet);
$writer->save($tempFile);
// Store the file in Pimcore Assets
$assetFolder = '/report/ExcelReports'; // Change this to your actual asset folder path
$filename = $user->getId() . '_' . time() . '_' . 'weather_report.xlsx';
$assetPath = API_BASE_URL . '/' . $assetFolder . '/' . $filename;
// Create a new asset
$asset = new \Pimcore\Model\Asset();
$asset->setFilename($filename);
$asset->setData(file_get_contents($tempFile));
$asset->setParent(\Pimcore\Model\Asset\Service::createFolderByPath($assetFolder));
$asset->save();
// Remove the temporary file
unlink($tempFile);
$report->setAsset($asset);
$report->setIsHistorical(true);
$report->save();
// Return the path to the stored Excel file in Pimcore
return $this->json(['success' => true, 'data' => $assetPath]);
}
/**
* @Route("/generate-historical-report", name="api_ncm_report_generate_historical_report", methods={"POST"})
*/
public function generateHistoricalReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['hours']) ||
!isset($params['parameters']) ||
!isset($params['locations'])
) {
throw new \Exception('Missing required parameters');
}
if (empty($params['parameters'] || !is_array($params['parameters']))) {
throw new \Exception('Parameters should be non empty array');
}
if (empty($params['locations'] || !is_array($params['locations']))) {
throw new \Exception('Locations should be non empty array');
}
if ($params['to_date'] > date('Y-m-d', strtotime(Carbon::now()))) {
$daysadd = date('Y-m-d', strtotime(Carbon::now()->addDays('17')));
if ($params['to_date'] >= $daysadd) {
throw new \Exception('End date limit exceeded');
}
}
$model = isset($params['model']) ? $params['model'] : 'mix';
$redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . '-' . $params['hours'] . '-' . implode('_', $params['locations'])) . '-' . implode('_', $params['parameters']) . '-' . $model;
$data = $this->redisCache->get($redisKey);
if (!$data) {
$cities = new \Pimcore\Model\DataObject\Location\Listing();
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
$cities->load();
if ($cities->getCount() > 0) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
foreach ($cities as $city) {
$cityLocations = json_decode($city->getCoordinates(), true);
foreach ($cityLocations as $coordinates) {
$long = number_format($coordinates[1], 6, '.', '');
$lat = number_format($coordinates[0], 6, '.', '');
$params['coordinates'][] = $coordinates;
$citiesArr[$lat . '|' . $long] = $city->getName();
}
}
$result = $this->meteomaticsWeatherService->getReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $params['hours'], $model, $params['parameters'], $this->translator, $citiesArr, $params);
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
$this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
} else {
return $this->json($data);
}
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-report-detail", name="api_ncm_report_get_report_detail")
*/
public function getReportDetails(Request $request)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (
!isset($params['id'])
) {
throw new \Exception('Missing required parameters');
}
$report = Report::getById($params['id'], true);
if (!$report instanceof Report) {
throw new \Exception('no_report_found');
} else {
$asset_path = $report->getAsset()?->getPath() . $report->getAsset()?->getFileName() ? API_BASE_URL . $report->getAsset()?->getPath() . $report->getAsset()?->getFileName() : '';
$data = [
'name' => $report->getCreatedBy()?->getId(),
'email' => $report->getCreatedBy()?->getEmail(),
'jsonData' => json_decode($report->getJsonData(), true),
'asset_path' => $asset_path,
'createdOn' => $report->getCreatedOn(),
];
}
return $this->json(['success' => true, 'data' => $data]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-latest-report", name="api_ncm_report_get_latest_report")
*/
public function getLatestReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$reportType = (isset($params['report_type']) && !empty($params['report_type'])) ? $params['report_type'] : '10-day-forecast-report';
$result = $this->reportModel->getLatestReport($reportType, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/generate-manned-report", name="api_ncm_report_generate_manned_report" , methods={"POST"})
*/
public function generateMannedReport(Request $request, UserInterface $user): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$requiredParameters = [
'titleEn',
'titleAr',
'descriptionEn',
'descriptionAr',
'channels',
'report_type_id',
'fileName',
'file',
'type'
];
foreach ($requiredParameters as $param) {
if (!isset($params[$param]) || empty($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
// Throw an exception with a message that includes the missing parameters
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
}
// Check if 'type' is either 'video' or 'pdf'
if (isset($params['type']) && !in_array($params['type'], ['video', 'pdf'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans("Type must be either video or pdf")]);
}
$result = $this->reportModel->createMannedReport($request, $this->translator, $params, $user);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-automatic-reports", name="api_ncm_report_get_automatic_reports")
*/
public function getAutomaticReports(Request $request, UserInterface $user, PaginatorInterface $paginator)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (!isset($params['page']) || !isset($params['limit']) || !isset($params['lang'])) {
throw new \Exception('Missing required parameters');
}
$search = isset($params['search']) ? $params['search'] : null;
$orderKey = isset($params['orderKey']) ? $params['orderKey'] : 'createdOn';
$order = isset($params['order']) ? $params['order'] : 'desc';
$result = $this->reportModel->listAutomaticReports($params, $user, $search, $orderKey, $order, $this->translator, $paginator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/generate-automatic-report-pdf", name="api_ncm_report_generate_automatic_report_pdf")
*/
public function generateAutomaticReportPdf(Request $request, UserInterface $user)
{
try {
$result = $this->reportModel->generatePdfReport($request, $user, $this->snappy, $this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/generate-history-report-pdf", name="api_ncm_report_generate_history_report_pdf")
*/
public function generateHistoryReportPdf(Request $request, UserInterface $user)
{
try {
return $this->getEWSHistoryPDF($request, $user, 'pdf/history_report_pdf.html.twig', $this->translator, '_history_report.pdf');
} catch (\Exception $ex) {
p_r($ex->getMessage());
exit;
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
public function getEWSHistoryPDF($request, $user, $template, $translator, $report_type)
{
$params = json_decode($request->getContent(), true);
if (!isset($params['id'])) {
return $this->json(["success" => false, "message" => $translator->trans("missing_required_parameters")]);
}
$ewsId = $params['id'];
$lang = isset($params['lang']) ? $params['lang'] : "en";
$ews = \Pimcore\Model\DataObject::getById($ewsId);
if (!$ews instanceof EwsNotification) {
return $this->json(["success" => false, "message" => $translator->trans("no_report_found")]);
}
$ewsNotificationModel = new EwsNotificationModel();
$fileName = '_ews_history_report.pdf';
$reportPath = '/report/ReportPdf/' . $params['id'];
$template = 'pdf/history_report_pdf.html.twig';
$data = $ewsNotificationModel->viewNotification($params, $translator);
$parameter = [
'data' => $data,
'reportTitleEn' => "EWS Notification History",
'template' => $template,
'lang' => $lang
];
// return $this->render('pdf/automatic_report_pdf_template_copy.html.twig',$parameter);
$pdf = \App\Lib\Utility::generatePdf($parameter, $this->snappy);
// $tempFilePath = tempnam(sys_get_temp_dir(), 'image_');
// file_put_contents($tempFilePath, $pdf);
// Create a BinaryFileResponse and set headers
// $response = new BinaryFileResponse($tempFilePath);
// $response->headers->set('Content-Type', 'application/pdf');
// $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, 'image.pdf');
// Return the response
// return $responseReport;
$asset = \App\Lib\Utility::createAsset($pdf, 'Alert_History_Report_' . date('Y-m-d') . '-' . $params['id'] . '.pdf', $reportPath);
$pdfasset = '';
if ($asset instanceof Asset) {
$pdfasset = API_BASE_URL . $asset->getPath() . $asset->getFilename();
}
return $this->json(['success' => true, 'data' => $pdfasset]);
}
public function getPdfReport($request, $user, $template, $translator, $report_type)
{
$params = json_decode($request->getContent(), true);
if (!isset($params['id'])) {
return $this->json(["success" => false, "message" => $translator->trans("missing_required_parameters")]);
}
$report = Report::getById($params['id'], true);
$lang = isset($params['lang']) ? $params['lang'] : "en";
if (!$report instanceof Report) {
return $this->json(["success" => false, "message" => $translator->trans("no_report_found")]);
}
$asset = $lang == 'ar' ? $report->getAssetAr() : $report->getAsset();
if ($asset) {
$pdfasset = API_BASE_URL . $asset->getPath() . $asset->getFilename();
return $this->json(['success' => true, 'data' => $pdfasset]);
}
//$template=$report->getReportType()?->getKey() == 'MannForecastReport'?'pdf/report_pdf_template.html.twig':'pdf/automatic_report_pdf_template.html.twig';
$fileName = '_custom_weather_report.pdf';
$reportPath = '/report/ReportPdf';
if ($report->getReportType()?->getKey() == 'MannForecastReport') {
$template = 'pdf/report_pdf_template.html.twig';
} elseif ($report->getReportType()?->getKey() == 'advance-custom-weather-report') {
$template = 'pdf/advance_custom_report_pdf_template.html.twig';
// $fileName = '_advance_custom_weather_report.pdf';
$reportPath = '/report/advanceCustomReportPdf';
} else {
$template = 'pdf/automatic_report_pdf_template.html.twig';
}
$parameter = [
'data' => $report,
'reportTitleEn' => $report->getReportTitle('en'),
'reportTitleAr' => $report->getReportTitle('ar'),
'reportDescriptionEn' => $report->getDescription('en'),
'reportDescriptionAr' => $report->getDescription('ar'),
'reportDisclaimerEn' => $report->getReportDisclaimer('en'), // new
'reportDisclaimerAr' => $report->getReportDisclaimer('ar'), // new
'additionalNoteEn' => $report->getAdditionalNote('en'), // new
'additionalNoteAr' => $report->getAdditionalNote('ar'), // new
'stateOfTheSeaEn' => $report->getStateOfTheSea('en'), // new
'stateOfTheSeaAr' => $report->getStateOfTheSea('ar'), // new
'waveHeightEn' => $report->getWaveHeight('en'), // new
'waveHeightAr' => $report->getWaveHeight('ar'), // new
'surfaceWindEn' => $report->getSurfaceWind('en'), // new
'surfaceWindAr' => $report->getSurfaceWind('ar'), // new
'publishOnPdf' => $report->getPublishOnPdf() == true ? true : false, // new
'reportType' => $report->getReportType()?->getReportkey(),
'template' => $template,
'lang' => $lang
];
// return $this->render('pdf/automatic_report_pdf_template_copy.html.twig',$parameter);
$pdf = \App\Lib\Utility::generatePdf($parameter, $this->snappy);
// $tempFilePath = tempnam(sys_get_temp_dir(), 'image_');
// file_put_contents($tempFilePath, $pdf);
// Create a BinaryFileResponse and set headers
// $response = new BinaryFileResponse($tempFilePath);
// $response->headers->set('Content-Type', 'application/pdf');
// $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, 'image.pdf');
// Return the response
// return $response;
// set the asset path and title
$pdfReportName = $report->getReportType() ? $report->getReportType()->getName($lang) : $report_type;
$pdfReportName = $pdfReportName . '_' . date('d-m-Y') . '.pdf';
$reportPath = $reportPath . '/' . $report->getId();
$asset = \App\Lib\Utility::createAsset($pdf, $pdfReportName, $reportPath);
$pdfasset = '';
if ($asset instanceof Asset) {
$pdfasset = API_BASE_URL . $asset->getPath() . $asset->getFilename();
}
if ($lang == 'ar') {
$report->setAssetAr($asset);
} else {
$report->setAsset($asset);
}
$report->save();
return $this->json(['success' => true, 'data' => $pdfasset]);
}
/**
* @Route("/get-today-weather-report", name="api_ncm_report_get_today_weather_report")
*/
public function getTodayWeatherReports(Request $request, UserInterface $user, PaginatorInterface $paginator)
{
try {
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['page']) || !isset($params['limit']) || !isset($params['lang'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->getTodayWeatherReports($params, $this->translator, $paginator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/preview-advance-custom-report", name="api_ncm_report_preview_advance_custom_report" , methods={"POST"})
*/
public function previewAdvanceCustomReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$locations = (isset($params['locations']) && !empty($params['locations'])) || (isset($params['weather_stations']) && !empty($params['weather_stations']));
if (
!isset($params['from_date']) ||
!isset($params['to_date']) ||
!isset($params['parameters']) ||
!isset($locations)
) {
throw new \Exception('Missing required parameters');
}
if (empty($params['parameters'] || !is_array($params['parameters']))) {
throw new \Exception('Parameters should be non empty array');
}
if ((!isset($params['locations']) || empty($params['locations']) || !is_array($params['locations'])) && (!isset($params['weather_stations']) || empty($params['weather_stations']) || !is_array($params['weather_stations']))) {
throw new \Exception('Either locations or weather_stations should be non empty array');
}
// Set default values for new parameters
$params['isAWSReport'] = isset($params['isAWSReport']) ? $params['isAWSReport'] : false;
$params['hours'] = isset($params['hours']) ? $params['hours'] : 24;
$params['weather_stations'] = isset($params['weather_stations']) ? $params['weather_stations'] : [];
$params['locations'] = isset($params['locations']) ? $params['locations'] : [];
$model = isset($params['model']) ? $params['model'] : 'mix';
// $redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . '-' . $params['hours'] . '-' . ($params['isAWSReport'] ? 'aws_' . implode('_', $params['weather_stations']) : implode('_', $params['locations']))) . '-' . implode('_', $params['parameters']) . '-' . $model;
// $data = $this->redisCache->get($redisKey);
// if (!$data) {
$params['coordinates'] = []; // Initialize an empty array for coordinates
$result = [];
$citiesArr = [];
if ($params['isAWSReport']) {
// Handle AWS Weather Station report
$stations = new \Pimcore\Model\DataObject\WeatherStations\Listing();
if (!empty($params['weather_stations'])) {
$stations->setCondition('o_id IN (?)', [$params['weather_stations']]);
}
$stations->load();
if ($stations->getCount() > 0) {
$hashArr = [];
foreach ($stations as $station) {
$params['coordinates'][] = [$station->getlatitude(), $station->getlongitude()];
$hash = $station->getHash();
// Append the coordinates for each station
$long = number_format($station->getlongitude(), 6, '.', '');
$lat = number_format($station->getlatitude(), 6, '.', '');
$citiesArr[$hash]["en"] = $station->getName("en");
$citiesArr[$hash]["ar"] = $station->getName("ar");
$citiesArr[$hash]["lat"] = $lat;
$citiesArr[$hash]["long"] = $long;
$hashArr[] = $hash;
}
$result = $this->meteomaticsWeatherService->getWeatherStationReportData($params['from_date'], $params['to_date'], $params['parameters'], $hashArr, false, $this->translator, 'PT' . $params['hours'] . 'H', $citiesArr);
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_weather_station_found')]);
}
} else {
// Handle regular Governorate report
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
if (isset($params['locations']) && !empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
$cities->load();
if ($cities->getCount() > 0) {
foreach ($cities as $city) {
$params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
// Append the coordinates for each city
$long = number_format($city->getLongitude(), 6, '.', '');
$lat = number_format($city->getLatitude(), 6, '.', '');
$citiesArr[$lat . '|' . $long]["en"] = $city->getName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getName("ar");
}
$result = $this->meteomaticsWeatherService->getReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $params['hours'], $model, $params['parameters'], $this->translator, $citiesArr, array_merge($params, ['skip_service_cache' => true]));
} else {
return $this->json(['success' => true, 'message' => $this->translator->trans('no_city_found')]);
}
}
$response[] = $result;
$jsonResponse = ['success' => true, 'data' => $response];
// $this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
return $this->json($jsonResponse);
// } else {
// return $this->json($data);
// }
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-advance-custom-report", name="api_ncm_report_publish_advance_custom_report" , methods={"POST"})
*/
public function publishAdvanceCustomReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->publishAdvanceCustomReport($user, $params, $this->translator, $this->logger);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/archive-weather-report", name="api_ncm_report_archive_weather_report")
*/
public function archiveWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['report_id'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->archiveWeatherReport($this->translator, $user, $params['report_id']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/delete-arabian-gulf-report", name="api_ncm_report_delete_arabian_gulf_report")
*/
public function deleteArabianGulfReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['report_id'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->archiveWeatherReport($this->translator, $user, $params['report_id']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/delete-10-day-forecast-report", name="api_ncm_report_delete_10_day_forecast_report")
*/
public function delete10DayForecastReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['report_id'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->archiveWeatherReport($this->translator, $user, $params['report_id']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/delete-red-sea-report", name="api_ncm_report_delete_red_sea_report")
*/
public function deleteRedSeaReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['report_id'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->archiveWeatherReport($this->translator, $user, $params['report_id']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/delete-custom-weather-report", name="api_ncm_report_delete_custom_weather_report")
*/
public function deleteCustomWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['report_id'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->archiveWeatherReport($this->translator, $user, $params['report_id']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/delete-mashaer-weather-report", name="api_ncm_report_delete_mashaer_weather_report")
*/
public function deleteMashaerWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
if (!isset($params['report_id'])) {
throw new \Exception('Missing required parameters');
}
$result = $this->reportModel->archiveWeatherReport($this->translator, $user, $params['report_id']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-advance-custom-report", name="api_ncm_report_update_advance_custom_report" , methods={"POST"})
*/
public function updateAdvanceCustomReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->publishAdvanceCustomReport($user, $params, $this->translator, $this->logger);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-report", name="api_ncm_report_update_report", methods={"POST"})
*/
public function updateReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-arabian-gulf-report", name="api_ncm_report_update_arabian_gulf_report", methods={"POST"})
*/
public function updateArabianGulfReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-10-day-forecast-report", name="api_ncm_report_update_10_day_forecast_report", methods={"POST"})
*/
public function update10DayForecastReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-red-sea-report", name="api_ncm_report_update_red_sea_report", methods={"POST"})
*/
public function updateRedSeaReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-custom-weather-report", name="api_ncm_report_update_custom_weather_report", methods={"POST"})
*/
public function updateCustomWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/update-mashaer-weather-report", name="api_ncm_report_update_mashaer_weather_report", methods={"POST"})
*/
public function updateMashaerWeatherReport(Request $request, UserInterface $user)
{
try {
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// Perform parameter validation here
// || !isset($params['locations'])
if (!isset($params['data']) || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
return $this->json(['success' => false, 'message' => $this->translator->trans('missing_required_parameters')]);
}
if (isset($params['organizations'])) {
if (!is_array($params['organizations'])) {
throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
}
}
if (isset($params['channels'])) {
if (!is_array($params['channels']) || empty($params['channels'])) {
throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
}
if (in_array('email', $params['channels'])) {
if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
}
}
}
$result = $this->reportModel->editReport($user, $params, $this->translator, $this->logger);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-centers", name="get_centeres", methods={"POST"})
*/
public function getCenters(Request $request, UserInterface $user, PaginatorInterface $paginator): JsonResponse
{
try {
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (empty($params['governorate_id'])) {
throw new \Exception("Governate id is required");
}
$result = $this->reportModel->getCenters($params["governorate_id"], $params['lang']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/get-districts", name="get_districts", methods={"POST"})
*/
public function getDistricts(Request $request, UserInterface $user, PaginatorInterface $paginator): JsonResponse
{
try {
if (!$user) {
throw new \Exception('User is not authenticated');
}
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
if (empty($params['governorate_id'])) {
throw new \Exception("Governate id is required");
}
$result = $this->reportModel->getDistricts($params["governorate_id"], $params['lang']);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/publish-alert-forecast-report", name="publish_alert_forecast_report", methods={"POST"})
*/
public function publishAlertForecastReport(Request $request, UserInterface $user): JsonResponse
{
try {
// Validate permissions
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
// Decode the JSON request
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$requiredParameters = [
'titleEn',
'titleAr',
'descriptionEn',
'descriptionAr',
'regions',
'parameterId'
];
$missingParams = [];
foreach ($requiredParameters as $param) {
if (empty($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => $this->translator->trans("required parameters are missing in the request") . ": " . $parameterList]);
}
$validationErrors = $this->validateAlertForecastRegions($params['regions']);
if (!empty($validationErrors)) {
return $this->json([
'success' => false,
'message' => $validationErrors
]);
}
$emailChannelError = $this->validateAlertForecastEmailChannel($params);
if ($emailChannelError !== null) {
return $this->json(['success' => false, 'message' => $emailChannelError], 400);
}
$data = [];
$data['titleEn'] = $params['titleEn'];
$data['titleAr'] = $params['titleAr'];
$data['descriptionEn'] = $params['descriptionEn'];
$data['descriptionAr'] = $params['descriptionAr'];
$data['regions'] = $params['regions'];
$data['lang'] = $params['lang'];
$data['user'] = $user;
$data['channels'] = $params['channels'] ?? [];
$data['parameterId'] = $params['parameterId'];
$data['xCaption'] = $params['xCaption'] ?? null;
$data['emails'] = $params['emails'] ?? [];
$data['user_group_ids'] = $params['user_group_ids'] ?? [];
$data['footerTitleEn'] = $params['footerTitleEn'] ?? '';
$data['footerTitleAr'] = $params['footerTitleAr'] ?? '';
$data['footerDescriptionEn'] = $params['footerDescriptionEn'] ?? '';
$data['footerDescriptionAr'] = $params['footerDescriptionAr'] ?? '';
// Step 3: Call the model function to handle report creation
$result = $this->reportModel->publishAlertForecastReport($data, $user, $this->translator);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
}
}
/**
* @Route("/update-alert-forecast-report", name="update_alert_forecast_report", methods={"POST"})
*/
public function updateAlertForecastReport(Request $request, UserInterface $user): JsonResponse
{
try {
// Validate permissions
$permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
if (isset($permissions['code']) && $permissions['code'] === 401) {
return $this->json($permissions, 401);
} elseif ($permissions['success'] === false) {
return $this->json($permissions);
}
if (!$user) {
throw new \Exception('User is not authenticated');
}
// Decode the JSON request
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$requiredParameters = [
'id',
'titleEn',
'titleAr',
'descriptionEn',
'descriptionAr',
'regions',
'parameterId'
];
$missingParams = [];
foreach ($requiredParameters as $param) {
if (empty($params[$param])) {
$missingParams[] = $param;
}
}
if (!empty($missingParams)) {
$parameterList = implode(", ", $missingParams);
return $this->json(['success' => false, 'message' => $this->translator->trans("required parameters are missing in the request") . ": " . $parameterList]);
}
$validationErrors = $this->validateAlertForecastRegions($params['regions']);
if (!empty($validationErrors)) {
return $this->json([
'success' => false,
'message' => $validationErrors
]);
}
$emailChannelError = $this->validateAlertForecastEmailChannel($params);
if ($emailChannelError !== null) {
return $this->json(['success' => false, 'message' => $emailChannelError], 400);
}
$data = [];
$data['titleEn'] = $params['titleEn'];
$data['titleAr'] = $params['titleAr'];
$data['descriptionEn'] = $params['descriptionEn'];
$data['descriptionAr'] = $params['descriptionAr'];
$data['regions'] = $params['regions'];
$data['lang'] = $params['lang'];
$data['user'] = $user;
$data['channels'] = $params['channels'] ?? [];
$data['id'] = $params['id'];
$data['xCaption'] = $params['xCaption'] ?? null;
$data['parameterId'] = $params['parameterId'];
$data['emails'] = $params['emails'] ?? [];
$data['user_group_ids'] = $params['user_group_ids'] ?? [];
$data['footerTitleEn'] = $params['footerTitleEn'] ?? '';
$data['footerTitleAr'] = $params['footerTitleAr'] ?? '';
$data['footerDescriptionEn'] = $params['footerDescriptionEn'] ?? '';
$data['footerDescriptionAr'] = $params['footerDescriptionAr'] ?? '';
// Step 3: Call the model function to handle report creation
$result = $this->reportModel->publishAlertForecastReport($data, $user, $this->translator);
return $this->json($this->finalizeModerationPublishResult($result, $user));
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
}
}
private function validateAlertForecastEmailChannel(array $params): ?string
{
$channels = $params['channels'] ?? [];
if (!is_array($channels) || !in_array('email', $channels, true)) {
return null;
}
$hasEmails = isset($params['emails']) && is_array($params['emails']) && $params['emails'] !== [];
$hasUserGroups = isset($params['user_group_ids']) && is_array($params['user_group_ids']) && $params['user_group_ids'] !== [];
if (!$hasEmails && !$hasUserGroups) {
return $this->translator->trans('alert_forecast_report_email_recipients_required');
}
return null;
}
private function validateAlertForecastRegions(array $regions): array
{
$errors = [];
if (!is_array($regions) || $regions === []) {
$errors[] = $this->translator->trans('regions is required');
return $errors;
}
foreach ($regions as $regionIndex => $regionData) {
$regionNumber = $regionIndex + 1;
if (!is_array($regionData)) {
$errors[] = $this->translator->trans("Invalid region data at region index $regionNumber");
continue;
}
if (empty($regionData['regionId'])) {
$errors[] = $this->translator->trans("regionId is required at region index $regionNumber");
}
if (empty($regionData['governorates']) || !is_array($regionData['governorates'])) {
$errors[] = $this->translator->trans("governorates are required at region index $regionNumber");
continue;
}
foreach ($regionData['governorates'] as $governorateIndex => $governorateData) {
$governorateErrors = $this->validateGovernorateData(
is_array($governorateData) ? $governorateData : [],
$regionNumber,
$governorateIndex + 1
);
$errors = array_merge($errors, $governorateErrors);
}
}
return $errors;
}
private function validateGovernorateData(array $governorateData, int $regionIndex, int $governorateIndex): array
{
$errors = [];
$location = "region index $regionIndex, governorate index $governorateIndex";
$requiredFields = [
'governateIds' => 'governateIds',
'categoryId' => 'categoryId',
'startDate' => 'startDate',
'endDate' => 'endDate',
'timePeriod' => 'timePeriod',
];
foreach ($requiredFields as $field => $localizedName) {
if (empty($governorateData[$field])) {
$errors[] = $this->translator->trans("$localizedName is required at $location");
}
}
if (isset($governorateData['governateIds']) && !empty($governorateData['governateIds'])) {
$governorates = explode(',', (string) $governorateData['governateIds']);
if (count(array_filter(array_map('trim', $governorates))) < 1) {
$errors[] = $this->translator->trans("At least one governateId is required at $location");
}
}
foreach (['centerIds', 'districtIds', 'otherLocationIds'] as $optionalField) {
if (!isset($governorateData[$optionalField]) || $governorateData[$optionalField] === '' || $governorateData[$optionalField] === null) {
continue;
}
$ids = array_filter(array_map('trim', explode(',', (string) $governorateData[$optionalField])));
if ($ids === []) {
$errors[] = $this->translator->trans("Invalid $optionalField at $location");
}
}
if (!isset($governorateData['categoryId']) || empty($governorateData['categoryId'])) {
$errors[] = $this->translator->trans("category ID is required at $location");
}
if (isset($governorateData['startDate']) && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $governorateData['startDate'])) {
$errors[] = $this->translator->trans("Invalid startDate format at $location");
}
if (isset($governorateData['endDate']) && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $governorateData['endDate'])) {
$errors[] = $this->translator->trans("Invalid endDate format at $location");
}
if ($this->isTruthyAdditionalCondition($governorateData['additionalCondition'] ?? false)) {
$additionalRequiredFields = [
'additionalConditionStartDate' => 'additionalConditionStartDate',
'additionalConditionEndDate' => 'additionalConditionEndDate',
];
foreach ($additionalRequiredFields as $field => $localizedName) {
if (empty($governorateData[$field])) {
$errors[] = $this->translator->trans("$localizedName is required at $location when additionalCondition is true");
}
}
$hasConditionText = !empty($governorateData['additionalParameterConditionEn'])
|| !empty($governorateData['additionalParameterConditionAr'])
|| !empty($governorateData['additionalConditionText']);
if (!$hasConditionText) {
$errors[] = $this->translator->trans("additionalParameterConditionEn or additionalParameterConditionAr is required at $location when additionalCondition is true");
}
foreach (['additionalConditionStartDate', 'additionalConditionEndDate'] as $dateField) {
if (
isset($governorateData[$dateField])
&& $governorateData[$dateField] !== ''
&& !preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $governorateData[$dateField])
) {
$errors[] = $this->translator->trans("Invalid $dateField format at $location");
}
}
}
return $errors;
}
private function isTruthyAdditionalCondition(mixed $value): bool
{
return filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === true;
}
/**
* @Route(
* "/alert-forecast-report-parameters",
* name="alert_forecast_report_parameters",
* methods={"POST"}
* )
*/
public function getAlertForecastParameters(Request $request, UserInterface $user)
{
try {
// Validate permissions
// $permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
// if (isset($permissions['code']) && $permissions['code'] === 401) {
// return $this->json($permissions, 401);
// } elseif ($permissions['success'] === false) {
// return $this->json($permissions);
// }
if (!$user) {
throw new \Exception('User is not authenticated');
}
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$result = $this->reportModel->getAlertForecastParameters($this->translator);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
}
}
/**
* @Route( "/alert-forecast-report-risk-categories", name="alert_forecast_report_risk_categories", methods={"POST"} )
*/
public function getAlertForecastRiskCategories(Request $request, UserInterface $user)
{
try {
if (!$user) {
throw new \Exception('User is not authenticated');
}
// Decode params BEFORE using them
$params = json_decode($request->getContent(), true) ?? [];
// Now safe to access $params["lang"]
$this->translator->setLocale($params["lang"] ?? DEFAULT_LOCALE);
$result = $this->reportModel->getAlertForecastRiskCategories($params);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json([
'success' => false,
'message' => $this->translator->trans(USER_ERROR_MESSAGE)
]);
}
}
private function finalizeModerationPublishResult(array $result, UserInterface $user): array
{
if (empty($result['notificationType'])) {
return $result;
}
$reportId = (int) ($result['reportId'] ?? $result['data'] ?? 0);
if (empty($result['success'])) {
$this->logger->warning(sprintf(
'Report moderation admin email skipped for report #%d: publish result was not successful',
$reportId
));
} elseif (!$user instanceof Customer) {
$this->logger->error(sprintf(
'Report moderation admin email skipped for report #%d: authenticated user is not a Customer instance',
$reportId
));
} else {
$this->reportModerationEmailService->notifyAdminReportSubmitted(
$reportId,
$result['reportTitleEn'] ?? '',
$result['reportTitleAr'] ?? '',
$user,
$result['notificationType'] === 'resubmitted'
);
}
unset($result['notificationType'], $result['reportTitleEn'], $result['reportTitleAr']);
return $result;
}
}