From 7bdef51dc5d10f97585176ca03f6ee68128bac3c Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Tue, 10 Nov 2026 21:33:22 -0700 Subject: [PATCH 1/4] Record who checked an aliquot out; Checked out by me filter; no-owner report Closes #192. Co-Authored-By: Claude Sonnet 5.5 --- krill/reports/README.md | 12 +- .../reports/checked_out_no_owner.html | 50 ++++++++ .../templates/reports/reports_dashboard.html | 4 + krill/reports/test_checked_out_no_owner.py | 60 ++++++++++ krill/reports/urls.py | 3 + krill/reports/views.py | 12 ++ .../0008_aliquot_checked_out_by_at.py | 26 +++++ krill/sample/models/aliquot.py | 20 ++++ krill/sample/tests/test_checked_out.py | 110 ++++++++++++++++++ krill/sample/views/detail.py | 3 + krill/sample/views/list.py | 9 ++ krill/templates/sample/detail.html | 6 + krill/templates/sample/list.html | 15 ++- krill/templates/sample/tube_detail.html | 6 + 14 files changed, 332 insertions(+), 4 deletions(-) create mode 100644 krill/reports/templates/reports/checked_out_no_owner.html create mode 100644 krill/reports/test_checked_out_no_owner.py create mode 100644 krill/sample/migrations/0008_aliquot_checked_out_by_at.py create mode 100644 krill/sample/tests/test_checked_out.py diff --git a/krill/reports/README.md b/krill/reports/README.md index bdffcee..64e241e 100644 --- a/krill/reports/README.md +++ b/krill/reports/README.md @@ -1,6 +1,6 @@ # Reports app -Reports is where you check that what Krill says is in storage is really there (the **storage audit**), and where alerts are listed. Open it from **Reports** in the sidebar. +Reports is where you check that what Krill says is in storage is really there (the **storage audit**), where alerts are listed, and where aliquots checked out with no recorded owner are listed. Open it from **Reports** in the sidebar. ## Storage audit @@ -38,6 +38,16 @@ Other people see the checklist with the fields disabled. Code: `reports/views.py` (`generate_audit_report`, `generate_storage_audit_data`, `audit_detail`, `audit_list`, `save_audit_result`, `delete_audit`), templates in `reports/templates/reports/`, tests in `reports/tests.py`. +## Checked out, no owner + +**Reports > Checked Out, No Owner** (`/reports/checked-out-no-owner/`) lists aliquots whose disposition is In Use but that have no recorded owner. Since Krill started recording who checks an aliquot out (the Check Out button saves the person and the time), every new checkout has an owner. The ones listed here were set to In Use before that, or by editing the aliquot by hand. + +A checked-out aliquot is used and discarded, so most of this list is tubes that were used long ago and never marked Exhausted. Open one to mark it Exhausted. The page shows the total and 50 aliquots per page, with sample, type, passage, sample date and last-updated date. + +A person's own checked-out aliquots are in the Aliquots list with the **Checked out by me** filter (`/samples/list/?type=aliquot&checked_out_by=me`). The owner and time stay on the aliquot after it is used up, as a record of who used it. + +Code: `checked_out_no_owner` in `reports/views.py`, template `reports/templates/reports/checked_out_no_owner.html`, tests in `reports/test_checked_out_no_owner.py`. + ## Alerts **Reports > View Alerts** lists alerts with their severity (low, medium, high, critical), type (storage, sample, system, security, general) and status (active, acknowledged, resolved, dismissed). An active alert can be acknowledged and then resolved. The Reports page shows the count of active alerts and the latest five. diff --git a/krill/reports/templates/reports/checked_out_no_owner.html b/krill/reports/templates/reports/checked_out_no_owner.html new file mode 100644 index 0000000..0ec2ceb --- /dev/null +++ b/krill/reports/templates/reports/checked_out_no_owner.html @@ -0,0 +1,50 @@ +{% extends 'base/layout.html' %} + +{% block title %}Checked Out, No Owner{% endblock %} + +{% block content %} +
+
+

Checked Out, No Owner

+
+
+

+ {{ total }} aliquot{{ total|pluralize }} marked In Use with no recorded owner. Most were checked out + before Krill recorded who, or had their status set to In Use by hand. A checked-out aliquot is used + and discarded, so these are mostly tubes that were used long ago and never marked Exhausted. Open one + to mark it Exhausted. +

+
+ {% if page_obj %} +
+ + + + + + {% for a in page_obj %} + + + + + + + + {% endfor %} + +
AliquotTypePassageSample DateLast Updated
{{ a.sample.name }} #{{ a.id }}{{ a.aliquot_type.name|default:"—" }}{{ a.passage|default:"—" }}{{ a.sample_date|date:"Y-m-d"|default:"—" }}{{ a.updated_at|date:"Y-m-d" }}
+
+ {% if page_obj.paginator.num_pages > 1 %} +
+ {% if page_obj.has_previous %}← Previous{% endif %} + Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} + {% if page_obj.has_next %}Next →{% endif %} +
+ {% endif %} + {% else %} +

No aliquots are checked out without an owner.

+ {% endif %} +
+
+
+{% endblock %} diff --git a/krill/reports/templates/reports/reports_dashboard.html b/krill/reports/templates/reports/reports_dashboard.html index 837b1dc..9fa7dc4 100644 --- a/krill/reports/templates/reports/reports_dashboard.html +++ b/krill/reports/templates/reports/reports_dashboard.html @@ -40,6 +40,10 @@

Active Alerts

