<?php
namespace App\Model;
use Carbon\Carbon;
use App\Lib\Utility;
use App\Service\EmailService;
use Pimcore\Model\DataObject;
use App\Service\UserPermission;
use Pimcore\Model\DataObject\Report;
use Pimcore\Model\DataObject\Customer;
use Pimcore\Model\DataObject\Location;
use Symfony\Component\Process\Process;
use Pimcore\Model\DataObject\ReportLog;
use Pimcore\Model\DataObject\ReportType;
use Pimcore\Model\DataObject\Organization;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Pimcore\Model\Asset;
class ReportLogModel
{
public function create(string $reportKey, array $param, array $response)
{
try {
// Define an array to store missing parameters
$missingParameters = [];
// Define an array of required parameters
$requiredParameters = [
'type_of_report',
'lon',
'lat',
'start_date',
'end_date'
];
// Check for missing required parameters
foreach ($requiredParameters as $parameter) {
if (!isset($param[$parameter])) {
$missingParameters[] = $parameter;
}
}
// If there are missing parameters, return them
if (!empty($missingParameters)) {
throw new \Exception("Missing parameters " . implode(",", $missingParameters));
}
if (!$response) {
throw new \Exception("Response data not available");
}
$reportLog = \Pimcore\Model\DataObject\ReportLog::getByReportKey($reportKey, true);
if (!$reportLog) {
$reportLog = new ReportLog();
$reportLog->setKey($reportKey);
$reportLog->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("ReportLog"));
}
$reportLog->setTypeOfReport($param['type_of_report']);
$reportLog->setLon($param['lon']);
$reportLog->setLat($param['lat']);
$reportLog->setStartDate(Carbon::parse(new \DateTime($param['start_date'])));
$reportLog->setEndDate(Carbon::parse(new \Datetime($param['end_date'])));
$reportLog->setIsPublished(true);
$reportLog->setPublished(true);
$reportLog->setReportKey($reportKey);
$reportLog->setResponseData(json_encode($response));
$reportLog->save();
return ["success" => true, "data" => $reportLog->getReportKey()];
} catch (\Exception $ex) {
return ["success" => false, "message" => $ex->getMessage()];
}
}
public function getReportLog($param)
{
$key = $this->createKey($param);
$reportLog = \Pimcore\Model\DataObject\ReportLog::getByReportKey($key, true);
return $reportLog;
}
public function deleteReport($param)
{
$reportLog = $this->getReportLog($param);
if ($reportLog) {
$reportLog->delete();
return true;
}
return false;
}
public function createKey($param)
{
return md5(implode(",", $param));
}
public function editReport($user, $params, $translator, $logger)
{
try {
$cityNames = '';
if (!empty($params['locations'])) {
// if governorate is true then get the cities from governorate else get the cities from city
if (isset($params['is_governate']) && $params['is_governate']) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
if (!empty($params['locations'])) {
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
}
} else {
$cities = new \Pimcore\Model\DataObject\City\Listing();
if (!empty($params['locations'])) {
$cities->setCondition('o_id IN (?)', [$params['locations']]);
}
}
$cities->load();
$locations = new \Pimcore\Model\DataObject\Location\Listing();
$locations->setCondition('o_id IN (?)', [$params['locations']]);
$locations->load();
if ($cities->getCount() > 0) {
foreach ($cities as $city) {
// if governorate is true then get the cities from governorate else get the cities from city
if ($params['is_governate']) {
$nameEN = $city->getName('en');
$nameAR = $city->getName('ar');
} else {
$nameEN = $city->getCityName('en');
$nameAR = $city->getCityName('ar');
}
$cityNames .= !empty($nameEN) ? $nameEN . ',' : '';
$cityNames .= !empty($nameAR) ? $nameAR . ',' : '';
}
} elseif ($locations->getCount() > 0) {
foreach ($locations as $location) {
$cityNames .= !empty($location->getName()) ? $location->getName() . ',' : '';
}
} else {
return ["success" => false, "message" => "invalid_location"];
}
// Remove the trailing comma
$cityNames = rtrim($cityNames, ',');
}
if (isset($params['report_id'])) {
$report = Report::getById($params['report_id'], true);
if (!$report instanceof Report) {
return ["success" => false, "message" => "invalid_report_id"];
}
} else {
$report = new Report();
$report->setKey(\Pimcore\Model\Element\Service::getValidKey($user->getEmail() . time(), 'object'));
$report->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Report/Report"));
}
$reportType = '';
$report->setCreatedBy($user);
$report->setCreatedOn(Carbon::now());
$report->setStartDate(Carbon::parse(new \DateTime($params['start_date'])));
$report->setEndDate(Carbon::parse(new \Datetime($params['end_date'])));
$report->setSearchData($cityNames);
$report->setLang($params['lang']);
// $report->setEmail($user->getEmail());
$report->setJsonData(json_encode($params['data']));
if (isset($params['report_title'])) {
$report->setReportTitle($params['report_title'], "en");
}
if (isset($params['report_title_ar'])) {
$report->setReportTitle($params['report_title_ar'], "ar");
}
if (isset($params['surface_wind'])) {
$report->setSurfaceWind($params['surface_wind'], "en");
}
if (isset($params['wave_height'])) {
$report->setWaveHeight($params['wave_height'], "en");
}
if (isset($params['state_of_the_sea'])) {
$report->setStateOfTheSea($params['state_of_the_sea'], "en");
}
if (isset($params['surface_wind_ar'])) {
$report->setSurfaceWind($params['surface_wind_ar'], "ar");
}
if (isset($params['wave_height_ar'])) {
$report->setWaveHeight($params['wave_height_ar'], "ar");
}
if (isset($params['state_of_the_sea_ar'])) {
$report->setStateOfTheSea($params['state_of_the_sea_ar'], "ar");
}
if (isset($params['reportDisclaimerEn'])) {
$report->setReportDisclaimer($params['reportDisclaimerEn'], "en");
}
if (isset($params['reportDisclaimerAr'])) {
$report->setReportDisclaimer($params['reportDisclaimerAr'], "ar");
}
if (isset($params['additionalNoteEn'])) {
$report->setAdditionalNote($params['additionalNoteEn'], "en");
}
if (isset($params['additionalNoteAr'])) {
$report->setAdditionalNote($params['additionalNoteAr'], "ar");
}
if (isset($params['publishOnPdf'])) {
$report->setPublishOnPdf($params['publishOnPdf'] == true ? true : false);
}
if (isset($params['is_governate']) && $params['is_governate']) {
$report->setIsGovernorates(true);
}
if (!empty($params['xCaption'])) {
$report->setTwitterDescription($params['xCaption']);
}
if (isset($params['report_type_id'])) {
$reportType = ReportType::getById($params['report_type_id'], true);
if ($reportType instanceof ReportType) {
$report->setReportType($reportType);
// if ($reportType->getKey() != 'CustomWeatherReport' || $reportType->getKey() != 'MashaerWeatherReport') {
// $report->setForPublicPortal(true);
// $report->setForAjwaaPortal(true);
// }
if ($reportType->getReportKey() != 'arabian-gulf-report' || $reportType->getKey() != 'red-sea-report') {
$report->setForPublicPortal(true);
$report->setForAjwaaPortal(true);
}
}
}
if (!empty($params['organizations'])) {
$selectedOrganizations = [];
if ($params['organizations'][0] == 0) {
$organizations = new Organization\Listing();
if ($organizations->count() > 0) {
foreach ($organizations as $organization) {
if ($organization) {
$selectedOrganizations[] = $organization;
}
}
$report->setOrganization($selectedOrganizations);
}
} else {
foreach ($params['organizations'] as $organization) {
$organizationObject = Organization::getById($organization, true);
if ($organizationObject) {
$selectedOrganizations[] = $organizationObject;
}
}
$report->setOrganization($selectedOrganizations);
}
}
$emails = "";
if (!empty($params['channels'])) {
$channels = ['public_portal', 'ajwaa_portal', 'email', 'twitter', 'sms'];
foreach ($params['channels'] as $channel) {
if ($channel == 'public_portal') {
$report->setForPublicPortal(true);
} elseif ($channel == 'ajwaa_portal') {
$report->setForAjwaaPortal(true);
if (isset($params['send_email'])) {
$report->setSendEmail(true);
}
} elseif ($channel == 'email') {
$report->setForEmailChannel(true);
$emails .= implode(",", $params['emails']);
} elseif ($channel == 'twitter') {
$report->setForTwitterChannel(true);
}
}
}
$emailArray = [];
if (isset($params['user_group_ids']) && !empty($params['user_group_ids'])) {
$userGroupIds = ($params['user_group_ids']);
foreach ($userGroupIds as $userGroupId) {
if ($userGroupId) {
$userGroup = \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupId, true);
if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
if (isset($currentUser->email)) {
$report->setForEmailChannel(true);
$emailArray[] = $currentUser->email;
}
}
}
}
}
}
if (!empty($emailArray)) {
if (!empty($emails)) {
$emails .= ',' . implode(',', $emailArray);
} else {
$emails = implode(',', $emailArray);
}
}
$report->setEmails($emails);
$report->setPublished(true);
//schedule report
if (isset($params['is_schedule']) && $params['is_schedule'] && isset($params['schedule_date'])) {
$report->setIsSchedule($params['is_schedule']);
// dd($params['schedule_date']);
// dd(Carbon::parse($params['schedule_date'], 'Asia/Riyadh'));
//exit;
$report->setScheduleDate(Carbon::parse($params['schedule_date'])->subHours(5));
$report->setPublished(false);
} else {
$report->setPublished(true);
}
// just to show title in public portal as description
$report->setShowPublicDescription(isset($params['show_public_description']) && $params['show_public_description'] === true);
// delete the existing pdf if report is updated
if (isset($params['report_id'])) {
$pdfEn = $report->getAsset();
$pdfAr = $report->getAssetAr();
if ($pdfEn instanceof Asset) {
$pdfEn->delete();
}
if ($pdfAr instanceof Asset) {
$pdfAr->delete();
}
}
$report->save();
//$phpPath = 'D:\laragon\bin\php\php-8.1.10-Win32-vs16-x64\php.exe'; // Adjust to the actual PHP path on your system
$consolePath = 'bin\console'; // Use backslashes for Windows paths
$commandArguments = ['bin/console', 'app:today-weather-pdf'];
if (!empty($reportType)) {
if ($reportType->getKey() != 'CustomWeatherReport' || $reportType->getKey() != 'MashaerWeatherReport') {
$process = new Process($commandArguments);
$process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
try {
$process->mustRun();
$logger->info("Today Weather command executed successfully: " . $process->getOutput());
// p_r("Today Weather command executed successfully: " . $process->getOutput());exit;
$result['success'] = true;
$result['message'] = $process->getOutput();
} catch (ProcessFailedException $exception) {
$logger->error("Today Weather command failed: " . $exception->getMessage());
// p_r("Today Weather command failed: " . $exception->getMessage());exit;
$result['success'] = false;
$result['message'] = "Failed to execute notification command.";
}
}
}
if (isset($params['report_id'])) {
return ["success" => true, "message" => $translator->trans("report_updated_successfully"), "data" => $report->getId()];
} else {
return ["success" => true, "message" => $translator->trans("report_published_successfully"), "data" => $report->getId()];
}
} catch (\Exception $ex) {
return ["success" => false, "message" => $ex->getMessage()];
}
}
public function reportList($params, $page, $limit, $translator, $paginator, $report_type, $user, $lang, $is_public = true): array
{
$result = [];
try {
// Load blog listing
$reportList = new DataObject\Report\Listing();
$search = isset($params['search']) ? $params['search'] : '';
if ($report_type == 'mannforecast') {
if (!empty($search)) {
$db = \Pimcore\Db::get();
$selectedLocalities = $db->fetchAllAssociative(
"SELECT oo_id FROM `object_query_customer` WHERE (`name` LIKE ? OR `email` LIKE ?)",
["%" . $search . "%", "%" . $search . "%"]
);
$ooIds = array_column($selectedLocalities, 'oo_id');
$reportList->setCondition(
"((reportType__id IS NULL) AND (isHistorical IN (?)) AND (createdBy__id IN (?) OR searchData LIKE ?))",
[
[false, null],
$ooIds,
'%' . $search . '%',
]
);
} else {
$reportList->setCondition(
"((reportType__id IS NULL) AND (isHistorical IN (?)))",
[
[false, null]
]
);
}
} elseif ($report_type == 'historical') {
if (!empty($search)) {
$db = \Pimcore\Db::get();
$selectedLocalities = $db->fetchAllAssociative(
"SELECT oo_id FROM `object_query_customer` WHERE (`name` LIKE ? OR `email` LIKE ?)",
["%" . $search . "%", "%" . $search . "%"]
);
$ooIds = array_column($selectedLocalities, 'oo_id');
$reportList->setCondition(
"((reportType__id IS NULL) AND (isHistorical = ?) AND (createdBy__id = ?) AND (searchData LIKE ?) )",
[
true,
$user->getId(),
'%' . $search . '%'
]
);
} else {
$reportList->setCondition("((reportType__id IS NULL) AND (createdBy__id = ?) AND (isHistorical = ?))", [$user->getId(), true]);
}
} elseif ($report_type == 'advamced_report_and_custom_report') {
// Define the report keys you want to check
$reportKeys = ['advance-custom-weather-report', 'custom-weather-report'];
$reportTypeIds = [];
// Loop through each report key and fetch the report type if it exists
foreach ($reportKeys as $key) {
$reportType = ReportType::getByReportKey($key, true);
if ($reportType instanceof ReportType) {
$reportTypeIds[] = $reportType->getId();
}
}
// If there are any valid report type IDs, set the condition with them
if (!empty($reportTypeIds)) {
$reportList->setCondition(
"(reportType__id IN (?))",
[$reportTypeIds]
);
}
} elseif ($is_public) {
// this if logic is totally build for public portal to get all reports according to the report type key here we are sening the array in report_type variable except other report type whic is string
// Define the report keys you want to check
foreach ($report_type as $key) {
$reportType = ReportType::getByReportKey($key, true);
if ($reportType instanceof ReportType) {
$reportTypeIds[] = $reportType->getId();
}
}
// If there are any valid report type IDs, set the condition with them
if (!empty($reportTypeIds)) {
$reportList->setCondition(
"(reportType__id IN (?)) AND forPublicPortal = ?",
[$reportTypeIds, true]
);
} else {
$reportList->setCondition(
"forPublicPortal = ?",
[true]
);
}
} else {
if (!empty($search)) {
$db = \Pimcore\Db::get();
$selectedLocalities = $db->fetchAllAssociative(
"SELECT oo_id FROM `object_query_customer` WHERE (`name` LIKE ? OR `email` LIKE ?)",
["%" . $search . "%", "%" . $search . "%"]
);
$selectedReportTypes = new ReportType\Listing();
$selectedReportTypes->setLocale($lang);
$selectedReportTypes->setCondition(
"(name LIKE ?)",
[
'%' . $search . '%'
]
);
$selectedReportTypes->load();
$report_types = [];
foreach ($selectedReportTypes as $reportType) {
array_push($report_types, $reportType->getId());
}
// p_r($selectedReportTypes);exit;
$organization = $user->getOrganization()?->getId();
$ooIds = array_column($selectedLocalities, 'oo_id');
$reportList->setLocale($params['lang']);
$reportList->addConditionParam(
"((reportType__id IS NOT NULL) AND (createdBy__id IN (?) OR reportType__id IN (?) OR reportTitle LIKE ?))",
[
$ooIds,
$report_types,
'%' . $search . '%'
]
);
if ($is_public) {
$reportList->addConditionParam(
"(forPublicPortal = ?)",
[
true
]
);
}
} else {
$organization = $user->getOrganization()?->getId();
$reportList->addConditionParam("reportType__id IS NOT NULL");
if ($is_public) {
$reportList->addConditionParam(
"(forPublicPortal = ?)",
[
true
]
);
}
}
}
$sortOrderCreatedAt = $params['sortByCreated'] ?? 'desc';
$reportList->setOrderKey('createdOn')
->setOrder($sortOrderCreatedAt);
if (count($reportList) > 0) {
// set pagination
$paginate = $paginator->paginate(
$reportList,
$page,
$limit
);
return $this->getReportListData($paginate);
}
return ["success" => false, "message" => $translator->trans("no_report_is_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function listReportsByType($params, $translator, $paginator): array
{
$page = $params['page'];
$limit = $params['limit'];
$lang = $params['lang'] ?? 'en';
$search = isset($params['search']) ? $params['search'] : '';
$db = \Pimcore\Db::get();
// Define the report keys you want to check
$reportTypeIds = [];
// Loop through each report key and fetch the report type if it exists
foreach ($params['allowedReportTypes'] as $key) {
$reportType = ReportType::getByReportKey($key, true);
if ($reportType instanceof ReportType) {
$reportTypeIds[] = $reportType->getId();
}
}
// If no allowed report types resolved, return empty result to avoid IN (NULL)
if (empty($reportTypeIds)) {
$paginate = $paginator->paginate([], $page, $limit);
return ["success" => true, "data" => [], "paginationVariables" => $paginate->getPaginationData()];
}
// Resolve class ids
$class = new \Pimcore\Model\DataObject\ClassDefinition();
$reportClassId = $class->getDao()->getIdByName('Report');
$reportTypeClassId = $class->getDao()->getIdByName('ReportType');
// Build query with proper joins for localized and relation fields
$select = $db->createQueryBuilder();
$select->select('report.oo_id')
->from('object_' . $reportClassId, 'report')
->where('report.reportType__id IS NOT NULL AND o_published =1')
->andWhere('report.reportType__id IN (:reportTypeIds)')
->setParameter('reportTypeIds', $reportTypeIds, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
// Title search (localized)
if (!empty($search)) {
$select->leftJoin('report', 'object_localized_query_' . $reportClassId . '_' . $lang, 'rq', 'rq.ooo_id = report.oo_id');
$select->andWhere('rq.reportTitle LIKE ' . $db->quote('%' . $search . '%'));
}
// Sorting
$sortBy = $params['orderKey'] ?? ($params['sortBy'] ?? 'createdOn');
$sortOrder = strtoupper($params['order'] ?? ($params['sortByCreated'] ?? 'desc')) === 'ASC' ? 'ASC' : 'DESC';
switch ($sortBy) {
case 'reportType':
$select->leftJoin('report', 'object_localized_query_' . $reportTypeClassId . '_' . $lang, 'rtq', 'rtq.ooo_id = report.reportType__id');
$select->addSelect('rtq.name AS reportType_name');
$select->orderBy('reportType_name', $sortOrder);
break;
case 'title':
$select->leftJoin('report', 'object_localized_query_' . $reportClassId . '_' . $lang, 'rq_sort', 'rq_sort.ooo_id = report.oo_id');
$select->addSelect('rq_sort.reportTitle AS localized_title');
$select->orderBy('localized_title', $sortOrder);
break;
case 'email':
$select->leftJoin('report', 'object_query_customer', 'cbq', 'cbq.oo_id = report.createdBy__id');
$select->addSelect('cbq.email AS createdBy_email');
$select->orderBy('createdBy_email', $sortOrder);
break;
case 'createdOn':
default:
$select->orderBy('report.createdOn', $sortOrder);
break;
}
// Avoid duplicates
$select->groupBy('report.oo_id');
$paginate = $paginator->paginate($select, $page, $limit);
return $this->getReportTypeListData($params['decodedJwtToken'], $params['userPermission'], $paginate, $translator);
}
public function listAutomaticReports($params, $user, $search, $orderKey, $order, $translator, $paginator)
{
$result = [];
try {
$organization = $user->getOrganization();
if (!$organization instanceof Organization) {
return ["success" => false, "message" => $translator->trans("no_organization_is_available_to_this_user")];
}
$organizationId = $user->getOrganization()?->getId();
$reportList = new DataObject\Report\Listing();
if (isset($params['report_type_id'])) {
$reportList->addConditionParam("(reportType__id = ?) AND (forAjwaaPortal = ?) AND (organization IS NULL OR organization LIKE ?)", [$params['report_type_id'], true, '%' . $organizationId . '%']);
} else {
$reportList->addConditionParam("(reportType__id IS NOT NULL) AND (forAjwaaPortal = ?) AND (organization IS NULL OR organization LIKE ?)", [true, '%' . $organizationId . '%']);
}
if ($search) {
$reportList->setLocale($params['lang']);
$reportList->addConditionParam(
"reportTitle LIKE ?",
['%' . $search . '%']
);
}
if (isset($params['startDate']) && isset($params['endDate']) && !empty($params['startDate']) && !empty($params['endDate'])) {
$startDate = new \DateTime($params['startDate']);
$endDate = new \DateTime($params['endDate']);
// Ensure the dates are in the correct format
$startDateStr = strtotime($startDate->format('Y-m-d H:i:s'));
$endDateStr = strtotime($endDate->format('Y-m-d') . ' 23:59:59');
$reportList->addConditionParam(
"(createdOn >= ? AND createdOn <= ?)",
[$startDateStr, $endDateStr]
);
}
$reportList->setOrderKey($orderKey)
->setOrder($order);
if (count($reportList) > 0) {
// set pagination
$paginate = $paginator->paginate(
$reportList,
$params['page'],
$params['limit']
);
return $this->getReportListData($paginate);
}
return ["success" => false, "message" => $translator->trans("no_report_is_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
public function listAutomaticPublicReports($params, $user, $search, $orderKey, $order, $translator, $paginator)
{
$result = [];
try {
$organization = $user->getOrganization();
if (!$organization instanceof Organization) {
return ["success" => false, "message" => $translator->trans("no_organization_is_available_to_this_user")];
}
$organizationId = $user->getOrganization()?->getId();
$reportList = new DataObject\Report\Listing();
if (isset($params['report_type_id'])) {
$reportList->addConditionParam("(reportType__id = ?) AND (forAjwaaPortal = ?)", [$params['report_type_id'], true]);
} else {
$reportList->addConditionParam("(reportType__id IS NOT NULL) AND (forAjwaaPortal = ?)", [true]);
}
if ($search) {
$reportList->setLocale($params['lang']);
$reportList->addConditionParam(
"reportTitle LIKE ?",
['%' . $search . '%']
);
}
if (isset($params['startDate']) && isset($params['endDate']) && !empty($params['startDate']) && !empty($params['endDate'])) {
$startDate = new \DateTime($params['startDate']);
$endDate = new \DateTime($params['endDate']);
// Ensure the dates are in the correct format
$startDateStr = strtotime($startDate->format('Y-m-d H:i:s'));
$endDateStr = strtotime($endDate->format('Y-m-d') . ' 23:59:59');
$reportList->addConditionParam(
"(createdOn >= ? AND createdOn <= ?)",
[$startDateStr, $endDateStr]
);
}
$reportList->setOrderKey($orderKey)
->setOrder($order);
if (count($reportList) > 0) {
// set pagination
$paginate = $paginator->paginate(
$reportList,
$params['page'],
$params['limit']
);
return $this->getReportListData($paginate);
}
return ["success" => false, "message" => $translator->trans("no_report_is_available")];
} catch (\Exception $ex) {
throw new \Exception($ex->getMessage());
}
return $result;
}
/**
* Get Latest MannForecastReport
*/
public function getLatestReport($reportType, $translator, $isPublic = true)
{
$mannforecastReportType = ReportType::getByReportKey($reportType, true);
if (!$mannforecastReportType) {
return ["success" => false, "message" => $translator->trans("report_type_not_created")];
}
$mannforecastReport = new Report\Listing();
$mannforecastReport->addConditionParam(
"reportType__id = ?",
[$mannforecastReportType->getId()]
);
if (!$isPublic) {
$mannforecastReport->addConditionParam(
"(forPublicPortal = ?)",
[
true
]
);
}
$mannforecastReport->setOrderKey('createdOn');
$mannforecastReport->setOrder('desc');
$latestReport = $mannforecastReport->current();
if (!$latestReport) {
return ["success" => false, "message" => $translator->trans("no_latest_report_found")];
} else {
$data = [];
$data = [
'id' => $latestReport->getId(),
'name' => $latestReport->getCreatedBy()?->getName(),
'email' => $latestReport->getCreatedBy()?->getEmail(),
'jsonData' => json_decode($latestReport->getJsonData(), true),
'createdOn' => $latestReport->getCreatedOn(),
'reportTitle' => $latestReport->getReportTitle("en"),
'stateOfTheSea' => $latestReport->getStateOfTheSea("en"),
'waveHeight' => $latestReport->getWaveHeight("en"),
'surfaceWind' => $latestReport->getSurfaceWind("en"),
'reportTitleAr' => $latestReport->getReportTitle("ar"),
'stateOfTheSeaAr' => $latestReport->getStateOfTheSea("ar"),
'waveHeightAr' => $latestReport->getWaveHeight("ar"),
'surfaceWindAr' => $latestReport->getSurfaceWind("ar"),
'showTenDayDescription' => $latestReport->getShowPublicDescription(),
'isGovernorates' => $latestReport->getIsGovernorates() == true ? true : false
];
return ['success' => true, 'data' => $data];
}
}
public function getReportListData($paginate)
{
$reportListData = [];
foreach ($paginate as $key => $reportlist) {
$asset_path = $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() ? API_BASE_URL . $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() : '';
$asset_path_ar = $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() ? API_BASE_URL . $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() : '';
$reportTitleEn = $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" ? "10-Day Forecast Report" : $reportlist->getReportTitle('en');
$reportTitleAr = $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" ? "توقعات لمدة 10 أيام" : $reportlist->getReportTitle('ar');
if ($reportlist->getReportType()?->getReportKey() == "advance-custom-weather-report") {
if ($reportlist->getIsMannedReport()) {
$isMannedReport = true;
} else {
$isMannedReport = false;
}
} else {
$isMannedReport = null;
}
$reportListData[$key] = [
'id' => $reportlist->getId(),
'createdBy' => $reportlist->getCreatedBy()?->getName(),
'email' => $reportlist->getCreatedBy()?->getEmail(),
'createdOn' => $reportlist->getCreatedOn(),
'startDate' => $reportlist->getStartDate('Y-m-d H:i:s'),
'endDate' => $reportlist->getEndDate('Y-m-d H:i:s'),
'report' => json_decode($reportlist->getJsonData(), true),
'reportTypeEn' => $reportlist->getReportType()?->getName('en'),
'reportTypeAr' => $reportlist->getReportType()?->getName('ar'),
'reportTypeId' => $reportlist->getReportType()?->getId(),
'reportTypeKey' => $reportlist->getReportType()?->getReportKey(),
'reportTitleEn' => $reportTitleEn,
'reportTitleAr' => $reportTitleAr,
'reportDescriptionAr' => $reportlist->getDescription('ar'),
'reportDescriptionEn' => $reportlist->getDescription('en'),
'isMannedAdvanceCustomReport' => $isMannedReport,
'stateOfTheSeaEn' => $reportlist->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $reportlist->getStateOfTheSea('ar'),
'surfaceWindEn' => $reportlist->getSurfaceWind('en'),
'surfaceWindAr' => $reportlist->getSurfaceWind('ar'),
'waveHeightEn' => $reportlist->getWaveHeight('en'),
'waveHeightAr' => $reportlist->getWaveHeight('ar'),
'asset' => $asset_path,
'assetAr' => $asset_path_ar,
'isAWSReport' => $reportlist->getIsAWSReport(),
];
// 15-Day Forecast Report
if ($reportlist->getReportType()?->getReportKey() == "15-day-forecast-report") {
$reportListData[$key]['reportDescriptionEn'] = $reportlist->getReportTitle('en');
$reportListData[$key]['reportDescriptionAr'] = $reportlist->getReportTitle('ar');
}
}
return ["success" => true, "data" => $reportListData, "paginationVariables" => $paginate->getPaginationData()];
}
public function getReportTypeListData($decodedJwtToken, $userPermission, $paginate, $translator)
{
$reportListData = [];
foreach ($paginate as $key => $row) {
$reportlist = \Pimcore\Model\DataObject\Report::getById($row['oo_id'], true);
if (!$reportlist instanceof \Pimcore\Model\DataObject\Report) {
continue;
}
$asset_path = $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() ? API_BASE_URL . $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() : '';
$asset_path_ar = $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() ? API_BASE_URL . $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() : '';
$reportTitleEn = $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" ? "10-Day Forecast Report" : $reportlist->getReportTitle('en');
$reportTitleAr = $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" ? "توقعات لمدة 10 أيام" : $reportlist->getReportTitle('ar');
if ($reportlist->getReportType()?->getReportKey() == "advance-custom-weather-report") {
if ($reportlist->getIsMannedReport()) {
$isMannedReport = true;
} else {
$isMannedReport = false;
}
} else {
$isMannedReport = null;
}
$reportListData[$key] = [
'id' => $reportlist->getId(),
'createdBy' => $reportlist->getCreatedBy()?->getName(),
'email' => $reportlist->getCreatedBy()?->getEmail(),
'createdOn' => $reportlist->getCreatedOn(),
'startDate' => $reportlist->getStartDate('Y-m-d H:i:s'),
'endDate' => $reportlist->getEndDate('Y-m-d H:i:s'),
'report' => json_decode($reportlist->getJsonData(), true),
'reportTypeEn' => $reportlist->getReportType()?->getName('en'),
'reportTypeAr' => $reportlist->getReportType()?->getName('ar'),
'reportTypeId' => $reportlist->getReportType()?->getId(),
'reportTypeKey' => $reportlist->getReportType()?->getReportKey(),
'reportTitleEn' => $reportTitleEn,
'reportTitleAr' => $reportTitleAr,
'reportDescriptionAr' => $reportlist->getDescription('ar'),
'reportDescriptionEn' => $reportlist->getDescription('en'),
'isMannedAdvanceCustomReport' => $isMannedReport,
'stateOfTheSeaEn' => $reportlist->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $reportlist->getStateOfTheSea('ar'),
'surfaceWindEn' => $reportlist->getSurfaceWind('en'),
'surfaceWindAr' => $reportlist->getSurfaceWind('ar'),
'waveHeightEn' => $reportlist->getWaveHeight('en'),
'waveHeightAr' => $reportlist->getWaveHeight('ar'),
'asset' => $asset_path,
'assetAr' => $asset_path_ar,
'isAWSReport' => $reportlist->getIsAWSReport(),
'fileType' => $reportlist->getFileType() == 'video' ? 'Video' : 'pdf',
];
// Initialize edit and delete flags
$editFlag = false;
$deleteFlag = false;
// Get the current report's type key
$currentReportTypeKey = $reportlist->getReportType()?->getReportKey();
// Map report type keys to permission names
$permissionMapping = [
'red-sea-report' => 'red_sea_report',
'arabian-gulf-report' => 'arabian_gulf_report',
'10-day-forecast-report' => '10_day_forecast_report',
'custom-weather-report' => 'custom_weather_report',
'advance-custom-weather-report' => 'advance_custom_weather_report',
'mashaer-weather-report' => 'mashaer_weather_report'
];
// Check permissions only for the current report type
if ($currentReportTypeKey && isset($permissionMapping[$currentReportTypeKey])) {
$permissionName = $permissionMapping[$currentReportTypeKey];
$permissionStatus = $userPermission->getUserPermissions($decodedJwtToken, $translator);
// Check edit permission
if (isset($permissionStatus['grants']["update_$permissionName"]) && $permissionStatus['grants']["update_$permissionName"] === true) {
$editFlag = true;
}
// Check delete permission
if (isset($permissionStatus['grants']["delete_$permissionName"]) && $permissionStatus['grants']["delete_$permissionName"] === true) {
$deleteFlag = true;
}
}
$reportListData[$key]['canEdit'] = $editFlag;
$reportListData[$key]['canDelete'] = $deleteFlag;
// 15-Day Forecast Report
if ($reportlist->getReportType()?->getReportKey() == "15-day-forecast-report") {
$reportListData[$key]['reportDescriptionEn'] = $reportlist->getReportTitle('en');
$reportListData[$key]['reportDescriptionAr'] = $reportlist->getReportTitle('ar');
}
}
return ["success" => true, "data" => $reportListData, "paginationVariables" => $paginate->getPaginationData()];
}
public function getTodayWeatherReports($params, $translator, $paginator)
{
$lang = $param['lang'] ?? "en";
$reports = new \Pimcore\Model\DataObject\ReportTodayWeather\Listing();
$reports->setLocale($lang);
if (isset($params['search'])) {
$reports->setCondition(
"(title LIKE ?)",
[
'%' . $params['search'] . '%'
]
);
}
$sortOrderCreatedAt = $params['sortByCreated'] ?? "desc";
$reports->setOrderKey("o_id")
->setOrder($sortOrderCreatedAt);
if (count($reports) > 0) {
// set pagination
$paginate = $paginator->paginate(
$reports,
$params['page'],
$params['limit']
);
$data = [];
foreach ($paginate as $report) {
$data[] = [
'reportNameEn' => $report->getTitle("en"),
'reportNameAr' => $report->getTitle("ar"),
'reportPathEn' => $report->getPdfReport() ? API_BASE_URL . $report->getPdfReport()->getPath() . $report->getPdfReport()->getFilename() : '',
'reportPathAr' => $report->getPdfReportAr() ? API_BASE_URL . $report->getPdfReportAr()->getPath() . $report->getPdfReportAr()->getFilename() : '',
'generatedAt' => $report->getGeneratedAt()
];
}
return ['success' => true, 'data' => $data, "paginationVariables" => $paginate->getPaginationData()];
}
return ["success" => false, "message" => $translator->trans("no_report_is_available")];
}
public function getTodayWeatherReportData($request, $translator)
{
$reportData = [];
$todaysDate = new \Carbon\Carbon(); // Assuming you are using Carbon\Carbon for $todaysDate
$todaysDate->setTime(0, 0, 0); // Set the time to midnight for comparison
$todaysDateString = $todaysDate->format('Y-m-d');
// get 15 day forecast report
$mannforecast_report = new Report\Listing();
$mannforecast_report_type = ReportType::getByKey('MannForecastReport', true);
if (!$mannforecast_report_type) {
return ["success" => false, "message" => $translator->trans('mannforecast_report_type_not_created')];
}
$mannforecast_report->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?)))",
[$mannforecast_report_type->getId(), [false, null]]
);
$mannforecast_report->setOrderKey("o_creationDate");
$mannforecast_report->setOrder("desc");
$mann_forecast_report = $mannforecast_report->current();
if (!$mann_forecast_report) {
return ["success" => false, "message" => $translator->trans('mannforecast_report_not_created')];
}
// get 15 red sea report
$redsea_report = new Report\Listing();
$redsea_report_type = ReportType::getByKey('RedSeaReport', true);
if (!$redsea_report_type) {
return ["success" => false, "message" => $translator->trans('redsea_report_type_not_created')];
}
$redsea_report->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?)))",
[$redsea_report_type->getId(), [false, null]]
);
$redsea_report->setOrderKey("o_creationDate");
$redsea_report->setOrder("desc");
$red_sea_report = $redsea_report->current();
if (!$red_sea_report) {
return ["success" => false, "message" => $translator->trans('redsea_report_not_created')];
}
// get 15 arabiangulf_report
$arabiangulf_report = new Report\Listing();
$arabiangulf_report_type = ReportType::getByKey('ArabianGulfReport', true);
if (!$arabiangulf_report_type) {
return ["success" => false, "message" => $translator->trans('arabiangulf_report_type_not_created')];
}
$arabiangulf_report->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?)))",
[$arabiangulf_report_type->getId(), [false, null]]
);
$arabiangulf_report->setOrderKey("o_creationDate");
$arabiangulf_report->setOrder("desc");
$arabian_gulf_report = $arabiangulf_report->current();
if (!$arabian_gulf_report) {
return ["success" => false, "message" => $translator->trans('arabiangulf_report_not_created')];
}
$red_sea_list = [
// 'reportTitleEn' => $red_sea_report->getReportTitle('en'),
// 'reportTitleAr' => $red_sea_report->getReportTitle('ar'),
'surfaceWindEn' => $red_sea_report->getSurfaceWind('en'),
'surfaceWindAr' => $red_sea_report->getSurfaceWind('ar'),
'waveHeightEn' => $red_sea_report->getWaveHeight('en'),
'waveHeightAr' => $red_sea_report->getWaveHeight('ar'),
'stateOfTheSeaEn' => $red_sea_report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $red_sea_report->getStateOfTheSea('ar'),
];
$json_data = [];
foreach (json_decode($mann_forecast_report->getJsonData()) as $data) {
$cityEn = $data->cityEn;
if (!isset($json_data[$cityEn])) {
$json_data[$cityEn] = [];
}
foreach ($data->parameters as $parameter) {
$first_date = $parameter->dates[0];
$json_data[$cityEn][] = [
'cityAr' => $data->cityAr,
'lat' => $data->lat,
'lon' => $data->lon,
'parameter' => $parameter->parameter,
'date' => $first_date->date,
'value' => $first_date->value
];
}
}
$mannforeacast_list = [
'reportTitleEn' => $mann_forecast_report->getReportTitle(),
'reportTitleAr' => $mann_forecast_report->getReportTitle(),
'jsonData' => $json_data,
'createdOn' => $mann_forecast_report->getCreatedOn(),
// 'lang' => $mann_forecast_report->getLang()
];
$arabian_gulf_list = [
// 'reportTitleEn' => $arabian_gulf_report->getReportTitle('en'),
// 'reportTitleAr' => $arabian_gulf_report->getReportTitle('ar'),
'surfaceWindEn' => $arabian_gulf_report->getSurfaceWind('en'),
'surfaceWindAr' => $arabian_gulf_report->getSurfaceWind('ar'),
'waveHeightEn' => $arabian_gulf_report->getWaveHeight('en'),
'waveHeightAr' => $arabian_gulf_report->getWaveHeight('ar'),
'stateOfTheSeaEn' => $arabian_gulf_report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $arabian_gulf_report->getStateOfTheSea('ar'),
];
$reportData = [
'redSea' => $red_sea_list,
'fifteenDay' => $mannforeacast_list,
'arabianGulf' => $arabian_gulf_list
];
return ['success' => true, 'data' => $reportData];
}
public function getAllWeatherReportData($request, $translator)
{
$json_data = [];
$report_listing_data = [
'reports' => [
'customWeather' => [],
'mashaerWeather' => [],
'todayWeather' => [],
'redSea' => [],
'arabianGulf' => [],
],
];
$todaysDate = new \Carbon\Carbon(); // Assuming you are using Carbon\Carbon for $todaysDate
$todaysDate->setTime(0, 0, 0); // Set the time to midnight for comparison
$todaysDateString = $todaysDate->format('Y-m-d');
// get Custom Weather report
$customWeatherReport = new Report\Listing();
$customWeatherReport_type = ReportType::getByKey('CustomWeatherReport', true);
if (!is_null($customWeatherReport_type)) {
$customWeatherReport->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
[$customWeatherReport_type->getId(), [false, null], $todaysDateString]
);
$customWeatherReport->setOrderKey("o_creationDate");
$customWeatherReport->setOrder("desc");
$custom_Weather_Report = $customWeatherReport->current();
$json_data = [];
if (!empty($custom_Weather_Report) and !is_null($custom_Weather_Report)) {
if (!empty($custom_Weather_Report->getJsonData()) and !is_null($custom_Weather_Report->getJsonData())) {
foreach (json_decode($custom_Weather_Report->getJsonData()) as $data) {
$cityEn = $data->cityEn;
if (!isset($json_data[$cityEn])) {
$json_data[$cityEn] = [];
}
$json_data[$cityEn] = [
'cityEn' => $data->cityEn,
'cityAr' => $data->cityAr,
'lat' => $data->lat,
'lon' => $data->lon,
'data' => $data->parameters
];
}
}
$report_listing_data['reports']['customWeather'] = [
'id' => $custom_Weather_Report->getId(),
'reportTitleEn' => $custom_Weather_Report->getReportTitle('en'),
'reportTitleAr' => $custom_Weather_Report->getReportTitle('ar'),
'jsonData' => $json_data,
'createdOn' => $custom_Weather_Report->getCreatedOn()->format('Y-m-d H:i:s')
];
}
}
// get Mashaer Weather report
$mashaerWeatherReport = new Report\Listing();
$mashaerWeatherReport_type = ReportType::getByKey('MashaerWeatherReport', true);
if (!is_null($mashaerWeatherReport_type)) {
$mashaerWeatherReport->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
[$mashaerWeatherReport_type->getId(), [false, null], $todaysDateString]
);
$mashaerWeatherReport->setOrderKey("o_creationDate");
$mashaerWeatherReport->setOrder("desc");
$mashaer_Weather_Report = $mashaerWeatherReport->current();
$json_data = [];
if (!empty($mashaer_Weather_Report) and !is_null($mashaer_Weather_Report)) {
if (!empty($mashaer_Weather_Report->getJsonData()) and !is_null($mashaer_Weather_Report->getJsonData())) {
foreach (json_decode($mashaer_Weather_Report->getJsonData()) as $data) {
$cityEn = $data->cityEn;
if (!isset($json_data[$cityEn])) {
$json_data[$cityEn] = [];
}
$json_data[$cityEn] = [
'cityEn' => $data->cityEn,
'cityAr' => $data->cityAr,
'lat' => $data->lat,
'lon' => $data->lon,
'data' => $data->parameters
];
}
}
$report_listing_data['reports']['mashaerWeather'] = [
'id' => $mashaer_Weather_Report->getId(),
'reportTitleEn' => $mashaer_Weather_Report->getReportTitle('en'),
'reportTitleAr' => $mashaer_Weather_Report->getReportTitle('ar'),
'jsonData' => $json_data,
'createdOn' => $mashaer_Weather_Report->getCreatedOn()->format('Y-m-d H:i:s')
];
}
}
// get 15 red sea report
$redsea_report = new Report\Listing();
$redsea_report_type = ReportType::getByKey('RedSeaReport', true);
if (!is_null($redsea_report_type)) {
$redsea_report->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
[$redsea_report_type->getId(), [false, null], $todaysDate]
);
$redsea_report->setOrderKey("o_creationDate");
$redsea_report->setOrder("desc");
$redsea_report->setLimit(10);
$red_sea_report = $redsea_report->current();
$json_data = [];
if (!empty($red_sea_report) and !is_null($red_sea_report)) {
if (!empty($red_sea_report->getJsonData()) and !is_null($red_sea_report->getJsonData())) {
foreach (json_decode($red_sea_report->getJsonData()) as $data) {
$cityEn = $data->cityEn;
if (!isset($json_data[$cityEn])) {
$json_data[$cityEn] = [];
}
$json_data[$cityEn] = [
'cityEn' => $data->cityEn,
'cityAr' => $data->cityAr,
'lat' => $data->lat,
'lon' => $data->lon,
'data' => $data->parameters
];
}
}
$report_listing_data['reports']['redSea'] = [
'id' => $red_sea_report->getId(),
'surfaceWindEn' => $red_sea_report->getSurfaceWind('en'),
'surfaceWindAr' => $red_sea_report->getSurfaceWind('ar'),
'waveHeightEn' => $red_sea_report->getWaveHeight('en'),
'waveHeightAr' => $red_sea_report->getWaveHeight('ar'),
'stateOfTheSeaEn' => $red_sea_report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $red_sea_report->getStateOfTheSea('ar'),
'reportTitleEn' => $red_sea_report->getReportTitle('en'),
'reportTitleAr' => $red_sea_report->getReportTitle('ar'),
'jsonData' => $json_data,
'createdOn' => $red_sea_report->getCreatedOn()->format('Y-m-d H:i:s')
];
}
}
// get 15 arabiangulf_report
$arabiangulf_report = new Report\Listing();
$arabiangulf_report_type = ReportType::getByKey('ArabianGulfReport', true);
if (!is_null($arabiangulf_report_type)) {
$arabiangulf_report->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
[$arabiangulf_report_type->getId(), [false, null], $todaysDate]
);
$arabiangulf_report->setOrderKey("o_creationDate");
$arabiangulf_report->setOrder("desc");
$arabian_gulf_report = $arabiangulf_report->current();
$json_data = [];
if (!empty($arabian_gulf_report) and !is_null($arabian_gulf_report)) {
if (!empty($arabian_gulf_report->getJsonData()) and !is_null($arabian_gulf_report->getJsonData())) {
foreach (json_decode($arabian_gulf_report->getJsonData()) as $data) {
$cityEn = $data->cityEn;
if (!isset($json_data[$cityEn])) {
$json_data[$cityEn] = [];
}
$json_data[$cityEn] = [
'cityEn' => $data->cityEn,
'cityAr' => $data->cityAr,
'lat' => $data->lat,
'lon' => $data->lon,
'data' => $data->parameters
];
}
}
$report_listing_data['reports']['arabianGulf'] = [
'id' => $arabian_gulf_report->getId(),
'surfaceWindEn' => $arabian_gulf_report->getSurfaceWind('en'),
'surfaceWindAr' => $arabian_gulf_report->getSurfaceWind('ar'),
'waveHeightEn' => $arabian_gulf_report->getWaveHeight('en'),
'waveHeightAr' => $arabian_gulf_report->getWaveHeight('ar'),
'stateOfTheSeaEn' => $arabian_gulf_report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $arabian_gulf_report->getStateOfTheSea('ar'),
'reportTitleEn' => $arabian_gulf_report->getReportTitle('en'),
'reportTitleAr' => $arabian_gulf_report->getReportTitle('ar'),
'jsonData' => $json_data,
'createdOn' => $arabian_gulf_report->getCreatedOn()->format('Y-m-d H:i:s')
];
}
}
// get 15 day forecast report'
$mannforecast_report = new Report\Listing();
$mannforecast_report_type = ReportType::getByKey('MannForecastReport', true);
if (!is_null($mannforecast_report_type)) {
$mannforecast_report->setCondition(
"((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
[$mannforecast_report_type->getId(), [false, null], $todaysDateString]
);
$mannforecast_report->setOrderKey("o_creationDate");
$mannforecast_report->setOrder("desc");
$mann_forecast_report = $mannforecast_report->current();
$json_data = [];
if (!empty($mann_forecast_report) and !is_null($mann_forecast_report)) {
foreach (json_decode($mann_forecast_report->getJsonData()) as $data) {
$cityEn = $data->cityEn;
if (!isset($json_data[$cityEn])) {
$json_data[$cityEn] = [];
}
foreach ($data->parameters as $parameter) {
$first_date = $parameter->dates[0];
$json_data[$cityEn][] = [
'cityAr' => $data->cityAr,
'lat' => $data->lat,
'lon' => $data->lon,
'parameter' => $parameter->parameter,
'date' => $first_date->date,
'value' => $first_date->value
];
}
}
$report_listing_data['reports']['todayWeather']['todayWeatherData'] = [
'id' => $mann_forecast_report->getId(),
'reportTitleEn' => $mann_forecast_report->getReportTitle('en'),
'reportTitleAr' => $mann_forecast_report->getReportTitle('ar'),
'jsonData' => $json_data,
'createdOn' => $mann_forecast_report->getCreatedOn()->format('Y-m-d H:i:s')
];
if ($red_sea_report) {
$report_listing_data['reports']['todayWeather']['redSeaData'] = [
'surfaceWindEn' => $red_sea_report->getSurfaceWind('en'),
'surfaceWindAr' => $red_sea_report->getSurfaceWind('ar'),
'waveHeightEn' => $red_sea_report->getWaveHeight('en'),
'waveHeightAr' => $red_sea_report->getWaveHeight('ar'),
'stateOfTheSeaEn' => $red_sea_report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $red_sea_report->getStateOfTheSea('ar'),
'reportTitleEn' => $red_sea_report->getReportTitle('en'),
'reportTitleAr' => $red_sea_report->getReportTitle('ar'),
];
}
if ($arabian_gulf_report) {
$report_listing_data['reports']['todayWeather']['arabianGulfData'] = [
'surfaceWindEn' => $arabian_gulf_report->getSurfaceWind('en'),
'surfaceWindAr' => $arabian_gulf_report->getSurfaceWind('ar'),
'waveHeightEn' => $arabian_gulf_report->getWaveHeight('en'),
'waveHeightAr' => $arabian_gulf_report->getWaveHeight('ar'),
'stateOfTheSeaEn' => $arabian_gulf_report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $arabian_gulf_report->getStateOfTheSea('ar'),
'reportTitleEn' => $arabian_gulf_report->getReportTitle('en'),
'reportTitleAr' => $arabian_gulf_report->getReportTitle('ar'),
];
}
}
}
return ['success' => true, 'data' => $report_listing_data];
}
public function createMannedReport($request, $translator, $params, $user)
{
try {
$reportType = ReportType::getById($params['report_type_id'], true);
if (!$reportType instanceof ReportType) {
return ["success" => true, "message" => $translator->trans("report_type_does_not_exists")];
}
$report = new Report();
$report->setPublished(true);
$report->setParent(DataObject\Service::createFolderByPath('/Report/Report/' . $reportType->getReportKey() . '/'));
$report->setKey($params['titleEn'] . '-' . uniqid());
$report->setReportType($reportType);
$report->setIsMannedReport(true);
$report->setCreatedBy($user);
$report->setCreatedOn(Carbon::now());
$report->setReportTitle($params['titleEn'], 'en');
$report->setReportTitle($params['titleAr'], 'ar');
$report->setDescription($params['descriptionEn'], 'en');
$report->setDescription($params['descriptionAr'], 'ar');
$report->setLang($params['lang']);
if (!empty($params['file'])) {
// Set the filename from the input
$filename = $params['fileName'];
// Check if the file type is video or pdf, and if so, append a unique ID
if ($params['type'] == 'video' || $params['type'] == 'pdf') {
// Append a unique ID before the extension (to ensure uniqueness)
$filename = pathinfo($filename, PATHINFO_FILENAME) . '_' . uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION);
}
$asset = $this->createAsset($params['file'], $filename, $params['type']);
if ($asset) {
$report->setAsset($asset);
$report->setFileType($params['type']);
}
}
if (isset($params['organizations']) && !empty($params['organizations'])) {
$selectedOrganizations = [];
if ($params['organizations'][0] == 0) {
// $organizations = new Organization\Listing();
// if ($organizations->count() > 0) {
// foreach ($organizations as $organization) {
// if ($organization) {
// $selectedOrganizations[] = $organization;
// }
// }
// $report->setOrganization($selectedOrganizations);
// }
} else {
foreach ($params['organizations'] as $organization) {
$organizationObject = Organization::getById($organization, true);
if ($organizationObject) {
$selectedOrganizations[] = $organizationObject;
}
}
$report->setOrganization($selectedOrganizations);
}
}
$emails = "";
if (!empty($params['channels'])) {
$channels = ['public_portal', 'ajwaa_portal', 'email', 'twitter', 'sms'];
foreach ($params['channels'] as $channel) {
if ($channel == 'public_portal') {
$report->setForPublicPortal(true);
} elseif ($channel == 'ajwaa_portal') {
$report->setForAjwaaPortal(true);
if (isset($params['send_email'])) {
$report->setSendEmail(true);
}
} elseif ($channel == 'email') {
$report->setForEmailChannel(true);
$emails .= implode(",", $params['emails']);
} elseif ($channel == 'twitter') {
$report->setForTwitterChannel(true);
}
}
}
$emailArray = [];
if (isset($params['user_group_ids']) && !empty($params['user_group_ids'])) {
$userGroupIds = ($params['user_group_ids']);
foreach ($userGroupIds as $userGroupId) {
if ($userGroupId) {
$userGroup = \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupId, true);
if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
if (isset($currentUser->email)) {
$report->setForEmailChannel(true);
$emailArray[] = $currentUser->email;
}
}
}
}
}
}
if (!empty($emailArray)) {
if (!empty($emails)) {
$emails .= ',' . implode(',', $emailArray);
} else {
$emails = implode(',', $emailArray);
}
}
$report->setEmails($emails);
$report->save();
return ["success" => true, "message" => $translator->trans("report_generated_successfully"), "report_id" => $report->getId()];
} catch (\Exception $ex) {
return ["success" => false, "message" => $ex->getMessage()];
}
}
public function createAsset($fileData, $filename, $type = null)
{
// Validate the file data
if (preg_match('/^data:(image\/(png|jpe?g)|application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel)|video\/(mp4|webm|x-msvideo|quicktime|x-matroska|x-flv|x-ms-wmv|mpeg|3gpp));base64,/', $fileData) !== 1) {
return false; // Invalid file data or MIME type
}
// Extract the file extension from the MIME type
$extension = '';
if (preg_match('/^data:image\/(png|jpe?g);base64,/', $fileData)) {
$extension = 'jpg'; // Assume JPG for base64-encoded image data (PNG or JPEG)
} elseif (preg_match('/^data:application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel);base64,/', $fileData)) {
$extension = 'pdf'; // PDF, DOCX, or Excel
} elseif (preg_match('/^data:video\/(mp4|webm|x-msvideo|quicktime|x-matroska|x-flv|x-ms-wmv|mpeg|3gpp);base64,/', $fileData)) {
// Added more video extensions
if (preg_match('/^data:video\/mp4;base64,/', $fileData)) {
$extension = 'mp4'; // MP4
} elseif (preg_match('/^data:video\/webm;base64,/', $fileData)) {
$extension = 'webm'; // WebM
} elseif (preg_match('/^data:video\/x-msvideo;base64,/', $fileData)) {
$extension = 'avi'; // AVI
} elseif (preg_match('/^data:video\/quicktime;base64,/', $fileData)) {
$extension = 'mov'; // MOV
} elseif (preg_match('/^data:video\/x-matroska;base64,/', $fileData)) {
$extension = 'mkv'; // MKV
} elseif (preg_match('/^data:video\/x-flv;base64,/', $fileData)) {
$extension = 'flv'; // FLV
} elseif (preg_match('/^data:video\/x-ms-wmv;base64,/', $fileData)) {
$extension = 'wmv'; // WMV
} elseif (preg_match('/^data:video\/mpeg;base64,/', $fileData)) {
$extension = 'mpeg'; // MPEG
} elseif (preg_match('/^data:video\/3gpp;base64,/', $fileData)) {
$extension = '3gp'; // 3GP
}
}
// Remove the "data:image/png;base64," or "data:application/pdf;base64," prefix to get the actual base64-encoded content
$base64Content = preg_replace('/^data:(image\/png|application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel)|video\/(mp4|webm|x-msvideo|quicktime|x-matroska|x-flv|x-ms-wmv|mpeg|3gpp));base64,/', '', $fileData);
// Decode the base64-encoded content
$fileContent = base64_decode($base64Content);
// Validate the decoded content
if ($fileContent === false) {
return false; // Invalid base64-encoded content
}
// Create the Pimcore asset
$asset = new \Pimcore\Model\Asset();
$parent = Asset\Service::createFolderByPath('/Reports/uploaded_files/'. ($type ?? '')); // General folder path
$asset->setFilename($filename); // Replace with the desired filename and extension
$asset->setParent($parent);
$asset->setData($fileContent);
// Set the MIME type based on the file extension
$mimeType = '';
if ($extension === 'pdf') {
$mimeType = 'application/pdf';
} elseif ($extension === 'jpg') {
$mimeType = 'image/jpeg';
} elseif ($extension === 'png') {
$mimeType = 'image/png';
} elseif ($extension === 'docx') {
$mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
} elseif ($extension === 'xlsx') {
$mimeType = 'application/vnd.ms-excel';
} elseif ($extension === 'mp4') {
$mimeType = 'video/mp4'; // Video MP4
} elseif ($extension === 'webm') {
$mimeType = 'video/webm'; // Video WebM
} elseif ($extension === 'avi') {
$mimeType = 'video/x-msvideo'; // Video AVI
} elseif ($extension === 'mov') {
$mimeType = 'video/quicktime'; // Video MOV
} elseif ($extension === 'mkv') {
$mimeType = 'video/x-matroska'; // Video MKV
} elseif ($extension === 'flv') {
$mimeType = 'video/x-flv'; // Video FLV
} elseif ($extension === 'wmv') {
$mimeType = 'video/x-ms-wmv'; // Video WMV
} elseif ($extension === 'mpeg') {
$mimeType = 'video/mpeg'; // Video MPEG
} elseif ($extension === '3gp') {
$mimeType = 'video/3gpp'; // Video 3GP
}
// Validate the MIME type
if (!in_array($mimeType, ['image/jpeg', 'image/png', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'video/mp4', 'video/webm', 'video/x-msvideo', 'video/quicktime', 'video/x-matroska', 'video/x-flv', 'video/x-ms-wmv', 'video/mpeg', 'video/3gpp'])) {
return false; // Invalid MIME type
}
$asset->setType($mimeType);
// Save the asset
$asset->save();
return $asset;
}
public function publishAdvanceCustomReport($user, $params, $translator, $logger)
{
try {
$cityNames = '';
// Set default values for new parameters
$params['isAWSReport'] = isset($params['isAWSReport']) ? $params['isAWSReport'] : false;
$params['weather_stations'] = isset($params['weather_stations']) ? $params['weather_stations'] : [];
if ($params['isAWSReport']) {
// Handle AWS Weather Station report
if (!empty($params['weather_stations'])) {
$stations = new \Pimcore\Model\DataObject\WeatherStations\Listing();
$stations->setCondition('o_id IN (?)', [$params['weather_stations']]);
$stations->load();
if ($stations->getCount() > 0) {
foreach ($stations as $station) {
$nameEN = $station->getName('en');
$nameAR = $station->getName('ar');
$cityNames .= !empty($nameEN) ? $nameEN . ',' : '';
$cityNames .= !empty($nameAR) ? $nameAR . ',' : '';
}
} else {
return ["success" => false, "message" => "invalid_weather_station"];
}
// Remove the trailing comma
$cityNames = rtrim($cityNames, ',');
}
} else {
// Handle regular Governorate report
if (!empty($params['locations'])) {
$cities = new \Pimcore\Model\DataObject\Governorate\Listing();
$cities->setCondition('governoteId IN (?)', [$params['locations']]);
$cities->load();
if ($cities->getCount() > 0) {
foreach ($cities as $city) {
$nameEN = $city->getCityName('en');
$nameAR = $city->getCityName('ar');
$cityNames .= !empty($nameEN) ? $nameEN . ',' : '';
$cityNames .= !empty($nameAR) ? $nameAR . ',' : '';
}
} else {
return ["success" => false, "message" => "invalid_location"];
}
// Remove the trailing comma
$cityNames = rtrim($cityNames, ',');
}
}
if (isset($params['report_id'])) {
$report = Report::getById($params['report_id'], true);
if (!$report instanceof Report) {
return ["success" => false, "message" => "invalid_report_id"];
}
} else {
$report = new Report();
$report->setKey(\Pimcore\Model\Element\Service::getValidKey($user->getEmail() . uniqid(), 'object'));
$report->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Report/Report/advance_custom_report/"));
}
$reportType = '';
$report->setCreatedBy($user);
$report->setCreatedOn(Carbon::now());
$report->setStartDate(Carbon::parse(new \DateTime($params['start_date'])));
$report->setEndDate(Carbon::parse(new \Datetime($params['end_date'])));
$report->setSearchData($cityNames);
$report->setLang($params['lang']);
// $report->setEmail($user->getEmail());
$report->setJsonData(json_encode($params['data']));
if (isset($params['titleEn'])) {
$report->setReportTitle($params['titleEn'], "en");
}
if (isset($params['titleAr'])) {
$report->setReportTitle($params['titleAr'], "ar");
}
if (isset($params['descriptionEn'])) {
$report->setDescription($params['descriptionEn'], "en");
}
if (isset($params['descriptionAr'])) {
$report->setDescription($params['descriptionAr'], "ar");
}
if (isset($params['reportDisclaimerEn'])) {
$report->setReportDisclaimer($params['reportDisclaimerEn'], "en");
}
if (isset($params['reportDisclaimerAr'])) {
$report->setReportDisclaimer($params['reportDisclaimerAr'], "ar");
}
if (isset($params['additionalNoteEn'])) {
$report->setAdditionalNote($params['additionalNoteEn'], "en");
}
if (isset($params['additionalNoteAr'])) {
$report->setAdditionalNote($params['additionalNoteAr'], "ar");
}
if (isset($params['publishOnPdf'])) {
$report->setPublishOnPdf($params['publishOnPdf'] == true ? true : false);
}
if (isset($params['report_type_id'])) {
$reportType = ReportType::getById($params['report_type_id'], true);
if ($reportType instanceof ReportType) {
$report->setReportType($reportType);
// if($reportType->getKey()!='CustomWeatherReport'|| $reportType->getKey()!='MashaerWeatherReport'){
// $report->setForPublicPortal(true);
// $report->setForAjwaaPortal(true);
// }
}
}
if (!empty($params['organizations'])) {
$selectedOrganizations = [];
if ($params['organizations'][0] == 0) {
// $organizations= new Organization\Listing();
// if ( $organizations->count() > 0) {
// foreach ($organizations as $organization) {
// if ($organization) {
// $selectedOrganizations[] = $organization;
// }
// }
// $report->setOrganization($selectedOrganizations);
// }
} else {
foreach ($params['organizations'] as $organization) {
$organizationObject = Organization::getById($organization, true);
if ($organizationObject) {
$selectedOrganizations[] = $organizationObject;
}
}
$report->setOrganization($selectedOrganizations);
}
}
$emails = "";
if (!empty($params['channels'])) {
$channels = ['public_portal', 'ajwaa_portal', 'email', 'twitter', 'sms'];
foreach ($params['channels'] as $channel) {
if ($channel == 'public_portal') {
$report->setForPublicPortal(true);
} elseif ($channel == 'ajwaa_portal') {
$report->setForAjwaaPortal(true);
if (isset($params['send_email'])) {
$report->setSendEmail(true);
}
} elseif ($channel == 'email') {
$report->setForEmailChannel(true);
$emails .= implode(",", $params['emails']);
} elseif ($channel == 'twitter') {
$report->setForTwitterChannel(true);
}
}
}
$emailArray = [];
if (isset($params['user_group_ids']) && !empty($params['user_group_ids'])) {
$userGroupIds = ($params['user_group_ids']);
foreach ($userGroupIds as $userGroupId) {
if ($userGroupId) {
$userGroup = \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupId, true);
if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
if (isset($currentUser->email)) {
$report->setForEmailChannel(true);
$emailArray[] = $currentUser->email;
}
}
}
}
}
}
if (!empty($emailArray)) {
if (!empty($emails)) {
$emails .= ',' . implode(',', $emailArray);
} else {
$emails = implode(',', $emailArray);
}
}
$report->setIsAWSReport($params['isAWSReport']);
$report->setEmails($emails);
$report->setPublished(true);
// delete the existing pdf if report is updated
if (isset($params['report_id'])) {
$pdfEn = $report->getAsset();
$pdfAr = $report->getAssetAr();
if ($pdfEn instanceof Asset) {
$pdfEn->delete();
}
if ($pdfAr instanceof Asset) {
$pdfAr->delete();
}
}
$report->save();
// //$phpPath = 'D:\laragon\bin\php\php-8.1.10-Win32-vs16-x64\php.exe'; // Adjust to the actual PHP path on your system
// $consolePath = 'bin\console'; // Use backslashes for Windows paths
// $commandArguments = ['bin/console', 'app:today-weather-pdf'];
// if(!empty($reportType)){
// if($reportType->getKey()!='CustomWeatherReport' || $reportType->getKey()!='MashaerWeatherReport'){
// $process = new Process($commandArguments);
// $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
// try {
// $process->mustRun();
// $logger->info("Today Weather command executed successfully: " . $process->getOutput());
// // p_r("Today Weather command executed successfully: " . $process->getOutput());exit;
// $result['success'] = true;
// $result['message'] = $process->getOutput();
// } catch (ProcessFailedException $exception) {
// $logger->error("Today Weather command failed: " . $exception->getMessage());
// // p_r("Today Weather command failed: " . $exception->getMessage());exit;
// $result['success'] = false;
// $result['message'] = "Failed to execute notification command.";
// }
// }
// }
if (isset($params['report_id'])) {
return ["success" => true, "message" => $translator->trans("report_updated_successfully"), "data" => $report->getId()];
} else {
return ["success" => true, "message" => $translator->trans("report_published_successfully"), "data" => $report->getId()];
}
} catch (\Exception $ex) {
return ["success" => false, "message" => $ex->getMessage()];
}
}
public function archiveWeatherReport($translator, $user, $reportId)
{
$report = Report::getById($reportId);
if ($report->getPublished()) {
$report->setPublished(false);
$report->setSoftDelete(true);
$report->save();
return ["success" => true, "message" => $translator->trans("archive_weather_report")];
} else {
return ["success" => false, "message" => $translator->trans("report_not_found")];
}
}
public function generatePdfReport($request, $user, $snappy, $translator)
{
// Parse request parameters
$params = json_decode($request->getContent(), true);
if (empty($params['id'])) {
return [
"success" => false,
"message" => $translator->trans("missing_required_parameters")
];
}
// Fetch the report
$report = Report::getById($params['id'], true);
$lang = $params['lang'] ?? "en";
if (!$report instanceof Report) {
return [
"success" => false,
"message" => $translator->trans("no_report_found")
];
}
// Check for existing asset
$asset = $lang === 'ar' ? $report->getAssetAr() : $report->getAsset();
if ($asset) {
$pdfUrl = API_BASE_URL . $asset->getPath() . $asset->getFilename();
return ['success' => true, 'data' => $pdfUrl];
}
// Determine the template and path based on the report type
$templates = [
'arabian-gulf-report' => 'pdfReportTemplates/arabian-gulf-report.html.twig',
'red-sea-report' => 'pdfReportTemplates/red-sea-report.html.twig',
'custom-weather-report' => 'pdfReportTemplates/custom-weather-report.html.twig',
'10-day-forecast-report' => 'pdfReportTemplates/ten-day-forecast-report.html.twig',
'mashaer-weather-report' => 'pdfReportTemplates/mashaer-weather-report.html.twig',
'advance-custom-weather-report' => 'pdfReportTemplates/advance-custom-weather-report.html.twig',
];
$defaultTemplate = 'pdfReportTemplates/automatic_report_pdf_template.html.twig';
$reportKey = $report->getReportType()?->getReportkey();
$template = $templates[$reportKey] ?? $defaultTemplate;
// Determine report path
$reportPaths = [
'red-sea-report' => '/report/advanceCustomReportPdf',
'custom-weather-report' => '/report/advanceCustomReportPdf',
'10-day-forecast-report' => '/report/advanceCustomReportPdf',
'mashaer-weather-report' => '/report/advanceCustomReportPdf',
'advance-custom-weather-report' => '/report/advanceCustomReportPdf',
];
$reportPath = $reportPaths[$reportKey] ?? '/report/ReportPdf';
// Prepare parameters for PDF generation
$parameter = [
'data' => $report,
'reportTitleEn' => $report->getReportTitle('en'),
'reportTitleAr' => $report->getReportTitle('ar'),
'reportDescriptionEn' => $report->getDescription('en'),
'reportDescriptionAr' => $report->getDescription('ar'),
'reportDisclaimerEn' => $report->getReportDisclaimer('en'),
'reportDisclaimerAr' => $report->getReportDisclaimer('ar'),
'additionalNoteEn' => $report->getAdditionalNote('en'),
'additionalNoteAr' => $report->getAdditionalNote('ar'),
'stateOfTheSeaEn' => $report->getStateOfTheSea('en'),
'stateOfTheSeaAr' => $report->getStateOfTheSea('ar'),
'waveHeightEn' => $report->getWaveHeight('en'),
'waveHeightAr' => $report->getWaveHeight('ar'),
'surfaceWindEn' => $report->getSurfaceWind('en'),
'surfaceWindAr' => $report->getSurfaceWind('ar'),
'publishOnPdf' => (bool)$report->getPublishOnPdf(),
'reportTypeNameEn' => $report->getReportType()?->getName('en'),
'reportTypeNameAr' => $report->getReportType()?->getName('ar'),
'reportType' => $reportKey,
'template' => $template,
'lang' => $lang,
];
// Generate PDF
try {
$pdf = \App\Lib\Utility::generatePdf($parameter, $snappy);
} catch (\Exception $e) {
return [
'success' => false,
'message' => $translator->trans("pdf_generation_failed"),
'error' => $e->getMessage(),
];
}
// Set file name and report path
$pdfReportName = ($report->getReportType()?->getName($lang) ?? 'Report') . '_' . date('d-m-Y') . '.pdf';
$reportPath .= '/' . $report->getId();
// Create asset
$asset = \App\Lib\Utility::createAsset($pdf, $pdfReportName, $reportPath);
if (!$asset instanceof Asset) {
return [
'success' => false,
'message' => $translator->trans("asset_creation_failed"),
];
}
// Save the asset to the report
if ($lang === 'ar') {
$report->setAssetAr($asset);
} else {
$report->setAsset($asset);
}
$report->save();
// Return the asset URL
$pdfUrl = API_BASE_URL . $asset->getPath() . $asset->getFilename();
return ['success' => true, 'data' => $pdfUrl];
}
}