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..828f60d --- /dev/null +++ b/krill/krill/tests/test_dashboard.py @@ -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 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..43ff55e 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,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 @@ -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, } @@ -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): diff --git a/krill/static/krill/js/dashboard.js b/krill/static/krill/js/dashboard.js deleted file mode 100644 index a15259c..0000000 --- a/krill/static/krill/js/dashboard.js +++ /dev/null @@ -1,182 +0,0 @@ -// Dashboard statistics update -async function updateDashboardStats() { - // Show loading state - showLoadingState(); - - try { - const response = await fetch('/dashboard/stats/'); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - const data = await response.json(); - - // Update Active Samples - const sampleCard = Array.from(document.querySelectorAll('.stat-card')).find(card => - card.querySelector('.material-icons-round').textContent.trim() === 'science' - ); - if (sampleCard) { - const sampleElement = sampleCard.querySelector('.stat-info p'); - if (sampleElement) { - sampleElement.textContent = data.active_samples || 0; - sampleElement.classList.remove('loading'); - } - } - - // Update Storage Usage - const storageCard = Array.from(document.querySelectorAll('.stat-card')).find(card => - card.querySelector('.material-icons-round').textContent.trim() === 'inventory_2' - ); - if (storageCard) { - const percentageElement = storageCard.querySelector('.stat-info p'); - if (percentageElement) { - percentageElement.textContent = `${data.storage_usage || 0}%`; - percentageElement.classList.remove('loading'); - } - } - - // Update Reports - const reportCard = Array.from(document.querySelectorAll('.stat-card')).find(card => - card.querySelector('.material-icons-round').textContent.trim() === 'description' - ); - if (reportCard) { - const reportElement = reportCard.querySelector('.stat-info p'); - if (reportElement) { - reportElement.textContent = `${data.recent_reports || 0} Recent`; - reportElement.classList.remove('loading'); - } - } - - // Update Alerts - const alertCard = Array.from(document.querySelectorAll('.stat-card')).find(card => - card.querySelector('.material-icons-round').textContent.trim() === 'warning' - ); - if (alertCard) { - const alertElement = alertCard.querySelector('.stat-info p'); - if (alertElement) { - alertElement.textContent = `${data.alerts || 0} New`; - alertElement.classList.remove('loading'); - } - } - - // Hide loading state - hideLoadingState(); - - } catch (error) { - console.error('Error fetching dashboard stats:', error); - showErrorState(); - } -} - -// Show loading state -function showLoadingState() { - const statCards = document.querySelectorAll('.stat-card .stat-info p'); - statCards.forEach(element => { - element.classList.add('loading'); - element.textContent = 'Loading...'; - }); -} - -// Hide loading state -function hideLoadingState() { - const loadingElements = document.querySelectorAll('.loading'); - loadingElements.forEach(element => { - element.classList.remove('loading'); - }); -} - -// Show error state -function showErrorState() { - const statCards = document.querySelectorAll('.stat-card .stat-info p'); - statCards.forEach(element => { - element.classList.add('error'); - element.textContent = 'Error'; - }); - - // Show error notification - showNotification('Failed to load dashboard statistics. Please refresh the page.', 'error'); -} - -// Show notification -function showNotification(message, type = 'info') { - // Create notification element - const notification = document.createElement('div'); - notification.className = `notification notification-${type}`; - notification.textContent = message; - - // Add styles - notification.style.cssText = ` - position: fixed; - top: 20px; - right: 20px; - padding: 12px 20px; - border-radius: 4px; - color: white; - font-weight: 500; - z-index: 1000; - opacity: 0; - transform: translateX(100%); - transition: all 0.3s ease; - `; - - // Set background color based on type - if (type === 'error') { - notification.style.backgroundColor = '#dc3545'; - } else if (type === 'success') { - notification.style.backgroundColor = '#28a745'; - } else { - notification.style.backgroundColor = '#007bff'; - } - - // Add to page - document.body.appendChild(notification); - - // Animate in - setTimeout(() => { - notification.style.opacity = '1'; - notification.style.transform = 'translateX(0)'; - }, 100); - - // Remove after 5 seconds - setTimeout(() => { - notification.style.opacity = '0'; - notification.style.transform = 'translateX(100%)'; - setTimeout(() => { - if (notification.parentNode) { - notification.parentNode.removeChild(notification); - } - }, 300); - }, 5000); -} - -// Storage usage calculation (keeping for backward compatibility) -async function updateStorageUsage() { - try { - const response = await fetch('/storage/capacity/'); - if (!response.ok) { - throw new Error('Network response was not ok'); - } - const data = await response.json(); - // Calculate percentage used - const percentageUsed = Math.round((data.used_slots / data.total_slots) * 100) || 0; - // Find the storage usage stat card - const storageCards = document.querySelectorAll('.stat-card'); - const storageCard = Array.from(storageCards).find(card => - card.querySelector('.material-icons-round').textContent.trim() === 'inventory_2' - ); - if (storageCard) { - const percentageElement = storageCard.querySelector('.stat-info p'); - if (percentageElement) { - percentageElement.textContent = `${percentageUsed}%`; - } - } - } catch (error) { - console.error('Error fetching storage capacity:', error); - } -} - -// Call the functions when the page loads -document.addEventListener('DOMContentLoaded', function() { - updateDashboardStats(); - // Keep the storage usage update for backward compatibility - // updateStorageUsage(); -}); diff --git a/krill/templates/krill/home.html b/krill/templates/krill/home.html index 759828b..97ac84b 100644 --- a/krill/templates/krill/home.html +++ b/krill/templates/krill/home.html @@ -2,37 +2,42 @@ {% load static %} {% block content %} -
- -
-

Welcome to Krill

-

Laboratory Information Management System

+
+
+

Dashboard

- +
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 +62,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 %} -
-
- + + + -
- - + {% if audits_in_progress %} + + {% endif %} + + + +