From 484ee6230410e94eef6b2e378bd6bb169f3c8e95 Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Wed, 11 Nov 2026 10:48:40 -0700 Subject: [PATCH] Search the Aliquots and Samples lists by field Closes #211. Co-Authored-By: Claude Sonnet 5.5 --- docs/README.md | 1 + krill/sample/README.md | 39 ++ krill/sample/list_filters.py | 264 ++++++++++++ krill/sample/tests/test_field_filters.py | 462 +++++++++++++++++++++ krill/sample/tests/test_views.py | 6 +- krill/sample/views/list.py | 90 ++-- krill/static/krill/style.css | 202 +++++++++ krill/templates/sample/_filter_chips.html | 12 + krill/templates/sample/_filter_fields.html | 34 ++ krill/templates/sample/list.html | 93 ++--- 10 files changed, 1107 insertions(+), 96 deletions(-) create mode 100644 krill/sample/README.md create mode 100644 krill/sample/list_filters.py create mode 100644 krill/sample/tests/test_field_filters.py create mode 100644 krill/templates/sample/_filter_chips.html create mode 100644 krill/templates/sample/_filter_fields.html diff --git a/docs/README.md b/docs/README.md index 3904d55..cbfe316 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,7 @@ - [Database Setup](database.md) - SQLite and PostgreSQL configuration ## Using Krill +- [Searching samples and aliquots](../krill/sample/README.md) - search the lists, filter by field, chips and pills - [Reports and storage audits](../krill/reports/README.md) - spot-check storage, resume and review audits, alerts ## Deployment (`deployment/`) diff --git a/krill/sample/README.md b/krill/sample/README.md new file mode 100644 index 0000000..32f272f --- /dev/null +++ b/krill/sample/README.md @@ -0,0 +1,39 @@ +# Samples and aliquots + +A **sample** is a cell line or other specimen. An **aliquot** is one portion of it. This page covers finding things in the lists. + +## Searching the Aliquots list + +Open **Samples > Aliquots**. The toolbar is one row: a search box, **Sample**, **Passage**, **More filters**, **Search** and **New Aliquot**. + +### Search everything +The first box looks in every field (sample name, experiment, notes, type, disposition, passage, lab member, sample date, box, freezer and aliquot number). Type several words and **every word must match something**, so `hela p8` finds the p8 aliquots of HeLa. Put words in "quotes" to match them as one phrase. A number, with or without `#`, also matches the aliquot number. + +### Search by field +Fill in a field to aim at it. **Every field you fill in must match**, so Sample `HeLa` with Passage `P8` gives only the P8 aliquots of HeLa. + +| Field | Where | How it matches | +|---|---|---| +| Sample | toolbar | part of the sample name, ignoring case; every word must appear | +| Passage | toolbar | **exactly**, ignoring case: `P8` finds `P8` and `p8`, not `P80`. End with `*` to match the start: `P8*` finds `P8`, `P80`, `P8+3` | +| Lab member | More filters | part of a name, username or initials | +| Date from / Date to | More filters | on or after, and on or before. The same date in both means that day. Aliquots with no sample date are never included, and the page says how many were left out | +| Location | More filters | part of a freezer or box name | +| Aliquot number | More filters | the exact number, with or without `#` | +| Disposition, Type | More filters | pick one | + +**More filters** opens by itself when one of its fields is in use, and shows how many are. + +### Chips, clearing and sharing +Each active filter shows as a chip under the toolbar, for example "Passage is P8". Click its **x** to remove just that one. With two or more chips, **Clear all** removes every filter, the search words and the pills, and keeps how the list is sorted. When nothing matches, the page lists the filters in use, each with a link that removes it. + +The search is kept in the page address, so you can bookmark it or send the link. The field parameters are `f_sample`, `f_passage`, `f_member`, `f_date_from`, `f_date_to`, `f_location` and `f_number`, plus the existing `disposition`, `aliquot_type` and `q`. + +### Pills +Two on/off pills sit under the toolbar: **Checked out by me** (with a count) and **Hide exhausted**. They combine with everything above. + +## Searching the Samples list +The Samples list has the search box plus **Source**, **Experiment** and **Notes** fields (all part-of matches), the **Low count** pill, and the same chips and Clear all. + +## For developers +Each list describes its filter fields once in `sample/list_filters.py` (a `FilterSpec`: name, label, kind, hint, inline or in the More panel). From that one description come the query filters, the inputs (`templates/sample/_filter_fields.html`), the chips and Clear all (`_filter_chips.html`) and the empty-result suggestions. To add a field to a list, add a `FilterField`; to give another list the same bar, define a spec for it and call `spec.apply` and `spec.bind` from its view. Treat the parameter names as stable, because people bookmark them. Tests are in `sample/tests/test_field_filters.py`. diff --git a/krill/sample/list_filters.py b/krill/sample/list_filters.py new file mode 100644 index 0000000..a041b14 --- /dev/null +++ b/krill/sample/list_filters.py @@ -0,0 +1,264 @@ +"""Field filters for list pages ("Sample X with Passage Y"). + +Each list describes its filter fields once, as a FilterSpec. From that one description come: + - the query filters (spec.apply), + - the inputs on the page (spec.bind(request).inline / .more), + - the removable chips, the Clear all link, and the suggestions shown when nothing matches. + +Every filled-in field must match (AND). The query parameter names are part of the page address, so +people can bookmark and share a search; treat them as stable. + +Matching rules: + contains case-insensitive; every word must appear, and "quoted words" keep their spacing + exact the whole value, ignoring case + passage exact, ignoring case; a trailing * matches the start instead (P8* finds P8, P80, P8+3) + number an exact aliquot number, with or without a leading # + date_from on or after; date_to on or before (aliquots with no date never match either) + select one of a fixed list of choices +""" +import re +from dataclasses import dataclass +from datetime import date +from typing import Callable, Optional, Tuple + +from django.db.models import Q + +CONTAINS = 'contains' +EXACT = 'exact' +PASSAGE = 'passage' +NUMBER = 'number' +DATE_FROM = 'date_from' +DATE_TO = 'date_to' +SELECT = 'select' + +DATE_KINDS = (DATE_FROM, DATE_TO) +_WORDS = re.compile(r'"([^"]+)"|(\S+)') + + +def split_words(text): + """'hela p8 "cell line"' -> ['hela', 'p8', 'cell line']""" + return [quoted or word for quoted, word in _WORDS.findall(text or '') if (quoted or word).strip()] + + +def parse_date(value): + try: + return date.fromisoformat(value) + except (TypeError, ValueError): + return None + + +@dataclass(frozen=True) +class FilterField: + param: str # query parameter, e.g. 'f_sample' + label: str # shown next to the input and in chips + kind: str + paths: Tuple[str, ...] = () # model lookups to search (OR across paths) + placeholder: str = '' + hint: str = '' # one line under the label in the More panel + inline: bool = False # shown in the toolbar row (otherwise in More) + verb: str = '' # chip wording override, e.g. 'contain' for "Notes contain x" + choices: Optional[Callable] = None # SELECT: () -> [(value, label)] + select_filter: Optional[Callable] = None # SELECT: (queryset, value) -> queryset + + +@dataclass(frozen=True) +class Chip: + text: str + remove_url: str + + +class BoundField: + """A field with its current value, ready for a template.""" + + def __init__(self, field, value): + self.field = field + self.param = field.param + self.label = field.label + self.kind = field.kind + self.value = value + self.placeholder = field.placeholder + self.hint = field.hint + self.is_select = field.kind == SELECT + self.is_date = field.kind in DATE_KINDS + self.choices = [] + if self.is_select: + self.choices = [(v, label, str(v) == value) for v, label in field.choices()] + + +class FilterBar: + def __init__(self, inline, more, chips, clear_all_url): + self.inline = inline + self.more = more + self.chips = chips + self.clear_all_url = clear_all_url + self.more_active = sum(1 for f in more if f.value) + # The rules for the inline fields, repeated at the top of the More panel + self.inline_hints = [(f.label, f.hint) for f in inline if f.hint] + self.has_filters = bool(chips) + self.show_clear_all = len(chips) >= 2 + + +class FilterSpec: + def __init__(self, fields, reset_params=()): + self.fields = list(fields) + # Other parameters that "Clear all" also removes (the search phrase, pills, ...) + self.reset_params = tuple(reset_params) + + # --- reading the request -------------------------------------------------- + + @staticmethod + def value_of(query, field): + return (query.get(field.param) or '').strip() + + def active(self, query): + """[(field, value)] for the fields that are filled in and mean something.""" + result = [] + for field in self.fields: + value = self.value_of(query, field) + if not value: + continue + if field.kind in DATE_KINDS and parse_date(value) is None: + continue + if field.kind == PASSAGE and value.rstrip('*').strip() == '': + continue + if field.kind == SELECT and not self._select_matches(field, value): + continue + result.append((field, value)) + return result + + @staticmethod + def _select_matches(field, value): + return any(str(v) == value for v, _ in field.choices()) + + # --- filtering ------------------------------------------------------------ + + def apply(self, queryset, query, skip_kinds=(), only_kinds=None): + for field, value in self.active(query): + if field.kind in skip_kinds or (only_kinds is not None and field.kind not in only_kinds): + continue + queryset = self._filter(queryset, field, value) + return queryset + + @staticmethod + def _filter(queryset, field, value): + kind = field.kind + if kind == CONTAINS: + for word in split_words(value): + match = Q() + for path in field.paths: + match |= Q(**{f'{path}__icontains': word}) + queryset = queryset.filter(match) + return queryset + if kind == EXACT: + match = Q() + for path in field.paths: + match |= Q(**{f'{path}__iexact': value}) + return queryset.filter(match) + if kind == PASSAGE: + path = field.paths[0] + if value.endswith('*'): + return queryset.filter(**{f'{path}__istartswith': value.rstrip('*').strip()}) + return queryset.filter(**{f'{path}__iexact': value}) + if kind == NUMBER: + number = value.lstrip('#') + return queryset.filter(pk=int(number)) if number.isdigit() else queryset.none() + if kind == DATE_FROM: + return queryset.filter(**{f'{field.paths[0]}__gte': parse_date(value)}) + if kind == DATE_TO: + return queryset.filter(**{f'{field.paths[0]}__lte': parse_date(value)}) + if kind == SELECT: + return field.select_filter(queryset, value) + return queryset + + # --- what the page shows -------------------------------------------------- + + @staticmethod + def chip_text(field, value): + kind = field.kind + if kind in DATE_KINDS: + return f'{field.label} {value}' + if kind == SELECT: + label = next((label for v, label in field.choices() if str(v) == value), value) + return f'{field.label}: {label}' + if kind == PASSAGE: + return f'{field.label} starts with {value.rstrip("*").strip()}' if value.endswith('*') else f'{field.label} is {value}' + if kind in (EXACT, NUMBER): + return f'{field.label} is {value}' + return f'{field.label} {field.verb or "contains"} {value}' + + @staticmethod + def url_without(request, *params): + """The current address minus some parameters, back on page 1.""" + query = request.GET.copy() + query.pop('page', None) + for param in params: + query.pop(param, None) + encoded = query.urlencode() + return f'?{encoded}' if encoded else request.path + + def bind(self, request, extra_chips=()): + """Everything a template needs. extra_chips are (text, parameter) pairs for filters this spec + does not own, such as the search phrase; they are shown first.""" + chips = [Chip(text, self.url_without(request, param)) for text, param in extra_chips] + for field, value in self.active(request.GET): + chips.append(Chip(self.chip_text(field, value), self.url_without(request, field.param))) + everything = [f.param for f in self.fields] + list(self.reset_params) + bound = [BoundField(field, self.value_of(request.GET, field)) for field in self.fields] + return FilterBar( + inline=[b for b in bound if b.field.inline], + more=[b for b in bound if not b.field.inline], + chips=chips, + clear_all_url=self.url_without(request, *everything), + ) + + +# --- the lists --------------------------------------------------------------- + +def _disposition_choices(): + from .models.aliquot import AliquotDisposition + return list(AliquotDisposition.DISPOSITION_CHOICES) + + +def _type_choices(): + from .models.aliquot import AliquotType + return [(str(t.pk), t.name) for t in AliquotType.objects.order_by('name')] + + +ALIQUOT_FILTERS = FilterSpec( + [ + FilterField('f_sample', 'Sample', CONTAINS, ('sample__name',), inline=True, + placeholder='Sample', hint='Part of the sample name.'), + FilterField('f_passage', 'Passage', PASSAGE, ('passage',), inline=True, + placeholder='Passage', + hint='Matches exactly, ignoring case: P8 finds P8 and p8, not P80. End with * to match the start, for example P8*.'), + FilterField('f_member', 'Lab member', CONTAINS, + ('lab_member_initials', 'lab_member__first_name', 'lab_member__last_name', 'lab_member__username'), + placeholder='Name or initials', hint='Name or initials.'), + FilterField('f_date_from', 'Date from', DATE_FROM, ('sample_date',), + hint='On or after. Aliquots with no sample date are left out.'), + FilterField('f_date_to', 'Date to', DATE_TO, ('sample_date',), + hint='On or before. Aliquots with no sample date are left out.'), + FilterField('f_location', 'Location', CONTAINS, + ('location__box__name', 'location__box__rack__shelf__device__name'), + placeholder='Freezer or box', hint='Part of a freezer or box name.'), + FilterField('f_number', 'Aliquot number', NUMBER, ('pk',), + placeholder='e.g. 1234', hint='The exact aliquot number.'), + FilterField('disposition', 'Disposition', SELECT, choices=_disposition_choices, + select_filter=lambda qs, value: qs.filter(disposition__disposition_type=value)), + FilterField('aliquot_type', 'Type', SELECT, choices=_type_choices, + select_filter=lambda qs, value: qs.filter(aliquot_type_id=int(value))), + ], + reset_params=('q', 'sample', 'checked_out_by', 'hide_finished', 'low_count'), +) + +SAMPLE_FILTERS = FilterSpec( + [ + FilterField('f_source', 'Source', CONTAINS, ('source__name',), inline=True, + placeholder='Source', hint='Part of the source name.'), + FilterField('f_experiment', 'Experiment', CONTAINS, ('experiment',), inline=True, + placeholder='Experiment', hint='Part of the experiment text.'), + FilterField('f_notes', 'Notes', CONTAINS, ('notes',), inline=True, verb='contain', + placeholder='Notes', hint='Part of the notes.'), + ], + reset_params=('q', 'checked_out_by', 'hide_finished', 'low_count'), +) diff --git a/krill/sample/tests/test_field_filters.py b/krill/sample/tests/test_field_filters.py new file mode 100644 index 0000000..37b1ff6 --- /dev/null +++ b/krill/sample/tests/test_field_filters.py @@ -0,0 +1,462 @@ +import datetime +from types import SimpleNamespace + +from django.contrib.auth import get_user_model +from django.http import QueryDict +from django.urls import reverse + +from .. import list_filters as lf +from ..models.aliquot import Aliquot, AliquotDisposition, AliquotType +from ..models.sample import Sample +from .test_views import SampleViewTest + +User = get_user_model() + + +class FilterFixture(SampleViewTest): + def setUp(self): + super().setUp() + Aliquot.objects.all().delete() + self.client.force_login(self.user) + self.url = reverse('sample:sample_list') + self.hela = Sample.objects.create(name='HeLa S3', source=self.source, experiment='Exp 12', notes='thawed twice') + self.jurkat = Sample.objects.create(name='Jurkat', source=self.source) + self.in_use = AliquotDisposition.objects.get_or_create(name='In Use', defaults={'disposition_type': 'in_use'})[0] + + def make(self, sample=None, **kwargs): + kwargs.setdefault('aliquot_type', self.aliquot_type) + kwargs.setdefault('disposition', self.stored_disposition) + return Aliquot.objects.create(sample=sample or self.hela, **kwargs) + + def names(self, response): + return [a.pk for a in response.context['items']] + + def list(self, **params): + return self.client.get(self.url, {'type': 'aliquot', **params}) + + def ids(self, **params): + return sorted(self.names(self.list(**params))) + + +class ParsingHelpersTest(FilterFixture): + def test_split_words_keeps_quoted_phrases_together(self): + self.assertEqual(lf.split_words('hela p8'), ['hela', 'p8']) + self.assertEqual(lf.split_words('hela "cell line" p8'), ['hela', 'cell line', 'p8']) + self.assertEqual(lf.split_words(' '), []) + self.assertEqual(lf.split_words('"open quote'), ['"open', 'quote']) + + def test_parse_date(self): + self.assertEqual(lf.parse_date('2025-03-01'), datetime.date(2025, 3, 1)) + for bad in ('', 'x', '2025-13-01', None): + self.assertIsNone(lf.parse_date(bad)) + + def test_url_without_drops_the_parameter_and_the_page_but_keeps_the_rest(self): + request = SimpleNamespace(GET=QueryDict('type=aliquot&f_sample=hela&sort=passage&order=desc&page=3'), path='/samples/list/') + self.assertEqual( + lf.FilterSpec.url_without(request, 'f_sample'), + '?type=aliquot&sort=passage&order=desc') + only = SimpleNamespace(GET=QueryDict('page=2'), path='/samples/list/') + self.assertEqual(lf.FilterSpec.url_without(only), '/samples/list/') + + +class SampleFieldTest(FilterFixture): + def test_contains_ignoring_case_and_every_word_must_appear(self): + a, b = self.make(self.hela), self.make(self.jurkat) + self.assertEqual(self.ids(f_sample='hela'), [a.pk]) + self.assertEqual(self.ids(f_sample='S3 he'), [a.pk]) # both words, any order + self.assertEqual(self.ids(f_sample='jurk'), [b.pk]) + self.assertEqual(self.ids(f_sample='zzz'), []) + + def test_a_quoted_phrase_is_kept_together(self): + a = self.make(self.hela) + self.assertEqual(self.ids(f_sample='"HeLa S3"'), [a.pk]) + self.assertEqual(self.ids(f_sample='"S3 HeLa"'), []) + + +class PassageFieldTest(FilterFixture): + def setUp(self): + super().setUp() + self.p8 = self.make(passage='p8') + self.p80 = self.make(passage='p80') + self.p8_3 = self.make(passage='P8+3') + self.p9 = self.make(passage='p9') + self.none = self.make(passage='') + + def test_exact_ignoring_case_so_p8_does_not_match_p80(self): + self.assertEqual(self.ids(f_passage='p8'), [self.p8.pk]) + self.assertEqual(self.ids(f_passage='P8'), [self.p8.pk]) + + def test_a_trailing_star_matches_the_start(self): + self.assertEqual(self.ids(f_passage='P8*'), sorted([self.p8.pk, self.p80.pk, self.p8_3.pk])) + self.assertEqual(self.ids(f_passage='p9*'), [self.p9.pk]) + + def test_surrounding_spaces_are_ignored(self): + self.assertEqual(self.ids(f_passage=' p8 '), [self.p8.pk]) + + def test_a_lone_star_or_blank_is_not_a_filter(self): + everything = sorted(a.pk for a in Aliquot.objects.all()) + self.assertEqual(self.ids(f_passage='*'), everything) + self.assertEqual(self.ids(f_passage=' '), everything) + self.assertEqual(self.list(f_passage='*').context['filter_bar'].chips, []) + + def test_the_search_everything_box_is_unchanged_for_loose_matching(self): + self.assertEqual(self.ids(q='p8'), sorted([self.p8.pk, self.p80.pk, self.p8_3.pk])) + + +class OtherFieldsTest(FilterFixture): + def test_lab_member_by_initials_name_and_username(self): + ada = User.objects.create_user(username='alove', first_name='Ada', last_name='Lovelace', password='x') + by_user = self.make(lab_member=ada) + by_initials = self.make(lab_member_initials='XYZ') + self.make() + self.assertEqual(self.ids(f_member='lovelace'), [by_user.pk]) + self.assertEqual(self.ids(f_member='ada love'), [by_user.pk]) # first and last name together + self.assertEqual(self.ids(f_member='alove'), [by_user.pk]) + self.assertEqual(self.ids(f_member='xyz'), [by_initials.pk]) + + def test_location_matches_freezer_or_box(self): + placed, unplaced = self.make(), self.make() + placed.store_in_location(self.box, 1, 1) + self.assertEqual(self.ids(f_location='test device'), [placed.pk]) + self.assertEqual(self.ids(f_location='box'), [placed.pk]) + self.assertEqual(self.ids(f_location='nowhere'), []) + + def test_aliquot_number_is_exact(self): + target = self.make() + self.make() + self.assertEqual(self.ids(f_number=str(target.pk)), [target.pk]) + self.assertEqual(self.ids(f_number=f'#{target.pk}'), [target.pk]) + self.assertEqual(self.ids(f_number=str(target.pk) + '0'), []) + self.assertEqual(self.ids(f_number='abc'), []) + + def test_disposition_and_type_selects_still_filter(self): + stored = self.make() + in_use = self.make(disposition=self.in_use) + other_type = AliquotType.objects.create(name='Pellet') + pellet = self.make(aliquot_type=other_type) + self.assertEqual(self.ids(disposition='in_use'), [in_use.pk]) + self.assertEqual(self.ids(aliquot_type=str(other_type.pk)), [pellet.pk]) + self.assertEqual(self.ids(disposition='nonsense'), sorted([stored.pk, in_use.pk, pellet.pk])) + self.assertEqual(self.ids(aliquot_type='abc'), sorted([stored.pk, in_use.pk, pellet.pk])) + + +class DateFilterTest(FilterFixture): + def setUp(self): + super().setUp() + d = datetime.date + self.early = self.make(sample_date=d(2025, 1, 10)) + self.mid = self.make(sample_date=d(2025, 3, 1)) + self.late = self.make(sample_date=d(2025, 6, 30)) + self.undated = self.make(sample_date=None) + + def test_from_only_is_on_or_after(self): + self.assertEqual(self.ids(f_date_from='2025-03-01'), sorted([self.mid.pk, self.late.pk])) + + def test_to_only_is_on_or_before(self): + self.assertEqual(self.ids(f_date_to='2025-03-01'), sorted([self.early.pk, self.mid.pk])) + + def test_the_same_date_twice_means_that_day(self): + self.assertEqual(self.ids(f_date_from='2025-03-01', f_date_to='2025-03-01'), [self.mid.pk]) + + def test_a_range(self): + self.assertEqual(self.ids(f_date_from='2025-02-01', f_date_to='2025-04-01'), [self.mid.pk]) + + def test_a_date_that_cannot_be_read_is_ignored(self): + response = self.list(f_date_from='not-a-date') + self.assertEqual(len(response.context['items']), 4) + self.assertEqual(response.context['filter_bar'].chips, []) + + def test_undated_aliquots_are_never_in_a_range_and_the_page_says_so(self): + response = self.list(f_date_from='2000-01-01') + self.assertNotIn(self.undated.pk, self.names(response)) + self.assertEqual(response.context['no_date_excluded'], 1) + self.assertContains(response, '1 aliquot with no sample date is excluded') + + def test_the_note_counts_only_what_the_other_filters_would_have_shown(self): + self.make(sample=self.jurkat, sample_date=None) + response = self.list(f_date_from='2000-01-01', f_sample='hela') + self.assertEqual(response.context['no_date_excluded'], 1) + self.assertContains(self.list(f_date_from='2000-01-01'), '2 aliquots with no sample date are excluded') + + def test_no_note_without_a_date_filter_or_with_nothing_excluded(self): + self.assertIsNone(self.list().context['no_date_excluded']) + self.undated.delete() + self.assertNotRegex(self.list(f_date_from='2000-01-01').content.decode(), + r'with no sample date (is|are) excluded') + + +class CombiningTest(FilterFixture): + def test_every_filled_field_must_match(self): + hit = self.make(self.hela, passage='p8') + self.make(self.hela, passage='p9') + self.make(self.jurkat, passage='p8') + self.assertEqual(self.ids(f_sample='hela', f_passage='p8'), [hit.pk]) + + def test_fields_combine_with_search_pills_and_disposition(self): + hit = self.make(self.hela, passage='p8') + self.make(self.hela, passage='p8', disposition=self.in_use) + self.assertEqual(self.ids(f_sample='hela', f_passage='p8', hide_finished='1', disposition='stored', q='hela'), [hit.pk]) + + def test_fields_survive_sorting_and_paging_parameters(self): + for i in range(3): + self.make(self.hela, passage=f'p{i}') + response = self.list(f_sample='hela', sort='passage', order='desc', page_size='20') + self.assertEqual([a.passage for a in response.context['items']], ['p2', 'p1', 'p0']) + + +class SearchEverythingTest(FilterFixture): + def test_every_word_must_match_something(self): + hit = self.make(self.hela, passage='p8') + self.make(self.hela, passage='p9') + self.make(self.jurkat, passage='p8') + self.assertEqual(self.ids(q='hela p8'), [hit.pk]) + + def test_words_can_match_different_fields(self): + ada = User.objects.create_user(username='ada', first_name='Ada', password='x') + hit = self.make(self.hela, lab_member=ada) + self.make(self.hela) + self.assertEqual(self.ids(q='hela ada'), [hit.pk]) + + def test_a_quoted_phrase_keeps_the_old_single_phrase_behaviour(self): + a = self.make(self.hela) + self.assertEqual(self.ids(q='"hela s3"'), [a.pk]) + self.assertEqual(self.ids(q='"s3 hela"'), []) + + def test_numbers_still_match_the_aliquot_number(self): + target = self.make() + self.assertEqual(self.ids(q=f'#{target.pk}')[0], target.pk) + + def test_other_lists_split_words_too(self): + from ..models.source import Source + Source.objects.create(name='Big Lab West') + Source.objects.create(name='Big Lab East') + response = self.client.get(self.url, {'type': 'source', 'q': 'big west'}) + self.assertEqual([s.name for s in response.context['items']], ['Big Lab West']) + + +class ChipsTest(FilterFixture): + def chips(self, **params): + return {c.text: c.remove_url for c in self.list(**params).context['filter_bar'].chips} + + def test_one_chip_per_field_with_its_rule(self): + chips = self.chips(f_sample='HeLa', f_passage='P8', f_member='ada', f_location='box', f_number='12', + f_date_from='2025-03-01', f_date_to='2025-04-01') + self.assertEqual(set(chips), { + 'Sample contains HeLa', 'Passage is P8', 'Lab member contains ada', 'Location contains box', + 'Aliquot number is 12', 'Date from 2025-03-01', 'Date to 2025-04-01'}) + + def test_prefix_passage_chip(self): + self.assertIn('Passage starts with P8', self.chips(f_passage='P8*')) + + def test_select_chips_use_the_label_and_name(self): + pellet = AliquotType.objects.create(name='Pellet') + chips = self.chips(disposition='in_use', aliquot_type=str(pellet.pk)) + self.assertEqual(set(chips), {'Disposition: In Use', 'Type: Pellet'}) + + def test_search_and_sample_filter_chips_come_first(self): + chips = list(self.chips(q='hela', sample=str(self.hela.pk), f_passage='p8')) + self.assertEqual(chips, ['"hela"', 'Sample: HeLa S3', 'Passage is p8']) + + def test_each_chip_removes_only_its_own_parameter_and_keeps_the_sort_and_resets_the_page(self): + chips = self.chips(f_sample='hela', f_passage='p8', sort='passage', order='desc', page='1') + url = chips['Sample contains hela'] + self.assertIn('f_passage=p8', url) + self.assertIn('sort=passage', url) + self.assertIn('order=desc', url) + self.assertNotIn('f_sample', url) + self.assertNotIn('page=', url) + + def test_chips_are_links_with_labels_for_screen_readers(self): + self.make(self.hela) + response = self.list(f_sample='hela') + self.assertContains(response, 'aria-label="Remove filter: Sample contains hela"') + + def test_clear_all_only_with_two_or_more_chips(self): + self.assertFalse(self.list(f_sample='hela').context['filter_bar'].show_clear_all) + self.assertNotContains(self.list(f_sample='hela'), 'Clear all') + response = self.list(f_sample='hela', f_passage='p8') + self.assertTrue(response.context['filter_bar'].show_clear_all) + self.assertContains(response, 'Clear all') + + def test_clear_all_resets_filters_search_and_pills_but_keeps_sort_and_list_type(self): + response = self.list(f_sample='hela', f_passage='p8', q='x', hide_finished='1', checked_out_by='me', + disposition='stored', sort='passage', order='desc', page_size='20', page='1') + url = response.context['filter_bar'].clear_all_url + for gone in ('f_sample', 'f_passage', 'q=', 'hide_finished', 'checked_out_by', 'disposition', 'page='): + self.assertNotIn(gone, url) + for kept in ('type=aliquot', 'sort=passage', 'order=desc', 'page_size=20'): + self.assertIn(kept, url) + + +class MorePanelTest(FilterFixture): + def test_inline_fields_and_hints_and_placeholders(self): + response = self.list() + self.assertContains(response, 'name="f_sample"') + # The placeholder is just the name; the rule is a tooltip and is repeated in the More panel + self.assertContains(response, 'placeholder="Passage"') + self.assertNotContains(response, 'placeholder="Passage (') + rule = 'Matches exactly, ignoring case: P8 finds P8 and p8, not P80. End with * to match the start, for example P8*.' + self.assertContains(response, f'title="{rule}"') + self.assertContains(response, f'