assignment_turned_in Start Storage Audit + + person_off + Checked Out, No Owner + search Search Samples diff --git a/krill/reports/test_checked_out_no_owner.py b/krill/reports/test_checked_out_no_owner.py new file mode 100644 index 0000000..b4d1506 --- /dev/null +++ b/krill/reports/test_checked_out_no_owner.py @@ -0,0 +1,60 @@ +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse +from django.utils import timezone + +from sample.models.aliquot import Aliquot, AliquotDisposition +from sample.models.sample import Sample +from sample.models.source import Source + +User = get_user_model() + + +class CheckedOutNoOwnerReportTest(TestCase): + def setUp(self): + self.user = User.objects.create_user(username='u', password='x') + self.sample = Sample.objects.create(name='Line A', source=Source.objects.create(name='S')) + self.disp = { + kind: AliquotDisposition.objects.get_or_create(name=name, defaults={'disposition_type': kind})[0] + for kind, name in (('in_use', 'In Use'), ('stored', 'Stored'), ('exhausted', 'Used')) + } + self.url = reverse('reports:checked_out_no_owner') + + def _aliquot(self, kind, owner=None, **kwargs): + return Aliquot.objects.create( + sample=self.sample, disposition=self.disp[kind], + checked_out_by=owner, checked_out_at=timezone.now() if owner else None, **kwargs) + + def test_requires_login(self): + self.assertEqual(self.client.get(self.url).status_code, 302) + + def test_lists_only_in_use_aliquots_without_an_owner(self): + ownerless = self._aliquot('in_use', passage='p6') + owned = self._aliquot('in_use', owner=self.user) + stored = self._aliquot('stored') + used_up = self._aliquot('exhausted') + self.client.force_login(self.user) + response = self.client.get(self.url) + self.assertEqual(list(response.context['page_obj']), [ownerless]) + self.assertEqual(response.context['total'], 1) + self.assertContains(response, 'p6') + self.assertContains(response, '1 aliquot marked In Use') + for other in (owned, stored, used_up): + self.assertNotContains(response, f'#{other.id}<') + + def test_empty_state(self): + self.client.force_login(self.user) + self.assertContains(self.client.get(self.url), 'No aliquots are checked out without an owner.') + + def test_paginates_at_50(self): + for _ in range(51): + self._aliquot('in_use') + self.client.force_login(self.user) + response = self.client.get(self.url) + self.assertEqual(len(response.context['page_obj']), 50) + self.assertEqual(response.context['total'], 51) + self.assertEqual(len(self.client.get(self.url, {'page': 2}).context['page_obj']), 1) + + def test_linked_from_reports_dashboard(self): + self.client.force_login(self.user) + self.assertContains(self.client.get(reverse('reports:reports_dashboard')), self.url) diff --git a/krill/reports/urls.py b/krill/reports/urls.py index 6afb849..c6203eb 100644 --- a/krill/reports/urls.py +++ b/krill/reports/urls.py @@ -28,6 +28,9 @@ path('alerts/create/', views.create_alert, name='create_alert'), + # Aliquots checked out with no recorded owner + path('checked-out-no-owner/', views.checked_out_no_owner, name='checked_out_no_owner'), + # Storage Dashboard path('storage/dashboard/', views.storage_dashboard, name='storage_dashboard'), diff --git a/krill/reports/views.py b/krill/reports/views.py index 97e9c08..ddeae7b 100644 --- a/krill/reports/views.py +++ b/krill/reports/views.py @@ -29,6 +29,18 @@ logger = logging.getLogger(__name__) +@login_required +def checked_out_no_owner(request): + """In Use aliquots with no recorded owner: a cleanup list, mostly checkouts from before Krill tracked who.""" + aliquots = ( + Aliquot.objects.filter(disposition__disposition_type='in_use', checked_out_by__isnull=True) + .select_related('sample', 'aliquot_type') + .order_by('sample__name', 'id') + ) + page = Paginator(aliquots, 50).get_page(request.GET.get('page')) + return render(request, 'reports/checked_out_no_owner.html', {'page_obj': page, 'total': page.paginator.count}) + + # Main Reports Dashboard @login_required def reports_dashboard(request): diff --git a/krill/sample/migrations/0008_aliquot_checked_out_by_at.py b/krill/sample/migrations/0008_aliquot_checked_out_by_at.py new file mode 100644 index 0000000..60f79a2 --- /dev/null +++ b/krill/sample/migrations/0008_aliquot_checked_out_by_at.py @@ -0,0 +1,26 @@ +# Generated by Django 6.1.3 on 2026-11-11 04:20 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('sample', '0007_aliquot_passage_sample_date_lab_member'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='aliquot', + name='checked_out_at', + field=models.DateTimeField(blank=True, help_text='When the aliquot was checked out', null=True), + ), + migrations.AddField( + model_name='aliquot', + name='checked_out_by', + field=models.ForeignKey(blank=True, help_text='User who checked the aliquot out. Kept after it is used up, as a record of who used it.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='aliquots_checked_out', to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/krill/sample/models/aliquot.py b/krill/sample/models/aliquot.py index 1bc0891..0d7a622 100644 --- a/krill/sample/models/aliquot.py +++ b/krill/sample/models/aliquot.py @@ -72,6 +72,19 @@ class Aliquot(models.Model): default='', help_text='Initials as recorded, used when the person has no linked user account', ) + checked_out_by = models.ForeignKey( + settings.AUTH_USER_MODEL, + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name='aliquots_checked_out', + help_text='User who checked the aliquot out. Kept after it is used up, as a record of who used it.', + ) + checked_out_at = models.DateTimeField( + null=True, + blank=True, + help_text='When the aliquot was checked out', + ) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True) deleted = models.BooleanField(default=False, db_index=True) @@ -90,6 +103,13 @@ def lab_member_display(self): return self.lab_member.get_full_name() or self.lab_member.get_username() return self.lab_member_initials + @property + def checked_out_by_display(self): + """Name of the person who checked the aliquot out, or '' if not recorded.""" + if self.checked_out_by_id: + return self.checked_out_by.get_full_name() or self.checked_out_by.get_username() + return '' + def store_in_location(self, box, row, column): """Store this aliquot in a location""" stored_disposition, _ = AliquotDisposition.objects.get_or_create( diff --git a/krill/sample/tests/test_checked_out.py b/krill/sample/tests/test_checked_out.py new file mode 100644 index 0000000..802c4b7 --- /dev/null +++ b/krill/sample/tests/test_checked_out.py @@ -0,0 +1,110 @@ +from django.contrib.auth import get_user_model +from django.urls import reverse +from django.utils import timezone + +from ..models.aliquot import Aliquot, AliquotDisposition +from .test_views import SampleViewTest + +User = get_user_model() + + +class CheckoutRecordsOwnerTest(SampleViewTest): + def setUp(self): + super().setUp() + self.client.force_login(self.user) + self.in_use = AliquotDisposition.objects.get_or_create( + name='In Use', defaults={'disposition_type': 'in_use'})[0] + self.exhausted = AliquotDisposition.objects.get_or_create( + name='Used', defaults={'disposition_type': 'exhausted'})[0] + + def _checkout(self, aliquot): + return self.client.post( + reverse('sample:aliquot_detail', kwargs={'pk': aliquot.pk}), {'action': 'checkout'}) + + def test_checkout_records_who_and_when(self): + before = timezone.now() + self._checkout(self.aliquot) + self.aliquot.refresh_from_db() + self.assertEqual(self.aliquot.disposition.disposition_type, 'in_use') + self.assertEqual(self.aliquot.checked_out_by, self.user) + self.assertGreaterEqual(self.aliquot.checked_out_at, before) + + def test_owner_is_kept_after_the_aliquot_is_used_up(self): + self._checkout(self.aliquot) + self.aliquot.refresh_from_db() + self.aliquot.disposition = self.exhausted + self.aliquot.save() + self.aliquot.refresh_from_db() + self.assertEqual(self.aliquot.checked_out_by, self.user) + self.assertIsNotNone(self.aliquot.checked_out_at) + + def test_deleting_the_user_keeps_the_aliquot(self): + self._checkout(self.aliquot) + self.user.delete() + self.aliquot.refresh_from_db() + self.assertIsNone(self.aliquot.checked_out_by) + + def test_detail_pages_show_who_checked_it_out(self): + self._checkout(self.aliquot) + for url in ( + reverse('sample:detail', kwargs={'type': 'aliquot', 'pk': self.aliquot.pk}), + reverse('sample:aliquot_detail', kwargs={'pk': self.aliquot.pk}), + ): + with self.subTest(url=url): + self.assertContains(self.client.get(url), 'Checked out by:') + self.assertContains(self.client.get(url), 'testuser') + + def test_never_checked_out_aliquot_has_no_checked_out_row(self): + response = self.client.get(reverse('sample:aliquot_detail', kwargs={'pk': self.aliquot.pk})) + self.assertNotContains(response, 'Checked out by:') + + +class CheckedOutByMeFilterTest(SampleViewTest): + def setUp(self): + super().setUp() + self.in_use = AliquotDisposition.objects.get_or_create( + name='In Use', defaults={'disposition_type': 'in_use'})[0] + self.exhausted = AliquotDisposition.objects.get_or_create( + name='Used', defaults={'disposition_type': 'exhausted'})[0] + self.other_user = User.objects.create_user(username='colleague', password='x') + self.client.force_login(self.user) + + def _make(self, owner, disposition=None, **kwargs): + return Aliquot.objects.create( + sample=self.sample, aliquot_type=self.aliquot_type, + disposition=disposition or self.in_use, + checked_out_by=owner, checked_out_at=timezone.now(), **kwargs) + + def _list(self, **params): + return self.client.get(reverse('sample:sample_list'), {'type': 'aliquot', 'checked_out_by': 'me', **params}) + + def test_lists_only_my_in_use_aliquots(self): + mine = self._make(self.user, passage='p3') + self._make(self.other_user) # someone else's + self._make(self.user, disposition=self.exhausted) # mine, but used up + Aliquot.objects.create(sample=self.sample, disposition=self.in_use) # in use, no owner + response = self._list() + self.assertEqual(list(response.context['items']), [mine]) + self.assertTrue(response.context['checked_out_by_me']) + + def test_shows_checked_out_time_column_and_chip_only_when_filtered(self): + self._make(self.user) + filtered = self._list() + self.assertContains(filtered, 'Checked Out') + self.assertContains(filtered, 'Checked out by me') + self.assertContains(filtered, 'name="checked_out_by" value="me"') + plain = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot'}) + self.assertNotContains(plain, 'Checked Out') + self.assertNotContains(plain, 'Checked out by me') + + def test_works_with_search_and_sort(self): + keep = self._make(self.user, passage='p8') + self._make(self.user, passage='p9') + response = self._list(q='p8', sort='passage') + self.assertEqual(list(response.context['items']), [keep]) + + def test_other_values_are_ignored(self): + self._make(self.other_user) + response = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot', 'checked_out_by': str(self.other_user.pk)}) + self.assertFalse(response.context['checked_out_by_me']) + self.assertEqual(len(response.context['items']), 2) # nothing filtered: self.aliquot + theirs diff --git a/krill/sample/views/detail.py b/krill/sample/views/detail.py index 4f05439..6da231d 100644 --- a/krill/sample/views/detail.py +++ b/krill/sample/views/detail.py @@ -5,6 +5,7 @@ from django.utils.decorators import method_decorator from django.db import IntegrityError, transaction from django.contrib import messages +from django.utils import timezone from ..models.sample import Sample from ..models.aliquot import Aliquot, AliquotType, AliquotLocation from ..models.source import Source @@ -234,6 +235,8 @@ def _handle_checkout(self, request): ) self.object.disposition = in_use_disposition + self.object.checked_out_by = request.user + self.object.checked_out_at = timezone.now() self.object.save() # Remove storage location if aliquot was stored diff --git a/krill/sample/views/list.py b/krill/sample/views/list.py index 23f2bfd..274dc48 100644 --- a/krill/sample/views/list.py +++ b/krill/sample/views/list.py @@ -53,6 +53,13 @@ def get_queryset(self): if sample_filter.isdigit(): queryset = queryset.filter(sample_id=int(sample_filter)) + # ?checked_out_by=me: aliquots the signed-in user has checked out and not yet used up + if self.request.GET.get('checked_out_by') == 'me': + queryset = queryset.filter( + checked_out_by=self.request.user, + disposition__disposition_type='in_use', + ) + # Hide finished (exhausted) aliquots. Disposed ones stay visible. if self.request.GET.get('hide_finished') == '1': queryset = queryset.exclude(disposition__disposition_type='exhausted') @@ -157,6 +164,7 @@ def get_context_data(self, **kwargs): context['disposition_filter'] = self.request.GET.get('disposition', '') context['aliquot_type_filter'] = self.request.GET.get('aliquot_type', '') context['hide_finished'] = self.request.GET.get('hide_finished') == '1' + context['checked_out_by_me'] = self.request.GET.get('checked_out_by') == 'me' sample_filter = self.request.GET.get('sample', '') context['sample_filter'] = Sample.objects.filter(pk=int(sample_filter)).first() if sample_filter.isdigit() else None context['disposition_choices'] = AliquotDisposition.DISPOSITION_CHOICES @@ -165,6 +173,7 @@ def get_context_data(self, **kwargs): context['disposition_filter'] = '' context['aliquot_type_filter'] = '' context['hide_finished'] = False + context['checked_out_by_me'] = False context['sample_filter'] = None context['disposition_choices'] = [] context['aliquot_types'] = AliquotType.objects.none() diff --git a/krill/templates/sample/detail.html b/krill/templates/sample/detail.html index 668346a..32892b9 100644 --- a/krill/templates/sample/detail.html +++ b/krill/templates/sample/detail.html @@ -38,6 +38,12 @@

