server/python/django2/renkanmanager/models.py
changeset 615 f3875fbe206a
parent 614 23416a833ca8
child 616 33fdb6f8164c
--- a/server/python/django2/renkanmanager/models.py	Wed Jun 15 16:31:43 2016 +0200
+++ b/server/python/django2/renkanmanager/models.py	Mon Jun 20 14:44:40 2016 +0200
@@ -25,9 +25,7 @@
 
     @property
     def renkan_count(self):
-        #TODO: check count and related objects
-        #return Renkan.objects.filter(workspace__workspace_guid=self.workspace_guid).count()
-        return Renkan.objects.filter(workspace_guid=self.workspace_guid).count()
+        return self.renkans.all().count()
 
     class Meta:
         app_label = 'renkanmanager'
@@ -42,8 +40,7 @@
     def create_renkan(self, creator, title='', content='', source_revision=None, workspace = None):
         new_renkan = Renkan()
         new_renkan.creator = creator
-        #TODO: !!! new_renkan_workspace_guid is not set on the new renkan ! only on the content !
-        new_renkan_workspace_guid = ""
+        new_renkan_workspace_guid = None
         new_renkan_title = title
         new_renkan_content = content
         if workspace is not None:
@@ -55,29 +52,30 @@
                 new_renkan_title = source_revision.title
             new_renkan_content = source_revision.content
         new_renkan.save()
+        creation_date =  timezone.now()
         initial_revision = Revision(parent_renkan=new_renkan)
-        initial_revision.modification_date = timezone.now()
+        initial_revision.title = new_renkan_title if new_renkan_title else "Untitled Renkan"
+        initial_revision.creation_date = creation_date
+        initial_revision.modification_date = creation_date
         initial_revision.creator = creator
         initial_revision.last_updated_by = creator
-        initial_revision.save() # saving once to set the creation date as we need it to fill the json content
-        if initial_revision.modification_date != initial_revision.creation_date:
-            initial_revision.modification_date = initial_revision.creation_date
-        initial_revision.title = new_renkan_title if new_renkan_title else "Untitled Renkan"
+        logger.debug("CREATE RENKAN NEW CONTENT %r", new_renkan_content)
         if new_renkan_content:
             new_renkan_content_dict = json.loads(new_renkan.validate_json_content(new_renkan_content))
-            new_renkan_content_dict["created"] = str(initial_revision.creation_date)
-            new_renkan_content_dict["updated"] = str(initial_revision.modification_date)
+            logger.debug("CREATE RENKAN NEW CONTENT AFTER VALIDATE %r", new_renkan_content_dict)
+            new_renkan_content_dict["created"] = str(creation_date)
+            new_renkan_content_dict["updated"] = str(creation_date)
         else:
             new_renkan_content_dict = {
                 "id": str(new_renkan.renkan_guid),
                 "title": initial_revision.title,
                 "description": "",
-                "created": str(initial_revision.creation_date),
-                "updated": str(initial_revision.modification_date),
+                "created": str(creation_date),
+                "updated": str(creation_date),
                 "edges": [],
                 "nodes": [],
                 "users": [],
-                "space_id": new_renkan_workspace_guid,
+                "space_id": str(new_renkan_workspace_guid),
                 "views": []
             }
         initial_revision.content = json.dumps(new_renkan_content_dict)
@@ -87,9 +85,9 @@
 class Renkan(models.Model):
 
     renkan_guid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False)
