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
33 changes: 33 additions & 0 deletions krill/krill/views/home.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ def post(self, request):
from django.http import HttpResponseForbidden
return HttpResponseForbidden("Only lab admins can change site configuration.")

if request.POST.get('form') == 'alert_levels':
return self._save_alert_levels(request)

config = SiteConfiguration.load()
consumables_enabled = request.POST.get('consumables_enabled') == 'on'
consumables_ordering_enabled = (
Expand Down Expand Up @@ -316,3 +319,33 @@ def post(self, request):
from django.contrib import messages
messages.success(request, 'Site configuration saved.')
return redirect('settings')

def _save_alert_levels(self, request):
"""Save the lab-wide low-count levels. Leaves the feature switches alone."""
from django.contrib import messages
try:
warn = int(request.POST.get('low_count_warn', ''))
alert = int(request.POST.get('low_count_alert', ''))
except ValueError:
warn = alert = -1
if warn < 0 or alert < 0:
messages.error(request, 'Enter whole numbers, zero or more, for both levels.')
elif alert > warn:
messages.error(request, 'The alert level cannot be higher than the warn level.')
else:
config = SiteConfiguration.load()
config.low_count_warn = warn
config.low_count_alert = alert
config.updated_by = request.user
config.save()
UserAuditLog.log_action(
user=request.user,
action='update',
target_type='SiteConfiguration',
target_id=config.pk,
target_name='Site Configuration',
details={'low_count_warn': warn, 'low_count_alert': alert},
request=request,
)
messages.success(request, f'Low-count levels saved: warn at {warn} or fewer, alert at {alert} or fewer.')
return redirect('settings')
23 changes: 23 additions & 0 deletions krill/person/migrations/0006_low_count_levels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 6.1.3 on 2026-11-11 17:03

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('person', '0005_bigint_object_ids'),
]

