Home Information - Your home, your data, organized.
Python
Cleanup and refactoring. Unify access to common vlocation/views.
Anthony Cassandra0095479c3e81
diff --git a/src/hi/apps/collection/async_views.py b/src/hi/apps/collection/async_views.pyindex ce6f0542..def90294 100644--- a/src/hi/apps/collection/async_views.py+++ b/src/hi/apps/collection/async_views.py@@ -3,6 +3,8 @@ import loggingfrom django.core.exceptions import BadRequestfrom django.http import Http404+from hi.apps.location.location_manager import LocationManager+from hi.hi_async_view import HiSideViewfrom .collection_manager import CollectionManager@@ -20,18 +22,19 @@ class CollectionDetailsView( HiSideView ):return Truedef get_template_context( self, request, *args, **kwargs ):- collection_id = kwargs.get( 'collection_id' )- if not collection_id:- raise BadRequest( 'Missing collection id in request.' )try:- collection = Collection.objects.get( id = collection_id )+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )except Collection.DoesNotExist:- raise Http404()-- current_location_view = None- if request.view_parameters.view_type.is_location_view:- current_location_view = request.view_parameters.location_view-+ raise Http404( request )++ current_location_view = LocationManager().get_default_location_view( request =request )collection_detail_data = CollectionManager().get_collection_detail_data(collection = collection,current_location_view = current_location_view,diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.pyindex 0fae358e..56eb530c 100644--- a/src/hi/apps/collection/collection_manager.py+++ b/src/hi/apps/collection/collection_manager.py@@ -23,6 +23,8 @@ from .models import (from .transient_models import (EntityCollectionItem,EntityCollectionGroup,+ CollectionViewItem,+ CollectionViewGroup,)@@ -31,18 +33,30 @@ class CollectionManager(Singleton):def __init_singleton__(self):return- def get_collection_data( self, collection : Collection ):-- entity_list = list()- for collection_entity in collection.entities.all().order_by('order_id'):- entity_list.append( collection_entity.entity )- continue-- return CollectionData(- collection = collection,- entity_list = entity_list,- )-+ def get_collection( self, request : HttpRequest, collection_id : int ) -> Collection:+ """+ This should always be used to fetch from the database and never using+ the "objects" query interface. The view_parameters loads the+ current default Collection, so any out-of-band loading risks the+ cached view_parameters version to be different from the one+ loaded. Since so much of the app features revolve around the+ current collection, not having the default update can result in hard+ to detect issues.+ """+ current_collection = request.view_parameters.collection+ if current_collection and ( current_collection.id == int(collection_id) ):+ return current_collection+ return Collection.objects.get( id = collection_id )++ def get_default_collection( self, request : HttpRequest ) -> Collection:+ current_collection = request.view_parameters.collection+ if current_collection:+ return current_collection+ collection = Collection.objects.order_by( 'order_id' ).first()+ if collection:+ return collection+ raise Collection.DoesNotExist()+def create_collection( self,request : HttpRequest,collection_type : CollectionType,@@ -59,6 +73,18 @@ class CollectionManager(Singleton):order_id = order_id,)+ def get_collection_data( self, collection : Collection ):++ entity_list = list()+ for collection_entity in collection.entities.all().order_by('order_id'):+ entity_list.append( collection_entity.entity )+ continue++ return CollectionData(+ collection = collection,+ entity_list = entity_list,+ )+def create_collection_entity( self,entity : Entity,collection : Collection ) -> CollectionEntity:@@ -85,25 +111,6 @@ class CollectionManager(Singleton):except CollectionEntity.DoesNotExist:return False- def remove_collection_view( self, collection : Collection, location_view : LocationView ):-- with transaction.atomic():- collection_view = CollectionView.objects.get(- collection = collection,- location_view = location_view,- )- collection_view.delete()-- return-- def create_collection_view_by_id( self, collection : Collection, location_view_id : int ):- location_view = LocationView.objects.get( id = location_view_id )- _ = self.create_collection_view(- collection = collection,- location_view = location_view,- )- return-def create_collection_view( self, collection : Collection, location_view : LocationView ):with transaction.atomic():@@ -135,50 +142,61 @@ class CollectionManager(Singleton):return collection_view+ def toggle_collection_in_view( self,+ collection : Collection,+ location_view : LocationView ) -> bool:++ try:+ with transaction.atomic():+ self.remove_collection_view(+ collection = collection,+ location_view = location_view,+ )+ return False++ except CollectionView.DoesNotExist:+ with transaction.atomic():+ _ = self.create_collection_view(+ collection = collection,+ location_view = location_view,+ )+ return True++ def remove_collection_view( self, collection : Collection, location_view : LocationView ):++ with transaction.atomic():+ collection_view = CollectionView.objects.get(+ collection = collection,+ location_view = location_view,+ )+ collection_view.delete()++ return+def set_collection_path( self,- collection_id : int,+ collection : Collection,location : Location,svg_path_str : str ) -> CollectionPath:- try:- collection_path = CollectionPath.objects.get(+ with transaction.atomic():+ try:+ collection_path = CollectionPath.objects.get(+ location = location,+ collection = collection,+ )+ collection_path.svg_path = svg_path_str+ collection_path.save()+ return collection_path++ except CollectionPath.DoesNotExist:+ pass++ return CollectionPath.objects.create(+ collection = collection,location = location,- collection_id = collection_id,+ svg_path = svg_path_str,)- collection_path.svg_path = svg_path_str- collection_path.save()- return collection_path-- except CollectionPath.DoesNotExist:- pass-- collection = Collection.objects.get( id = collection_id )- return CollectionPath.objects.create(- collection = collection,- location = location,- svg_path = svg_path_str,- )- def get_collection_position( self,- collection_id : int,- location : Location ) -> CollectionPosition:- try:- collection = Collection.objects.get( id = collection_id )- except Collection.DoesNotExist:- return None-- collection_position = CollectionPosition.objects.filter(- collection = collection,- location = location,- ).first()- if collection_position:- return collection_position-- return CollectionPosition(- collection = collection,- location = location,- )-def add_collection_position_if_needed( self,collection : Collection,location_view : LocationView ) -> CollectionPosition:@@ -291,11 +309,6 @@ class CollectionManager(Singleton):self.add_entity_to_collection( entity = entity, collection = collection )return True- def add_entity_to_collection_by_id( self, entity : Entity, collection_id : int ) -> bool:- collection = Collection.objects.get( id = collection_id )- self.add_entity_to_collection( entity = entity, collection = collection )- return-def add_entity_to_collection( self, entity : Entity, collection : Collection ) -> bool:with transaction.atomic():@@ -317,7 +330,7 @@ class CollectionManager(Singleton):def set_collection_entity_order( self,collection_id : int,entity_id_list : List[int] ):- item_id_to_order_id = {+ item_id_to_idx = {item_id: order_id for order_id, item_id in enumerate( entity_id_list )}@@ -327,21 +340,51 @@ class CollectionManager(Singleton):)with transaction.atomic():for collection_entity in collection_entity_queryset:- collection_entity.order_id = item_id_to_order_id.get( collection_entity.entity.id )+ item_idx = item_id_to_idx.get( collection_entity.entity.id )+ order_id = 2 * ( item_idx + 1) # Leave gaps to make one-off insertions easier+ collection_entity.order_id = order_idcollection_entity.save()continuereturndef set_collection_order( self, collection_id_list : List[int] ):- item_id_to_order_id = {+ item_id_to_idx = {item_id: order_id for order_id, item_id in enumerate( collection_id_list )}collection_queryset = Collection.objects.filter( id__in = collection_id_list )with transaction.atomic():for collection in collection_queryset:- collection.order_id = item_id_to_order_id.get( collection.id )+ item_idx = item_id_to_idx.get( collection.id )+ order_id = 2 * ( item_idx + 1) # Leave gaps to make one-off insertions easier+ collection.order_id = order_idcollection.save()continuereturn+ def create_collection_view_group( self, location_view : LocationView ) -> CollectionViewGroup:++ collection_queryset = Collection.objects.all()++ collection_view_group = CollectionViewGroup(+ location_view = location_view,+ )+ for collection in collection_queryset:++ exists_in_view = False+ for collection_view in collection.collection_views.all():+ if collection_view.location_view == location_view:+ exists_in_view = True+ break+ continue++ collection_view_item = CollectionViewItem(+ collection = collection,+ exists_in_view = exists_in_view,+ )+ collection_view_group.item_list.append( collection_view_item )+ continue++ collection_view_group.item_list.sort( key = lambda item : item.collection.name )+ return collection_view_group+diff --git a/src/hi/apps/collection/edit/async_views.py b/src/hi/apps/collection/edit/async_views.pyindex ae488355..3228a429 100644--- a/src/hi/apps/collection/edit/async_views.py+++ b/src/hi/apps/collection/edit/async_views.py@@ -12,6 +12,7 @@ from hi.apps.collection.models import Collection, CollectionPositionimport hi.apps.common.antinode as antinodefrom hi.apps.entity.models import Entityfrom hi.apps.location.svg_item_factory import SvgItemFactory+from hi.apps.location.location_manager import LocationManagerfrom hi.constants import DIVIDfrom hi.decorators import edit_required@@ -25,10 +26,15 @@ logger = logging.getLogger(__name__)class CollectionEditView( View ):def post( self, request, *args, **kwargs ):-- collection_id = kwargs.get('collection_id')try:- collection = Collection.objects.get( id = collection_id )+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )except Collection.DoesNotExist:raise Http404( request )@@ -73,9 +79,12 @@ class CollectionReorder( View ):class CollectionPositionEditView( View ):def post(self, request, *args, **kwargs):+ try:+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )- collection_id = kwargs.get('collection_id')- location = request.view_parameters.location+ location = LocationManager().get_default_location( request = request )try:collection_position = CollectionPosition.objects.get(collection_id = collection_id,@@ -140,9 +149,10 @@ class CollectionManageItemsView( HiSideView ):class CollectionReorderEntitiesView( View ):def post(self, request, *args, **kwargs):- collection_id = kwargs.get('collection_id')- if not collection_id:- raise BadRequest( 'Missing collection id.' )+ try:+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )try:entity_id_list = json.loads( kwargs.get( 'entity_id_list' ) )@@ -163,12 +173,27 @@ class CollectionReorderEntitiesView( View ):class CollectionEntityToggleView( View ):def post(self, request, *args, **kwargs):+ try:+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )+ except Collection.DoesNotExist:+ raise Http404( request )- collection_id = kwargs.get('collection_id')- entity_id = kwargs.get('entity_id')+ try:+ entity_id = int( kwargs.get('entity_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid entity id.' )+ try:+ entity = Entity.objects.get( id = entity_id )+ except Entity.DoesNotExist:+ raise Http404( request )- entity = Entity.objects.get( id = entity_id )- collection = Collection.objects.get( id = collection_id )exists_in_collection = CollectionManager().toggle_entity_in_collection(entity = entity,collection = collection,diff --git a/src/hi/apps/collection/edit/forms.py b/src/hi/apps/collection/edit/forms.pyindex 4a5bd4a7..ee7e5624 100644--- a/src/hi/apps/collection/edit/forms.py+++ b/src/hi/apps/collection/edit/forms.py@@ -12,6 +12,7 @@ class CollectionForm( forms.ModelForm ):fields = ('name','collection_type_str',+ 'order_id',)collection_type_str = forms.ChoiceField(diff --git a/src/hi/apps/collection/edit/views.py b/src/hi/apps/collection/edit/views.pyindex 711f32b3..1c0440ff 100644--- a/src/hi/apps/collection/edit/views.py+++ b/src/hi/apps/collection/edit/views.py@@ -8,6 +8,8 @@ from django.utils.decorators import method_decoratorfrom hi.apps.collection.collection_manager import CollectionManagerfrom hi.apps.collection.models import Collection+from hi.apps.location.location_manager import LocationManager+from hi.apps.location.models import LocationViewfrom hi.decorators import edit_requiredfrom hi.enums import ViewType@@ -38,26 +40,33 @@ class CollectionAddView( HiModalView ):}return self.modal_response( request, context )- try:- with transaction.atomic():- collection = collection_form.save()- if ( request.view_parameters.view_type.is_location_view- and request.view_parameters.location_view_id ):- CollectionManager().create_collection_view_by_id(- collection = collection,- location_view_id = request.view_parameters.location_view_id,- )-- except ValueError as e:- raise BadRequest( str(e) )+ with transaction.atomic():+ collection = collection_form.save()+ self._add_to_location_view(+ request = request,+ collection = collection,+ )if request.view_parameters.view_type == ViewType.COLLECTION:- request.view_parameters.collection_id = collection.id+ request.view_parameters.update_collection( collection = collection )request.view_parameters.to_session( request )redirect_url = reverse('home')return self.redirect_response( request, redirect_url )+ def _add_to_location_view( self, request, collection : Collection ):+ try:+ # Ensure we have a location view to add the entity to.+ current_location_view = LocationManager().get_default_location_view( request = request )+ CollectionManager().create_collection_view(+ collection = collection,+ location_view = current_location_view,+ )+ except LocationView.DoesNotExist:+ logger.warning( 'No current location view to add new collection to.')++ return+@method_decorator( edit_required, name='dispatch' )class CollectionDeleteView( HiModalView ):@@ -66,12 +75,15 @@ class CollectionDeleteView( HiModalView ):return 'collection/edit/modals/collection_delete.html'def get(self, request, *args, **kwargs):- collection_id = kwargs.get( 'collection_id' )- if not collection_id:- raise BadRequest( 'No current collection found.' )-try:- collection = Collection.objects.get( id = collection_id )+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )except Collection.DoesNotExist:raise Http404( request )@@ -81,26 +93,26 @@ class CollectionDeleteView( HiModalView ):return self.modal_response( request, context )def post( self, request, *args, **kwargs ):- action = request.POST.get( 'action' )- if action != 'confirm':- raise BadRequest( 'Missing confirmation value.' )-- collection_id = kwargs.get( 'collection_id' )- if not collection_id:- raise BadRequest( 'Missing collection id.' )try:- collection = Collection.objects.get( id = collection_id )+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )except Collection.DoesNotExist:raise Http404( request )+ action = request.POST.get( 'action' )+ if action != 'confirm':+ raise BadRequest( 'Missing confirmation value.' )+collection.delete()- if request.view_parameters.view_type == ViewType.COLLECTION:- next_collection = Collection.objects.all().order_by( 'order_id' ).first()- if next_collection:- request.view_parameters.collection_id = next_collection.id- else:- request.view_parameters.collection_id = None+ if request.view_parameters.collection_id == collection_id:+ request.view_parameters.update_collection( collection = None )request.view_parameters.to_session( request )redirect_url = reverse('home')diff --git a/src/hi/apps/collection/templates/collection/collection_buttons.html b/src/hi/apps/collection/templates/collection/collection_buttons.htmlindex 365b6e1a..0fe56616 100644--- a/src/hi/apps/collection/templates/collection/collection_buttons.html+++ b/src/hi/apps/collection/templates/collection/collection_buttons.html@@ -4,7 +4,7 @@class="{% if request.is_editing %}draggable{% endif %}"{% if request.is_editing %}draggable="true"{% endif %}>- <a href="{% url 'collection_view' id=collection.id %}"+ <a href="{% url 'collection_view' collection_id=collection.id %}"class="btn btn-secondary btn-control"role="button"data-async="true" >diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_form.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_form.htmldeleted file mode 100644index 11cf312c..00000000--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_edit_form.html+++ /dev/null@@ -1,22 +0,0 @@-{% for hidden in collection_form.hidden_fields %}-{{ hidden }}-{% endfor %}--{% if collection_form.non_field_errors %}-<div class="non-field-errors">- {% for err in collection_form.non_field_errors %}- <p class="form-error text-danger">ERROR: {{ err }}</p>- {% endfor %}-</div>-{% endif %}--<div>- {{ collection_form.name.label }}- {{ collection_form.name }}- {{ collection_form.name.errors }}-</div>-<div>- {{ collection_form.collection_type_str.label }}- {{ collection_form.collection_type_str }}- {{ collection_form.collection_type_str.errors }}-</div>diff --git a/src/hi/apps/collection/templates/collection/edit/panes/collection_form.html b/src/hi/apps/collection/templates/collection/edit/panes/collection_form.htmlindex c1f56476..1d0988e0 100644--- a/src/hi/apps/collection/templates/collection/edit/panes/collection_form.html+++ b/src/hi/apps/collection/templates/collection/edit/panes/collection_form.html@@ -26,3 +26,9 @@{{ collection_form.name.errors }}</div>+<div>+ {{ collection_form.order_id.label }}+ {{ collection_form.order_id }}+ {{ collection_form.order_id.errors }}+</div>+diff --git a/src/hi/apps/collection/transient_models.py b/src/hi/apps/collection/transient_models.pyindex 6a215d68..e3bfcae7 100644--- a/src/hi/apps/collection/transient_models.py+++ b/src/hi/apps/collection/transient_models.py@@ -3,10 +3,25 @@ from typing import Listfrom hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entity+from hi.apps.location.models import LocationViewfrom .models import Collection+@dataclass+class CollectionViewItem:++ collection : Collection+ exists_in_view : bool+++@dataclass+class CollectionViewGroup:++ location_view : LocationView+ item_list : List[CollectionViewItem] = field( default_factory = list )++@dataclassclass EntityCollectionItem:diff --git a/src/hi/apps/collection/urls.py b/src/hi/apps/collection/urls.pyindex 1aecd16b..6a6b66bc 100644--- a/src/hi/apps/collection/urls.py+++ b/src/hi/apps/collection/urls.py@@ -6,8 +6,8 @@ from . import viewsurlpatterns = [- re_path( r'^view/(?P<id>\d+)$',- views.CollectionView.as_view(),+ re_path( r'^view/(?P<collection_id>\d+)$',+ views.CollectionViewView.as_view(),name='collection_view'),re_path( r'^view$',diff --git a/src/hi/apps/collection/views.py b/src/hi/apps/collection/views.pyindex 8af018b1..a32cebf4 100644--- a/src/hi/apps/collection/views.py+++ b/src/hi/apps/collection/views.py@@ -28,38 +28,41 @@ class CollectionViewDefaultView( View ):return HttpResponseRedirect( redirect_url )def _get_default_collection( self, request ):- if request.view_parameters.collection:- return request.view_parameters.collection-- collection = Collection.objects.order_by( 'order_id' ).first()- if not collection:+ try:+ collection = CollectionManager().get_default_collection( request = request )+ except Collection.DoesNotExist:raise BadRequest( 'No collections defined.' )request.view_parameters.view_type = ViewType.COLLECTION- request.view_parameters.collection_id = collection.id+ request.view_parameters.update_collection( collection )request.view_parameters.to_session( request )return collection-class CollectionView( HiGridView ):+class CollectionViewView( HiGridView ):def get_main_template_name( self ) -> str:return 'collection/collection_view.html'def get_template_context( self, request, *args, **kwargs ):-- collection_id = kwargs.get('id')try:- collection = Collection.objects.get( id = collection_id )+ collection_id = int( kwargs.get( 'collection_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )except Collection.DoesNotExist:- raise Http404()+ raise Http404( request )# Remember last collection chosenview_type_changed = bool( request.view_parameters.view_type != ViewType.COLLECTION )view_id_changed = bool( request.view_parameters.collection_id != collection.id )request.view_parameters.view_type = ViewType.COLLECTION- request.view_parameters.collection_id = collection.id+ request.view_parameters.update_collection( collection )request.view_parameters.to_session( request )# When in edit mode, a collection change needs a fulldiff --git a/src/hi/apps/edit/templates/edit/panes/side_header.html b/src/hi/apps/edit/templates/edit/panes/side_header.htmlindex 0621c5cd..25d5d3fb 100644--- a/src/hi/apps/edit/templates/edit/panes/side_header.html+++ b/src/hi/apps/edit/templates/edit/panes/side_header.html@@ -3,14 +3,21 @@<div class="d-flex justify-content-between"><div class="h3"><small>View:</small> {{ request.view_parameters.location_view.name }}</div><div>- <a href="{% url 'location_details' location_view_id=request.view_parameters.view_type.location_view_id %}"+ <a href="{% url 'location_details' location_view_id=request.view_parameters.location_view_id %}"class="btn btn-tertiary" role="button" data-async="true">Location/View Details- </a>-+ </a></div></div>{% elif request.view_parameters.view_type.is_collection %}- <div class="h3"><small>Collection:</small> {{ request.view_parameters.collection.name }}</div>+ <div class="d-flex justify-content-between">+ <div class="h3"><small>Collection:</small> {{ request.view_parameters.collection.name }}</div>+ <div>+ <a href="{% url 'collection_details' collection_id=request.view_parameters.collection_id %}"+ class="btn btn-tertiary" role="button" data-async="true">+ Collection Details+ </a>+ </div>+ </div>{% endif %}</div>diff --git a/src/hi/apps/entity/async_views.py b/src/hi/apps/entity/async_views.pyindex 1d049473..abcdb93c 100644--- a/src/hi/apps/entity/async_views.py+++ b/src/hi/apps/entity/async_views.py@@ -3,6 +3,8 @@ import loggingfrom django.core.exceptions import BadRequestfrom django.http import Http404+from hi.apps.location.location_manager import LocationManager+from hi.hi_async_view import HiSideViewfrom .entity_manager import EntityManager@@ -31,7 +33,7 @@ class EntityDetailsView( HiSideView ):current_location_view = Noneif request.view_parameters.view_type.is_location_view:- current_location_view = request.view_parameters.location_view+ current_location_view = LocationManager().get_default_location_view( request = request )entity_detail_data = EntityManager().get_entity_detail_data(entity = entity,diff --git a/src/hi/apps/entity/edit/async_views.py b/src/hi/apps/entity/edit/async_views.pyindex 1611f674..1cdd93de 100644--- a/src/hi/apps/entity/edit/async_views.py+++ b/src/hi/apps/entity/edit/async_views.py@@ -1,5 +1,6 @@import logging+from django.core.exceptions import BadRequestfrom django.http import Http404from django.template.loader import get_templatefrom django.utils.decorators import method_decorator@@ -8,6 +9,7 @@ from django.views.generic import Viewimport hi.apps.common.antinode as antinodefrom hi.apps.entity.models import Entity, EntityPositionfrom hi.apps.location.svg_item_factory import SvgItemFactory+from hi.apps.location.location_manager import LocationManagerfrom hi.constants import DIVIDfrom hi.decorators import edit_required@@ -20,8 +22,10 @@ logger = logging.getLogger(__name__)class EntityEditView( View ):def post( self, request, *args, **kwargs ):-- entity_id = kwargs.get('entity_id')+ try:+ entity_id = int( kwargs.get('entity_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid entity id.' )try:entity = Entity.objects.get( id = entity_id )except Entity.DoesNotExist:@@ -48,9 +52,12 @@ class EntityEditView( View ):class EntityPositionEditView( View ):def post(self, request, *args, **kwargs):+ try:+ entity_id = int( kwargs.get('entity_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid entity id.' )- entity_id = kwargs.get('entity_id')- location = request.view_parameters.location+ location = LocationManager().get_default_location( request = request )try:entity_position = EntityPosition.objects.get(entity_id = entity_id,diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.pyindex 9dd7503a..0751ec41 100644--- a/src/hi/apps/entity/edit/views.py+++ b/src/hi/apps/entity/edit/views.py@@ -7,9 +7,10 @@ from django.urls import reversefrom django.utils.decorators import method_decoratorfrom hi.apps.collection.collection_manager import CollectionManager-import hi.apps.common.antinode as antinode+from hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.entity.models import Entityfrom hi.apps.location.location_manager import LocationManager+from hi.apps.location.models import LocationViewfrom hi.decorators import edit_requiredfrom hi.hi_async_view import HiModalView@@ -37,36 +38,46 @@ class EntityAddView( HiModalView ):context = {'entity_form': entity_form,}- return antinode.modal_from_template(+ return self.modal_response( request, context )++ with transaction.atomic():+ entity = entity_form.save()+ self._add_to_current_view_type(request = request,- template_name = 'entity/edit/modals/entity_add.html',- context = context,+ entity = entity,)++ redirect_url = reverse('home')+ return self.redirect_response( request, redirect_url )- try:- with transaction.atomic():- entity = entity_form.save()- if ( request.view_parameters.view_type.is_location_view- and request.view_parameters.location_view_id ):- LocationManager().add_entity_to_view_by_id(- entity = entity,- location_view_id = request.view_parameters.location_view_id,- )-- elif ( request.view_parameters.view_type.is_collection- and request.view_parameters.collection_id ):- CollectionManager().add_entity_to_collection_by_id(- entity = entity,- collection_id = request.view_parameters.collection_id,- )-- redirect_url = reverse('home')- return self.redirect_response( request, redirect_url )-- except ValueError as e:- raise BadRequest( str(e) )+ def _add_to_current_view_type( self, request, entity : Entity ):+ if request.view_parameters.view_type.is_location_view:+ try:+ current_location_view = LocationManager().get_default_location_view( request = request )+ EntityManager().add_entity_to_view(+ entity = entity,+ location_view = current_location_view,+ )+ except LocationView.DoesNotExist:+ logger.warning( 'No current location view to add new entity to.')++ elif request.view_parameters.view_type.is_collection:+ try:+ current_collection = CollectionManager().get_default_collection( request = request )+ CollectionManager().add_entity_to_collection(+ entity = entity,+ collection = current_collection,+ )+ except LocationView.DoesNotExist:+ logger.warning( 'No current collection to add new entity to.')++ else:+ logger.warning( 'No valid current view type to add new entity to.')++ return+@method_decorator( edit_required, name='dispatch' )class EntityDeleteView( HiModalView ):@@ -74,10 +85,10 @@ class EntityDeleteView( HiModalView ):return 'entity/edit/modals/entity_delete.html'def get( self, request, *args, **kwargs ):- entity_id = kwargs.get( 'entity_id' )- if not entity_id:- raise BadRequest( 'Missing entity id in request.' )-+ try:+ entity_id = int( kwargs.get('entity_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid entity id.' )try:entity = Entity.objects.get( id = entity_id )except Entity.DoesNotExist:diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex cc62afba..c53412c7 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -1,4 +1,5 @@from decimal import Decimal+from typing import Listfrom django.db import transaction@@ -7,6 +8,7 @@ from hi.apps.entity.edit.forms import EntityForm, EntityPositionFormfrom hi.apps.location.models import Location, LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactory+from .delegation_manager import DelegationManagerfrom .entity_detail_data import EntityDetailDatafrom .enums import (EntityType,@@ -17,6 +19,10 @@ from .models import (EntityPosition,EntityView,)+from .transient_models import (+ EntityViewGroup,+ EntityViewItem,+)class EntityManager(Singleton):@@ -43,44 +49,26 @@ class EntityManager(Singleton):location : Location,svg_path_str : str ) -> EntityPath:- try:- entity_path = EntityPath.objects.get(+ with transaction.atomic():+ try:+ entity_path = EntityPath.objects.get(+ location = location,+ entity_id = entity_id,+ )+ entity_path.svg_path = svg_path_str+ entity_path.save()+ return entity_path++ except EntityPath.DoesNotExist:+ pass++ entity = Entity.objects.get( id = entity_id )+ return EntityPath.objects.create(+ entity = entity,location = location,- entity_id = entity_id,+ svg_path = svg_path_str,)- entity_path.svg_path = svg_path_str- entity_path.save()- return entity_path-- except EntityPath.DoesNotExist:- pass-- entity = Entity.objects.get( id = entity_id )- return EntityPath.objects.create(- entity = entity,- location = location,- svg_path = svg_path_str,- )- def get_entity_position( self,- entity_id : int,- location : Location ) -> EntityPosition:- try:- entity = Entity.objects.get( id = entity_id )- except Entity.DoesNotExist:- return None-- entity_position = EntityPosition.objects.filter(- entity = entity,- location = location,- ).first()- if entity_position:- return entity_position- return EntityPosition(- entity = entity,- location = location,- )-def create_entity_view( self, entity : Entity, location_view : LocationView ):with transaction.atomic():@@ -111,7 +99,7 @@ class EntityManager(Singleton):)return entity_view-+def remove_entity_view( self, entity : Entity, location_view : LocationView ):with transaction.atomic():@@ -123,6 +111,57 @@ class EntityManager(Singleton):return+ def add_entity_to_view( self, entity : Entity, location_view : LocationView ):++ with transaction.atomic():+ # Only create delegate entities the first time an entity is added to a view.+ if not entity.entity_views.all().exists():+ delegate_entity_list = DelegationManager().get_delegate_entities_with_defaults(+ entity = entity,+ )+ else:+ delegate_entity_list = DelegationManager().get_delegate_entities(+ entity = entity,+ )++ _ = self.create_entity_view(+ entity = entity,+ location_view = location_view,+ )++ for delegate_entity in delegate_entity_list:+ _ = self.create_entity_view(+ entity = delegate_entity,+ location_view = location_view,+ )+ continue++ return++ def toggle_entity_in_view( self, entity : Entity, location_view : LocationView ) -> bool:++ try:+ self.remove_entity_from_view( entity = entity, location_view = location_view )+ return False+ except EntityView.DoesNotExist:+ self.add_entity_to_view( entity = entity, location_view = location_view )+ return True++ def remove_entity_from_view( self, entity : Entity, location_view : LocationView ):++ with transaction.atomic():+ self.remove_entity_view(+ entity = entity,+ location_view = location_view,+ )++ DelegationManager().remove_delegate_entities_from_view_if_needed(+ entity = entity,+ location_view = location_view,+ )++ return+def add_entity_position_if_needed( self,entity : Entity,location_view : LocationView ) -> EntityPosition:@@ -194,3 +233,35 @@ class EntityManager(Singleton):entity_position_form = entity_position_form,)+ def create_entity_view_group_list( self, location_view : LocationView ) -> List[EntityViewGroup]:++ entity_queryset = Entity.objects.all()++ entity_view_group_dict = dict()+ for entity in entity_queryset:++ exists_in_view = False+ for entity_view in entity.entity_views.all():+ if entity_view.location_view == location_view:+ exists_in_view = True+ break+ continue++ entity_view_item = EntityViewItem(+ entity = entity,+ exists_in_view = exists_in_view,+ )++ if entity.entity_type not in entity_view_group_dict:+ entity_view_group = EntityViewGroup(+ location_view = location_view,+ entity_type = entity.entity_type,+ )+ entity_view_group_dict[entity.entity_type] = entity_view_group+ entity_view_group_dict[entity.entity_type].item_list.append( entity_view_item )+ continue++ entity_view_group_list = list( entity_view_group_dict.values() )+ entity_view_group_list.sort( key = lambda item : item.entity_type.label )+ return entity_view_group_list+diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pynew file mode 100644index 00000000..f5c59a1d--- /dev/null+++ b/src/hi/apps/entity/transient_models.py@@ -0,0 +1,22 @@+from dataclasses import dataclass, field+from typing import List++from hi.apps.location.models import LocationView++from .enums import EntityType+from .models import Entity+++@dataclass+class EntityViewItem:++ entity : Entity+ exists_in_view : bool+++@dataclass+class EntityViewGroup:++ location_view : LocationView+ entity_type : EntityType+ item_list : List[EntityViewItem] = field( default_factory = list )diff --git a/src/hi/apps/location/async_views.py b/src/hi/apps/location/async_views.pyindex 787dd3e9..769afa24 100644--- a/src/hi/apps/location/async_views.py+++ b/src/hi/apps/location/async_views.py@@ -16,6 +16,8 @@ from hi.apps.location.edit.forms import (from hi.enums import ItemTypefrom hi.hi_async_view import HiSideView+from .location_manager import LocationManager+from .models import LocationViewlogger = logging.getLogger(__name__)@@ -30,24 +32,17 @@ class LocationViewDetailsView( HiSideView ):return Truedef get_template_context( self, request, *args, **kwargs ):-- location_view_id = kwargs.get( 'location_view_id' )- if location_view_id:- location_view_id = int(location_view_id)- default_location_view_id = request.view_parameters.location_view_id- if default_location_view_id:- default_location_view_id = int(default_location_view_id)-- if not location_view_id and not default_location_view_id:- raise BadRequest( 'No location given and no default available.' )-- if location_view_id and ( location_view_id != default_location_view_id ):- try:- location_view = LocationView.objects.get( id = location_view_id )- except LocationView.DoesNotExist:- raise Http404()- else:- location_view = request.view_parameters.location_view+ try:+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )+ except LocationView.DoesNotExist:+ raise Http404( request )return {'location': location_view.location,diff --git a/src/hi/apps/location/edit/async_views.py b/src/hi/apps/location/edit/async_views.pyindex 5a629c11..f95383a7 100644--- a/src/hi/apps/location/edit/async_views.py+++ b/src/hi/apps/location/edit/async_views.py@@ -32,9 +32,15 @@ logger = logging.getLogger(__name__)class LocationEditView( View ):def post( self, request, *args, **kwargs ):- location_id = kwargs.get('location_id')try:- location = Location.objects.get( id = location_id )+ location_id = int( kwargs.get( 'location_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location id.' )+ try:+ location = LocationManager().get_location(+ request = request,+ location_id = location_id,+ )except Location.DoesNotExist:raise Http404( request )@@ -78,12 +84,11 @@ class LocationViewManageItemsView( HiSideView ):def get_template_context( self, request, *args, **kwargs ):- location_view = request.view_parameters.location_view- location_manager = LocationManager()- entity_view_group_list = location_manager.create_entity_view_group_list(+ location_view = LocationManager().get_default_location_view( request = request )+ entity_view_group_list = EntityManager().create_entity_view_group_list(location_view = location_view,)- collection_view_group = location_manager.create_collection_view_group(+ collection_view_group = CollectionManager().create_collection_view_group(location_view = location_view,)return {@@ -114,11 +119,15 @@ class LocationViewReorder( View ):class LocationViewEditView( View ):def post( self, request, *args, **kwargs ):-- location_view_id = kwargs.get('location_view_id')try:- location_view = LocationView.objects.select_related(- 'location' ).get( id = location_view_id )+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )except LocationView.DoesNotExist:raise Http404( request )@@ -143,11 +152,15 @@ class LocationViewEditView( View ):class LocationViewGeometryView( View ):def post(self, request, *args, **kwargs):-- location_view_id = kwargs.get('location_view_id')try:- location_view = LocationView.objects.select_related(- 'location' ).get( id = location_view_id )+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )except LocationView.DoesNotExist:raise Http404( request )@@ -176,13 +189,28 @@ class LocationViewGeometryView( View ):class LocationViewEntityToggleView( View ):def post( self, request, *args, **kwargs ):+ try:+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )+ except LocationView.DoesNotExist:+ raise Http404( request )- location_view_id = kwargs.get('location_view_id')- entity_id = kwargs.get('entity_id')+ try:+ entity_id = int( kwargs.get('entity_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid entity id.' )+ try:+ entity = Entity.objects.get( id = entity_id )+ except Entity.DoesNotExist:+ raise Http404( request )- entity = Entity.objects.get( id = entity_id )- location_view = LocationView.objects.get( id = location_view_id )- exists_in_view = LocationManager().toggle_entity_in_view(+ exists_in_view = EntityManager().toggle_entity_in_view(entity = entity,location_view = location_view,)@@ -216,13 +244,31 @@ class LocationViewEntityToggleView( View ):class LocationViewCollectionToggleView( View ):def post(self, request, *args, **kwargs):+ try:+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )+ except LocationView.DoesNotExist:+ raise Http404( request )- location_view_id = kwargs.get('location_view_id')- collection_id = kwargs.get('collection_id')+ try:+ collection_id = int( kwargs.get('collection_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid collection id.' )+ try:+ collection = CollectionManager().get_collection(+ request = request,+ collection_id = collection_id,+ )+ except Collection.DoesNotExist:+ raise Http404( request )- collection = Collection.objects.get( id = collection_id )- location_view = LocationView.objects.get( id = location_view_id )- exists_in_view = LocationManager().toggle_collection_in_view(+ exists_in_view = CollectionManager().toggle_collection_in_view(collection = collection,location_view = location_view,)@@ -290,17 +336,21 @@ class LocationItemPathView( View ):if not svg_path_str:raise BadRequest( 'Missing SVG path' )- location_view = request.view_parameters.location_view+ location = LocationManager().get_default_location( request = request )if item_type == ItemType.ENTITY:EntityManager().set_entity_path(entity_id = item_id,- location = location_view.location,+ location = location,svg_path_str = svg_path_str,)elif item_type == ItemType.COLLECTION:- CollectionManager().set_collection_path(+ collection = CollectionManager().get_collection(+ request = request,collection_id = item_id,- location = location_view.location,+ )+ CollectionManager().set_collection_path(+ collection = collection,+ location = location,svg_path_str = svg_path_str,)else:diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.pyindex d9642023..58e71ee4 100644--- a/src/hi/apps/location/edit/views.py+++ b/src/hi/apps/location/edit/views.py@@ -52,7 +52,7 @@ class LocationAddView( HiModalView ):location_view = location.views.order_by( 'order_id' ).first()request.view_parameters.view_type = ViewType.LOCATION_VIEW- request.view_parameters.location_view_id = location_view.id+ request.view_parameters.update_location_view( location_view )request.view_parameters.to_session( request )redirect_url = reverse('home')@@ -66,13 +66,18 @@ class LocationSvgReplaceView( HiModalView ):return 'location/edit/modals/location_svg_replace.html'def get( self, request, *args, **kwargs ):- location_id = kwargs.get( 'location_id' )- if not location_id:- raise BadRequest( 'Missing location id.' )try:- location = Location.objects.get( id = location_id )+ location_id = int( kwargs.get( 'location_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location id.' )+ try:+ location = LocationManager().get_location(+ request = request,+ location_id = location_id,+ )except Location.DoesNotExist:raise Http404( request )+context = {'location': location,'location_svg_file_form': forms.LocationSvgReplaceForm(),@@ -80,11 +85,15 @@ class LocationSvgReplaceView( HiModalView ):return self.modal_response( request, context )def post( self, request, *args, **kwargs ):- location_id = kwargs.get( 'location_id' )- if not location_id:- raise BadRequest( 'Missing location id.' )try:- location = Location.objects.get( id = location_id )+ location_id = int( kwargs.get( 'location_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location id.' )+ try:+ location = LocationManager().get_location(+ request = request,+ location_id = location_id,+ )except Location.DoesNotExist:raise Http404( request )@@ -117,11 +126,15 @@ class LocationDeleteView( HiModalView ):return 'location/edit/modals/location_delete.html'def get(self, request, *args, **kwargs):- location_id = kwargs.get( 'location_id' )- if not location_id:- raise BadRequest( 'Missing location id.' )try:- location = Location.objects.get( id = location_id )+ location_id = int( kwargs.get('location_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location id.' )+ try:+ location = LocationManager().get_location(+ request = request,+ location_id = location_id,+ )except Location.DoesNotExist:raise Http404( request )@@ -131,27 +144,27 @@ class LocationDeleteView( HiModalView ):return self.modal_response( request, context )def post( self, request, *args, **kwargs ):- action = request.POST.get( 'action' )- if action != 'confirm':- raise BadRequest( 'Missing confirmation value.' )-- location_id = kwargs.get( 'location_id' )- if not location_id:- raise BadRequest( 'Missing location id.' )-try:- location = Location.objects.get( id = location_id )+ location_id = int( kwargs.get('location_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location id.' )+ try:+ location = LocationManager().get_location(+ request = request,+ location_id = location_id,+ )except Location.DoesNotExist:raise Http404( request )+ action = request.POST.get( 'action' )+ if action != 'confirm':+ raise BadRequest( 'Missing confirmation value.' )+location.delete()- next_location = Location.objects.all().order_by( 'order_id' ).first()- if next_location:- request.view_parameters.location_id = next_location.id- else:- request.view_parameters.location_id = None- request.view_parameters.to_session( request )+ if request.view_parameters.location_id == location_id:+ request.view_parameters.update_location_view( location_view = None )+ request.view_parameters.to_session( request )redirect_url = reverse('home')return self.redirect_response( request, redirect_url )@@ -164,12 +177,22 @@ class LocationViewAddView( HiModalView ):return 'location/edit/modals/location_view_add.html'def get( self, request, *args, **kwargs ):+ try:+ # Ensure we have a location to add the view to.+ _ = LocationManager().get_default_location( request = request )+ except Location.DoesNotExist:+ raise BadRequest( 'No locations defined.' )context = {'location_view_add_form': forms.LocationViewAddForm(),}return self.modal_response( request, context )def post( self, request, *args, **kwargs ):+ try:+ current_location = LocationManager().get_default_location( request = request )+ except Location.DoesNotExist:+ raise BadRequest( 'No locations defined.' )+location_view_add_form = forms.LocationViewAddForm( request.POST )if not location_view_add_form.is_valid():context = {@@ -177,21 +200,16 @@ class LocationViewAddView( HiModalView ):}return self.modal_response( request, context )- if request.view_parameters.location_view:- location = request.view_parameters.location_view.location- else:- location = Location.objects.order_by( 'order_id' ).first()-try:location_view = LocationManager().create_location_view(- location = location,+ location = current_location,name = location_view_add_form.cleaned_data.get('name'),)except ValueError as e:raise BadRequest( str(e) )request.view_parameters.view_type = ViewType.LOCATION_VIEW- request.view_parameters.location_view_id = location_view.id+ request.view_parameters.update_location_view( location_view = location_view )request.view_parameters.to_session( request )redirect_url = reverse('home')@@ -205,13 +223,15 @@ class LocationViewDeleteView( HiModalView ):return 'location/edit/modals/location_view_delete.html'def get(self, request, *args, **kwargs):- location_view_id = kwargs.get( 'location_view_id' )- if not location_view_id:- raise BadRequest( 'Missing location view id.' )-try:- location_view = LocationView.objects.select_related(- 'location' ).get( id = location_view_id )+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )except LocationView.DoesNotExist:raise Http404( request )@@ -221,28 +241,27 @@ class LocationViewDeleteView( HiModalView ):return self.modal_response( request, context )def post( self, request, *args, **kwargs ):- action = request.POST.get( 'action' )- if action != 'confirm':- raise BadRequest( 'Missing confirmation value.' )-- location_view_id = kwargs.get( 'location_view_id' )- if not location_view_id:- raise BadRequest( 'Missing location view id.' )-try:- location_view = LocationView.objects.select_related(- 'location' ).get( id = location_view_id )+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )except LocationView.DoesNotExist:raise Http404( request )+ action = request.POST.get( 'action' )+ if action != 'confirm':+ raise BadRequest( 'Missing confirmation value.' )+location_view.delete()- next_location_view = LocationView.objects.all().order_by( 'order_id' ).first()- if next_location_view:- request.view_parameters.location_view_id = next_location_view.id- else:- request.view_parameters.location_view_id = None- request.view_parameters.to_session( request )+ if request.view_parameters.location_view_id == location_view_id:+ request.view_parameters.update_location_view( location_view = None )+ request.view_parameters.to_session( request )redirect_url = reverse('home')return self.redirect_response( request, redirect_url )diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.pyindex 9e84b2fe..d6f01590 100644--- a/src/hi/apps/location/location_manager.py+++ b/src/hi/apps/location/location_manager.py@@ -4,20 +4,10 @@ from typing import Listfrom django.core.files.storage import default_storage, FileSystemStoragefrom django.db import transaction+from django.http import HttpRequest-from hi.apps.collection.collection_manager import CollectionManager-from hi.apps.collection.models import (- Collection,- CollectionView,-)from hi.apps.common.singleton import Singletonfrom hi.apps.common.svg_models import SvgViewBox-from hi.apps.entity.delegation_manager import DelegationManager-from hi.apps.entity.entity_manager import EntityManager-from hi.apps.entity.models import (- Entity,- EntityView,-)from .enums import LocationViewTypefrom .location_view_data import LocationViewData@@ -25,12 +15,6 @@ from .models import (Location,LocationView,)-from .transient_models import (- EntityViewGroup,- EntityViewItem,- CollectionViewItem,- CollectionViewGroup,-)class LocationManager(Singleton):@@ -40,6 +24,30 @@ class LocationManager(Singleton):def __init_singleton__(self):return+ def get_location( self, request : HttpRequest, location_id : int ) -> Location:+ """+ This should always be used to fetch from the database and never using+ the "objects" query interface. The view_parameters loads the+ current default Location, so any out-of-band loading risks the+ cached view_parameters version to be different from the one+ loaded. Since so much of the app features revolve around the+ current location, not having the default update can result in hard+ to detect issues.+ """+ current_location = request.view_parameters.location+ if current_location and ( current_location.id == int(location_id) ):+ return current_location+ return Location.objects.get( id = location_id )++ def get_default_location( self, request : HttpRequest ) -> Location:+ current_location = request.view_parameters.location+ if current_location:+ return current_location+ location = Location.objects.order_by( 'order_id' ).first()+ if location:+ return location+ raise Location.DoesNotExist()+def create_location( self,name : str,svg_fragment_filename : str,@@ -114,6 +122,36 @@ class LocationManager(Singleton):order_id = order_id,)+ def get_location_view( self, request : HttpRequest, location_view_id : int ) -> LocationView:+ """+ This should always be used to fetch from the database and never using+ the "objects" query interface. The view_parameters loads the+ current default LocationView, so any out-of-band loading risks the+ cached view_parameters version to be different from the one+ loaded. Since so much of the app features revolve around the+ current location view, not having the default update can result in+ hard to detect issues.+ """+ current_location_view = request.view_parameters.location_view+ if current_location_view and ( current_location_view.id == int(location_view_id) ):+ return current_location_view+ return LocationView.objects.select_related('location').get( id = location_view_id )++ def get_default_location_view( self, request : HttpRequest ) -> LocationView:+ current_location_view = request.view_parameters.location_view+ if current_location_view:+ return current_location_view++ location = self.get_default_location( request = request )+ if not location:+ raise LocationView.DoesNotExist()++ location_view = location.views.order_by( 'order_id' ).first()+ if not location_view:+ raise LocationView.DoesNotExist()++ return location_view+def get_location_view_data( self, location_view : LocationView ):location = location_view.location@@ -173,150 +211,18 @@ class LocationManager(Singleton):orphan_entities = orphan_entities,)- def create_entity_view_group_list( self, location_view : LocationView ) -> List[EntityViewGroup]:-- entity_queryset = Entity.objects.all()-- entity_view_group_dict = dict()- for entity in entity_queryset:-- exists_in_view = False- for entity_view in entity.entity_views.all():- if entity_view.location_view == location_view:- exists_in_view = True- break- continue-- entity_view_item = EntityViewItem(- entity = entity,- exists_in_view = exists_in_view,- )-- if entity.entity_type not in entity_view_group_dict:- entity_view_group = EntityViewGroup(- location_view = location_view,- entity_type = entity.entity_type,- )- entity_view_group_dict[entity.entity_type] = entity_view_group- entity_view_group_dict[entity.entity_type].item_list.append( entity_view_item )- continue-- entity_view_group_list = list( entity_view_group_dict.values() )- entity_view_group_list.sort( key = lambda item : item.entity_type.label )- return entity_view_group_list-- def create_collection_view_group( self, location_view : LocationView ) -> CollectionViewGroup:-- collection_queryset = Collection.objects.all()-- collection_view_group = CollectionViewGroup(- location_view = location_view,- )- for collection in collection_queryset:-- exists_in_view = False- for collection_view in collection.collection_views.all():- if collection_view.location_view == location_view:- exists_in_view = True- break- continue-- collection_view_item = CollectionViewItem(- collection = collection,- exists_in_view = exists_in_view,- )- collection_view_group.item_list.append( collection_view_item )- continue-- collection_view_group.item_list.sort( key = lambda item : item.collection.name )- return collection_view_group-- def toggle_entity_in_view( self, entity : Entity, location_view : LocationView ) -> bool:-- try:- self.remove_entity_from_view( entity = entity, location_view = location_view )- return False- except EntityView.DoesNotExist:- self.add_entity_to_view( entity = entity, location_view = location_view )- return True-- def remove_entity_from_view( self, entity : Entity, location_view : LocationView ):-- with transaction.atomic():- EntityManager().remove_entity_view(- entity = entity,- location_view = location_view,- )-- DelegationManager().remove_delegate_entities_from_view_if_needed(- entity = entity,- location_view = location_view,- )-- return-- def add_entity_to_view_by_id( self, entity : Entity, location_view_id : int ):- location_view = LocationView.objects.get( id = location_view_id )- self.add_entity_to_view( entity = entity, location_view = location_view )- return-- def add_entity_to_view( self, entity : Entity, location_view : LocationView ):-- with transaction.atomic():- # Only create delegate entities the first time an entity is added to a view.- if not entity.entity_views.all().exists():- delegate_entity_list = DelegationManager().get_delegate_entities_with_defaults(- entity = entity,- )- else:- delegate_entity_list = DelegationManager().get_delegate_entities(- entity = entity,- )-- _ = EntityManager().create_entity_view(- entity = entity,- location_view = location_view,- )-- for delegate_entity in delegate_entity_list:- _ = EntityManager().create_entity_view(- entity = delegate_entity,- location_view = location_view,- )- continue-- return-- def toggle_collection_in_view( self,- collection : Collection,- location_view : LocationView ) -> bool:-- try:- with transaction.atomic():- CollectionManager().remove_collection_view(- collection = collection,- location_view = location_view,- )- return False-- except CollectionView.DoesNotExist:- with transaction.atomic():- _ = CollectionManager().create_collection_view(- collection = collection,- location_view = location_view,- )- return True-def set_location_view_order( self, location_view_id_list : List[int] ):- item_id_to_order_id = {+ item_id_to_idx = {item_id: order_id for order_id, item_id in enumerate( location_view_id_list )}location_view_queryset = LocationView.objects.filter( id__in = location_view_id_list )with transaction.atomic():for location_view in location_view_queryset:- location_view.order_id = item_id_to_order_id.get( location_view.id )+ item_idx = item_id_to_idx.get( location_view.id )+ order_id = 2 * ( item_idx + 1) # Leave gaps to make one-off insertions easier+ location_view.order_id = order_idlocation_view.save()continuereturndiff --git a/src/hi/apps/location/templates/location/location_view_buttons.html b/src/hi/apps/location/templates/location/location_view_buttons.htmlindex 6ba30da7..90126867 100644--- a/src/hi/apps/location/templates/location/location_view_buttons.html+++ b/src/hi/apps/location/templates/location/location_view_buttons.html@@ -4,7 +4,7 @@class="{% if request.is_editing %}draggable{% endif %}"{% if request.is_editing %}draggable="true"{% endif %}>- <a href="{% url 'location_view' id=location_view.id %}"+ <a href="{% url 'location_view' location_view_id=location_view.id %}"class="btn btn-primary btn-control"role="button"data-async="true" >diff --git a/src/hi/apps/location/transient_models.py b/src/hi/apps/location/transient_models.pydeleted file mode 100644index 0ae5bca1..00000000--- a/src/hi/apps/location/transient_models.py+++ /dev/null@@ -1,37 +0,0 @@-from dataclasses import dataclass, field-from typing import List--from hi.apps.collection.models import Collection-from hi.apps.entity.enums import EntityType-from hi.apps.entity.models import Entity--from .models import LocationView---@dataclass-class EntityViewItem:-- entity : Entity- exists_in_view : bool---@dataclass-class EntityViewGroup:-- location_view : LocationView- entity_type : EntityType- item_list : List[EntityViewItem] = field( default_factory = list )---@dataclass-class CollectionViewItem:-- collection : Collection- exists_in_view : bool---@dataclass-class CollectionViewGroup:-- location_view : LocationView- item_list : List[CollectionViewItem] = field( default_factory = list )diff --git a/src/hi/apps/location/urls.py b/src/hi/apps/location/urls.pyindex 1355110a..bff22960 100644--- a/src/hi/apps/location/urls.py+++ b/src/hi/apps/location/urls.py@@ -10,11 +10,11 @@ urlpatterns = [views.LocationSwitchView.as_view(),name='location_switch'),- re_path( r'^details/(?P<location_view_id>\d*)$',+ re_path( r'^details/(?P<location_view_id>\d+)$',async_views.LocationViewDetailsView.as_view(),name='location_details' ),- re_path( r'^view/(?P<id>\d+)$',+ re_path( r'^view/(?P<location_view_id>\d+)$',views.LocationViewView.as_view(),name='location_view'),diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex 7251c43a..7974e4e1 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -33,19 +33,13 @@ class LocationViewDefaultView( View ):return HttpResponseRedirect( redirect_url )def _get_default_location_view( self, request ):- if request.view_parameters.location_view:- return request.view_parameters.location_view-- location = Location.objects.order_by( 'order_id' ).first()- if not location:- raise Location.DoesNotExist()-- location_view = location.views.order_by( 'order_id' ).first()- if not location_view:- raise BadRequest( 'No views defined for this location.' )+ try:+ location_view = LocationManager().get_default_location_view( request = request )+ except LocationView.DoesNotExist:+ raise BadRequest( 'No views and no locations defined.' )request.view_parameters.view_type = ViewType.LOCATION_VIEW- request.view_parameters.location_view_id = location_view.id+ request.view_parameters.update_location_view( location_view )request.view_parameters.to_session( request )return location_view@@ -56,20 +50,24 @@ class LocationViewView( HiGridView ):return 'location/location_view.html'def get_template_context( self, request, *args, **kwargs ):-- location_view_id = kwargs.get('id')try:- location_view = LocationView.objects.select_related(- 'location' ).get( id = location_view_id )+ location_view_id = int( kwargs.get( 'location_view_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location view id.' )+ try:+ location_view = LocationManager().get_location_view(+ request = request,+ location_view_id = location_view_id,+ )except LocationView.DoesNotExist:- raise Http404()+ raise Http404( request )# Remember last location view chosenview_type_changed = bool( request.view_parameters.view_type != ViewType.LOCATION_VIEW )view_id_changed = bool( request.view_parameters.location_view_id != location_view.id )request.view_parameters.view_type = ViewType.LOCATION_VIEW- request.view_parameters.location_view_id = location_view.id+ request.view_parameters.update_location_view( location_view )request.view_parameters.to_session( request )# When in edit mode, a location view change needs a full@@ -96,10 +94,15 @@ class LocationViewView( HiGridView ):class LocationSwitchView( View ):def get(self, request, *args, **kwargs):-- location_id = kwargs.get('location_id')try:- location = Location.objects.get( id = location_id )+ location_id = int( kwargs.get('location_id'))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid location id.' )+ try:+ location = LocationManager().get_location(+ request = request,+ location_id = location_id,+ )except Location.DoesNotExist:raise Http404( request )@@ -108,7 +111,7 @@ class LocationSwitchView( View ):raise BadRequest( 'No views defined for this location.' )request.view_parameters.view_type = ViewType.LOCATION_VIEW- request.view_parameters.location_view_id = location_view.id+ request.view_parameters.update_location_view( location_view = location_view )request.view_parameters.to_session( request )redirect_url = reverse(diff --git a/src/hi/hi_grid_view.py b/src/hi/hi_grid_view.pyindex f865922a..136e7218 100644--- a/src/hi/hi_grid_view.py+++ b/src/hi/hi_grid_view.py@@ -12,7 +12,7 @@ from hi.apps.common.utils import is_ajaxfrom hi.apps.location.edit.async_views import LocationViewManageItemsViewfrom hi.apps.collection.edit.async_views import CollectionManageItemsView-+from hi.apps.location.location_manager import LocationManagerfrom hi.apps.collection.models import Collectionfrom hi.apps.location.models import Location@@ -76,7 +76,7 @@ class HiGridView(View):def get(self, request, *args, **kwargs):- current_location = request.view_parameters.location+ current_location = LocationManager().get_default_location( request = request )if not current_location:redirect_url = reverse('start')if is_ajax( request ):diff --git a/src/hi/static/js/edit-dragdrop.js b/src/hi/static/js/edit-dragdrop.jsindex d80e9a4f..e88fe43b 100644--- a/src/hi/static/js/edit-dragdrop.js+++ b/src/hi/static/js/edit-dragdrop.js@@ -21,7 +21,7 @@const DRAGGABLE_SELECTOR = '.' + DRAGGABLE_CLASS;const DRAG_OVER_CLASS = 'drag-over';- const API_REORDER_ITEMS_URL = '/edit/reorder-items';+ const API_REORDER_ITEMS_URL = '/edit/item/reorder';let gDraggedElement = null;diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex c7c64c3c..a015c878 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -14,7 +14,6 @@DATA_TYPE_ICON_VALUE: 'svg-icon',DATA_TYPE_PATH_VALUE: 'svg-path',API_LOCATION_ITEM_DETAILS_URL: '/location/item/details',- API_LOCATION_DETAILS_URL: '/location/details',generateUniqueId: function() {return _generateUniqueId();diff --git a/src/hi/view_parameters.py b/src/hi/view_parameters.pyindex 911a6fdb..90ea619a 100644--- a/src/hi/view_parameters.py+++ b/src/hi/view_parameters.py@@ -1,7 +1,7 @@from dataclasses import dataclassfrom hi.apps.collection.models import Collection-from hi.apps.location.models import LocationView+from hi.apps.location.models import Location, LocationViewfrom .enums import ViewMode, ViewType@@ -31,29 +31,48 @@ class ViewParameters:return@property- def location(self):+ def location_id(self) -> int:+ location = self.location+ if location:+ return self._location.id+ return None++ @property+ def location(self) -> Location:if self._location:return self._location- location_view = self.location_view- if not location_view:- return None- self._location = location_view.location+ _ = self.location_view # This will also load the location (if possible)return self._location@property- def location_view(self):+ def location_view(self) -> LocationView:if self._location_view:return self._location_viewif self.location_view_id is None:return Nonetry:- self._location_view = LocationView.objects.get( id = self.location_view_id )+ self._location_view = LocationView.objects.select_related('location').get(+ id = self.location_view_id,+ )+ self._location = self._location_view.locationreturn self._location_viewexcept LocationView.DoesNotExist:+ self.location_view_id = Nonereturn None++ def update_location_view( self, location_view : LocationView ):+ if not location_view:+ self.location_view_id = None+ self._location_view = None+ self._location = None+ else:+ self.location_view_id = location_view.id+ self._location_view = location_view+ self._location = location_view.location+ return@property- def collection(self):+ def collection(self) -> Collection:if self._collection:return self._collectionif self.collection_id is None:@@ -62,8 +81,18 @@ class ViewParameters:self._collection = Collection.objects.get( id = self.collection_id )return self._collectionexcept Collection.DoesNotExist:+ self.collection_id = Nonereturn None+ def update_collection( self, collection : Collection ):+ if not collection:+ self.collection_id = None+ self._collection = None+ else:+ self.collection_id = collection.id+ self._collection = collection+ return+def to_session( self, request ):if not hasattr( request, 'session' ):return