Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#8689u4y5t-native-land-resource-update #361

Merged
merged 18 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion helpers/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@
path('community-boundary-view/<int:community_id>', views.community_boundary_view, name="community-boundary-view"),
path('project-boundary-view/<int:project_id>', views.project_boundary_view, name="project-boundary-view"),
path('boundary-preview/', views.boundary_preview, name="boundary-preview"),
]
path('nld-data/', views.native_land_data, name="nld-data"),
]
14 changes: 14 additions & 0 deletions helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,3 +479,17 @@ def create_or_update_boundary(
# create boundary when it does not exist
entity.boundary = Boundary(coordinates=boundary_coordinates)
entity.boundary.save()


def retrieve_native_land_all_slug_data() -> dict:
"""
Does request to obtain all NLD slug data list
which includes the groups of coordinates for each slug
"""
url = (
'https://raw.githubusercontent.com/biocodellc/'
'localcontexts_json/refs/heads/main/data/'
'nativeland_slug_coordinates_description_dict.json'
)
response = requests.get(url)
return response.json()
35 changes: 34 additions & 1 deletion helpers/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import json

from django.core.cache import cache
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404
from django.http import HttpResponse, Http404, JsonResponse
from django.conf import settings
from django.views.decorators.clickjacking import xframe_options_sameorigin

Expand All @@ -15,6 +16,7 @@
from .models import NoticeDownloadTracker
from institutions.models import Institution
from researchers.models import Researcher
from .utils import retrieve_native_land_all_slug_data


def restricted_view(request, exception=None):
Expand Down Expand Up @@ -131,3 +133,34 @@ def boundary_preview(request):
'preview_boundary': True,
}
return render(request, 'boundary/boundary-preview.html', context)


@login_required(login_url='login')
def native_land_data(request):
"""
Returns data associated with particular slug
"""
slug = request.GET.get('slug')
if slug is None:
return Http404('Slug Variable Is Not Defined In Request')

# get all slug data from cache
all_slug_data = cache.get('all_slug_data')

# when cache doesn't exist, then retrieve actual data and cache it
if all_slug_data is None:
try:
all_slug_data = retrieve_native_land_all_slug_data()
except (
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError
):
return Http404('Unable to Retrieve All NLD Slug Data')
cache.set('all_slug_data', all_slug_data)

slug_data = all_slug_data.get(slug)
if slug_data is None:
return Http404(f'Unable to Retrieve Specific NLD Slug Data for {slug}')

return JsonResponse(slug_data)
6 changes: 6 additions & 0 deletions localcontexts/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,12 @@
}
}

CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}

SITE_ID = 1

