skillbox/server/books/schema/nodes/snapshot.py

94 lines
3.1 KiB
Python

import graphene
from django.db.models import Q
from graphene import relay, ObjectType
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from . import ChapterInSnapshotNode
from books.models.snapshot import Snapshot
from ..interfaces import ModuleInterface, ChapterInterface
from ..interfaces.contentblock import ContentBlockInterface
from ...models import Module, Chapter, ChapterSnapshot, ContentBlock
class SnapshotContentBlock:
def __init__(self, content_block, snapshot):
self.id = content_block.id
self.pk = content_block.pk
self.title = content_block.title
self.contents = content_block.title
self.type = content_block.type
self.hidden = snapshot.hidden_content_blocks.filter(id=content_block.id).exists()
class SnapshotChapter:
def __init__(self, chapter, snapshot, description_hidden=False, title_hidden=False):
self.id = chapter.id
self.pk = chapter.pk
self.title = chapter.title
self.description = chapter.description
self.title_hidden = title_hidden
self.description_hidden = description_hidden
self.content_blocks = []
base_qs = ContentBlock.get_by_parent(chapter)
without_owner = Q(owner__isnull=True)
this_snapshot = Q(contentblocksnapshot__snapshot=snapshot)
self.content_blocks = [
SnapshotContentBlock(
content_block=content_block,
snapshot=snapshot
) for content_block in
base_qs.filter(without_owner | this_snapshot)
]
# all from module without owner
# all with snapshotcontentblock with this snapshot
class SnapshotContentBlockNode(ObjectType):
class Meta:
interfaces = (ContentBlockInterface,)
hidden = graphene.Boolean()
class SnapshotChapterNode(ObjectType):
class Meta:
interfaces = (ChapterInterface,)
content_blocks = graphene.List(SnapshotContentBlockNode)
description_hidden = graphene.Boolean()
title_hidden = graphene.Boolean()
class SnapshotNode(DjangoObjectType):
title = graphene.String()
# chapters = graphene.Field(SnapshotChapterNode)
snapshot_chapters = DjangoFilterConnectionField(ChapterInSnapshotNode)
chapters = graphene.List(SnapshotChapterNode)
class Meta:
model = Snapshot
interfaces = (relay.Node,)
@staticmethod
def resolve_snapshot_chapters(parent, info, **kwargs):
# return Chapter.objects.filter(chapter_snapshots__snapshot=self)
return parent.chapters.through.objects.all()
@staticmethod
def resolve_chapters(parent, info, **kwargs):
return [
SnapshotChapter(
chapter_snapshot.chapter,
snapshot=parent,
title_hidden=chapter_snapshot.title_hidden,
description_hidden=chapter_snapshot.description_hidden
)
for chapter_snapshot in parent.chapters.through.objects.all()
]
@staticmethod
def resolve_title(parent, info, **kwargs):
return parent.__str__()