import structlog from vbv_lernwelt.core.models import User from vbv_lernwelt.course.consts import ( COURSE_UK, COURSE_UK_FR, COURSE_UK_IT, VV_COURSE_IDS, ) 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: 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]) ) return create_or_sync_learning_mentor(berufsbildner, new_members) def create_or_sync_ausbildungsverantwortlicher( ausbildungsverantwortlicher: User, ) -> bool: new_members = set( CourseSessionUser.objects.filter( user__organisation=ausbildungsverantwortlicher.organisation ) .filter(course_session__course__configuration__is_uk=False) .filter(role=CourseSessionUser.Role.MEMBER.value) .filter(course_session__course_id__in=VV_COURSE_IDS) ) return create_or_sync_learning_mentor(ausbildungsverantwortlicher, new_members) def create_or_sync_learning_mentor( agent: User, new_members: set[CourseSessionUser] ) -> bool: logger.info( "Creating or syncing berufsbildner", berufsbildner=agent, org=agent.organisation.name_de, ) # check if it is a valid organisation if agent.organisation and agent.organisation.organisation_id < 4: logger.error("Invalid organisation", org=agent.organisation) return False # get existing connections existing_members = set(agent.agentparticipantrelation_set.all()) # 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=agent, 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