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

[GWELLS-2055] FEATURE** Search by licences #2075

Merged
merged 3 commits into from
Dec 12, 2023
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
43 changes: 37 additions & 6 deletions app/backend/wells/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from django import forms
from django.core.exceptions import FieldDoesNotExist
from django.db import connection
from django.http import HttpRequest, QueryDict
from django.contrib.gis.geos import GEOSException, Polygon, GEOSGeometry, Point
from django.contrib.gis.gdal import GDALException
Expand All @@ -42,6 +43,7 @@
BoundaryEffectCode,
AnalysisMethodCode
)
from wells.constants import WELL_TAGS

logger = logging.getLogger('wells_filters')

Expand Down Expand Up @@ -346,7 +348,10 @@ class WellListFilter(AnyOrAllFilterSet):
method='filter_licenced_status',
label='Licence status'
)

licence_number = filters.NumberFilter(field_name='licence_number',
method="filter_licence_number",
label="Licence Number"
)
class Meta:
model = Well
fields = [
Expand Down Expand Up @@ -416,6 +421,7 @@ class Meta:
'legal_range',
'legal_section',
'legal_township',
'licence_number',
'licenced_status',
'liner_diameter',
'liner_from',
Expand Down Expand Up @@ -509,11 +515,37 @@ def filter_street_address_or_city(self, queryset, name, value):
return queryset.filter(Q(street_address__icontains=value) |
Q(city__icontains=value))

def filter_licence_number(self, queryset, name, value):
raw_query = """
SELECT DISTINCT
wl.well_id
FROM well_licences wl
LEFT JOIN aquifers_waterrightslicence aw
ON aw.wrl_sysid = wl.waterrightslicence_id
WHERE aw.licence_number = %s
"""
params = [value]
try:
if int(value):
with connection.cursor() as cursor:
cursor.execute(raw_query, params)
result = cursor.fetchall()
well_ids = [row[0] for row in result]
print(well_ids)
return queryset.filter(well_tag_number__in=well_ids)
except:
pass
logger.warning(f"[FILTER SEARCH]: invalid licence_number '{value}' was inputted.")
return queryset.filter(well_tag_number=None)

def filter_by_document_type(self, queryset, name, value):
filter_condition = {f"{value.lower().replace(' ', '_')}__gt": 0}
attachments = WellAttachment.objects.filter(**filter_condition).values_list('well_tag_number', flat=True)
attachments = list(map(int, attachments))
return queryset.filter(well_tag_number__in=attachments)
if any(value == entry["value"] for entry in WELL_TAGS):
filter_condition = {f"{value.lower().replace(' ', '_')}__gt": 0}
attachments = WellAttachment.objects.filter(**filter_condition).values_list('well_tag_number', flat=True)
attachments = list(map(int, attachments))
return queryset.filter(well_tag_number__in=attachments)
logger.warning(f"[FILTER SEARCH]: invalid document_type '{value}' was inputted.")
return queryset.filter(well_tag_number=None)

def filter_combined_legal(self, queryset, name, value):
lookups = (
Expand Down Expand Up @@ -729,7 +761,6 @@ class WellListOrderingFilter(OrderingFilter):
for field in Well._meta.get_fields()
if field.many_to_many and not field.auto_created
}

def get_ordering(self, request, queryset, view):
ordering = super().get_ordering(request, queryset, view)
updated_ordering = []
Expand Down
26 changes: 23 additions & 3 deletions app/backend/wells/serializers_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""
import logging
from decimal import Decimal

from django.db import connection
from rest_framework import serializers
from django.contrib.gis.geos import Point

Expand Down Expand Up @@ -142,7 +142,7 @@ def create(self, validated_data):

class WellListSerializerV2(serializers.ModelSerializer):
"""Serializes a well record"""

licence_number = serializers.SerializerMethodField()
legal_pid = serializers.SerializerMethodField()
drilling_company = serializers.ReadOnlyField(
source='company_of_person_responsible.org_guid')
Expand Down Expand Up @@ -286,9 +286,29 @@ class Meta:
"static_water_level",
"alternative_specs_submitted",
"technical_report",
"drinking_water_protection_area_ind"
"drinking_water_protection_area_ind",
"licence_number"
)
def get_licence_number(self, obj):
with connection.cursor() as cursor:
licence_num_query = """
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm looking for context on why we are using raw SQL here? I understand there are situations where routing around the model layer and using raw SQL is necessary.

SELECT ARRAY_AGG(aw.licence_number) AS licence_numbers
FROM well_licences wl
LEFT JOIN aquifers_waterrightslicence aw ON aw.wrl_sysid = wl.waterrightslicence_id
WHERE wl.well_id = %s
GROUP BY wl.well_id
"""
cursor.execute(licence_num_query, [obj.well_tag_number])
row = cursor.fetchone()
if row:
return row[0]
else:
return None

def to_representation(self, instance):
representation = super().to_representation(instance)
representation['licence_number'] = self.get_licence_number(instance)
return representation

class WellListAdminSerializerV2(WellListSerializerV2):
class Meta:
Expand Down
3 changes: 3 additions & 0 deletions app/frontend/src/wells/components/AdvancedSearchForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ const ADDITIONAL_FILTER_SECTIONS = [
'ownerCity',
'ownerProvince',
'ownerPostalCode' ] },
{ header: "Licence Information",
fields:
[ 'licenceNumber'] },
{ header: 'Well location',
fields:
[ 'legalBlock',
Expand Down
3 changes: 2 additions & 1 deletion app/frontend/src/wells/components/SearchColumnSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ const RESULT_COLUMNS = [
'alterationStartDate',
'alterationEndDate',
'decomissionStartDate',
'decomissionEndDate'
'decomissionEndDate',
'licenceNumber',
]

export default {
Expand Down
10 changes: 9 additions & 1 deletion app/frontend/src/wells/components/SearchResults.vue
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@
<template v-else-if="column.param === 'legal_pid'">
{{ row[column.param] }}
</template>
<template v-else-if="column.param === 'licence_number'">
<span v-for="(licence, index) in row.licence_number">
<a :href="LICENCE_URL + licence">
{{ licence }}{{ index + 1 < row.licence_number.length ? ', ' : '' }}
</a>
</span>
</template>
<template v-else>
{{ row[column.param] | defaultFormat }}
</template>
Expand Down Expand Up @@ -154,7 +161,8 @@ export default {
{ value: 10, text: '10' },
{ value: 25, text: '25' },
{ value: 50, text: '50' }
]
],
LICENCE_URL: 'https://j200.gov.bc.ca/pub/ams/Default.aspx?PossePresentation=AMSPublic&PosseObjectDef=o_ATIS_DocumentSearch&PosseMenuName=WS_Main&Criteria_LicenceNumber='
}
},
computed: {
Expand Down
6 changes: 6 additions & 0 deletions app/frontend/src/wells/components/mixins/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ const SEARCH_FIELDS = {
]
},
well: { param: 'well', label: 'Well tag or ID plate number', type: 'text' },
licenceNumber: {
param: "licence_number",
label: "Licence number",
type: "number",
resultLabel: "Licence number(s)"
},
wellDocumentType: {
param: "well_document_type",
label: "Contains document type",
Expand Down