skillbox/server/books/models/snapshot.py

74 lines
2.7 KiB
Python

from django.db import models
from django.db.models import Q
from books.models import Chapter, ContentBlock, ContentBlockSnapshot
class ChapterSnapshot(models.Model):
"""
Captures the state of a chapter at the time when the snapshot was taken, for the school class that was selected
for the user creating the snapshot
"""
chapter = models.ForeignKey(
'books.Chapter',
related_name='chapter_snapshots',
on_delete=models.PROTECT
)
snapshot = models.ForeignKey(
'books.Snapshot',
related_name='chapter_snapshots',
on_delete=models.CASCADE
)
title_hidden = models.BooleanField(default=False)
description_hidden = models.BooleanField(default=False)
class SnapshotManager(models.Manager):
def create_snapshot(self, module, school_class, user, *args, **kwargs):
snapshot = self.create(module=module, *args, **kwargs)
chapters_with_hidden_properties = Chapter.get_by_parent(module).filter(
Q(description_hidden_for=school_class)
| Q(title_hidden_for=school_class)
)
for chapter in chapters_with_hidden_properties:
ChapterSnapshot.objects.create(
chapter=chapter,
snapshot=snapshot,
title_hidden=chapter.title_hidden_for.filter(id=school_class.id).exists(),
description_hidden=chapter.description_hidden_for.filter(id=school_class.id).exists()
)
base_qs = ContentBlock.get_by_parent(chapter).filter(contentblocksnapshot__isnull=True)
for content_block in base_qs.filter(user_created=False):
if content_block.hidden_for.filter(id=school_class.id).exists():
snapshot.hidden_content_blocks.add(content_block)
for content_block in base_qs.filter(Q(user_created=True) & Q(owner=user)):
new_content_block = ContentBlockSnapshot(
hidden=False,
snapshot=snapshot,
contents=content_block.contents,
type=content_block.type,
title=content_block.title
)
content_block.add_sibling(instance=new_content_block, pos='right')
revision = new_content_block.save_revision()
revision.publish()
new_content_block.save()
return snapshot
class Snapshot(models.Model):
module = models.ForeignKey(
'books.Module',
on_delete=models.PROTECT
)
chapters = models.ManyToManyField(
'books.Chapter',
through=ChapterSnapshot
)
hidden_content_blocks = models.ManyToManyField(
'books.ContentBlock',
related_name='hidden_for_snapshots'
)
objects = SnapshotManager()