{{ object.name }}

{{ object.lab_member_display|default:"Not recorded" }} + {% if object.checked_out_at or object.checked_out_by %} +
+ + {{ object.checked_out_by_display|default:"Unknown" }}{% if object.checked_out_at %} on {{ object.checked_out_at|date:"M d, Y H:i" }}{% endif %} +
+ {% endif %}
- {% if search_query or disposition_filter or aliquot_type_filter or hide_finished or sample_filter %} + {% if search_query or disposition_filter or aliquot_type_filter or hide_finished or sample_filter or checked_out_by_me %}
{% if search_query %} @@ -66,6 +67,12 @@

{{ model_name }}

{% endif %} + {% if checked_out_by_me %} + + Checked out by me + + + {% endif %} {% if sample_filter %} Sample: {{ sample_filter.name }} @@ -173,6 +180,7 @@

{{ model_name }}

Disposition Location Sample Date + {% if checked_out_by_me %}Checked Out{% endif %} @@ -194,6 +202,7 @@

{{ model_name }}

{% else %}—{% endif %} {{ item.sample_date|date:"Y-m-d"|default:"—" }} + {% if checked_out_by_me %}{{ item.checked_out_at|date:"Y-m-d H:i"|default:"—" }}{% endif %} open_in_new @@ -201,8 +210,8 @@

{{ model_name }}

{% empty %} - -{% if search_query or disposition_filter or aliquot_type_filter or hide_finished or sample_filter %} + +{% if search_query or disposition_filter or aliquot_type_filter or hide_finished or sample_filter or checked_out_by_me %} No aliquots match your filters — try clearing a filter above. {% else %} No aliquots yet.
Create your first aliquot to get started. diff --git a/krill/templates/sample/tube_detail.html b/krill/templates/sample/tube_detail.html index 2b0613d..2f68ab2 100644 --- a/krill/templates/sample/tube_detail.html +++ b/krill/templates/sample/tube_detail.html @@ -60,6 +60,12 @@

info Aliquot Information

