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
Empty file added krill/krill/tests/__init__.py
Empty file.
109 changes: 109 additions & 0 deletions krill/krill/tests/test_dashboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
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_page_is_plain_and_does_not_blank_its_numbers_with_a_loading_script(self):
self.store(3)
page = self.page()
self.assertNotContains(page, 'Welcome to Krill')
self.assertNotContains(page, 'Laboratory Information Management System')
self.assertNotContains(page, 'dashboard.js') # it replaced every card with "Loading..."
self.assertNotContains(page, 'storage slots used') # the cards already say it
self.assertEqual(page.context['stats']['aliquots'], 3)

def test_site_name_only_appears_on_freezer_cards_when_there_are_several_sites(self):
self.assertFalse(self.page().context['show_sites'])
Device.objects.create(name='Other', site=Site.objects.create(name='Annex'))
self.assertTrue(self.page().context['show_sites'])

def test_quick_actions_drop_settings_and_offer_an_audit(self):
page = self.page()
self.assertNotContains(page, 'class="action-btn">\n <span class="material-icons-round">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')
174 changes: 122 additions & 52 deletions krill/krill/views/home.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -27,12 +27,13 @@ class HomeView(View):
def get(self, request):
# Get dashboard statistics
stats = get_dashboard_statistics()
# Get recent activity
recent_activity = get_recent_activity()

freezers = get_freezer_cards()
return render(request, self.template_name, {
'stats': stats,
'recent_activity': recent_activity,
'freezers': freezers,
'show_sites': len({card['device'].site_id for card in freezers}) > 1,
'audits_in_progress': get_audits_in_progress(),
'recent_activity': get_recent_activity(),
})

@login_required
Expand Down Expand Up @@ -91,6 +92,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,
}
Expand All @@ -103,62 +105,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):
Expand Down
Loading
Loading