import graphene from graphene import relay from api.utils import get_object from books.models import Module, ContentBlock from books.models.snapshot import Snapshot from books.schema.nodes import SnapshotNode from users.models import SchoolClass class CreateSnapshot(relay.ClientIDMutation): class Input: module = graphene.String(required=True) selected_class = graphene.ID(required=True) snapshot = graphene.Field(SnapshotNode) success = graphene.Boolean() @classmethod def mutate_and_get_payload(cls, root, info, **args): module_slug = args.get('module') module = Module.objects.get(slug=module_slug) user = info.context.user # todo: check user # raise NotImplementedError('Permissions') selected_class_id = args.get('selected_class') selected_class = get_object(SchoolClass, selected_class_id) snapshot = Snapshot.objects.create_snapshot(module, selected_class, user) return cls(snapshot=snapshot, success=True) class ApplySnapshot(relay.ClientIDMutation): class Input: snapshot = graphene.ID(required=True) selected_class = graphene.ID(required=True) success = graphene.Boolean() @classmethod def mutate_and_get_payload(cls, root, info, **args): snapshot_id = args.get('snapshot') snapshot = get_object(Snapshot, snapshot_id) user = info.context.user selected_class_id = args.get('selected_class') selected_class = get_object(SchoolClass, selected_class_id) if not selected_class.users.filter(username=user.username).exists() or not user.is_teacher(): raise PermissionError('Not allowed') for content_block in snapshot.hidden_content_blocks.all(): content_block.hidden_for.add(selected_class) for custom_content_block in snapshot.custom_content_blocks.all(): custom_content_block.to_regular_content_block(user, selected_class) for chapter_snapshot in snapshot.chapters.through.objects.all(): chapter = chapter_snapshot.chapter if chapter_snapshot.title_hidden: chapter.title_hidden_for.add(selected_class) if chapter_snapshot.description_hidden: chapter.description_hidden_for.add(selected_class) return cls(success=True)