Skip to content

Commit

Permalink
Merge pull request #23 from wmo-raf/dev
Browse files Browse the repository at this point in the history
Updates and Bug Fixes
  • Loading branch information
erick-otenyo authored May 2, 2024
2 parents 9008fe9 + 6f4517b commit 4cffddb
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 18 deletions.
30 changes: 26 additions & 4 deletions capeditor/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@
import shapely
from django import forms
from django.contrib.gis.geos import GEOSGeometry
from django.core.exceptions import ValidationError
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from shapely import Point, Polygon
from shapely.geometry import shape
from wagtail import blocks
from wagtail.blocks import FieldBlock, StructValue
from wagtail.blocks import FieldBlock, StructValue, StructBlockValidationError
from wagtail.documents.blocks import DocumentChooserBlock
from wagtail.models import Site
from wagtailmodelchooser.blocks import ModelChooserBlock

from .forms.fields import PolygonField, MultiPolygonField, BoundaryMultiPolygonField, PolygonOrMultiPolygonField
from .forms.widgets import CircleWidget
from .serializers import parse_tz
from .utils import file_path_mime


Expand Down Expand Up @@ -115,9 +117,9 @@ class AlertReferenceStructValue(StructValue):
@property
def ref_alert_identifier(self):
alert_page = self.get("ref_alert").specific

if hasattr(alert_page, "cap_reference_id"):
return alert_page.cap_reference_id
if hasattr(alert_page, "sender") and hasattr(alert_page, "identifier") and hasattr(alert_page, "sent"):
sent = parse_tz(alert_page.sent.isoformat())
return "{},{},{}".format(alert_page.sender, alert_page.identifier, sent)

return None

Expand Down Expand Up @@ -698,6 +700,26 @@ class Meta:
value_class = AlertInfoStructValue
label_format = "({language}) {event}"

def clean(self, value):
result = super().clean(value)
effective = result.get("effective")
onset = result.get("onset")
expires = result.get("expires")

if expires:
if effective and expires < effective:
raise StructBlockValidationError(block_errors={
"expires": ValidationError(
_("The expiry time of the alert should be greater than the effective time"))
})

if onset and expires < onset:
raise StructBlockValidationError(block_errors={
"expires": ValidationError(_("The expiry time of the alert should be greater than the onset time"))
})

return result


class AudienceTypeBlock(blocks.StructBlock):
audience = blocks.CharBlock(max_length=255, label=_("Audience"), help_text=_("Intended audience"))
Expand Down
3 changes: 2 additions & 1 deletion capeditor/cap_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ def geojson(self):

panels = [
FieldPanel("name"),
FieldPanel("geom", widget=PolygonDrawWidget(attrs={"resize_trigger_class": "map-resize-trigger"})),
FieldPanel("geom",
widget=PolygonDrawWidget(attrs={"resize_trigger_selector": ".w-tabs__tab.map-resize-trigger"})),
]


Expand Down
42 changes: 42 additions & 0 deletions capeditor/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,48 @@ def __init__(self, *args, **kwargs):
info_field.block.child_blocks[block_type].child_blocks[field_name].name = name
info_field.block.child_blocks[block_type].child_blocks[field_name].label = label

def clean(self):
cleaned_data = super().clean()

# validata msgType
msgType = cleaned_data.get("msgType")
if msgType and msgType != 'Alert':
references = cleaned_data.get("references")
if not references:
# if the message type is not 'Alert' then references are required
self.add_error('references', _("You must select at least one reference alert for this message type. "
"Only 'Alert' Message Type can be saved without references."))
else:
alerts_ids = []
for reference in references:
ref_alert_page = reference.value.get("ref_alert").specific
if ref_alert_page:
alerts_ids.append(ref_alert_page.identifier)

# check if the same alert is selected more than once
if len(alerts_ids) != len(set(alerts_ids)):
self.add_error('references', _("You cannot select the same alert more than once."))

# validate dates
sent = cleaned_data.get("sent")
alert_infos = cleaned_data.get("info")
if alert_infos:
for info in alert_infos:
effective = info.value.get("effective")
onset = info.value.get("onset")
expires = info.value.get("expires")

if effective and sent and effective < sent:
self.add_error('info', _("Effective date cannot be earlier than the alert sent date."))

if onset and sent and onset < sent:
self.add_error('info', _("Onset date cannot be earlier than the alert sent date."))

if expires and sent and expires < sent:
self.add_error('info', _("Expires date cannot be earlier than the alert sent date."))

return cleaned_data