{{ aliquot.lab_member_display|default:"Not recorded" }}
+ {% if aliquot.checked_out_at or aliquot.checked_out_by %} +
+ + {{ aliquot.checked_out_by_display|default:"Unknown" }}{% if aliquot.checked_out_at %} on {{ aliquot.checked_out_at|date:"M d, Y H:i" }}{% endif %} +
+ {% endif %}
{{ aliquot.created_at|date:"M d, Y H:i" }} From fbd192264519068ed1257f7b9f046c1106e330ef Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Tue, 10 Nov 2026 21:39:32 -0700 Subject: [PATCH 2/4] Aliquots list: toggle pills for Checked out by me and Hide exhausted Replace the boxed checkbox and the filter chips for the two yes/no filters with pills that are links toggling their query parameter. The checked-out pill shows the user's In Use count. Singular count text; aria-label on Search. Co-Authored-By: Claude Sonnet 5.5 --- krill/sample/tests/test_checked_out.py | 68 ++++++++++++++++++++++++-- krill/sample/tests/test_views.py | 4 +- krill/sample/views/list.py | 17 +++++++ krill/static/krill/style.css | 42 +++++++++++----- krill/templates/sample/list.html | 36 ++++++-------- 5 files changed, 130 insertions(+), 37 deletions(-) diff --git a/krill/sample/tests/test_checked_out.py b/krill/sample/tests/test_checked_out.py index 802c4b7..9eab449 100644 --- a/krill/sample/tests/test_checked_out.py +++ b/krill/sample/tests/test_checked_out.py @@ -87,15 +87,13 @@ def test_lists_only_my_in_use_aliquots(self): self.assertEqual(list(response.context['items']), [mine]) self.assertTrue(response.context['checked_out_by_me']) - def test_shows_checked_out_time_column_and_chip_only_when_filtered(self): + def test_shows_checked_out_time_column_only_when_filtered(self): self._make(self.user) filtered = self._list() self.assertContains(filtered, 'Checked Out') - self.assertContains(filtered, 'Checked out by me') self.assertContains(filtered, 'name="checked_out_by" value="me"') plain = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot'}) self.assertNotContains(plain, 'Checked Out') - self.assertNotContains(plain, 'Checked out by me') def test_works_with_search_and_sort(self): keep = self._make(self.user, passage='p8') @@ -108,3 +106,67 @@ def test_other_values_are_ignored(self): response = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot', 'checked_out_by': str(self.other_user.pk)}) self.assertFalse(response.context['checked_out_by_me']) self.assertEqual(len(response.context['items']), 2) # nothing filtered: self.aliquot + theirs + + +class ToggleKeyPillsTest(SampleViewTest): + """The two yes/no filters are pills (links) under the search bar.""" + + def setUp(self): + super().setUp() + self.client.force_login(self.user) + self.in_use = AliquotDisposition.objects.get_or_create( + name='In Use', defaults={'disposition_type': 'in_use'})[0] + self.exhausted = AliquotDisposition.objects.get_or_create( + name='Used', defaults={'disposition_type': 'exhausted'})[0] + + def _list(self, **params): + return self.client.get(reverse('sample:sample_list'), {'type': 'aliquot', **params}) + + def test_pills_start_off_with_aria_state(self): + response = self._list() + self.assertContains(response, 'aria-label="Checked out by me, off. Select to turn on"') + self.assertContains(response, 'aria-label="Hide exhausted, off. Select to turn on"') + self.assertNotContains(response, 'toggle-pill on') + + def test_pills_show_on_state_and_turn_off_links(self): + response = self._list(checked_out_by='me', hide_finished='1') + self.assertContains(response, 'aria-label="Checked out by me, on. Select to turn off"') + self.assertContains(response, 'aria-label="Hide exhausted, on. Select to turn off"') + self.assertEqual(response.content.decode().count('toggle-pill on'), 2) + + def test_toggle_urls_flip_one_param_keep_others_and_reset_page(self): + response = self._list(q='p8', sort='passage', page='1', hide_finished='1') + on_url = response.context['checked_out_toggle_url'] + self.assertIn('checked_out_by=me', on_url) + self.assertIn('hide_finished=1', on_url) + self.assertIn('q=p8', on_url) + self.assertIn('sort=passage', on_url) + self.assertNotIn('page=', on_url) + off_url = response.context['hide_finished_toggle_url'] + self.assertNotIn('hide_finished', off_url) + self.assertIn('q=p8', off_url) + self.assertNotIn('page=', off_url) + + def test_following_a_toggle_link_applies_the_filter(self): + mine = Aliquot.objects.create( + sample=self.sample, disposition=self.in_use, + checked_out_by=self.user, checked_out_at=timezone.now()) + url = self._list().context['checked_out_toggle_url'] + response = self.client.get(reverse('sample:sample_list') + url) + self.assertEqual(list(response.context['items']), [mine]) + + def test_checked_out_pill_counts_my_in_use_aliquots_only(self): + other = User.objects.create_user(username='colleague', password='x') + for owner, disp in ((self.user, self.in_use), (self.user, self.in_use), + (self.user, self.exhausted), (other, self.in_use)): + Aliquot.objects.create(sample=self.sample, disposition=disp, + checked_out_by=owner, checked_out_at=timezone.now()) + response = self._list() + self.assertEqual(response.context['checked_out_count'], 2) + self.assertContains(response, 'Checked out by me · 2') + + def test_search_button_has_aria_label_and_singular_count(self): + response = self._list(q='Test Sample') + self.assertContains(response, 'aria-label="Search"') + self.assertContains(response, '1 aliquot found') + self.assertNotContains(response, '1 aliquots found') diff --git a/krill/sample/tests/test_views.py b/krill/sample/tests/test_views.py index 58501d8..dd4f1d7 100644 --- a/krill/sample/tests/test_views.py +++ b/krill/sample/tests/test_views.py @@ -305,7 +305,9 @@ def test_hide_finished_works_with_search_and_sort(self): self.aliquot.save() response = self._aliquot_list(hide_finished='1', q='p5', sort='passage') self.assertEqual(list(response.context['items']), [self.aliquot]) - self.assertContains(response, 'name="hide_finished" value="1" checked') + # The pill is on, and the search form keeps the toggle when it is submitted + self.assertContains(response, 'class="toggle-pill on"') + self.assertContains(response, '') def test_aliquot_list_context_includes_filter_choices(self): """Context includes disposition_choices, aliquot_types, and active filter values.""" diff --git a/krill/sample/views/list.py b/krill/sample/views/list.py index 274dc48..6d39900 100644 --- a/krill/sample/views/list.py +++ b/krill/sample/views/list.py @@ -131,6 +131,17 @@ def _search_aliquots(queryset, term): match |= Q(id=int(number)) return queryset.filter(match) + def _toggle_url(self, param, value): + """Link that flips one yes/no filter, keeps every other parameter, and goes back to page 1.""" + params = self.request.GET.copy() + params.pop('page', None) + if params.get(param) == value: + params.pop(param) + else: + params[param] = value + query = params.urlencode() + return f'?{query}' if query else self.request.path + def get_paginate_by(self, queryset): if self.request.GET.get('page_size') == '20': return 20 @@ -165,6 +176,12 @@ def get_context_data(self, **kwargs): context['aliquot_type_filter'] = self.request.GET.get('aliquot_type', '') context['hide_finished'] = self.request.GET.get('hide_finished') == '1' context['checked_out_by_me'] = self.request.GET.get('checked_out_by') == 'me' + context['checked_out_toggle_url'] = self._toggle_url('checked_out_by', 'me') + context['hide_finished_toggle_url'] = self._toggle_url('hide_finished', '1') + context['checked_out_count'] = Aliquot.objects.filter( + checked_out_by=self.request.user, + disposition__disposition_type='in_use', + ).count() sample_filter = self.request.GET.get('sample', '') context['sample_filter'] = Sample.objects.filter(pk=int(sample_filter)).first() if sample_filter.isdigit() else None context['disposition_choices'] = AliquotDisposition.DISPOSITION_CHOICES diff --git a/krill/static/krill/style.css b/krill/static/krill/style.css index 74a30f9..497c000 100644 --- a/krill/static/krill/style.css +++ b/krill/static/krill/style.css @@ -2629,30 +2629,46 @@ main table tbody tr:last-child td{ outline-offset: 1px; } -.toolbar-toggle { +.toggle-pills { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-top: 0.6rem; +} + +.toggle-pill { display: inline-flex; align-items: center; - gap: 0.4rem; - padding: 0.45rem 0.6rem; + gap: 0.25rem; + padding: 0.3rem 0.8rem; border: 1px solid var(--color-gray-border); - border-radius: var(--border-radius-1); - background: var(--color-white); + border-radius: 999px; + background: transparent; color: var(--color-dark); - font-size: 0.85rem; + font-size: 0.82rem; + font-weight: 500; font-family: var(--font-family); - line-height: normal; + text-decoration: none; white-space: nowrap; - cursor: pointer; } -.toolbar-toggle input[type="checkbox"] { - width: auto; - margin: 0; - cursor: pointer; +.toggle-pill:hover { + border-color: var(--color-primary); +} + +.toggle-pill:focus-visible { + outline: 2px solid var(--color-primary); + outline-offset: 2px; } -.toolbar-toggle:has(input:checked) { +.toggle-pill.on { + background: var(--color-primary); border-color: var(--color-primary); + color: #fff; +} + +.toggle-pill .material-icons-round { + font-size: 1rem; } .toolbar-btn-search { diff --git a/krill/templates/sample/list.html b/krill/templates/sample/list.html index 8c94b86..d355953 100644 --- a/krill/templates/sample/list.html +++ b/krill/templates/sample/list.html @@ -20,6 +20,7 @@

{{ model_name }}

{% if sample_filter %}{% endif %} {% if checked_out_by_me %}{% endif %} + {% if hide_finished %}{% endif %} {% if request.GET.sort %}{% endif %} {% if request.GET.order %}{% endif %} {% if request.GET.page_size %}{% endif %} @@ -39,12 +40,7 @@

{{ model_name }}

{% endfor %} - - @@ -53,7 +49,19 @@

{{ model_name }}

- {% if search_query or disposition_filter or aliquot_type_filter or hide_finished or sample_filter or checked_out_by_me %} + + {% if search_query or disposition_filter or aliquot_type_filter or sample_filter %}
{% if search_query %} @@ -67,24 +75,12 @@

{{ model_name }}

{% endif %} - {% if checked_out_by_me %} - - Checked out by me - - - {% endif %} {% if sample_filter %} Sample: {{ sample_filter.name }} {% endif %} - {% if hide_finished %} - - Hiding exhausted - - - {% endif %} {% if aliquot_type_filter %} Type: {% for at in aliquot_types %}{% if at.id|stringformat:"i" == aliquot_type_filter %}{{ at.name }}{% endif %}{% endfor %} @@ -151,7 +147,7 @@

{{ model_name }}

{{ model_name }}