SOCIALACCOUNT_LOGIN_ON_GET=True
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load static %}
{% load static %} {% load custom_api_tags %}
<style>
.region-container{
margin-top: 20px;
Expand Down Expand Up @@ -255,18 +255,19 @@
let BoundaryPayLoad = {}
let InitialShareBoundaryPublicly = {% if entity.share_boundary_publicly %}true{% else %}false{% endif %}

fetch('https://native-land.ca/wp-json/nativeland/v1/map-list').then(resp => resp.json()).then(response => {
fetch('{% external_api "https://raw.githubusercontent.com/biocodellc/localcontexts_json/main/data/nativeland_slug_name_list.json" %}').
then(resp => resp.json()).then(response => {

document.querySelector('.region-container input.search').addEventListener("keyup", (event) => {
let html = ''
const textInput = event.target.value
const inputLength = textInput.length
if (inputLength >= 3) {
var results = response.filter(item => item.post_title.toLowerCase().indexOf(textInput.toLowerCase()) > -1);
var results = response.filter(item => item.name.toLowerCase().indexOf(textInput.toLowerCase()) > -1);
results.forEach(result => {
html += `
<div class="result-item" data-slug="${result.slug}" data-title="${result.post_title}" onclick="selectSlug(this)">
${result.post_title}</br />
<div class="result-item" data-slug="${result.slug}" data-title="${result.name}" onclick="selectSlug(this)">
${result.name}</br />
</div>
`
})
Expand Down Expand Up @@ -351,27 +352,26 @@
* */
try {
// do post call to get boundary
const url = `https://native-land.ca/wp-json/nativeland/v1/api/index.php?maps=territories&name=${slug}`
const url = `{% url 'nld-data' %}?slug=${slug}`
showSpinner()
const boundaryResponse = await fetch(url)
const boundaryData = await boundaryResponse.json()
hideSpinner()

if (boundaryData.length === 0) {
if (!boundaryData.coordinates[0].length) {
const errorMessage = 'Selected location does not have any Native Land boundary'
raiseError(selectionUnit, errorMessage)
throw new Error(errorMessage)
}

const boundary = boundaryData[0]
const boundaryCoordinates = boundary.geometry.coordinates[0]

const boundaryCoordinates = boundaryData.coordinates[0][0]
// reorder so (lon, lat)'s become (lat, lon)'s
boundaryCoordinates.map(row=>row.reverse())

// set Boundary with payload
BoundaryPayLoad = {
source: boundary.properties.description,
name: boundary.properties.Name,
source: boundaryData.description,
name: slug,
boundary: boundaryCoordinates,
should_update_coordinates: true,
}
Expand Down
24 changes: 12 additions & 12 deletions templates/communities/add-community-boundary.html
Original file line number Diff line number Diff line change
Expand Up @@ -184,18 +184,19 @@ <h2 class="mt-0">Search the Native Land Digital database</h2>
</div>

<script>
fetch('{% external_api "https://native-land.ca/wp-json/nativeland/v1/map-list" %}').then(resp => resp.json()).then(response => {
fetch('{% external_api "https://raw.githubusercontent.com/biocodellc/localcontexts_json/main/data/nativeland_slug_name_list.json" %}').
then(resp => resp.json()).then(response => {

document.querySelector('#region-container input.search').addEventListener("keyup", (event) => {
let html = ''
const textInput = event.target.value
const inputLength = textInput.length
if (inputLength >= 3) {
var results = response.filter(item => item.post_title.toLowerCase().indexOf(textInput.toLowerCase()) > -1);
var results = response.filter(item => item.name.toLowerCase().indexOf(textInput.toLowerCase()) > -1);
results.forEach(result => {
html += `
<div class="result-item" data-slug="${result.slug}" data-title="${result.post_title}" onclick="selectSlug()">
${result.post_title}</br />
<div class="result-item" data-slug="${result.slug}" data-title="${result.name}" onclick="selectSlug()">
${result.name}</br />
</div>
`
})
Expand Down Expand Up @@ -229,7 +230,7 @@ <h2 class="mt-0">Search the Native Land Digital database</h2>
function selectSlug() {
const title = event.target.dataset.title
const slug = event.target.dataset.slug
const url = `https://native-land.ca/wp-content/themes/Native-Land-Theme/embed/embed.html?maps=territories&name=${slug}`
const url = `https://native-land.ca/maps/territories/${slug}`
document.querySelector('#nld-link').setAttribute('href', url)
document.querySelector('#selected-title').innerHTML = `<div class="selected-title-ellipsis">${title}</div>`

Expand All @@ -249,26 +250,25 @@ <h2 class="mt-0">Search the Native Land Digital database</h2>
const href = document.querySelector('#community-boundary-continue-btn').getAttribute('href')
const slug = document.querySelector('#selected-title').getAttribute('data-slug')

const url = `{% external_api "https://native-land.ca/wp-json/nativeland/v1/api/index.php?maps=territories&name=${slug}" %}`
const url = `{% url 'nld-data' %}?slug=${slug}`
const boundaryResponse = await fetch(url)
const boundaryData = await boundaryResponse.json()
document.querySelector("#community-boundary-continue-btn .fa-spinner").classList.remove("spinner-container");
document.getElementById("community-boundary-continue-btn").classList.remove("disabled-btn");

if (boundaryData.length === 0) {
if (!boundaryData.coordinates[0].length) {
const errorMessage = 'Selected location does not have any Native Land boundary'
alert(errorMessage)
throw new Error(errorMessage)
}

const boundary = boundaryData[0]
const boundaryCoordinates = boundary.geometry.coordinates[0]

const boundaryCoordinates = boundaryData.coordinates[0][0]
// reorder so (lon, lat)'s become (lat, lon)'s
boundaryCoordinates.map(row=>row.reverse())

const payload = {
source: boundary.properties.description,
name: boundary.properties.Name,
source: boundaryData.description,
name: slug,
boundary: boundaryCoordinates,
share_boundary_publicly: document.getElementById("share-boundary-publicly").checked
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load static %}
{% load static %} {% load custom_api_tags %}
<style>
.region-container{
margin-top: 20px;
Expand Down Expand Up @@ -230,18 +230,19 @@
<script>
let BoundaryPayLoad = {}

fetch('https://native-land.ca/wp-json/nativeland/v1/map-list').then(resp => resp.json()).then(response => {
fetch('{% external_api "https://raw.githubusercontent.com/biocodellc/localcontexts_json/main/data/nativeland_slug_name_list.json" %}').
then(resp => resp.json()).then(response => {

document.querySelector('.region-container input.search').addEventListener("keyup", (event) => {
let html = ''
const textInput = event.target.value
const inputLength = textInput.length
if (inputLength >= 3) {
var results = response.filter(item => item.post_title.toLowerCase().indexOf(textInput.toLowerCase()) > -1);
var results = response.filter(item => item.name.toLowerCase().indexOf(textInput.toLowerCase()) > -1);
results.forEach(result => {
html += `
<div class="result-item" data-slug="${result.slug}" data-title="${result.post_title}" onclick="selectSlug(this)">
${result.post_title}</br />
<div class="result-item" data-slug="${result.slug}" data-title="${result.name}" onclick="selectSlug(this)">
${result.name}</br />
</div>
`
})
Expand Down Expand Up @@ -303,27 +304,26 @@
* */
try {
// do post call to get boundary
const url = `https://native-land.ca/wp-json/nativeland/v1/api/index.php?maps=territories&name=${slug}`
const url = `{% url 'nld-data' %}?slug=${slug}`
showSpinner()
const boundaryResponse = await fetch(url)
const boundaryData = await boundaryResponse.json()
hideSpinner()

if (boundaryData.length === 0) {
if (!boundaryData.coordinates[0].length) {
const errorMessage = 'Selected location does not have any Native Land boundary'
raiseError(selectionUnit, errorMessage)
throw new Error(errorMessage)
}

const boundary = boundaryData[0]
const boundaryCoordinates = boundary.geometry.coordinates[0]
const boundaryCoordinates = boundaryData.coordinates[0][0]
// reorder so (lon, lat)'s become (lat, lon)'s
boundaryCoordinates.map(row=>row.reverse())

// set Boundary with payload
BoundaryPayLoad = {
source: boundary.properties.description,
name: boundary.properties.Name,
source: boundaryData.description,
name: slug,
boundary: boundaryCoordinates
}
setViewLocationsHref(selectionUnit, boundaryCoordinates)
Expand Down
11 changes: 5 additions & 6 deletions tests/external_api/urls.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from localcontexts.urls import urlpatterns
from django.urls import path

from . views import (
native_land_map_list,
native_land_boundary_response
)
from . views import native_land_map_list


class UrlsWithMockedExternalApi:
urlpatterns = urlpatterns + [
path('wp-json/nativeland/v1/map-list/', native_land_map_list),
path('wp-json/nativeland/v1/api/index.php', native_land_boundary_response)
path(
'biocodellc/localcontexts_json/main/data/nativeland_slug_name_list.json',
native_land_map_list
),
]
10 changes: 0 additions & 10 deletions tests/external_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,3 @@ def native_land_map_list(request):
json_data = open('tests/fixtures/native_land_map_list.json')
data = json.load(json_data)
return JsonResponse(data, safe=False)


def native_land_boundary_response(request):
"""
This view is called when getting specific boundary data
for a single Native Land territory
"""
json_data = open('tests/fixtures/native_land_boundary_response.json')
data = json.load(json_data)
return JsonResponse(data, safe=False)
12 changes: 3 additions & 9 deletions tests/fixtures/native_land_map_list.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
[
{
"post_title": "Prinzus",
"post_id": 27229,
"category": "Territories",
"name": "Prinzus",
"slug": "prinzus"
},
{
"post_title": "Bawikas",
"post_id": 27226,
"category": "Territories",
"name": "Bawikas",
"slug": "bawikas"
},
{
"post_title": "Panamakas",
"post_id": 27222,
"category": "Territories",
"name": "Panamakas",
"slug": "panamakas"
}
]
4 changes: 2 additions & 2 deletions tests/functional/test_cleared_boundaries_are_not_saved_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def test_that_cleared_project_boundaries_are_not_saved_for_a_community(self):
self.accept_cookies()

# select NLD territory
selected_territory = 'Panamakas'
selected_territory = 'panamakas'
self.select_specific_nld_territory(selected_territory)

# clear boundary
Expand Down Expand Up @@ -160,7 +160,7 @@ def test_that_cleared_project_boundaries_are_not_saved_for_an_institution(self):
self.accept_cookies()

# select NLD territory
selected_territory = 'Panamakas'
selected_territory = 'panamakas'
self.select_specific_nld_territory(selected_territory)

# clear boundary
Expand Down
Loading
Loading