class AbstractCapAlertPage(Page):
base_form_class = CapAlertPageForm
Expand Down
10 changes: 9 additions & 1 deletion capeditor/static/capeditor/js/widget/boundary-polygon-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ BoundaryPolygonWidget.prototype.initMap = async function () {
container: this.options.map_id,
style: defaultStyle,
doubleClickZoom: false,
scrollZoom: false,
});


Expand Down Expand Up @@ -290,7 +291,14 @@ BoundaryPolygonWidget.prototype.addAdminBoundaryLayer = function () {
if (name) {
this.areaDescInput.val(name)
}
this.setSourceData(feature)

const truncatedFeature = turf.truncate(feature, {
precision: 2,
coordinates: 2,
mutate: true
})

this.setSourceData(truncatedFeature)
})
}
}
Expand Down
3 changes: 1 addition & 2 deletions capeditor/static/capeditor/js/widget/circle-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ CircleWidget.prototype.initMap = async function () {
container: this.options.map_id,
style: defaultStyle,
doubleClickZoom: false,
scrollZoom: false,
});


Expand Down Expand Up @@ -277,8 +278,6 @@ CircleWidget.prototype.setSourceData = function (feature) {
CircleWidget.prototype.initFromState = function () {
const circeValue = this.getState()

console.log(circeValue)

if (circeValue) {
const {lon, lat, radius} = this.parseCircleValue(circeValue) || {}

Expand Down
17 changes: 11 additions & 6 deletions capeditor/static/capeditor/js/widget/polygon-draw-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,15 @@ class PolygonDrawWidget {
this.geomInput = document.getElementById(this.options.id)


if (this.options.resize_trigger_class) {
this.resizeTriggerEls = document.getElementsByClassName(this.options.resize_trigger_class)
if (this.options.resize_trigger_selector) {
this.resizeTriggerEls = document.querySelectorAll(this.options.resize_trigger_selector)
}

this.initalValue = this.geomInput.value
this.countriesBounds = this.geomInput.dataset.bounds ? JSON.parse(this.geomInput.dataset.bounds) : null

this.createMap().then((map) => {
this.map = map;

this.fitBounds()

if (this.resizeTriggerEls && this.resizeTriggerEls.length > 0) {
Expand All @@ -31,7 +30,6 @@ class PolygonDrawWidget {
}
}


this.initDraw();
});

Expand Down Expand Up @@ -83,6 +81,7 @@ class PolygonDrawWidget {
container: this.options.map_id,
style: defaultStyle,
doubleClickZoom: false,
scrollZoom: false,
});


Expand Down Expand Up @@ -138,7 +137,6 @@ class PolygonDrawWidget {

initDraw() {
const feature = this.getValue()

this.draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
Expand Down Expand Up @@ -173,7 +171,14 @@ class PolygonDrawWidget {
if (combinedFeatures) {
const feature = combinedFeatures.features[0]

this.setValue(JSON.stringify(feature.geometry))

const truncatedFeature = turf.truncate(feature, {
precision: 2,
coordinates: 2,
mutate: true
})

this.setValue(JSON.stringify(truncatedFeature.geometry))

} else {
this.setValue("")
Expand Down
13 changes: 11 additions & 2 deletions capeditor/static/capeditor/js/widget/polygon-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ PolygonWidget.prototype.initMap = async function () {
container: this.options.map_id,
style: defaultStyle,
doubleClickZoom: false,
scrollZoom: false,
});


Expand Down Expand Up @@ -323,8 +324,16 @@ PolygonWidget.prototype.clearDraw = function () {
}


PolygonWidget.prototype.setDrawData = function (geometry) {
if (geometry) {
PolygonWidget.prototype.setDrawData = function (featureGeom) {
if (featureGeom) {

// truncate geometry
const geometry = turf.truncate(featureGeom, {
precision: 2,
coordinates: 2,
mutate: true
})

const bbox = turf.bbox(geometry)
const bounds = [[bbox[0], bbox[1]], [bbox[2], bbox[3]]]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
map_id: '{{ id }}_map',
map_srid: {{ map_srid|unlocalize }},
name: '{{ name }}',
resize_trigger_class: '{{ resize_trigger_class }}',
resize_trigger_selector: '{{ resize_trigger_selector }}',
};
{% endblock %}
var {{ module }} =
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = capeditor
version = 0.5.3
version = 0.5.4
description = Wagtail based CAP composer
long_description = file:README.md
long_description_content_type = text/markdown
Expand Down

0 comments on commit 4cffddb

Please sign in to comment.