Skip to content

Commit

Permalink
Merge pull request #88 from wmo-raf/dev
Browse files Browse the repository at this point in the history
Updates
  • Loading branch information
erick-otenyo authored Apr 2, 2024
2 parents e645674 + b39ab56 commit 6c4d9df
Show file tree
Hide file tree
Showing 15 changed files with 527 additions and 453 deletions.
36 changes: 25 additions & 11 deletions nmhs_cms/templates/navigation/navbar.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load i18n wagtailcore_tags static wagtailimages_tags wagtailiconchooser_tags cap_tags %}
{% load i18n wagtailcore_tags static wagtailimages_tags wagtailiconchooser_tags %}
{% url 'wagtailadmin_home' as wagtail_admin_url %}
{% wagtail_site as current_site %}
<header class="header-nav">
Expand All @@ -20,7 +20,6 @@
{% else %}
N.M.H.S
{% endif %}

</a>

</div>
Expand Down Expand Up @@ -109,7 +108,7 @@
{{ user.username }}, CMS
</a>
{% endif %}
{% get_latest_active_cap_alert %}
<div class="latest-active-alert"></div>
</div>
</div>
</div>
Expand Down Expand Up @@ -145,29 +144,44 @@
</div>
</div>
</nav>
<div class="is-hidden-desktop">
{% get_latest_active_cap_alert %}
<div class="is-hidden-desktop latest-active-alert">
</div>

</header>
{% block extra_js %}
<script>
const latestActiveAlertUrl = {% url 'latest_active_alert' %};