-    workspace_guid = models.CharField(max_length=256, blank=True, null=True)
-    current_revision_guid = models.CharField(max_length=256, blank=True, null=True)
-    source_revision_guid = models.CharField(max_length=256, blank=True, null=True)
+    workspace = models.ForeignKey('renkanmanager.Workspace', null=True, blank=True, on_delete=models.CASCADE, related_name="renkans")
+    current_revision = models.ForeignKey('renkanmanager.Revision', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')
+    source_revision = models.ForeignKey('renkanmanager.Revision', null=True, blank=True, on_delete=models.SET_NULL, related_name='copies')
 
     creator = models.ForeignKey(auth_user_model, blank=True, null=True, related_name="renkan_creator")
     creation_date = models.DateTimeField(auto_now_add=True)
@@ -99,44 +97,34 @@
 
     @property
     def revision_count(self):
-        #TODO: check related object count
-        return Revision.objects.filter(parent_renkan_guid=self.renkan_guid).count()
-        #return Revision.objects.filter(parent_renkan__renkan_guid=self.renkan_guid).count()
+        return self.revisions.all().count()
+
+    @property
+    def workspace_guid(self):
+        return self.workspace and self.workspace.workspace_guid
+
+    @property
+    def current_revision_guid(self):
+        return self.current_revision and self.current_revision.revision_guid
+
+    @property
+    def source_revision_guid(self):
+        return self.source_revision and self.source_revision.revision_guid
+
 
     @property
     def is_copy(self):
-        #return bool(self.source_revision)
-        return bool(self.source_revision_guid)
-
-    # Current revision object or None if there is none
-#    @property
-#    def current_revision(self):
-#        return Revision.objects.filter(parent_renkan__renkan_guid=self.renkan_guid).order_by('-creation_date').first()
+        return bool(self.source_revision)
 
     # Current revision title
     @property
     def title(self):
-        current_revision = Revision.objects.get(revision_guid = self.current_revision_guid)
-        return current_revision.title
-        #TODO: not good -> 2 requests
-        #if self.current_revision:
-        #    return self.current_revision.title
-        #else:
-        #    return ''
+        return self.current_revision and self.current_revision.title or ''
 
     # Current revision content
     @property
     def content(self):
-        #TODO: not good -> 2 requests
-        current_revision = Revision.objects.get(revision_guid = self.current_revision_guid)
-        return current_revision.content
-        #if self.current_revision:
-        #    return self.current_revision.content
-        #else:
-        #    return ''
-
-    def __unicode__(self):
-        return self.renkan_guid
+        return self.current_revision and self.current_revision.content or ''
 
     def __str__(self):
         return self.renkan_guid
@@ -152,12 +140,13 @@
             raise ValidationError(_("Cannot save, provided timestamp is invalid"))
         else:
             dt_timestamp = dateparse.parse_datetime(timestamp)
-        self.save()
+        logger.debug("SAVE RENKAN create new revision %r", create_new_revision)
+
         if create_new_revision:
             revision_to_update = Revision(parent_renkan=self)
             revision_to_update.creator = updator
         else:
-            revision_to_update = Revision.objects.select_for_update().get(revision_guid=self.current_revision.revision_guid)
+            revision_to_update = Revision.objects.select_for_update().get(id=self.current_revision.id)
 
         updated_content = self.validate_json_content(content) if content else current_revision.content
         updated_content_dict = json.loads(updated_content)
@@ -179,6 +168,7 @@
             revision_to_update.modification_date += datetime.resolution
         revision_to_update.last_updated_by = updator
         revision_to_update.save()
+        self.save()
 
     def validate_json_content(self, content):
         """
@@ -223,17 +213,6 @@
             raise ValidationError("Provided content has an invalid 'users' key: not a list")
         return json.dumps(content_to_validate_dict)
 
-    #TODO:
-    # @transaction.atomic
-    # def delete(self):
-    #     """
-    #         Deleting a renkan also deletes every related revision
-    #     """
-    #     renkan_revisions = Revision.objects.filter(parent_renkan__renkan_guid = self.renkan_guid)
-    #     for child_revision in renkan_revisions:
-    #         child_revision.delete()
-    #     super(Renkan, self).delete()
-
     class Meta:
         app_label = 'renkanmanager'
         permissions = (
@@ -244,28 +223,28 @@
 class Revision(models.Model):
 
     revision_guid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False)
-    parent_renkan_guid = models.CharField(max_length=256)
-    #parent_renkan = models.ForeignKey('Renkan', null=False, blank=False, to_field='renkan_guid')
+    parent_renkan = models.ForeignKey('renkanmanager.Renkan', on_delete=models.CASCADE, related_name="revisions")
     title = models.CharField(max_length=1024, null=True, blank=True)
     content = models.TextField(blank=True, null=True)
     creator = models.ForeignKey(auth_user_model, blank=True, null=True, related_name="revision_creator")
     last_updated_by = models.ForeignKey(auth_user_model, blank=True, null=True, related_name="revision_last_updated_by")
-    creation_date = models.DateTimeField(auto_now_add=True)
-    modification_date = models.DateTimeField(auto_now=True)
-    #modification_date = models.DateTimeField()
+    creation_date = models.DateTimeField(auto_now_add=True, editable=False)
+    modification_date = models.DateTimeField()
+
+    @property
+    def parent_renkan_guid(self):
+        return self.parent_renkan and self.parent_renkan.renkan_guid
 
     @property
     def is_current_revision(self):
-        try:
-            parent_project = Renkan.objects.get(renkan_guid=self.parent_renkan_guid)
-        except Renkan.DoesNotExist: # SHOULD NOT HAPPEN!
-            raise Http404
-        return parent_project.current_revision_guid == self.revision_guid
-        # No need to check if parent_renkan.current_revision is not None, as it won't be if we're calling from a revision
-        #return self.parent_renkan.current_revision.revision_guid == self.revision_guid
+        return self == self.parent_renkan.current_revision
 
     class Meta:
         app_label = 'renkanmanager'
+        ordering = ['-modification_date']
         permissions = (
             ('view_revision', 'Can view revision'),
         )
+
+    def __str__(self):
+        return str(self.revision_guid)