Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion krill/reports/README.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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.
Expand Down
109 changes: 109 additions & 0 deletions krill/reports/templates/reports/checked_out_no_owner.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
{% extends 'base/layout.html' %}

{% block title %}Checked Out, No Owner{% endblock %}

{% block content %}
<div class="detail-container">
<div class="detail-header">
<h1>Checked Out, No Owner</h1>
</div>
<div class="detail-content">
<p>
{{ 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.
</p>
{% for message in messages %}
<p class="no-owner-message no-owner-{{ message.level_tag }}" role="status">{{ message }}</p>
{% endfor %}
<div class="detail-section">
{% if page_obj %}
{% if can_change %}<form method="post" id="bulkStatusForm">{% csrf_token %}<input type="hidden" name="page" value="{{ page_obj.number }}">{% endif %}
{% if can_change %}
<div class="bulk-bar">
<label for="bulkDisposition">Move ticked aliquots to</label>
<select id="bulkDisposition" name="disposition" class="toolbar-filter">
{% for d in target_dispositions %}<option value="{{ d.id }}">{{ d.name }}</option>{% endfor %}
</select>
<button type="submit" class="btn btn-sm btn-primary" id="bulkApply" disabled>Apply</button>
<span id="bulkCount" class="bulk-count">None ticked</span>
</div>
{% endif %}
<div class="detail-table-wrap">
<table class="detail-table">
<thead>
<tr>
{% if can_change %}<th><input type="checkbox" id="bulkSelectAll" aria-label="Select all on this page"></th>{% endif %}
<th>Aliquot</th><th>Type</th><th>Passage</th><th>Sample Date</th><th>Last Updated</th>
</tr>
</thead>
<tbody>
{% for a in page_obj %}
<tr>
{% if can_change %}<td><input type="checkbox" name="aliquot_ids" value="{{ a.id }}" class="bulk-row" aria-label="Select aliquot {{ a.id }}"></td>{% endif %}
<td><a href="{% url 'sample:detail' type='aliquot' pk=a.id %}" class="detail-link">{{ a.sample.name }} #{{ a.id }}</a></td>
<td>{{ a.aliquot_type.name|default:"—" }}</td>
<td>{{ a.passage|default:"—" }}</td>
<td>{{ a.sample_date|date:"Y-m-d"|default:"—" }}</td>
<td>{{ a.updated_at|date:"Y-m-d" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if can_change %}</form>{% endif %}
{% if page_obj.paginator.num_pages > 1 %}
<div class="detail-section-actions">
{% if page_obj.has_previous %}<a href="?page={{ page_obj.previous_page_number }}" class="detail-link">&larr; Previous</a>{% endif %}
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
{% if page_obj.has_next %}<a href="?page={{ page_obj.next_page_number }}" class="detail-link">Next &rarr;</a>{% endif %}
</div>
{% endif %}
{% else %}
<p>No aliquots are checked out without an owner.</p>
{% endif %}
</div>
</div>
</div>

<style>
.bulk-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.6rem; margin-bottom: 1rem; }
.bulk-count { color: var(--color-dark-variant); font-size: 0.85rem; }
.no-owner-message { padding: 0.6rem 0.9rem; border-radius: var(--border-radius-1); margin: 0.75rem 0; }
.no-owner-success { background: rgba(27, 156, 133, 0.2); color: var(--color-success); }
.no-owner-error { background: rgba(255, 0, 96, 0.2); color: var(--color-danger); }
</style>

{% if can_change %}
<script>
(function () {
var form = document.getElementById('bulkStatusForm');
if (!form) return;
var rows = Array.prototype.slice.call(form.querySelectorAll('.bulk-row'));
var all = document.getElementById('bulkSelectAll');
var apply = document.getElementById('bulkApply');
var count = document.getElementById('bulkCount');
function update() {
var n = rows.filter(function (r) { return r.checked; }).length;
apply.disabled = n === 0;
count.textContent = n === 0 ? 'None ticked' : n + ' ticked';
all.checked = n > 0 && n === rows.length;
all.indeterminate = n > 0 && n < rows.length;
}
all.addEventListener('change', function () {
rows.forEach(function (r) { r.checked = all.checked; });
update();
});
rows.forEach(function (r) { r.addEventListener('change', update); });
form.addEventListener('submit', function (e) {
var n = rows.filter(function (r) { return r.checked; }).length;
var sel = document.getElementById('bulkDisposition');
var name = sel.options[sel.selectedIndex].text;
if (!confirm('Mark ' + n + ' aliquot' + (n === 1 ? '' : 's') + ' as ' + name + '?')) e.preventDefault();
});
update();
})();
</script>
{% endif %}
{% endblock %}
4 changes: 4 additions & 0 deletions krill/reports/templates/reports/reports_dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ <h3>Active Alerts</h3>
<span class="material-icons-round">assignment_turned_in</span>
Start Storage Audit
</a>
<a href="{% url 'reports:checked_out_no_owner' %}" class="action-btn">
<span class="material-icons-round">person_off</span>
Checked Out, No Owner
</a>
<a href="{% url 'sample:sample_search' %}" class="action-btn">
<span class="material-icons-round">search</span>
Search Samples
Expand Down
158 changes: 158 additions & 0 deletions krill/reports/test_checked_out_no_owner.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 3 additions & 0 deletions krill/reports/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'),

Expand Down
58 changes: 57 additions & 1 deletion krill/reports/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading