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

Autocomplete fixes 2 #992

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 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
18 changes: 18 additions & 0 deletions backend-project/small_eod/autocomplete/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,24 @@ def validate_item(self, item):
self.assertEqual(item["id"], self.obj.id)
self.assertEqual(item["name"], self.obj.name)

def test_suggests_related(self):
institution_a = InstitutionFactory(name="institution_a")
institution_b = InstitutionFactory(name="institution_b")
InstitutionFactory(name="institution_c")

# Make the case audit the 2nd institution - it's unlikely to appear
# at the top of the results just by coincidence.
case = CaseFactory(audited_institutions=[institution_b])

# Match all - the related institution should appear at the top.
resp = self.get_response_for_query("institution", case=case.id)
self.assertEqual(resp.data['results'][0]['id'], institution_b.id)

# Match a specific, non-related item.
# The related institution should not be present.
resp = self.get_response_for_query("institution_a", case=case.id)
self.assertEqual([r['id'] for r in resp.data['results']], [institution_a.id])


class TagAutocompleteViewSetTestCase(ReadOnlyViewSetMixin, SearchQueryMixin, TestCase):
basename = "autocomplete_tag"
Expand Down
19 changes: 17 additions & 2 deletions backend-project/small_eod/autocomplete/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django_filters.rest_framework import DjangoFilterBackend
from django.db import models
from rest_framework import viewsets

from ..administrative_units.filterset import AdministrativeUnitFilterSet
Expand Down Expand Up @@ -32,7 +33,6 @@
UserAutocompleteSerializer,
)


class AdministrativeUnitAutocompleteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = AdministrativeUnit.objects.only("id", "name").all()
serializer_class = AdministrativeUnitAutocompleteSerializer
Expand Down Expand Up @@ -83,11 +83,26 @@ class FeatureOptionAutocompleteViewSet(viewsets.ReadOnlyModelViewSet):


class InstitutionAutocompleteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Institution.objects.only("id", "name").all()
serializer_class = InstitutionAutocompleteSerializer
filter_backends = (DjangoFilterBackend,)
filterset_class = InstitutionFilterSet

def get_queryset(self):
req = self.request
related_case_id = req.GET.get('case', None)
if related_case_id is None:
qs = Institution.objects.all()
else:
# Put related institutions at the beginning of the list.
qs = Institution.objects.annotate(
related=models.Case(
models.When(case=related_case_id, then=True),
default=False,
output_field=models.BooleanField()
)
).order_by('-related')
return qs.only("id", "name")


class TagAutocompleteViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Tag.objects.only("id", "name").all()
Expand Down
4 changes: 2 additions & 2 deletions backend-project/small_eod/search/tests/mixins.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
class SearchQueryMixin:
def get_response_for_query(self, query):
def get_response_for_query(self, query, **data):
self.login_required()
return self.client.get(
self.get_url(name="list", **self.get_extra_kwargs()),
data={"query": query},
data={"query": query, **data},
)

def assertResultEqual(self, response, items):
Expand Down
81 changes: 58 additions & 23 deletions frontend-project/src/components/FetchSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ export function FetchSelect<
value?: ValueType;
labelField?: SearchField;
}) {
const [isFetching, setFetching] = useState(false);
const [shownOptions, setShownOptions] = useState<OptionsType[]>([]);
const [isFetchingRelatedItems, setFetchingRelatedItems] = useState(false);
const [relatedItems, setRelatedItems] = useState<OptionsType[]>([]);
const [isFetchingAutocompleteOptions, setFetchingAutocompleteOptions] = useState(false);
const [autocompleteOptions, setAutocompleteOptions] = useState<OptionsType[]>([]);
const { debouncePromise } = useDebounce();
const searchField = labelField || 'name';
Expand All @@ -59,56 +60,90 @@ export function FetchSelect<
);
}

// Call the autocomplete api once to convert field ids, fetched from the object's detail endpoint,
// into human readable names.
// Call the autocomplete api to convert field ids, fetched from the object's detail endpoint,
// into human readable names. Expected to be called once per select field.
// Uses the autocomplete API for (id => name) mapping for consistency - subsequent calls, triggered
// by user input, will receive (id, name) pairs from the same API.
function fetchRelatedItems(arrayValue: Array<number>) {
return autocompleteFunction({
query: QQ.in('id', arrayValue),
pageSize: 10,
}).then(extractOptionsFromApiResults);
}

// Request autocomplete suggestions from the backend.
function fetchSuggestions(search: string) {
return autocompleteFunction({
query: QQ.icontains(searchField, search),
pageSize: 10,
}).then(extractOptionsFromApiResults);
}

useEffect(() => {
// 1. Map related items' ids (e.g. the current channel id) to a human readable name.

// Convert current value to an array.
// For multiselect fields, the value will already be an array.
const arrayValue = Array.isArray(value) ? value : [value];

if (
typeof value === 'undefined' ||
value === null ||
arrayValue.length === 0 ||
// Tags are already provided as human readable names - no need to fetch anything.
mode === 'tags'
)
return;
setShownOptions([]);
setFetching(true);
) {
// Noop.
// Nothing to fetch.
} else {
setRelatedItems([]);
setFetchingRelatedItems(true);

autocompleteFunction({
query: QQ.in('id', arrayValue),
pageSize: 10,
})
// NOTE(rwakulszowa): `ValueType` is a bit complicated - converting it to
Copy link
Member

Choose a reason for hiding this comment

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

@kuskoman could you provide comment there?

// an array of numbers in a type safe way may require refactoring the
// code a bit, hence a manual cast.
fetchRelatedItems(arrayValue as Array<number>)
.then(autocompleteResults => {
setRelatedItems(autocompleteResults);
})
.catch(onError)
.finally(() => setFetchingRelatedItems(false));
}

// 2. Fetch an initial set of suggestions to display in the select component,
// before the user had a chance to type anything in the search field.
setAutocompleteOptions([]);
setFetchingAutocompleteOptions(true);

fetchSuggestions('')
.then(autocompleteResults => {
setShownOptions(extractOptionsFromApiResults(autocompleteResults));
setAutocompleteOptions(autocompleteResults);
})
.catch(onError)
.finally(() => setFetching(false));
.finally(() => setFetchingAutocompleteOptions(false));
}, []);

// Fetch (id, name) pairs matching the search string.
// Invoked on every keystroke, after a short delay.
const debounceFetcher = (search: string) => {
if (!search) return [];
setAutocompleteOptions([]);
setFetching(true);
setFetchingAutocompleteOptions(true);

return debouncePromise(() =>
autocompleteFunction({
query: QQ.icontains(searchField, search),
pageSize: 10,
})
fetchSuggestions(search)
.then(autocompleteResults => {
setAutocompleteOptions(extractOptionsFromApiResults(autocompleteResults));
setAutocompleteOptions(autocompleteResults);
})
.catch(onError)
.finally(() => setFetching(false)),
.finally(() => setFetchingAutocompleteOptions(false)),
);
};

// All options to display to the user.
// Sets may overlap - remove duplicates to avoid duplicate rendering issues.
const options = sortBy(unionBy(shownOptions, autocompleteOptions, 'value'), 'label');
const options = sortBy(unionBy(relatedItems, autocompleteOptions, 'value'), 'label');

const isFetching = isFetchingRelatedItems || isFetchingAutocompleteOptions;

return (
<Select<OptionsType>
Expand Down