diff --git a/krill/krill/views/home.py b/krill/krill/views/home.py
index 9b8d444..fdfe1ad 100644
--- a/krill/krill/views/home.py
+++ b/krill/krill/views/home.py
@@ -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 = (
@@ -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')
diff --git a/krill/person/migrations/0006_low_count_levels.py b/krill/person/migrations/0006_low_count_levels.py
new file mode 100644
index 0000000..4c1a078
--- /dev/null
+++ b/krill/person/migrations/0006_low_count_levels.py
@@ -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'),
+ ),
+ ]
diff --git a/krill/person/models.py b/krill/person/models.py
index c43b59d..a99e3ba 100644
--- a/krill/person/models.py
+++ b/krill/person/models.py
@@ -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,
diff --git a/krill/reports/README.md b/krill/reports/README.md
index 2bf9e3e..9c7ca89 100644
--- a/krill/reports/README.md
+++ b/krill/reports/README.md
@@ -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.
diff --git a/krill/reports/attention.py b/krill/reports/attention.py
index b88d8b0..83c1260 100644
--- a/krill/reports/attention.py
+++ b/krill/reports/attention.py
@@ -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
@@ -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))
@@ -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 --------------------------------------------------------------
diff --git a/krill/reports/test_attention.py b/krill/reports/test_attention.py
index 0ef60f6..bca685f 100644
--- a/krill/reports/test_attention.py
+++ b/krill/reports/test_attention.py
@@ -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):
@@ -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)
diff --git a/krill/sample/forms.py b/krill/sample/forms.py
index efc98df..4c0c06c 100644
--- a/krill/sample/forms.py
+++ b/krill/sample/forms.py
@@ -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',
@@ -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(
diff --git a/krill/sample/low_count.py b/krill/sample/low_count.py
new file mode 100644
index 0000000..8cd4cb4
--- /dev/null
+++ b/krill/sample/low_count.py
@@ -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
diff --git a/krill/sample/migrations/0009_low_count_levels.py b/krill/sample/migrations/0009_low_count_levels.py
new file mode 100644
index 0000000..4f474b7
--- /dev/null
+++ b/krill/sample/migrations/0009_low_count_levels.py
@@ -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),
+ ),
+ ]
diff --git a/krill/sample/models/sample.py b/krill/sample/models/sample.py
index c5d18b3..c86014a 100644
--- a/krill/sample/models/sample.py
+++ b/krill/sample/models/sample.py
@@ -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'),
@@ -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']
diff --git a/krill/sample/tests/test_dashboard_sections.py b/krill/sample/tests/test_dashboard_sections.py
index 8dad199..9f128f1 100644
--- a/krill/sample/tests/test_dashboard_sections.py
+++ b/krill/sample/tests/test_dashboard_sections.py
@@ -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
@@ -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(
diff --git a/krill/sample/tests/test_lineage_and_remaining.py b/krill/sample/tests/test_lineage_and_remaining.py
index 515dedc..d3b1a14 100644
--- a/krill/sample/tests/test_lineage_and_remaining.py
+++ b/krill/sample/tests/test_lineage_and_remaining.py
@@ -95,8 +95,8 @@ def setUp(self):
def _disp(self, name, kind):
return AliquotDisposition.objects.get_or_create(name=name, defaults={'disposition_type': kind})[0]
- def test_lists_only_stored_aliquots_in_a_box(self):
- # self.aliquot is 'stored' but has no box position, so it is not "remaining"
+ def test_lists_every_stored_aliquot_whether_or_not_it_has_a_box_position(self):
+ # self.aliquot is 'stored' with no box position: it still counts as remaining
placed = Aliquot.objects.create(
sample=self.sample, aliquot_type=self.aliquot_type, disposition=self.stored_disposition,
passage='p8', sample_date=datetime.date(2024, 3, 5),
@@ -110,15 +110,27 @@ def test_lists_only_stored_aliquots_in_a_box(self):
other.store_in_location(self.box, 1, 3)
response = self.client.get(self.url)
- self.assertEqual(response.context['remaining_aliquots'], [placed])
- self.assertEqual(response.context['remaining_count'], 1)
- self.assertContains(response, 'Remaining aliquots (1)')
+ self.assertCountEqual(response.context['remaining_aliquots'], [placed, self.aliquot])
+ self.assertEqual(response.context['remaining_count'], 2)
+ self.assertContains(response, 'Remaining aliquots (2)')
for text in ('p8', '2024-03-05', 'Test Type', 'Test Device', 'Test Box', '(1, 2)'):
self.assertContains(response, text)
- for gone in (in_use, exhausted, disposed, other, self.aliquot):
+ for gone in (in_use, exhausted, disposed, other):
self.assertNotIn(gone, response.context['remaining_aliquots'])
+ def test_aliquot_without_a_position_shows_a_dash_for_its_location(self):
+ response = self.client.get(self.url)
+ self.assertEqual(response.context['remaining_aliquots'], [self.aliquot])
+ self.assertRegex(response.content.decode(), r'
+
+ {{ low_count.count }}{% if low_count.state and low_count.enabled %}
+ {% if low_count.state == 'alert' %}Alert{% else %}Low{% endif %}{% endif %}
+
+
+
+ {% if low_count.enabled %}On: warn at {{ low_count.warn }} or fewer, alert at {{ low_count.alert }} or fewer{% else %}Off for this sample{% endif %}
+