<?php
namespace App\Controller;
use Carbon\Carbon;
use Knp\Snappy\Pdf;
use Knp\Snappy\Image;
use Pimcore\Model\Asset;
use App\Service\RedisCache;
use App\Model\ReportLogModel;
use App\Service\EmailService;
use App\Service\ReportService;
use DateTime;
use Pimcore\Log\ApplicationLogger;
use App\Model\EwsNotificationModel;
use App\Service\NotificationService;
use Pimcore\Model\DataObject\Report;
use App\Service\MeteomaticApiService;
use App\Model\WeatherForecastCityModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use App\Service\CustomNotificationService;
use App\Service\MeteomaticsWeatherService;
use Pimcore\Controller\FrontendController;
use Knp\Component\Pager\PaginatorInterface;
use App\Service\PublicUserPermissionService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Pimcore\Model\DataObject\ReportWeatherSymbols;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class PublicApiController extends FrontendController
{
private $ewsNotificationModel;
private $reportModel;
public function __construct(
private TokenStorageInterface $tokenStorageInterface,
private JWTTokenManagerInterface $jwtManager,
private PublicUserPermissionService $publicUserPermissionService,
protected TranslatorInterface $translator,
private ApplicationLogger $logger,
private MeteomaticApiService $meteomaticApiService,
private \Doctrine\DBAL\Connection $connection,
private RedisCache $redisCache,
private MeteomaticsWeatherService $meteomaticsWeatherService,
private Pdf $snappy,
private CustomNotificationService $customNotificationService,
private ReportService $reportService,
private NotificationService $notificationService,
private Image $snappyImage,
private EmailService $emailService
) {
// header('Content-Type: application/json; charset=UTF-8');
// header("Access-Control-Allow-Origin: *");
$this->meteomaticApiService = $meteomaticApiService;
$this->publicUserPermissionService = $publicUserPermissionService;
$this->ewsNotificationModel = new EwsNotificationModel();
$this->reportModel = new ReportLogModel();
}
/**
* @Route("/api/public/{startdate}/{enddate}/{resolution}/{parameter}/{coordinate}/{format}", name="api_public_route_query", methods={"GET"})
*/
public function publicRouteQueryData(Request $request): JsonResponse
{
try {
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$startDate = $request->get('startdate');
$endDate = $request->get('enddate');
$resolution = $request->get('resolution');
$parameter = $request->get('parameter');
$coordinate = $request->get('coordinate');
$format = $request->get('format');
// Optional Parameter
$source = $request->get('source');
$onInvalid = $request->get('on_invalid');
$model = $request->get('model');
if (!$startDate) {
throw new \InvalidArgumentException("Missing mandatory parameter: start date");
}
if (!$endDate) {
throw new \InvalidArgumentException("Missing mandatory parameter: end date");
}
if (!$resolution) {
throw new \InvalidArgumentException("Missing mandatory parameter: resolution");
}
if (!$parameter) {
throw new \InvalidArgumentException("Missing mandatory parameter: parameters");
}
if (!$coordinate) {
throw new \InvalidArgumentException("Missing mandatory parameter: coordinate");
}
if (!$format) {
throw new \InvalidArgumentException("Missing mandatory parameter: format");
}
$startDate = new DateTime($startDate);
$endDate = new DateTime($endDate);
$user = $response['user'];
$parametersArray = explode(',', $parameter);
// Varify user allowed permissions
// $reslult = $this->publicUserPermissionService->publicUserPermissionCheck($user, $parametersArray, $this->translator);
// if ($reslult['success'] !== true) {
// return $this->json($reslult);
// }
$response = $this->meteomaticApiService->publicRouteQuery(
$startDate,
$endDate,
$resolution,
$parametersArray,
$coordinate,
$format,
$model,
$source,
$onInvalid
);
// For demonstration purposes, we will just return a JSON response
return $this->json($response);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/get-report-detail", name="public_get_report_detail")
*/
public function getReportDetails(Request $request)
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$user = $response['user'];
// $params = json_decode($request->getContent(), true);
$requestUri = $request->getRequestUri();
// Extract the last segment from the URL
$segments = explode('/', trim($requestUri, '/'));
$action = end($segments);
$action = str_replace("-", "_", $action);
$params[] = $action;
// $reslult = $this->publicUserPermissionService->publicUserPermissionCheck($user, $params, $this->translator);
// if ($reslult['success'] !== true) {
// return $this->json($reslult);
// }
$latestReport = Report::getList([
"limit" => 1,
"orderKey" => "createdOn",
"order" => "desc"
]);
if ($latestReport->getCount() <= 0) {
throw new \Exception('no_latest_report_found');
} else {
$data = [];
foreach ($latestReport as $report) {
$data = [
'name' => $report->getCreatedBy()?->getName(),
'email' => $report->getCreatedBy()?->getEmail(),
'jsonData' => json_decode($report->getJsonData(), true),
'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("/api/public/ews-analytics", methods={"POST"})
*/
public function ewsAnalyticsAction(Request $request): JsonResponse
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
$lang = ($request->headers->has('lang')) ? $request->headers->get('lang') : "en";
$result = $this->ewsNotificationModel->ewsAnalytics($params, $this->connection, $lang);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/generate-report", methods={"POST"})
*/
public function generateReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
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');
}
$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\City\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) {
$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->getCityName("en");
$citiesArr[$lat . '|' . $long]["ar"] = $city->getCityName("ar");
}
$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("/api/public/update-report", methods={"POST"})
*/
public function updateReport(Request $request)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$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->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("/api/public/get-city-list", name="public-city-listing")
*/
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->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("/api/public/list-report", name="public-report-listing")
*/
public function getReportListAction(Request $request, PaginatorInterface $paginator)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$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 params: page or limit');
}
$report_type = isset($params['report_type']) ? $params['report_type'] : null;
$lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
$isPublicReports = isset($params['publicReports']) ? $params['publicReports'] : false; // sending this flag from public portal to get all reports accordong to our needs
$page = $params['page'];
$limit = $params['limit'];
$result = $this->reportModel->reportList($params, $page, $limit, $this->translator, $paginator, $report_type, $user, $lang, $isPublicReports);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/generate-report-pdf", name="public-report-pdf")
*/
public function generateReportPdf(Request $request)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
return $this->getPdfReport($request, $user, 'pdf/report_pdf_template.html.twig', $this->translator, '_manned_forecast_report.pdf');
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/get-report-types", name="public-report-types-listing")
*/
public function getReportTypes(Request $request)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$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("/api/public/get-weather-params-list", name="public-weather-params-listing")
*/
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("/api/public/generate-excel", name="public-generate-excel")
*/
public function generateExcelReport(Request $request)
{
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$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 = ['City', 'Lat', 'Lon', 'Date']; // Initialize headers with common columns
// Extract parameter names and add them to headers
foreach ($parameters as $parameter) {
$headers[] = $parameter['parameter'];
}
// Add headers to the worksheet
foreach ($headers as $index => $header) {
$sheet->setCellValueByColumnAndRow($index + 1, 1, $header);
}
// 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++;
}
}
// 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("/api/public/generate-historical-report", methods={"POST"})
*/
public function generateHistoricalReport(Request $request): JsonResponse
{
try {
$response = [];
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
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("/api/public/get-latest-report", name="public-get-latest-report")
*/
public function getLatestReport(Request $request)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$params = json_decode($request->getContent(), true);
$reportType = (isset($params['report_type']) && !empty($params['report_type'])) ? $params['report_type'] : 'ten-day-forecast-report';
$result = $this->reportModel->getLatestReport($reportType, $this->translator, false);
return $this->json($result);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/get-automatic-reports", name="public_get_automatic_reports")
*/
public function getAutomaticReports(Request $request, PaginatorInterface $paginator)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$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->listAutomaticPublicReports($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("/api/public/generate-automatic-report-pdf", name="public-automatic-report-pdf")
*/
public function generateAutomaticReportPdf(Request $request)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$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()]);
}
}
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
'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;
$asset = \App\Lib\Utility::createAsset($pdf, $user->getId() . '_' . time() . $report_type, $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("/api/public/get-today-weather-report", name="public_get_today_weather_report")
*/
public function getTodayWeatherReports(Request $request, PaginatorInterface $paginator)
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$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("/api/public/get-report-weather-symbols", name="public_get_report_weather_symbols")
*/
public function getReportWeatherSymbols(Request $request): JsonResponse
{
try {
$permissions = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($permissions['success'] !== true) {
return $this->json($permissions);
}
$user = $permissions['user'];
$data = [];
$weatherSymbols = new ReportWeatherSymbols\Listing();
foreach ($weatherSymbols as $weatherSymbol) {
if ($weatherSymbol) {
$weatherSymbolNames = $weatherSymbol->getWeatherSymbols();
$weatherSymbolIcons = $weatherSymbol->getWeatherIcons();
if ($weatherSymbolNames) {
foreach ($weatherSymbolNames as $weatherSymbolName) {
$response['symbols'][] = [
'nameEn' => $weatherSymbolName->getSymbolName('en'),
'nameAr' => $weatherSymbolName->getSymbolName('ar'),
];
}
}
if ($weatherSymbolIcons) {
foreach ($weatherSymbolIcons as $weatherSymbolIcon) {
$response['icons'][] = [
'iconValue' => $weatherSymbolIcon->getIconValue(),
];
}
}
}
$data[] = $response;
}
return $this->json(['success' => true, 'data' => $data]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
}
}
/**
* @Route("/api/public/get-forecast-cities", methods={"POST"})
*/
public function getForecastCities(Request $request): Response
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$forecastCityModel = new WeatherForecastCityModel();
$cities = $forecastCityModel->getWeatherForecastCities();
return $this->json(['success' => true, 'data' => $cities]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/get-regions-bbox", name="get-regions-bbox")
*/
public function getRegionsBbox(Request $request)
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$data = REGIONS_BBOX;
return $this->json(['success' => true, 'data' => $data]);
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/get-station-data", methods={"GET"})
*/
public function getWeatherStationDataAction(Request $request)
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$typeName = $request->get('type_name');
$parameters = $request->get('parameters');
$dateTime = $request->get('date_time');
$bBox = $request->get('b_box');
if (!$typeName) {
throw new \InvalidArgumentException("Missing mandatory parameter: type_name");
}
if (!$parameters) {
throw new \InvalidArgumentException("Missing mandatory parameter: parameters");
}
if (!$dateTime) {
throw new \InvalidArgumentException("Missing mandatory parameter: date_time");
}
if (!$bBox) {
throw new \InvalidArgumentException("Missing mandatory parameter: b_box");
}
$result = $this->meteomaticsWeatherService->getWeatherStationData($typeName, $parameters, $dateTime, $bBox);
return $result;
} catch (\Exception $ex) {
return $this->json(['success' => false, 'message' => $ex->getMessage()]);
}
}
/**
* @Route("/api/public/daily-forecast", methods={"POST"})
*/
public function dailyForecast(Request $request): JsonResponse
{
try {
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// check user credentials and expiry
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$requiredParameters = ['coordinates', 'from_date', 'to_date', 'model'];
foreach ($requiredParameters as $param) {
if (!isset($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)]);
}
$result = $this->meteomaticsWeatherService->getForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $params['hours'], $params['model'], $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("/api/public/weather/{path}", name="api_meteomatics", requirements={"path"=".+"}, methods={"GET"})
*/
public function getDynamicWeatherData(Request $request, string $path): Response
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$user = $response['user'];
$queryParams = $request->query->all();
$weatherData = $this->meteomaticApiService->getDynamicWeatherData($path, $queryParams, $user);
return $weatherData;
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage());
return $this->json(['success' => false, 'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
}
}
/**
* @Route("/api/public/create-manned-alert-subscription", methods={"POST"})
*/
public function mannedAlertSubscription(Request $request): JsonResponse
{
try {
$response = $this->publicUserPermissionService->isAuthorized($request, $this->translator);
if ($response['success'] !== true) {
return $this->json($response);
}
$user = $response['user'];
$params = json_decode($request->getContent(), true);
$this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
// $requiredParameters = ['region_id', 'governorate_id', 'alert_type_id'];
// 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)]);
// }
$result = $this->customNotificationService->mannedAlertSubscription($user, $params, $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)]);
}
}
}