From dfe6cd654d58e744cfede3c17cadcc9ea8449033 Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Mon, 9 Nov 2026 19:56:42 -0700 Subject: [PATCH 1/2] Rework the dashboard: freezer fill cards, readable activity, audits in progress Replace the welcome banner with a one-line summary. Add a card per freezer with a fill bar (green to 70%, amber to 90%, red above), used and total slots and the last change. Write recent activity as 'user created aliquot X in Freezer / Box Y' with a link, show audits still in progress, drop Settings from Quick Actions and cap the page width at 1600px. Co-Authored-By: Claude Sonnet 5.5 --- krill/krill/tests/__init__.py | 0 krill/krill/tests/test_dashboard.py | 102 +++++++++++++++ krill/krill/views/home.py | 172 +++++++++++++++++-------- krill/templates/krill/home.html | 192 ++++++++++++++++++---------- 4 files changed, 344 insertions(+), 122 deletions(-) create mode 100644 krill/krill/tests/__init__.py create mode 100644 krill/krill/tests/test_dashboard.py diff --git a/krill/krill/tests/__init__.py b/krill/krill/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/krill/krill/tests/test_dashboard.py b/krill/krill/tests/test_dashboard.py new file mode 100644 index 0000000..f49a859 --- /dev/null +++ b/krill/krill/tests/test_dashboard.py @@ -0,0 +1,102 @@ +import json + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse + +from krill.views.home import fill_level +from person.models import UserAuditLog +from reports.models import Report, ReportTemplate +from sample.models.aliquot import Aliquot, AliquotLocation +from sample.models.sample import Sample +from sample.models.source import Source +from storage.models.site import Site +from storage.models.storage import Box, Device, Rack, Shelf + +User = get_user_model() + + +class DashboardTest(TestCase): + def setUp(self): + self.user = User.objects.create_user(username='talia.hoang', password='x') + self.client.force_login(self.user) + site = Site.objects.create(name='Main') + self.device = Device.objects.create(name='Sikora LN2', site=site) + shelf = Shelf.objects.create(name='Canes', device=self.device) + rack = Rack.objects.create(name='1', shelf=shelf) + self.box = Box.objects.create(name='1_A', rack=rack, rows=2, columns=5) # 10 slots + self.sample = Sample.objects.create(name='MM134', source=Source.objects.create(name='Lab')) + + def store(self, count): + aliquots = [] + for n in range(count): + aliquot = Aliquot.objects.create(sample=self.sample) + AliquotLocation.objects.create(aliquot=aliquot, box=self.box, row=n // 5 + 1, column=n % 5 + 1) + aliquots.append(aliquot) + return aliquots + + def page(self): + response = self.client.get(reverse('home')) + self.assertEqual(response.status_code, 200) + return response + + def test_fill_levels_use_the_agreed_thresholds(self): + self.assertEqual([fill_level(p) for p in (0, 70, 71, 90, 91, 100)], ['ok', 'ok', 'warn', 'warn', 'full', 'full']) + + def test_freezer_card_shows_used_total_and_colour(self): + self.store(8) # 8 of 10 = 80%: amber + card = self.page().context['freezers'][0] + self.assertEqual((card['used'], card['total'], card['percent'], card['level']), (8, 10, 80, 'warn')) + self.assertContains(self.page(), 'Sikora LN2') + self.assertContains(self.page(), '8 of 10 slots') + self.assertContains(self.page(), reverse('storage:detail', kwargs={'type': 'device', 'pk': self.device.pk})) + + def test_a_full_freezer_is_red_and_an_empty_one_says_so(self): + self.assertEqual(self.page().context['freezers'][0]['last_activity'], 'Empty') + self.store(10) + card = self.page().context['freezers'][0] + self.assertEqual((card['percent'], card['level']), (100, 'full')) + self.assertEqual(card['last_activity'], 'Just now') + + def test_header_summarises_instead_of_welcoming(self): + self.store(3) + page = self.page() + self.assertContains(page, '3 aliquots of 1 sample') + self.assertNotContains(page, 'Welcome to Krill') + self.assertNotContains(page, 'Laboratory Information Management System') + + def test_quick_actions_drop_settings_and_offer_an_audit(self): + page = self.page() + self.assertNotContains(page, 'class="action-btn">\n settings') + self.assertContains(page, reverse('reports:generate_audit_report')) + + def test_recent_activity_reads_as_a_sentence_with_where_it_is_stored(self): + aliquot = self.store(1)[0] + UserAuditLog.log_action(user=self.user, action='aliquot_created', target_type='Aliquot', + target_id=aliquot.id, target_name=str(aliquot)) + entry = self.page().context['recent_activity'][0] + self.assertEqual(entry['user'], 'talia.hoang') + self.assertEqual(entry['verb'], 'created aliquot') + self.assertEqual(entry['place'], 'Sikora LN2 / Box 1_A') + self.assertEqual(entry['url'], reverse('sample:detail', kwargs={'type': 'aliquot', 'pk': aliquot.id})) + self.assertContains(self.page(), 'created aliquot') + self.assertContains(self.page(), 'in Sikora LN2 / Box 1_A') + + def test_in_progress_audits_are_listed_until_finished(self): + template = ReportTemplate.objects.create(name='t', report_type='storage_audit', created_by=self.user) + slots = [{'result': 'correct'}, {'result': ''}] + report = Report.objects.create(template=template, name='Spot check', status='complete', created_by=self.user, + result_data={'audit_slots': slots}) + page = self.page() + self.assertContains(page, 'Spot check') + self.assertContains(page, '1 of 2 checked') + slots[1]['result'] = 'wrong' + report.result_data = {'audit_slots': slots} + report.save() + self.assertNotContains(self.page(), 'Spot check') + + def test_dashboard_still_loads_with_nothing_in_it(self): + for model in (Box, Rack, Shelf, Device): # children first: the foreign keys are PROTECT + model.objects.all().delete() + self.assertContains(self.page(), 'No freezers yet') + self.assertContains(self.page(), 'No activity yet') diff --git a/krill/krill/views/home.py b/krill/krill/views/home.py index 0c27ae0..1f04bb0 100644 --- a/krill/krill/views/home.py +++ b/krill/krill/views/home.py @@ -8,7 +8,7 @@ from django.utils import timezone from sample.models.sample import Sample -from sample.models.aliquot import AliquotLocation +from sample.models.aliquot import Aliquot, AliquotLocation from storage.models.storage import Box from person.models import UserAuditLog, UserPreference, SiteConfiguration from person.decorators import require_minimum_role @@ -27,12 +27,11 @@ class HomeView(View): def get(self, request): # Get dashboard statistics stats = get_dashboard_statistics() - # Get recent activity - recent_activity = get_recent_activity() - return render(request, self.template_name, { 'stats': stats, - 'recent_activity': recent_activity, + 'freezers': get_freezer_cards(), + 'audits_in_progress': get_audits_in_progress(), + 'recent_activity': get_recent_activity(), }) @login_required @@ -91,6 +90,7 @@ def get_dashboard_statistics(): 'alerts': alerts, 'total_slots': total_slots, 'used_slots': used_slots, + 'aliquots': Aliquot.objects.filter(deleted=False).count(), 'low_stock_count': low_stock_count, 'expiring_soon_count': expiring_soon_count, } @@ -103,62 +103,130 @@ def get_dashboard_statistics(): 'alerts': 0, 'total_slots': 0, 'used_slots': 0, + 'aliquots': 0, 'low_stock_count': 0, 'expiring_soon_count': 0, } -def get_recent_activity(): - """Get recent activity from audit logs""" +def time_ago(moment): + """'3 hours ago' style text for a past datetime.""" + if moment is None: + return 'No activity yet' + diff = timezone.now() - moment + if diff.days > 0: + return f"{diff.days} day{'s' if diff.days != 1 else ''} ago" + if diff.seconds >= 3600: + hours = diff.seconds // 3600 + return f"{hours} hour{'s' if hours != 1 else ''} ago" + if diff.seconds >= 60: + minutes = diff.seconds // 60 + return f"{minutes} minute{'s' if minutes != 1 else ''} ago" + return 'Just now' + + +FILL_WARN = 70 # amber above this percentage +FILL_FULL = 90 # red above this percentage + + +def fill_level(percent): + if percent > FILL_FULL: + return 'full' + if percent > FILL_WARN: + return 'warn' + return 'ok' + + +def get_freezer_cards(): + """One card per freezer or dewar: how full it is, and when something last changed in it.""" + from django.db.models import Count, F, Max, Sum + from storage.models.storage import Device + + capacity = { + row['rack__shelf__device']: row['slots'] + for row in Box.objects.values('rack__shelf__device').annotate(slots=Sum(F('rows') * F('columns'))) + } + usage = { + row['box__rack__shelf__device']: row + for row in AliquotLocation.objects.values('box__rack__shelf__device').annotate(used=Count('id'), last=Max('updated_at')) + } + cards = [] + for device in Device.objects.select_related('site').order_by('name'): + total = capacity.get(device.pk) or 0 + used = usage.get(device.pk, {}).get('used', 0) + percent = round(used * 100 / total) if total else 0 + cards.append({ + 'device': device, + 'used': used, + 'total': total, + 'percent': percent, + 'level': fill_level(percent), + 'last_activity': time_ago(usage.get(device.pk, {}).get('last')) if used else 'Empty', + }) + return cards + + +def get_audits_in_progress(limit=3): + """Storage audits that still have slots to check, most recent first.""" + from reports.models import Report + from reports.views import audit_progress + + audits = [] + for report in Report.objects.filter(template__report_type='storage_audit', status='complete').select_related('created_by'): + progress = audit_progress(report.result_data) + if progress['total'] and not progress['complete']: + audits.append({'report': report, 'progress': progress}) + if len(audits) == limit: + break + return audits + + +ACTIVITY_VERBS = { + 'sample_created': 'created sample', 'sample_updated': 'updated sample', 'sample_deleted': 'archived sample', + 'aliquot_created': 'created aliquot', 'aliquot_updated': 'updated aliquot', +} + + +def activity_link(activity): + """Where an activity entry should lead.""" + from django.urls import reverse + kind = (activity.target_type or '').lower() + if activity.target_id: + if 'sample' in activity.action or kind == 'sample': + return reverse('sample:detail', kwargs={'type': 'sample', 'pk': activity.target_id}) + if 'aliquot' in activity.action or kind == 'aliquot': + return reverse('sample:detail', kwargs={'type': 'aliquot', 'pk': activity.target_id}) + if kind == 'user': + return reverse('person:user_detail', args=[activity.target_id]) + if 'aliquot' in activity.action: + return reverse('sample:sample_list') + '?type=aliquot' + return reverse('sample:sample_list') + + +def get_recent_activity(limit=8): + """Recent activity written as a sentence: who did what to which item, and where it is stored.""" try: - recent_activities = UserAuditLog.objects.select_related('user').order_by('-timestamp')[:5] + logs = list(UserAuditLog.objects.select_related('user').order_by('-timestamp')[:limit]) + aliquot_ids = [log.target_id for log in logs if log.target_id and (log.target_type or '').lower() == 'aliquot'] + places = { + loc.aliquot_id: f"{loc.box.rack.shelf.device.name} / Box {loc.box.name}" + for loc in AliquotLocation.objects.filter(aliquot_id__in=aliquot_ids) + .select_related('box__rack__shelf__device') + } activities = [] - for activity in recent_activities: - # Format the activity message based on action type - if activity.action == 'sample_created': - message = f"New sample added: {activity.target_name or 'Unknown'}" - elif activity.action == 'sample_updated': - message = f"Sample updated: {activity.target_name or 'Unknown'}" - elif activity.action == 'sample_deleted': - message = f"Sample archived: {activity.target_name or 'Unknown'}" - elif activity.action == 'aliquot_created': - message = f"New aliquot created: {activity.target_name or 'Unknown'}" - elif activity.action == 'aliquot_updated': - message = f"Aliquot updated: {activity.target_name or 'Unknown'}" - else: - message = f"{activity.action.replace('_', ' ').title()}: {activity.target_name or 'Unknown'}" - # Calculate time ago - time_diff = timezone.now() - activity.timestamp - if time_diff.days > 0: - time_ago = f"{time_diff.days} day{'s' if time_diff.days != 1 else ''} ago" - elif time_diff.seconds > 3600: - hours = time_diff.seconds // 3600 - time_ago = f"{hours} hour{'s' if hours != 1 else ''} ago" - elif time_diff.seconds > 60: - minutes = time_diff.seconds // 60 - time_ago = f"{minutes} minute{'s' if minutes != 1 else ''} ago" - else: - time_ago = "Just now" + for log in logs: + verb = ACTIVITY_VERBS.get(log.action, log.action.replace('_', ' ')) activities.append({ - 'message': message, - 'time_ago': time_ago, - 'action_type': activity.action, - 'user': activity.user.username if activity.user else 'System', - 'target_id': activity.target_id, - 'target_type': activity.target_type or '', + 'user': log.user.username if log.user else 'System', + 'verb': verb, + 'target': log.target_name or '', + 'place': places.get(log.target_id, ''), + 'time_ago': time_ago(log.timestamp), + 'action_type': log.action, + 'url': activity_link(log), }) return activities - except Exception as e: - # Return default activities if there's an error - return [ - { - 'message': 'System initialized', - 'time_ago': 'Just now', - 'action_type': 'system_init', - 'user': 'System', - 'target_id': None, - 'target_type': '', - } - ] + except Exception: + return [] @method_decorator(login_required, name='dispatch') class ReportsView(View): diff --git a/krill/templates/krill/home.html b/krill/templates/krill/home.html index 759828b..d098af8 100644 --- a/krill/templates/krill/home.html +++ b/krill/templates/krill/home.html @@ -2,37 +2,46 @@ {% load static %} {% block content %} -
- -
-