document.addEventListener('DOMContentLoaded', () => {
const $navbarBurger = document.getElementById('navBurger')
const navbarBurgerEl = document.getElementById('navBurger')

// Add a click event
$navbarBurger.addEventListener('click', (e) => {
navbarBurgerEl.addEventListener('click', (e) => {

e.stopImmediatePropagation()

// Get the target from the "data-target" attribute
const target = $navbarBurger.dataset.target;
const $target = document.getElementById(target);
const target = navbarBurgerEl.dataset.target;
const targetEl = document.getElementById(target);

// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
$navbarBurger.classList.toggle('is-active');
$target.classList.toggle('is-active');
navbarBurgerEl.classList.toggle('is-active');
targetEl.classList.toggle('is-active');
});

if (latestActiveAlertUrl) {
fetch(latestActiveAlertUrl)
.then(response => response.text())
.then(data => {
const latestActiveAlert = document.querySelectorAll('.latest-active-alert')
if (data) {
latestActiveAlert.forEach((alertContainer) => {
alertContainer.innerHTML = data;
});
}
})
}

});


Expand Down
8 changes: 5 additions & 3 deletions nmhs_cms/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,9 @@
urlpatterns = [
path("documents/", include(wagtaildocs_urls)),

path("api/satellite-imagery/", include("pages.satellite_imagery.urls")),
path("api/cityclimate/", include("pages.cityclimate.urls")),
path("api/videos/<int:pk>", VideoView.as_view(), name="youtube_playlist_items"),
path("", include("pages.home.urls")),
path("", include("pages.cap.urls")),
path("", include("pages.weather.urls")),

path("", include("geomanager.urls"), name="geomanager"),
path("", include("pages.stations.urls"), name="stations"),
Expand All @@ -39,6 +37,10 @@
path('auth/', include('allauth.urls')),

path('api/v2/', api_router.urls, name="wagtailapi"),

path("api/satellite-imagery/", include("pages.satellite_imagery.urls")),
path("api/cityclimate/", include("pages.cityclimate.urls")),
path("api/videos/<int:pk>", VideoView.as_view(), name="youtube_playlist_items"),
]

if ADMIN_URL_PATH:
Expand Down
Empty file removed pages/cap/templatetags/__init__.py
Empty file.
29 changes: 0 additions & 29 deletions pages/cap/templatetags/cap_tags.py

This file was deleted.

4 changes: 3 additions & 1 deletion pages/cap/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django.urls import path

from pages.cap.views import AlertDetail, AlertListFeed, cap_geojson
from pages.cap.views import AlertDetail, AlertListFeed, cap_geojson, get_home_map_alerts, get_latest_active_alert

urlpatterns = [
path("home-map-alerts/", get_home_map_alerts, name="home_map_alerts"),
path("latest-active-alert/", get_latest_active_alert, name="latest_active_alert"),
path("api/cap/rss.xml", AlertListFeed(), name="cap_alert_feed"),
path("api/cap/alerts.geojson", cap_geojson, name="cap_alerts_geojson"),
path("api/cap/<uuid:identifier>.xml", AlertDetail.as_view(), name="cap_alert_detail"),
Expand Down
64 changes: 64 additions & 0 deletions pages/cap/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import json
from typing import Any, Dict, List

from capeditor.constants import SEVERITY_MAPPING
from capeditor.models import CapSetting
from capeditor.renderers import CapXMLRenderer
from capeditor.serializers import AlertSerializer
from django.contrib.syndication.views import Feed
from django.db.models.base import Model
from django.http import JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from django.utils.feedgenerator import Enclosure
Expand Down Expand Up @@ -142,3 +145,64 @@ def cap_geojson(request):
geojson["features"].extend(features)

return JsonResponse(geojson)


def get_home_map_alerts(request):
alerts = CapAlertPage.objects.all().live().filter(status="Actual")
active_alert_infos = []
geojson = {"type": "FeatureCollection", "features": []}

for alert in alerts:
for info in alert.info:
if info.value.get('expires') > timezone.localtime():
start_time = info.value.get("effective") or alert.sent

if timezone.now() > start_time:
status = "Ongoing"
else:
status = "Expected"

area_desc = [area.get("areaDesc") for area in info.value.area]
area_desc = ",".join(area_desc)

alert_info = {
"status": status,
"url": alert.url,
"event": f"{info.value.get('event')} ({area_desc})",
"event_icon": info.value.event_icon,
"severity": SEVERITY_MAPPING[info.value.get("severity")]
}

active_alert_infos.append(alert_info)

if info.value.features:
for feature in info.value.features:
geojson["features"].append(feature)
context = {
'active_alert_info': active_alert_infos,
'geojson': json.dumps(geojson)
}

return render(request, "home/section/home_map_alerts_include.html", context)


def get_latest_active_alert(request):
alerts = CapAlertPage.objects.all().live().filter(status="Actual")
active_alert_infos = []

for alert in alerts:
for alert_info in alert.infos:
info = alert_info.get("info")
if info.value.get('expires') > timezone.localtime():
active_alert_infos.append(alert_info)

if len(active_alert_infos) == 0:
return {
'latest_active_alert': None
}

context = {
'latest_active_alert': active_alert_infos[0]
}

return render(request, "cap/active_alert.html", context)
101 changes: 8 additions & 93 deletions pages/home/models.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import json

from adminboundarymanager.models import AdminBoundarySettings
from capeditor.constants import SEVERITY_MAPPING
from django.contrib.gis.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from forecastmanager.forecast_settings import ForecastSetting
from forecastmanager.models import City, CityForecast
from wagtail.admin.panels import MultiFieldPanel, FieldPanel
from wagtail.api.v2.utils import get_full_url
from wagtail.contrib.settings.models import BaseSiteSetting
from wagtail.contrib.settings.registry import register_setting
from wagtail.fields import StreamField
from wagtail.models import Page, Site
from wagtail.models import Page
from wagtail_color_panel.fields import ColorField

from base import blocks
from base.mixins import MetadataPageMixin
from pages.cap.models import CapAlertPage
from pages.events.models import EventPage
from pages.home.blocks import AreaBoundaryBlock, AreaPolygonBlock
from pages.news.models import NewsPage
Expand Down Expand Up @@ -66,9 +59,6 @@ class HomePage(MetadataPageMixin, Page):
]
max_count = 1

# don't cache home page
cache_control = 'no-cache'

hero_title = models.CharField(max_length=100, verbose_name=_('Title'))
hero_subtitle = models.CharField(blank=True, null=True, max_length=100, verbose_name=_('Subtitle'))
hero_banner = models.ForeignKey("wagtailimages.Image", on_delete=models.SET_NULL, null=True, blank=False,
Expand Down Expand Up @@ -137,67 +127,29 @@ def get_meta_image(self):
return self.hero_banner

def get_context(self, request, *args, **kwargs):
context = super(HomePage, self).get_context(
request, *args, **kwargs)

abm_settings = AdminBoundarySettings.for_request(request)
abm_extents = abm_settings.combined_countries_bounds
boundary_tiles_url = get_full_url(request, abm_settings.boundary_tiles_url)
map_settings_url = get_full_url(request, reverse("home-map-settings"))

context.update({
"bounds": abm_extents,
"boundary_tiles_url": boundary_tiles_url,
"weather_icons_url": get_full_url(request, reverse("weather-icons")),
"forecast_settings_url": get_full_url(request, reverse("forecast-settings")),
"home_map_settings_url": map_settings_url
})

site = Site.objects.get(is_default_site=True)
forecast_setting = ForecastSetting.for_site(site)
context = super(HomePage, self).get_context(request, *args, **kwargs)

forecast_setting = ForecastSetting.for_request(request)
city_detail_page = forecast_setting.weather_detail_page
city_detail_page_url = None

if city_detail_page:
city_detail_page = city_detail_page.specific
all_city_detail_page_url = city_detail_page.get_full_url(request)
city_detail_page_url = all_city_detail_page_url + city_detail_page.detail_page_base_url
context.update({
"all_city_detail_page_url": all_city_detail_page_url,
"city_detail_page_url": city_detail_page_url,

})

city_search_url = get_full_url(request, reverse("cities-list"))
context.update({
"city_search_url": city_search_url,
"city_detail_page_url": city_detail_page_url
})

if forecast_setting.weather_reports_page:
context.update({
"weather_reports_page_url": forecast_setting.weather_reports_page.get_full_url(request)
})

default_city = forecast_setting.default_city
if not default_city:
default_city = City.objects.first()

if default_city:
default_city_forecasts = CityForecast.objects.filter(
city=default_city,
parent__forecast_date__gte=timezone.localtime(),
parent__effective_period__default=True
).order_by("parent__forecast_date")

# get unique forecast dates
forecast_dates = default_city_forecasts.values_list("parent__forecast_date", flat=True).distinct()

context.update({
"default_city_forecasts": default_city_forecasts,
"forecast_dates": forecast_dates,
})
map_settings_url = get_full_url(request, reverse("home-map-settings"))
context.update({
"home_map_settings_url": map_settings_url,
"home_weather_widget_url": get_full_url(request, reverse("home-weather-widget")),
})

if self.youtube_playlist:
context['youtube_playlist_url'] = self.youtube_playlist.get_playlist_items_api_url(request)
Expand Down Expand Up @@ -239,43 +191,6 @@ def latest_updates(self):

return updates

@cached_property
def cap_alerts(self):
alerts = CapAlertPage.objects.all().live().filter(status="Actual")
active_alert_infos = []
geojson = {"type": "FeatureCollection", "features": []}

for alert in alerts:
for info in alert.info:
if info.value.get('expires') > timezone.localtime():
start_time = info.value.get("effective") or alert.sent

if timezone.now() > start_time:
status = "Ongoing"
else:
status = "Expected"

area_desc = [area.get("areaDesc") for area in info.value.area]
area_desc = ",".join(area_desc)

alert_info = {
"status": status,
"url": alert.url,
"event": f"{info.value.get('event')} ({area_desc})",
"event_icon": info.value.event_icon,
"severity": SEVERITY_MAPPING[info.value.get("severity")]
}

active_alert_infos.append(alert_info)

if info.value.features:
for feature in info.value.features:
geojson["features"].append(feature)
return {
'active_alert_info': active_alert_infos,
'geojson': json.dumps(geojson)
}

@cached_property
def services(self):
services = ServicePage.objects.live()
Expand Down
Loading

0 comments on commit 6c4d9df

Please sign in to comment.