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
18 changes: 18 additions & 0 deletions krill/consumables/migrations/0002_consumable_alerts_silenced.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 6.1.3 on 2026-11-11 16:38

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('consumables', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='consumable',
name='alerts_silenced',
field=models.BooleanField(default=False, help_text='Stop low-stock and expiry alerts and reorder suggestions for this consumable, for example one the lab is phasing out'),
),
]
8 changes: 8 additions & 0 deletions krill/consumables/models/consumable.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ def active(self):
return self.filter(deleted=False)

def low_stock(self):
"""Low-stock consumables that still raise alerts (silenced ones are left out)."""
return self.active().filter(
low_stock_threshold__isnull=False,
quantity__lte=F('low_stock_threshold'),
alerts_silenced=False,
)


Expand Down Expand Up @@ -57,6 +59,12 @@ class Consumable(models.Model):
blank=True,
)

alerts_silenced = models.BooleanField(
default=False,
help_text='Stop low-stock and expiry alerts and reorder suggestions for this consumable, '
'for example one the lab is phasing out',
)

expiration_date = models.DateField(null=True, blank=True)
notes = models.TextField(blank=True, null=True)
specs = models.JSONField(default=dict, blank=True)
Expand Down
2 changes: 2 additions & 0 deletions krill/consumables/views/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ def get_queryset(self):
qs = qs.filter(
low_stock_threshold__isnull=False,
quantity__lte=F('low_stock_threshold'),
alerts_silenced=False,
)

# Expiring soon filter (within 30 days)
Expand All @@ -72,6 +73,7 @@ def get_queryset(self):
expiration_date__isnull=False,
expiration_date__lte=today + timedelta(days=30),
expiration_date__gte=today,
alerts_silenced=False,
)

# Sorting
Expand Down
16 changes: 8 additions & 8 deletions krill/krill/views/home.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from sample.models.aliquot import Aliquot, AliquotLocation
from storage.models.storage import Box
from person.models import UserAuditLog, UserPreference, SiteConfiguration, UserRole
from reports import attention
from person.decorators import require_minimum_role

__all__ = (
Expand All @@ -26,10 +27,12 @@ class HomeView(View):

def get(self, request):
# Get dashboard statistics
stats = get_dashboard_statistics()
attention_summary = attention.summary()
stats = get_dashboard_statistics(attention_summary)
freezers = get_freezer_cards()
return render(request, self.template_name, {
'stats': stats,
'attention': attention_summary,
'freezers': freezers,
'show_sites': len({card['device'].site_id for card in freezers}) > 1,
'checked_out': get_checked_out(request.user),
Expand All @@ -44,7 +47,7 @@ def dashboard_stats(request):
stats = get_dashboard_statistics()
return JsonResponse(stats)

def get_dashboard_statistics():
def get_dashboard_statistics(attention_summary=None):
"""Calculate dashboard statistics from database"""
try:
# Active samples (non-deleted)
Expand All @@ -68,12 +71,8 @@ def get_dashboard_statistics():
action='report_generated',
timestamp__gte=timezone.now() - timedelta(days=7)
).count()
# Alerts (using audit logs for now)
# In a real system, you'd have an Alert model
alerts = UserAuditLog.objects.filter(
action__in=['alert_created', 'warning_created'],
timestamp__gte=timezone.now() - timedelta(days=1)
).count()
# Items needing attention: the same count the header pill and the overview page use
alerts = (attention_summary or attention.summary())['count']
# Consumables stats (only when feature is enabled)
low_stock_count = 0
expiring_soon_count = 0
Expand All @@ -85,6 +84,7 @@ def get_dashboard_statistics():
expiration_date__isnull=False,
expiration_date__lte=date.today() + timedelta(days=30),
expiration_date__gte=date.today(),
alerts_silenced=False,
).count()

return {
Expand Down
15 changes: 12 additions & 3 deletions 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**), where alerts are listed, and where aliquots checked out with no recorded owner 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 the items that need attention 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 @@ -48,9 +48,18 @@ A person's own checked-out aliquots are in the Aliquots list with the **Checked

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
## Needs attention

**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.
The pill in the Dashboard header ("All clear", or "N need attention", amber for a warning and red for an alert) opens **Needs Attention** (`/reports/alerts/`). It lists everything that needs action, grouped by what it is about:

- **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).

**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.

**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.

## Other pieces

Expand Down
170 changes: 170 additions & 0 deletions krill/reports/attention.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""What needs attention: one place that works out the lab's pending action items.