Welcome to Krill

-

Laboratory Information Management System

+
+
+

Dashboard

+

+ {{ stats.aliquots }} aliquot{{ stats.aliquots|pluralize }} of {{ stats.active_samples }} sample{{ stats.active_samples|pluralize }} + • {{ stats.used_slots }} of {{ stats.total_slots }} storage slots used ({{ stats.storage_usage }}%) +

- +
science
-

Active Samples

+

Samples

{{ stats.active_samples|default:"0" }}

- + + biotech +
+

Aliquots

+

{{ stats.aliquots|default:"0" }}

+
+
+ inventory_2
-

Storage Usage

+

Storage Used

{{ stats.storage_usage|default:"0" }}%

- - description + + fact_check
-

Reports

-

{% if stats.recent_reports %}{{ stats.recent_reports }} this week{% else %}None this week{% endif %}

+

Audits

+

{% if audits_in_progress %}{{ audits_in_progress|length }} in progress{% else %}None in progress{% endif %}

- + warning

Alerts

@@ -57,58 +66,8 @@

Expiring Soon

{% endif %}
- -
- -
- {% if recent_activity %} - {% for activity in recent_activity %} - {% if activity.action_type == 'system_init' %} -
- info -
-

{{ activity.message }}

- {{ activity.time_ago }} -
-
- {% else %} - - - {% if activity.action_type == 'sample_created' or activity.action_type == 'aliquot_created' %} - add_circle - {% elif activity.action_type == 'sample_updated' or activity.action_type == 'aliquot_updated' %} - edit - {% elif activity.action_type == 'sample_deleted' %} - delete - {% else %} - info - {% endif %} - -
-

{{ activity.message }}

- {{ activity.time_ago }} -
-
- {% endif %} - {% endfor %} - {% else %} -
- info -
-

No activity yet

- Create a sample or aliquot to get started -
-
- {% endif %} -
-
- + + +
+
+

Freezers

+ View All +
+ {% if freezers %} + + {% else %} +

No freezers yet

+ {% endif %} +
+ + {% if audits_in_progress %} + + {% endif %} + + +
@@ -134,6 +169,23 @@

Quick Actions