vbv/server/vbv_lernwelt/learning_mentor/services.py

55 lines
1.8 KiB
Python

import structlog
from vbv_lernwelt.core.models import User
from vbv_lernwelt.course.consts import COURSE_UK, COURSE_UK_FR, COURSE_UK_IT
from vbv_lernwelt.course.models import CourseSessionUser
from vbv_lernwelt.learning_mentor.models import (
AgentParticipantRelation,
AgentParticipantRoleType,
)
logger = structlog.get_logger(__name__)
UK_COURSES = [COURSE_UK, COURSE_UK_FR, COURSE_UK_IT]
def create_or_sync_berufsbildner(berufsbildner: User) -> bool:
logger.info(
"Creating or syncing berufsbildner",
berufsbildner=berufsbildner,
org=berufsbildner.organisation.name_de,
)
# check if it is a valid organisation
if berufsbildner.organisation and berufsbildner.organisation.organisation_id < 4:
logger.error("Invalid organisation", org=berufsbildner.organisation)
return False
# get existing connections
existing_members = set(berufsbildner.agentparticipantrelation_set.all())
# gather new relations
new_members = set(
CourseSessionUser.objects.filter(user__organisation=berufsbildner.organisation)
.filter(course_session__course__configuration__is_uk=True)
.filter(role=CourseSessionUser.Role.MEMBER.value)
.filter(course_session__course_id__in=UK_COURSES)
.exclude(course_session_id__in=[4, 5, 6])
)
# add new relations that are not in existing relations
for csu in new_members:
if csu not in existing_members:
AgentParticipantRelation.objects.get_or_create(
agent=berufsbildner,
participant=csu,
role=AgentParticipantRoleType.BERUFSBILDNER.value,
)
# remove old relations that are not in the new relations
for relation in existing_members:
if relation.participant not in new_members:
relation.delete()
return True