Gastansicht, Verbesserungen bei Planung

This commit is contained in:
concierge committed 2026-11-18 07:57:00 +01:00
1 parent b3afa3ef32
commit c08d43e7dd
38 files changed
+3845 -219

No files matched your search

+184 -25
View File
@@ -2,6 +2,8 @@ package domain
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
)
@@ -89,19 +91,86 @@ type Church struct {
Notes string `json:"notes"`
}
// WeekdayPeriod narrows a preferred weekday to a part of the day.
type WeekdayPeriod string
const (
PeriodAllDay WeekdayPeriod = "all"
PeriodMorning WeekdayPeriod = "morning"
PeriodAfternoon WeekdayPeriod = "afternoon"
PeriodEvening WeekdayPeriod = "evening"
)
var AllWeekdayPeriods = []WeekdayPeriod{PeriodAllDay, PeriodMorning, PeriodAfternoon, PeriodEvening}
func (p WeekdayPeriod) Label() string {
switch p {
case PeriodMorning:
return "vormittags (0–12 Uhr)"
case PeriodAfternoon:
return "nachmittags (12–17 Uhr)"
case PeriodEvening:
return "abends (ab 17 Uhr)"
default:
return "ganztägig"
}
}
func (p WeekdayPeriod) ShortLabel() string {
switch p {
case PeriodMorning:
return "vormittags"
case PeriodAfternoon:
return "nachmittags"
case PeriodEvening:
return "abends"
default:
return "ganztägig"
}
}
func (p WeekdayPeriod) IsValid() bool {
return p == PeriodAllDay || p == PeriodMorning || p == PeriodAfternoon || p == PeriodEvening
}
// Matches reports whether a service starting at timeMinutes falls into the
// selected part of the day. Morning is 0–12, afternoon 12–17, evening after 17.
func (p WeekdayPeriod) Matches(timeMinutes int) bool {
switch p {
case PeriodMorning:
return timeMinutes < 12*60
case PeriodAfternoon:
return timeMinutes >= 12*60 && timeMinutes < 17*60
case PeriodEvening:
return timeMinutes >= 17*60
default:
return true
}
}
// WeekdayPeriodPreference stores the selected part of the day for one
// preferred weekday. Weekdays without an entry count as all day.
type WeekdayPeriodPreference struct {
Weekday int `json:"weekday"`
Period WeekdayPeriod `json:"period"`
}
type Person struct {
ID string `json:"id"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Roles []Role `json:"roles"`
Email string `json:"email"`
EmailLocked bool `json:"-"`
PreferredChurchIDs []string `json:"preferredChurchIDs"`
PreferredWeekdays []int `json:"preferredWeekdays"`
PreferredServiceTitles []string `json:"preferredServiceTitles"`
MaxPerMonth int `json:"maxPerMonth"`
Active bool `json:"active"`
Notes string `json:"notes"`
ID string `json:"id"`
ShortCode string `json:"shortCode"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Roles []Role `json:"roles"`
Email string `json:"email"`
EmailLocked bool `json:"-"`
PreferredChurchIDs []string `json:"preferredChurchIDs"`
PreferredWeekdays []int `json:"preferredWeekdays"`
PreferredWeekdayPeriods []WeekdayPeriodPreference `json:"preferredWeekdayPeriods"`
PreferredServiceTitles []string `json:"preferredServiceTitles"`
MaxPerMonth int `json:"maxPerMonth"`
AllowBeyondPreferences bool `json:"allowBeyondPreferences"`
Active bool `json:"active"`
Notes string `json:"notes"`
}
func (p Person) FullName() string {
@@ -127,6 +196,80 @@ func (p Person) AbbreviatedName() string {
return p.LastName
}
// DisplayShort is the guest-facing label: an explicitly maintained Kürzel wins,
// otherwise the initials from first and last name.
func (p Person) DisplayShort() string {
if code := strings.TrimSpace(p.ShortCode); code != "" {
return code
}
return p.Initials()
}
// WeekdayPeriodFor returns the selected part of the day for a weekday.
func (p Person) WeekdayPeriodFor(weekday int) WeekdayPeriod {
for _, preference := range p.PreferredWeekdayPeriods {
if preference.Weekday == weekday && preference.Period.IsValid() {
return preference.Period
}
}
return PeriodAllDay
}
// MatchesWeekdayPreference reports whether the service day and time satisfy
// the weekday preferences. High feasts count like Sundays, so a Sunday
// preference also covers them. An empty weekday list means no restriction.
func (p Person) MatchesWeekdayPreference(weekday, timeMinutes int, highFeast bool) bool {
if len(p.PreferredWeekdays) == 0 {
return true
}
candidates := []int{weekday}
if highFeast && weekday != 1 {
candidates = append(candidates, 1)
}
for _, day := range candidates {
if IntContains(p.PreferredWeekdays, day) && p.WeekdayPeriodFor(day).Matches(timeMinutes) {
return true
}
}
return false
}
// PreferenceNote is the free-text planning note shown next to assignments.
func (p Person) PreferenceNote() string { return strings.TrimSpace(p.Notes) }
// PersonLabels computes stable short labels for a set of people. If two people
// share a label, every member of that group gets a running number appended.
func PersonLabels(people []Person) map[string]string {
sorted := append([]Person(nil), people...)
sort.SliceStable(sorted, func(i, j int) bool {
if sorted[i].LastName != sorted[j].LastName {
return sorted[i].LastName < sorted[j].LastName
}
if sorted[i].FirstName != sorted[j].FirstName {
return sorted[i].FirstName < sorted[j].FirstName
}
return sorted[i].ID < sorted[j].ID
})
base := make(map[string]string, len(sorted))
counts := map[string]int{}
for _, person := range sorted {
label := person.DisplayShort()
base[person.ID] = label
counts[label]++
}
seen := map[string]int{}
labels := make(map[string]string, len(sorted))
for _, person := range sorted {
label := base[person.ID]
if counts[label] > 1 {
seen[label]++
label += strconv.Itoa(seen[label])
}
labels[person.ID] = label
}
return labels
}
func (p Person) RoleLabel() string {
var parts []string
for _, role := range AllRoles {
@@ -336,13 +479,14 @@ func (s ServiceOccurrence) RolesNeeded() []Role {
}
type Assignment struct {
ID string `json:"id"`
ServiceID string `json:"serviceID"`
PersonID string `json:"personID"`
Role Role `json:"role"`
Locked bool `json:"locked"`
Note string `json:"note"`
CreatedAt time.Time `json:"createdAt"`
ID string `json:"id"`
ServiceID string `json:"serviceID"`
PersonID string `json:"personID"`
Role Role `json:"role"`
Locked bool `json:"locked"`
BeyondPreferences bool `json:"beyondPreferences"`
Note string `json:"note"`
CreatedAt time.Time `json:"createdAt"`
}
// Liturgical model ---------------------------------------------------------
@@ -702,6 +846,19 @@ func (r DayPlanRow) AssignmentCount() int {
}
func (r DayPlanRow) HasServices() bool { return len(r.Services) > 0 }
// HasBeyondPreferences marks days with at least one assignment that goes
// beyond the person's preferences.
func (r DayPlanRow) HasBeyondPreferences() bool {
for _, service := range r.Services {
for _, assignment := range service.Assignments {
if assignment.BeyondPreferences {
return true
}
}
}
return false
}
func (r DayPlanRow) IsSunday() bool {
return (r.LiturgicalDay != nil && r.LiturgicalDay.IsSunday()) || IsSunday(r.Date)
}
@@ -823,6 +980,7 @@ func (s RangeStatistics) AverageAssignments() float64 {
type PlannerOptions struct {
ReplaceExisting bool
RespectPreferredWeekdays bool
AllowBeyondPreferences bool
AllowDoubleRolesOnSameDay bool
WeightChurchPreference float64
WeightServicePreference float64
@@ -850,10 +1008,11 @@ type PlanResult struct {
}
type CandidateSuggestion struct {
Person Person
Score float64
Warnings []string
Blocked bool
Preferred bool
TotalAssignments int
Person Person
Score float64
Warnings []string
Blocked bool
Preferred bool
BeyondPreferences bool
TotalAssignments int
}
+93 -13
View File
@@ -14,6 +14,7 @@ type ServicePlanner struct {
Services []ServiceOccurrence
ExistingAssignments []Assignment
Churches []Church
LiturgicalDays []LiturgicalDay
Options PlannerOptions
}
@@ -41,6 +42,12 @@ func (p ServicePlanner) Plan() PlanResult {
for _, s := range p.Services {
serviceByID[s.ID] = s
}
highFeastByDate := map[string]bool{}
for _, day := range p.LiturgicalDays {
if day.IsHighFeast() {
highFeastByDate[day.DateKey()] = true
}
}
working := make([]Assignment, 0, len(p.ExistingAssignments))
for _, a := range p.ExistingAssignments {
@@ -129,9 +136,10 @@ func (p ServicePlanner) Plan() PlanResult {
continue
}
for i := existingForRole; i < required; i++ {
highFeast := highFeastByDate[service.DateKey()]
result := p.bestCandidate(service, role, activePeople, absencesByPerson,
totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson,
lastDateByPerson, assignedRoles)
lastDateByPerson, assignedRoles, highFeast, true)
if result.person == nil {
unfilled = append(unfilled, UnfilledSlot{
Service: service,
@@ -165,6 +173,59 @@ func (p ServicePlanner) Plan() PlanResult {
}
}
// Second pass, only on explicit request: use volunteers who agreed to be
// planned beyond their preferences for the slots that remained open.
if p.Options.AllowBeyondPreferences && len(unfilled) > 0 {
var flagged []Person
for _, person := range activePeople {
if person.AllowBeyondPreferences {
flagged = append(flagged, person)
}
}
if len(flagged) > 0 {
remaining := make([]UnfilledSlot, 0, len(unfilled))
for _, slot := range unfilled {
service := slot.Service
highFeast := highFeastByDate[service.DateKey()]
assignedRoles := map[string]map[Role]bool{}
for _, assignment := range working {
if assignment.ServiceID != service.ID {
continue
}
if assignedRoles[assignment.PersonID] == nil {
assignedRoles[assignment.PersonID] = map[Role]bool{}
}
assignedRoles[assignment.PersonID][assignment.Role] = true
}
result := p.bestCandidate(service, slot.Role, flagged, absencesByPerson,
totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson,
lastDateByPerson, assignedRoles, highFeast, false)
if result.person == nil {
slot.Reason = result.reason
remaining = append(remaining, slot)
continue
}
person := *result.person
assignment := Assignment{
ID: newID(),
ServiceID: service.ID,
PersonID: person.ID,
Role: slot.Role,
BeyondPreferences: true,
CreatedAt: now(),
}
newAssignments = append(newAssignments, assignment)
working = append(working, assignment)
if roleCounts[service.ID] == nil {
roleCounts[service.ID] = map[Role]int{}
}
roleCounts[service.ID][slot.Role]++
applyToCounts(assignment, service)
}
unfilled = remaining
}
}
filled := len(newAssignments)
var message string
switch {
@@ -211,6 +272,8 @@ func (p ServicePlanner) bestCandidate(
churchByPerson map[string]map[string]int,
lastDateByPerson map[string]time.Time,
assignedRolesByPerson map[string]map[Role]bool,
highFeast bool,
enforcePreferences bool,
) candidateResult {
blockedReasons := map[string]int{}
var eligible []Person
@@ -237,14 +300,14 @@ func (p ServicePlanner) bestCandidate(
continue
}
}
if p.Options.RespectPreferredWeekdays && len(person.PreferredWeekdays) > 0 &&
!IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
blockedReasons["Einsatztag passt nicht"]++
if p.Options.RespectPreferredWeekdays && enforcePreferences &&
!person.MatchesWeekdayPreference(Weekday(service.Date), service.TimeMinutes, highFeast) {
blockedReasons["Einsatztag oder Uhrzeit passt nicht"]++
continue
}
month := MonthKey(service.Date)
usedThisMonth := monthByPerson[person.ID+"|"+month]
if person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth {
if enforcePreferences && person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth {
blockedReasons["Monatslimit erreicht"]++
continue
}
@@ -303,7 +366,8 @@ func (p ServicePlanner) bestCandidate(
}
}
}
if IntContains(person.PreferredWeekdays, Weekday(service.Date)) {
if person.MatchesWeekdayPreference(Weekday(service.Date), service.TimeMinutes, highFeast) &&
len(person.PreferredWeekdays) > 0 {
score += 3
}
score -= float64(total) * p.Options.WeightFairness
@@ -377,6 +441,7 @@ func CandidateSuggestions(
services []ServiceOccurrence,
serviceAssignments []Assignment,
ignorePreferredWeekdays bool,
liturgicalDay *LiturgicalDay,
) []CandidateSuggestion {
monthKey := MonthKey(service.Date)
serviceDateByID := map[string]ServiceOccurrence{}
@@ -424,11 +489,13 @@ func CandidateSuggestions(
}
const fairnessSlack = 1
weekday := Weekday(service.Date)
highFeast := liturgicalDay != nil && liturgicalDay.IsHighFeast()
var suggestions []CandidateSuggestion
for _, person := range eligible {
var warnings []string
blocked := false
beyond := false
for _, a := range absences {
if a.PersonID == person.ID && a.Overlaps(service.Date) {
warnings = append(warnings, "abwesend")
@@ -436,13 +503,26 @@ func CandidateSuggestions(
break
}
}
if !ignorePreferredWeekdays && len(person.PreferredWeekdays) > 0 && !IntContains(person.PreferredWeekdays, weekday) {
warnings = append(warnings, "Einsatztag passt nicht")
blocked = true
weekdayMatch := person.MatchesWeekdayPreference(weekday, service.TimeMinutes, highFeast)
if !weekdayMatch {
switch {
case ignorePreferredWeekdays:
beyond = true
case person.AllowBeyondPreferences:
beyond = true
default:
warnings = append(warnings, "Einsatztag oder Uhrzeit passt nicht")
blocked = true
}
}
if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth {
warnings = append(warnings, "Monatslimit")
blocked = true
if person.AllowBeyondPreferences {
warnings = append(warnings, "Monatslimit")
beyond = true
} else {
warnings = append(warnings, "Monatslimit")
blocked = true
}
}
used := dayServices[person.ID+"|"+service.DateKey()]
if len(used) > 0 && !subsetOfSingle(used, service.ID) {
@@ -473,7 +553,7 @@ func CandidateSuggestions(
if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) {
score -= 2
}
if IntContains(person.PreferredWeekdays, weekday) {
if weekdayMatch && len(person.PreferredWeekdays) > 0 {
score += 3
preferred = true
}
@@ -492,7 +572,7 @@ func CandidateSuggestions(
}
suggestions = append(suggestions, CandidateSuggestion{
Person: person, Score: score, Warnings: warnings, Blocked: blocked,
Preferred: preferred, TotalAssignments: total,
Preferred: preferred, BeyondPreferences: beyond, TotalAssignments: total,
})
}
+157
View File
@@ -0,0 +1,157 @@
package domain
import "testing"
func TestPersonLabelsUsesShortCodeAndNumbersDuplicates(t *testing.T) {
people := []Person{
{ID: "p1", FirstName: "Anna", LastName: "Berg"},
{ID: "p2", FirstName: "Anton", LastName: "Berg"},
{ID: "p3", ShortCode: "MK", FirstName: "Markus", LastName: "Klein"},
{ID: "p4", FirstName: "Mia", LastName: "Sommer"},
}
labels := PersonLabels(people)
cases := map[string]string{"p1": "AB1", "p2": "AB2", "p3": "MK", "p4": "MS"}
for id, want := range cases {
if got := labels[id]; got != want {
t.Errorf("label for %s = %q, want %q", id, got, want)
}
}
}
func TestMatchesWeekdayPreferenceTreatsHighFeastsLikeSundays(t *testing.T) {
sundayOnly := Person{PreferredWeekdays: []int{1}}
if !sundayOnly.MatchesWeekdayPreference(2, 10*60, true) {
t.Fatal("a Sunday preference must cover a high feast on another weekday")
}
if sundayOnly.MatchesWeekdayPreference(2, 10*60, false) {
t.Fatal("an ordinary Monday must not match a Sunday preference")
}
morningSunday := Person{
PreferredWeekdays: []int{1},
PreferredWeekdayPeriods: []WeekdayPeriodPreference{
{Weekday: 1, Period: PeriodMorning},
},
}
if !morningSunday.MatchesWeekdayPreference(2, 10*60, true) {
t.Fatal("a high feast in the morning should match the Sunday morning preference")
}
if morningSunday.MatchesWeekdayPreference(2, 18*60, true) {
t.Fatal("a high feast in the evening must not match the Sunday morning preference")
}
}
func TestMatchesWeekdayPreferenceUsesPeriodBounds(t *testing.T) {
person := Person{
PreferredWeekdays: []int{2},
PreferredWeekdayPeriods: []WeekdayPeriodPreference{
{Weekday: 2, Period: PeriodMorning},
},
}
if !person.MatchesWeekdayPreference(2, 11*60+59, false) {
t.Error("11:59 belongs to the morning")
}
if person.MatchesWeekdayPreference(2, 12*60, false) {
t.Error("12:00 must no longer count as morning")
}
if person.MatchesWeekdayPreference(2, 16*60+59, false) {
t.Error("16:59 belongs to the afternoon, not the morning")
}
person.PreferredWeekdayPeriods = []WeekdayPeriodPreference{{Weekday: 2, Period: PeriodEvening}}
if !person.MatchesWeekdayPreference(2, 17*60, false) {
t.Error("17:00 belongs to the evening")
}
}
func plannerFixture(person Person) (ServicePlanner, ServiceOccurrence) {
church := Church{ID: "c1", Name: "St. Andreas"}
// 2026-11-16 is a Monday.
service := ServiceOccurrence{
ID: "s1", ChurchID: church.ID, Date: MustDate("2026-11-16"),
TimeMinutes: 18 * 60, Title: "Abendmesse", LectorsNeeded: 1,
}
planner := ServicePlanner{
People: []Person{person},
Services: []ServiceOccurrence{service},
Churches: []Church{church},
Options: DefaultPlannerOptions(),
}
return planner, service
}
func TestPlannerBeyondPreferencesRequiresExplicitPass(t *testing.T) {
person := Person{
ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []Role{RoleLector},
PreferredWeekdays: []int{1}, Active: true, MaxPerMonth: 1,
}
planner, _ := plannerFixture(person)
planner.Options.RespectPreferredWeekdays = true
result := planner.Plan()
if len(result.Unfilled) != 1 || len(result.Assignments) != 0 {
t.Fatalf("without permission the slot must stay open, got %#v", result)
}
person.AllowBeyondPreferences = true
planner, _ = plannerFixture(person)
planner.Options.RespectPreferredWeekdays = true
planner.Options.AllowBeyondPreferences = true
result = planner.Plan()
if len(result.Unfilled) != 0 || len(result.Assignments) != 1 {
t.Fatalf("expected a fallback assignment, got %#v", result)
}
if !result.Assignments[0].BeyondPreferences {
t.Fatal("fallback assignment must be marked as beyond preferences")
}
person.AllowBeyondPreferences = false
planner, _ = plannerFixture(person)
planner.Options.AllowBeyondPreferences = true
if result := planner.Plan(); len(result.Assignments) != 0 {
t.Fatal("a person without permission must not be planned beyond preferences")
}
}
func TestPlannerTreatsHighFeastAsSunday(t *testing.T) {
person := Person{
ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []Role{RoleLector},
PreferredWeekdays: []int{1}, Active: true, MaxPerMonth: 6,
}
planner, service := plannerFixture(person)
planner.LiturgicalDays = []LiturgicalDay{{
Date: service.Date, Title: "Hochfest", Rank: RankSolemnity,
}}
result := planner.Plan()
if len(result.Assignments) != 1 || len(result.Unfilled) != 0 {
t.Fatalf("high feast must match a Sunday preference, got %#v", result)
}
if result.Assignments[0].BeyondPreferences {
t.Fatal("a matched high feast is not beyond preferences")
}
}
func TestCandidateSuggestionsMarkBeyondPreferences(t *testing.T) {
service := ServiceOccurrence{
ID: "s1", ChurchID: "c1", Date: MustDate("2026-11-16"),
TimeMinutes: 18 * 60, Title: "Abendmesse", LectorsNeeded: 1,
}
sundayOnly := Person{
ID: "p1", FirstName: "Anna", LastName: "Berg", Roles: []Role{RoleLector},
PreferredWeekdays: []int{1}, Active: true, MaxPerMonth: 6,
}
suggestions := CandidateSuggestions(service, RoleLector,
[]Person{sundayOnly}, nil, nil, []ServiceOccurrence{service}, nil, false, nil)
if len(suggestions) != 1 || !suggestions[0].Blocked || suggestions[0].BeyondPreferences {
t.Fatalf("person without permission should be blocked, got %#v", suggestions)
}
sundayOnly.AllowBeyondPreferences = true
suggestions = CandidateSuggestions(service, RoleLector,
[]Person{sundayOnly}, nil, nil, []ServiceOccurrence{service}, nil, false, nil)
if len(suggestions) != 1 || suggestions[0].Blocked || !suggestions[0].BeyondPreferences {
t.Fatalf("flagged person should be suggested beyond preferences, got %#v", suggestions)
}
if suggestions[0].Person.PreferenceNote() != "" {
t.Fatal("unexpected preference note")
}
}
+325
View File
@@ -0,0 +1,325 @@
package store
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"sort"
"strings"
"time"
"lektorenplan/domain"
)
// ReaderContact is one reader account together with the person it represents.
// The e-mail address is only filled when the requesting session holds the data
// key for that person, i.e. after the owner shared it.
type ReaderContact struct {
UserID string
Person domain.Person
}
// ReaderDirectory lists the active reader accounts linked to a tenant. The
// contacts are hydrated with the current request's keyring, so addresses that
// were not shared remain empty and locked.
func (s *Store) ReaderDirectory(ctx context.Context, tenantID string) ([]ReaderContact, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT u.id, u.linked_person_id
FROM users u
JOIN people p ON p.tenant_id=u.linked_tenant_id AND p.id=u.linked_person_id
WHERE u.active=1 AND u.role='reader' AND u.linked_tenant_id=?
ORDER BY p.last_name COLLATE NOCASE, p.first_name COLLATE NOCASE, u.id`, tenantID)
if err != nil {
return nil, err
}
type readerRow struct {
userID string
personID string
}
var ids []readerRow
for rows.Next() {
var row readerRow
if err := rows.Scan(&row.userID, &row.personID); err != nil {
rows.Close()
return nil, err
}
ids = append(ids, row)
}
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
rows.Close()
out := make([]ReaderContact, 0, len(ids))
for _, row := range ids {
person, err := s.Person(ctx, tenantID, row.personID)
if errors.Is(err, ErrNotFound) {
continue
}
if err != nil {
return nil, err
}
out = append(out, ReaderContact{UserID: row.userID, Person: *person})
}
return out, nil
}
// ReaderForPerson returns the active reader account linked to a person.
func (s *Store) ReaderForPerson(ctx context.Context, tenantID, personID string) (string, bool) {
var userID string
err := s.db.QueryRowContext(ctx, `
SELECT id FROM users
WHERE active=1 AND role='reader' AND linked_tenant_id=? AND linked_person_id=?
ORDER BY id LIMIT 1`, tenantID, personID).Scan(&userID)
if err != nil {
return "", false
}
return userID, true
}
// ContactSharesForOwner lists the reader accounts that may see the owner's
// e-mail address.
func (s *Store) ContactSharesForOwner(ctx context.Context, tenantID, ownerPersonID string) (map[string]bool, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT viewer_user_id FROM contact_shares
WHERE tenant_id=? AND owner_person_id=?`, tenantID, ownerPersonID)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]bool{}
for rows.Next() {
var userID string
if err := rows.Scan(&userID); err != nil {
return nil, err
}
out[userID] = true
}
return out, rows.Err()
}
// ContactSharesForViewer lists the persons whose e-mail addresses were shared
// with one reader account.
func (s *Store) ContactSharesForViewer(ctx context.Context, tenantID, viewerUserID string) ([]string, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT owner_person_id FROM contact_shares
WHERE tenant_id=? AND viewer_user_id=? ORDER BY owner_person_id`, tenantID, viewerUserID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var personID string
if err := rows.Scan(&personID); err != nil {
return nil, err
}
out = append(out, personID)
}
return out, rows.Err()
}
func (s *Store) contactShareViewers(ctx context.Context, tenantID, ownerPersonID string) ([]string, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT viewer_user_id FROM contact_shares
WHERE tenant_id=? AND owner_person_id=? ORDER BY viewer_user_id`, tenantID, ownerPersonID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var userID string
if err := rows.Scan(&userID); err != nil {
return nil, err
}
out = append(out, userID)
}
return out, rows.Err()
}
// ContactShareExists reports whether ownerPersonID shared the address with the
// given account.
func (s *Store) ContactShareExists(ctx context.Context, tenantID, ownerPersonID, viewerUserID string) bool {
var count int
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM contact_shares
WHERE tenant_id=? AND owner_person_id=? AND viewer_user_id=?`,
tenantID, ownerPersonID, viewerUserID).Scan(&count)
return err == nil && count > 0
}
// SetContactShares replaces the viewer list of one owner. Newly selected
// readers receive the encrypted person scope; removed readers lose their
// wrapper immediately. The returned lists contain the actual changes.
func (s *Store) SetContactShares(ctx context.Context, keyring *Keyring, tenantID, ownerUserID, ownerPersonID string, viewerUserIDs []string) (added, removed []string, err error) {
// Refuse before touching the consent table when the session cannot grant
// the encrypted scope; otherwise a failed save would leave an announced
// share without a usable key.
if s.SecretIsInitialized(ctx, tenantID) && keyring == nil {
return nil, nil, errKeyLocked
}
current, err := s.ContactSharesForOwner(ctx, tenantID, ownerPersonID)
if err != nil {
return nil, nil, err
}
wanted := map[string]bool{}
for _, raw := range viewerUserIDs {
userID := strings.TrimSpace(raw)
if userID == "" || userID == ownerUserID || wanted[userID] {
continue
}
var count int
if err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM users
WHERE id=? AND active=1 AND role='reader' AND linked_tenant_id=?
AND linked_person_id<>'' AND linked_person_id<>?`,
userID, tenantID, ownerPersonID).Scan(&count); err != nil {
return nil, nil, err
}
if count == 0 {
return nil, nil, errors.New("Ein ausgewähltes Konto ist kein aktiver Leserzugang dieses Mandanten")
}
wanted[userID] = true
}
for userID := range current {
if !wanted[userID] {
removed = append(removed, userID)
}
}
for userID := range wanted {
if !current[userID] {
added = append(added, userID)
}
}
sort.Strings(added)
sort.Strings(removed)
if err := s.transaction(ctx, func(tx *sql.Tx) error {
for _, userID := range removed {
if _, err := tx.ExecContext(ctx, `
DELETE FROM contact_shares
WHERE tenant_id=? AND owner_person_id=? AND viewer_user_id=?`,
tenantID, ownerPersonID, userID); err != nil {
return err
}
}
for _, userID := range added {
if _, err := tx.ExecContext(ctx, `
INSERT INTO contact_shares(tenant_id, owner_person_id, viewer_user_id, granted_at)
VALUES(?, ?, ?, ?)
ON CONFLICT DO NOTHING`,
tenantID, ownerPersonID, userID, time.Now().UTC().Format(time.RFC3339)); err != nil {
return err
}
}
// A pending swap is only possible while both sides still release
// their addresses. Revoking a share cancels affected requests so the
// plan never keeps a swap-requested mark for an impossible swap.
if _, err := tx.ExecContext(ctx, `
UPDATE swap_requests SET status=?, responded_at=?
WHERE tenant_id=? AND status=? AND NOT (
EXISTS (
SELECT 1 FROM contact_shares a
WHERE a.tenant_id=swap_requests.tenant_id
AND a.owner_person_id=swap_requests.target_person_id
AND a.viewer_user_id=swap_requests.requester_user_id
) AND EXISTS (
SELECT 1 FROM contact_shares b
WHERE b.tenant_id=swap_requests.tenant_id
AND b.owner_person_id=swap_requests.requester_person_id
AND b.viewer_user_id=swap_requests.target_user_id
)
)`, SwapCancelled, time.Now().UTC().Format(time.RFC3339), tenantID, SwapPending); err != nil {
return err
}
return nil
}); err != nil {
return nil, nil, err
}
if s.SecretIsInitialized(ctx, tenantID) {
scope := KeyScope{Type: ScopePerson, TenantID: tenantID, ID: ownerPersonID}
if len(added) > 0 {
dek, err := s.ensureScope(ctx, keyring, scope)
if err != nil {
return added, removed, err
}
if err := s.grantScopeDEK(ctx, keyring, scope, dek, added); err != nil {
return added, removed, err
}
}
for _, userID := range removed {
if _, err := s.db.ExecContext(ctx, `
DELETE FROM key_wrappers
WHERE scope_type=? AND tenant_id=? AND scope_id=? AND user_id=?`,
ScopePerson, tenantID, ownerPersonID, userID); err != nil {
return added, removed, err
}
}
}
return added, removed, nil
}
// readerRosterHash fingerprints the current reader accounts of a tenant. The
// owner's own account is excluded.
func (s *Store) readerRosterHash(ctx context.Context, tenantID, ownerUserID string) (string, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, linked_person_id FROM users
WHERE active=1 AND role='reader' AND linked_tenant_id=? AND id<>?
ORDER BY id`, tenantID, ownerUserID)
if err != nil {
return "", err
}
defer rows.Close()
hash := sha256.New()
for rows.Next() {
var userID, personID string
if err := rows.Scan(&userID, &personID); err != nil {
return "", err
}
hash.Write([]byte(userID + "|" + personID + "\n"))
}
if err := rows.Err(); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
// ContactRosterChanged reports whether the reader directory changed since the
// owner last reviewed the sharing list. known is false before the first save.
func (s *Store) ContactRosterChanged(ctx context.Context, tenantID, ownerUserID, ownerPersonID string) (changed, known bool, err error) {
current, err := s.readerRosterHash(ctx, tenantID, ownerUserID)
if err != nil {
return false, false, err
}
var stored string
err = s.db.QueryRowContext(ctx, `
SELECT roster_hash FROM contact_reviews
WHERE tenant_id=? AND owner_person_id=?`, tenantID, ownerPersonID).Scan(&stored)
if errors.Is(err, sql.ErrNoRows) {
return false, false, nil
}
if err != nil {
return false, false, err
}
return stored != current, true, nil
}
// MarkContactRosterReviewed stores the current reader directory fingerprint.
func (s *Store) MarkContactRosterReviewed(ctx context.Context, tenantID, ownerUserID, ownerPersonID string) error {
hash, err := s.readerRosterHash(ctx, tenantID, ownerUserID)
if err != nil {
return err
}
_, err = s.db.ExecContext(ctx, `
INSERT INTO contact_reviews(tenant_id, owner_person_id, roster_hash, reviewed_at)
VALUES(?, ?, ?, ?)
ON CONFLICT(tenant_id, owner_person_id) DO UPDATE SET
roster_hash=excluded.roster_hash, reviewed_at=excluded.reviewed_at`,
tenantID, ownerPersonID, hash, time.Now().UTC().Format(time.RFC3339))
return err
}
+89 -8
View File
@@ -135,14 +135,17 @@ CREATE TABLE IF NOT EXISTS churches (
CREATE TABLE IF NOT EXISTS people (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL,
short_code TEXT NOT NULL DEFAULT '',
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
roles TEXT NOT NULL,
email TEXT NOT NULL DEFAULT '',
preferred_church_ids TEXT NOT NULL DEFAULT '[]',
preferred_weekdays TEXT NOT NULL DEFAULT '[]',
preferred_weekday_periods TEXT NOT NULL DEFAULT '[]',
preferred_service_titles TEXT NOT NULL DEFAULT '[]',
max_per_month INTEGER NOT NULL DEFAULT 6,
allow_beyond_preferences INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id)
@@ -215,6 +218,7 @@ CREATE TABLE IF NOT EXISTS assignments (
person_id TEXT NOT NULL,
role TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0,
beyond_preferences INTEGER NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, id),
@@ -315,6 +319,41 @@ CREATE TABLE IF NOT EXISTS secret_state (
tenant_id TEXT PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
initialized_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS contact_shares (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
owner_person_id TEXT NOT NULL,
viewer_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
granted_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, owner_person_id, viewer_user_id)
);
CREATE INDEX IF NOT EXISTS idx_contact_shares_viewer ON contact_shares(viewer_user_id);
CREATE TABLE IF NOT EXISTS contact_reviews (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
owner_person_id TEXT NOT NULL,
roster_hash TEXT NOT NULL,
reviewed_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, owner_person_id)
);
CREATE TABLE IF NOT EXISTS swap_requests (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
requester_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
requester_person_id TEXT NOT NULL,
target_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
target_person_id TEXT NOT NULL,
offered_assignment_id TEXT NOT NULL,
wanted_assignment_id TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
token_hash TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL,
responded_at TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_swap_requests_tenant ON swap_requests(tenant_id, status);
CREATE INDEX IF NOT EXISTS idx_swap_requests_requester ON swap_requests(requester_user_id, status);
CREATE INDEX IF NOT EXISTS idx_swap_requests_target ON swap_requests(target_user_id, status);
`
func (s *Store) migrate(ctx context.Context) error {
@@ -344,8 +383,41 @@ func (s *Store) migrate(ctx context.Context) error {
return fmt.Errorf("add users.%s: %w", column.name, err)
}
}
// People gained a guest label, weekday time periods and permission to be
// planned beyond their preferences. Assignments record when that happened.
peopleColumns := []struct {
name string
definition string
}{
{"short_code", "TEXT NOT NULL DEFAULT ''"},
{"preferred_weekday_periods", "TEXT NOT NULL DEFAULT '[]'"},
{"allow_beyond_preferences", "INTEGER NOT NULL DEFAULT 0"},
}
for _, column := range peopleColumns {
exists, err := s.hasColumn(ctx, "people", column.name)
if err != nil {
return fmt.Errorf("inspect people table: %w", err)
}
if exists {
continue
}
if _, err := s.db.ExecContext(ctx,
"ALTER TABLE people ADD COLUMN "+column.name+" "+column.definition); err != nil {
return fmt.Errorf("add people.%s: %w", column.name, err)
}
}
hasBeyond, err := s.hasColumn(ctx, "assignments", "beyond_preferences")
if err != nil {
return fmt.Errorf("inspect assignments table: %w", err)
}
if !hasBeyond {
if _, err := s.db.ExecContext(ctx,
"ALTER TABLE assignments ADD COLUMN beyond_preferences INTEGER NOT NULL DEFAULT 0"); err != nil {
return fmt.Errorf("add assignments.beyond_preferences: %w", err)
}
}
if _, err := s.db.ExecContext(ctx,
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '5') "+
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '7') "+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
return fmt.Errorf("record schema version: %w", err)
}
@@ -365,7 +437,8 @@ func (s *Store) migrate(ctx context.Context) error {
}
}
// Editors and linked readers hold key material; administrators never do.
// Readers may only keep the scope of their linked person.
// Readers keep their own person scope plus every scope that another reader
// has explicitly shared with them.
if _, err := s.db.ExecContext(ctx,
"DELETE FROM key_wrappers WHERE user_id IN (SELECT id FROM users WHERE role='admin')"); err != nil {
return fmt.Errorf("prune administrator key wrappers: %w", err)
@@ -376,15 +449,23 @@ func (s *Store) migrate(ctx context.Context) error {
}
if _, err := s.db.ExecContext(ctx, `
DELETE FROM key_wrappers WHERE user_id IN (
SELECT u.id FROM users u WHERE u.role='reader' AND (
u.linked_tenant_id='' OR u.linked_person_id='' OR NOT (
key_wrappers.scope_type='person'
AND key_wrappers.tenant_id=u.linked_tenant_id
AND key_wrappers.scope_id=u.linked_person_id
SELECT id FROM users WHERE role='reader'
) AND NOT EXISTS (
SELECT 1 FROM users u
WHERE u.id=key_wrappers.user_id AND u.role='reader' AND u.active=1
AND key_wrappers.scope_type='person'
AND key_wrappers.tenant_id=u.linked_tenant_id
AND (
key_wrappers.scope_id=u.linked_person_id
OR EXISTS (
SELECT 1 FROM contact_shares cs
WHERE cs.tenant_id=key_wrappers.tenant_id
AND cs.owner_person_id=key_wrappers.scope_id
AND cs.viewer_user_id=u.id
)
)
)`); err != nil {
return fmt.Errorf("prune unlinked reader key wrappers: %w", err)
return fmt.Errorf("prune reader key wrappers: %w", err)
}
// Dispatch logs used to contain the full recipient address. Remove that
// plaintext now that addresses are stored encrypted.
+35 -10
View File
@@ -14,8 +14,8 @@ import (
// KeyScope identifies one encrypted data scope. Tenant scopes hold the SMTP
// credentials, person scopes hold e-mail addresses. Editors hold the person
// scopes of their tenants; a reader only holds the scope of the person linked
// to their account.
// scopes of their tenants; a reader holds the scope of the person linked to
// their account and the scopes that other readers have shared with them.
type KeyScope struct {
Type string
TenantID string
@@ -62,6 +62,14 @@ func (k *Keyring) remember(scope KeyScope, dek []byte) {
k.deks[scope.String()] = append([]byte{}, dek...)
}
// Forget drops a cached data key. It is used when a reader revokes access to
// their e-mail address so an already open session loses the key immediately.
func (k *Keyring) Forget(scope KeyScope) {
k.mu.Lock()
defer k.mu.Unlock()
delete(k.deks, scope.String())
}
type keyringContextKey struct{}
// WithKeyring attaches an unlocked keyring to a request context.
@@ -407,6 +415,12 @@ func (s *Store) ReconcileTenant(ctx context.Context, keyring *Keyring, tenantID
if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" {
recipients = append(recipients, linked)
}
shared, err := s.contactShareViewers(ctx, tenantID, personID)
if err != nil {
rememberError(err)
} else {
recipients = append(recipients, shared...)
}
if err := s.grantScope(ctx, keyring, scope, recipients); err != nil {
rememberError(err)
}
@@ -663,9 +677,10 @@ func (s *Store) SetSecret(ctx context.Context, tenantID, scopeType, scopeID, key
}
// EnsurePersonScope creates the person scope if needed and grants it to all
// active editors plus the linked reader. It works with an editor keyring and
// with a reader keyring that already holds the person's data key; the latter
// lets a reader refresh editor access after a new editor was created.
// active editors, the linked reader and every reader the owner shared their
// address with. It works with an editor keyring and with a reader keyring that
// already holds the person's data key; the latter lets a reader refresh access
// after a new editor was created.
func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantID, personID string) error {
if keyring == nil || !s.SecretIsInitialized(ctx, tenantID) {
return nil
@@ -681,6 +696,11 @@ func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantI
if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" {
recipients = append(recipients, linked)
}
shared, err := s.contactShareViewers(ctx, tenantID, personID)
if err != nil {
return err
}
recipients = append(recipients, shared...)
return s.grantScope(ctx, keyring, scope, recipients)
}
@@ -785,9 +805,9 @@ func (s *Store) DeleteUserKeys(ctx context.Context, userID string) error {
}
// PruneUserWrappers enforces the key access policy. Editors keep the scopes of
// their tenant memberships. A reader may hold exactly one wrapper: the person
// scope of the account they are linked to. Administrators never hold key
// material.
// their tenant memberships. A reader keeps the person scope they are linked to
// plus every person scope that its owner has shared with the account.
// Administrators never hold key material.
func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error {
var role, linkedTenantID, linkedPersonID string
var active int
@@ -826,8 +846,13 @@ func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error {
}
_, err = s.db.ExecContext(ctx, `
DELETE FROM key_wrappers WHERE user_id=? AND NOT (
scope_type='person' AND tenant_id=? AND scope_id=?
)`, userID, linkedTenantID, linkedPersonID)
scope_type='person' AND tenant_id=? AND (
scope_id=? OR scope_id IN (
SELECT owner_person_id FROM contact_shares
WHERE tenant_id=? AND viewer_user_id=?
)
)
)`, userID, linkedTenantID, linkedPersonID, linkedTenantID, userID)
return err
}
+60 -15
View File
@@ -49,6 +49,25 @@ func encodeInts(values []int) string {
return string(data)
}
func encodeWeekdayPeriods(values []domain.WeekdayPeriodPreference) string {
if values == nil {
values = []domain.WeekdayPeriodPreference{}
}
data, err := json.Marshal(values)
if err != nil {
return "[]"
}
return string(data)
}
func decodeWeekdayPeriods(value string) []domain.WeekdayPeriodPreference {
var out []domain.WeekdayPeriodPreference
if err := json.Unmarshal([]byte(value), &out); err != nil {
return nil
}
return out
}
// Churches lists a tenant's churches.
func (s *Store) Churches(ctx context.Context, tenantID string) ([]domain.Church, error) {
rows, err := s.db.QueryContext(ctx, `
@@ -152,8 +171,9 @@ func (s *Store) DeleteChurch(ctx context.Context, tenantID, id string) error {
// People lists a tenant's volunteers.
func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, first_name, last_name, roles, email, preferred_church_ids,
preferred_weekdays, preferred_service_titles, max_per_month, active, notes
SELECT id, short_code, first_name, last_name, roles, email, preferred_church_ids,
preferred_weekdays, preferred_weekday_periods, preferred_service_titles,
max_per_month, allow_beyond_preferences, active, notes
FROM people WHERE tenant_id=? ORDER BY last_name COLLATE NOCASE, first_name COLLATE NOCASE`, tenantID)
if err != nil {
return nil, err
@@ -183,8 +203,9 @@ func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, e
// Person loads one volunteer.
func (s *Store) Person(ctx context.Context, tenantID, id string) (*domain.Person, error) {
row := s.db.QueryRowContext(ctx, `
SELECT id, first_name, last_name, roles, email, preferred_church_ids,
preferred_weekdays, preferred_service_titles, max_per_month, active, notes
SELECT id, short_code, first_name, last_name, roles, email, preferred_church_ids,
preferred_weekdays, preferred_weekday_periods, preferred_service_titles,
max_per_month, allow_beyond_preferences, active, notes
FROM people WHERE tenant_id=? AND id=?`, tenantID, id)
person, err := scanPerson(row)
if errors.Is(err, sql.ErrNoRows) {
@@ -218,11 +239,11 @@ func (s *Store) hydratePersonContacts(ctx context.Context, tenantID string, pers
func scanPerson(row rowScanner) (*domain.Person, error) {
var person domain.Person
var roles, churches, weekdays, titles string
var active int
if err := row.Scan(&person.ID, &person.FirstName, &person.LastName, &roles,
&person.Email, &churches, &weekdays, &titles,
&person.MaxPerMonth, &active, &person.Notes); err != nil {
var roles, churches, weekdays, periods, titles string
var allowBeyond, active int
if err := row.Scan(&person.ID, &person.ShortCode, &person.FirstName, &person.LastName, &roles,
&person.Email, &churches, &weekdays, &periods, &titles,
&person.MaxPerMonth, &allowBeyond, &active, &person.Notes); err != nil {
return nil, err
}
for _, raw := range decodeStrings(roles) {
@@ -233,7 +254,9 @@ func scanPerson(row rowScanner) (*domain.Person, error) {
}
person.PreferredChurchIDs = decodeStrings(churches)
person.PreferredWeekdays = decodeInts(weekdays)
person.PreferredWeekdayPeriods = decodeWeekdayPeriods(periods)
person.PreferredServiceTitles = decodeStrings(titles)
person.AllowBeyondPreferences = allowBeyond != 0
person.Active = active != 0
return &person, nil
}
@@ -285,21 +308,28 @@ func (s *Store) UpsertPerson(ctx context.Context, tenantID string, person domain
email = ""
}
_, err := tx.ExecContext(ctx, `
INSERT INTO people(tenant_id, id, first_name, last_name, roles, email,
preferred_church_ids, preferred_weekdays, preferred_service_titles,
max_per_month, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
INSERT INTO people(tenant_id, id, short_code, first_name, last_name, roles, email,
preferred_church_ids, preferred_weekdays, preferred_weekday_periods,
preferred_service_titles, max_per_month, allow_beyond_preferences, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET
short_code=excluded.short_code,
first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
email=CASE WHEN ? THEN excluded.email ELSE people.email END,
preferred_church_ids=excluded.preferred_church_ids,
preferred_weekdays=excluded.preferred_weekdays,
preferred_weekday_periods=excluded.preferred_weekday_periods,
preferred_service_titles=excluded.preferred_service_titles,
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes`,
tenantID, person.ID, person.FirstName, person.LastName, encodeStrings(roleStrings),
max_per_month=excluded.max_per_month,
allow_beyond_preferences=excluded.allow_beyond_preferences,
active=excluded.active, notes=excluded.notes`,
tenantID, person.ID, strings.TrimSpace(person.ShortCode),
person.FirstName, person.LastName, encodeStrings(roleStrings),
email, encodeStrings(person.PreferredChurchIDs),
encodeInts(person.PreferredWeekdays),
encodeWeekdayPeriods(person.PreferredWeekdayPeriods),
encodeStrings(person.PreferredServiceTitles), person.MaxPerMonth,
boolInt(person.AllowBeyondPreferences),
boolInt(person.Active), person.Notes, boolInt(updateLegacyContact))
if err != nil {
return err
@@ -360,6 +390,21 @@ func (s *Store) DeletePerson(ctx context.Context, tenantID, id string) error {
ScopePerson, tenantID, id); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
"DELETE FROM contact_shares WHERE tenant_id=? AND (owner_person_id=? OR viewer_user_id IN ("+
"SELECT id FROM users WHERE linked_tenant_id=? AND linked_person_id=?))",
tenantID, id, tenantID, id); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
"DELETE FROM contact_reviews WHERE tenant_id=? AND owner_person_id=?", tenantID, id); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
"DELETE FROM swap_requests WHERE tenant_id=? AND (requester_person_id=? OR target_person_id=?)",
tenantID, id, id); err != nil {
return err
}
_, err := tx.ExecContext(ctx, "DELETE FROM people WHERE tenant_id=? AND id=?", tenantID, id)
return err
})
+21 -14
View File
@@ -270,7 +270,8 @@ func (s *Store) DeleteGeneratedServices(ctx context.Context, tenantID string, r
// Assignments returns assignments whose service lies in the range.
func (s *Store) Assignments(ctx context.Context, tenantID string, r domain.DayRange) ([]domain.Assignment, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT a.id, a.service_id, a.person_id, a.role, a.locked, a.note, a.created_at
SELECT a.id, a.service_id, a.person_id, a.role, a.locked, a.beyond_preferences,
a.note, a.created_at
FROM assignments a JOIN services s ON s.tenant_id=a.tenant_id AND s.id=a.service_id
WHERE a.tenant_id=? AND s.date >= ? AND s.date <= ?
ORDER BY s.date, s.time_minutes`, tenantID, domain.Key(r.Start), domain.Key(r.End))
@@ -292,7 +293,7 @@ func (s *Store) AssignmentsForServices(ctx context.Context, tenantID string, ser
for _, id := range serviceIDs {
args = append(args, id)
}
query := "SELECT id, service_id, person_id, role, locked, note, created_at FROM assignments " +
query := "SELECT id, service_id, person_id, role, locked, beyond_preferences, note, created_at FROM assignments " +
"WHERE tenant_id=? AND service_id IN (" + placeholders + ")"
rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil {
@@ -305,7 +306,7 @@ func (s *Store) AssignmentsForServices(ctx context.Context, tenantID string, ser
// AssignmentsForPerson lists all assignments of a volunteer.
func (s *Store) AssignmentsForPerson(ctx context.Context, tenantID, personID string) ([]domain.Assignment, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, service_id, person_id, role, locked, note, created_at
SELECT id, service_id, person_id, role, locked, beyond_preferences, note, created_at
FROM assignments WHERE tenant_id=? AND person_id=? ORDER BY created_at`, tenantID, personID)
if err != nil {
return nil, err
@@ -326,13 +327,14 @@ func scanAssignments(rows *sql.Rows) ([]domain.Assignment, error) {
for rows.Next() {
var assignment domain.Assignment
var role, created string
var locked int
var locked, beyond int
if err := rows.Scan(&assignment.ID, &assignment.ServiceID, &assignment.PersonID,
&role, &locked, &assignment.Note, &created); err != nil {
&role, &locked, &beyond, &assignment.Note, &created); err != nil {
return nil, err
}
assignment.Role = domain.Role(role)
assignment.Locked = locked != 0
assignment.BeyondPreferences = beyond != 0
assignment.CreatedAt = parseTime(created)
out = append(out, assignment)
}
@@ -351,14 +353,16 @@ func (s *Store) UpsertAssignment(ctx context.Context, tenantID string, assignmen
assignment.CreatedAt = time.Now().UTC()
}
_, err := s.db.ExecContext(ctx, `
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked,
beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET
service_id=excluded.service_id, person_id=excluded.person_id,
role=excluded.role, locked=excluded.locked, note=excluded.note`,
role=excluded.role, locked=excluded.locked,
beyond_preferences=excluded.beyond_preferences, note=excluded.note`,
tenantID, assignment.ID, assignment.ServiceID, assignment.PersonID,
string(assignment.Role), boolInt(assignment.Locked), assignment.Note,
assignment.CreatedAt.Format(time.RFC3339))
string(assignment.Role), boolInt(assignment.Locked), boolInt(assignment.BeyondPreferences),
assignment.Note, assignment.CreatedAt.Format(time.RFC3339))
if err != nil && isUniqueViolation(err) {
return ErrConflict
}
@@ -399,13 +403,16 @@ func (s *Store) SavePlan(ctx context.Context, tenantID string, assignments []dom
assignment.CreatedAt = time.Now().UTC()
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked,
beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET
service_id=excluded.service_id, person_id=excluded.person_id,
role=excluded.role, locked=excluded.locked, note=excluded.note`,
role=excluded.role, locked=excluded.locked,
beyond_preferences=excluded.beyond_preferences, note=excluded.note`,
tenantID, assignment.ID, assignment.ServiceID, assignment.PersonID,
string(assignment.Role), boolInt(assignment.Locked), assignment.Note,
string(assignment.Role), boolInt(assignment.Locked),
boolInt(assignment.BeyondPreferences), assignment.Note,
assignment.CreatedAt.Format(time.RFC3339)); err != nil {
return err
}
+442
View File
@@ -0,0 +1,442 @@
package store
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"strings"
"time"
"lektorenplan/domain"
)
// Swap request states.
const (
SwapPending = "pending"
SwapAccepted = "accepted"
SwapDeclined = "declined"
SwapCancelled = "cancelled"
)
// SwapRequest is one proposed exchange of two assignments.
type SwapRequest struct {
ID string
TenantID string
RequesterUserID string
RequesterPersonID string
TargetUserID string
TargetPersonID string
OfferedAssignmentID string
WantedAssignmentID string
Status string
TokenHash string
CreatedAt time.Time
RespondedAt time.Time
}
// SwapAssignmentInfo bundles an assignment with its service.
type SwapAssignmentInfo struct {
Assignment domain.Assignment
Service domain.ServiceOccurrence
}
func swapTokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// SwapTokenMatches reports whether a plaintext e-mail token belongs to the
// stored request.
func SwapTokenMatches(request *SwapRequest, token string) bool {
if request == nil || request.TokenHash == "" || token == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(request.TokenHash), []byte(swapTokenHash(token))) == 1
}
func newSwapToken() (string, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
func scanSwapRequest(row rowScanner) (*SwapRequest, error) {
var request SwapRequest
var created, responded string
if err := row.Scan(&request.ID, &request.TenantID, &request.RequesterUserID,
&request.RequesterPersonID, &request.TargetUserID, &request.TargetPersonID,
&request.OfferedAssignmentID, &request.WantedAssignmentID, &request.Status,
&request.TokenHash, &created, &responded); err != nil {
return nil, err
}
request.CreatedAt = parseTime(created)
request.RespondedAt = parseTime(responded)
return &request, nil
}
const swapRequestColumns = `id, tenant_id, requester_user_id, requester_person_id,
target_user_id, target_person_id, offered_assignment_id, wanted_assignment_id,
status, token_hash, created_at, responded_at`
// SwapRequestByToken loads a request by its unhashed e-mail token.
func (s *Store) SwapRequestByToken(ctx context.Context, tenantID, token string) (*SwapRequest, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+swapRequestColumns+`
FROM swap_requests WHERE tenant_id=? AND token_hash=?`,
tenantID, swapTokenHash(strings.TrimSpace(token)))
request, err := scanSwapRequest(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return request, err
}
// SwapRequestByID loads one request of a tenant.
func (s *Store) SwapRequestByID(ctx context.Context, tenantID, id string) (*SwapRequest, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+swapRequestColumns+`
FROM swap_requests WHERE tenant_id=? AND id=?`, tenantID, id)
request, err := scanSwapRequest(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return request, err
}
// swapAssignmentInfo loads one assignment together with its service.
func (s *Store) SwapAssignmentInfo(ctx context.Context, tenantID, assignmentID string) (*SwapAssignmentInfo, error) {
row := s.db.QueryRowContext(ctx, `
SELECT a.id, a.service_id, a.person_id, a.role, a.locked, a.note, a.created_at,
s.id, s.church_id, s.location, s.template_id, s.date, s.time_minutes,
s.title, s.lectors_needed, s.helpers_needed, s.kind, s.notes,
s.locked, s.created_at
FROM assignments a
JOIN services s ON s.tenant_id=a.tenant_id AND s.id=a.service_id
WHERE a.tenant_id=? AND a.id=?`, tenantID, assignmentID)
var info SwapAssignmentInfo
var role, aCreated, date, kind, sCreated, location string
var templateID sql.NullString
var aLocked, sLocked int
if err := row.Scan(&info.Assignment.ID, &info.Assignment.ServiceID,
&info.Assignment.PersonID, &role, &aLocked, &info.Assignment.Note, &aCreated,
&info.Service.ID, &info.Service.ChurchID, &location, &templateID, &date,
&info.Service.TimeMinutes, &info.Service.Title, &info.Service.LectorsNeeded,
&info.Service.HelpersNeeded, &kind, &info.Service.Notes, &sLocked, &sCreated); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
info.Assignment.Role = domain.Role(role)
info.Assignment.Locked = aLocked != 0
info.Assignment.CreatedAt = parseTime(aCreated)
if location != "" {
info.Service.Location = &location
}
if templateID.Valid && templateID.String != "" {
value := templateID.String
info.Service.TemplateID = &value
}
info.Service.Date = domain.MustDate(date)
info.Service.Kind = domain.ServiceKind(kind)
info.Service.Locked = sLocked != 0
info.Service.CreatedAt = parseTime(sCreated)
return &info, nil
}
func (s *Store) personAbsentOn(ctx context.Context, tenantID, personID string, date time.Time) bool {
var count int
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM absences
WHERE tenant_id=? AND person_id=? AND start_date<=? AND end_date>=?`,
tenantID, personID, domain.Key(date), domain.Key(date)).Scan(&count)
return err == nil && count > 0
}
func (s *Store) assignmentConflict(ctx context.Context, tenantID, serviceID, personID string, role domain.Role, excludeID string) bool {
var count int
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM assignments
WHERE tenant_id=? AND service_id=? AND person_id=? AND role=? AND id<>?`,
tenantID, serviceID, personID, string(role), excludeID).Scan(&count)
return err == nil && count > 0
}
func (s *Store) pendingSwapForAssignment(ctx context.Context, tenantID, assignmentID, excludeRequestID string) bool {
var count int
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM swap_requests
WHERE tenant_id=? AND status=? AND id<>?
AND (offered_assignment_id=? OR wanted_assignment_id=?)`,
tenantID, SwapPending, excludeRequestID, assignmentID, assignmentID).Scan(&count)
return err == nil && count > 0
}
// swapConsentExists verifies the mutual address release that makes both the
// request and the response e-mail possible.
func (s *Store) swapConsentExists(ctx context.Context, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID string) bool {
return s.ContactShareExists(ctx, tenantID, targetPersonID, requesterUserID) &&
s.ContactShareExists(ctx, tenantID, requesterPersonID, targetUserID)
}
// validateSwapPair checks every planning and privacy precondition for a swap.
// excludeRequestID is the request currently being answered, if any.
func (s *Store) validateSwapPair(ctx context.Context, tenantID, requesterPersonID, targetPersonID, offeredID, wantedID, excludeRequestID string) (*SwapAssignmentInfo, *SwapAssignmentInfo, error) {
if requesterPersonID == "" || targetPersonID == "" || offeredID == "" || wantedID == "" {
return nil, nil, errors.New("Für den Tausch fehlen Angaben")
}
if requesterPersonID == targetPersonID {
return nil, nil, errors.New("Ein Tausch mit sich selbst ist nicht möglich")
}
offered, err := s.SwapAssignmentInfo(ctx, tenantID, offeredID)
if err != nil {
return nil, nil, errors.New("Der angebotene Einsatz wurde nicht gefunden")
}
wanted, err := s.SwapAssignmentInfo(ctx, tenantID, wantedID)
if err != nil {
return nil, nil, errors.New("Der gewünschte Einsatz wurde nicht gefunden")
}
if offered.Assignment.PersonID != requesterPersonID {
return nil, nil, errors.New("Der angebotene Einsatz gehört nicht mehr zu Ihnen")
}
if wanted.Assignment.PersonID != targetPersonID {
return nil, nil, errors.New("Der gewünschte Einsatz gehört nicht mehr zur angefragten Person")
}
if offered.Assignment.Role != wanted.Assignment.Role {
return nil, nil, errors.New("Es können nur Einsätze derselben Rolle getauscht werden")
}
today := domain.Today()
if offered.Service.Date.Before(today) || wanted.Service.Date.Before(today) {
return nil, nil, errors.New("Vergangene Einsätze können nicht getauscht werden")
}
if offered.Service.Locked || offered.Assignment.Locked || wanted.Service.Locked || wanted.Assignment.Locked {
return nil, nil, errors.New("Gesperrte Einsätze können nicht getauscht werden")
}
if s.personAbsentOn(ctx, tenantID, targetPersonID, offered.Service.Date) {
return nil, nil, errors.New("Die angefragte Person ist am angebotenen Termin als abwesend eingetragen")
}
if s.personAbsentOn(ctx, tenantID, requesterPersonID, wanted.Service.Date) {
return nil, nil, errors.New("Sie sind am gewünschten Termin als abwesend eingetragen")
}
if s.assignmentConflict(ctx, tenantID, wanted.Service.ID, requesterPersonID, wanted.Assignment.Role, wanted.Assignment.ID) {
return nil, nil, errors.New("Sie sind für diesen Gottesdienst bereits in derselben Rolle eingeteilt")
}
if s.assignmentConflict(ctx, tenantID, offered.Service.ID, targetPersonID, offered.Assignment.Role, offered.Assignment.ID) {
return nil, nil, errors.New("Die angefragte Person ist für diesen Gottesdienst bereits in derselben Rolle eingeteilt")
}
if s.pendingSwapForAssignment(ctx, tenantID, offered.Assignment.ID, excludeRequestID) ||
s.pendingSwapForAssignment(ctx, tenantID, wanted.Assignment.ID, excludeRequestID) {
return nil, nil, errors.New("Für einen der beiden Einsätze liegt bereits eine offene Tauschanfrage vor")
}
return offered, wanted, nil
}
// SwapOptions lists the requester's future assignments that can be offered for
// the wanted assignment of the target person.
func (s *Store) SwapOptions(ctx context.Context, tenantID, requesterPersonID, targetPersonID, wantedAssignmentID string) ([]SwapAssignmentInfo, error) {
wanted, err := s.SwapAssignmentInfo(ctx, tenantID, wantedAssignmentID)
if err != nil {
return nil, errors.New("Der gewünschte Einsatz wurde nicht gefunden")
}
if wanted.Assignment.PersonID != targetPersonID {
return nil, errors.New("Der gewünschte Einsatz gehört nicht mehr zur angefragten Person")
}
if wanted.Service.Date.Before(domain.Today()) {
return nil, errors.New("Vergangene Einsätze können nicht getauscht werden")
}
if wanted.Service.Locked || wanted.Assignment.Locked {
return nil, errors.New("Gesperrte Einsätze können nicht getauscht werden")
}
assignments, err := s.AssignmentsForPerson(ctx, tenantID, requesterPersonID)
if err != nil {
return nil, err
}
out := make([]SwapAssignmentInfo, 0, len(assignments))
for _, assignment := range assignments {
if assignment.Role != wanted.Assignment.Role || assignment.ID == wanted.Assignment.ID {
continue
}
service, err := s.Service(ctx, tenantID, assignment.ServiceID)
if err != nil || service.Date.Before(domain.Today()) {
continue
}
offered, _, err := s.validateSwapPair(ctx, tenantID, requesterPersonID,
targetPersonID, assignment.ID, wantedAssignmentID, "")
if err != nil {
continue
}
out = append(out, *offered)
}
return out, nil
}
// CreateSwapRequest validates a proposed exchange, stores it and returns the
// plaintext e-mail token. Only the token hash is persisted.
func (s *Store) CreateSwapRequest(ctx context.Context, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID, offeredID, wantedID string) (*SwapRequest, string, error) {
if !s.swapConsentExists(ctx, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID) {
return nil, "", errors.New("Für eine Tauschanfrage müssen beide Seiten ihre E-Mail-Adresse gegenseitig freigegeben haben")
}
if _, _, err := s.validateSwapPair(ctx, tenantID, requesterPersonID, targetPersonID, offeredID, wantedID, ""); err != nil {
return nil, "", err
}
token, err := newSwapToken()
if err != nil {
return nil, "", err
}
now := time.Now().UTC()
request := &SwapRequest{
ID: domain.NewID(), TenantID: tenantID,
RequesterUserID: requesterUserID, RequesterPersonID: requesterPersonID,
TargetUserID: targetUserID, TargetPersonID: targetPersonID,
OfferedAssignmentID: offeredID, WantedAssignmentID: wantedID,
Status: SwapPending, TokenHash: swapTokenHash(token), CreatedAt: now,
}
_, err = s.db.ExecContext(ctx, `
INSERT INTO swap_requests(id, tenant_id, requester_user_id, requester_person_id,
target_user_id, target_person_id, offered_assignment_id, wanted_assignment_id,
status, token_hash, created_at, responded_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '')`,
request.ID, request.TenantID, request.RequesterUserID, request.RequesterPersonID,
request.TargetUserID, request.TargetPersonID, request.OfferedAssignmentID,
request.WantedAssignmentID, request.Status, request.TokenHash,
request.CreatedAt.Format(time.RFC3339))
if err != nil {
return nil, "", err
}
return request, token, nil
}
// RespondSwapRequest accepts or declines a request on behalf of the target
// account. Accepting swaps both assignments atomically and revalidates every
// planning rule first.
func (s *Store) RespondSwapRequest(ctx context.Context, tenantID, token, targetUserID string, accept bool) (*SwapRequest, error) {
request, err := s.SwapRequestByToken(ctx, tenantID, token)
if err != nil {
return nil, err
}
if request.TargetUserID != targetUserID {
return nil, errors.New("Diese Tauschanfrage richtet sich an ein anderes Konto")
}
if request.Status != SwapPending {
return nil, errors.New("Diese Tauschanfrage wurde bereits beantwortet")
}
now := time.Now().UTC()
if !accept {
result, err := s.db.ExecContext(ctx, `
UPDATE swap_requests SET status=?, responded_at=?
WHERE tenant_id=? AND id=? AND status=?`,
SwapDeclined, now.Format(time.RFC3339), tenantID, request.ID, SwapPending)
if err != nil {
return nil, err
}
if affected, _ := result.RowsAffected(); affected == 0 {
return nil, errors.New("Diese Tauschanfrage wurde bereits beantwortet")
}
request.Status = SwapDeclined
request.RespondedAt = now
return request, nil
}
offered, wanted, err := s.validateSwapPair(ctx, tenantID, request.RequesterPersonID,
request.TargetPersonID, request.OfferedAssignmentID, request.WantedAssignmentID, request.ID)
if err != nil {
return nil, err
}
if !s.swapConsentExists(ctx, tenantID, request.RequesterUserID, request.RequesterPersonID,
request.TargetUserID, request.TargetPersonID) {
return nil, errors.New("Die gegenseitige E-Mail-Freigabe wurde inzwischen entzogen; der Tausch kann nicht angenommen werden")
}
tempPerson := "swap-tmp-" + request.ID
err = s.transaction(ctx, func(tx *sql.Tx) error {
update := func(personID, assignmentID, expected string) error {
result, err := tx.ExecContext(ctx, `
UPDATE assignments SET person_id=?
WHERE tenant_id=? AND id=? AND person_id=?`,
personID, tenantID, assignmentID, expected)
if err != nil {
return err
}
if affected, _ := result.RowsAffected(); affected != 1 {
return errors.New("Die Einteilung hat sich inzwischen geändert")
}
return nil
}
if err := update(tempPerson, offered.Assignment.ID, request.RequesterPersonID); err != nil {
return err
}
if err := update(request.RequesterPersonID, wanted.Assignment.ID, request.TargetPersonID); err != nil {
return err
}
if err := update(request.TargetPersonID, offered.Assignment.ID, tempPerson); err != nil {
return err
}
result, err := tx.ExecContext(ctx, `
UPDATE swap_requests SET status=?, responded_at=?
WHERE tenant_id=? AND id=? AND status=?`,
SwapAccepted, now.Format(time.RFC3339), tenantID, request.ID, SwapPending)
if err != nil {
return err
}
if affected, _ := result.RowsAffected(); affected != 1 {
return errors.New("Diese Tauschanfrage wurde bereits beantwortet")
}
// Competing requests for the same assignments can no longer be
// fulfilled after this swap.
_, err = tx.ExecContext(ctx, `
UPDATE swap_requests SET status=?, responded_at=?
WHERE tenant_id=? AND status=? AND id<>?
AND (offered_assignment_id IN (?, ?) OR wanted_assignment_id IN (?, ?))`,
SwapCancelled, now.Format(time.RFC3339), tenantID, SwapPending, request.ID,
offered.Assignment.ID, wanted.Assignment.ID,
offered.Assignment.ID, wanted.Assignment.ID)
return err
})
if err != nil {
return nil, err
}
request.Status = SwapAccepted
request.RespondedAt = now
return request, nil
}
// PendingSwapAssignmentIDs maps assignment IDs of open swap requests to the
// request ID so the plan and service views can mark them.
func (s *Store) PendingSwapAssignmentIDs(ctx context.Context, tenantID string) (map[string]string, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, offered_assignment_id, wanted_assignment_id
FROM swap_requests WHERE tenant_id=? AND status=?`,
tenantID, SwapPending)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]string{}
for rows.Next() {
var id, offered, wanted string
if err := rows.Scan(&id, &offered, &wanted); err != nil {
return nil, err
}
out[offered] = id
out[wanted] = id
}
return out, rows.Err()
}
// SwapStatusLabel returns the German label of a request state.
func SwapStatusLabel(status string) string {
switch status {
case SwapAccepted:
return "angenommen"
case SwapDeclined:
return "abgelehnt"
case SwapCancelled:
return "abgebrochen"
default:
return "offen"
}
}
+21
View File
@@ -1,6 +1,7 @@
package web
import (
"context"
"log"
"net/http"
"net/url"
@@ -69,10 +70,30 @@ func (s *Server) handleLoginPost(w http.ResponseWriter, r *http.Request) {
return
}
s.setFlash(w, "Willkommen zurück, "+user.DisplayName+".", "success")
if notice := s.readerRosterNotice(r.Context(), user); notice != "" {
s.setFlash(w, notice, "info")
}
next := safeNext(r.FormValue("next"))
s.redirect(w, r, next)
}
// readerRosterNotice returns a login hint when the reader directory changed
// since the last review of the sharing list.
func (s *Server) readerRosterNotice(ctx context.Context, user *store.User) string {
if user == nil || user.Role != store.RoleReader {
return ""
}
personID, linked := user.LinkedPerson(user.LinkedTenantID)
if !linked {
return ""
}
changed, known, err := s.store.ContactRosterChanged(ctx, user.LinkedTenantID, user.ID, personID)
if err != nil || !known || !changed {
return ""
}
return "Die Liste der Lektoren und Kommunionhelfer hat sich geändert. Bitte prüfen Sie unter „Team & Abwesenheiten“, wer Ihre E-Mail-Adresse sehen darf."
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
s.dropSessionKeyring(session.ID)
if cookie, err := r.Cookie(sessionCookie); err == nil {
+92 -10
View File
@@ -3,33 +3,41 @@ package web
import (
"net/http"
"strings"
"time"
"lektorenplan/domain"
"lektorenplan/store"
)
// guestPageData is the read-only public plan. It deliberately contains no
// person records: assignments are shown by role only.
// guestPageData is the read-only public plan. It exposes only short labels
// (Kürzel or initials) of assigned people, never full names or contact data.
type guestPageData struct {
Range domain.DayRange
Start string
End string
MinDate string
MaxDate string
PrevStart string
PrevEnd string
NextStart string
NextEnd string
CanPrev bool
CanNext bool
DefaultStart string
DefaultEnd string
Rows []domain.DayPlanRow
Churches []domain.Church
Tenants []store.Tenant
TenantID string
TenantName string
PersonLabels map[string]string
ServiceCount int
OpenSlots int
Today string
}
// handleGuest renders the plan without authentication. It never exposes
// settings, write actions or the names of assigned people.
// settings, write actions or the full names of assigned people.
func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
tenants, err := s.store.Tenants(r.Context())
if err != nil {
@@ -51,7 +59,18 @@ func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
}
}
rng := s.rangeFromRequest(r)
today := domain.Today()
// The selectable range starts at the most recent Sunday and ends with the
// last day that actually has planning data.
minDate := domain.AddingDays(-(domain.Weekday(today) - 1), today)
maxDate := today
if latest, err := s.store.LatestServiceDate(r.Context(), tenant.ID); err == nil && latest != nil {
maxDate = *latest
}
if maxDate.Before(minDate) {
maxDate = minDate
}
rng := guestRangeFromRequest(r, today, minDate, maxDate)
rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng)
if err != nil {
http.Error(w, "Der Gastzugang ist derzeit nicht verfügbar.", http.StatusInternalServerError)
@@ -63,15 +82,50 @@ func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
return
}
prev := domain.MonthRange(domain.AddingMonths(-1, rng.Start))
next := domain.MonthRange(domain.AddingMonths(1, rng.Start))
assignedIDs := map[string]bool{}
for _, row := range rows {
for _, service := range row.Services {
for _, assignment := range service.Assignments {
assignedIDs[assignment.PersonID] = true
}
}
}
labels := map[string]string{}
if len(assignedIDs) > 0 {
people, err := s.store.People(r.Context(), tenant.ID)
if err != nil {
http.Error(w, "Der Gastzugang ist derzeit nicht verfügbar.", http.StatusInternalServerError)
return
}
var assigned []domain.Person
for _, person := range people {
if assignedIDs[person.ID] {
assigned = append(assigned, person)
}
}
labels = domain.PersonLabels(assigned)
}
prevEnd := domain.AddingDays(-1, rng.Start)
nextStart := domain.AddingDays(1, rng.End)
page := guestPageData{
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
PrevStart: domain.Key(prev.Start), PrevEnd: domain.Key(prev.End),
NextStart: domain.Key(next.Start), NextEnd: domain.Key(next.End),
MinDate: domain.Key(minDate), MaxDate: domain.Key(maxDate),
Rows: rows, Churches: churches, Tenants: tenants,
TenantID: tenant.ID, TenantName: tenant.Name,
Today: domain.Key(domain.Today()),
TenantID: tenant.ID, TenantName: tenant.Name, PersonLabels: labels,
Today: domain.Key(today),
DefaultStart: domain.Key(guestClamp(today, minDate, maxDate)),
DefaultEnd: domain.Key(guestClamp(domain.AddingDays(28, today), minDate, maxDate)),
}
page.CanPrev = !prevEnd.Before(minDate)
if page.CanPrev {
page.PrevEnd = domain.Key(prevEnd)
page.PrevStart = domain.Key(guestClamp(domain.AddingDays(-27, prevEnd), minDate, maxDate))
}
page.CanNext = !nextStart.After(maxDate)
if page.CanNext {
page.NextStart = domain.Key(nextStart)
page.NextEnd = domain.Key(guestClamp(domain.AddingDays(27, nextStart), minDate, maxDate))
}
for _, row := range rows {
page.ServiceCount += len(row.Services)
@@ -86,3 +140,31 @@ func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
data.Data = page
s.renderPage(w, r, "guest", data)
}
// guestRangeFromRequest applies the narrower guest rules: the default is today
// through four weeks later, and every requested date is clamped to the
// selectable window between the most recent Sunday and the last planned day.
func guestRangeFromRequest(r *http.Request, today, minDate, maxDate time.Time) domain.DayRange {
start := guestClamp(today, minDate, maxDate)
end := guestClamp(domain.AddingDays(28, today), minDate, maxDate)
if parsed, ok := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("start"))); ok {
start = guestClamp(parsed, minDate, maxDate)
}
if parsed, ok := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("end"))); ok {
end = guestClamp(parsed, minDate, maxDate)
}
if end.Before(start) {
start, end = end, start
}
return domain.NewDayRange(start, end)
}
func guestClamp(date, minDate, maxDate time.Time) time.Time {
if date.Before(minDate) {
return minDate
}
if date.After(maxDate) {
return maxDate
}
return date
}
+47
View File
@@ -0,0 +1,47 @@
package web
import (
"net/http/httptest"
"testing"
"lektorenplan/domain"
)
func TestGuestRangeDefaultsToFourWeeks(t *testing.T) {
today := domain.MustDate("2026-11-17") // Tuesday
minDate := domain.MustDate("2026-11-15")
maxDate := domain.MustDate("2027-06-30")
request := httptest.NewRequest("GET", "/guest", nil)
rng := guestRangeFromRequest(request, today, minDate, maxDate)
if got := domain.Key(rng.Start); got != "2026-11-17" {
t.Errorf("default start = %s, want today", got)
}
if got := domain.Key(rng.End); got != "2026-12-15" {
t.Errorf("default end = %s, want four weeks", got)
}
}
func TestGuestRangeClampsToSundayAndLatestPlannedDay(t *testing.T) {
today := domain.MustDate("2026-11-17")
minDate := domain.MustDate("2026-11-15")
maxDate := domain.MustDate("2026-12-24")
request := httptest.NewRequest("GET", "/guest?start=2026-01-01&end=2027-01-01", nil)
rng := guestRangeFromRequest(request, today, minDate, maxDate)
if got := domain.Key(rng.Start); got != domain.Key(minDate) {
t.Errorf("start = %s, want the most recent Sunday %s", got, domain.Key(minDate))
}
if got := domain.Key(rng.End); got != domain.Key(maxDate) {
t.Errorf("end = %s, want the latest planned day %s", got, domain.Key(maxDate))
}
}
func TestGuestRangeSwapsReversedInput(t *testing.T) {
today := domain.MustDate("2026-11-17")
minDate := domain.MustDate("2026-11-15")
maxDate := domain.MustDate("2026-12-31")
request := httptest.NewRequest("GET", "/guest?start=2026-12-10&end=2026-11-20", nil)
rng := guestRangeFromRequest(request, today, minDate, maxDate)
if rng.End.Before(rng.Start) {
t.Fatalf("range not normalized: %s – %s", domain.Key(rng.Start), domain.Key(rng.End))
}
}
+20
View File
@@ -62,6 +62,26 @@ func (s *Server) refreshCachedKeyrings(ctx context.Context) {
}
}
// forgetCachedScopeForUsers removes a revoked data key from the sessions of
// the selected accounts. The owner's own session is deliberately untouched.
func (s *Server) forgetCachedScopeForUsers(scope store.KeyScope, userIDs []string) {
selected := map[string]bool{}
for _, userID := range userIDs {
selected[userID] = true
}
s.keyMu.Lock()
keyrings := make([]*store.Keyring, 0, len(s.keyrings))
for _, keyring := range s.keyrings {
if keyring != nil && selected[keyring.UserID] {
keyrings = append(keyrings, keyring)
}
}
s.keyMu.Unlock()
for _, keyring := range keyrings {
keyring.Forget(scope)
}
}
// activeEditorKeyring returns any unlocked editor keyring from the in-memory
// session cache. It lets an administrator trigger a re-grant after a password
// reset without ever decrypting the data themselves.
+35 -4
View File
@@ -64,6 +64,9 @@ type planPageData struct {
Timeline planTimeline
FilterPeople []domain.Person
PersonFilter string
SwapMarks map[string]string
PromptBeyond bool
BeyondOpen int
}
func flattenRows(rows []domain.DayPlanRow) ([]domain.ServiceOccurrence, []domain.Assignment) {
@@ -158,7 +161,7 @@ func (s *Server) handlePlan(w http.ResponseWriter, r *http.Request, user *store.
fourWeeks := domain.DaysRange(28, domain.Today())
data := s.baseView(w, r, "Gottesdienstplan", "plan")
data.Data = planPageData{
page := planPageData{
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
Rows: rows, Churches: churches, People: people, Stats: stats,
CanEdit: canEdit,
@@ -167,6 +170,11 @@ func (s *Server) handlePlan(w http.ResponseWriter, r *http.Request, user *store.
PresetFourStart: domain.Key(fourWeeks.Start), PresetFourEnd: domain.Key(fourWeeks.End),
Presets: presets, Timeline: timeline, FilterPeople: filterPeople, PersonFilter: personFilter,
}
page.PromptBeyond = canEdit && r.URL.Query().Get("beyondPrompt") == "1" &&
strings.TrimSpace(r.URL.Query().Get("beyondOpen")) != ""
page.BeyondOpen = parseInt(r.URL.Query().Get("beyondOpen"), 0)
page.SwapMarks, _ = s.store.PendingSwapAssignmentIDs(r.Context(), tenant.ID)
data.Data = page
s.renderPage(w, r, "plan", data)
}
@@ -339,7 +347,15 @@ func (s *Server) handleAutoPlan(w http.ResponseWriter, r *http.Request, user *st
}
rng := formRange(r)
options := s.planningOptions(r, tenant.ID)
options.ReplaceExisting = r.FormValue("replace") == "1" || r.FormValue("replace") == "on"
allowBeyond := r.FormValue("beyond") == "1" || r.FormValue("beyond") == "on"
if allowBeyond {
// Keep the result of the first pass and only add the fallback
// assignments for volunteers who explicitly allowed it.
options.ReplaceExisting = false
options.AllowBeyondPreferences = true
} else {
options.ReplaceExisting = r.FormValue("replace") == "1" || r.FormValue("replace") == "on"
}
services, err := s.store.Services(r.Context(), tenant.ID, rng)
if err != nil {
@@ -376,9 +392,11 @@ func (s *Server) handleAutoPlan(w http.ResponseWriter, r *http.Request, user *st
s.redirect(w, r, "/plan")
return
}
liturgicalDays, _ := s.store.LiturgicalDays(r.Context(), rng)
planner := domain.ServicePlanner{
People: people, Absences: absences, Services: services,
ExistingAssignments: existing, Churches: churches, Options: options,
ExistingAssignments: existing, Churches: churches, LiturgicalDays: liturgicalDays,
Options: options,
}
result := planner.Plan()
if err := s.store.SavePlan(r.Context(), tenant.ID, result.Assignments, rng, options.ReplaceExisting); err != nil {
@@ -390,7 +408,20 @@ func (s *Server) handleAutoPlan(w http.ResponseWriter, r *http.Request, user *st
}
s.setFlash(w, result.Message, kind)
}
s.redirect(w, r, "/plan?start="+domain.Key(rng.Start)+"&end="+domain.Key(rng.End))
target := "/plan?start=" + domain.Key(rng.Start) + "&end=" + domain.Key(rng.End)
if !allowBeyond && len(result.Unfilled) > 0 && hasBeyondVolunteers(people) {
target += fmt.Sprintf("&beyondPrompt=1&beyondOpen=%d", len(result.Unfilled))
}
s.redirect(w, r, target)
}
func hasBeyondVolunteers(people []domain.Person) bool {
for _, person := range people {
if person.Active && person.AllowBeyondPreferences {
return true
}
}
return false
}
func formRange(r *http.Request) domain.DayRange {
+10
View File
@@ -68,6 +68,7 @@ func New(st *store.Store, opts Options) (*Server, error) {
"login", "plan", "service", "services", "team", "person", "statistics",
"exchange", "settings", "liturgy", "dispatch", "guest", "admin_tenants", "admin_users",
"admin_churches", "password", "unlock", "error", "no_tenant",
"swap_request", "swap_detail",
}
views := make(map[string]*template.Template, len(names))
for _, name := range names {
@@ -158,6 +159,15 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /team/person/{id}/delete", s.editor(s.handlePersonDelete))
mux.HandleFunc("POST /team/person/{id}/absence", s.personEditor(s.handleAbsenceSave))
mux.HandleFunc("POST /team/person/{id}/absence/delete", s.personEditor(s.handleAbsenceDelete))
mux.HandleFunc("POST /team/sharing", s.auth(s.handleContactSharesSave))
mux.HandleFunc("POST /team/sharing/ack", s.auth(s.handleContactRosterAck))
mux.HandleFunc("GET /swap/new", s.auth(s.handleSwapNew))
mux.HandleFunc("POST /swap/request", s.auth(s.handleSwapRequestCreate))
mux.HandleFunc("GET /swap/requests/{id}", s.auth(s.handleSwapRequestView))
mux.HandleFunc("GET /swap/{token}", s.auth(s.handleSwapTokenView))
mux.HandleFunc("GET /swap/{token}/{action}", s.auth(s.handleSwapTokenAction))
mux.HandleFunc("POST /swap/{token}/respond", s.auth(s.handleSwapRespond))
mux.HandleFunc("GET /statistics", s.auth(s.handleStatistics))
mux.HandleFunc("GET /exchange", s.auth(s.handleExchange))
+88 -16
View File
@@ -41,6 +41,8 @@ type serviceDetailData struct {
HelperCandidates []domain.CandidateSuggestion
LectorAssigned []domain.Assignment
HelperAssigned []domain.Assignment
SwapMarks map[string]string
SwapCandidates map[string]bool
}
func (s *Server) handleServiceOrder(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
@@ -106,11 +108,22 @@ func (s *Server) handleServiceOrder(w http.ResponseWriter, r *http.Request, user
}
var editingSpecial *domain.ServiceOccurrence
if id := strings.TrimSpace(r.URL.Query().Get("edit_special")); id != "" {
for i := range specials {
if specials[i].ID == id {
copy := specials[i]
editingSpecial = &copy
break
if id == "new" {
date, ok := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("date")))
if !ok {
date = domain.Today()
}
editingSpecial = &domain.ServiceOccurrence{
Date: date, TimeMinutes: 18 * 60, Kind: domain.KindSpecial,
LectorsNeeded: 1, HelpersNeeded: 1,
}
} else {
for i := range specials {
if specials[i].ID == id {
copy := specials[i]
editingSpecial = &copy
break
}
}
}
}
@@ -187,18 +200,55 @@ func (s *Server) handleServiceDetail(w http.ResponseWriter, r *http.Request, use
}
detail.LectorOpen = withAssignments.OpenSlotsFor(domain.RoleLector)
detail.HelperOpen = withAssignments.OpenSlotsFor(domain.RoleHelper)
detail.SwapMarks, _ = s.store.PendingSwapAssignmentIDs(r.Context(), tenant.ID)
detail.SwapCandidates = map[string]bool{}
if requesterPersonID, linked := user.LinkedPerson(tenant.ID); linked && user.Role == store.RoleReader {
directory, err := s.store.ReaderDirectory(r.Context(), tenant.ID)
if err == nil {
readerByPerson := map[string]string{}
for _, entry := range directory {
readerByPerson[entry.Person.ID] = entry.UserID
}
for _, assignment := range assignments {
if assignment.PersonID == requesterPersonID {
continue
}
targetUserID, ok := readerByPerson[assignment.PersonID]
if !ok || service.Date.Before(domain.Today()) || service.Locked || assignment.Locked {
continue
}
if detail.SwapMarks[assignment.ID] != "" {
continue
}
if s.swapConsent(r.Context(), tenant.ID, user.ID, requesterPersonID,
targetUserID, assignment.PersonID) {
detail.SwapCandidates[assignment.ID] = true
}
}
}
}
if detail.LectorOpen > 0 {
detail.LectorCandidates = domain.CandidateSuggestions(*service, domain.RoleLector, people, absences,
rangeAssignments, rangeServices, assignments, false)
rangeAssignments, rangeServices, assignments, false, s.liturgicalDay(r, service.Date))
}
if detail.HelperOpen > 0 {
detail.HelperCandidates = domain.CandidateSuggestions(*service, domain.RoleHelper, people, absences,
rangeAssignments, rangeServices, assignments, false)
rangeAssignments, rangeServices, assignments, false, s.liturgicalDay(r, service.Date))
}
data.Data = detail
s.renderPage(w, r, "service", data)
}
// liturgicalDay loads the liturgical entry for one date so candidate lists and
// manual assignments can treat high feasts like Sundays.
func (s *Server) liturgicalDay(r *http.Request, date time.Time) *domain.LiturgicalDay {
days, err := s.store.LiturgicalDays(r.Context(), domain.NewDayRange(date, date))
if err != nil || len(days) == 0 {
return nil
}
return &days[0]
}
func (s *Server) serviceRange(r *http.Request, date time.Time) domain.DayRange {
start, startOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("start")))
end, endOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("end")))
@@ -251,9 +301,26 @@ func (s *Server) handleAssign(w http.ResponseWriter, r *http.Request, user *stor
return
}
locked := r.FormValue("locked") == "1" || r.FormValue("locked") == "on"
highFeast := false
if day := s.liturgicalDay(r, service.Date); day != nil {
highFeast = day.IsHighFeast()
}
beyond := !person.MatchesWeekdayPreference(domain.Weekday(service.Date), service.TimeMinutes, highFeast)
if !beyond && person.MaxPerMonth > 0 {
if monthAssignments, err := s.store.Assignments(r.Context(), tenant.ID, domain.MonthRange(service.Date)); err == nil {
used := 0
for _, existing := range monthAssignments {
if existing.PersonID == person.ID && existing.ServiceID != service.ID {
used++
}
}
beyond = used >= person.MaxPerMonth
}
}
assignment := domain.Assignment{
ID: domain.NewID(), ServiceID: service.ID, PersonID: person.ID,
Role: role, Locked: locked, Note: strings.TrimSpace(r.FormValue("note")),
Role: role, Locked: locked, BeyondPreferences: beyond,
Note: strings.TrimSpace(r.FormValue("note")),
}
if err := s.store.UpsertAssignment(r.Context(), tenant.ID, assignment); err != nil {
s.setFlash(w, "Die Einteilung konnte nicht gespeichert werden: "+err.Error(), "error")
@@ -344,18 +411,23 @@ func (s *Server) handleServiceDelete(w http.ResponseWriter, r *http.Request, use
s.redirect(w, r, "/plan")
return
}
if service.Kind == domain.KindRegular {
s.setFlash(w, "Regelmäßige Gottesdienste werden über die Gottesdienstordnung verwaltet und können nicht einzeln gelöscht werden.", "info")
if err := s.store.DeleteService(r.Context(), tenant.ID, id); err != nil {
s.setFlash(w, "Der Gottesdienst konnte nicht gelöscht werden.", "error")
s.redirectBack(w, r, "/plan")
return
}
if err := s.store.DeleteService(r.Context(), tenant.ID, id); err != nil {
s.setFlash(w, "Der Gottesdienst konnte nicht gelöscht werden.", "error")
s.redirectBack(w, r, "/services")
return
if service.Kind == domain.KindSpecial {
s.setFlash(w, "Sondergottesdienst gelöscht.", "success")
} else {
s.setFlash(w, "Gottesdienst gelöscht. Die Gottesdienstordnung bleibt unverändert.", "success")
}
s.setFlash(w, "Sondergottesdienst gelöscht.", "success")
s.redirectBack(w, r, "/services")
// The detail page no longer exists, so always return to the overview and
// keep the visible range when the caller supplied one.
target := "/plan"
if start, end := r.FormValue("start"), r.FormValue("end"); start != "" && end != "" {
target += "?start=" + start + "&end=" + end
}
s.redirect(w, r, target)
}
func (s *Server) handleSpecialServiceSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
+553
View File
@@ -0,0 +1,553 @@
package web
import (
"context"
"encoding/base64"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"lektorenplan/domain"
"lektorenplan/store"
)
// readerPairFixture prepares two linked reader accounts and one future
// assignment for each of them. The editor logs in after the accounts exist so
// that the initial key reconciliation grants every reader their own scope.
type readerPairFixture struct {
ts *httptest.Server
st *store.Store
tenantID string
editor *http.Client
anna *http.Client
markus *http.Client
annaUser *store.User
markUser *store.User
annaPass string
markPass string
annaJob domain.Assignment
markJob domain.Assignment
annaSvc domain.ServiceOccurrence
markSvc domain.ServiceOccurrence
}
// httptestServer was intentionally removed; the fixture uses *httptest.Server.
func newReaderPairFixture(t *testing.T) *readerPairFixture {
t.Helper()
ts, st := newTestServer(t)
ctx := context.Background()
tenant, err := st.TenantBySlug(ctx, "bad-godesberg")
if err != nil {
t.Fatalf("tenant: %v", err)
}
annaUser, err := st.CreateUser(ctx, "anna", "Anna Berg", "annaread123",
store.RoleReader, true, []string{tenant.ID})
if err != nil {
t.Fatalf("create anna: %v", err)
}
if err := st.SetUserPersonLink(ctx, annaUser.ID, tenant.ID, "p-anna"); err != nil {
t.Fatalf("link anna: %v", err)
}
markusUser, err := st.CreateUser(ctx, "markus", "Markus Weber", "markusread123",
store.RoleReader, true, []string{tenant.ID})
if err != nil {
t.Fatalf("create markus: %v", err)
}
if err := st.SetUserPersonLink(ctx, markusUser.ID, tenant.ID, "p-markus"); err != nil {
t.Fatalf("link markus: %v", err)
}
editor := newClient(t)
login(t, editor, ts.URL, "editor", "editor123")
anna := newClient(t)
login(t, anna, ts.URL, "anna", "annaread123")
markus := newClient(t)
login(t, markus, ts.URL, "markus", "markusread123")
fixture := &readerPairFixture{
ts: ts, st: st, tenantID: tenant.ID,
editor: editor, anna: anna, markus: markus,
annaUser: annaUser, markUser: markusUser,
annaPass: "annaread1231", markPass: "markusread1231",
}
// The demo seeds a cure for Markus that would hide the next days. Clear
// both volunteers so the fixture controls the only absence in a test.
for _, personID := range []string{"p-anna", "p-markus"} {
absences, err := st.AbsencesForPerson(ctx, tenant.ID, personID)
if err != nil {
t.Fatalf("absences for %s: %v", personID, err)
}
for _, absence := range absences {
if err := st.DeleteAbsence(ctx, tenant.ID, absence.ID); err != nil {
t.Fatalf("delete absence %s: %v", absence.ID, err)
}
}
}
annaDate := domain.AddingDays(1, domain.Today())
markDate := domain.AddingDays(2, domain.Today())
annaServiceID, err := st.UpsertService(ctx, tenant.ID, domain.ServiceOccurrence{
ID: "swap-service-anna", ChurchID: "c-andreas", Date: annaDate,
TimeMinutes: 9 * 60, Title: "Tauschprobe Anna", Kind: domain.KindSpecial,
LectorsNeeded: 1, CreatedAt: time.Now().UTC(),
})
if err != nil {
t.Fatalf("create anna service: %v", err)
}
markServiceID, err := st.UpsertService(ctx, tenant.ID, domain.ServiceOccurrence{
ID: "swap-service-markus", ChurchID: "c-evergislus", Date: markDate,
TimeMinutes: 10 * 60, Title: "Tauschprobe Markus", Kind: domain.KindSpecial,
LectorsNeeded: 1, CreatedAt: time.Now().UTC(),
})
if err != nil {
t.Fatalf("create markus service: %v", err)
}
fixture.annaJob = domain.Assignment{ID: "swap-assignment-anna", ServiceID: annaServiceID,
PersonID: "p-anna", Role: domain.RoleLector}
fixture.markJob = domain.Assignment{ID: "swap-assignment-markus", ServiceID: markServiceID,
PersonID: "p-markus", Role: domain.RoleLector}
for _, assignment := range []domain.Assignment{fixture.annaJob, fixture.markJob} {
if err := st.UpsertAssignment(ctx, tenant.ID, assignment); err != nil {
t.Fatalf("create assignment %s: %v", assignment.ID, err)
}
}
fixture.annaSvc, _ = serviceByID(t, st, tenant.ID, annaServiceID)
fixture.markSvc, _ = serviceByID(t, st, tenant.ID, markServiceID)
return fixture
}
func serviceByID(t *testing.T, st *store.Store, tenantID, id string) (domain.ServiceOccurrence, bool) {
t.Helper()
service, err := st.Service(context.Background(), tenantID, id)
if err != nil {
return domain.ServiceOccurrence{}, false
}
return *service, true
}
// shareContacts lets owner share their address with the given reader accounts.
func shareContacts(t *testing.T, client *http.Client, base string, viewerIDs ...string) {
t.Helper()
page := get(t, client, base+"/team", http.StatusOK)
form := url.Values{"csrf": {extractCSRF(t, page)}}
for _, viewerID := range viewerIDs {
form.Add("viewer", viewerID)
}
resp := postForm(t, client, base+"/team/sharing", form)
defer resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("save sharing = %d, want 303", resp.StatusCode)
}
}
func mutualShares(t *testing.T, f *readerPairFixture) {
t.Helper()
shareContacts(t, f.anna, f.ts.URL, f.markUser.ID)
shareContacts(t, f.markus, f.ts.URL, f.annaUser.ID)
}
func decodeFlash(t *testing.T, resp *http.Response) string {
t.Helper()
message := ""
for _, cookie := range resp.Cookies() {
if cookie.Name != flashCookie || cookie.Value == "" {
continue
}
data, err := base64.RawURLEncoding.DecodeString(cookie.Value)
if err != nil {
t.Fatalf("decode flash: %v", err)
}
// A second flash overwrites the first one; the client keeps the last
// Set-Cookie value.
message = string(data)
}
return message
}
func TestReaderContactSharingAndRevocation(t *testing.T) {
f := newReaderPairFixture(t)
before := get(t, f.markus, f.ts.URL+"/team", http.StatusOK)
if strings.Contains(before, "anna.berg@example.org") {
t.Fatal("reader sees an address that was not shared")
}
shareContacts(t, f.anna, f.ts.URL, f.markUser.ID)
after := get(t, f.markus, f.ts.URL+"/team", http.StatusOK)
if !strings.Contains(after, "anna.berg@example.org") {
t.Fatal("shared address is not visible to the other reader")
}
if !strings.Contains(after, "Freigegeben für Sie") {
t.Fatal("team page is missing the shared-with-me section")
}
// A shared scope survives the login policy pruning.
if err := f.st.PruneUserWrappers(context.Background(), f.markUser.ID); err != nil {
t.Fatalf("prune wrappers: %v", err)
}
scopes, err := f.st.ScopesForUser(context.Background(), f.markUser.ID)
if err != nil {
t.Fatalf("scopes: %v", err)
}
if !hasPersonScope(scopes, f.tenantID, "p-anna") {
t.Fatal("shared scope was pruned although the consent still exists")
}
// Revoking removes the wrapper and the open session loses the key.
shareContacts(t, f.anna, f.ts.URL)
revoked := get(t, f.markus, f.ts.URL+"/team", http.StatusOK)
if strings.Contains(revoked, "anna.berg@example.org") {
t.Fatal("address is still visible after revoking the share")
}
scopes, err = f.st.ScopesForUser(context.Background(), f.markUser.ID)
if err != nil {
t.Fatalf("scopes after revoke: %v", err)
}
if hasPersonScope(scopes, f.tenantID, "p-anna") {
t.Fatal("revoked scope is still wrapped for the reader")
}
}
func hasPersonScope(scopes []store.KeyScope, tenantID, personID string) bool {
for _, scope := range scopes {
if scope.Type == store.ScopePerson && scope.TenantID == tenantID && scope.ID == personID {
return true
}
}
return false
}
func TestReaderRosterChangeNotice(t *testing.T) {
f := newReaderPairFixture(t)
// One review makes the current reader directory known.
shareContacts(t, f.anna, f.ts.URL, f.markUser.ID)
page := get(t, f.anna, f.ts.URL+"/team", http.StatusOK)
if strings.Contains(page, "hat sich geändert") {
t.Fatal("roster notice appears without a roster change")
}
ctx := context.Background()
third, err := f.st.CreateUser(ctx, "jonas", "Jonas Schmitz", "jonasread123",
store.RoleReader, true, []string{f.tenantID})
if err != nil {
t.Fatalf("create third reader: %v", err)
}
if err := f.st.SetUserPersonLink(ctx, third.ID, f.tenantID, "p-johannes"); err != nil {
t.Fatalf("link third reader: %v", err)
}
page = get(t, f.anna, f.ts.URL+"/team", http.StatusOK)
if !strings.Contains(page, "Die Liste der Leserinnen und Leser hat sich geändert.") {
t.Fatal("persistent roster notice is missing")
}
// The hint is repeated as a login flash on the next sign-in.
relogin := newClient(t)
resp, err := relogin.PostForm(f.ts.URL+"/login", url.Values{
"username": {"anna"}, "password": {f.annaPass},
})
if err != nil {
t.Fatalf("relogin: %v", err)
}
resp.Body.Close()
flash := decodeFlash(t, resp)
if !strings.Contains(flash, "Liste der Lektoren und Kommunionhelfer hat sich geändert") {
t.Fatalf("login flash = %q, want roster notice", flash)
}
// Acknowledging keeps the existing shares but silences the notice.
page = get(t, relogin, f.ts.URL+"/team", http.StatusOK)
csrf := extractCSRF(t, page)
ack := postForm(t, relogin, f.ts.URL+"/team/sharing/ack", url.Values{"csrf": {csrf}})
ack.Body.Close()
if ack.StatusCode != http.StatusSeeOther {
t.Fatalf("ack = %d, want 303", ack.StatusCode)
}
page = get(t, relogin, f.ts.URL+"/team", http.StatusOK)
if strings.Contains(page, "Die Liste der Leserinnen und Leser hat sich geändert.") {
t.Fatal("roster notice is still shown after acknowledgement")
}
if !f.st.ContactShareExists(context.Background(), f.tenantID, "p-anna", f.markUser.ID) {
t.Fatal("acknowledging the roster dropped the existing share")
}
}
func createSwapRequest(t *testing.T, f *readerPairFixture) (requestID, token string) {
t.Helper()
page := get(t, f.anna, f.ts.URL+"/swap/new?assignment="+f.markJob.ID, http.StatusOK)
if !strings.Contains(page, f.markJob.ID) {
t.Fatalf("request page does not describe the wanted assignment:\n%s", page)
}
if !strings.Contains(page, f.annaJob.ID) {
t.Fatal("request page does not offer the own assignment")
}
csrf := extractCSRF(t, page)
resp := postForm(t, f.anna, f.ts.URL+"/swap/request", url.Values{
"csrf": {csrf},
"wanted": {f.markJob.ID},
"offered": {f.annaJob.ID},
})
defer resp.Body.Close()
if resp.StatusCode != http.StatusSeeOther {
t.Fatalf("create swap = %d, want 303", resp.StatusCode)
}
location := resp.Header.Get("Location")
parsed, err := url.Parse(location)
if err != nil {
t.Fatalf("parse redirect %q: %v", location, err)
}
requestID = strings.TrimPrefix(parsed.Path, "/swap/requests/")
token = parsed.Query().Get("token")
if requestID == "" || token == "" {
t.Fatalf("redirect %q is missing request id or token", location)
}
return requestID, token
}
func TestSwapRequestLifecycle(t *testing.T) {
f := newReaderPairFixture(t)
mutualShares(t, f)
// The reader sees a request button next to the other reader's assignment.
detail := get(t, f.anna, f.ts.URL+"/services/"+f.markSvc.ID, http.StatusOK)
if !strings.Contains(detail, "/swap/new?assignment="+f.markJob.ID) {
t.Fatal("service view is missing the swap request button")
}
requestID, token := createSwapRequest(t, f)
page := get(t, f.anna, f.ts.URL+"/swap/requests/"+requestID+"?token="+url.QueryEscape(token), http.StatusOK)
if !strings.Contains(page, "markus.weber@example.org") {
t.Fatal("request page does not offer a mail draft to the target address")
}
if strings.Count(page, token) < 2 || !strings.Contains(page, "Annehmen") || !strings.Contains(page, "Ablehnen") {
t.Fatal("request mail draft is missing the accept and decline links")
}
marks, err := f.st.PendingSwapAssignmentIDs(context.Background(), f.tenantID)
if err != nil {
t.Fatalf("pending marks: %v", err)
}
if marks[f.annaJob.ID] == "" || marks[f.markJob.ID] == "" {
t.Fatal("both assignments must be marked as swap-requested")
}
plan := get(t, f.anna, f.ts.URL+"/plan?start="+domain.Key(domain.Today())+
"&end="+domain.Key(domain.AddingDays(10, domain.Today())), http.StatusOK)
if !strings.Contains(plan, "Tausch angefragt") {
t.Fatal("plan does not mark the pending swap")
}
// The target can confirm and accept the swap.
targetPage := get(t, f.markus, f.ts.URL+"/swap/"+token, http.StatusOK)
if !strings.Contains(targetPage, "Möchten Sie tauschen?") {
t.Fatal("target does not see the response controls")
}
confirm := get(t, f.markus, f.ts.URL+"/swap/"+token+"/accept", http.StatusOK)
if !strings.Contains(confirm, "Tausch annehmen?") {
t.Fatal("accept confirmation page is missing")
}
csrf := extractCSRF(t, confirm)
response := postForm(t, f.markus, f.ts.URL+"/swap/"+token+"/respond", url.Values{
"csrf": {csrf},
"action": {"accept"},
})
response.Body.Close()
if response.StatusCode != http.StatusSeeOther {
t.Fatalf("accept = %d, want 303", response.StatusCode)
}
if !personHasAssignment(t, f.st, f.tenantID, "p-anna", f.markSvc.ID) {
t.Fatal("anna did not receive the wanted assignment")
}
if !personHasAssignment(t, f.st, f.tenantID, "p-markus", f.annaSvc.ID) {
t.Fatal("markus did not receive the offered assignment")
}
if assignmentPerson(t, f.st, f.tenantID, f.annaJob.ID) != "p-markus" {
t.Fatal("offered assignment was not transferred")
}
if assignmentPerson(t, f.st, f.tenantID, f.markJob.ID) != "p-anna" {
t.Fatal("wanted assignment was not transferred")
}
marks, err = f.st.PendingSwapAssignmentIDs(context.Background(), f.tenantID)
if err != nil {
t.Fatalf("pending marks after accept: %v", err)
}
if marks[f.annaJob.ID] != "" || marks[f.markJob.ID] != "" {
t.Fatal("accepted swap is still marked as pending")
}
// The target receives a response draft addressed to the requester.
result := get(t, f.markus, f.ts.URL+"/swap/"+token, http.StatusOK)
if !strings.Contains(result, "Antwort-E-Mail öffnen") {
t.Fatal("accepted request has no response mail draft")
}
if !strings.Contains(result, "anna.berg@example.org") {
t.Fatal("response draft does not use the requester address")
}
}
func TestSwapDeclineKeepsPlan(t *testing.T) {
f := newReaderPairFixture(t)
mutualShares(t, f)
_, token := createSwapRequest(t, f)
confirm := get(t, f.markus, f.ts.URL+"/swap/"+token+"/decline", http.StatusOK)
if !strings.Contains(confirm, "Tausch ablehnen?") {
t.Fatal("decline confirmation page is missing")
}
csrf := extractCSRF(t, confirm)
response := postForm(t, f.markus, f.ts.URL+"/swap/"+token+"/respond", url.Values{
"csrf": {csrf},
"action": {"decline"},
})
response.Body.Close()
if response.StatusCode != http.StatusSeeOther {
t.Fatalf("decline = %d, want 303", response.StatusCode)
}
if assignmentPerson(t, f.st, f.tenantID, f.annaJob.ID) != "p-anna" {
t.Fatal("decline changed the offered assignment")
}
if assignmentPerson(t, f.st, f.tenantID, f.markJob.ID) != "p-markus" {
t.Fatal("decline changed the wanted assignment")
}
marks, err := f.st.PendingSwapAssignmentIDs(context.Background(), f.tenantID)
if err != nil {
t.Fatalf("pending marks: %v", err)
}
if marks[f.annaJob.ID] != "" || marks[f.markJob.ID] != "" {
t.Fatal("declined swap is still marked as pending")
}
result := get(t, f.markus, f.ts.URL+"/swap/"+token, http.StatusOK)
if !strings.Contains(result, "Abgelehnt") && !strings.Contains(result, "abgelehnt") {
t.Fatal("result page does not show the declined state")
}
if !strings.Contains(result, "Antwort-E-Mail öffnen") {
t.Fatal("declined request has no response mail draft")
}
}
func TestAcceptRevalidatesAbsence(t *testing.T) {
f := newReaderPairFixture(t)
mutualShares(t, f)
_, token := createSwapRequest(t, f)
ctx := context.Background()
if err := f.st.UpsertAbsence(ctx, f.tenantID, domain.Absence{
ID: "late-absence", PersonID: "p-markus",
Start: f.annaSvc.Date, End: f.annaSvc.Date, Reason: "Kurzfristig krank",
}); err != nil {
t.Fatalf("create absence: %v", err)
}
if _, err := f.st.RespondSwapRequest(ctx, f.tenantID, token, f.markUser.ID, true); err == nil ||
!strings.Contains(err.Error(), "abwesend") {
t.Fatalf("accept error = %v, want absence rejection", err)
}
if assignmentPerson(t, f.st, f.tenantID, f.annaJob.ID) != "p-anna" {
t.Fatal("rejected acceptance still moved the offered assignment")
}
if assignmentPerson(t, f.st, f.tenantID, f.markJob.ID) != "p-markus" {
t.Fatal("rejected acceptance still moved the wanted assignment")
}
marks, err := f.st.PendingSwapAssignmentIDs(ctx, f.tenantID)
if err != nil {
t.Fatalf("pending marks: %v", err)
}
if marks[f.annaJob.ID] == "" || marks[f.markJob.ID] == "" {
t.Fatal("open request lost its plan marks after a rejected acceptance")
}
}
func TestRevokingConsentCancelsPendingSwap(t *testing.T) {
f := newReaderPairFixture(t)
mutualShares(t, f)
requestID, _ := createSwapRequest(t, f)
// Anna revokes the share; the pending request can no longer be answered
// and the plan markers must disappear.
shareContacts(t, f.anna, f.ts.URL)
request, err := f.st.SwapRequestByID(context.Background(), f.tenantID, requestID)
if err != nil {
t.Fatalf("load request: %v", err)
}
if request.Status != store.SwapCancelled {
t.Fatalf("request status = %q, want cancelled", request.Status)
}
marks, err := f.st.PendingSwapAssignmentIDs(context.Background(), f.tenantID)
if err != nil {
t.Fatalf("pending marks: %v", err)
}
if marks[f.annaJob.ID] != "" || marks[f.markJob.ID] != "" {
t.Fatal("cancelled swap is still marked as pending")
}
}
func TestSwapRequestRequiresMutualConsent(t *testing.T) {
f := newReaderPairFixture(t)
// Only the requester shares; the target has not shared the other way.
shareContacts(t, f.anna, f.ts.URL, f.markUser.ID)
get(t, f.anna, f.ts.URL+"/swap/new?assignment="+f.markJob.ID, http.StatusForbidden)
page := get(t, f.anna, f.ts.URL+"/services/"+f.markSvc.ID, http.StatusOK)
if strings.Contains(page, "/swap/new?assignment="+f.markJob.ID) {
t.Fatal("swap button is offered without mutual consent")
}
}
func TestSwapRejectsAbsence(t *testing.T) {
f := newReaderPairFixture(t)
mutualShares(t, f)
ctx := context.Background()
if err := f.st.UpsertAbsence(ctx, f.tenantID, domain.Absence{
ID: "swap-absence", PersonID: "p-markus",
Start: f.annaSvc.Date, End: f.annaSvc.Date, Reason: "Testabwesenheit",
}); err != nil {
t.Fatalf("create absence: %v", err)
}
_, _, err := f.st.CreateSwapRequest(ctx, f.tenantID, f.annaUser.ID,
"p-anna", f.markUser.ID, "p-markus", f.annaJob.ID, f.markJob.ID)
if err == nil || !strings.Contains(err.Error(), "abwesend") {
t.Fatalf("swap request error = %v, want absence rejection", err)
}
options, err := f.st.SwapOptions(ctx, f.tenantID, "p-anna", "p-markus", f.markJob.ID)
if err != nil {
t.Fatalf("swap options: %v", err)
}
if len(options) != 0 {
t.Fatalf("swap options = %d, want none while the target is absent", len(options))
}
}
func personHasAssignment(t *testing.T, st *store.Store, tenantID, personID, serviceID string) bool {
t.Helper()
assignments, err := st.AssignmentsForPerson(context.Background(), tenantID, personID)
if err != nil {
t.Fatalf("assignments for %s: %v", personID, err)
}
for _, assignment := range assignments {
if assignment.ServiceID == serviceID {
return true
}
}
return false
}
func assignmentPerson(t *testing.T, st *store.Store, tenantID, assignmentID string) string {
t.Helper()
info, err := st.SwapAssignmentInfo(context.Background(), tenantID, assignmentID)
if err != nil {
t.Fatalf("assignment %s: %v", assignmentID, err)
}
return info.Assignment.PersonID
}
+2
View File
@@ -50,6 +50,8 @@
show = parseInt(row.getAttribute("data-open") || "0", 10) > 0;
} else if (filter === "feasts") {
show = row.getAttribute("data-special") === "true";
} else if (filter === "beyond") {
show = row.getAttribute("data-beyond") === "true";
}
row.hidden = !show;
if (show) visible++;
+94
View File
@@ -963,3 +963,97 @@ hr { border: 0; border-top: 1px solid var(--line); margin: 1rem 0; }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
/* E-Mail-Freigaben und Tauschanfragen ------------------------------------- */
.sharing-card { display: flex; flex-direction: column; gap: .9rem; }
.sharing-intro { margin: 0; color: var(--ink-soft, #6b6257); line-height: 1.55; }
.sharing-notice {
display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem;
padding: .9rem 1rem; border-radius: 12px;
background: color-mix(in srgb, #c2a14d 16%, transparent);
border: 1px solid color-mix(in srgb, #c2a14d 42%, transparent);
}
.sharing-notice p { margin: .25rem 0 0; color: var(--ink-soft, #6b6257); }
.sharing-form { display: flex; flex-direction: column; gap: .8rem; }
.sharing-all { padding-bottom: .6rem; border-bottom: 1px dashed color-mix(in srgb, #6b6257 22%, transparent); }
.sharing-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: .35rem .9rem; }
.sharing-grid .check small { color: var(--ink-soft, #6b6257); }
.sharing-people { display: flex; flex-direction: column; gap: .55rem; }
.sharing-person {
display: flex; align-items: center; gap: .65rem; flex-wrap: wrap;
padding: .55rem .7rem; border-radius: 10px;
background: color-mix(in srgb, #2e5c57 6%, transparent);
}
.sharing-person-name { display: flex; flex-direction: column; min-width: 140px; }
.sharing-person-name small { color: var(--ink-soft, #6b6257); }
.sharing-person a { margin-left: auto; }
.swap-panel .swap-assignment { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .8rem; }
.swap-assignment > div { display: flex; flex-direction: column; gap: .15rem; }
.swap-assignment span { color: var(--ink-soft, #6b6257); }
.swap-option-list { display: flex; flex-direction: column; gap: .45rem; }
.swap-option {
display: flex; align-items: center; gap: .7rem;
padding: .65rem .8rem; border: 1px solid color-mix(in srgb, #6b6257 22%, transparent);
border-radius: 10px; cursor: pointer;
}
.swap-option:has(input:checked) { border-color: #2e5c57; background: color-mix(in srgb, #2e5c57 7%, transparent); }
.swap-option-main { display: flex; flex-direction: column; flex: 1; }
.swap-option-main span { color: var(--ink-soft, #6b6257); }
.swap-compare { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
.swap-actions { display: flex; flex-wrap: wrap; gap: .6rem; }
.swap-action-card { display: flex; flex-direction: column; gap: .5rem; }
.swap-action-card p { margin: 0; color: var(--ink-soft, #6b6257); }
.mail-card { border-color: color-mix(in srgb, #2e5c57 30%, transparent); }
.person-chip.swap-pending { outline: 1px dashed #b0833c; outline-offset: 1px; }
.swap-mark { margin-right: .15rem; color: #b0833c; font-weight: 700; }
@media (max-width: 760px) {
.swap-panel .swap-assignment, .swap-compare { grid-template-columns: 1fr; }
.sharing-notice { flex-direction: column; }
}
/* Präferenzen: Tageszeiten, Kürzel und Planung über Präferenzen hinaus */
.weekday-preference { display: flex; align-items: center; gap: .3rem; }
.weekday-period {
font-size: .66rem; padding: .22rem .3rem; border-radius: 6px;
border: 1px solid color-mix(in srgb, #6b6257 25%, transparent);
background: #fffdf7; color: var(--ink, #332f2a);
}
.person-note {
display: block; margin-top: .15rem; font-size: .68rem; line-height: 1.35;
color: var(--ink-soft, #6b6257); font-style: italic;
}
.candidate .person-note { max-width: 34rem; }
.person-chip.beyond-pref {
background: color-mix(in srgb, #8d3b4a 16%, #fffdf7);
color: var(--burgundy, #8d3b4a);
outline: 1px dashed color-mix(in srgb, #8d3b4a 55%, transparent);
outline-offset: 1px;
}
.beyond-mark { margin-right: .15rem; font-weight: 800; color: var(--burgundy, #8d3b4a); }
.beyond-prompt {
display: flex; align-items: center; justify-content: space-between; gap: 1.2rem;
flex-wrap: wrap; border-color: color-mix(in srgb, #b0833c 45%, transparent);
background: color-mix(in srgb, #c2a14d 10%, #fffdf7);
}
.beyond-prompt h3 { margin: .15rem 0 .35rem; }
.beyond-prompt p { margin: 0; max-width: 62ch; color: var(--ink-soft, #6b6257); }
.service-card-wrap { position: relative; }
.service-delete-form { position: absolute; top: -2px; right: -2px; }
.service-delete {
opacity: 0; transition: opacity .12s ease; width: 1.25rem; height: 1.25rem;
background: color-mix(in srgb, #fffdf7 88%, transparent);
}
.service-card-wrap:hover .service-delete, .service-delete:focus-visible { opacity: 1; }
.col-day-action { width: 2.2rem; }
.day-action { text-align: right; vertical-align: top; padding-top: .55rem; }
.day-special-add { width: 1.55rem; height: 1.55rem; color: var(--burgundy, #8d3b4a); }
.day-special-add-mobile { margin-bottom: .55rem; }
.icon-button.is-disabled { opacity: .35; pointer-events: none; }
.visually-hidden {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
@media (max-width: 760px) {
.beyond-prompt { flex-direction: column; align-items: flex-start; }
.service-delete { opacity: 1; }
}
+387
View File
@@ -0,0 +1,387 @@
package web
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"lektorenplan/domain"
"lektorenplan/store"
)
type swapAssignmentView struct {
Assignment domain.Assignment
Service domain.ServiceOccurrence
Church domain.Church
}
func (v swapAssignmentView) Exists() bool { return v.Assignment.ID != "" }
type swapRequestPageData struct {
Request *store.SwapRequest
Token string
RequesterPerson domain.Person
TargetPerson domain.Person
Offered swapAssignmentView
Wanted swapAssignmentView
StatusLabel string
CanRespond bool
Action string
ShowRequestMail bool
RequestMailto string
ResponseMailto string
ResponseUnavailable bool
}
type swapNewPageData struct {
Requester domain.Person
Target domain.Person
Wanted swapAssignmentView
Options []swapAssignmentView
}
func (s *Server) swapReader(user *store.User, tenant *store.Tenant) (string, bool) {
if tenant == nil || user == nil || user.Role != store.RoleReader {
return "", false
}
return user.LinkedPerson(tenant.ID)
}
func (s *Server) swapView(ctx context.Context, tenantID string, info store.SwapAssignmentInfo) swapAssignmentView {
view := swapAssignmentView{Assignment: info.Assignment, Service: info.Service}
if church, err := s.store.Church(ctx, tenantID, info.Service.ChurchID); err == nil {
view.Church = *church
} else {
view.Church = domain.Church{ID: info.Service.ChurchID, Name: "Unbekannte Kirche"}
}
return view
}
func (s *Server) swapConsent(ctx context.Context, tenantID, requesterUserID, requesterPersonID, targetUserID, targetPersonID string) bool {
return s.store.ContactShareExists(ctx, tenantID, targetPersonID, requesterUserID) &&
s.store.ContactShareExists(ctx, tenantID, requesterPersonID, targetUserID)
}
func (s *Server) swapRequestTarget(ctx context.Context, tenantID, personID string) (string, bool) {
return s.store.ReaderForPerson(ctx, tenantID, personID)
}
func (s *Server) handleSwapNew(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
requesterPersonID, ok := s.swapReader(user, tenant)
if !ok {
s.renderError(w, r, http.StatusForbidden, "Tausch",
"Nur verknüpfte Leser-Konten können Einsätze tauschen.")
return
}
wantedID := strings.TrimSpace(r.URL.Query().Get("assignment"))
// Load the wanted assignment first to determine the target person, then
// compute the selectable own assignments.
wantedInfo, err := s.store.SwapAssignmentInfo(r.Context(), tenant.ID, wantedID)
if err != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Dieser Einsatz wurde nicht gefunden.")
return
}
targetUserID, ok := s.swapRequestTarget(r.Context(), tenant.ID, wantedInfo.Assignment.PersonID)
if !ok {
s.renderError(w, r, http.StatusConflict, "Tausch",
"Für die angefragte Person ist kein Leser-Konto verknüpft.")
return
}
if !s.swapConsent(r.Context(), tenant.ID, user.ID, requesterPersonID, targetUserID, wantedInfo.Assignment.PersonID) {
s.renderError(w, r, http.StatusForbidden, "Tausch",
"Für eine Tauschanfrage müssen beide Seiten ihre E-Mail-Adresse gegenseitig freigegeben haben. "+
"Prüfen Sie die Einstellungen unter „Team & Abwesenheiten“.")
return
}
options, err := s.store.SwapOptions(r.Context(), tenant.ID, requesterPersonID,
wantedInfo.Assignment.PersonID, wantedID)
if err != nil {
s.renderError(w, r, http.StatusConflict, "Tausch", err.Error())
return
}
requester, err := s.store.Person(r.Context(), tenant.ID, requesterPersonID)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Tausch", err.Error())
return
}
target, err := s.store.Person(r.Context(), tenant.ID, wantedInfo.Assignment.PersonID)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "Tausch", err.Error())
return
}
page := swapNewPageData{
Requester: *requester,
Target: *target,
Wanted: s.swapView(r.Context(), tenant.ID, *wantedInfo),
}
for _, option := range options {
page.Options = append(page.Options, s.swapView(r.Context(), tenant.ID, option))
}
data := s.baseView(w, r, "Tausch anfragen", "team")
data.Data = page
s.renderPage(w, r, "swap_request", data)
}
func (s *Server) handleSwapRequestCreate(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
requesterPersonID, ok := s.swapReader(user, tenant)
if !ok {
s.renderError(w, r, http.StatusForbidden, "Tausch",
"Nur verknüpfte Leser-Konten können Einsätze tauschen.")
return
}
wantedID := strings.TrimSpace(r.FormValue("wanted"))
offeredID := strings.TrimSpace(r.FormValue("offered"))
wantedInfo, err := s.store.SwapAssignmentInfo(r.Context(), tenant.ID, wantedID)
if err != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Der gewünschte Einsatz wurde nicht gefunden.")
return
}
if wantedInfo.Assignment.PersonID == requesterPersonID {
s.renderError(w, r, http.StatusBadRequest, "Tausch", "Ein Tausch mit sich selbst ist nicht möglich.")
return
}
targetUserID, ok := s.swapRequestTarget(r.Context(), tenant.ID, wantedInfo.Assignment.PersonID)
if !ok {
s.renderError(w, r, http.StatusConflict, "Tausch",
"Für die angefragte Person ist kein Leser-Konto verknüpft.")
return
}
if !s.swapConsent(r.Context(), tenant.ID, user.ID, requesterPersonID, targetUserID, wantedInfo.Assignment.PersonID) {
s.renderError(w, r, http.StatusForbidden, "Tausch",
"Für eine Tauschanfrage müssen beide Seiten ihre E-Mail-Adresse gegenseitig freigegeben haben.")
return
}
request, token, err := s.store.CreateSwapRequest(r.Context(), tenant.ID, user.ID,
requesterPersonID, targetUserID, wantedInfo.Assignment.PersonID, offeredID, wantedID)
if err != nil {
s.renderError(w, r, http.StatusConflict, "Tausch", err.Error())
return
}
s.redirect(w, r, "/swap/requests/"+request.ID+"?token="+url.QueryEscape(token))
}
func (s *Server) handleSwapRequestView(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
request, err := s.store.SwapRequestByID(r.Context(), tenant.ID, r.PathValue("id"))
if err != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Diese Tauschanfrage wurde nicht gefunden.")
return
}
if request.RequesterUserID != user.ID && request.TargetUserID != user.ID {
s.renderError(w, r, http.StatusForbidden, "Tausch", "Diese Tauschanfrage gehört nicht zu Ihrem Konto.")
return
}
token := strings.TrimSpace(r.URL.Query().Get("token"))
if token != "" && store.SwapTokenMatches(request, token) {
s.renderSwapPage(w, r, user, tenant, request, token, "")
return
}
s.renderSwapPage(w, r, user, tenant, request, "", "")
}
func (s *Server) handleSwapTokenView(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
token := strings.TrimSpace(r.PathValue("token"))
request, err := s.store.SwapRequestByToken(r.Context(), tenant.ID, token)
if err != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Diese Tauschanfrage wurde nicht gefunden oder ist abgelaufen.")
return
}
if request.RequesterUserID != user.ID && request.TargetUserID != user.ID {
s.renderError(w, r, http.StatusForbidden, "Tausch", "Diese Tauschanfrage gehört nicht zu Ihrem Konto.")
return
}
s.renderSwapPage(w, r, user, tenant, request, token, "")
}
func (s *Server) handleSwapTokenAction(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
action := strings.TrimSpace(r.PathValue("action"))
if action != "accept" && action != "decline" {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Unbekannte Aktion.")
return
}
token := strings.TrimSpace(r.PathValue("token"))
request, err := s.store.SwapRequestByToken(r.Context(), tenant.ID, token)
if err != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Diese Tauschanfrage wurde nicht gefunden oder ist abgelaufen.")
return
}
if request.TargetUserID != user.ID {
s.renderError(w, r, http.StatusForbidden, "Tausch", "Diese Tauschanfrage richtet sich an ein anderes Konto.")
return
}
if request.Status != store.SwapPending {
s.setFlash(w, "Diese Tauschanfrage ist bereits "+store.SwapStatusLabel(request.Status)+".", "info")
s.redirect(w, r, "/swap/"+token)
return
}
s.renderSwapPage(w, r, user, tenant, request, token, action)
}
func (s *Server) handleSwapRespond(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.renderNoTenant(w, r)
return
}
token := strings.TrimSpace(r.PathValue("token"))
action := strings.TrimSpace(r.FormValue("action"))
if action != "accept" && action != "decline" {
s.renderError(w, r, http.StatusBadRequest, "Tausch", "Unbekannte Aktion.")
return
}
request, err := s.store.SwapRequestByToken(r.Context(), tenant.ID, token)
if err != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Diese Tauschanfrage wurde nicht gefunden oder ist abgelaufen.")
return
}
if request.TargetUserID != user.ID {
s.renderError(w, r, http.StatusForbidden, "Tausch", "Diese Tauschanfrage richtet sich an ein anderes Konto.")
return
}
if _, err := s.store.RespondSwapRequest(r.Context(), tenant.ID, token, user.ID, action == "accept"); err != nil {
s.setFlash(w, "Die Tauschanfrage konnte nicht beantwortet werden: "+err.Error(), "error")
s.redirect(w, r, "/swap/"+token)
return
}
if action == "accept" {
s.setFlash(w, "Der Tausch wurde durchgeführt. Der Plan ist aktualisiert.", "success")
} else {
s.setFlash(w, "Die Tauschanfrage wurde abgelehnt. Der Plan bleibt unverändert.", "success")
}
s.redirect(w, r, "/swap/"+token)
}
func (s *Server) renderSwapPage(w http.ResponseWriter, r *http.Request, user *store.User, tenant *store.Tenant, request *store.SwapRequest, token, action string) {
requester, requesterErr := s.store.Person(r.Context(), tenant.ID, request.RequesterPersonID)
target, targetErr := s.store.Person(r.Context(), tenant.ID, request.TargetPersonID)
if requesterErr != nil || targetErr != nil {
s.renderError(w, r, http.StatusNotFound, "Tausch", "Die an der Tauschanfrage beteiligten Personen wurden nicht gefunden.")
return
}
page := swapRequestPageData{
Request: request,
Token: token,
RequesterPerson: *requester,
TargetPerson: *target,
StatusLabel: store.SwapStatusLabel(request.Status),
Action: action,
}
if offered, err := s.store.SwapAssignmentInfo(r.Context(), tenant.ID, request.OfferedAssignmentID); err == nil {
page.Offered = s.swapView(r.Context(), tenant.ID, *offered)
}
if wanted, err := s.store.SwapAssignmentInfo(r.Context(), tenant.ID, request.WantedAssignmentID); err == nil {
page.Wanted = s.swapView(r.Context(), tenant.ID, *wanted)
}
isRequester := request.RequesterUserID == user.ID
isTarget := request.TargetUserID == user.ID
page.CanRespond = isTarget && request.Status == store.SwapPending && token != ""
if isRequester && request.Status == store.SwapPending && token != "" && target.Email != "" {
page.ShowRequestMail = true
acceptURL := s.absoluteURL(r, "/swap/"+token+"/accept")
declineURL := s.absoluteURL(r, "/swap/"+token+"/decline")
subject := "Tauschanfrage: " + swapAssignmentSummary(page.Offered)
body := swapRequestEmailBody(*requester, *target, page.Offered, page.Wanted, acceptURL, declineURL)
page.RequestMailto = dispatchMailto(target.Email, subject, body)
}
if isTarget && (request.Status == store.SwapAccepted || request.Status == store.SwapDeclined) {
if requester.Email != "" {
subject := "Antwort auf die Tauschanfrage: " + swapAssignmentSummary(page.Wanted)
body := swapResponseEmailBody(*target, *requester, page.Offered, page.Wanted, request.Status)
page.ResponseMailto = dispatchMailto(requester.Email, subject, body)
} else {
page.ResponseUnavailable = true
}
}
data := s.baseView(w, r, "Tausch", "team")
data.Data = page
s.renderPage(w, r, "swap_detail", data)
}
func (s *Server) absoluteURL(r *http.Request, path string) string {
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if proto := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0]); proto != "" {
scheme = proto
}
host := r.Host
if forwarded := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Host"), ",")[0]); forwarded != "" {
host = forwarded
}
return scheme + "://" + host + path
}
func swapAssignmentSummary(view swapAssignmentView) string {
if !view.Exists() {
return "Einsatz"
}
date := domain.LongString(view.Service.Date)
if view.Service.Title != "" {
return date + " · " + view.Service.Title
}
return date
}
func swapAssignmentLine(view swapAssignmentView) string {
if !view.Exists() {
return "Der Einsatz ist nicht mehr vorhanden."
}
church := view.Church.Name
if church == "" {
church = "Kirche unbekannt"
}
return fmt.Sprintf("%s, %s Uhr · %s\n %s (%s)",
domain.LongString(view.Service.Date), domain.TimeString(view.Service.TimeMinutes),
church, view.Service.Title, view.Assignment.Role.Title())
}
func swapRequestEmailBody(requester, target domain.Person, offered, wanted swapAssignmentView, acceptURL, declineURL string) string {
return strings.Join([]string{
"Guten Tag " + target.FullName() + ",",
requester.FullName() + " möchte mit Ihnen einen Dienst tauschen.",
"Ihr Einsatz, den " + requester.FullName() + " übernehmen würde:\n" + swapAssignmentLine(wanted),
"Der angebotene Einsatz von " + requester.FullName() + ":\n" + swapAssignmentLine(offered),
"Bitte antworten Sie nach der Anmeldung über einen dieser Links:\n\n" +
"Annehmen: " + acceptURL + "\n" +
"Ablehnen: " + declineURL,
"Der Plan wird erst geändert, nachdem Sie den Tausch auf der Bestätigungsseite angenommen haben.",
"Mit freundlichen Grüßen\nIhr Planungsteam",
}, "\n\n")
}
func swapResponseEmailBody(target, requester domain.Person, offered, wanted swapAssignmentView, status string) string {
answer := "angenommen"
if status == store.SwapDeclined {
answer = "abgelehnt"
}
return strings.Join([]string{
"Guten Tag " + requester.FullName() + ",",
target.FullName() + " hat Ihre Tauschanfrage " + answer + ".",
"Ihr angebotener Einsatz:\n" + swapAssignmentLine(offered),
"Der gewünschte Einsatz:\n" + swapAssignmentLine(wanted),
"Bei Annahme ist der Plan bereits aktualisiert. Bei Ablehnung bleibt der Plan unverändert.",
"Mit freundlichen Grüßen\nIhr Planungsteam",
}, "\n\n")
}
+152 -3
View File
@@ -1,6 +1,7 @@
package web
import (
"context"
"net/http"
"sort"
"strings"
@@ -39,6 +40,21 @@ type teamPageData struct {
LectorCount int
HelperCount int
Year int
Sharing *contactSharingData
}
type contactShareReader struct {
UserID string
Person domain.Person
Shared bool
}
type contactSharingData struct {
Owner domain.Person
Readers []contactShareReader
SharedWithMe []domain.Person
RosterChanged bool
RosterKnown bool
}
type personAssignmentRow struct {
@@ -55,6 +71,7 @@ type personPageData struct {
Assignments []personAssignmentRow
Stats domain.PersonStat
Weekdays []weekdayOption
Periods []domain.WeekdayPeriod
CanEdit bool
CanManageAll bool
CanEditContact bool
@@ -156,11 +173,134 @@ func (s *Server) handleTeam(w http.ResponseWriter, r *http.Request, user *store.
page.HelperCount++
}
}
if !canManageAll {
linkedID, _ := user.LinkedPerson(tenant.ID)
if linkedID != "" {
sharing, err := s.contactSharingData(r.Context(), tenant.ID, user, linkedID)
if err != nil {
s.renderError(w, r, http.StatusInternalServerError, "E-Mail-Freigaben", err.Error())
return
}
page.Sharing = sharing
}
}
data := s.baseView(w, r, "Team", "team")
data.Data = page
s.renderPage(w, r, "team", data)
}
// contactSharingData prepares the reader self-service card: whom the owner has
// shared their address with and who shared an address with the owner.
func (s *Server) contactSharingData(ctx context.Context, tenantID string, user *store.User, ownerPersonID string) (*contactSharingData, error) {
directory, err := s.store.ReaderDirectory(ctx, tenantID)
if err != nil {
return nil, err
}
grants, err := s.store.ContactSharesForOwner(ctx, tenantID, ownerPersonID)
if err != nil {
return nil, err
}
sharedWithMe, err := s.store.ContactSharesForViewer(ctx, tenantID, user.ID)
if err != nil {
return nil, err
}
out := &contactSharingData{}
readerByPerson := map[string]domain.Person{}
for _, entry := range directory {
readerByPerson[entry.Person.ID] = entry.Person
if entry.Person.ID == ownerPersonID {
out.Owner = entry.Person
continue
}
out.Readers = append(out.Readers, contactShareReader{
UserID: entry.UserID, Person: entry.Person, Shared: grants[entry.UserID],
})
}
for _, personID := range sharedWithMe {
if person, ok := readerByPerson[personID]; ok {
out.SharedWithMe = append(out.SharedWithMe, person)
}
}
changed, known, err := s.store.ContactRosterChanged(ctx, tenantID, user.ID, ownerPersonID)
if err != nil {
return nil, err
}
out.RosterChanged = changed
out.RosterKnown = known
return out, nil
}
func (s *Server) handleContactSharesSave(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.redirect(w, r, "/plan")
return
}
ownerPersonID, linked := user.LinkedPerson(tenant.ID)
if user.Role != store.RoleReader || !linked {
s.renderError(w, r, http.StatusForbidden, "E-Mail-Freigaben",
"E-Mail-Freigaben können nur verknüpfte Leser-Konten verwalten.")
return
}
directory, err := s.store.ReaderDirectory(r.Context(), tenant.ID)
if err != nil {
s.setFlash(w, "Die Freigaben konnten nicht geladen werden.", "error")
s.redirect(w, r, "/team")
return
}
var selected []string
if r.FormValue("share_all") == "1" {
for _, entry := range directory {
if entry.UserID != user.ID {
selected = append(selected, entry.UserID)
}
}
} else {
selected = r.Form["viewer"]
}
added, removed, err := s.store.SetContactShares(r.Context(), store.KeyringFrom(r.Context()),
tenant.ID, user.ID, ownerPersonID, selected)
if err != nil {
s.setFlash(w, "Die Freigaben konnten nicht gespeichert werden: "+err.Error(), "error")
s.redirect(w, r, "/team")
return
}
if len(removed) > 0 {
s.forgetCachedScopeForUsers(store.KeyScope{Type: store.ScopePerson, TenantID: tenant.ID, ID: ownerPersonID}, removed)
}
if err := s.store.MarkContactRosterReviewed(r.Context(), tenant.ID, user.ID, ownerPersonID); err != nil {
s.setFlash(w, "Die Freigaben wurden gespeichert, die Prüfmarke konnte aber nicht aktualisiert werden.", "error")
s.redirect(w, r, "/team")
return
}
s.refreshCachedKeyrings(r.Context())
if len(added) == 0 && len(removed) == 0 {
s.setFlash(w, "Die E-Mail-Freigaben sind unverändert.", "info")
} else {
s.setFlash(w, "E-Mail-Freigaben gespeichert: "+plural(len(added), "neue Freigabe", "neue Freigaben")+
", "+plural(len(removed), "entzogene Freigabe", "entzogene Freigaben")+".", "success")
}
s.redirect(w, r, "/team")
}
func (s *Server) handleContactRosterAck(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
if tenant == nil {
s.redirect(w, r, "/plan")
return
}
ownerPersonID, linked := user.LinkedPerson(tenant.ID)
if user.Role != store.RoleReader || !linked {
s.renderError(w, r, http.StatusForbidden, "E-Mail-Freigaben",
"E-Mail-Freigaben können nur verknüpfte Leser-Konten verwalten.")
return
}
if err := s.store.MarkContactRosterReviewed(r.Context(), tenant.ID, user.ID, ownerPersonID); err != nil {
s.setFlash(w, "Die Prüfmarke konnte nicht gespeichert werden.", "error")
} else {
s.setFlash(w, "Die geänderte Leserliste wurde zur Kenntnis genommen. Ihre Freigaben bleiben unverändert.", "success")
}
s.redirect(w, r, "/team")
}
func blankPerson() domain.Person {
return domain.Person{
ID: domain.NewID(), Roles: []domain.Role{domain.RoleLector},
@@ -256,7 +396,7 @@ func (s *Server) handlePerson(w http.ResponseWriter, r *http.Request, user *stor
}
page := personPageData{
Person: person, IsNew: isNew, Absences: absences, Churches: churches,
Assignments: rows, Weekdays: weekdays,
Assignments: rows, Weekdays: weekdays, Periods: domain.AllWeekdayPeriods,
CanEdit: canManageAll || !isNew, CanManageAll: canManageAll,
CanEditContact: canManageContacts,
OwnContact: ownContact,
@@ -336,18 +476,27 @@ func (s *Server) handlePersonSave(w http.ResponseWriter, r *http.Request, user *
return
}
person := domain.Person{
ID: id, FirstName: strings.TrimSpace(r.FormValue("first_name")),
LastName: strings.TrimSpace(r.FormValue("last_name")), Roles: roles,
ID: id, ShortCode: strings.TrimSpace(r.FormValue("short_code")),
FirstName: strings.TrimSpace(r.FormValue("first_name")),
LastName: strings.TrimSpace(r.FormValue("last_name")), Roles: roles,
Email: strings.TrimSpace(r.FormValue("email")),
PreferredChurchIDs: r.Form["preferred_churches"],
PreferredServiceTitles: splitList(r.FormValue("preferred_titles")),
MaxPerMonth: parseInt(r.FormValue("max_per_month"), 6),
AllowBeyondPreferences: r.FormValue("allow_beyond_preferences") == "1" || r.FormValue("allow_beyond_preferences") == "on",
Active: r.FormValue("active") == "1" || r.FormValue("active") == "on",
Notes: strings.TrimSpace(r.FormValue("notes")),
}
for _, raw := range r.Form["preferred_weekdays"] {
if value := parseInt(raw, 0); value >= 1 && value <= 7 {
person.PreferredWeekdays = append(person.PreferredWeekdays, value)
period := domain.WeekdayPeriod(strings.TrimSpace(r.FormValue("weekday_period_" + raw)))
if !period.IsValid() {
period = domain.PeriodAllDay
}
person.PreferredWeekdayPeriods = append(person.PreferredWeekdayPeriods, domain.WeekdayPeriodPreference{
Weekday: value, Period: period,
})
}
}
if existing != nil {
+9 -9
View File
@@ -4,7 +4,7 @@
<div>
<span class="eyebrow">Öffentlicher Plan · {{.Data.TenantName}}</span>
<h2>{{rangeLong .Data.Range}}</h2>
<p>Alle Gottesdienste mit liturgischen Angaben und Lesungsverweisen – ohne Namen der eingesetzten Personen, ohne Einstellungen und ohne Schreibzugriffe.</p>
<p>Alle Gottesdienste mit liturgischen Angaben und Lesungsverweisen – ohne vollständige Namen, ohne Einstellungen und ohne Schreibzugriffe. Lektoren und Kommunionhelfer erscheinen mit Kürzel oder Initialen.</p>
</div>
<div class="intro-actions">
{{if gt (len .Data.Tenants) 1}}
@@ -23,17 +23,17 @@
<section class="toolbar card">
<div class="toolbar-group range-nav">
<a class="icon-button" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.PrevStart}}&amp;end={{.Data.PrevEnd}}" title="Vorheriger Monat">{{icon "left"}}</a>
{{if .Data.CanPrev}}<a class="icon-button" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.PrevStart}}&amp;end={{.Data.PrevEnd}}" title="Vorheriger Zeitraum">{{icon "left"}}</a>{{else}}<span class="icon-button is-disabled" title="Keine früheren Planungsdaten">{{icon "left"}}</span>{{end}}
<form class="range-form" method="get" action="/guest">
<input type="hidden" name="tid" value="{{.Data.TenantID}}">
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}"></label>
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}"></label>
<label class="field field-inline"><span>Von</span><input type="date" name="start" value="{{.Data.Start}}" min="{{.Data.MinDate}}" max="{{.Data.MaxDate}}"></label>
<label class="field field-inline"><span>Bis</span><input type="date" name="end" value="{{.Data.End}}" min="{{.Data.MinDate}}" max="{{.Data.MaxDate}}"></label>
<button class="btn btn-secondary btn-small" type="submit">Anzeigen</button>
</form>
<a class="icon-button" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.NextStart}}&amp;end={{.Data.NextEnd}}" title="Nächster Monat">{{icon "right"}}</a>
{{if .Data.CanNext}}<a class="icon-button" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.NextStart}}&amp;end={{.Data.NextEnd}}" title="Nächster Zeitraum">{{icon "right"}}</a>{{else}}<span class="icon-button is-disabled" title="Keine späteren Planungsdaten">{{icon "right"}}</span>{{end}}
</div>
<div class="toolbar-group">
<a class="chip" href="/guest?tid={{.Data.TenantID}}">{{icon "calendar"}} Dieser Monat</a>
<a class="chip" href="/guest?tid={{.Data.TenantID}}&amp;start={{.Data.DefaultStart}}&amp;end={{.Data.DefaultEnd}}">{{icon "calendar"}} Aktuelle 4 Wochen</a>
</div>
</section>
@@ -118,7 +118,7 @@
{{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
<span class="service-people">
{{range .Assignments}}
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}">{{roleTitle .Role}}</span>
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}">{{with index $.Data.PersonLabels .PersonID}}{{.}}{{else}}?{{end}}</span>
{{end}}
</span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
@@ -198,7 +198,7 @@
{{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
<span class="service-people">
{{range .Assignments}}
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}">{{roleTitle .Role}}</span>
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}">{{with index $.Data.PersonLabels .PersonID}}{{.}}{{else}}?{{end}}</span>
{{end}}
</span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
@@ -215,6 +215,6 @@
<p class="plan-mobile-empty empty-note" data-plan-mobile-empty hidden>Keine Tage passen zu diesem Filter.</p>
</div>
</section>
<p class="table-note">Gastansicht: Die Einsätze werden nur mit ihrer Rolle angezeigt. Liturgische Daten von www.eucharistiefeier.de, Lesungen verlinkt zu Schott.</p>
<p class="table-note">Gastansicht: Die Einsätze werden mit Kürzel oder Initialen angezeigt; vollständige Namen und Kontaktdaten bleiben verborgen. Liturgische Daten von www.eucharistiefeier.de, Lesungen verlinkt zu Schott.</p>
</div>
{{end}}
+12 -4
View File
@@ -39,6 +39,7 @@
<label class="field"><span class="field-label">Vorname</span><input type="text" name="first_name" value="{{$person.FirstName}}"></label>
<label class="field"><span class="field-label">Nachname</span><input type="text" name="last_name" value="{{$person.LastName}}"></label>
</div>
<label class="field"><span class="field-label">Kürzel <small>optional, erscheint in der Gastansicht statt der Initialen</small></span><input type="text" name="short_code" value="{{$person.ShortCode}}" maxlength="8" placeholder="z. B. AB"></label>
<div class="form-row">
<label class="field"><span class="field-label">E-Mail{{if not .Data.CanEditContact}} <small>{{if .Data.OwnContact}}noch nicht freigegeben{{else}}nur Redakteure{{end}}</small>{{else if $person.EmailLocked}} <small>gesperrt</small>{{end}}</span><input type="email" name="email" value="{{$person.Email}}" {{if not .Data.CanEditContact}}disabled placeholder="{{if .Data.OwnContact}}Wird nach der Einrichtung durch einen Redakteur freigegeben{{else}}Wird nur von Redakteuren verwaltet{{end}}"{{else if $person.EmailLocked}}placeholder="Verschlüsselt – zum Ändern neu eingeben"{{end}}></label>
</div>
@@ -58,10 +59,15 @@
</div>
</div>
<div class="field-group">
<span class="field-label">Bevorzugte Einsatztage</span>
<span class="field-label">Bevorzugte Einsatztage <small>Hochfeste gelten zusätzlich als Sonntag</small></span>
<div class="weekday-grid">
{{range .Data.Weekdays}}
<label class="weekday-check"><input type="checkbox" name="preferred_weekdays" value="{{.Number}}" {{if containsInt $person.PreferredWeekdays .Number}}checked{{end}}><span>{{.Short}}</span></label>
{{range $weekday := .Data.Weekdays}}
<div class="weekday-preference">
<label class="weekday-check"><input type="checkbox" name="preferred_weekdays" value="{{$weekday.Number}}" {{if containsInt $person.PreferredWeekdays $weekday.Number}}checked{{end}}><span>{{$weekday.Short}}</span></label>
<select name="weekday_period_{{$weekday.Number}}" class="weekday-period" aria-label="Tageszeit für {{$weekday.Name}}">
{{range $.Data.Periods}}<option value="{{.}}" {{if eq ($person.WeekdayPeriodFor $weekday.Number) .}}selected{{end}}>{{.ShortLabel}}</option>{{end}}
</select>
</div>
{{end}}
</div>
</div>
@@ -72,12 +78,14 @@
<label class="check standalone"><input type="checkbox" name="active" value="1" {{if $person.Active}}checked{{end}} {{if not .Data.CanManageAll}}disabled{{end}}><span>aktiv und planbar</span></label>
</label>
</div>
<label class="field"><span class="field-label">Notizen</span><textarea name="notes" rows="3">{{$person.Notes}}</textarea></label>
<label class="check"><input type="checkbox" name="allow_beyond_preferences" value="1" {{if $person.AllowBeyondPreferences}}checked{{end}}><span>Diese Person darf nach Rückfrage auch über ihre Präferenzen hinaus eingeplant werden</span></label>
<label class="field"><span class="field-label">Notizen <small>erscheinen in der Dienstplanung bei Einsätzen und Vorschlägen</small></span><textarea name="notes" rows="3">{{$person.Notes}}</textarea></label>
<button class="btn btn-primary" type="submit">{{if .Data.IsNew}}Person anlegen{{else}}Person speichern{{end}}</button>
</form>
{{else}}
<dl class="detail-list">
<dt>Name</dt><dd>{{$person.FullName}}</dd>
{{if $person.ShortCode}}<dt>Kürzel</dt><dd>{{$person.ShortCode}}</dd>{{end}}
<dt>Dienste</dt><dd>{{$person.RoleLabel}}</dd>
{{if $person.Email}}<dt>E-Mail</dt><dd>{{$person.Email}}</dd>{{end}}
{{if $person.EmailLocked}}<dt>Kontaktdaten</dt><dd>verschlüsselt und für dieses Konto nicht entsperrt</dd>{{end}}
+54 -4
View File
@@ -93,6 +93,23 @@
</div>
</section>
{{if .Data.PromptBeyond}}
<section class="beyond-prompt card">
<div>
<span class="eyebrow">Rückfrage zur Planung</span>
<h3>{{.Data.BeyondOpen}} {{plural .Data.BeyondOpen "Dienst bleibt" "Dienste bleiben"}} offen</h3>
<p>Es gibt Personen, die ausdrücklich bereit sind, auch über ihre Präferenzen hinaus eingeplant zu werden. Sollen sie für die verbleibenden Dienste eingesetzt werden? Die Einsätze werden im Plan besonders gekennzeichnet.</p>
</div>
<form method="post" action="/plan/auto" class="inline-form">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<input type="hidden" name="start" value="{{.Data.Start}}">
<input type="hidden" name="end" value="{{.Data.End}}">
<input type="hidden" name="beyond" value="1">
<button class="btn btn-primary btn-small" type="submit">{{icon "sparkles"}} Ja, freigegebene Personen einplanen</button>
</form>
</section>
{{end}}
<section class="stat-strip">
<article class="mini-stat">
<span class="mini-stat-label">Gottesdienste</span>
@@ -122,11 +139,13 @@
<button class="chip" type="button" data-plan-filter="services">Mit Gottesdiensten</button>
<button class="chip" type="button" data-plan-filter="open">Nur offene</button>
<button class="chip" type="button" data-plan-filter="feasts">Sonn- &amp; Feiertage</button>
<button class="chip" type="button" data-plan-filter="beyond">Über Präferenzen</button>
</div>
<div class="legend-items">
<span><i class="swatch sunday"></i>Sonntag</span>
<span><i class="swatch feast"></i>Hochfest</span>
<span><i class="swatch open"></i>Offener Dienst</span>
<span><span class="beyond-mark">↑</span>Über Präferenzen</span>
</div>
</div>
@@ -145,6 +164,7 @@
</span>
</th>
{{end}}
<th class="col-day-action"><span class="visually-hidden">Aktionen</span></th>
</tr>
</thead>
<tbody>
@@ -153,7 +173,8 @@
data-plan-row
data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
data-open="{{.OpenSlots}}"
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}">
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}"
data-beyond="{{if .HasBeyondPreferences}}true{{else}}false{{end}}">
<td class="date-cell">
<div class="date-number">{{dayNumber .Date}}</div>
<div class="date-meta"><span>{{shortWeekday .Date}}</span><span>{{shortMonth .Date}}</span></div>
@@ -185,6 +206,7 @@
{{if $services}}
<div class="service-stack">
{{range $services}}
<div class="service-card-wrap">
<a class="service-card {{if .IsFullyStaffed}}staffed{{else}}open{{end}}" href="/services/{{.Service.ID}}?start={{$.Data.Start}}&amp;end={{$.Data.End}}">
<span class="service-time">{{timeLabel .Service.TimeMinutes}}</span>
<span class="service-title">{{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}<span class="service-kind">Sonder</span>{{end}}</span>
@@ -192,11 +214,20 @@
<span class="service-people">
{{range .Assignments}}
{{$person := index $.Data.People .PersonID}}
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}{{if $person}} · {{$person.FullName}}{{end}}">{{if $person}}{{$person.AbbreviatedName}}{{else}}?{{end}}</span>
<span class="person-chip role-{{roleShort .Role}}{{if index $.Data.SwapMarks .ID}} swap-pending{{end}}{{if .BeyondPreferences}} beyond-pref{{end}}" title="{{roleTitle .Role}}{{if $person}} · {{$person.FullName}}{{end}}{{if index $.Data.SwapMarks .ID}} · Tausch angefragt{{end}}{{if .BeyondPreferences}} · über Präferenzen hinaus{{end}}{{if and $person $person.PreferenceNote}} · {{$person.PreferenceNote}}{{end}}">{{if index $.Data.SwapMarks .ID}}<span class="swap-mark" aria-hidden="true">⇄</span>{{end}}{{if .BeyondPreferences}}<span class="beyond-mark" aria-hidden="true">↑</span>{{end}}{{if $person}}{{$person.AbbreviatedName}}{{else}}?{{end}}</span>
{{end}}
</span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
</a>
{{if $.Data.CanEdit}}
<form class="service-delete-form" method="post" action="/services/{{.Service.ID}}/delete" data-confirm="Diesen Gottesdienst mit allen Einteilungen wirklich löschen?">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="start" value="{{$.Data.Start}}">
<input type="hidden" name="end" value="{{$.Data.End}}">
<button class="icon-button danger service-delete" type="submit" title="Gottesdienst löschen">{{icon "trash"}}</button>
</form>
{{end}}
</div>
{{end}}
</div>
{{else}}
@@ -204,6 +235,11 @@
{{end}}
</td>
{{end}}
<td class="day-action">
{{if $.Data.CanEdit}}
<a class="icon-button day-special-add" href="/services?edit_special=new&amp;date={{isoDate .Date}}" title="Sondergottesdienst an diesem Tag anlegen">{{icon "plus"}}</a>
{{end}}
</td>
</tr>
{{end}}
</tbody>
@@ -217,7 +253,8 @@
data-plan-row
data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
data-open="{{.OpenSlots}}"
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}">
data-special="{{if .IsSpecialDay}}true{{else}}false{{end}}"
data-beyond="{{if .HasBeyondPreferences}}true{{else}}false{{end}}">
<summary class="plan-day-summary">
<span class="day-date">
<span class="date-number">{{dayNumber $row.Date}}</span>
@@ -255,6 +292,9 @@
<span class="day-chevron" aria-hidden="true">{{icon "right"}}</span>
</summary>
<div class="day-details">
{{if $.Data.CanEdit}}
<a class="btn btn-secondary btn-tiny day-special-add-mobile" href="/services?edit_special=new&amp;date={{isoDate $row.Date}}">{{icon "plus"}} Sondergottesdienst an diesem Tag</a>
{{end}}
{{if $row.LiturgicalDay}}
{{if not $row.LiturgicalDay.Readings.IsEmpty}}
<a class="readings day-readings" href="https://schott.erzabtei-beuron.de/?datum={{isoDate $row.Date}}" target="_blank" rel="noopener" title="{{$row.LiturgicalDay.Readings.FullLabel}} · Tageslesungen bei Schott öffnen">{{$row.LiturgicalDay.Readings.ShortLabel}}{{icon "external"}}</a>
@@ -272,6 +312,7 @@
</div>
<div class="service-stack">
{{range $services}}
<div class="service-card-wrap">
<a class="service-card day-service-card {{if .IsFullyStaffed}}staffed{{else}}open{{end}}" href="/services/{{.Service.ID}}?start={{$.Data.Start}}&amp;end={{$.Data.End}}">
<span class="service-time">{{timeLabel .Service.TimeMinutes}}</span>
<span class="service-title">{{.Service.Title}}{{if eq (printf "%s" .Service.Kind) "special"}}<span class="service-kind">Sonder</span>{{end}}</span>
@@ -279,11 +320,20 @@
<span class="service-people">
{{range .Assignments}}
{{$person := index $.Data.People .PersonID}}
<span class="person-chip role-{{roleShort .Role}}" title="{{roleTitle .Role}}{{if $person}} · {{$person.FullName}}{{end}}">{{if $person}}{{$person.AbbreviatedName}}{{else}}?{{end}}</span>
<span class="person-chip role-{{roleShort .Role}}{{if index $.Data.SwapMarks .ID}} swap-pending{{end}}{{if .BeyondPreferences}} beyond-pref{{end}}" title="{{roleTitle .Role}}{{if $person}} · {{$person.FullName}}{{end}}{{if index $.Data.SwapMarks .ID}} · Tausch angefragt{{end}}{{if .BeyondPreferences}} · über Präferenzen hinaus{{end}}{{if and $person $person.PreferenceNote}} · {{$person.PreferenceNote}}{{end}}">{{if index $.Data.SwapMarks .ID}}<span class="swap-mark" aria-hidden="true">⇄</span>{{end}}{{if .BeyondPreferences}}<span class="beyond-mark" aria-hidden="true">↑</span>{{end}}{{if $person}}{{$person.AbbreviatedName}}{{else}}?{{end}}</span>
{{end}}
</span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
</a>
{{if $.Data.CanEdit}}
<form class="service-delete-form" method="post" action="/services/{{.Service.ID}}/delete" data-confirm="Diesen Gottesdienst mit allen Einteilungen wirklich löschen?">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="start" value="{{$.Data.Start}}">
<input type="hidden" name="end" value="{{$.Data.End}}">
<button class="icon-button danger service-delete" type="submit" title="Gottesdienst löschen">{{icon "trash"}}</button>
</form>
{{end}}
</div>
{{end}}
</div>
</div>
+14 -6
View File
@@ -21,8 +21,8 @@
</div>
<div class="detail-hero-actions">
<a class="btn btn-ghost btn-small" href="/plan?start={{.Data.Start}}&amp;end={{.Data.End}}">{{icon "calendar"}} Zum Plan</a>
{{if and .Data.CanEdit (eq (printf "%s" $service.Kind) "special")}}
<form method="post" action="/services/{{$service.ID}}/delete" data-confirm="Diesen Sondergottesdienst wirklich löschen?">
{{if .Data.CanEdit}}
<form method="post" action="/services/{{$service.ID}}/delete" data-confirm="Diesen Gottesdienst mit allen Einteilungen wirklich löschen?">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<button class="btn btn-danger btn-small" type="submit">{{icon "trash"}} Löschen</button>
</form>
@@ -42,8 +42,11 @@
{{$person := index $.Data.People .PersonID}}
<div class="assignment-row">
<span class="avatar small">{{if $person}}{{$person.Initials}}{{else}}?{{end}}</span>
<span class="assignment-person"><strong>{{if $person}}{{$person.FullName}}{{else}}Unbekannt{{end}}</strong><small>{{if $person}}{{$person.RoleLabel}}{{else}}—{{end}}</small></span>
<span class="assignment-person"><strong>{{if $person}}{{$person.FullName}}{{else}}Unbekannt{{end}}</strong><small>{{if $person}}{{$person.RoleLabel}}{{else}}—{{end}}</small>{{if and $person $person.PreferenceNote}}<span class="person-note">{{$person.PreferenceNote}}</span>{{end}}</span>
{{if .Locked}}<span class="badge badge-gold">gesperrt</span>{{end}}
{{if .BeyondPreferences}}<span class="badge badge-burgundy">über Präferenzen</span>{{end}}
{{if index $.Data.SwapMarks .ID}}<span class="badge badge-gold">Tausch angefragt</span>{{end}}
{{if index $.Data.SwapCandidates .ID}}<a class="btn btn-secondary btn-tiny" href="/swap/new?assignment={{.ID}}">Tausch anfragen</a>{{end}}
{{if $.Data.CanEdit}}
<div class="assignment-actions">
<form method="post" action="/services/{{$service.ID}}/lock">
@@ -69,9 +72,10 @@
<div class="candidate {{if .Blocked}}blocked{{end}}">
<div class="candidate-main">
<span class="avatar small">{{.Person.Initials}}</span>
<div><strong>{{.Person.FullName}}</strong><small>{{.TotalAssignments}} Einsätze im Zeitraum · Score {{formatFloat .Score}}</small></div>
<div><strong>{{.Person.FullName}}</strong><small>{{.TotalAssignments}} Einsätze im Zeitraum · Score {{formatFloat .Score}}</small>{{if .Person.PreferenceNote}}<span class="person-note">{{.Person.PreferenceNote}}</span>{{end}}</div>
</div>
<div class="candidate-tags">
{{if .BeyondPreferences}}<span class="badge badge-burgundy">über Präferenzen</span>{{end}}
{{if .Preferred}}<span class="badge badge-green">Präferenz</span>{{end}}
{{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}}
</div>
@@ -100,8 +104,11 @@
{{$person := index $.Data.People .PersonID}}
<div class="assignment-row">
<span class="avatar small">{{if $person}}{{$person.Initials}}{{else}}?{{end}}</span>
<span class="assignment-person"><strong>{{if $person}}{{$person.FullName}}{{else}}Unbekannt{{end}}</strong><small>{{if $person}}{{$person.RoleLabel}}{{else}}—{{end}}</small></span>
<span class="assignment-person"><strong>{{if $person}}{{$person.FullName}}{{else}}Unbekannt{{end}}</strong><small>{{if $person}}{{$person.RoleLabel}}{{else}}—{{end}}</small>{{if and $person $person.PreferenceNote}}<span class="person-note">{{$person.PreferenceNote}}</span>{{end}}</span>
{{if .Locked}}<span class="badge badge-gold">gesperrt</span>{{end}}
{{if .BeyondPreferences}}<span class="badge badge-burgundy">über Präferenzen</span>{{end}}
{{if index $.Data.SwapMarks .ID}}<span class="badge badge-gold">Tausch angefragt</span>{{end}}
{{if index $.Data.SwapCandidates .ID}}<a class="btn btn-secondary btn-tiny" href="/swap/new?assignment={{.ID}}">Tausch anfragen</a>{{end}}
{{if $.Data.CanEdit}}
<div class="assignment-actions">
<form method="post" action="/services/{{$service.ID}}/lock">
@@ -127,9 +134,10 @@
<div class="candidate {{if .Blocked}}blocked{{end}}">
<div class="candidate-main">
<span class="avatar small">{{.Person.Initials}}</span>
<div><strong>{{.Person.FullName}}</strong><small>{{.TotalAssignments}} Einsätze im Zeitraum · Score {{formatFloat .Score}}</small></div>
<div><strong>{{.Person.FullName}}</strong><small>{{.TotalAssignments}} Einsätze im Zeitraum · Score {{formatFloat .Score}}</small>{{if .Person.PreferenceNote}}<span class="person-note">{{.Person.PreferenceNote}}</span>{{end}}</div>
</div>
<div class="candidate-tags">
{{if .BeyondPreferences}}<span class="badge badge-burgundy">über Präferenzen</span>{{end}}
{{if .Preferred}}<span class="badge badge-green">Präferenz</span>{{end}}
{{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}}
</div>
+105
View File
@@ -0,0 +1,105 @@
{{define "content"}}
{{$request := .Data.Request}}
{{$offered := .Data.Offered}}
{{$wanted := .Data.Wanted}}
<div class="page-stack">
<section class="detail-hero card">
<div class="detail-hero-main">
<span class="avatar large">⇄</span>
<div>
<span class="eyebrow">Tauschanfrage</span>
<h2>{{.Data.RequesterPerson.FullName}} ⇄ {{.Data.TargetPerson.FullName}}</h2>
<p class="detail-place">Angelegt am {{longDate $request.CreatedAt}}{{if ne $request.Status "pending"}} · beantwortet am {{longDate $request.RespondedAt}}{{end}}</p>
<div class="badge-row">
<span class="badge {{if eq $request.Status "pending"}}badge-gold{{else if eq $request.Status "accepted"}}badge-green{{else}}badge-burgundy{{end}}">{{.Data.StatusLabel}}</span>
<span class="badge badge-neutral">{{$wanted.Assignment.Role.Title}}</span>
</div>
</div>
</div>
<div class="detail-hero-actions">
<a class="btn btn-ghost btn-small" href="/plan">{{icon "calendar"}} Zum Plan</a>
</div>
</section>
<div class="swap-compare">
<section class="card">
<div class="card-head"><div><span class="eyebrow">Angebot von {{.Data.RequesterPerson.FullName}}</span><h3>{{$offered.Service.Title}}</h3></div></div>
{{if $offered.Exists}}
<dl class="detail-list">
<dt>Datum</dt><dd>{{longDate $offered.Service.Date}}, {{timeLabel $offered.Service.TimeMinutes}} Uhr</dd>
<dt>Ort</dt><dd>{{$offered.Church.Name}}</dd>
<dt>Rolle</dt><dd>{{$offered.Assignment.Role.Title}}</dd>
</dl>
{{else}}<p class="empty-note">Dieser Einsatz ist nicht mehr vorhanden.</p>{{end}}
</section>
<section class="card">
<div class="card-head"><div><span class="eyebrow">Gewünscht von {{.Data.TargetPerson.FullName}}</span><h3>{{$wanted.Service.Title}}</h3></div></div>
{{if $wanted.Exists}}
<dl class="detail-list">
<dt>Datum</dt><dd>{{longDate $wanted.Service.Date}}, {{timeLabel $wanted.Service.TimeMinutes}} Uhr</dd>
<dt>Ort</dt><dd>{{$wanted.Church.Name}}</dd>
<dt>Rolle</dt><dd>{{$wanted.Assignment.Role.Title}}</dd>
</dl>
{{else}}<p class="empty-note">Dieser Einsatz ist nicht mehr vorhanden.</p>{{end}}
</section>
</div>
{{if .Data.Action}}
<section class="card swap-action-card">
<span class="eyebrow">Bestätigung</span>
<h3>{{if eq .Data.Action "accept"}}Tausch annehmen?{{else}}Tausch ablehnen?{{end}}</h3>
{{if eq .Data.Action "accept"}}
<p>Beim Annehmen werden beide Einsätze sofort getauscht. Der Plan wird erst nach Ihrer Bestätigung geändert.</p>
{{else}}
<p>Beim Ablehnen bleibt der Plan unverändert. {{.Data.RequesterPerson.FullName}} erhält anschließend die Möglichkeit, eine Antwort-E-Mail zu senden.</p>
{{end}}
<form method="post" action="/swap/{{.Data.Token}}/respond" class="inline-form">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<input type="hidden" name="action" value="{{.Data.Action}}">
<button class="btn {{if eq .Data.Action "accept"}}btn-primary{{else}}btn-danger{{end}}" type="submit">{{if eq .Data.Action "accept"}}Tausch annehmen{{else}}Tausch ablehnen{{end}}</button>
<a class="btn btn-ghost" href="/swap/{{.Data.Token}}">Abbrechen</a>
</form>
</section>
{{else if .Data.CanRespond}}
<section class="card swap-action-card">
<span class="eyebrow">Ihre Antwort</span>
<h3>Möchten Sie tauschen?</h3>
<p>Die Anfrage von {{.Data.RequesterPerson.FullName}} ist noch offen. Erst mit Ihrer Bestätigung wird der Plan geändert.</p>
<div class="swap-actions">
<a class="btn btn-primary" href="/swap/{{.Data.Token}}/accept">{{icon "check"}} Annehmen</a>
<a class="btn btn-ghost" href="/swap/{{.Data.Token}}/decline">{{icon "close"}} Ablehnen</a>
</div>
</section>
{{end}}
{{if .Data.RequestMailto}}
<section class="card mail-card">
<div class="card-head"><div><span class="eyebrow">E-Mail</span><h3>Anfrage an {{.Data.TargetPerson.FullName}} senden</h3></div>{{icon "mail"}}</div>
<p>Der Entwurf enthält beide Termine sowie die Links „Annehmen“ und „Ablehnen“. Öffnen Sie ihn in Ihrem E-Mail-Programm und senden Sie ihn ab.</p>
<a class="btn btn-primary" href="{{.Data.RequestMailto}}">{{icon "mail"}} E-Mail-Entwurf öffnen</a>
</section>
{{end}}
{{if .Data.ResponseMailto}}
<section class="card mail-card">
<div class="card-head"><div><span class="eyebrow">E-Mail</span><h3>Antwort an {{.Data.RequesterPerson.FullName}} senden</h3></div>{{icon "mail"}}</div>
<p>Der Entwurf enthält Ihre Antwort „{{.Data.StatusLabel}}“ und beide Termine. Öffnen Sie ihn in Ihrem E-Mail-Programm und senden Sie ihn ab.</p>
<a class="btn btn-primary" href="{{.Data.ResponseMailto}}">{{icon "mail"}} Antwort-E-Mail öffnen</a>
</section>
{{end}}
{{if .Data.ResponseUnavailable}}
<section class="card side-note">
<span class="eyebrow">Hinweis</span>
<p>Die E-Mail-Adresse von {{.Data.RequesterPerson.FullName}} ist für Sie nicht freigegeben. Bitte antworten Sie direkt auf die ursprüngliche Anfrage-E-Mail.</p>
</section>
{{end}}
{{if and (eq $request.Status "pending") (not .Data.CanRespond) (not .Data.RequestMailto)}}
<section class="card side-note">
<span class="eyebrow">Hinweis</span>
<p>Der E-Mail-Entwurf mit den Antwort-Links wird nur direkt nach dem Anlegen der Anfrage angezeigt. Die angefragte Person kann die Anfrage weiterhin über ihre E-Mail beantworten.</p>
</section>
{{end}}
</div>
{{end}}
+53
View File
@@ -0,0 +1,53 @@
{{define "content"}}
{{$wanted := .Data.Wanted}}
<div class="page-stack">
<section class="page-intro">
<div>
<span class="eyebrow">Tausch anfragen</span>
<h2>Welchen eigenen Einsatz möchten Sie anbieten?</h2>
<p>Die angefragte Person erhält eine E-Mail mit beiden Terminen und kann den Tausch nach der Anmeldung annehmen oder ablehnen. Bis dahin bleibt der Plan unverändert.</p>
</div>
<div class="intro-actions">
<a class="btn btn-ghost btn-small" href="/services/{{$wanted.Service.ID}}">{{icon "left"}} Zurück zum Gottesdienst</a>
</div>
</section>
<section class="card swap-panel">
<div class="card-head">
<div><span class="eyebrow">Gewünschter Einsatz</span><h3>{{$wanted.Service.Title}}</h3></div>
<span class="badge badge-green">{{$wanted.Assignment.Role.Title}}</span>
</div>
<div class="swap-assignment">
<div><strong>{{longDate $wanted.Service.Date}}</strong><span>{{timeLabel $wanted.Service.TimeMinutes}} Uhr</span></div>
<div><strong>{{$wanted.Church.Name}}</strong><span>{{$wanted.Service.Title}}</span></div>
<div><strong>{{.Data.Target.FullName}}</strong><span>angefragte Person</span></div>
</div>
</section>
<section class="card">
<div class="card-head"><div><span class="eyebrow">Ihr Angebot</span><h3>Zukünftige eigene Einsätze</h3></div><span class="count-pill">{{len .Data.Options}}</span></div>
{{if .Data.Options}}
<form method="post" action="/swap/request" class="form-stack">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<input type="hidden" name="wanted" value="{{$wanted.Assignment.ID}}">
<div class="swap-option-list">
{{range .Data.Options}}
<label class="swap-option">
<input type="radio" name="offered" value="{{.Assignment.ID}}" required>
<span class="swap-option-main">
<strong>{{longDate .Service.Date}} · {{timeLabel .Service.TimeMinutes}} Uhr</strong>
<span>{{.Church.Name}} · {{.Service.Title}}</span>
</span>
<span class="badge badge-neutral">{{.Assignment.Role.Title}}</span>
</label>
{{end}}
</div>
<p class="empty-note">Beim Absenden wird noch kein Einsatz geändert. Zuerst öffnet sich ein E-Mail-Entwurf an {{.Data.Target.FullName}}.</p>
<button class="btn btn-primary" type="submit">{{icon "mail"}} Tauschanfrage vorbereiten</button>
</form>
{{else}}
<p class="empty-note">Sie haben im selben Dienst keine passenden zukünftigen Einsätze, die Sie anbieten könnten. Ein Tausch ist nur zwischen Einsätzen derselben Rolle möglich, wenn keine Abwesenheit oder Sperre entgegensteht.</p>
{{end}}
</section>
</div>
{{end}}
+55
View File
@@ -20,6 +20,61 @@
<article class="mini-stat"><span class="mini-stat-label">Abwesenheiten</span><strong>{{len .Data.Absences}}</strong><small>hinterlegte Zeiträume</small></article>
</section>
{{with .Data.Sharing}}
<section class="card sharing-card">
<div class="card-head">
<div><span class="eyebrow">E-Mail-Freigaben</span><h3>Wer darf Ihre E-Mail-Adresse sehen?</h3></div>
<span class="count-pill">{{len .Readers}}</span>
</div>
{{if .RosterChanged}}
<div class="sharing-notice">
<div>
<strong>Die Liste der Leserinnen und Leser hat sich geändert.</strong>
<p>Bitte prüfen Sie, wer Ihre E-Mail-Adresse sehen darf. Ihre bisherigen Freigaben bleiben unverändert.</p>
</div>
<form method="post" action="/team/sharing/ack">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button class="btn btn-secondary btn-small" type="submit">Zur Kenntnis genommen</button>
</form>
</div>
{{end}}
<p class="sharing-intro">Lektoren und Kommunionhelfer können ihre E-Mail-Adressen gegenseitig freigeben. Für eine Tauschanfrage müssen beide Seiten einverstanden sein. Neue Leser erhalten keinen automatischen Zugriff; wird die Liste erweitert, erscheint nach dem nächsten Anmelden ein Hinweis.</p>
<form method="post" action="/team/sharing" class="sharing-form">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<label class="check sharing-all"><input type="checkbox" name="share_all" value="1"><span>Alle aktuellen Lektoren und Kommunionhelfer freigeben</span></label>
<div class="sharing-grid">
{{range .Readers}}
<label class="check">
<input type="checkbox" name="viewer" value="{{.UserID}}" {{if .Shared}}checked{{end}}>
<span>{{.Person.FullName}} <small>{{.Person.RoleLabel}}</small></span>
</label>
{{else}}
<p class="empty-note">Es sind noch keine weiteren Leser-Konten mit diesem Mandanten verknüpft.</p>
{{end}}
</div>
<button class="btn btn-primary btn-small" type="submit">Freigaben speichern</button>
</form>
</section>
<section class="card sharing-card">
<div class="card-head">
<div><span class="eyebrow">Gegenseitig</span><h3>Freigegeben für Sie</h3></div>
<span class="count-pill">{{len .SharedWithMe}}</span>
</div>
<div class="sharing-people">
{{range .SharedWithMe}}
<div class="sharing-person">
<span class="avatar small">{{.Initials}}</span>
<span class="sharing-person-name"><strong>{{.FullName}}</strong><small>{{.RoleLabel}}</small></span>
{{if .Email}}<a href="mailto:{{.Email}}">{{.Email}}</a>{{else}}<span class="muted">E-Mail noch nicht entschlüsselbar</span>{{end}}
</div>
{{else}}
<p class="empty-note">Noch niemand hat seine E-Mail-Adresse für Sie freigegeben.</p>
{{end}}
</div>
</section>
{{end}}
<div class="team-layout">
<section class="card">
<div class="card-head">