feat: Add new data-manager service for professor and module management and a new frontend application with i18n and a professor dashboard.

This commit is contained in:
Elmar Kresse
2025-11-22 20:20:00 +01:00
parent 48926233d5
commit 34ad90d50d
19 changed files with 769 additions and 68 deletions

View File

@@ -17,27 +17,31 @@
package main
import (
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
_ "htwkalender/data-manager/migrations"
"htwkalender/data-manager/model/serviceModel"
"htwkalender/data-manager/service"
"htwkalender/data-manager/service/events"
"htwkalender/data-manager/service/grpc"
"htwkalender/data-manager/service/professor"
"log/slog"
"os"
"strings"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
)
func setupApp() *pocketbase.PocketBase {
app := pocketbase.New()
courseService := events.NewPocketBaseCourseService(app)
eventService := events.NewPocketBaseEventService(app)
professorService := professor.NewProfessorService(app)
services := serviceModel.Service{
CourseService: courseService,
EventService: eventService,
App: app,
CourseService: courseService,
EventService: eventService,
ProfessorService: professorService,
App: app,
}
// loosely check if it was executed using "go run"

View File

@@ -0,0 +1,32 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("users")
if err != nil {
return err
}
// Enable OAuth2
collection.OAuth2.Enabled = true
// Optional: Map fields if necessary, for now just enabling it
// collection.OAuth2.MappedFields.Name = "name"
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("users")
if err != nil {
return err
}
collection.OAuth2.Enabled = false
return app.Save(collection)
})
}

View File

@@ -30,12 +30,13 @@ func (m *Module) SetName(name string) {
}
type ModuleDTO struct {
UUID string `json:"uuid" db:"uuid"`
Name string `json:"name" db:"Name"`
Prof string `json:"prof" db:"Prof"`
Course string `json:"course" db:"course"`
Semester string `json:"semester" db:"semester"`
EventType string `db:"EventType" json:"eventType"`
UUID string `json:"uuid" db:"uuid"`
Name string `json:"name" db:"Name"`
Prof string `json:"prof" db:"Prof"`
Course string `json:"course" db:"course"`
Semester string `json:"semester" db:"semester"`
EventType string `db:"EventType" json:"eventType"`
ConfidenceScore float64 `json:"confidenceScore,omitempty"`
}
func (m *ModuleDTO) GetName() string {

View File

@@ -1,12 +1,15 @@
package serviceModel
import (
"github.com/pocketbase/pocketbase"
"htwkalender/data-manager/service/events"
"htwkalender/data-manager/service/professor"
"github.com/pocketbase/pocketbase"
)
type Service struct {
App *pocketbase.PocketBase
EventService events.EventService
CourseService events.CourseService
App *pocketbase.PocketBase
EventService events.EventService
CourseService events.CourseService
ProfessorService *professor.ProfessorService
}

View File

@@ -23,6 +23,7 @@ import (
v1 "htwkalender/data-manager/service/fetch/v1"
v2 "htwkalender/data-manager/service/fetch/v2"
"htwkalender/data-manager/service/functions/time"
"htwkalender/data-manager/service/professor"
"htwkalender/data-manager/service/room"
"log/slog"
"net/http"
@@ -231,6 +232,7 @@ func AddRoutes(services serviceModel.Service) {
}).Bind(apis.RequireSuperuserAuth())
addFeedRoutes(se, services.App)
professor.RegisterRoutes(se, services.ProfessorService)
return se.Next()
})

View File

