From 1e4ddd2b9cdd3cebd046fe780df6610c1ddd280c Mon Sep 17 00:00:00 2001 From: rngsurrounded Date: Mon, 3 Mar 2025 17:11:00 +0900 Subject: [PATCH 1/6] work test --- .../src/pages/CompetitionSession/index.tsx | 3 - .../components/SolutionHistorySheet/index.tsx | 1 + .../modules/TaskSolution/index.tsx | 56 +++++++++++-------- 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/services/frontend/src/pages/CompetitionSession/index.tsx b/services/frontend/src/pages/CompetitionSession/index.tsx index 4d0c5f8..5c8e7c1 100644 --- a/services/frontend/src/pages/CompetitionSession/index.tsx +++ b/services/frontend/src/pages/CompetitionSession/index.tsx @@ -44,9 +44,6 @@ const CompetitionSession = () => { queryClient.invalidateQueries({ queryKey: ['solutionHistory', competitionId, taskId] }); - - setAnswer(""); - setSelectedFile(null); }, onError: (error) => { console.error("Error submitting solution:", error); diff --git a/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/components/SolutionHistorySheet/index.tsx b/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/components/SolutionHistorySheet/index.tsx index 3f181bd..83d8cda 100644 --- a/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/components/SolutionHistorySheet/index.tsx +++ b/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/components/SolutionHistorySheet/index.tsx @@ -22,6 +22,7 @@ const SolutionHistorySheet: React.FC = ({ onSolutionSelect, currentSolutionId }) => { + return ( diff --git a/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx b/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx index 20fdda1..a463cde 100644 --- a/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx +++ b/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx @@ -32,7 +32,7 @@ const TaskSolution: React.FC = ({ const [selectedSolutionUrl, setSelectedSolutionUrl] = useState(null); const [currentSolution, setCurrentSolution] = useState(null); const { id: competitionId } = useParams<{ id: string }>(); - const previousTaskIdRef = useRef(null); + const taskIdRef = useRef(null); const solutionsQuery = useQuery({ queryKey: ['solutionHistory', competitionId, task.id], @@ -40,37 +40,42 @@ const TaskSolution: React.FC = ({ enabled: !!(competitionId && task.id), }); + // Get the solution history - already sorted from oldest to newest const solutionHistory = solutionsQuery.data || []; - + + // Handle task changes useEffect(() => { - if (solutionHistory.length > 0 && !currentSolution) { - setCurrentSolution(solutionHistory[solutionHistory.length - 1]); - } - }, [solutionHistory, currentSolution]); - - useEffect(() => { - if (solutionHistory.length > 0 && currentSolution && - solutionHistory[0].id !== currentSolution.id) { - setCurrentSolution(solutionHistory[solutionHistory.length - 1]); - } - }, [solutionHistory, currentSolution]); - - useEffect(() => { - if (previousTaskIdRef.current !== task.id) { + // If task changed, reset everything and load the latest solution + if (taskIdRef.current !== task.id) { setCurrentSolution(null); setSelectedSolutionUrl(null); - setAnswer(""); setSelectedFile(null); + taskIdRef.current = task.id; - if (solutionHistory.length > 0 && !solutionsQuery.isLoading) { - setCurrentSolution(solutionHistory[solutionHistory.length - 1]); + // Wait for the query to complete + if (!solutionsQuery.isLoading && solutionHistory.length > 0) { + // Get the most recent solution (last in the array) + const latestSolution = solutionHistory[solutionHistory.length - 1]; + setCurrentSolution(latestSolution); } - - previousTaskIdRef.current = task.id; } }, [task.id, solutionHistory, solutionsQuery.isLoading, setAnswer, setSelectedFile]); + // Refresh current solution when the solution history changes (after a new submission) + useEffect(() => { + if (!solutionsQuery.isLoading && solutionHistory.length > 0) { + // If we don't have a current solution or there's a new submission + // (which would be the last item in the array) + if (!currentSolution || + currentSolution.id !== solutionHistory[solutionHistory.length - 1].id) { + // Set to the latest solution (last in the array) + setCurrentSolution(solutionHistory[solutionHistory.length - 1]); + } + } + }, [solutionHistory, currentSolution, solutionsQuery.isLoading]); + + // Load solution content when current solution changes useEffect(() => { const loadSolutionContent = async () => { if (!currentSolution || !currentSolution.content) return; @@ -108,6 +113,13 @@ const TaskSolution: React.FC = ({ setSelectedSolutionUrl(null); }; + const handleSubmitWrapper = () => { + onSubmit(); + setAnswer(""); + setSelectedFile(null); + setSelectedSolutionUrl(null); + }; + return (
{currentSolution ? ( @@ -143,7 +155,7 @@ const TaskSolution: React.FC = ({ )} From 8f7111a99869469225b479dda77189e6c8541bec Mon Sep 17 00:00:00 2001 From: Timur Date: Mon, 3 Mar 2025 11:15:20 +0300 Subject: [PATCH 2/6] add missing verbose names to admin --- services/backend/apps/task/models.py | 28 ++++++++++++++++++++-------- services/backend/apps/user/models.py | 2 +- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/services/backend/apps/task/models.py b/services/backend/apps/task/models.py index 0c77556..a5e725b 100644 --- a/services/backend/apps/task/models.py +++ b/services/backend/apps/task/models.py @@ -19,11 +19,15 @@ class CompetitionTask(BaseModel): def answer_file_upload_to(instance, filename) -> str: return f"tasks/{instance.id}/answer/{uuid4()}/{filename}" - in_competition_position = models.PositiveSmallIntegerField() - competition = models.ForeignKey(Competition, on_delete=models.CASCADE) + in_competition_position = models.PositiveSmallIntegerField( + verbose_name="позиция в соревновании" + ) + competition = models.ForeignKey(Competition, on_delete=models.CASCADE, + verbose_name="привязанное соревнование") title = models.CharField(verbose_name="заголовок", max_length=50) description = MartorField(verbose_name="описание") - max_attempts = models.PositiveSmallIntegerField(null=True, blank=True) + max_attempts = models.PositiveSmallIntegerField(null=True, blank=True, + verbose_name="максимальное кол-во попыток") type = models.CharField( choices=CompetitionTaskType, max_length=8, verbose_name="тип проверки" ) @@ -56,7 +60,7 @@ class CompetitionTask(BaseModel): help_text="Справа отображаются действующие проверяющие, слева - доступные для выбора. Для перемещения можно кликнуть 2 раза по проверяющему", ) submission_reviewers_count = models.PositiveSmallIntegerField( - default=1, null=True, blank=True + default=1, null=True, blank=True, verbose_name="кол-во проверяющих для зачета задачи" ) def __str__(self): @@ -72,10 +76,18 @@ class CompetitionTaskCriteria(BaseModel): CompetitionTask, on_delete=models.CASCADE, related_name="criteries" ) - name = models.TextField() - slug = models.SlugField() - description = models.TextField() - max_value = models.PositiveSmallIntegerField() + name = models.TextField( + verbose_name="название" + ) + slug = models.SlugField( + verbose_name="техническое название" + ) + description = models.TextField( + verbose_name="описание критерии" + ) + max_value = models.PositiveSmallIntegerField( + verbose_name="максимальное кол-во баллов" + ) class CompetitionTaskAttachment(BaseModel): diff --git a/services/backend/apps/user/models.py b/services/backend/apps/user/models.py index aaa0ec0..c1df2f1 100644 --- a/services/backend/apps/user/models.py +++ b/services/backend/apps/user/models.py @@ -15,7 +15,7 @@ class User(BaseModel): username = models.SlugField(unique=True, verbose_name="юзернейм") password = models.TextField(verbose_name="пароль") - created_at = models.DateTimeField(auto_now=True) + created_at = models.DateTimeField(auto_now=True, verbose_name="дата создания") achievements = models.ManyToManyField( Achievement, blank=True, verbose_name="ачивки пользователя" From 8064eb9cbaa893720c7050fd07b29d4b2785e052 Mon Sep 17 00:00:00 2001 From: Timur Date: Mon, 3 Mar 2025 11:21:53 +0300 Subject: [PATCH 3/6] add verbose names to user roles and user status --- services/backend/apps/user/models.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/backend/apps/user/models.py b/services/backend/apps/user/models.py index c1df2f1..598abb6 100644 --- a/services/backend/apps/user/models.py +++ b/services/backend/apps/user/models.py @@ -5,9 +5,9 @@ from apps.achievement.models import Achievement from apps.core.models import BaseModel -class UserRole(models.Choices): - STUDENT = "student" - METODIST = "metodist" +class UserRole(models.TextChoices): + STUDENT = "student", "Участник соревнований" + METODIST = "metodist", "Методист (составитель заданий)" class User(BaseModel): @@ -29,7 +29,8 @@ class User(BaseModel): return check_password(self.password, password) status = models.CharField( - max_length=10, choices=UserRole, default="student" + max_length=10, choices=UserRole.choices, default="student", + verbose_name="роль участника" ) def __str__(self) -> str: From c06cd72627c319c1086700e9feb87b1a74a128b4 Mon Sep 17 00:00:00 2001 From: Timur Date: Mon, 3 Mar 2025 11:31:15 +0300 Subject: [PATCH 4/6] change markdown editor in admin (now I use https://github.com/pylixm/django-mdeditor) --- services/backend/apps/task/admin.py | 8 +++++++- services/backend/apps/task/models.py | 10 +++++++++- services/backend/config/settings.py | 3 +++ services/backend/config/urls.py | 2 ++ services/backend/pyproject.toml | 1 + 5 files changed, 22 insertions(+), 2 deletions(-) diff --git a/services/backend/apps/task/admin.py b/services/backend/apps/task/admin.py index 7b6fbfa..10f3c67 100644 --- a/services/backend/apps/task/admin.py +++ b/services/backend/apps/task/admin.py @@ -4,6 +4,7 @@ from apps.task.models import ( CompetitionTask, CompetitionTaskAttachment, CompetitionTaskSubmission, + CompetitionTaskCriteria ) @@ -12,12 +13,17 @@ class CompletionAttachmentInline(admin.StackedInline): extra = 0 +class CompetitionCriteriaInline(admin.StackedInline): + model = CompetitionTaskCriteria + extra = 0 + + @admin.register(CompetitionTask) class CompetitionTaskAdmin(admin.ModelAdmin): list_display = ("title", "type", "points") filter_horizontal = ("reviewers",) list_filter = ("type",) - inlines = (CompletionAttachmentInline,) + inlines = (CompletionAttachmentInline, CompetitionCriteriaInline,) @admin.register(CompetitionTaskSubmission) diff --git a/services/backend/apps/task/models.py b/services/backend/apps/task/models.py index a5e725b..9947fb3 100644 --- a/services/backend/apps/task/models.py +++ b/services/backend/apps/task/models.py @@ -3,6 +3,7 @@ from uuid import uuid4 from django.db import models from django.db.models import Count, Q from martor.models import MartorField +from mdeditor.fields import MDTextField from apps.competition.models import Competition from apps.core.models import BaseModel @@ -25,7 +26,7 @@ class CompetitionTask(BaseModel): competition = models.ForeignKey(Competition, on_delete=models.CASCADE, verbose_name="привязанное соревнование") title = models.CharField(verbose_name="заголовок", max_length=50) - description = MartorField(verbose_name="описание") + description = MDTextField(verbose_name="описание") max_attempts = models.PositiveSmallIntegerField(null=True, blank=True, verbose_name="максимальное кол-во попыток") type = models.CharField( @@ -89,6 +90,13 @@ class CompetitionTaskCriteria(BaseModel): verbose_name="максимальное кол-во баллов" ) + def __str__(self): + return self.name + + class Meta: + verbose_name = "критерий" + verbose_name_plural = "критерии" + class CompetitionTaskAttachment(BaseModel): def file_upload_at(instance, filename) -> str: diff --git a/services/backend/config/settings.py b/services/backend/config/settings.py index 3987361..da2215b 100644 --- a/services/backend/config/settings.py +++ b/services/backend/config/settings.py @@ -271,6 +271,8 @@ DEFAULT_CHARSET = "utf-8" FORCE_SCRIPT_NAME = None +X_FRAME_OPTIONS = "SAMEORIGIN" + INTERNAL_IPS = env( "DJANGO_INTERNAL_IPS", list, @@ -440,6 +442,7 @@ INSTALLED_APPS = [ "minio_storage", "tinymce", "martor", + "mdeditor", # Internal apps "apps.core", "apps.user", diff --git a/services/backend/config/urls.py b/services/backend/config/urls.py index 6fe96c2..0fb5044 100644 --- a/services/backend/config/urls.py +++ b/services/backend/config/urls.py @@ -16,6 +16,8 @@ urlpatterns = [ path("tinymce/", include("tinymce.urls")), # martor path("martor/", include("martor.urls")), + # mdeditor + path(r'mdeditor/', include('mdeditor.urls')), # Admin urls path("admin/", admin.site.urls), # API urls diff --git a/services/backend/pyproject.toml b/services/backend/pyproject.toml index d3b2371..bb39e9e 100644 --- a/services/backend/pyproject.toml +++ b/services/backend/pyproject.toml @@ -12,6 +12,7 @@ dependencies = [ "django-extensions>=3.2.3", "django-guid>=3.5.0", "django-health-check>=3.18.3", + "django-mdeditor>=0.1.20", "django-minio-storage>=0.5.7", "django-ninja>=1.3.0", "django-pagedown>=2.2.1", From e8311d7c14117749d9b994241ecf83ac9d40873e Mon Sep 17 00:00:00 2001 From: Timur Date: Mon, 3 Mar 2025 11:32:10 +0300 Subject: [PATCH 5/6] remove old markdown editors --- services/backend/apps/task/models.py | 1 - services/backend/config/settings.py | 61 ---------------------------- services/backend/pyproject.toml | 2 - 3 files changed, 64 deletions(-) diff --git a/services/backend/apps/task/models.py b/services/backend/apps/task/models.py index 9947fb3..ef0016d 100644 --- a/services/backend/apps/task/models.py +++ b/services/backend/apps/task/models.py @@ -2,7 +2,6 @@ from uuid import uuid4 from django.db import models from django.db.models import Count, Q -from martor.models import MartorField from mdeditor.fields import MDTextField from apps.competition.models import Competition diff --git a/services/backend/config/settings.py b/services/backend/config/settings.py index da2215b..cb0d18e 100644 --- a/services/backend/config/settings.py +++ b/services/backend/config/settings.py @@ -440,8 +440,6 @@ INSTALLED_APPS = [ "django_guid", "ninja", "minio_storage", - "tinymce", - "martor", "mdeditor", # Internal apps "apps.core", @@ -453,65 +451,6 @@ INSTALLED_APPS = [ "apps.achievement", ] -# tinymce -TINYMCE_DEFAULT_CONFIG = { - "theme": "silver", - "height": 500, - "menubar": False, - "plugins": "advlist,autolink,lists,link,image,charmap,print,preview,anchor," - "searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste," - "code,help,wordcount,markdown", - "toolbar": "undo redo | formatselect | " - "bold italic backcolor | alignleft aligncenter " - "alignright alignjustify | bullist numlist outdent indent | " - "removeformat | help", - "skin": "oxide-dark", - "content_css": "dark", - "textpattern_patterns": [ - {"start": "*", "end": "*", "format": "italic"}, - {"start": "**", "end": "**", "format": "bold"}, - {"start": "#", "format": "h1"}, - {"start": "##", "format": "h2"}, - {"start": "###", "format": "h3"}, - {"start": "####", "format": "h4"}, - {"start": "#####", "format": "h5"}, - {"start": "######", "format": "h6"}, - {"start": "1. ", "cmd": "InsertOrderedList"}, - {"start": "* ", "cmd": "InsertUnorderedList"}, - {"start": "- ", "cmd": "InsertUnorderedList"}, - ], -} - -# martor - -MARTOR_THEME = "bootstrap" - -MARTOR_ENABLE_CONFIGS = { - "emoji": "true", # to enable/disable emoji icons. - "imgur": "true", # to enable/disable imgur/custom uploader. - "mention": "false", # to enable/disable mention - "jquery": "true", # to include/revoke jquery (require for admin default django) - "living": "false", # to enable/disable live updates in preview - "spellcheck": "false", # to enable/disable spellcheck in form textareas - "hljs": "true", # to enable/disable hljs highlighting in preview -} - -MARTOR_TOOLBAR_BUTTONS = [ - "bold", - "italic", - "horizontal", - "heading", - "pre-code", - "blockquote", - "unordered-list", - "ordered-list", - "link", - "emoji", - "direct-mention", - "toggle-maximize", - "help", -] - # GUID DJANGO_GUID = { diff --git a/services/backend/pyproject.toml b/services/backend/pyproject.toml index bb39e9e..23fefd0 100644 --- a/services/backend/pyproject.toml +++ b/services/backend/pyproject.toml @@ -17,10 +17,8 @@ dependencies = [ "django-ninja>=1.3.0", "django-pagedown>=2.2.1", "django-stubs-ext>=5.1.3", - "django-tinymce>=4.1.0", "gunicorn>=23.0.0", "httpx>=0.28.1", - "martor>=1.6.45", "pillow>=11.1.0", "psycopg2-binary>=2.9.10", "pydantic>=2.10.5", From 889d49f95542b0515f9e4a69fd6a49d3b5b1b6ca Mon Sep 17 00:00:00 2001 From: rngsurrounded Date: Mon, 3 Mar 2025 17:36:54 +0900 Subject: [PATCH 6/6] input hotfix --- services/frontend/src/pages/CompetitionSession/index.tsx | 3 +++ .../pages/CompetitionSession/modules/TaskSolution/index.tsx | 6 ------ 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/services/frontend/src/pages/CompetitionSession/index.tsx b/services/frontend/src/pages/CompetitionSession/index.tsx index 5c8e7c1..4d0c5f8 100644 --- a/services/frontend/src/pages/CompetitionSession/index.tsx +++ b/services/frontend/src/pages/CompetitionSession/index.tsx @@ -44,6 +44,9 @@ const CompetitionSession = () => { queryClient.invalidateQueries({ queryKey: ['solutionHistory', competitionId, taskId] }); + + setAnswer(""); + setSelectedFile(null); }, onError: (error) => { console.error("Error submitting solution:", error); diff --git a/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx b/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx index a463cde..06cebdd 100644 --- a/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx +++ b/services/frontend/src/pages/CompetitionSession/modules/TaskSolution/index.tsx @@ -40,12 +40,9 @@ const TaskSolution: React.FC = ({ enabled: !!(competitionId && task.id), }); - // Get the solution history - already sorted from oldest to newest const solutionHistory = solutionsQuery.data || []; - // Handle task changes useEffect(() => { - // If task changed, reset everything and load the latest solution if (taskIdRef.current !== task.id) { setCurrentSolution(null); setSelectedSolutionUrl(null); @@ -115,9 +112,6 @@ const TaskSolution: React.FC = ({ const handleSubmitWrapper = () => { onSubmit(); - setAnswer(""); - setSelectedFile(null); - setSelectedSolutionUrl(null); }; return (