- {{ paginator.count }} {{ model_name|lower }} found + {{ 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 %} From 516befaf55234b47207e3d65418fab21a0b7e1d8 Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Tue, 10 Nov 2026 21:44:02 -0700 Subject: [PATCH 3/4] No-owner report: let managers move ticked aliquots to Exhausted or Disposed Co-Authored-By: Claude Sonnet 5.5 --- krill/reports/README.md | 4 +- .../reports/checked_out_no_owner.html | 61 ++++++++++- krill/reports/test_checked_out_no_owner.py | 100 +++++++++++++++++- krill/reports/views.py | 60 +++++++++-- 4 files changed, 213 insertions(+), 12 deletions(-) diff --git a/krill/reports/README.md b/krill/reports/README.md index 64e241e..44fed8e 100644 --- a/krill/reports/README.md +++ b/krill/reports/README.md @@ -42,11 +42,11 @@ Code: `reports/views.py` (`generate_audit_report`, `generate_storage_audit_data` **Reports > Checked Out, No Owner** (`/reports/checked-out-no-owner/`) lists aliquots whose disposition is In Use but that have no recorded owner. Since Krill started recording who checks an aliquot out (the Check Out button saves the person and the time), every new checkout has an owner. The ones listed here were set to In Use before that, or by editing the aliquot by hand. -A checked-out aliquot is used and discarded, so most of this list is tubes that were used long ago and never marked Exhausted. Open one to mark it Exhausted. The page shows the total and 50 aliquots per page, with sample, type, passage, sample date and last-updated date. +A checked-out aliquot is used and discarded, so most of this list is tubes that were used long ago and never marked Exhausted. Lab managers and admins can clear them from the page: tick the rows (the box in the header ticks everything on the page), pick a status, and press **Apply**. The status list is every status except Stored and In Use (Exhausted and Disposed), because a checked-out tube is never put back in storage. Each change is saved as an "Aliquot Updated" entry in the audit log, and only tubes that are still In Use with no owner are changed, so a stale page cannot overwrite someone else's edit. Other people see the list without the tick boxes and can still open one aliquot at a time. The page shows the total and 50 aliquots per page, with sample, type, passage, sample date and last-updated date. A person's own checked-out aliquots are in the Aliquots list with the **Checked out by me** filter (`/samples/list/?type=aliquot&checked_out_by=me`). The owner and time stay on the aliquot after it is used up, as a record of who used it. -Code: `checked_out_no_owner` in `reports/views.py`, template `reports/templates/reports/checked_out_no_owner.html`, tests in `reports/test_checked_out_no_owner.py`. +Code: `checked_out_no_owner` in `reports/views.py` (handles the list and the status change), template `reports/templates/reports/checked_out_no_owner.html`, tests in `reports/test_checked_out_no_owner.py`. ## Alerts diff --git a/krill/reports/templates/reports/checked_out_no_owner.html b/krill/reports/templates/reports/checked_out_no_owner.html index 0ec2ceb..fd38bba 100644 --- a/krill/reports/templates/reports/checked_out_no_owner.html +++ b/krill/reports/templates/reports/checked_out_no_owner.html @@ -14,16 +14,34 @@

Checked Out, No Owner

and discarded, so these are mostly tubes that were used long ago and never marked Exhausted. Open one to mark it Exhausted.

+ {% for message in messages %} +

{{ message }}

+ {% endfor %}
{% if page_obj %} + {% if can_change %}
{% csrf_token %}{% endif %} + {% if can_change %} +
+ + + + None ticked +
+ {% endif %}
- + + {% if can_change %}{% endif %} + + {% for a in page_obj %} + {% if can_change %}{% endif %} @@ -34,6 +52,7 @@

Checked Out, No Owner

AliquotTypePassageSample DateLast Updated
AliquotTypePassageSample DateLast Updated
{{ a.sample.name }} #{{ a.id }} {{ a.aliquot_type.name|default:"—" }} {{ a.passage|default:"—" }}
+ {% if can_change %}
{% endif %} {% if page_obj.paginator.num_pages > 1 %}
{% if page_obj.has_previous %}← Previous{% endif %} @@ -47,4 +66,44 @@

Checked Out, No Owner

+ + + +{% if can_change %} + +{% endif %} {% endblock %} diff --git a/krill/reports/test_checked_out_no_owner.py b/krill/reports/test_checked_out_no_owner.py index b4d1506..8f5bea2 100644 --- a/krill/reports/test_checked_out_no_owner.py +++ b/krill/reports/test_checked_out_no_owner.py @@ -3,6 +3,7 @@ from django.urls import reverse from django.utils import timezone +from person.models import UserAuditLog from sample.models.aliquot import Aliquot, AliquotDisposition from sample.models.sample import Sample from sample.models.source import Source @@ -10,7 +11,7 @@ User = get_user_model() -class CheckedOutNoOwnerReportTest(TestCase): +class ReportTestBase(TestCase): def setUp(self): self.user = User.objects.create_user(username='u', password='x') self.sample = Sample.objects.create(name='Line A', source=Source.objects.create(name='S')) @@ -25,6 +26,8 @@ def _aliquot(self, kind, owner=None, **kwargs): sample=self.sample, disposition=self.disp[kind], checked_out_by=owner, checked_out_at=timezone.now() if owner else None, **kwargs) + +class CheckedOutNoOwnerReportTest(ReportTestBase): def test_requires_login(self): self.assertEqual(self.client.get(self.url).status_code, 302) @@ -58,3 +61,98 @@ def test_paginates_at_50(self): def test_linked_from_reports_dashboard(self): self.client.force_login(self.user) self.assertContains(self.client.get(reverse('reports:reports_dashboard')), self.url) + + +class BulkStatusChangeTest(ReportTestBase): + """Managers and admins can tick ownerless In Use aliquots and move them to Exhausted or Disposed.""" + + def setUp(self): + super().setUp() + self.manager = User.objects.create_user(username='mgr', password='x') + self.manager.role.role = 'lab_manager' + self.manager.role.save() + self.disp['disposed'] = AliquotDisposition.objects.get_or_create( + name='Disposed', defaults={'disposition_type': 'disposed'})[0] + + def _post(self, ids, disposition, **extra): + return self.client.post(self.url, {'aliquot_ids': ids, 'disposition': disposition.id, **extra}) + + def test_controls_shown_to_managers_only(self): + self._aliquot('in_use') + self.client.force_login(self.manager) + manager_page = self.client.get(self.url) + self.assertTrue(manager_page.context['can_change']) + self.assertContains(manager_page, 'id="bulkApply"') + self.assertContains(manager_page, 'name="aliquot_ids"') + self.client.force_login(self.user) # lab_member + member_page = self.client.get(self.url) + self.assertFalse(member_page.context['can_change']) + self.assertNotContains(member_page, 'id="bulkApply"') + self.assertNotContains(member_page, 'name="aliquot_ids"') + + def test_dropdown_offers_only_exhausted_and_disposed(self): + self.client.force_login(self.manager) + offered = {d.disposition_type for d in self.client.get(self.url).context['target_dispositions']} + self.assertEqual(offered, {'exhausted', 'disposed'}) + + def test_manager_moves_ticked_aliquots_and_it_is_logged(self): + a, b, untouched = self._aliquot('in_use'), self._aliquot('in_use'), self._aliquot('in_use') + self.client.force_login(self.manager) + response = self._post([a.id, b.id], self.disp['exhausted'], page='1') + self.assertRedirects(response, self.url + '?page=1', fetch_redirect_response=False) + for moved in (a, b): + moved.refresh_from_db() + self.assertEqual(moved.disposition, self.disp['exhausted']) + untouched.refresh_from_db() + self.assertEqual(untouched.disposition.disposition_type, 'in_use') + self.assertEqual(UserAuditLog.objects.filter(action='aliquot_updated', user=self.manager).count(), 2) + self.assertContains(self.client.get(self.url), 'Marked 2 aliquots as Used.') + + def test_can_move_to_disposed(self): + a = self._aliquot('in_use') + self.client.force_login(self.manager) + self._post([a.id], self.disp['disposed']) + a.refresh_from_db() + self.assertEqual(a.disposition.disposition_type, 'disposed') + + def test_member_cannot_change_status(self): + a = self._aliquot('in_use') + self.client.force_login(self.user) + self.assertEqual(self._post([a.id], self.disp['exhausted']).status_code, 403) + a.refresh_from_db() + self.assertEqual(a.disposition.disposition_type, 'in_use') + + def test_cannot_move_to_stored_or_in_use(self): + a = self._aliquot('in_use') + self.client.force_login(self.manager) + for kind in ('stored', 'in_use'): + with self.subTest(target=kind): + self._post([a.id], self.disp[kind]) + a.refresh_from_db() + self.assertEqual(a.disposition.disposition_type, 'in_use') + + def test_skips_aliquots_that_are_no_longer_ownerless_in_use(self): + stale_owned = self._aliquot('in_use', owner=self.user) + stale_stored = self._aliquot('stored') + fresh = self._aliquot('in_use') + self.client.force_login(self.manager) + self._post([stale_owned.id, stale_stored.id, fresh.id], self.disp['exhausted']) + stale_owned.refresh_from_db(); stale_stored.refresh_from_db(); fresh.refresh_from_db() + self.assertEqual(stale_owned.disposition.disposition_type, 'in_use') + self.assertEqual(stale_stored.disposition.disposition_type, 'stored') + self.assertEqual(fresh.disposition.disposition_type, 'exhausted') + self.assertContains(self.client.get(self.url), 'Marked 1 aliquot as Used. 2 skipped') + + def test_nothing_ticked_changes_nothing_and_says_so(self): + a = self._aliquot('in_use') + self.client.force_login(self.manager) + self._post([], self.disp['exhausted']) + a.refresh_from_db() + self.assertEqual(a.disposition.disposition_type, 'in_use') + self.assertContains(self.client.get(self.url), 'Choose at least one aliquot and a status.') + + def test_bad_page_value_in_redirect_is_ignored(self): + a = self._aliquot('in_use') + self.client.force_login(self.manager) + response = self._post([a.id], self.disp['exhausted'], page='//evil.example') + self.assertRedirects(response, self.url, fetch_redirect_response=False) diff --git a/krill/reports/views.py b/krill/reports/views.py index ddeae7b..23d9f82 100644 --- a/krill/reports/views.py +++ b/krill/reports/views.py @@ -22,23 +22,67 @@ from .models import ReportTemplate, Report, ScheduledReport, Alert from sample.models import Sample, Aliquot -from sample.models.aliquot import AliquotLocation +from sample.models.aliquot import AliquotDisposition, AliquotLocation from storage.models.storage import Device, Box from person.models import UserAuditLog, UserRole logger = logging.getLogger(__name__) +def _no_owner_aliquots(): + return Aliquot.objects.filter(disposition__disposition_type='in_use', checked_out_by__isnull=True) + + @login_required def checked_out_no_owner(request): - """In Use aliquots with no recorded owner: a cleanup list, mostly checkouts from before Krill tracked who.""" - aliquots = ( - Aliquot.objects.filter(disposition__disposition_type='in_use', checked_out_by__isnull=True) - .select_related('sample', 'aliquot_type') - .order_by('sample__name', 'id') - ) + """In Use aliquots with no recorded owner: a cleanup list, mostly checkouts from before Krill tracked who. + + Lab managers and admins can tick rows and move them to another status (Exhausted, Disposed). + """ + can_change = UserRole.get_or_create_for_user(request.user).role in ('lab_manager', 'lab_admin') + # Statuses a tube can move to from here: anything but Stored and In Use + target_dispositions = AliquotDisposition.objects.filter( + disposition_type__in=('exhausted', 'disposed') + ).order_by('disposition_type', 'name') + + if request.method == 'POST': + if not can_change: + raise PermissionDenied("Only lab managers and admins can change the status of aliquots in bulk.") + target = target_dispositions.filter(pk=request.POST.get('disposition') or 0).first() + ids = [int(i) for i in request.POST.getlist('aliquot_ids') if i.isdigit()] + if not target or not ids: + messages.error(request, 'Choose at least one aliquot and a status.') + else: + # Only aliquots that are still In Use with no owner: the list may be out of date + with transaction.atomic(): + changed = list(_no_owner_aliquots().filter(pk__in=ids).select_related('sample')) + for aliquot in changed: + aliquot.disposition = target + aliquot.save() + UserAuditLog.log_action( + user=request.user, + action='aliquot_updated', + target_type='Aliquot', + target_id=aliquot.id, + target_name=str(aliquot), + details={'disposition': target.name, 'source': 'checked_out_no_owner_report'}, + request=request, + ) + skipped = len(ids) - len(changed) + note = f' {skipped} skipped: no longer In Use without an owner.' if skipped else '' + messages.success(request, f'Marked {len(changed)} aliquot{"s" if len(changed) != 1 else ""} as {target.name}.{note}') + page_number = request.POST.get('page', '') + url = reverse('reports:checked_out_no_owner') + return redirect(f'{url}?page={page_number}' if page_number.isdigit() else url) + + aliquots = _no_owner_aliquots().select_related('sample', 'aliquot_type').order_by('sample__name', 'id') page = Paginator(aliquots, 50).get_page(request.GET.get('page')) - return render(request, 'reports/checked_out_no_owner.html', {'page_obj': page, 'total': page.paginator.count}) + return render(request, 'reports/checked_out_no_owner.html', { + 'page_obj': page, + 'total': page.paginator.count, + 'can_change': can_change, + 'target_dispositions': target_dispositions, + }) # Main Reports Dashboard From ef5348e91a6f665c043f362d8877013dcda99c1b Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Tue, 10 Nov 2026 21:54:04 -0700 Subject: [PATCH 4/4] Dashboard: checked-out card with Create child and Done Card above Freezers lists the user's five newest checkouts. Create child opens the form prefilled (sample, type, passage) with a default-on 'Parent aliquot is exhausted' toggle and returns to the dashboard. Done marks the aliquot Exhausted without a child. Co-Authored-By: Claude Sonnet 5.5 --- krill/krill/views/home.py | 20 ++ krill/sample/models/aliquot.py | 9 + .../tests/test_dashboard_checkout_card.py | 221 ++++++++++++++++++ krill/sample/views/create.py | 44 +++- krill/sample/views/detail.py | 19 ++ krill/sample/views/next_url.py | 9 + krill/templates/krill/home.html | 46 ++++ krill/templates/sample/create.html | 18 +- 8 files changed, 377 insertions(+), 9 deletions(-) create mode 100644 krill/sample/tests/test_dashboard_checkout_card.py create mode 100644 krill/sample/views/next_url.py diff --git a/krill/krill/views/home.py b/krill/krill/views/home.py index 43ff55e..1ae600c 100644 --- a/krill/krill/views/home.py +++ b/krill/krill/views/home.py @@ -32,6 +32,7 @@ def get(self, request): 'stats': stats, 'freezers': freezers, 'show_sites': len({card['device'].site_id for card in freezers}) > 1, + 'checked_out': get_checked_out(request.user), 'audits_in_progress': get_audits_in_progress(), 'recent_activity': get_recent_activity(), }) @@ -167,6 +168,25 @@ def get_freezer_cards(): return cards +def get_checked_out(user, limit=5): + """The signed-in user's In Use aliquots, newest checkout first, with how many children each has.""" + from django.db.models import Count + + mine = Aliquot.objects.filter(checked_out_by=user, disposition__disposition_type='in_use') + rows = ( + mine.select_related('sample', 'aliquot_type') + .annotate(child_count=Count('children')) + .order_by('-checked_out_at', '-id')[:limit] + ) + return { + 'total': mine.count(), + 'items': [ + {'aliquot': a, 'out': time_ago(a.checked_out_at), 'children': a.child_count} + for a in rows + ], + } + + def get_audits_in_progress(limit=3): """Storage audits that still have slots to check, most recent first.""" from reports.models import Report diff --git a/krill/sample/models/aliquot.py b/krill/sample/models/aliquot.py index 0d7a622..42a7000 100644 --- a/krill/sample/models/aliquot.py +++ b/krill/sample/models/aliquot.py @@ -110,6 +110,15 @@ def checked_out_by_display(self): return self.checked_out_by.get_full_name() or self.checked_out_by.get_username() return '' + def mark_exhausted(self): + """Mark the aliquot used up. Frees its box slot if it still has one.""" + exhausted = AliquotDisposition.objects.filter(disposition_type='exhausted').order_by('id').first() + if exhausted is None: + exhausted = AliquotDisposition.objects.create(name='Exhausted', disposition_type='exhausted') + AliquotLocation.objects.filter(aliquot=self).delete() + self.disposition = exhausted + self.save() + def store_in_location(self, box, row, column): """Store this aliquot in a location""" stored_disposition, _ = AliquotDisposition.objects.get_or_create( diff --git a/krill/sample/tests/test_dashboard_checkout_card.py b/krill/sample/tests/test_dashboard_checkout_card.py new file mode 100644 index 0000000..9dc5593 --- /dev/null +++ b/krill/sample/tests/test_dashboard_checkout_card.py @@ -0,0 +1,221 @@ +from datetime import timedelta + +from django.contrib.auth import get_user_model +from django.urls import reverse +from django.utils import timezone + +from person.models import UserAuditLog +from ..models.aliquot import Aliquot, AliquotDisposition, AliquotLocation +from .test_views import SampleViewTest + +User = get_user_model() + + +class CheckoutFixtureMixin: + def make_dispositions(self): + self.in_use = AliquotDisposition.objects.get_or_create( + name='In Use', defaults={'disposition_type': 'in_use'})[0] + self.exhausted = AliquotDisposition.objects.get_or_create( + name='Used', defaults={'disposition_type': 'exhausted'})[0] + + def checked_out(self, owner, hours_ago=1, **kwargs): + return Aliquot.objects.create( + sample=self.sample, aliquot_type=self.aliquot_type, disposition=self.in_use, + checked_out_by=owner, checked_out_at=timezone.now() - timedelta(hours=hours_ago), **kwargs) + + +class DashboardCheckedOutCardTest(CheckoutFixtureMixin, SampleViewTest): + def setUp(self): + super().setUp() + self.make_dispositions() + self.client.force_login(self.user) + self.other = User.objects.create_user(username='colleague', password='x') + + def _home(self): + return self.client.get(reverse('home')) + + def test_lists_only_my_in_use_aliquots_newest_first(self): + old = self.checked_out(self.user, hours_ago=48) + new = self.checked_out(self.user, hours_ago=1) + self.checked_out(self.other) # someone else's + used_up = self.checked_out(self.user) + used_up.disposition = self.exhausted + used_up.save() + Aliquot.objects.create(sample=self.sample, disposition=self.in_use) # no owner + response = self._home() + self.assertEqual([r['aliquot'] for r in response.context['checked_out']['items']], [new, old]) + self.assertEqual(response.context['checked_out']['total'], 2) + self.assertContains(response, 'Checked out by you (2)') + + def test_shows_at_most_five_rows_but_counts_all(self): + for hours in range(1, 8): + self.checked_out(self.user, hours_ago=hours) + checked_out = self._home().context['checked_out'] + self.assertEqual(len(checked_out['items']), 5) + self.assertEqual(checked_out['total'], 7) + self.assertContains(self._home(), 'Checked out by you (7)') + + def test_row_shows_details_children_and_actions(self): + parent = self.checked_out(self.user, hours_ago=50, passage='p12') + Aliquot.objects.create(sample=self.sample, parent=parent, disposition=self.stored_disposition) + Aliquot.objects.create(sample=self.sample, parent=parent, disposition=self.stored_disposition) + response = self._home() + self.assertContains(response, f'Test Sample #{parent.id}') + self.assertContains(response, 'Test Type') + self.assertContains(response, 'p12') + self.assertContains(response, 'out 2 days ago') + self.assertContains(response, '2 children') + self.assertContains(response, f'?type=aliquot&parent={parent.id}&next=/') + self.assertContains(response, 'name="action" value="done"') + self.assertContains(response, reverse('sample:aliquot_detail', kwargs={'pk': parent.id})) + self.assertContains(response, '?type=aliquot&checked_out_by=me') + + def test_singular_child_and_zero_children(self): + one = self.checked_out(self.user, hours_ago=2) + Aliquot.objects.create(sample=self.sample, parent=one, disposition=self.stored_disposition) + self.checked_out(self.user, hours_ago=1) + response = self._home() + self.assertContains(response, '1 child<') + self.assertContains(response, '0 children') + + def test_card_sits_above_freezers(self): + self.checked_out(self.user) + html = self._home().content.decode() + self.assertLess(html.index('Checked out by you'), html.index('

Freezers

')) + + def test_empty_state_is_one_line_with_a_find_link(self): + response = self._home() + self.assertContains(response, 'Nothing checked out.') + self.assertContains(response, 'Find an aliquot') + self.assertNotContains(response, 'Checked out by you (') + + +class CreateChildFlowTest(CheckoutFixtureMixin, SampleViewTest): + def setUp(self): + super().setUp() + self.make_dispositions() + self.client.force_login(self.user) + self.parent = self.checked_out(self.user, passage='p8') + self.url = reverse('sample:sample_create') + + def _get(self, **params): + return self.client.get(self.url, {'type': 'aliquot', 'parent': self.parent.id, **params}) + + def _post(self, extra=None, query=''): + data = { + 'parent': self.parent.id, 'sample': self.sample.id, 'aliquot_type': self.aliquot_type.id, + 'disposition': self.stored_disposition.id, 'access_level': 'all_members', + 'passage': 'p9', 'count': 1, **(extra or {}), + } + return self.client.post(f'{self.url}?type=aliquot&parent={self.parent.id}{query}', data) + + def test_form_prefills_sample_type_and_passage(self): + initial = self._get().context['form'].initial + self.assertEqual(initial['sample'], self.sample.id) + self.assertEqual(initial['aliquot_type'], self.aliquot_type.id) + self.assertEqual(initial['passage'], 'p8') + + def test_used_up_checkbox_is_on_by_default_for_an_in_use_parent(self): + response = self._get() + self.assertEqual(response.context['parent_aliquot'], self.parent) + self.assertContains(response, 'name="parent_used_up" value="1" checked') + # The form hides the real checkbox and draws a box from this span; without it nothing is visible + self.assertRegex(response.content.decode(), r'name="parent_used_up"[^>]*>\s*') + + def test_no_checkbox_without_parent_or_for_a_stored_parent(self): + self.assertNotContains(self.client.get(self.url, {'type': 'aliquot'}), 'parent_used_up') + stored_parent = Aliquot.objects.create(sample=self.sample, disposition=self.stored_disposition) + self.assertNotContains(self._get(parent=stored_parent.id), 'parent_used_up') + + def test_ticked_box_marks_parent_exhausted_and_logs_it(self): + response = self._post({'parent_used_up': '1'}) + self.assertEqual(response.status_code, 302) + self.parent.refresh_from_db() + self.assertEqual(self.parent.disposition, self.exhausted) + child = Aliquot.objects.get(parent=self.parent) + self.assertEqual(child.passage, 'p9') + self.assertTrue(UserAuditLog.objects.filter( + action='aliquot_updated', target_id=self.parent.id, user=self.user).exists()) + + def test_unticked_box_leaves_parent_in_use(self): + self._post() + self.parent.refresh_from_db() + self.assertEqual(self.parent.disposition, self.in_use) + self.assertTrue(Aliquot.objects.filter(parent=self.parent).exists()) + + def test_ticked_box_is_ignored_for_a_stored_parent(self): + stored_parent = Aliquot.objects.create(sample=self.sample, disposition=self.stored_disposition) + self.client.post( + f'{self.url}?type=aliquot&parent={stored_parent.id}', + {'parent': stored_parent.id, 'sample': self.sample.id, 'aliquot_type': self.aliquot_type.id, + 'disposition': self.stored_disposition.id, 'access_level': 'all_members', 'count': 1, + 'parent_used_up': '1'}) + stored_parent.refresh_from_db() + self.assertEqual(stored_parent.disposition, self.stored_disposition) + + def test_returns_to_dashboard_when_next_is_given(self): + response = self._post(query='&next=/') + self.assertRedirects(response, '/', fetch_redirect_response=False) + + def test_default_return_is_the_aliquot_list_and_foreign_next_is_ignored(self): + default = reverse('sample:sample_list') + '?type=aliquot' + self.assertRedirects(self._post(), default, fetch_redirect_response=False) + self.assertRedirects(self._post(query='&next=https://evil.example/'), default, fetch_redirect_response=False) + + def test_cancel_goes_back_to_next(self): + self.assertContains(self._get(next='/'), "window.location.href='/'") + + +class DoneActionTest(CheckoutFixtureMixin, SampleViewTest): + def setUp(self): + super().setUp() + self.make_dispositions() + self.client.force_login(self.user) + self.aliquot = self.checked_out(self.user) + self.url = reverse('sample:aliquot_detail', kwargs={'pk': self.aliquot.pk}) + + def test_done_marks_exhausted_logs_and_returns_to_next(self): + response = self.client.post(self.url, {'action': 'done', 'next': '/'}) + self.assertRedirects(response, '/', fetch_redirect_response=False) + self.aliquot.refresh_from_db() + self.assertEqual(self.aliquot.disposition, self.exhausted) + self.assertEqual(self.aliquot.checked_out_by, self.user) # kept as the record + self.assertTrue(UserAuditLog.objects.filter(action='aliquot_updated', target_id=self.aliquot.id).exists()) + + def test_done_without_next_returns_to_the_aliquot_page(self): + self.assertRedirects(self.client.post(self.url, {'action': 'done'}), self.url, fetch_redirect_response=False) + + def test_foreign_next_is_ignored(self): + response = self.client.post(self.url, {'action': 'done', 'next': 'https://evil.example/'}) + self.assertRedirects(response, self.url, fetch_redirect_response=False) + + def test_done_does_nothing_to_an_aliquot_that_is_not_in_use(self): + stored = Aliquot.objects.create(sample=self.sample, disposition=self.stored_disposition) + self.client.post(reverse('sample:aliquot_detail', kwargs={'pk': stored.pk}), {'action': 'done'}) + stored.refresh_from_db() + self.assertEqual(stored.disposition, self.stored_disposition) + + def test_done_requires_login(self): + self.client.logout() + self.assertEqual(self.client.post(self.url, {'action': 'done'}).status_code, 302) + self.aliquot.refresh_from_db() + self.assertEqual(self.aliquot.disposition, self.in_use) + + +class MarkExhaustedTest(CheckoutFixtureMixin, SampleViewTest): + def test_uses_an_existing_exhausted_disposition(self): + self.make_dispositions() + self.aliquot.mark_exhausted() + self.aliquot.refresh_from_db() + self.assertEqual(self.aliquot.disposition, self.exhausted) + + def test_creates_one_when_none_exists(self): + self.assertFalse(AliquotDisposition.objects.filter(disposition_type='exhausted').exists()) + self.aliquot.mark_exhausted() + self.aliquot.refresh_from_db() + self.assertEqual(self.aliquot.disposition.disposition_type, 'exhausted') + + def test_frees_the_box_slot(self): + self.aliquot.store_in_location(self.box, 1, 1) + self.aliquot.mark_exhausted() + self.assertFalse(AliquotLocation.objects.filter(aliquot=self.aliquot).exists()) diff --git a/krill/sample/views/create.py b/krill/sample/views/create.py index 996fbf2..c5cf84a 100644 --- a/krill/sample/views/create.py +++ b/krill/sample/views/create.py @@ -11,6 +11,7 @@ from ..models.source import Source from ..forms import SampleForm, AliquotForm, AliquotTypeForm, SourceForm from person.models import UserAuditLog +from .next_url import safe_next @method_decorator(login_required, name='dispatch') class ModelCreateView(CreateView): @@ -28,24 +29,36 @@ def get_form_class(self): def get_initial(self): """?type=aliquot&parent= opens the form with the parent and its sample filled in.""" initial = super().get_initial() - if self.request.GET.get('type') == 'aliquot': - parent_id = self.request.GET.get('parent', '') - if parent_id.isdigit(): - parent = Aliquot.objects.filter(pk=int(parent_id)).first() - if parent: - initial['parent'] = parent.pk - initial['sample'] = parent.sample_id + parent = self._parent_aliquot() + if parent: + initial['parent'] = parent.pk + initial['sample'] = parent.sample_id + initial['aliquot_type'] = parent.aliquot_type_id + initial['passage'] = parent.passage # often the same, sometimes not: editable return initial + def _parent_aliquot(self): + """The aliquot named by ?parent= when creating an aliquot, if it exists.""" + if self.request.GET.get('type') != 'aliquot': + return None + parent_id = self.request.GET.get('parent', '') + if not parent_id.isdigit(): + return None + return Aliquot.objects.filter(pk=int(parent_id)).select_related('disposition').first() + def get_success_url(self): model_type = self.request.GET.get('type', 'sample') - return f"{reverse('sample:sample_list')}?type={model_type}" + return safe_next(self.request, f"{reverse('sample:sample_list')}?type={model_type}") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) model_type = self.request.GET.get('type', 'sample') context['model_type'] = model_type context['model_name'] = model_type.replace('-', ' ').title() + parent = self._parent_aliquot() + if parent and parent.disposition and parent.disposition.disposition_type == 'in_use': + context['parent_aliquot'] = parent # offers 'Parent aliquot is exhausted' + context['cancel_url'] = safe_next(self.request, f"{reverse('sample:sample_list')}?type={model_type}") return context def form_valid(self, form): @@ -87,6 +100,21 @@ def _handle_aliquot_creation(self, form): request=self.request, ) + # The parent was checked out and used to make this: optionally mark it used up + parent = first_aliquot.parent + if (self.request.POST.get('parent_used_up') and parent + and parent.disposition and parent.disposition.disposition_type == 'in_use'): + parent.mark_exhausted() + UserAuditLog.log_action( + user=self.request.user, + action='aliquot_updated', + target_type='Aliquot', + target_id=parent.id, + target_name=str(parent), + details={'disposition': parent.disposition.name, 'source': 'create_child'}, + request=self.request, + ) + # Create additional aliquots if count > 1 created_aliquots = [first_aliquot] for _ in range(count - 1): diff --git a/krill/sample/views/detail.py b/krill/sample/views/detail.py index 6da231d..f12ae23 100644 --- a/krill/sample/views/detail.py +++ b/krill/sample/views/detail.py @@ -11,6 +11,8 @@ from ..models.source import Source from ..forms import SampleForm, AliquotForm, AliquotTypeForm, SourceForm, AliquotMoveForm from ..models.aliquot import AliquotDisposition +from person.models import UserAuditLog +from .next_url import safe_next def remaining_aliquots(sample): """Aliquots of a sample still in the freezer: stored disposition and a box position.""" @@ -139,6 +141,8 @@ def post(self, request, *args, **kwargs): return self._handle_move(request) elif action == 'checkout': return self._handle_checkout(request) + elif action == 'done': + return self._handle_done(request) else: return self._handle_edit(request) @@ -225,6 +229,21 @@ def _handle_move(self, request): context['move_form'] = move_form return render(request, self.template_name, context) + def _handle_done(self, request): + """The aliquot is used up and no child is being recorded: mark it Exhausted.""" + if self.object.disposition and self.object.disposition.disposition_type == 'in_use': + self.object.mark_exhausted() + UserAuditLog.log_action( + user=request.user, + action='aliquot_updated', + target_type='Aliquot', + target_id=self.object.id, + target_name=str(self.object), + details={'disposition': self.object.disposition.name, 'source': 'done'}, + request=request, + ) + return redirect(safe_next(request, reverse('sample:aliquot_detail', kwargs={'pk': self.object.pk}))) + def _handle_checkout(self, request): """Handle checkout action - change disposition to 'in_use'""" was_stored = self.object.disposition and self.object.disposition.disposition_type == 'stored' diff --git a/krill/sample/views/next_url.py b/krill/sample/views/next_url.py new file mode 100644 index 0000000..56397ee --- /dev/null +++ b/krill/sample/views/next_url.py @@ -0,0 +1,9 @@ +from django.utils.http import url_has_allowed_host_and_scheme + + +def safe_next(request, default): + """The ?next= / posted next= address if it stays on this site, otherwise the default.""" + candidate = request.POST.get('next') or request.GET.get('next') or '' + if candidate and url_has_allowed_host_and_scheme(candidate, allowed_hosts={request.get_host()}): + return candidate + return default diff --git a/krill/templates/krill/home.html b/krill/templates/krill/home.html index 97ac84b..6e0b316 100644 --- a/krill/templates/krill/home.html +++ b/krill/templates/krill/home.html @@ -80,6 +80,43 @@

Expiring Soon

+ + {% url 'home' as home_url %} + {% if checked_out.total %} +
+
+

Checked out by you ({{ checked_out.total }})

+ All checked out +
+
+ {% for row in checked_out.items %} +
+ shopping_cart +
+

{{ row.aliquot.sample.name }} #{{ row.aliquot.id }}{% if row.aliquot.aliquot_type %} · {{ row.aliquot.aliquot_type.name }}{% endif %}{% if row.aliquot.passage %} · {{ row.aliquot.passage }}{% endif %}

+ out {{ row.out|lower }} • {{ row.children }} child{{ row.children|pluralize:"ren" }} +
+
+ + add + Create child + +
+ {% csrf_token %} + + + +
+
+
+ {% endfor %} +
+
+ {% else %} +

Nothing checked out. Find an aliquot to check one out.

+ {% endif %} +
@@ -163,6 +200,15 @@

Recent Activity