@@ -0,0 +1,284 @@
package professor
import (
"fmt"
"htwkalender/data-manager/model"
"log/slog"
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase"
)
type ProfessorService struct {
app *pocketbase.PocketBase
}
func NewProfessorService(app *pocketbase.PocketBase) *ProfessorService {
return &ProfessorService{app: app}
}
func (s *ProfessorService) GetModulesForProfessor(email string) ([]model.ModuleDTO, error) {
// Extract name from email
// Format: firstname.lastname@htwk-leipzig.de
parts := strings.Split(email, "@")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid email format")
}
nameParts := strings.Split(parts[0], ".")
if len(nameParts) < 2 {
slog.Warn("Email does not contain dot separator", "email", email)
return []model.ModuleDTO{}, nil
}
// Extract first and last name
firstName := nameParts[0]
lastName := nameParts[len(nameParts)-1]
// Capitalize first letter
if len(firstName) > 0 {
firstName = strings.ToUpper(firstName[:1]) + firstName[1:]
}
if len(lastName) > 0 {
lastName = strings.ToUpper(lastName[:1]) + lastName[1:]
}
slog.Info("Searching for modules for professor", "firstName", firstName, "lastName", lastName, "email", email)
// First, get all distinct modules with their professors
type EventProf struct {
Name string `db:"Name" json:"name"`
EventType string `db:"EventType" json:"eventType"`
Prof string `db:"Prof" json:"prof"`
Course string `db:"course" json:"course"`
Semester string `db:"semester" json:"semester"`
UUID string `db:"uuid" json:"uuid"`
}
var allEvents []EventProf
err := s.app.DB().
Select("Name", "EventType", "Prof", "course", "semester", "uuid").
From("events").
Where(dbx.NewExp("Prof != ''")).
GroupBy("Name", "course", "Prof").
Distinct(true).
All(&allEvents)
if err != nil {
return nil, err
}
// Filter events by matching professor name and calculate confidence scores
var modules []model.ModuleDTO
seenModules := make(map[string]bool) // key: Name+Course to avoid duplicates
for _, event := range allEvents {
score := calculateConfidenceScore(event.Prof, firstName, lastName)
if score > 0 { // Include all modules with any match
key := event.Name + "|" + event.Course
if !seenModules[key] {
modules = append(modules, model.ModuleDTO{
Name: event.Name,
EventType: event.EventType,
Prof: event.Prof,
Course: event.Course,
Semester: event.Semester,
UUID: event.UUID,
ConfidenceScore: score,
})
seenModules[key] = true
}
}
}
slog.Info("Found modules for professor", "count", len(modules), "lastName", lastName)
return modules, nil
}
// calculateConfidenceScore returns a score from 0.0 to 1.0 indicating how confident we are
// that this professor string matches the given first and last name
// 1.0 = perfect match (both first and last name exact)
// 0.7-0.9 = good match (last name exact, first name fuzzy or present)
// 0.4-0.6 = possible match (last name fuzzy or partial)
// 0.1-0.3 = weak match (last name substring)
// 0.0 = no match
func calculateConfidenceScore(profString, firstName, lastName string) float64 {
// Normalize the professor string: remove common titles and split into words
profString = strings.ToLower(profString)
// Remove common titles
titles := []string{"prof.", "dr.", "arch.", "ing.", "dipl.", "m.sc.", "b.sc.", "ph.d."}
for _, title := range titles {
profString = strings.ReplaceAll(profString, title, "")
}
// Split by spaces, hyphens, and other separators
words := strings.FieldsFunc(profString, func(r rune) bool {
return r == ' ' || r == '-' || r == ',' || r == '.'
})
// Normalize firstName and lastName
firstNameLower := strings.ToLower(firstName)
lastNameLower := strings.ToLower(lastName)
lastNameExact := false
lastNameFuzzy := false
lastNameSubstring := false
firstNameExact := false
firstNameFuzzy := false
for _, word := range words {
word = strings.TrimSpace(word)
if word == "" {
continue
}
// Check last name
if word == lastNameLower {
lastNameExact = true
} else if levenshteinDistance(word, lastNameLower) <= 1 && len(lastNameLower) > 3 {
lastNameFuzzy = true
} else if strings.Contains(word, lastNameLower) || strings.Contains(lastNameLower, word) {
lastNameSubstring = true
}
// Check first name
if word == firstNameLower {
firstNameExact = true
} else if levenshteinDistance(word, firstNameLower) <= 1 && len(firstNameLower) > 3 {
firstNameFuzzy = true
}
}
// Calculate confidence score based on matches
score := 0.0
if lastNameExact {
if firstNameExact {
score = 1.0 // Perfect match
} else if firstNameFuzzy {
score = 0.9 // Excellent match
} else {
score = 0.8 // Good match (last name exact, no first name match)
}
} else if lastNameFuzzy {
if firstNameExact || firstNameFuzzy {
score = 0.6 // Decent match (fuzzy last name but first name matches)
} else {
score = 0.5 // Medium match (fuzzy last name, no first name)
}
} else if lastNameSubstring {
score = 0.2 // Weak match (substring only)
}
return score
}
// matchesProfessor is deprecated, use calculateConfidenceScore instead
func matchesProfessor(profString, firstName, lastName string) bool {
// Normalize the professor string: remove common titles and split into words
profString = strings.ToLower(profString)
// Remove common titles
titles := []string{"prof.", "dr.", "arch.", "ing.", "dipl.", "m.sc.", "b.sc.", "ph.d."}
for _, title := range titles {
profString = strings.ReplaceAll(profString, title, "")
}
// Split by spaces, hyphens, and other separators
words := strings.FieldsFunc(profString, func(r rune) bool {
return r == ' ' || r == '-' || r == ',' || r == '.'
})
// Normalize firstName and lastName
firstNameLower := strings.ToLower(firstName)
lastNameLower := strings.ToLower(lastName)
lastNameFound := false
firstNameFound := false
for _, word := range words {
word = strings.TrimSpace(word)
if word == "" {
continue
}
// Exact match for last name
if word == lastNameLower {
lastNameFound = true
}
// Exact match for first name (optional, but increases confidence)
if word == firstNameLower {
firstNameFound = true
}
// Also check Levenshtein distance for typos
if !lastNameFound && levenshteinDistance(word, lastNameLower) <= 1 {
lastNameFound = true
}
if !firstNameFound && levenshteinDistance(word, firstNameLower) <= 1 {
firstNameFound = true
}
}
// Match if last name is found (first name is optional for additional confidence)
// We require at least the last name to match
return lastNameFound
}
// levenshteinDistance calculates the Levenshtein distance between two strings
func levenshteinDistance(s1, s2 string) int {
if len(s1) == 0 {
return len(s2)
}
if len(s2) == 0 {
return len(s1)
}
// Create a 2D array for dynamic programming
d := make([][]int, len(s1)+1)
for i := range d {
d[i] = make([]int, len(s2)+1)
}
// Initialize first column and row
for i := 0; i <= len(s1); i++ {
d[i][0] = i
}
for j := 0; j <= len(s2); j++ {
d[0][j] = j
}
// Fill the matrix
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
cost := 0
if s1[i-1] != s2[j-1] {
cost = 1
}
d[i][j] = min(
d[i-1][j]+1, // deletion
d[i][j-1]+1, // insertion
d[i-1][j-1]+cost, // substitution
)
}
}
return d[len(s1)][len(s2)]
}
func min(a, b, c int) int {
if a < b {
if a < c {
return a
}
return c
}
if b < c {
return b
}
return c
}

View File

@@ -0,0 +1,29 @@
package professor
import (
"net/http"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
)
func RegisterRoutes(se *core.ServeEvent, service *ProfessorService) {
se.Router.GET("/api/professor/modules", func(e *core.RequestEvent) error {
record := e.Auth
if record == nil {
return apis.NewForbiddenError("Only authenticated users can access this endpoint", nil)
}
email := record.GetString("email")
if email == "" {
return apis.NewBadRequestError("User has no email", nil)
}
modules, err := service.GetModulesForProfessor(email)
if err != nil {
return apis.NewBadRequestError("Failed to fetch modules", err)
}
return e.JSON(http.StatusOK, modules)
}).Bind(apis.RequireAuth())
}