Passage: {rule}

') + self.assertContains(response, 'On or after. Aliquots with no sample date are left out.') + + def test_disposition_and_type_moved_into_the_panel(self): + html = self.list().content.decode() + start = html.index('id="filter-more-panel"') + panel = html[start:html.index('', start)] + for name in ('f_member', 'f_date_from', 'f_date_to', 'f_location', 'f_number', 'disposition', 'aliquot_type'): + with self.subTest(field=name): + self.assertIn(f'name="{name}"', panel) + row = html[html.index('class="toolbar-row"'):html.index('id="filter-more-panel"')] + self.assertNotIn('name="disposition"', row) + + def test_the_panel_is_closed_until_one_of_its_fields_is_used(self): + self.assertNotRegex(self.list().content.decode(), r'
2<') + + def test_the_form_keeps_the_pills_when_searching(self): + html = self.list(hide_finished='1', f_passage='p8').content.decode() + self.assertIn('', html) + self.assertIn('value="p8"', html) + + def test_new_aliquot_button_keeps_a_label_for_screen_readers(self): + self.assertContains(self.list(), 'aria-label="New Aliquot"') + + +class ToolbarLayoutTest(FilterFixture): + """The Aliquots toolbar is one row: search, Sample, Passage, More, Search, New Aliquot.""" + + def row(self): + html = self.list().content.decode() + return html[html.index('class="toolbar-row"'):html.index('id="filter-more-panel"')] + + def test_controls_are_on_one_row_in_order_with_new_aliquot_last(self): + row = self.row() + order = ['name="q"', 'name="f_sample"', 'name="f_passage"', 'class="filter-more"', + 'class="toolbar-btn-search"', 'toolbar-new'] + positions = [row.index(token) for token in order] + self.assertEqual(positions, sorted(positions)) + + def test_more_is_a_summary_in_the_row_that_controls_the_panel_below(self): + row = self.row() + self.assertIn('More filters', row) + html = self.list().content.decode() + self.assertIn('id="filter-more-panel"', html) + self.assertLess(html.index('class="filter-more"'), html.index('id="filter-more-panel"')) + + def test_more_shows_how_many_of_its_fields_are_active(self): + self.assertIn('More filters2', + self.list(f_location='x', f_number='1').content.decode()) + + def test_no_template_comment_text_leaks_into_the_page(self): + for params in ({}, {'f_sample': 'x', 'f_passage': 'y'}): + html = self.list(**params).content.decode() + for leaked in ('{#', '#}', 'variant:', 'FilterBar', '{% comment', 'endcomment'): + with self.subTest(params=params, leaked=leaked): + self.assertNotIn(leaked, html) + samples = self.client.get(self.url).content.decode() + for leaked in ('{#', '#}', 'variant:', 'FilterBar'): + self.assertNotIn(leaked, samples) + + def test_the_page_header_is_one_description_line(self): + html = self.list().content.decode() + header = html[html.index('class="list-header"'):html.index(' @@ -29,26 +24,26 @@

{{ model_name }}

- - + {% include 'sample/_filter_fields.html' with fields=filter_bar.inline variant='inline' %} +
+ More filters{% if filter_bar.more_active %}{{ filter_bar.more_active }}{% endif %} +
- + add - New Aliquot + New Aliquot +
+ {% if filter_bar.inline_hints %} +
+ {% for label, hint in filter_bar.inline_hints %}

{{ label }}: {{ hint }}

{% endfor %} +
+ {% endif %} + {% include 'sample/_filter_fields.html' with fields=filter_bar.more variant='panel' %} +
- {% if search_query or disposition_filter or aliquot_type_filter or sample_filter or checked_out_all %} -
- {% if checked_out_all %} - - Checked out by anyone - - - {% endif %} - {% if search_query %} - - "{{ search_query }}" - - - {% endif %} - {% if disposition_filter %} - - Disposition: {{ disposition_filter|title }} - - - {% endif %} - {% if sample_filter %} - - Sample: {{ sample_filter.name }} - - - {% endif %} - {% if aliquot_type_filter %} - - Type: {% for at in aliquot_types %}{% if at.id|stringformat:"i" == aliquot_type_filter %}{{ at.name }}{% endif %}{% endfor %} - - - {% endif %} -
- {% endif %} + {% include 'sample/_filter_chips.html' %} {% else %}
@@ -133,6 +95,11 @@

{{ model_name }}

+ {% if filter_bar %} +
+ {% include 'sample/_filter_fields.html' with fields=filter_bar.inline variant='card' %} +
+ {% endif %}
+ {% if filter_bar %}{% include 'sample/_filter_chips.html' %}{% endif %} {% if model_type == 'sample' %}
{{ model_name }}
-

{{ model_name }}

{{ paginator.count }} {% if paginator.count == 1 %}{{ model_name|lower|slice:":-1" }}{% else %}{{ model_name|lower }}{% endif %} found {% if search_query %} (filtered by "{{ search_query }}") {% endif %} + {% if no_date_excluded %} + {{ no_date_excluded }} aliquot{{ no_date_excluded|pluralize }} with no sample date {{ no_date_excluded|pluralize:"is,are" }} excluded + {% endif %}