diff --git a/krill/reports/README.md b/krill/reports/README.md index bdffcee..31872f3 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 aliquots 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 aliquot is never put back in storage. Each change is saved as an "Aliquot Updated" entry in the audit log, and only aliquots 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 exhausted, as a record of who used it. + +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 **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..5a265d1 --- /dev/null +++ b/krill/reports/templates/reports/checked_out_no_owner.html @@ -0,0 +1,109 @@ +{% 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 aliquots 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 %} + + + + + + + {% 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 can_change %}
{% endif %} + {% 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 %} +
+
+
+ + + +{% if can_change %} + +{% 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..8f5bea2 --- /dev/null +++ b/krill/reports/test_checked_out_no_owner.py @@ -0,0 +1,158 @@ +from django.contrib.auth import get_user_model +from django.test import TestCase +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 + +User = get_user_model() + + +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')) + 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) + + +class CheckedOutNoOwnerReportTest(ReportTestBase): + 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) + + +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/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..938d314 100644 --- a/krill/reports/views.py +++ b/krill/reports/views.py @@ -22,13 +22,69 @@ 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. + + 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 an aliquot 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, + 'can_change': can_change, + 'target_dispositions': target_dispositions, + }) + + # 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..445daf4 --- /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 exhausted, 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..430f7eb 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 exhausted, 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..01af8cf --- /dev/null +++ b/krill/sample/tests/test_checked_out.py @@ -0,0 +1,172 @@ +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 exhausted + 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_only_when_filtered(self): + self._make(self.user) + filtered = self._list() + self.assertContains(filtered, 'Checked Out') + self.assertContains(filtered, 'name="checked_out_by" value="me"') + plain = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot'}) + self.assertNotContains(plain, 'Checked Out') + + 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 + + +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/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..54aa155 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 exhausted + 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') @@ -124,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 @@ -157,6 +175,13 @@ 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' + 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 @@ -165,6 +190,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/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/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 %}
diff --git a/krill/templates/sample/list.html b/krill/templates/sample/list.html index 0516186..d355953 100644 --- a/krill/templates/sample/list.html +++ b/krill/templates/sample/list.html @@ -19,6 +19,8 @@

{{ 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 %} @@ -38,12 +40,7 @@

{{ model_name }}

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

{{ model_name }}

- {% if search_query or disposition_filter or aliquot_type_filter or hide_finished or sample_filter %} +
+ + {% if checked_out_by_me %}check{% endif %} + Checked out by me · {{ checked_out_count }} + + + {% if hide_finished %}check{% endif %} + Hide exhausted + +
+ {% if search_query or disposition_filter or aliquot_type_filter or sample_filter %}
{% if search_query %} @@ -72,12 +81,6 @@

{{ model_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 %} @@ -144,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 %} @@ -173,6 +176,7 @@

{{ model_name }}

Disposition Location Sample Date + {% if checked_out_by_me %}Checked Out{% endif %} @@ -194,6 +198,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 +206,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" }}