from wagtail.models import Locale, Page from books.models.module import Module from books.models.topic import Topic from core.logger import get_logger logger = get_logger(__name__) class AlreadyTranslatedException(Exception): pass class ModuleDoesNotExistException(Exception): pass # todo: make this a django command # todo: add language to translate to as an argument # todo: write a test maybe def convert_page_to_translation(slug: str, original_slug: str, language_code="en"): """ Migrate a module and its children to a new locale and links it to its translation in the original locale. @param slug: the slug of the module to migrate @param original_slug: the slug of the module in the original locale """ try: module = Module.objects.get(slug=slug) original = Module.objects.get(slug=original_slug) if original.translation_key == module.translation_key: raise AlreadyTranslatedException except Module.DoesNotExist: raise ModuleDoesNotExistException locale, _ = Locale.objects.get_or_create(language_code=language_code) logger.debug("Starting conversion") topic: Topic = module.get_parent() try: logger.debug("Getting existing topic translation") translated_topic = topic.get_translation(locale) except Page.DoesNotExist: logger.debug("Creating topic translation") translated_topic = topic.copy_for_translation(locale) revision = translated_topic.latest_revision translated_topic.publish(revision) module.locale = locale if original is not None: translation_key = original.translation_key module.translation_key = translation_key module.save() chapters = module.get_children() for chapter in chapters: chapter.locale = locale chapter.save() content_blocks = chapter.get_children() for content_block in content_blocks: content_block.locale = locale content_block.save() module.move(translated_topic, "last-child") return f"Converted page {slug} to be the {language_code} translation of {original_slug}"