operations = [
migrations.AddField(
model_name='siteconfiguration',
name='low_count_alert',
field=models.PositiveIntegerField(default=3, help_text='Alert when a sample has this many stored aliquots or fewer'),
),
migrations.AddField(
model_name='siteconfiguration',
name='low_count_warn',
field=models.PositiveIntegerField(default=5, help_text='Warn when a sample has this many stored aliquots or fewer'),
),
]
8 changes: 8 additions & 0 deletions krill/person/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,14 @@ class SiteConfiguration(models.Model):
"""Singleton site-wide feature flags. Access via SiteConfiguration.load()."""
consumables_enabled = models.BooleanField(default=False)
consumables_ordering_enabled = models.BooleanField(default=False)
low_count_warn = models.PositiveIntegerField(
default=5,
help_text='Warn when a sample has this many stored aliquots or fewer',
)
low_count_alert = models.PositiveIntegerField(
default=3,
help_text='Alert when a sample has this many stored aliquots or fewer',
)
updated_at = models.DateTimeField(auto_now=True)
updated_by = models.ForeignKey(
User,
Expand Down
6 changes: 4 additions & 2 deletions krill/reports/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,11 @@ The pill in the Dashboard header ("All clear", or "N need attention", amber for
- **Low stock:** a consumable at or below its low-stock threshold. It is an alert when it is out of stock and a warning otherwise.
- **Expiring soon:** a consumable that expires within 30 days (warning).

These two only appear when Consumables are turned on in Settings. Items come from your data; nobody types them in. The older manually created alerts are gone (the table was empty in the lab's backup, and the data model is kept).
- **Low sample counts:** a sample with few stored aliquots left. It is an alert at the alert level or fewer and a warning at the warn level or fewer (lab default: warn at 5, alert at 3; a lab admin sets these in **Settings > Low-count alerts**). A sample's count is its aliquots whose disposition is Stored. A box position is not needed, and exhausted, in-use, disposed and deleted aliquots do not count. A sample with no aliquots at all is not checked. A sample can have its own levels, or switch the check off, in its **Edit** form (fields **Low-count alerts**, **Warn at**, **Alert at**). The Samples list shows each sample's stored count with a badge, and has a **Low count** filter.

**Silence.** Lab managers and admins can press **Silence** on an item when the lab does not want to hear about it, for example a consumable it is phasing out. The switch lives on the consumable itself (`alerts_silenced`), so it also leaves the Low Stock and Expiring Soon tiles, their filtered lists and the reorder list. Silenced items stay on the page under **Silenced**, with **Turn back on**. Silencing is saved to the audit log.
The two consumables sources only appear when Consumables are turned on in Settings; low sample counts always appear. Items come from your data; nobody types them in. The older manually created alerts are gone (the table was empty in the lab's backup, and the data model is kept).

**Silence.** Lab managers and admins can press **Silence** on an item when the lab does not want to hear about it, for example a consumable it is phasing out or a sample that is deliberately kept low. The switch lives on the record itself: a consumable's `alerts_silenced` (which also takes it off the Low Stock and Expiring Soon tiles, their filtered lists and the reorder list), or a sample's low-count check being switched off. Silenced items stay on the page under **Silenced**, with **Turn back on**. Silencing is saved to the audit log.

**How it is built.** `reports/attention.py` works everything out, and the pill, this page and the Reports page all read from it, so they always agree. Each item has a stable key such as `low_stock:consumable:12`. To add a source, write a function that returns a list of `AttentionItem`, register it with `register_source()`, and (if it can be silenced) register a silencer for its record type. Email notifications, when added, should use the same items and keys to avoid sending the same alert twice.

Expand Down
37 changes: 34 additions & 3 deletions krill/reports/attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
register it with register_source(). Each item has a stable `key`, so silencing and email
de-duplication can refer to the same item over time.

An item is silenced by a flag on the record it is about (for example Consumable.alerts_silenced),
not by a separate table, because the lab sets such things per record. Silenced items are still
returned, marked silenced, so the overview can show them; they are left out of the counts.
An item is silenced by a flag on the record it is about (Consumable.alerts_silenced, or a sample's
low_count_check being off), not by a separate table, because the lab sets such things per record.
Silenced items are still returned, marked silenced, so the overview can show them; they are left
out of the counts.
"""
from dataclasses import dataclass
from datetime import date, timedelta
Expand Down Expand Up @@ -126,6 +127,34 @@ def expiring_items():
return items


# --- low sample counts -------------------------------------------------------

def low_count_items():
from sample import low_count
items = []
for row in low_count.low_samples():
sample, count = row['sample'], row['count']
left = 'No stored aliquots left' if count == 0 else f'{count} stored aliquot{"s" if count != 1 else ""} left'
items.append(AttentionItem(
source='low_count',
key=f'low_count:sample:{sample.pk}',
title=sample.name,
detail=f'{left} (alert at {row["alert"]} or fewer, warn at {row["warn"]} or fewer)',
level=LEVEL_ALERT if row['state'] == low_count.ALERT else LEVEL_WARN,
url=reverse('sample:detail', kwargs={'type': 'sample', 'pk': sample.pk}),
silenced=row['silenced'],
target_type='sample',
target_id=sample.pk,
))
return items


def _silence_sample(target_id, silenced):
from sample.models.sample import Sample
# Silenced means the low-count check is switched off for this sample
return bool(Sample.objects.filter(pk=target_id).update(low_count_check=not silenced))


def _silence_consumable(target_id, silenced):
from consumables.models.consumable import Consumable
return bool(Consumable.objects.filter(pk=target_id, deleted=False).update(alerts_silenced=silenced))
Expand All @@ -134,6 +163,8 @@ def _silence_consumable(target_id, silenced):
register_source('low_stock', 'Low stock', 'production_quantity_limits', low_stock_items, _consumables_enabled)
register_source('expiring', 'Expiring soon', 'event_busy', expiring_items, _consumables_enabled)
register_silencer('consumable', _silence_consumable)
register_source('low_count', 'Low sample counts', 'science', low_count_items)
register_silencer('sample', _silence_sample)


# --- reading it --------------------------------------------------------------
Expand Down
20 changes: 18 additions & 2 deletions krill/reports/test_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,16 @@ def test_all_clear(self):
def test_consumable_sources_are_hidden_when_the_feature_is_off(self):
self.consumable(quantity='0', threshold='5')
self.set_consumables(False)
self.assertEqual(attention.groups(), [])
# Only the sources that do not depend on Consumables remain
self.assertEqual([g['source'].name for g in attention.groups()], ['low_count'])
self.assertEqual(attention.summary(), {'count': 0, 'level': None})

def test_no_groups_at_all_when_no_source_is_available(self):
from unittest.mock import patch
with patch.object(attention, 'SOURCES', []):
self.assertEqual(attention.groups(), [])
self.assertEqual(attention.summary(), {'count': 0, 'level': None})


class SilenceTest(AttentionFixture):
def test_silence_and_unsilence_a_consumable(self):
Expand Down Expand Up @@ -172,9 +179,18 @@ def test_all_clear_and_empty_groups(self):
self.assertContains(response, 'Nothing needs attention.')

def test_explains_when_nothing_is_watched(self):
from unittest.mock import patch
self.client.force_login(self.user)
with patch.object(attention, 'SOURCES', []):
self.assertContains(self.client.get(self.url), 'Nothing is being watched yet.')

def test_consumable_groups_are_absent_when_the_feature_is_off(self):
self.set_consumables(False)
self.client.force_login(self.user)
self.assertContains(self.client.get(self.url), 'Nothing is being watched yet.')
response = self.client.get(self.url)
self.assertContains(response, 'Low sample counts (0)')
self.assertNotContains(response, 'Low stock (')
self.assertNotContains(response, 'Expiring soon (')

def test_silenced_items_are_displayed_separately(self):
self.consumable('Quiet', alerts_silenced=True)
Expand Down
17 changes: 16 additions & 1 deletion krill/sample/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@
class SampleForm(forms.ModelForm):
class Meta:
model = Sample
fields = ['name', 'experiment', 'source', 'notes', 'access_level']
fields = [
'name', 'experiment', 'source', 'notes', 'access_level',
'low_count_check', 'low_count_warn', 'low_count_alert',
]
labels = {
'low_count_check': 'Low-count alerts',
'low_count_warn': 'Warn at (stored aliquots)',
'low_count_alert': 'Alert at (stored aliquots)',
}
help_texts = {
'name': 'Unique identifier for this sample (e.g., cell line name)',
'experiment': 'Experiment identifier or number associated with this sample',
Expand All @@ -18,6 +26,13 @@ class Meta:
'notes': forms.Textarea(attrs={'rows': 4}),
}

def clean(self):
cleaned = super().clean()
warn, alert = cleaned.get('low_count_warn'), cleaned.get('low_count_alert')
if warn is not None and alert is not None and alert > warn:
self.add_error('low_count_alert', 'The alert level cannot be higher than the warn level.')
return cleaned

class AliquotForm(forms.ModelForm):
# count: number of aliquots to create at once (not a model field)
count = forms.IntegerField(
Expand Down
65 changes: 65 additions & 0 deletions krill/sample/low_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Low-count alerts: warn when a sample has few stored aliquots left.

A sample's count is its aliquots whose disposition is Stored (no box position needed; soft-deleted
aliquots are ignored). It is **alert** at or below the alert level and **warn** at or below the warn
level. The levels come from the lab default (SiteConfiguration, set in Settings) unless the sample
has its own. A sample with no aliquots at all is not checked, and a sample can opt out with
Sample.low_count_check.
"""
from typing import Optional

from person.models import SiteConfiguration

ALERT = 'alert'
WARN = 'warn'


def levels_for(sample, config=None):
"""(warn, alert) for a sample. The alert level is never above the warn level."""
config = config or SiteConfiguration.load()
warn = config.low_count_warn if sample.low_count_warn is None else sample.low_count_warn
alert = config.low_count_alert if sample.low_count_alert is None else sample.low_count_alert
return warn, min(alert, warn)


def state_for_count(count, warn, alert) -> Optional[str]:
if count <= alert:
return ALERT
if count <= warn:
return WARN
return None


def state_for(sample, config=None) -> Optional[str]:
"""'alert', 'warn' or None for a sample annotated by Sample.objects.with_stored_count().

Ignores the opt-out switch, so a silenced sample still shows how low it is.
"""
if not sample.aliquot_total:
return None
warn, alert = levels_for(sample, config)
return state_for_count(sample.stored_count, warn, alert)


def low_samples():
"""Every sample that is at or below its warn level, as dicts with its counts and levels.

Samples that opted out are included with silenced=True; callers decide what to do with them.
"""
from .models.sample import Sample

config = SiteConfiguration.load()
rows = []
for sample in Sample.objects.with_stored_count().filter(aliquot_total__gt=0).order_by('name', 'id'):
warn, alert = levels_for(sample, config)
state = state_for_count(sample.stored_count, warn, alert)
if state:
rows.append({
'sample': sample,
'count': sample.stored_count,
'warn': warn,
'alert': alert,
'state': state,
'silenced': not sample.low_count_check,
})
return rows
28 changes: 28 additions & 0 deletions krill/sample/migrations/0009_low_count_levels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 6.1.3 on 2026-11-11 17:03

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('sample', '0008_aliquot_checked_out_by_at'),
]

operations = [
migrations.AddField(
model_name='sample',
name='low_count_alert',
field=models.PositiveIntegerField(blank=True, help_text='Alert at this many stored aliquots or fewer. Leave blank to use the lab default.', null=True),
),
migrations.AddField(
model_name='sample',
name='low_count_check',
field=models.BooleanField(default=True, help_text='Warn when few stored aliquots are left. Turn off for a sample that is deliberately kept low.'),
),
migrations.AddField(
model_name='sample',
name='low_count_warn',
field=models.PositiveIntegerField(blank=True, help_text='Warn at this many stored aliquots or fewer. Leave blank to use the lab default.', null=True),
),
]
35 changes: 35 additions & 0 deletions krill/sample/models/sample.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
from django.db import models
from django.db.models import Count, Q
from storage.models import Box


class SampleQuerySet(models.QuerySet):
def with_stored_count(self):
"""Add stored_count (aliquots whose disposition is Stored) and aliquot_total (all aliquots).

Soft-deleted aliquots are left out of both. A box position is not required: many stored
aliquots have not been given one.
"""
return self.annotate(
stored_count=Count(
'aliquots',
filter=Q(aliquots__deleted=False, aliquots__disposition__disposition_type='stored'),
),
aliquot_total=Count('aliquots', filter=Q(aliquots__deleted=False)),
)


class Sample(models.Model):
ACCESS_LEVEL_CHOICES = [
('admins_only', 'Admins Only'),
Expand All @@ -19,6 +37,23 @@ class Sample(models.Model):
help_text="Restrict access to specific user tiers"
)

low_count_check = models.BooleanField(
default=True,
help_text='Warn when few stored aliquots are left. Turn off for a sample that is deliberately kept low.',
)
low_count_warn = models.PositiveIntegerField(
null=True,
blank=True,
help_text='Warn at this many stored aliquots or fewer. Leave blank to use the lab default.',
)
low_count_alert = models.PositiveIntegerField(
null=True,
blank=True,
help_text='Alert at this many stored aliquots or fewer. Leave blank to use the lab default.',
)

objects = SampleQuerySet.as_manager()

class Meta:
ordering = ['name']

Expand Down
3 changes: 3 additions & 0 deletions krill/sample/tests/test_dashboard_sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from consumables.models.consumable import Consumable
from consumables.models.consumable_type import ConsumableType
from ..models.sample import Sample
from person.models import SiteConfiguration
from ..models.aliquot import Aliquot, AliquotDisposition
from .test_views import SampleViewTest
Expand Down Expand Up @@ -100,6 +101,8 @@ def setUp(self):
config = SiteConfiguration.load()
config.consumables_enabled = True
config.save()
# The fixture's sample has one stored aliquot, which would count as low; these tests are about consumables
Sample.objects.update(low_count_check=False)

def _consumable(self, quantity='3', threshold='5', **kwargs):
return Consumable.objects.create(
Expand Down
Loading
Loading