Self hosted FLOSS fitness/workout, nutrition and weight tracker
Rework and simplify the history revert logic
Roland Geider1da7d8980886
diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex 26e8c16e0..f7dd8e029 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -139,8 +139,6 @@ class ExerciseTranslationViewSet(ModelViewSet):"""Save entry to activity stream"""- super().perform_create(serializer)-# Clean the description HTMLif serializer.validated_data.get('description'):serializer.validated_data['description'] = bleach.clean(@@ -150,6 +148,7 @@ class ExerciseTranslationViewSet(ModelViewSet):styles=HTML_STYLES_WHITELIST,strip=True)+ super().perform_create(serializer)actstream_action.send(self.request.user,@@ -162,17 +161,6 @@ class ExerciseTranslationViewSet(ModelViewSet):Save entry to activity stream"""- obj_id = self.kwargs['pk']- updated_object = Exercise.objects.get(id=obj_id)-- # Create a default history to diff against if there is none- if updated_object:- most_recent_history = updated_object.history.order_by('history_date').last()- if most_recent_history is None:- updated_object.save()-- most_recent_history = updated_object.history.order_by('history_date').last()-# Don't allow to change the base or the language over the APIif serializer.validated_data.get('exercise_base'):del serializer.validated_data['exercise_base']@@ -191,14 +179,10 @@ class ExerciseTranslationViewSet(ModelViewSet):)super().perform_update(serializer)-actstream_action.send(self.request.user,verb=StreamVerbs.UPDATED.value,action_object=serializer.instance,- data={- 'history_id': most_recent_history.history_id,- })diff --git a/wger/exercises/models/base.py b/wger/exercises/models/base.pyindex ccf130be4..b28e9abbb 100644--- a/wger/exercises/models/base.py+++ b/wger/exercises/models/base.py@@ -25,6 +25,7 @@ from typing import (from django.core.checks import translationfrom django.db import modelsfrom django.db.models import Q+from django.urls import reversefrom django.utils.translation import (get_language,gettext_lazy as _,@@ -154,12 +155,13 @@ class ExerciseBase(AbstractLicenseModel, AbstractHistoryMixin, models.Model):happen in our dataset, but it is possible that some local installationshave deleted the English translation or similar"""+ from wger.exercises.models import Exerciselanguage = language or get_language()try:exercise = self.exercises.get(language__short_name=language)- except: # can't do Exercise.DoesNotExist because of circular imports+ except Exercise.DoesNotExist:try:exercise = self.exercises.get(language__short_name=ENGLISH_SHORT_NAME)except:diff --git a/wger/exercises/models/exercise.py b/wger/exercises/models/exercise.pyindex e68c7ec80..491d264aa 100644--- a/wger/exercises/models/exercise.py+++ b/wger/exercises/models/exercise.py@@ -116,7 +116,8 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):"""Returns the canonical URL to view an exercise"""- return reverse('exercise:exercise:view', kwargs={'id': self.id, 'slug': slugify(self.name)})+ return reverse('exercise:exercise:view-base',+ kwargs={'id': self.exercise_base_id, 'slug': slugify(self.name)})def save(self, *args, **kwargs):"""diff --git a/wger/exercises/templates/history/list3.html b/wger/exercises/templates/history/list3.htmlindex a572c5044..c8e0c7d39 100644--- a/wger/exercises/templates/history/list3.html+++ b/wger/exercises/templates/history/list3.html@@ -22,114 +22,131 @@-->{% block content %}<table class="table">- <thead>- <tr>- <th scope="col">{% translate 'User' %}</th>- <th scope="col">{% translate 'Action Type' %}</th>- <th scope="col">{% translate 'Object' %}</th>- <th scope="col">{% translate 'Time' %}</th>- <th scope="col">{% translate 'Changes' %}</th>- <th scope="col">{% translate 'Revert' %}</th>- </tr>+ <thead class="thead-light">+ <tr>+ <th scope="col" style="width: 5%">{% translate 'Action' %}</th>+ <th scope="col" style="width: 5%">{% translate 'User' %}</th>+ <th scope="col" style="width: 45%">{% translate 'Object' %}</th>+ <th scope="col" style="width: 15%">{% translate 'Time' %}</th>+ <th scope="col" style="width: 15%">{% translate 'Changes' %}</th>+ <th scope="col" style="width: 15%">{% translate 'Revert' %}</th>+ </tr></thead><tbody>- {% for event in context %}+ {% for event in context %}<tr>+ <td>+ {% if event.stream.verb == verbs.CREATED.value %}+ <span class="{% fa_class 'circle-plus' %}"></span>+ {% elif event.stream.verb == verbs.UPDATED.value %}+ <span class="{% fa_class 'pen' %}"></span>+ {% else %}+ {{ event.verb }}+ {% endif %}+ </td><td>{{ event.stream.actor }}</td>- <td>{{ event.stream.verb }}</td><td>{% if event.stream.action_object.get_absolute_url %}<a href="{{ event.stream.action_object.get_absolute_url }}">{{ event.stream.action_object }}</a>{% else %}{{ event.stream.action_object }}{% endif %}++ {% if event.stream.data.info %}+ <span class="badge badge-secondary">{{ event.stream.data.info }}</span>+ {% endif %}</td><td>{{ event.stream.timesince }}</td>- {% if event.stream.verb == modes.CREATED.value %}+ {% if event.stream.verb == verbs.CREATED.value %}<td>- <a href="{{ event.stream.action_object.get_absolute_url }}" id="view-changes" class="btn btn-success btn-sm btn-block">- {% translate "View exercise" %}+ <a href="{{ event.stream.action_object.get_absolute_url }}" id="view-changes"+ class="btn btn-success btn-sm btn-block">+ {% translate "View Object" %}</a></td><td>- <a href="{% url 'exercise:exercise:delete' event.stream.action_object.id %}" id="view-changes" class="btn btn-danger btn-sm btn-block">- {% translate "Delete exercise" %}- </a>+</td>- {% elif event.stream.verb == modes.UPDATED.value %}+ {% elif event.stream.verb == verbs.UPDATED.value %}<td>- <a href="#" id="view-changes" data-toggle="modal" data-target="#changes-modal-{{ event.stream.id }}"- class="btn btn-success btn-sm btn-block">+ <a class="btn btn-success btn-sm btn-block" data-toggle="collapse"+ href="#collapse-{{ event.stream.id }}"+ role="button">{% translate "View changes" %}</a>- <div class="modal fade" id="changes-modal-{{ event.stream.id }}">- <div class="modal-dialog">- <div class="modal-content">- <div class="modal-header">- <h4 class="modal-title">{% translate 'Exercise changes' %}</h4>- </div>- <div class="modal-body">- <table>- <thead>- <tr>- <td>Field</td>- <td>Old</td>- <td>New</td>- </tr>- </thead>- <tbody>- {% if event.history.delta %}- {% for change in event.history.delta.changes %}- <tr>- <td>{{ change.field }}</td>- <td>{{ change.old }}</td>- <td>{{ change.new }}</td>- </tr>- {% endfor %}- {% endif %}- </tbody>- </table>- </div>- <div class="modal-footer">- <button type="button" class="btn btn-light" data-dismiss="modal">{% translate "Close" %}</button>- </div>- </div>- </div>- </div></td><td>- <a href="#" id="revert-changes" data-toggle="modal" data-target="#revert-modal-{{ event.stream.id }}"- class="btn btn-danger btn-sm btn-block">+ <a href="#"+ id="revert-changes"+ data-toggle="modal"+ data-target="#revert-modal-{{ event.stream.id }}"+ class="btn btn-danger btn-sm btn-block"+ {% if not event.history_id %}disabled{% endif %}+ >{% translate "Revert changes" %}</a>- <div class="modal fade" id="revert-modal-{{ event.stream.id }}">- <div class="modal-dialog">- <div class="modal-content">- <div class="modal-header">- <h4 class="modal-title">{% translate 'Are you sure?' %}</h4>- </div>- <div class="modal-body">- <a href="revert/{{ event.history.record.history_id }}" id="view-changes" class="btn btn-danger btn-sm btn-block">- {% translate "Yes" %}- </a>- </div>- <div class="modal-footer">- <button type="button" class="btn btn-light" data-dismiss="modal">{% translate "No" %}</button>+ {% if event.history_id %}+ <div class="modal fade" id="revert-modal-{{ event.stream.id }}">+ <div class="modal-dialog">+ <div class="modal-content">+ <div class="modal-header">+ <h4 class="modal-title">{% translate 'Are you sure?' %}</h4>+ </div>+ <div class="modal-body">+ <a href="{% url 'exercise:history:revert' event.history_id event.content_type_id %}"+ id="view-changes"+ class="btn btn-danger btn-sm btn-block">+ {% translate "Yes" %}+ </a>+ </div>+ <div class="modal-footer">+ <button type="button"+ class="btn btn-light"+ data-dismiss="modal">+ {% translate "No" %}+ </button>+ </div></div></div></div>- </div>+ {% endif %}</td>{% endif %}</tr>- {% endfor %}+ <tr class="collapse" id="collapse-{{ event.stream.id }}">+ <td colspan="6">+ <table class="table">+ <thead>+ <tr>+ <td>Field</td>+ <td>Old</td>+ <td>New</td>+ </tr>+ </thead>+ <tbody>+ {% if event.delta %}+ {% for change in event.delta.changes %}+ <tr>+ <td>{{ change.field }}</td>+ <td>{{ change.old }}</td>+ <td>{{ change.new }}</td>+ </tr>+ {% endfor %}+ {% endif %}+ </tbody>+ </table>+ </td>+++ </tr>+ {% endfor %}</tbody></table>{% endblock %}<!--- Side bar+ Sidebar-->{% block sidebar %}diff --git a/wger/exercises/urls.py b/wger/exercises/urls.pyindex ad85dea65..279fc5b90 100644--- a/wger/exercises/urls.py+++ b/wger/exercises/urls.py@@ -36,11 +36,14 @@ from wger.exercises.views import (# sub patterns for historypatterns_history = [- path('overview/', history.overview, name='overview'),- path('overview-history/', history.overview2, name='overview-history'),- path('admin-control/', history.control, name='admin-control'),- path('admin-control/revert/<int:pk>/',- history.history_revert, name='history-revert'),+ path('overview', history.overview, name='overview'),+ path('overview-history', history.overview2, name='overview-history'),+ path('admin-control', history.control, name='admin-control'),+ path(+ 'admin-control/revert/<int:history_pk>/<int:content_type_id>',+ history.history_revert,+ name='revert'+ ),]# sub patterns for muscles@@ -157,6 +160,11 @@ patterns_exercise = [TemplateView.as_view(template_name='exercise/view-base.html'),name='view-base',),+ url(+ r'^(?P<id>\d+)/view/(?P<slug>[-\w]*)/?$',+ TemplateView.as_view(template_name='exercise/view-base.html'),+ name='view-base',+ ),path('<int:pk>/delete/',exercises.ExerciseDeleteView.as_view(),diff --git a/wger/exercises/views/history.py b/wger/exercises/views/history.pyindex daa5ba739..f87355600 100644--- a/wger/exercises/views/history.py+++ b/wger/exercises/views/history.py@@ -19,7 +19,7 @@ import logging# Djangofrom django.contrib.auth.decorators import permission_requiredfrom django.contrib.contenttypes.models import ContentType-from django.shortcuts import render+from django.shortcuts import render, get_object_or_404from django.http import HttpResponseRedirectfrom django.urls import (reverse,@@ -72,82 +72,49 @@ def control(request):"""Admin view of the history of the exercises"""- object_content_type = ContentType.objects.get_for_model(Exercise)+ all_streams = Action.objects.all()+ out = []+ for entry in all_streams:+ data = {'verb': entry.verb, 'stream': entry}- stream = Action.objects.filter(- action_object_content_type_id=object_content_type.id,- )+ if entry.verb == StreamVerbs.UPDATED.value:+ entry_obj = entry.action_object.history.as_of(entry.timestamp)+ historical_entry = entry_obj._history+ previous_entry = historical_entry.prev_record- out = []- for entry in stream:- if entry.verb == StreamVerbs.CREATED.value:- out.append({- 'history': None,- 'stream': entry- })- continue- elif entry.verb == StreamVerbs.UPDATED.value:- entry_data = entry.data- if entry_data is None:- continue-- entry_dict = entry_data.get('data', {})- history_id = entry_dict.get('history_id', 0)- if history_id == 0:- continue-- hist = Exercise.history.get(history_id=history_id)- if hist.prev_record:- out.append({- 'history': {'record': hist, 'delta': hist.diff_against(hist.prev_record)},- 'stream': entry- })+ data['id'] = historical_entry.id+ data['content_type_id'] = ContentType.objects.get_for_model(entry_obj).id++ if previous_entry:+ data['delta'] = historical_entry.diff_against(previous_entry)+ data['history_id'] = previous_entry.history_id++ out.append(data)return render(request, 'history/list3.html', {'context': out,# We can't pass the enum to the template, so we have to do this# https://stackoverflow.com/questions/35953132/- 'modes': StreamVerbs.__members__+ 'verbs': StreamVerbs.__members__})@permission_required('exercises.change_exercise')-def history_revert(request, pk):+def history_revert(request, history_pk, content_type_id):"""Used to revert history objects"""- hist = Exercise.history.get(history_id=pk)- if hist is None:- return HttpResponseRedirect(reverse('exercise:history:admin-control'))-- revert_obj = hist.prev_record- if revert_obj is None:- return HttpResponseRedirect(reverse('exercise:history:admin-control'))-- diff = hist.diff_against(hist.prev_record)-- current_obj = Exercise.objects.get(id=revert_obj.instance.id)- if current_obj is None:- return HttpResponseRedirect(reverse('exercise:history:admin-control'))-- for change in diff.changes:- try:- setattr(current_obj, change.field, change.old)- except:- logger.warn(f"Failed setting field: {change.field} to {change.old} for Exercise {current_obj.id}")-- current_obj.save()-- most_recent_history = current_obj.history.order_by('history_date').last()+ object_type = get_object_or_404(ContentType, pk=content_type_id)+ object_class = object_type.model_class()+ history = object_class.history.get(history_id=history_pk)+ history.instance.save()actstream_action.send(request.user,verb=StreamVerbs.UPDATED.value,- action_object=revert_obj.instance,- data={- 'history_id': most_recent_history.history_id,- }+ action_object=history.instance,+ info='reverted history by admin')return HttpResponseRedirect(reverse('exercise:history:admin-control'))