The header pill, the overview page and (later) email notifications all read from here, so they
always agree. To add a source, write a function that returns a list of AttentionItem and
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.
"""
from dataclasses import dataclass
from datetime import date, timedelta
from typing import Callable, List, Optional

from django.db.models import F
from django.urls import reverse

LEVEL_ALERT = 'alert'
LEVEL_WARN = 'warn'
_LEVEL_RANK = {LEVEL_WARN: 1, LEVEL_ALERT: 2}

EXPIRING_SOON_DAYS = 30


@dataclass(frozen=True)
class AttentionItem:
source: str # source name, e.g. 'low_stock'
key: str # stable id, e.g. 'low_stock:consumable:12'
title: str
detail: str
level: str # LEVEL_ALERT or LEVEL_WARN
url: str # where to go to deal with it
silenced: bool
target_type: str # what the item is about: 'consumable'
target_id: int


@dataclass(frozen=True)
class Source:
name: str
label: str
icon: str
collect: Callable[[], List[AttentionItem]]
available: Callable[[], bool]


SOURCES: List[Source] = []
# target_type -> function(target_id, silenced) -> True if a record was changed
SILENCERS = {}


def register_source(name, label, icon, collect, available=lambda: True):
SOURCES.append(Source(name, label, icon, collect, available))


def register_silencer(target_type, setter):
SILENCERS[target_type] = setter


def _number(value):
"""Decimal('3.000') -> '3'"""
return format(value.normalize(), 'f')


# --- consumables -------------------------------------------------------------

def _consumables_enabled():
from person.models import SiteConfiguration
return SiteConfiguration.load().consumables_enabled


def _consumable_url(consumable):
return reverse('consumables:detail', kwargs={'type': 'consumable', 'pk': consumable.pk})


def low_stock_items():
from consumables.models.consumable import Consumable
rows = Consumable.objects.active().filter(
low_stock_threshold__isnull=False,
quantity__lte=F('low_stock_threshold'),
).order_by('name', 'id')
return [
AttentionItem(
source='low_stock',
key=f'low_stock:consumable:{c.pk}',
title=c.name,
detail=(
f'Out of stock (reorder at {_number(c.low_stock_threshold)} {c.unit})'
if c.quantity <= 0 else
f'{_number(c.quantity)} {c.unit} left (reorder at {_number(c.low_stock_threshold)})'
),
level=LEVEL_ALERT if c.quantity <= 0 else LEVEL_WARN,
url=_consumable_url(c),
silenced=c.alerts_silenced,
target_type='consumable',
target_id=c.pk,
)
for c in rows
]


def expiring_items():
from consumables.models.consumable import Consumable
today = date.today()
rows = Consumable.objects.active().filter(
expiration_date__isnull=False,
expiration_date__gte=today,
expiration_date__lte=today + timedelta(days=EXPIRING_SOON_DAYS),
).order_by('expiration_date', 'name', 'id')
items = []
for c in rows:
days = (c.expiration_date - today).days
when = 'today' if days == 0 else f'in {days} day{"s" if days != 1 else ""}'
items.append(AttentionItem(
source='expiring',
key=f'expiring:consumable:{c.pk}',
title=c.name,
detail=f'Expires {c.expiration_date:%Y-%m-%d} ({when})',
level=LEVEL_WARN,
url=_consumable_url(c),
silenced=c.alerts_silenced,
target_type='consumable',
target_id=c.pk,
))
return items


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))


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)


# --- reading it --------------------------------------------------------------

def groups():
"""[{'source': Source, 'active': [...], 'silenced': [...]}] for every source that is available."""
result = []
for source in SOURCES:
if not source.available():
continue
items = source.collect()
result.append({
'source': source,
'active': [i for i in items if not i.silenced],
'silenced': [i for i in items if i.silenced],
})
return result


def worst_level(items) -> Optional[str]:
levels = [i.level for i in items]
return max(levels, key=lambda lv: _LEVEL_RANK[lv]) if levels else None


def summary():
"""{'count': int, 'level': 'alert' | 'warn' | None} over the items that are not silenced."""
active = [i for g in groups() for i in g['active']]
return {'count': len(active), 'level': worst_level(active)}


def silence(target_type, target_id, silenced=True):
"""Silence or unsilence everything about one record. Returns False if nothing matched."""
setter = SILENCERS.get(target_type)
return bool(setter and setter(target_id, silenced))
45 changes: 4 additions & 41 deletions krill/reports/templates/reports/reports_dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ <h3>In Progress</h3>
<p>{{ audits_in_progress }}</p>
</div>
</a>
<a href="{% url 'reports:alert_list' %}" class="stat-card clickable {% if active_alerts %}stat-card-warning{% endif %}">
<span class="material-icons-round">warning</span>
<a href="{% url 'reports:alert_list' %}" class="stat-card clickable {% if attention.count %}stat-card-warning{% endif %}">
<span class="material-icons-round">{% if attention.count %}warning{% else %}check_circle{% endif %}</span>
<div class="stat-info">
<h3>Active Alerts</h3>
<p>{{ active_alerts }}</p>
<h3>Needs Attention</h3>
<p>{% if attention.count %}{{ attention.count }} item{{ attention.count|pluralize }}{% else %}All clear{% endif %}</p>
</div>
</a>
</div>
Expand Down Expand Up @@ -78,43 +78,6 @@ <h2>Recent Audits</h2>
{% endfor %}
</div>
</div>

<!-- Recent Alerts -->
<div class="recent-activity">
<div class="section-header">
<h2>Recent Alerts</h2>
<button class="view-all" onclick="window.location.href='{% url 'reports:alert_list' %}'">View All</button>
</div>
<div class="activity-list">
{% if recent_alerts %}
{% for alert in recent_alerts %}
<div class="activity-item">
<span class="material-icons-round">
{% if alert.severity == 'critical' %}
error
{% elif alert.severity == 'high' %}
warning
{% else %}
info
{% endif %}
</span>
<div class="activity-info">
<p><strong>{{ alert.title }}</strong></p>
<small>{{ alert.message|truncatechars:60 }} - {{ alert.created_at|timesince }} ago</small>
</div>
</div>
{% endfor %}
{% else %}
<div class="activity-item">
<span class="material-icons-round">check_circle</span>
<div class="activity-info">
<p>No active alerts</p>
<small>System is running normally</small>
</div>
</div>
{% endif %}
</div>
</div>
</div>

{% endblock %}
Loading
Loading