Home Information - Your home, your data, organized.
Python
Implemented Entity Pairing Management (replaces principal management).
Anthony Cassandrafa7e7d6bc111
diff --git a/src/hi/apps/entity/edit/urls.py b/src/hi/apps/entity/edit/urls.pyindex 7b035a21..b30168ac 100644--- a/src/hi/apps/entity/edit/urls.py+++ b/src/hi/apps/entity/edit/urls.py@@ -18,6 +18,6 @@ urlpatterns = [name='entity_position_edit' ),re_path( r'^entity/principal/manage/(?P<entity_id>\d+)$',- views.PrincipalManageView.as_view(),- name='entity_edit_principal_manage' ),+ views.ManagePairingsView.as_view(),+ name='entity_edit_manage_pairings' ),]diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.pyindex 54cfb917..a282fbc8 100644--- a/src/hi/apps/entity/edit/views.py+++ b/src/hi/apps/entity/edit/views.py@@ -12,6 +12,7 @@ from django.views.generic import Viewfrom hi.apps.collection.collection_manager import CollectionManagerimport hi.apps.common.antinode as antinodefrom hi.apps.entity.entity_manager import EntityManager+from hi.apps.entity.entity_pairing_manager import EntityPairingManagerfrom hi.apps.entity.forms import EntityFormfrom hi.apps.entity.models import Entity, EntityPositionfrom hi.apps.entity.view_mixin import EntityViewMixin@@ -169,43 +170,50 @@ class EntityPositionEditView( View, EntityViewMixin ):@method_decorator( edit_required, name='dispatch' )-class PrincipalManageView( HiModalView, EntityViewMixin ):+class ManagePairingsView( HiModalView, EntityViewMixin ):- PRINCIPAL_ENTITY_ID_NAME_PREFIX = 'principal-entity-id-'+ ENTITY_PAIR_ID_NAME_PREFIX = 'entity-pair-id-'def get_template_name( self ) -> str:- return 'entity/edit/modals/principal_manage.html'+ return 'entity/edit/modals/manage_pairings.html'def get( self, request, *args, **kwargs ):entity = self.get_entity( request, *args, **kwargs )- entity_manager = EntityManager()- entity_view_group_list = entity_manager.create_principal_entity_view_group_list(- entity= entity,+ entity_pairing_manager = EntityPairingManager()+ entity_pairings = entity_pairing_manager.get_entity_pairing_list( entity = entity )+ candidate_entities = entity_pairing_manager.get_candidate_entities( entity = entity )++ existing_entities = [ x.paired_entity for x in entity_pairings ]+ entity_view_group_list = EntityManager().create_entity_view_group_list(+ existing_entities = existing_entities,+ all_entities = candidate_entities,)context = {'entity': entity,'entity_view_group_list': entity_view_group_list,- 'principal_entity_id_name_prefix': self.PRINCIPAL_ENTITY_ID_NAME_PREFIX,+ 'principal_entity_id_name_prefix': self.ENTITY_PAIR_ID_NAME_PREFIX,}return self.modal_response( request, context )def post( self, request, *args, **kwargs ):entity = self.get_entity( request, *args, **kwargs )- desired_principal_entity_ids = set()+ desired_paired_entity_ids = set()for name, value in request.POST.items():m = re.match( r'(\D+)(\d+)', name )if not m:continueprefix = m.group(1)- if prefix == self.PRINCIPAL_ENTITY_ID_NAME_PREFIX:- desired_principal_entity_ids.add( int( m.group(2) ))+ if prefix == self.ENTITY_PAIR_ID_NAME_PREFIX:+ desired_paired_entity_ids.add( int( m.group(2) ))continue- EntityManager().adjust_principal_entities(- entity = entity,- desired_principal_entity_ids = desired_principal_entity_ids,- )-- return antinode.refresh_response()+ try:+ EntityPairingManager().adjust_entity_pairings(+ entity = entity,+ desired_paired_entity_ids = desired_paired_entity_ids,+ )+ return antinode.refresh_response()+ except EntityPairingManager.EntityPairingError as epe:+ raise BadRequest( str(epe) )diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex 451d4b84..74daf3e3 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -1,7 +1,7 @@from decimal import Decimalimport loggingfrom threading import local-from typing import List, Set+from typing import List, Sequencefrom django.db import transactionfrom django.db.models.signals import post_save, post_delete@@ -12,10 +12,9 @@ from hi.apps.entity.edit.forms import EntityPositionFormfrom hi.apps.location.models import Location, LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactory-from .delegation_manager import DelegationManager+from .entity_pairing_manager import EntityPairingManagerfrom .enums import (EntityGroupType,- EntityPairingType,EntityStateType,)from .models import (@@ -30,7 +29,6 @@ from .models import (from .transient_models import (EntityDetailsData,EntityEditData,- EntityPairing,EntityViewGroup,EntityViewItem,)@@ -77,48 +75,15 @@ class EntityManager(Singleton):if entity_position:entity_position_form = EntityPositionForm( instance = entity_position )- entity_pairing_list = self.get_entity_pairing_list( entity = entity )- principal_entity_list = self.get_principal_entity_list( entity = entity )+ entity_pairing_list = EntityPairingManager().get_entity_pairing_list( entity = entity )entity_edit_data = EntityEditData( entity = entity )return EntityDetailsData(entity_edit_data = entity_edit_data,entity_position_form = entity_position_form,entity_pairing_list = entity_pairing_list,- principal_entity_list = principal_entity_list,)- def get_entity_pairing_list( self, entity : Entity ) -> List[ EntityPairing ]:- delegation_manager = DelegationManager()- entity_pairing_list = list()-- for principal_entity in delegation_manager.get_principal_entities( entity = entity ):- entity_pairing = EntityPairing(- entity = entity,- paired_entity = principal_entity,- pairing_type = EntityPairingType.PRINCIPAL,- )- entity_pairing_list.append( entity_pairing )- continue-- for delegate_entity in delegation_manager.get_delegate_entities( entity = entity ):- entity_pairing = EntityPairing(- entity = entity,- paired_entity = delegate_entity,- pairing_type = EntityPairingType.DELEGATE,- )- entity_pairing_list.append( entity_pairing )- continue-- return entity_pairing_list-- def get_principal_entity_list( self, entity : Entity ) -> List[ Entity ]:- entity_state_delegation_list = list(- entity.entity_state_delegations.select_related('entity_state', 'entity_state__entity').all()- )- principal_state_list = [ x.entity_state for x in entity_state_delegation_list ]- return list({ x.entity for x in principal_state_list }) # de-dupe-def set_entity_path( self,entity_id : int,location : Location,@@ -161,7 +126,6 @@ class EntityManager(Singleton):entity = entity,location_view = location_view,)-try:entity_view = EntityView.objects.get(entity = entity,@@ -172,7 +136,6 @@ class EntityManager(Singleton):entity = entity,location_view = location_view,)-return entity_viewdef remove_entity_view( self, entity : Entity, location_view : LocationView ):@@ -183,7 +146,6 @@ class EntityManager(Singleton):location_view = location_view,)entity_view.delete()-returndef add_entity_to_view( self, entity : Entity, location_view : LocationView ):@@ -191,11 +153,11 @@ class EntityManager(Singleton):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(+ delegate_entity_list = EntityPairingManager().get_delegate_entities_with_defaults(entity = entity,)else:- delegate_entity_list = DelegationManager().get_delegate_entities(+ delegate_entity_list = EntityPairingManager().get_delegate_entities(entity = entity,)@@ -203,14 +165,12 @@ class EntityManager(Singleton):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-returndef toggle_entity_in_view( self, entity : Entity, location_view : LocationView ) -> bool:@@ -229,12 +189,10 @@ class EntityManager(Singleton):entity = entity,location_view = location_view,)-- DelegationManager().remove_delegate_entities_from_view_if_needed(+ EntityPairingManager().remove_delegate_entities_from_view_if_needed(entity = entity,location_view = location_view,)-returndef add_entity_position_if_needed( self,@@ -291,28 +249,19 @@ class EntityManager(Singleton):def create_location_entity_view_group_list( self, location_view : LocationView ) -> List[EntityViewGroup]:existing_entities = [ x.entityfor x in location_view.entity_views.select_related('entity').all() ]+ all_entities = Entity.objects.all()return self.create_entity_view_group_list(existing_entities = existing_entities,- exclude_delegates = False,- )-- def create_principal_entity_view_group_list( self, entity : Entity ) -> List[EntityViewGroup]:- existing_entities = self.get_principal_entity_list( entity = entity )- return self.create_entity_view_group_list(- existing_entities = existing_entities,- exclude_delegates = True, # Do not allow delegates to delegate+ all_entities = all_entities,)def create_entity_view_group_list( self,- existing_entities : List[ Entity ],- exclude_delegates : bool ) -> List[EntityViewGroup]:+ existing_entities : List[ Entity ],+ all_entities : Sequence[ Entity ] ) -> List[EntityViewGroup]:existing_entity_set = set( existing_entities )- entity_queryset = Entity.objects.all()entity_view_group_dict = dict()- for entity in entity_queryset:- if exclude_delegates and entity.entity_state_delegations.exists():- continue+ for entity in all_entities:entity_view_item = EntityViewItem(entity = entity,exists_in_view = bool( entity in existing_entity_set ),@@ -333,36 +282,6 @@ class EntityManager(Singleton):entity_view_group_list = list( entity_view_group_dict.values() )entity_view_group_list.sort( key = lambda item : item.entity_group_type.label )return entity_view_group_list-- def adjust_principal_entities( self, entity : Entity, desired_principal_entity_ids : Set[ int ] ):-- principal_entity_list = self.get_principal_entity_list( entity = entity )- previous_principal_entity_map = { x.id: x for x in principal_entity_list }- previous_principal_entity_ids = set( previous_principal_entity_map.keys() )-- to_add_entity_ids = desired_principal_entity_ids - previous_principal_entity_ids- to_delete_entity_ids = previous_principal_entity_ids - desired_principal_entity_ids-- to_add_principal_entities = list( Entity.objects.filter( id__in = list(to_add_entity_ids) ) )-- with transaction.atomic():- for add_principal_entity in to_add_principal_entities:- for entity_state in add_principal_entity.states.all():- EntityStateDelegation.objects.create(- entity_state = entity_state,- delegate_entity = entity,- )- continue- continue-- delegation_queryset = entity.entity_state_delegations.select_related(- 'entity_state',- 'entity_state__entity' ).all()- for delegation in delegation_queryset:- if delegation.entity_state.entity.id in to_delete_entity_ids:- delegation.delete()- continue- returndef get_view_stream_entities(self) -> List[ Entity ]:""" Return all entities that have a video stream state """diff --git a/src/hi/apps/entity/delegation_manager.py b/src/hi/apps/entity/entity_pairing_manager.pysimilarity index 54%rename from src/hi/apps/entity/delegation_manager.pyrename to src/hi/apps/entity/entity_pairing_manager.pyindex 3aa8acc4..414da699 100644--- a/src/hi/apps/entity/delegation_manager.py+++ b/src/hi/apps/entity/entity_pairing_manager.py@@ -1,13 +1,20 @@-from typing import List+from typing import List, Set++from django.db import transactionfrom hi.apps.common.singleton import Singletonfrom hi.apps.location.models import LocationViewfrom . import enumsfrom . import models+from .transient_models import EntityPairing++class EntityPairingError(Exception):+ pass-class DelegationManager(Singleton):++class EntityPairingManager(Singleton):CREATE_BY_DEFAULT_MAP = {# Defines which EntityStateType should have a delegate entity by@@ -24,24 +31,66 @@ class DelegationManager(Singleton):def __init_singleton__(self):return+ def get_entity_pairing_list( self, entity : models.Entity ) -> List[ EntityPairing ]:+ entity_pairing_list = list()++ for principal_entity in self.get_principal_entities( entity = entity ):+ entity_pairing = EntityPairing(+ entity = entity,+ paired_entity = principal_entity,+ pairing_type = enums.EntityPairingType.PRINCIPAL,+ )+ entity_pairing_list.append( entity_pairing )+ continue++ for delegate_entity in self.get_delegate_entities( entity = entity ):+ entity_pairing = EntityPairing(+ entity = entity,+ paired_entity = delegate_entity,+ pairing_type = enums.EntityPairingType.DELEGATE,+ )+ entity_pairing_list.append( entity_pairing )+ continue++ return entity_pairing_list++ def get_candidate_entities( self, entity : models.Entity ) -> List[ EntityPairing ]:+ """ We only allow pairing entities with states to those without states. """+ entity_has_states = bool( entity.states.exists() )++ candidate_entity_list = list()+ for candidate_entity in models.Entity.objects.all():+ candidate_entity_has_states = bool( candidate_entity.states.exists() )++ if (( entity_has_states and not candidate_entity_has_states )+ or ( not entity_has_states and candidate_entity_has_states )):+ candidate_entity_list.append( candidate_entity )++ continue+ return candidate_entity_list+def get_delegate_entities( self, entity : models.Entity ) -> List[ models.Entity ]:- delegate_entity_list = list()+ delegate_entity_set = set()for entity_state in entity.states.all():for entity_state_delegation in entity_state.entity_state_delegations.all():- delegate_entity_list.append( entity_state_delegation.delegate_entity )+ delegate_entity_set.add( entity_state_delegation.delegate_entity )continuecontinue+ delegate_entity_list = list( delegate_entity_set )+ delegate_entity_list.sort( key = lambda entity : entity.name )return delegate_entity_listdef get_principal_entities( self, entity : models.Entity ) -> List[ models.Entity ]:- principal_entity_list = list()+ principal_entity_set = set()delegation_queryset = entity.entity_state_delegations.select_related('entity_state','entity_state__entity').all()for entity_state_delegation in delegation_queryset:- principal_entity_list.append( entity_state_delegation.entity_state.entity )+ principal_entity_set.add( entity_state_delegation.entity_state.entity )continue+ principal_entity_list = list( principal_entity_set )+ principal_entity_list.sort( key = lambda entity : entity.name )return principal_entity_listdef get_delegate_entities_with_defaults( self, entity : models.Entity ) -> List[ models.Entity ]:@@ -138,3 +187,59 @@ class DelegationManager(Singleton):continuereturn++ def adjust_entity_pairings( self, entity : models.Entity, desired_paired_entity_ids : Set[ int ] ):++ previous_entity_pairings = self.get_entity_pairing_list( entity = entity )+ previous_paired_entity_ids = { x.paired_entity.id for x in previous_entity_pairings }++ to_add_entity_ids = desired_paired_entity_ids - previous_paired_entity_ids+ to_delete_entity_ids = previous_paired_entity_ids - desired_paired_entity_ids++ entity_has_states = bool( entity.states.exists() )+ to_add_paired_entities = list( models.Entity.objects.filter( id__in = list(to_add_entity_ids) ) )++ for candidate_entity in to_add_paired_entities:+ candidate_entity_has_states = bool( candidate_entity.states.exists() )++ if entity_has_states and candidate_entity_has_states:+ raise EntityPairingError(+ f'Cannot pair entities both with states: {entity} and {candidate_entity}' )+ if not entity_has_states and not candidate_entity_has_states:+ raise EntityPairingError(+ f'Cannot pair entities both without states: {entity} and {candidate_entity}' )+ continue++ with transaction.atomic():+ for to_add_entity in to_add_paired_entities:+ if entity_has_states:+ principle_entity = entity+ delegate_entity = to_add_entity+ else:+ principle_entity = to_add_entity+ delegate_entity = entity++ for entity_state in principle_entity.states.all():+ models.EntityStateDelegation.objects.create(+ entity_state = entity_state,+ delegate_entity = delegate_entity,+ )+ continue+ continue++ for to_delete_entity in to_delete_entity_ids:+ if entity_has_states:+ principle_entity = entity+ delegate_entity = to_add_entity+ else:+ principle_entity = to_add_entity+ delegate_entity = entity++ delegation_queryset = delegate_entity.entity_state_delegations.select_related(+ 'entity_state',+ 'entity_state__entity' ).all()+ for delegation in delegation_queryset:+ if delegation.entity_state.entity == principle_entity:+ delegation.delete()+ continue+ returndiff --git a/src/hi/apps/entity/templates/entity/edit/modals/manage_pairings.html b/src/hi/apps/entity/templates/entity/edit/modals/manage_pairings.htmlnew file mode 100644index 00000000..92b42d04--- /dev/null+++ b/src/hi/apps/entity/templates/entity/edit/modals/manage_pairings.html@@ -0,0 +1,57 @@+{% extends "modals/action_with_cancel.html" %}++{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}++{% block preamble %}+<form action="{% url 'entity_edit_manage_pairings' entity_id=entity.id %}" method="post"+ class="form" data-async="true">+ {% csrf_token %}+{% endblock %}++ {% block title_text %}+ Manage Item Pairings+ {% endblock %}++ {% block body %}+ <div>+ {% if entity.states.exists %}+ Select "delegate" items to pair whose status will determined by+ {% else %}+ Select "principal" items to pair whose status will be reflected by:+ {% endif %}+ <div class="mt-1 ml-4">+ <span class="h6">{{ entity.name }}</span>+ </div>+ </div>++ {% for entity_view_group in entity_view_group_list %}+ <div class="mt-2">+ <div class="h5">{{ entity_view_group.entity_group_type.label }}</div>+ <div class="row">+ {% for entity_view_item in entity_view_group.item_list %}+ <div class="col-6">+ <input type="checkbox"+ id="principal-entity-checkbox-{{ entity_view_item.entity.id }}"+ name="{{ principal_entity_id_name_prefix }}{{ entity_view_item.entity.id }}"+ {% if entity_view_item.exists_in_view %}checked{% endif %} >+ <label for="principal-entity-checkbox-{{ entity_view_item.entity.id }}">{{ entity_view_item.entity.name }}</label>+ </div>+ {% endfor %}+ </div>+ </div>+ {% empty %}+ <div><em>No candidate items found.</em></div>+ {% endfor %}++ {% endblock %}++ {% block action_right %}+ <button id="hi-principal-manage-button" type="submit" class="btn btn-lg btn-success"+ name="action" value="submit">+ SUBMIT+ </button>+ {% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/apps/entity/templates/entity/edit/modals/principal_manage.html b/src/hi/apps/entity/templates/entity/edit/modals/principal_manage.htmldeleted file mode 100644index bdd56a00..00000000--- a/src/hi/apps/entity/templates/entity/edit/modals/principal_manage.html+++ /dev/null@@ -1,46 +0,0 @@-{% extends "modals/action_with_cancel.html" %}--{% block preamble %}-<form action="{% url 'entity_edit_principal_manage' entity_id=entity.id %}" method="post"- class="form" data-async="true">- {% csrf_token %}-{% endblock %}--{% block title_text %}-Principal Add-{% endblock %}--{% block body %}-<div>- Select entities to add as principals.-</div>--{% for entity_view_group in entity_view_group_list %}-<div class="">- <div class="h5">{{ entity_view_group.entity_group_type.label }}</div>- {% for entity_view_item in entity_view_group.item_list %}- <div>- <input type="checkbox"- id="principal-entity-checkbox-{{ entity_view_item.entity.id }}"- name="{{ principal_entity_id_name_prefix }}{{ entity_view_item.entity.id }}"- {% if entity_view_item.exists_in_view %}checked{% endif %} >- <label for="principal-entity-checkbox-{{ entity_view_item.entity.id }}">{{ entity_view_item.entity.name }}</label>- </div>- {% endfor %}-</div>-{% empty %}-<div><em>No entities defined.</em></div>-{% endfor %}--{% endblock %}--{% block action_right %}-<button id="hi-principal-manage-button" type="submit" class="btn btn-lg btn-success"- name="action" value="submit">- SUBMIT-</button>-{% endblock %}--{% block postamble %}-</form>-{% endblock %}diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_details.htmlindex 568b0f16..5383cc08 100644--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html@@ -43,7 +43,7 @@</ul><div class="">- <a href="{% url 'entity_edit_principal_manage' entity_id=entity.id %}"+ <a href="{% url 'entity_edit_manage_pairings' entity_id=entity.id %}"class="btn btn-primary btn-control" role="button" data-async="true">MANAGE PAIRINGS</a>diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pyindex fda961d5..58f34f6a 100644--- a/src/hi/apps/entity/transient_models.py+++ b/src/hi/apps/entity/transient_models.py@@ -31,7 +31,15 @@ class EntityViewGroup:@dataclassclass EntityPairing:-+ """+ An "Entity Pair: abstracts the concepts of principal and delegate+ entities to a simpler, non-directional view for end users. We only+ allow an entity to participate as a principal or a delegate, not+ both. Further, We only allow a primcipal entity to delegate if it has+ EntityStates and we do not allow delegates to have their own+ state. Thus, by just pairing two entities, we can deduce which+ direction the delagation relatiojnship goes.+ """entity : Entitypaired_entity : Entitypairing_type : EntityPairingType@@ -84,13 +92,11 @@ class EntityDetailsData:entity_edit_data : EntityEditDataentity_position_form : EntityPositionForm = Noneentity_pairing_list : List[ EntityPairing ] = None- principal_entity_list : List[ Entity ] = Nonedef to_template_context(self):context = {'entity_position_form': self.entity_position_form,'entity_pairing_list': self.entity_pairing_list,- 'principal_entity_list': self.principal_entity_list,}context.update( self.entity_edit_data.to_template_context() )return contextdiff --git a/src/hi/static/js/svg-location.js b/src/hi/static/js/svg-location.jsindex 427b62f0..98a57998 100644--- a/src/hi/static/js/svg-location.js+++ b/src/hi/static/js/svg-location.js@@ -529,16 +529,17 @@return;}- /* We decided that automatically saving the location view geometry- after all move/scale/rotate operations was more inconvenient- than helpful. While editing, it is often useful to manipulate- the location view geometry while editing and arranging the- entities. If these entity refinements happen after the the- desired geometry has been set, then the act of editing those- entities and manipulating the location view will result in- undoing the original geometry work. Further, the user only finds- this out after they exit editing mode and see that it has- changed. Thus, we changed to require an explicit the location+ /* We only save the current location view geometry on a change if+ the Location View editing pane is showing. automatically saving+ the geometry after all move/scale/rotate operations is more+ inconvenient than helpful. While editing, it is often useful to+ manipulate the location view geometry while editing and+ arranging the entities. If these entity refinements happen+ after the the desired geometry has been set, then the act of+ editing those entities and manipulating the location view will+ result in undoing the original geometry work. Further, the user+ only finds this out after they exit editing mode and see that it+ has changed. Thus, we changed to require an explicit the locationediting view pane to be visible.*/