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
+3788 -162

No files matched your search

+55 -9
View File
@@ -68,6 +68,7 @@ enum PlanFilter: String, CaseIterable, Identifiable {
case all case all
case services case services
case open case open
case beyond
var id: String { rawValue } var id: String { rawValue }
@@ -76,6 +77,7 @@ enum PlanFilter: String, CaseIterable, Identifiable {
case .all: "Alle Tage" case .all: "Alle Tage"
case .services: "Mit Gottesdiensten" case .services: "Mit Gottesdiensten"
case .open: "Nur offene" case .open: "Nur offene"
case .beyond: "Über Präferenzen"
} }
} }
} }
@@ -144,6 +146,7 @@ struct CandidateSuggestion: Identifiable {
var warnings: [String] var warnings: [String]
var blocked: Bool var blocked: Bool
var preferred: Bool var preferred: Bool
var beyondPreferences: Bool
var totalAssignments: Int var totalAssignments: Int
var id: String { person.id } var id: String { person.id }
@@ -347,6 +350,8 @@ final class PlanModel: ObservableObject {
if !row.hasServices { return false } if !row.hasServices { return false }
case .open: case .open:
if row.openSlots == 0 { return false } if row.openSlots == 0 { return false }
case .beyond:
if !row.hasBeyondPreferences { return false }
} }
guard !query.isEmpty else { return true } guard !query.isEmpty else { return true }
if row.liturgicalDay?.title.lowercased().contains(query) == true { return true } if row.liturgicalDay?.title.lowercased().contains(query) == true { return true }
@@ -382,7 +387,7 @@ final class PlanModel: ObservableObject {
// MARK: - Planning // MARK: - Planning
func autoPlan(replaceExisting: Bool) -> PlanResult? { func autoPlan(replaceExisting: Bool, allowBeyond: Bool = false) -> PlanResult? {
guard !isPlanning else { return nil } guard !isPlanning else { return nil }
isPlanning = true isPlanning = true
defer { isPlanning = false } defer { isPlanning = false }
@@ -390,8 +395,11 @@ final class PlanModel: ObservableObject {
let rangeServices = try db.services(in: range) let rangeServices = try db.services(in: range)
let existing = try db.assignments(in: range) let existing = try db.assignments(in: range)
let options = PlannerOptions( let options = PlannerOptions(
replaceExisting: replaceExisting, // A follow-up pass keeps the result of the first pass and only
// adds assignments for volunteers who allowed them.
replaceExisting: allowBeyond ? false : replaceExisting,
respectPreferredWeekdays: db.setting("respectPreferredWeekdays") != "0", respectPreferredWeekdays: db.setting("respectPreferredWeekdays") != "0",
allowBeyondPreferences: allowBeyond,
weightFairness: Double(db.setting("fairnessWeight") ?? "") ?? 2.2, weightFairness: Double(db.setting("fairnessWeight") ?? "") ?? 2.2,
maxAssignmentsPerDay: 1 maxAssignmentsPerDay: 1
) )
@@ -401,11 +409,12 @@ final class PlanModel: ObservableObject {
services: rangeServices, services: rangeServices,
existingAssignments: existing, existingAssignments: existing,
churches: churches, churches: churches,
liturgicalDays: Array(liturgicalDays.values),
options: options options: options
) )
let result = planner.plan() let result = planner.plan()
if result.filledCount > 0 || replaceExisting { if result.filledCount > 0 || replaceExisting {
try db.savePlan(result.assignments, in: range, replaceUnlocked: replaceExisting) try db.savePlan(result.assignments, in: range, replaceUnlocked: allowBeyond ? false : replaceExisting)
} }
loadAll() loadAll()
planResult = result planResult = result
@@ -429,6 +438,7 @@ final class PlanModel: ObservableObject {
services: [service], services: [service],
existingAssignments: existing.filter { $0.serviceID == serviceID }, existingAssignments: existing.filter { $0.serviceID == serviceID },
churches: churches, churches: churches,
liturgicalDays: Array(liturgicalDays.values),
options: PlannerOptions(replaceExisting: false, respectPreferredWeekdays: false) options: PlannerOptions(replaceExisting: false, respectPreferredWeekdays: false)
) )
let result = planner.plan() let result = planner.plan()
@@ -448,7 +458,27 @@ final class PlanModel: ObservableObject {
func assign(serviceID: String, role: Role, personID: String?) { func assign(serviceID: String, role: Role, personID: String?) {
do { do {
try db.setAssignment(serviceID: serviceID, role: role, personID: personID) var beyond = false
if let personID, let person = peopleByID[personID], let service = try db.service(id: serviceID) {
let highFeast = liturgicalDays[service.dateKey]?.isHighFeast ?? false
let fits = person.matchesWeekdayPreference(
weekday: DayMath.weekday(service.date),
timeMinutes: service.timeMinutes,
highFeast: highFeast
)
beyond = !fits
if !beyond, person.maxPerMonth > 0 {
let monthAssignments = try db.assignments(in: DayRange.month(containing: service.date))
let used = monthAssignments.filter {
$0.personID == personID && $0.serviceID != serviceID
}.count
beyond = used >= person.maxPerMonth
}
}
try db.setAssignment(
serviceID: serviceID, role: role, personID: personID,
beyondPreferences: beyond
)
loadAll() loadAll()
if let personID, let person = peopleByID[personID] { if let personID, let person = peopleByID[personID] {
showToast("\(person.fullName) als \(role.title) eingetragen.", kind: .success) showToast("\(person.fullName) als \(role.title) eingetragen.", kind: .success)
@@ -501,6 +531,7 @@ final class PlanModel: ObservableObject {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role) assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
} }
let weekday = DayMath.weekday(service.date) let weekday = DayMath.weekday(service.date)
let highFeast = liturgicalDays[service.dateKey]?.isHighFeast ?? false
let eligiblePeople = people.filter { person in let eligiblePeople = people.filter { person in
guard person.active, person.canFill(role) else { return false } guard person.active, person.canFill(role) else { return false }
@@ -515,20 +546,34 @@ final class PlanModel: ObservableObject {
.map { person in .map { person in
var warnings: [String] = [] var warnings: [String] = []
var blocked = false var blocked = false
var beyond = false
if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) { if absences.contains(where: { $0.personID == person.id && $0.overlaps(service.date) }) {
warnings.append("abwesend") warnings.append("abwesend")
blocked = true blocked = true
} }
if !ignorePreferredWeekdays, let weekdayMatch = person.matchesWeekdayPreference(
!person.preferredWeekdays.isEmpty, weekday: weekday,
!person.preferredWeekdays.contains(weekday) { timeMinutes: service.timeMinutes,
warnings.append("Einsatztag passt nicht") highFeast: highFeast
)
if !weekdayMatch {
if ignorePreferredWeekdays {
beyond = true
} else if person.allowBeyondPreferences {
beyond = true
} else {
warnings.append("Einsatztag oder Uhrzeit passt nicht")
blocked = true blocked = true
} }
}
if person.maxPerMonth > 0, monthlyCounts["\(person.id)|\(monthKey)", default: 0] >= person.maxPerMonth { if person.maxPerMonth > 0, monthlyCounts["\(person.id)|\(monthKey)", default: 0] >= person.maxPerMonth {
warnings.append("Monatslimit") warnings.append("Monatslimit")
if person.allowBeyondPreferences {
beyond = true
} else {
blocked = true blocked = true
} }
}
let servicesThisDay = dayServices["\(person.id)|\(service.dateKey)", default: []] let servicesThisDay = dayServices["\(person.id)|\(service.dateKey)", default: []]
if !servicesThisDay.isEmpty, !servicesThisDay.isSubset(of: [service.id]) { if !servicesThisDay.isEmpty, !servicesThisDay.isSubset(of: [service.id]) {
warnings.append("bereits an diesem Tag") warnings.append("bereits an diesem Tag")
@@ -554,7 +599,7 @@ final class PlanModel: ObservableObject {
if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) { if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) {
score -= 2 score -= 2
} }
if person.preferredWeekdays.contains(weekday) { if weekdayMatch, !person.preferredWeekdays.isEmpty {
score += 3 score += 3
preferred = true preferred = true
} }
@@ -574,6 +619,7 @@ final class PlanModel: ObservableObject {
warnings: warnings, warnings: warnings,
blocked: blocked, blocked: blocked,
preferred: preferred, preferred: preferred,
beyondPreferences: beyond,
totalAssignments: totalCounts[person.id, default: 0] totalAssignments: totalCounts[person.id, default: 0]
) )
} }
+22 -4
View File
@@ -270,24 +270,42 @@ struct PersonMiniChip: View {
var person: Person var person: Person
var role: Role var role: Role
var color: Color var color: Color
var beyond: Bool = false
var body: some View { var body: some View {
HStack(spacing: 4) { HStack(spacing: 4) {
Avatar(initials: person.initials, color: color, size: 18) Avatar(initials: person.initials, color: color, size: 18)
if beyond {
Image(systemName: "arrow.up.right")
.font(.system(size: 7, weight: .black))
.foregroundStyle(LP.burgundy)
}
Text(person.abbreviatedName) Text(person.abbreviatedName)
.font(.system(size: 10.5, weight: .medium)) .font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.ink) .foregroundStyle(beyond ? LP.burgundy : LP.ink)
.lineLimit(1) .lineLimit(1)
} }
.padding(.horizontal, 4) .padding(.horizontal, 4)
.padding(.vertical, 2) .padding(.vertical, 2)
.background( .background(
Capsule().fill(LP.cardMuted) Capsule().fill(beyond ? LP.burgundySoft.opacity(0.7) : LP.cardMuted)
) )
.overlay( .overlay(
Capsule().strokeBorder(LP.line.opacity(0.5), lineWidth: 0.6) Capsule().strokeBorder(
beyond ? LP.burgundy.opacity(0.5) : LP.line.opacity(0.5),
style: StrokeStyle(lineWidth: 0.6, dash: beyond ? [2, 1.5] : [])
) )
.help("\(person.fullName) · \(role.title)\n\(person.preferredChurchIDs.isEmpty ? "Alle Orte" : "Bevorzugte Orte") · max. \(person.maxPerMonth) Einsätze/Monat") )
.help(chipHelp)
}
private var chipHelp: String {
var lines = ["\(person.fullName) · \(role.title)"]
lines.append(person.preferredChurchIDs.isEmpty ? "Alle Orte" : "Bevorzugte Orte")
lines.append("max. \(person.maxPerMonth) Einsätze/Monat")
if beyond { lines.append("Über die Präferenzen hinaus eingeplant") }
if !person.preferenceNote.isEmpty { lines.append(person.preferenceNote) }
return lines.joined(separator: "\n")
} }
} }
@@ -9,13 +9,16 @@ struct PersonEditorSheet: View {
@State private var firstName = "" @State private var firstName = ""
@State private var lastName = "" @State private var lastName = ""
@State private var shortCode = ""
@State private var email = "" @State private var email = ""
@State private var phone = "" @State private var phone = ""
@State private var roles: Set<Role> = [.lector] @State private var roles: Set<Role> = [.lector]
@State private var preferredChurchIDs: Set<String> = [] @State private var preferredChurchIDs: Set<String> = []
@State private var preferredWeekdays: Set<Int> = [] @State private var preferredWeekdays: Set<Int> = []
@State private var weekdayPeriods: [Int: WeekdayPeriod] = [:]
@State private var preferredServiceTitles: Set<String> = [] @State private var preferredServiceTitles: Set<String> = []
@State private var maxPerMonth = 6 @State private var maxPerMonth = 6
@State private var allowBeyondPreferences = false
@State private var active = true @State private var active = true
@State private var notes = "" @State private var notes = ""
@@ -33,6 +36,13 @@ struct PersonEditorSheet: View {
["", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][max(0, min(7, weekday))] ["", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][max(0, min(7, weekday))]
} }
private func periodBinding(_ weekday: Int) -> Binding<WeekdayPeriod> {
Binding(
get: { weekdayPeriods[weekday] ?? .all },
set: { weekdayPeriods[weekday] = $0 }
)
}
private var isValid: Bool { private var isValid: Bool {
!firstName.trimmingCharacters(in: .whitespaces).isEmpty !firstName.trimmingCharacters(in: .whitespaces).isEmpty
&& !lastName.trimmingCharacters(in: .whitespaces).isEmpty && !lastName.trimmingCharacters(in: .whitespaces).isEmpty
@@ -118,7 +128,15 @@ struct PersonEditorSheet: View {
TextField("z. B. Berg", text: $lastName) TextField("z. B. Berg", text: $lastName)
.textFieldStyle(.roundedBorder) .textFieldStyle(.roundedBorder)
} }
LabeledField(label: "Kürzel") {
TextField("optional", text: $shortCode)
.textFieldStyle(.roundedBorder)
.frame(width: 90)
} }
}
Text("Das Kürzel erscheint in der Gastansicht. Ohne Kürzel werden die Initialen angezeigt.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
HStack(spacing: 12) { HStack(spacing: 12) {
LabeledField(label: "E-Mail") { LabeledField(label: "E-Mail") {
TextField("optional", text: $email) TextField("optional", text: $email)
@@ -195,8 +213,9 @@ struct PersonEditorSheet: View {
Text("Bevorzugte Einsatztage") Text("Bevorzugte Einsatztage")
.font(.system(size: 9.5, weight: .semibold)) .font(.system(size: 9.5, weight: .semibold))
.foregroundStyle(LP.inkSecondary) .foregroundStyle(LP.inkSecondary)
HStack(spacing: 5) { HStack(alignment: .top, spacing: 5) {
ForEach(weekdayOrder, id: \.self) { weekday in ForEach(weekdayOrder, id: \.self) { weekday in
VStack(spacing: 3) {
ChipToggle( ChipToggle(
title: weekdayLabel(weekday), title: weekdayLabel(weekday),
isOn: preferredWeekdays.contains(weekday), isOn: preferredWeekdays.contains(weekday),
@@ -204,12 +223,29 @@ struct PersonEditorSheet: View {
) { ) {
if preferredWeekdays.contains(weekday) { if preferredWeekdays.contains(weekday) {
preferredWeekdays.remove(weekday) preferredWeekdays.remove(weekday)
weekdayPeriods[weekday] = nil
} else { } else {
preferredWeekdays.insert(weekday) preferredWeekdays.insert(weekday)
weekdayPeriods[weekday] = .all
}
}
if preferredWeekdays.contains(weekday) {
Picker("Tageszeit", selection: periodBinding(weekday)) {
ForEach(WeekdayPeriod.allCases) { period in
Text(period.shortLabel).tag(period)
}
}
.labelsHidden()
.pickerStyle(.menu)
.controlSize(.mini)
.frame(width: 88)
} }
} }
} }
} }
Text("Hochfeste gelten zusätzlich als Sonntag. Die Tageszeit grenzt den Einsatztag ein (vormittags 0–12, nachmittags 12–17, abends ab 17 Uhr).")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
} }
VStack(alignment: .leading, spacing: 5) { VStack(alignment: .leading, spacing: 5) {
@@ -262,6 +298,21 @@ struct PersonEditorSheet: View {
.background(RoundedRectangle(cornerRadius: 7).fill(LP.card)) .background(RoundedRectangle(cornerRadius: 7).fill(LP.card))
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.8), lineWidth: 1)) .overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(LP.line.opacity(0.8), lineWidth: 1))
} }
Text("Diese Notiz erscheint in der Dienstplanung bei Einsätzen und Vorschlägen.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
Toggle(isOn: $allowBeyondPreferences) {
VStack(alignment: .leading, spacing: 1) {
Text("Auch über Präferenzen hinaus planbar")
.font(.system(size: 10.5, weight: .medium))
.foregroundStyle(LP.inkSecondary)
Text("Die Person kann nach Rückfrage für Dienste außerhalb ihrer Tage, Zeiten und ihres Monatslimits eingeplant werden.")
.font(.system(size: 9.5))
.foregroundStyle(LP.inkTertiary)
}
}
.toggleStyle(.switch)
.controlSize(.small)
} }
} }
@@ -350,13 +401,16 @@ struct PersonEditorSheet: View {
} }
firstName = person.firstName firstName = person.firstName
lastName = person.lastName lastName = person.lastName
shortCode = person.shortCode
email = person.email email = person.email
phone = person.phone phone = person.phone
roles = person.roles roles = person.roles
preferredChurchIDs = person.preferredChurchIDs preferredChurchIDs = person.preferredChurchIDs
preferredWeekdays = person.preferredWeekdays preferredWeekdays = person.preferredWeekdays
weekdayPeriods = Dictionary(uniqueKeysWithValues: person.preferredWeekdayPeriods.map { ($0.weekday, $0.period) })
preferredServiceTitles = Set(person.preferredServiceTitles) preferredServiceTitles = Set(person.preferredServiceTitles)
maxPerMonth = person.maxPerMonth maxPerMonth = person.maxPerMonth
allowBeyondPreferences = person.allowBeyondPreferences
active = person.active active = person.active
notes = person.notes notes = person.notes
} }
@@ -378,6 +432,7 @@ struct PersonEditorSheet: View {
private func save() { private func save() {
let person = Person( let person = Person(
id: personID ?? UUID().uuidString, id: personID ?? UUID().uuidString,
shortCode: shortCode.trimmingCharacters(in: .whitespaces),
firstName: firstName.trimmingCharacters(in: .whitespaces), firstName: firstName.trimmingCharacters(in: .whitespaces),
lastName: lastName.trimmingCharacters(in: .whitespaces), lastName: lastName.trimmingCharacters(in: .whitespaces),
roles: roles, roles: roles,
@@ -385,8 +440,12 @@ struct PersonEditorSheet: View {
phone: phone.trimmingCharacters(in: .whitespaces), phone: phone.trimmingCharacters(in: .whitespaces),
preferredChurchIDs: preferredChurchIDs, preferredChurchIDs: preferredChurchIDs,
preferredWeekdays: preferredWeekdays, preferredWeekdays: preferredWeekdays,
preferredWeekdayPeriods: preferredWeekdays.sorted().map {
WeekdayPeriodPreference(weekday: $0, period: weekdayPeriods[$0] ?? .all)
},
preferredServiceTitles: Array(preferredServiceTitles).sorted(), preferredServiceTitles: Array(preferredServiceTitles).sorted(),
maxPerMonth: maxPerMonth, maxPerMonth: maxPerMonth,
allowBeyondPreferences: allowBeyondPreferences,
active: active, active: active,
notes: notes.trimmingCharacters(in: .whitespacesAndNewlines) notes: notes.trimmingCharacters(in: .whitespacesAndNewlines)
) )
@@ -8,6 +8,9 @@ struct PlanResultSheet: View {
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
if let result = model.planResult { if let result = model.planResult {
let canOfferBeyond = !result.unfilled.isEmpty
&& !result.assignments.contains(where: \.beyondPreferences)
&& model.people.contains { $0.active && $0.allowBeyondPreferences }
SheetHeader( SheetHeader(
icon: result.unfilled.isEmpty ? "checkmark.seal" : "exclamationmark.triangle", icon: result.unfilled.isEmpty ? "checkmark.seal" : "exclamationmark.triangle",
title: result.unfilled.isEmpty ? "Planung abgeschlossen" : "Planung mit Lücken", title: result.unfilled.isEmpty ? "Planung abgeschlossen" : "Planung mit Lücken",
@@ -98,12 +101,31 @@ struct PlanResultSheet: View {
.clipShape(RoundedRectangle(cornerRadius: 9)) .clipShape(RoundedRectangle(cornerRadius: 9))
.overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8)) .overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(LP.line.opacity(0.55), lineWidth: 0.8))
} }
if canOfferBeyond {
let flagged = model.people.filter { $0.active && $0.allowBeyondPreferences }
HStack(alignment: .top, spacing: 9) {
Image(systemName: "arrow.up.right.circle")
.foregroundStyle(LP.burgundy)
Text("\(flagged.count) \(flagged.count == 1 ? "Person hat" : "Personen haben") sich bereit erklärt, nach Rückfrage auch über die eigenen Präferenzen hinaus eingeplant zu werden. Diese Einsätze werden im Plan besonders gekennzeichnet.")
.font(.system(size: 10.5))
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
.padding(12)
.background(RoundedRectangle(cornerRadius: 10).fill(LP.burgundySoft.opacity(0.5)))
}
} }
} }
.padding(22) .padding(22)
} }
SheetFooter { SheetFooter {
if canOfferBeyond {
PrimaryActionButton(title: "Über Präferenzen hinaus planen", icon: "arrow.up.right") {
_ = model.autoPlan(replaceExisting: false, allowBeyond: true)
}
}
Spacer() Spacer()
SecondaryActionButton(title: "Statistik ansehen", icon: "chart.xyaxis.line") { SecondaryActionButton(title: "Statistik ansehen", icon: "chart.xyaxis.line") {
model.planResult = nil model.planResult = nil
+61 -15
View File
@@ -158,6 +158,7 @@ private struct CalendarTable: View {
private let horizontalPadding: CGFloat = 12 private let horizontalPadding: CGFloat = 12
private let dateWidth: CGFloat = 86 private let dateWidth: CGFloat = 86
private let liturgyWidth: CGFloat = 240 private let liturgyWidth: CGFloat = 240
private let actionWidth: CGFloat = 22
private let churchMinWidth: CGFloat = 186 private let churchMinWidth: CGFloat = 186
var body: some View { var body: some View {
@@ -166,9 +167,9 @@ private struct CalendarTable: View {
toolbar toolbar
Hairline() Hairline()
GeometryReader { geo in GeometryReader { geo in
let minimum = horizontalPadding * 2 + dateWidth + liturgyWidth + churchMinWidth * 4 + gap * 5 let minimum = horizontalPadding * 2 + dateWidth + liturgyWidth + actionWidth + churchMinWidth * 4 + gap * 6
let width = max(geo.size.width, minimum) let width = max(geo.size.width, minimum)
let churchWidth = (width - horizontalPadding * 2 - dateWidth - liturgyWidth - gap * 5) / 4 let churchWidth = (width - horizontalPadding * 2 - dateWidth - liturgyWidth - actionWidth - gap * 6) / 4
if model.churches.isEmpty { if model.churches.isEmpty {
EmptyStateView( EmptyStateView(
icon: "building.columns", icon: "building.columns",
@@ -201,6 +202,7 @@ private struct CalendarTable: View {
churchWidth: churchWidth, churchWidth: churchWidth,
dateWidth: dateWidth, dateWidth: dateWidth,
liturgyWidth: liturgyWidth, liturgyWidth: liturgyWidth,
actionWidth: actionWidth,
gap: gap, gap: gap,
horizontalPadding: horizontalPadding horizontalPadding: horizontalPadding
) )
@@ -317,6 +319,14 @@ private struct CalendarTable: View {
} }
.font(.system(size: 8.5, weight: .medium)) .font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary) .foregroundStyle(LP.inkTertiary)
HStack(spacing: 3) {
Image(systemName: "arrow.up.right")
.font(.system(size: 8, weight: .bold))
.foregroundStyle(LP.burgundy)
Text("über Präferenzen")
}
.font(.system(size: 8.5, weight: .medium))
.foregroundStyle(LP.inkTertiary)
} }
} }
@@ -345,6 +355,8 @@ private struct CalendarTable: View {
ForEach(model.churches) { church in ForEach(model.churches) { church in
ChurchColumnHeader(church: church, width: churchWidth) ChurchColumnHeader(church: church, width: churchWidth)
} }
Text("")
.frame(width: actionWidth)
} }
.padding(.horizontal, horizontalPadding) .padding(.horizontal, horizontalPadding)
.padding(.vertical, 10) .padding(.vertical, 10)
@@ -369,7 +381,7 @@ private struct CalendarTable: View {
} }
.padding(.horizontal, horizontalPadding) .padding(.horizontal, horizontalPadding)
.padding(.vertical, 7) .padding(.vertical, 7)
.frame(width: horizontalPadding * 2 + dateWidth + liturgyWidth + churchWidth * 4 + gap * 5, alignment: .leading) .frame(width: horizontalPadding * 2 + dateWidth + liturgyWidth + actionWidth + churchWidth * 4 + gap * 6, alignment: .leading)
.background(LP.paperDeep.opacity(0.55)) .background(LP.paperDeep.opacity(0.55))
.overlay(alignment: .top) { Hairline() } .overlay(alignment: .top) { Hairline() }
.overlay(alignment: .bottom) { Hairline().opacity(0.55) } .overlay(alignment: .bottom) { Hairline().opacity(0.55) }
@@ -440,6 +452,7 @@ private struct DayRow: View {
var churchWidth: CGFloat var churchWidth: CGFloat
var dateWidth: CGFloat var dateWidth: CGFloat
var liturgyWidth: CGFloat var liturgyWidth: CGFloat
var actionWidth: CGFloat
var gap: CGFloat var gap: CGFloat
var horizontalPadding: CGFloat var horizontalPadding: CGFloat
@@ -459,6 +472,16 @@ private struct DayRow: View {
churchCell(church: church) churchCell(church: church)
.frame(width: churchWidth, alignment: .topLeading) .frame(width: churchWidth, alignment: .topLeading)
} }
Button {
model.specialServiceEditor = SpecialServiceRequest(churchID: nil, date: row.date)
} label: {
Image(systemName: "plus.circle.fill")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(LP.burgundy.opacity(0.6))
}
.buttonStyle(.plain)
.help("Sondergottesdienst an diesem Tag hinzufügen")
.frame(width: actionWidth, alignment: .trailing)
} }
.padding(.horizontal, horizontalPadding) .padding(.horizontal, horizontalPadding)
.padding(.vertical, 9) .padding(.vertical, 9)
@@ -526,17 +549,6 @@ private struct DayRow: View {
} }
} }
} }
.overlay(alignment: .topTrailing) {
Button {
model.specialServiceEditor = SpecialServiceRequest(churchID: nil, date: row.date)
} label: {
Image(systemName: "plus.circle.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(LP.burgundy.opacity(0.62))
}
.buttonStyle(.plain)
.help("Sondergottesdienst an diesem Tag hinzufügen")
}
} }
private var liturgyCell: some View { private var liturgyCell: some View {
@@ -624,6 +636,7 @@ private struct ServiceCard: View {
@EnvironmentObject private var model: PlanModel @EnvironmentObject private var model: PlanModel
var service: ServiceWithAssignments var service: ServiceWithAssignments
var liturgy: LiturgicalDay? var liturgy: LiturgicalDay?
@State private var confirmDelete = false
private var churchColor: Color { LP.churchColor(service.church.colorHex) } private var churchColor: Color { LP.churchColor(service.church.colorHex) }
@@ -674,6 +687,7 @@ private struct ServiceCard: View {
} }
} }
.padding(.horizontal, 7) .padding(.horizontal, 7)
.padding(.trailing, 10)
.padding(.vertical, 6) .padding(.vertical, 6)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.background( .background(
@@ -693,6 +707,30 @@ private struct ServiceCard: View {
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.help(helpText) .help(helpText)
.overlay(alignment: .bottomTrailing) {
Button {
confirmDelete = true
} label: {
Image(systemName: "trash")
.font(.system(size: 8, weight: .semibold))
.foregroundStyle(LP.danger.opacity(0.65))
.padding(3)
}
.buttonStyle(.plain)
.help("Gottesdienst löschen")
}
.confirmationDialog(
"Gottesdienst löschen?",
isPresented: $confirmDelete,
titleVisibility: .visible
) {
Button("Endgültig löschen", role: .destructive) {
model.deleteService(service.service)
}
Button("Abbrechen", role: .cancel) {}
} message: {
Text("Der Termin und alle zugehörigen Einsätze werden entfernt. Die Gottesdienstordnung bleibt unverändert.")
}
} }
private func roleLine(role: Role) -> some View { private func roleLine(role: Role) -> some View {
@@ -713,7 +751,12 @@ private struct ServiceCard: View {
} else { } else {
ForEach(assigned) { assignment in ForEach(assigned) { assignment in
if let person = model.peopleByID[assignment.personID] { if let person = model.peopleByID[assignment.personID] {
PersonMiniChip(person: person, role: role, color: churchColor) PersonMiniChip(
person: person,
role: role,
color: churchColor,
beyond: assignment.beyondPreferences
)
} }
} }
if open > 0 { if open > 0 {
@@ -742,6 +785,9 @@ private struct ServiceCard: View {
if !liturgy.remark.isEmpty { lines.append(liturgy.remark) } if !liturgy.remark.isEmpty { lines.append(liturgy.remark) }
} }
if !service.service.notes.isEmpty { lines.append(service.service.notes) } if !service.service.notes.isEmpty { lines.append(service.service.notes) }
if service.assignments.contains(where: \.beyondPreferences) {
lines.append("Mindestens ein Einsatz geht über die Präferenzen hinaus")
}
lines.append("Klicken zum Bearbeiten") lines.append("Klicken zum Bearbeiten")
return lines.joined(separator: "\n") return lines.joined(separator: "\n")
} }
@@ -45,6 +45,7 @@ struct ServiceDetailSheet: View {
.foregroundStyle(LP.inkSecondary) .foregroundStyle(LP.inkSecondary)
} }
.buttonStyle(.plain) .buttonStyle(.plain)
}
Button { Button {
confirmDelete = true confirmDelete = true
@@ -54,8 +55,8 @@ struct ServiceDetailSheet: View {
.foregroundStyle(LP.danger) .foregroundStyle(LP.danger)
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.help("Sondergottesdienst löschen") .help("Gottesdienst löschen")
}
Spacer() Spacer()
SecondaryActionButton(title: "Schließen", icon: "xmark") { dismiss() } SecondaryActionButton(title: "Schließen", icon: "xmark") { dismiss() }
PrimaryActionButton(title: "Automatisch besetzen", icon: "wand.and.stars") { PrimaryActionButton(title: "Automatisch besetzen", icon: "wand.and.stars") {
@@ -79,11 +80,11 @@ struct ServiceDetailSheet: View {
} }
} }
.confirmationDialog( .confirmationDialog(
"Sondergottesdienst löschen?", "Gottesdienst löschen?",
isPresented: $confirmDelete, isPresented: $confirmDelete,
titleVisibility: .visible titleVisibility: .visible
) { ) {
Button("Löschen", role: .destructive) { Button("Endgültig löschen", role: .destructive) {
if let item { if let item {
model.deleteService(item.service) model.deleteService(item.service)
} }
@@ -91,7 +92,7 @@ struct ServiceDetailSheet: View {
} }
Button("Abbrechen", role: .cancel) {} Button("Abbrechen", role: .cancel) {}
} message: { } message: {
Text("Der Termin und alle zugehörigen Einsätze werden entfernt.") Text("Der Termin und alle zugehörigen Einsätze werden entfernt. Die Gottesdienstordnung bleibt unverändert.")
} }
} }
@@ -286,12 +287,24 @@ struct ServiceDetailSheet: View {
HStack(spacing: 8) { HStack(spacing: 8) {
Avatar(initials: person.initials, color: LP.churchColor(item.church.colorHex), size: 24) Avatar(initials: person.initials, color: LP.churchColor(item.church.colorHex), size: 24)
VStack(alignment: .leading, spacing: 1) { VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 5) {
Text(person.fullName) Text(person.fullName)
.font(.system(size: 11, weight: .medium)) .font(.system(size: 11, weight: .medium))
.foregroundStyle(LP.ink) .foregroundStyle(LP.ink)
if assignment.beyondPreferences {
TinyBadge(text: "ÜBER PRÄFERENZEN", color: LP.burgundy)
}
}
Text(person.roleLabel) Text(person.roleLabel)
.font(.system(size: 8.5)) .font(.system(size: 8.5))
.foregroundStyle(LP.inkTertiary) .foregroundStyle(LP.inkTertiary)
if !person.preferenceNote.isEmpty {
Text(person.preferenceNote)
.font(.system(size: 8.5))
.italic()
.foregroundStyle(LP.inkSecondary)
.fixedSize(horizontal: false, vertical: true)
}
} }
Spacer() Spacer()
Button { Button {
@@ -400,6 +413,16 @@ struct ServiceDetailSheet: View {
if candidate.person.roles.contains(.lector) && candidate.person.roles.contains(.helper) { if candidate.person.roles.contains(.lector) && candidate.person.roles.contains(.helper) {
TinyBadge(text: "L+K", color: LP.accent) TinyBadge(text: "L+K", color: LP.accent)
} }
if candidate.beyondPreferences {
TinyBadge(text: "ÜBER PRÄFERENZEN", color: LP.burgundy)
}
}
if !candidate.person.preferenceNote.isEmpty {
Text(candidate.person.preferenceNote)
.font(.system(size: 8.5))
.italic()
.foregroundStyle(LP.inkSecondary)
.lineLimit(2)
} }
HStack(spacing: 6) { HStack(spacing: 6) {
Text("\(candidate.totalAssignments) Einsätze im Zeitraum") Text("\(candidate.totalAssignments) Einsätze im Zeitraum")
+58 -15
View File
@@ -47,6 +47,7 @@ public final class AppDatabase {
CREATE TABLE IF NOT EXISTS people ( CREATE TABLE IF NOT EXISTS people (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
short_code TEXT NOT NULL DEFAULT '',
first_name TEXT NOT NULL, first_name TEXT NOT NULL,
last_name TEXT NOT NULL, last_name TEXT NOT NULL,
roles TEXT NOT NULL, roles TEXT NOT NULL,
@@ -54,8 +55,10 @@ public final class AppDatabase {
phone TEXT NOT NULL DEFAULT '', phone TEXT NOT NULL DEFAULT '',
preferred_church_ids TEXT NOT NULL DEFAULT '[]', preferred_church_ids TEXT NOT NULL DEFAULT '[]',
preferred_weekdays TEXT NOT NULL DEFAULT '[]', preferred_weekdays TEXT NOT NULL DEFAULT '[]',
preferred_weekday_periods TEXT NOT NULL DEFAULT '[]',
preferred_service_titles TEXT NOT NULL DEFAULT '[]', preferred_service_titles TEXT NOT NULL DEFAULT '[]',
max_per_month INTEGER NOT NULL DEFAULT 6, max_per_month INTEGER NOT NULL DEFAULT 6,
allow_beyond_preferences INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1, active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT '' notes TEXT NOT NULL DEFAULT ''
); );
@@ -118,6 +121,7 @@ public final class AppDatabase {
person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE, person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE,
role TEXT NOT NULL, role TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0, locked INTEGER NOT NULL DEFAULT 0,
beyond_preferences INTEGER NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL, created_at TEXT NOT NULL,
UNIQUE(service_id, person_id, role) UNIQUE(service_id, person_id, role)
@@ -178,7 +182,14 @@ public final class AppDatabase {
column: "location", column: "location",
definition: "TEXT NOT NULL DEFAULT ''" definition: "TEXT NOT NULL DEFAULT ''"
) )
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '3')") // People gained a Kürzel, weekday time periods and permission to be
// planned beyond their preferences.
try addColumnIfMissing(table: "people", column: "short_code", definition: "TEXT NOT NULL DEFAULT ''")
try addColumnIfMissing(table: "people", column: "preferred_weekday_periods", definition: "TEXT NOT NULL DEFAULT '[]'")
try addColumnIfMissing(table: "people", column: "allow_beyond_preferences", definition: "INTEGER NOT NULL DEFAULT 0")
// Assignments record when a volunteer was planned beyond preferences.
try addColumnIfMissing(table: "assignments", column: "beyond_preferences", definition: "INTEGER NOT NULL DEFAULT 0")
try database.run("INSERT OR REPLACE INTO settings(key, value) VALUES('schemaVersion', '4')")
} }
private func addColumnIfMissing(table: String, column: String, definition: String) throws { private func addColumnIfMissing(table: String, column: String, definition: String) throws {
@@ -246,22 +257,30 @@ public final class AppDatabase {
let roles = encode(person.roles.map(\.rawValue).sorted()) let roles = encode(person.roles.map(\.rawValue).sorted())
let churches = encode(person.preferredChurchIDs.sorted()) let churches = encode(person.preferredChurchIDs.sorted())
let weekdays = encode(person.preferredWeekdays.sorted()) let weekdays = encode(person.preferredWeekdays.sorted())
let periods = encode(person.preferredWeekdayPeriods.sorted { $0.weekday < $1.weekday })
let titles = encode(person.preferredServiceTitles) let titles = encode(person.preferredServiceTitles)
try database.run(""" try database.run("""
INSERT INTO people(id, first_name, last_name, roles, email, phone, preferred_church_ids, INSERT INTO people(id, short_code, first_name, last_name, roles, email, phone, preferred_church_ids,
preferred_weekdays, preferred_service_titles, max_per_month, active, notes) preferred_weekdays, preferred_weekday_periods, preferred_service_titles,
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) max_per_month, allow_beyond_preferences, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET ON CONFLICT(id) DO UPDATE SET
short_code=excluded.short_code,
first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles, first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
email=excluded.email, phone=excluded.phone, email=excluded.email, phone=excluded.phone,
preferred_church_ids=excluded.preferred_church_ids, preferred_church_ids=excluded.preferred_church_ids,
preferred_weekdays=excluded.preferred_weekdays, preferred_weekdays=excluded.preferred_weekdays,
preferred_weekday_periods=excluded.preferred_weekday_periods,
preferred_service_titles=excluded.preferred_service_titles, preferred_service_titles=excluded.preferred_service_titles,
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes max_per_month=excluded.max_per_month,
allow_beyond_preferences=excluded.allow_beyond_preferences,
active=excluded.active, notes=excluded.notes
""", [ """, [
.text(person.id), .text(person.firstName), .text(person.lastName), .text(roles), .text(person.id), .text(person.shortCode.trimmingCharacters(in: .whitespacesAndNewlines)),
.text(person.firstName), .text(person.lastName), .text(roles),
.text(person.email), .text(person.phone), .text(churches), .text(weekdays), .text(person.email), .text(person.phone), .text(churches), .text(weekdays),
.text(titles), .int(person.maxPerMonth), .bool(person.active), .text(person.notes) .text(periods), .text(titles), .int(person.maxPerMonth),
.bool(person.allowBeyondPreferences), .bool(person.active), .text(person.notes)
]) ])
} }
@@ -277,6 +296,7 @@ public final class AppDatabase {
let roleStrings: [String] = decode(row.string("roles", default: "[]")) let roleStrings: [String] = decode(row.string("roles", default: "[]"))
return Person( return Person(
id: id, id: id,
shortCode: row.string("short_code", default: ""),
firstName: first, firstName: first,
lastName: last, lastName: last,
roles: Set(roleStrings.compactMap(Role.init(rawValue:))), roles: Set(roleStrings.compactMap(Role.init(rawValue:))),
@@ -284,8 +304,10 @@ public final class AppDatabase {
phone: row.string("phone", default: ""), phone: row.string("phone", default: ""),
preferredChurchIDs: Set(decode(row.string("preferred_church_ids", default: "[]")) as [String]), preferredChurchIDs: Set(decode(row.string("preferred_church_ids", default: "[]")) as [String]),
preferredWeekdays: Set(decode(row.string("preferred_weekdays", default: "[]")) as [Int]), preferredWeekdays: Set(decode(row.string("preferred_weekdays", default: "[]")) as [Int]),
preferredWeekdayPeriods: decode(row.string("preferred_weekday_periods", default: "[]")),
preferredServiceTitles: decode(row.string("preferred_service_titles", default: "[]")), preferredServiceTitles: decode(row.string("preferred_service_titles", default: "[]")),
maxPerMonth: row.int("max_per_month", default: 6), maxPerMonth: row.int("max_per_month", default: 6),
allowBeyondPreferences: row.bool("allow_beyond_preferences", default: false),
active: row.bool("active", default: true), active: row.bool("active", default: true),
notes: row.string("notes", default: "") notes: row.string("notes", default: "")
) )
@@ -545,29 +567,49 @@ public final class AppDatabase {
public func upsert(_ assignment: Assignment) throws { public func upsert(_ assignment: Assignment) throws {
try database.run(""" try database.run("""
INSERT INTO assignments(id, service_id, person_id, role, locked, note, created_at) INSERT INTO assignments(id, service_id, person_id, role, locked, beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?) VALUES(?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET service_id=excluded.service_id, person_id=excluded.person_id, ON CONFLICT(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
""", [ """, [
.text(assignment.id), .text(assignment.serviceID), .text(assignment.personID), .text(assignment.id), .text(assignment.serviceID), .text(assignment.personID),
.text(assignment.role.rawValue), .bool(assignment.locked), .text(assignment.note), .text(assignment.role.rawValue), .bool(assignment.locked),
.bool(assignment.beyondPreferences), .text(assignment.note),
.text(ISO8601DateFormatter().string(from: assignment.createdAt)) .text(ISO8601DateFormatter().string(from: assignment.createdAt))
]) ])
} }
/// Replaces the assignment for one role of a service. Passing nil clears the slot. /// Replaces the assignment for one role of a service. Passing nil clears the slot.
public func setAssignment(serviceID: String, role: Role, personID: String?, locked: Bool = false) throws { public func setAssignment(
serviceID: String,
role: Role,
personID: String?,
locked: Bool = false,
beyondPreferences: Bool = false
) throws {
try database.transaction { try database.transaction {
try database.run("DELETE FROM assignments WHERE service_id=? AND role=?", [.text(serviceID), .text(role.rawValue)]) try database.run("DELETE FROM assignments WHERE service_id=? AND role=?", [.text(serviceID), .text(role.rawValue)])
guard let personID else { return } guard let personID else { return }
let assignment = Assignment(serviceID: serviceID, personID: personID, role: role, locked: locked) let assignment = Assignment(
serviceID: serviceID, personID: personID, role: role,
locked: locked, beyondPreferences: beyondPreferences
)
try upsert(assignment) try upsert(assignment)
} }
} }
public func setAssignment(serviceID: String, personID: String?, role: Role, locked: Bool = false) throws { public func setAssignment(
try setAssignment(serviceID: serviceID, role: role, personID: personID, locked: locked) serviceID: String,
personID: String?,
role: Role,
locked: Bool = false,
beyondPreferences: Bool = false
) throws {
try setAssignment(
serviceID: serviceID, role: role, personID: personID,
locked: locked, beyondPreferences: beyondPreferences
)
} }
public func deleteAssignment(id: String) throws { public func deleteAssignment(id: String) throws {
@@ -605,6 +647,7 @@ public final class AppDatabase {
personID: personID, personID: personID,
role: role, role: role,
locked: row.bool("locked", default: false), locked: row.bool("locked", default: false),
beyondPreferences: row.bool("beyond_preferences", default: false),
note: row.string("note", default: ""), note: row.string("note", default: ""),
createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date() createdAt: ISO8601DateFormatter().date(from: row.string("created_at", default: "")) ?? Date()
) )
+164
View File
@@ -107,8 +107,58 @@ public struct Church: Identifiable, Codable, Hashable, Sendable {
// MARK: - People // MARK: - People
public enum WeekdayPeriod: String, Codable, CaseIterable, Identifiable, Sendable, Hashable {
case all
case morning
case afternoon
case evening
public var id: String { rawValue }
public var label: String {
switch self {
case .morning: "vormittags (0–12 Uhr)"
case .afternoon: "nachmittags (12–17 Uhr)"
case .evening: "abends (ab 17 Uhr)"
case .all: "ganztägig"
}
}
public var shortLabel: String {
switch self {
case .morning: "vormittags"
case .afternoon: "nachmittags"
case .evening: "abends"
case .all: "ganztägig"
}
}
/// Morning is 0–12, afternoon 12–17, evening after 17.
public func matches(timeMinutes: Int) -> Bool {
switch self {
case .morning: timeMinutes < 12 * 60
case .afternoon: timeMinutes >= 12 * 60 && timeMinutes < 17 * 60
case .evening: timeMinutes >= 17 * 60
case .all: true
}
}
}
public struct WeekdayPeriodPreference: Codable, Hashable, Sendable, Identifiable {
public var weekday: Int
public var period: WeekdayPeriod
public var id: Int { weekday }
public init(weekday: Int, period: WeekdayPeriod = .all) {
self.weekday = weekday
self.period = period
}
}
public struct Person: Identifiable, Codable, Hashable, Sendable { public struct Person: Identifiable, Codable, Hashable, Sendable {
public var id: String public var id: String
public var shortCode: String
public var firstName: String public var firstName: String
public var lastName: String public var lastName: String
public var roles: Set<Role> public var roles: Set<Role>
@@ -116,13 +166,16 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
public var phone: String public var phone: String
public var preferredChurchIDs: Set<String> public var preferredChurchIDs: Set<String>
public var preferredWeekdays: Set<Int> // 1 = Sunday … 7 = Saturday; empty = no preference public var preferredWeekdays: Set<Int> // 1 = Sunday … 7 = Saturday; empty = no preference
public var preferredWeekdayPeriods: [WeekdayPeriodPreference]
public var preferredServiceTitles: [String] public var preferredServiceTitles: [String]
public var maxPerMonth: Int public var maxPerMonth: Int
public var allowBeyondPreferences: Bool
public var active: Bool public var active: Bool
public var notes: String public var notes: String
public init( public init(
id: String = UUID().uuidString, id: String = UUID().uuidString,
shortCode: String = "",
firstName: String, firstName: String,
lastName: String, lastName: String,
roles: Set<Role> = [.lector], roles: Set<Role> = [.lector],
@@ -130,12 +183,15 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
phone: String = "", phone: String = "",
preferredChurchIDs: Set<String> = [], preferredChurchIDs: Set<String> = [],
preferredWeekdays: Set<Int> = [], preferredWeekdays: Set<Int> = [],
preferredWeekdayPeriods: [WeekdayPeriodPreference] = [],
preferredServiceTitles: [String] = [], preferredServiceTitles: [String] = [],
maxPerMonth: Int = 6, maxPerMonth: Int = 6,
allowBeyondPreferences: Bool = false,
active: Bool = true, active: Bool = true,
notes: String = "" notes: String = ""
) { ) {
self.id = id self.id = id
self.shortCode = shortCode
self.firstName = firstName self.firstName = firstName
self.lastName = lastName self.lastName = lastName
self.roles = roles self.roles = roles
@@ -143,12 +199,42 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
self.phone = phone self.phone = phone
self.preferredChurchIDs = preferredChurchIDs self.preferredChurchIDs = preferredChurchIDs
self.preferredWeekdays = preferredWeekdays self.preferredWeekdays = preferredWeekdays
self.preferredWeekdayPeriods = preferredWeekdayPeriods
self.preferredServiceTitles = preferredServiceTitles self.preferredServiceTitles = preferredServiceTitles
self.maxPerMonth = maxPerMonth self.maxPerMonth = maxPerMonth
self.allowBeyondPreferences = allowBeyondPreferences
self.active = active self.active = active
self.notes = notes self.notes = notes
} }
private enum CodingKeys: String, CodingKey {
case id, shortCode, firstName, lastName, roles, email, phone
case preferredChurchIDs, preferredWeekdays, preferredWeekdayPeriods
case preferredServiceTitles, maxPerMonth, allowBeyondPreferences
case active, notes
}
/// Older exchange files and backups predate the Kürzel, weekday periods and
/// the beyond-preferences flag, so every new key falls back to a default.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
shortCode = try container.decodeIfPresent(String.self, forKey: .shortCode) ?? ""
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
roles = try container.decodeIfPresent(Set<Role>.self, forKey: .roles) ?? [.lector]
email = try container.decodeIfPresent(String.self, forKey: .email) ?? ""
phone = try container.decodeIfPresent(String.self, forKey: .phone) ?? ""
preferredChurchIDs = try container.decodeIfPresent(Set<String>.self, forKey: .preferredChurchIDs) ?? []
preferredWeekdays = try container.decodeIfPresent(Set<Int>.self, forKey: .preferredWeekdays) ?? []
preferredWeekdayPeriods = try container.decodeIfPresent([WeekdayPeriodPreference].self, forKey: .preferredWeekdayPeriods) ?? []
preferredServiceTitles = try container.decodeIfPresent([String].self, forKey: .preferredServiceTitles) ?? []
maxPerMonth = try container.decodeIfPresent(Int.self, forKey: .maxPerMonth) ?? 6
allowBeyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .allowBeyondPreferences) ?? false
active = try container.decodeIfPresent(Bool.self, forKey: .active) ?? true
notes = try container.decodeIfPresent(String.self, forKey: .notes) ?? ""
}
public var fullName: String { public var fullName: String {
"\(firstName) \(lastName)".trimmingCharacters(in: .whitespaces) "\(firstName) \(lastName)".trimmingCharacters(in: .whitespaces)
} }
@@ -176,6 +262,34 @@ public struct Person: Identifiable, Codable, Hashable, Sendable {
} }
public func canFill(_ role: Role) -> Bool { roles.contains(role) } public func canFill(_ role: Role) -> Bool { roles.contains(role) }
/// Guest-facing label: an explicitly maintained Kürzel wins, otherwise the
/// initials from first and last name.
public var displayShort: String {
let code = shortCode.trimmingCharacters(in: .whitespacesAndNewlines)
return code.isEmpty ? initials : code
}
public func weekdayPeriod(for weekday: Int) -> WeekdayPeriod {
preferredWeekdayPeriods.first { $0.weekday == weekday }?.period ?? .all
}
/// High feasts count like Sundays, so a Sunday preference also covers them.
/// An empty weekday list means no restriction.
public func matchesWeekdayPreference(weekday: Int, timeMinutes: Int, highFeast: Bool) -> Bool {
guard !preferredWeekdays.isEmpty else { return true }
var candidates = [weekday]
if highFeast && weekday != 1 { candidates.append(1) }
for day in candidates where preferredWeekdays.contains(day) {
if weekdayPeriod(for: day).matches(timeMinutes: timeMinutes) { return true }
}
return false
}
/// Free-text planning note shown next to assignments and candidates.
public var preferenceNote: String {
notes.trimmingCharacters(in: .whitespacesAndNewlines)
}
} }
public struct Absence: Identifiable, Codable, Hashable, Sendable { public struct Absence: Identifiable, Codable, Hashable, Sendable {
@@ -380,6 +494,7 @@ public struct Assignment: Identifiable, Codable, Hashable, Sendable {
public var personID: String public var personID: String
public var role: Role public var role: Role
public var locked: Bool public var locked: Bool
public var beyondPreferences: Bool
public var note: String public var note: String
public var createdAt: Date public var createdAt: Date
@@ -389,6 +504,7 @@ public struct Assignment: Identifiable, Codable, Hashable, Sendable {
personID: String, personID: String,
role: Role, role: Role,
locked: Bool = false, locked: Bool = false,
beyondPreferences: Bool = false,
note: String = "", note: String = "",
createdAt: Date = Date() createdAt: Date = Date()
) { ) {
@@ -397,9 +513,28 @@ public struct Assignment: Identifiable, Codable, Hashable, Sendable {
self.personID = personID self.personID = personID
self.role = role self.role = role
self.locked = locked self.locked = locked
self.beyondPreferences = beyondPreferences
self.note = note self.note = note
self.createdAt = createdAt self.createdAt = createdAt
} }
private enum CodingKeys: String, CodingKey {
case id, serviceID, personID, role, locked, beyondPreferences, note, createdAt
}
/// Exchange files created before the beyond-preferences marker decode to
/// the ordinary case.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
serviceID = try container.decode(String.self, forKey: .serviceID)
personID = try container.decode(String.self, forKey: .personID)
role = try container.decode(Role.self, forKey: .role)
locked = try container.decodeIfPresent(Bool.self, forKey: .locked) ?? false
beyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .beyondPreferences) ?? false
note = try container.decodeIfPresent(String.self, forKey: .note) ?? ""
createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
}
} }
// MARK: - Liturgy // MARK: - Liturgy
@@ -710,6 +845,13 @@ public struct DayPlanRow: Identifiable, Hashable, Sendable {
public var openSlots: Int { services.reduce(0) { $0 + $1.openSlots } } public var openSlots: Int { services.reduce(0) { $0 + $1.openSlots } }
public var assignmentCount: Int { services.reduce(0) { $0 + $1.assignments.count } } public var assignmentCount: Int { services.reduce(0) { $0 + $1.assignments.count } }
public var hasServices: Bool { !services.isEmpty } public var hasServices: Bool { !services.isEmpty }
/// Marks days with at least one assignment beyond the person's preferences.
public var hasBeyondPreferences: Bool {
services.contains { service in
service.assignments.contains(where: \.beyondPreferences)
}
}
} }
public struct UnfilledSlot: Identifiable, Hashable, Sendable { public struct UnfilledSlot: Identifiable, Hashable, Sendable {
@@ -898,6 +1040,7 @@ public struct ExchangeSummary: Hashable, Sendable {
public struct PlannerOptions: Codable, Hashable, Sendable { public struct PlannerOptions: Codable, Hashable, Sendable {
public var replaceExisting: Bool public var replaceExisting: Bool
public var respectPreferredWeekdays: Bool public var respectPreferredWeekdays: Bool
public var allowBeyondPreferences: Bool
public var allowDoubleRolesOnSameDay: Bool public var allowDoubleRolesOnSameDay: Bool
public var weightChurchPreference: Double public var weightChurchPreference: Double
public var weightServicePreference: Double public var weightServicePreference: Double
@@ -908,6 +1051,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
public init( public init(
replaceExisting: Bool = false, replaceExisting: Bool = false,
respectPreferredWeekdays: Bool = true, respectPreferredWeekdays: Bool = true,
allowBeyondPreferences: Bool = false,
allowDoubleRolesOnSameDay: Bool = false, allowDoubleRolesOnSameDay: Bool = false,
weightChurchPreference: Double = 8, weightChurchPreference: Double = 8,
weightServicePreference: Double = 4, weightServicePreference: Double = 4,
@@ -917,6 +1061,7 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
) { ) {
self.replaceExisting = replaceExisting self.replaceExisting = replaceExisting
self.respectPreferredWeekdays = respectPreferredWeekdays self.respectPreferredWeekdays = respectPreferredWeekdays
self.allowBeyondPreferences = allowBeyondPreferences
self.allowDoubleRolesOnSameDay = allowDoubleRolesOnSameDay self.allowDoubleRolesOnSameDay = allowDoubleRolesOnSameDay
self.weightChurchPreference = weightChurchPreference self.weightChurchPreference = weightChurchPreference
self.weightServicePreference = weightServicePreference self.weightServicePreference = weightServicePreference
@@ -924,6 +1069,25 @@ public struct PlannerOptions: Codable, Hashable, Sendable {
self.weightDualRolePreference = weightDualRolePreference self.weightDualRolePreference = weightDualRolePreference
self.maxAssignmentsPerDay = maxAssignmentsPerDay self.maxAssignmentsPerDay = maxAssignmentsPerDay
} }
private enum CodingKeys: String, CodingKey {
case replaceExisting, respectPreferredWeekdays, allowBeyondPreferences
case allowDoubleRolesOnSameDay, weightChurchPreference, weightServicePreference
case weightFairness, weightDualRolePreference, maxAssignmentsPerDay
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
replaceExisting = try container.decodeIfPresent(Bool.self, forKey: .replaceExisting) ?? false
respectPreferredWeekdays = try container.decodeIfPresent(Bool.self, forKey: .respectPreferredWeekdays) ?? true
allowBeyondPreferences = try container.decodeIfPresent(Bool.self, forKey: .allowBeyondPreferences) ?? false
allowDoubleRolesOnSameDay = try container.decodeIfPresent(Bool.self, forKey: .allowDoubleRolesOnSameDay) ?? false
weightChurchPreference = try container.decodeIfPresent(Double.self, forKey: .weightChurchPreference) ?? 8
weightServicePreference = try container.decodeIfPresent(Double.self, forKey: .weightServicePreference) ?? 4
weightFairness = try container.decodeIfPresent(Double.self, forKey: .weightFairness) ?? 2.2
weightDualRolePreference = try container.decodeIfPresent(Double.self, forKey: .weightDualRolePreference) ?? 14
maxAssignmentsPerDay = try container.decodeIfPresent(Int.self, forKey: .maxAssignmentsPerDay) ?? 1
}
} }
public struct PlanResult: Sendable { public struct PlanResult: Sendable {
+75 -8
View File
@@ -6,6 +6,7 @@ public struct ServicePlanner {
public var services: [ServiceOccurrence] public var services: [ServiceOccurrence]
public var existingAssignments: [Assignment] public var existingAssignments: [Assignment]
public var churches: [Church] public var churches: [Church]
public var liturgicalDays: [LiturgicalDay]
public var options: PlannerOptions public var options: PlannerOptions
public init( public init(
@@ -14,6 +15,7 @@ public struct ServicePlanner {
services: [ServiceOccurrence], services: [ServiceOccurrence],
existingAssignments: [Assignment] = [], existingAssignments: [Assignment] = [],
churches: [Church] = [], churches: [Church] = [],
liturgicalDays: [LiturgicalDay] = [],
options: PlannerOptions = PlannerOptions() options: PlannerOptions = PlannerOptions()
) { ) {
self.people = people self.people = people
@@ -21,6 +23,7 @@ public struct ServicePlanner {
self.services = services self.services = services
self.existingAssignments = existingAssignments self.existingAssignments = existingAssignments
self.churches = churches self.churches = churches
self.liturgicalDays = liturgicalDays
self.options = options self.options = options
} }
@@ -29,6 +32,7 @@ public struct ServicePlanner {
let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) }) let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) })
let absencesByPerson = Dictionary(grouping: absences, by: \.personID) let absencesByPerson = Dictionary(grouping: absences, by: \.personID)
let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) }) let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) })
let highFeastDates = Set(liturgicalDays.filter(\.isHighFeast).map(\.dateKey))
var working: [Assignment] var working: [Assignment]
if options.replaceExisting { if options.replaceExisting {
@@ -93,7 +97,9 @@ public struct ServicePlanner {
dayServicesByPerson: dayServicesByPerson, dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson, churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson, lastDateByPerson: lastDateByPerson,
assignedRolesByPerson: assignedRolesByPerson assignedRolesByPerson: assignedRolesByPerson,
highFeast: highFeastDates.contains(service.dateKey),
enforcePreferences: true
) )
switch result { switch result {
case .success(let person): case .success(let person):
@@ -122,6 +128,58 @@ public struct ServicePlanner {
} }
} }
// Second pass, only on explicit request: use volunteers who agreed to be
// planned beyond their preferences for the slots that remained open.
if options.allowBeyondPreferences, !unfilled.isEmpty {
let flagged = activePeople.filter(\.allowBeyondPreferences)
if !flagged.isEmpty {
var remaining: [UnfilledSlot] = []
for slot in unfilled {
let service = slot.service
var assignedRolesByPerson: [String: Set<Role>] = [:]
for assignment in working where assignment.serviceID == service.id {
assignedRolesByPerson[assignment.personID, default: []].insert(assignment.role)
}
let result = bestCandidate(
for: service,
role: slot.role,
people: flagged,
peopleByID: peopleByID,
absencesByPerson: absencesByPerson,
totalByPerson: totalByPerson,
monthByPerson: monthByPerson,
dayServicesByPerson: dayServicesByPerson,
churchByPerson: churchByPerson,
lastDateByPerson: lastDateByPerson,
assignedRolesByPerson: assignedRolesByPerson,
highFeast: highFeastDates.contains(service.dateKey),
enforcePreferences: false
)
switch result {
case .success(let person):
let assignment = Assignment(
serviceID: service.id,
personID: person.id,
role: slot.role,
beyondPreferences: true
)
newAssignments.append(assignment)
working.append(assignment)
totalByPerson[person.id, default: 0] += 1
monthByPerson["\(person.id)|\(DayMath.monthKey(service.date))", default: 0] += 1
dayServicesByPerson["\(person.id)|\(service.dateKey)", default: []].insert(service.id)
churchByPerson[person.id, default: [:]][service.churchID, default: 0] += 1
lastDateByPerson[person.id] = service.date
case .failure(let reason):
var updated = slot
updated.reason = reason
remaining.append(updated)
}
}
unfilled = remaining
}
}
let filled = newAssignments.count let filled = newAssignments.count
let message: String let message: String
if filled == 0 && unfilled.isEmpty { if filled == 0 && unfilled.isEmpty {
@@ -156,7 +214,9 @@ public struct ServicePlanner {
dayServicesByPerson: [String: Set<String>], dayServicesByPerson: [String: Set<String>],
churchByPerson: [String: [String: Int]], churchByPerson: [String: [String: Int]],
lastDateByPerson: [String: Date], lastDateByPerson: [String: Date],
assignedRolesByPerson: [String: Set<Role>] assignedRolesByPerson: [String: Set<Role>],
highFeast: Bool,
enforcePreferences: Bool
) -> CandidateResult { ) -> CandidateResult {
var blockedReasons: [String: Int] = [:] var blockedReasons: [String: Int] = [:]
var eligiblePeople: [Person] = [] var eligiblePeople: [Person] = []
@@ -171,15 +231,18 @@ public struct ServicePlanner {
blockedReasons["abwesend", default: 0] += 1 blockedReasons["abwesend", default: 0] += 1
continue continue
} }
if options.respectPreferredWeekdays, if options.respectPreferredWeekdays, enforcePreferences,
!person.preferredWeekdays.isEmpty, !person.matchesWeekdayPreference(
!person.preferredWeekdays.contains(DayMath.weekday(service.date)) { weekday: DayMath.weekday(service.date),
blockedReasons["Einsatztag passt nicht", default: 0] += 1 timeMinutes: service.timeMinutes,
highFeast: highFeast
) {
blockedReasons["Einsatztag oder Uhrzeit passt nicht", default: 0] += 1
continue continue
} }
let month = DayMath.monthKey(service.date) let month = DayMath.monthKey(service.date)
let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0] let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0]
if person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth { if enforcePreferences, person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth {
blockedReasons["Monatslimit erreicht", default: 0] += 1 blockedReasons["Monatslimit erreicht", default: 0] += 1
continue continue
} }
@@ -232,7 +295,11 @@ public struct ServicePlanner {
} }
} }
} }
if person.preferredWeekdays.contains(DayMath.weekday(service.date)) { if person.matchesWeekdayPreference(
weekday: DayMath.weekday(service.date),
timeMinutes: service.timeMinutes,
highFeast: highFeast
), !person.preferredWeekdays.isEmpty {
score += 3 score += 3
} }
score -= Double(total) * options.weightFairness score -= Double(total) * options.weightFairness
@@ -159,6 +159,76 @@ final class CoreTests: XCTestCase {
XCTAssertEqual(result.assignments.first?.personID, "b") XCTAssertEqual(result.assignments.first?.personID, "b")
} }
func testPlannerTreatsHighFeastLikeSundayAndHonoursPeriods() {
let monday = DayMath.date(fromKey: "2026-11-16")! // Monday
let person = Person(
id: "sunday", firstName: "Sara", lastName: "Sonntag", roles: [.lector],
preferredWeekdays: [1], maxPerMonth: 10
)
let morning = Person(
id: "morning", firstName: "Mia", lastName: "Morgen", roles: [.lector],
preferredWeekdays: [1],
preferredWeekdayPeriods: [WeekdayPeriodPreference(weekday: 1, period: .morning)],
maxPerMonth: 10
)
let eveningService = ServiceOccurrence(
churchID: "c1", date: monday, timeMinutes: 18 * 60,
title: "Hochfestmesse", lectorsNeeded: 1, helpersNeeded: 0
)
let highFeast = LiturgicalDay(date: monday, title: "Hochfest", rank: .solemnity)
let planner = ServicePlanner(
people: [person, morning],
absences: [],
services: [eveningService],
liturgicalDays: [highFeast]
)
let evening = planner.plan()
XCTAssertEqual(evening.assignments.first?.personID, "sunday")
XCTAssertEqual(evening.unfilled.count, 0)
XCTAssertFalse(evening.assignments.first?.beyondPreferences ?? true)
let morningService = ServiceOccurrence(
churchID: "c1", date: monday, timeMinutes: 10 * 60,
title: "Hochfestmesse", lectorsNeeded: 1, helpersNeeded: 0
)
let morningPlanner = ServicePlanner(
people: [morning],
absences: [],
services: [morningService],
liturgicalDays: [highFeast]
)
XCTAssertEqual(morningPlanner.plan().assignments.first?.personID, "morning")
}
func testPlannerFallbackRequiresPermissionAndMarksAssignments() {
let monday = DayMath.date(fromKey: "2026-11-16")!
let person = Person(
id: "p", firstName: "Paula", lastName: "Person", roles: [.lector],
preferredWeekdays: [1], maxPerMonth: 10
)
let service = ServiceOccurrence(
churchID: "c1", date: monday, timeMinutes: 18 * 60,
title: "Abendmesse", lectorsNeeded: 1, helpersNeeded: 0
)
let denied = ServicePlanner(
people: [person], absences: [], services: [service],
options: PlannerOptions(allowBeyondPreferences: true)
).plan()
XCTAssertEqual(denied.assignments.count, 0)
XCTAssertEqual(denied.unfilled.count, 1)
var permitted = person
permitted.allowBeyondPreferences = true
let allowed = ServicePlanner(
people: [permitted], absences: [], services: [service],
options: PlannerOptions(allowBeyondPreferences: true)
).plan()
XCTAssertEqual(allowed.assignments.count, 1)
XCTAssertEqual(allowed.unfilled.count, 0)
XCTAssertTrue(allowed.assignments.first?.beyondPreferences ?? false)
}
func testPlannerAssignsSamePersonToBothComplementaryRoles() { func testPlannerAssignsSamePersonToBothComplementaryRoles() {
let date = DayMath.date(fromKey: "2026-11-08")! // Sunday let date = DayMath.date(fromKey: "2026-11-08")! // Sunday
let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10) let dual = Person(id: "dual", firstName: "Dana", lastName: "Doppel", roles: [.lector, .helper], maxPerMonth: 10)
+159
View File
@@ -2,6 +2,8 @@ package domain
import ( import (
"fmt" "fmt"
"sort"
"strconv"
"strings" "strings"
"time" "time"
) )
@@ -89,8 +91,73 @@ type Church struct {
Notes string `json:"notes"` 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 { type Person struct {
ID string `json:"id"` ID string `json:"id"`
ShortCode string `json:"shortCode"`
FirstName string `json:"firstName"` FirstName string `json:"firstName"`
LastName string `json:"lastName"` LastName string `json:"lastName"`
Roles []Role `json:"roles"` Roles []Role `json:"roles"`
@@ -98,8 +165,10 @@ type Person struct {
EmailLocked bool `json:"-"` EmailLocked bool `json:"-"`
PreferredChurchIDs []string `json:"preferredChurchIDs"` PreferredChurchIDs []string `json:"preferredChurchIDs"`
PreferredWeekdays []int `json:"preferredWeekdays"` PreferredWeekdays []int `json:"preferredWeekdays"`
PreferredWeekdayPeriods []WeekdayPeriodPreference `json:"preferredWeekdayPeriods"`
PreferredServiceTitles []string `json:"preferredServiceTitles"` PreferredServiceTitles []string `json:"preferredServiceTitles"`
MaxPerMonth int `json:"maxPerMonth"` MaxPerMonth int `json:"maxPerMonth"`
AllowBeyondPreferences bool `json:"allowBeyondPreferences"`
Active bool `json:"active"` Active bool `json:"active"`
Notes string `json:"notes"` Notes string `json:"notes"`
} }
@@ -127,6 +196,80 @@ func (p Person) AbbreviatedName() string {
return p.LastName 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 { func (p Person) RoleLabel() string {
var parts []string var parts []string
for _, role := range AllRoles { for _, role := range AllRoles {
@@ -341,6 +484,7 @@ type Assignment struct {
PersonID string `json:"personID"` PersonID string `json:"personID"`
Role Role `json:"role"` Role Role `json:"role"`
Locked bool `json:"locked"` Locked bool `json:"locked"`
BeyondPreferences bool `json:"beyondPreferences"`
Note string `json:"note"` Note string `json:"note"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
} }
@@ -702,6 +846,19 @@ func (r DayPlanRow) AssignmentCount() int {
} }
func (r DayPlanRow) HasServices() bool { return len(r.Services) > 0 } 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 { func (r DayPlanRow) IsSunday() bool {
return (r.LiturgicalDay != nil && r.LiturgicalDay.IsSunday()) || IsSunday(r.Date) return (r.LiturgicalDay != nil && r.LiturgicalDay.IsSunday()) || IsSunday(r.Date)
} }
@@ -823,6 +980,7 @@ func (s RangeStatistics) AverageAssignments() float64 {
type PlannerOptions struct { type PlannerOptions struct {
ReplaceExisting bool ReplaceExisting bool
RespectPreferredWeekdays bool RespectPreferredWeekdays bool
AllowBeyondPreferences bool
AllowDoubleRolesOnSameDay bool AllowDoubleRolesOnSameDay bool
WeightChurchPreference float64 WeightChurchPreference float64
WeightServicePreference float64 WeightServicePreference float64
@@ -855,5 +1013,6 @@ type CandidateSuggestion struct {
Warnings []string Warnings []string
Blocked bool Blocked bool
Preferred bool Preferred bool
BeyondPreferences bool
TotalAssignments int TotalAssignments int
} }
+90 -10
View File
@@ -14,6 +14,7 @@ type ServicePlanner struct {
Services []ServiceOccurrence Services []ServiceOccurrence
ExistingAssignments []Assignment ExistingAssignments []Assignment
Churches []Church Churches []Church
LiturgicalDays []LiturgicalDay
Options PlannerOptions Options PlannerOptions
} }
@@ -41,6 +42,12 @@ func (p ServicePlanner) Plan() PlanResult {
for _, s := range p.Services { for _, s := range p.Services {
serviceByID[s.ID] = s 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)) working := make([]Assignment, 0, len(p.ExistingAssignments))
for _, a := range p.ExistingAssignments { for _, a := range p.ExistingAssignments {
@@ -129,9 +136,10 @@ func (p ServicePlanner) Plan() PlanResult {
continue continue
} }
for i := existingForRole; i < required; i++ { for i := existingForRole; i < required; i++ {
highFeast := highFeastByDate[service.DateKey()]
result := p.bestCandidate(service, role, activePeople, absencesByPerson, result := p.bestCandidate(service, role, activePeople, absencesByPerson,
totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson, totalByPerson, monthByPerson, dayServicesByPerson, churchByPerson,
lastDateByPerson, assignedRoles) lastDateByPerson, assignedRoles, highFeast, true)
if result.person == nil { if result.person == nil {
unfilled = append(unfilled, UnfilledSlot{ unfilled = append(unfilled, UnfilledSlot{
Service: service, 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) filled := len(newAssignments)
var message string var message string
switch { switch {
@@ -211,6 +272,8 @@ func (p ServicePlanner) bestCandidate(
churchByPerson map[string]map[string]int, churchByPerson map[string]map[string]int,
lastDateByPerson map[string]time.Time, lastDateByPerson map[string]time.Time,
assignedRolesByPerson map[string]map[Role]bool, assignedRolesByPerson map[string]map[Role]bool,
highFeast bool,
enforcePreferences bool,
) candidateResult { ) candidateResult {
blockedReasons := map[string]int{} blockedReasons := map[string]int{}
var eligible []Person var eligible []Person
@@ -237,14 +300,14 @@ func (p ServicePlanner) bestCandidate(
continue continue
} }
} }
if p.Options.RespectPreferredWeekdays && len(person.PreferredWeekdays) > 0 && if p.Options.RespectPreferredWeekdays && enforcePreferences &&
!IntContains(person.PreferredWeekdays, Weekday(service.Date)) { !person.MatchesWeekdayPreference(Weekday(service.Date), service.TimeMinutes, highFeast) {
blockedReasons["Einsatztag passt nicht"]++ blockedReasons["Einsatztag oder Uhrzeit passt nicht"]++
continue continue
} }
month := MonthKey(service.Date) month := MonthKey(service.Date)
usedThisMonth := monthByPerson[person.ID+"|"+month] usedThisMonth := monthByPerson[person.ID+"|"+month]
if person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth { if enforcePreferences && person.MaxPerMonth > 0 && usedThisMonth >= person.MaxPerMonth {
blockedReasons["Monatslimit erreicht"]++ blockedReasons["Monatslimit erreicht"]++
continue 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 += 3
} }
score -= float64(total) * p.Options.WeightFairness score -= float64(total) * p.Options.WeightFairness
@@ -377,6 +441,7 @@ func CandidateSuggestions(
services []ServiceOccurrence, services []ServiceOccurrence,
serviceAssignments []Assignment, serviceAssignments []Assignment,
ignorePreferredWeekdays bool, ignorePreferredWeekdays bool,
liturgicalDay *LiturgicalDay,
) []CandidateSuggestion { ) []CandidateSuggestion {
monthKey := MonthKey(service.Date) monthKey := MonthKey(service.Date)
serviceDateByID := map[string]ServiceOccurrence{} serviceDateByID := map[string]ServiceOccurrence{}
@@ -424,11 +489,13 @@ func CandidateSuggestions(
} }
const fairnessSlack = 1 const fairnessSlack = 1
weekday := Weekday(service.Date) weekday := Weekday(service.Date)
highFeast := liturgicalDay != nil && liturgicalDay.IsHighFeast()
var suggestions []CandidateSuggestion var suggestions []CandidateSuggestion
for _, person := range eligible { for _, person := range eligible {
var warnings []string var warnings []string
blocked := false blocked := false
beyond := false
for _, a := range absences { for _, a := range absences {
if a.PersonID == person.ID && a.Overlaps(service.Date) { if a.PersonID == person.ID && a.Overlaps(service.Date) {
warnings = append(warnings, "abwesend") warnings = append(warnings, "abwesend")
@@ -436,14 +503,27 @@ func CandidateSuggestions(
break break
} }
} }
if !ignorePreferredWeekdays && len(person.PreferredWeekdays) > 0 && !IntContains(person.PreferredWeekdays, weekday) { weekdayMatch := person.MatchesWeekdayPreference(weekday, service.TimeMinutes, highFeast)
warnings = append(warnings, "Einsatztag passt nicht") if !weekdayMatch {
switch {
case ignorePreferredWeekdays:
beyond = true
case person.AllowBeyondPreferences:
beyond = true
default:
warnings = append(warnings, "Einsatztag oder Uhrzeit passt nicht")
blocked = true blocked = true
} }
}
if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth { if person.MaxPerMonth > 0 && monthlyCounts[person.ID+"|"+monthKey] >= person.MaxPerMonth {
if person.AllowBeyondPreferences {
warnings = append(warnings, "Monatslimit")
beyond = true
} else {
warnings = append(warnings, "Monatslimit") warnings = append(warnings, "Monatslimit")
blocked = true blocked = true
} }
}
used := dayServices[person.ID+"|"+service.DateKey()] used := dayServices[person.ID+"|"+service.DateKey()]
if len(used) > 0 && !subsetOfSingle(used, service.ID) { if len(used) > 0 && !subsetOfSingle(used, service.ID) {
warnings = append(warnings, "bereits an diesem Tag") warnings = append(warnings, "bereits an diesem Tag")
@@ -473,7 +553,7 @@ func CandidateSuggestions(
if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) { if len(person.PreferredChurchIDs) > 0 && !StringContains(person.PreferredChurchIDs, service.ChurchID) {
score -= 2 score -= 2
} }
if IntContains(person.PreferredWeekdays, weekday) { if weekdayMatch && len(person.PreferredWeekdays) > 0 {
score += 3 score += 3
preferred = true preferred = true
} }
@@ -492,7 +572,7 @@ func CandidateSuggestions(
} }
suggestions = append(suggestions, CandidateSuggestion{ suggestions = append(suggestions, CandidateSuggestion{
Person: person, Score: score, Warnings: warnings, Blocked: blocked, 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
}
+88 -7
View File
@@ -135,14 +135,17 @@ CREATE TABLE IF NOT EXISTS churches (
CREATE TABLE IF NOT EXISTS people ( CREATE TABLE IF NOT EXISTS people (
tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
id TEXT NOT NULL, id TEXT NOT NULL,
short_code TEXT NOT NULL DEFAULT '',
first_name TEXT NOT NULL, first_name TEXT NOT NULL,
last_name TEXT NOT NULL, last_name TEXT NOT NULL,
roles TEXT NOT NULL, roles TEXT NOT NULL,
email TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '',
preferred_church_ids TEXT NOT NULL DEFAULT '[]', preferred_church_ids TEXT NOT NULL DEFAULT '[]',
preferred_weekdays TEXT NOT NULL DEFAULT '[]', preferred_weekdays TEXT NOT NULL DEFAULT '[]',
preferred_weekday_periods TEXT NOT NULL DEFAULT '[]',
preferred_service_titles TEXT NOT NULL DEFAULT '[]', preferred_service_titles TEXT NOT NULL DEFAULT '[]',
max_per_month INTEGER NOT NULL DEFAULT 6, max_per_month INTEGER NOT NULL DEFAULT 6,
allow_beyond_preferences INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1, active INTEGER NOT NULL DEFAULT 1,
notes TEXT NOT NULL DEFAULT '', notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (tenant_id, id) PRIMARY KEY (tenant_id, id)
@@ -215,6 +218,7 @@ CREATE TABLE IF NOT EXISTS assignments (
person_id TEXT NOT NULL, person_id TEXT NOT NULL,
role TEXT NOT NULL, role TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0, locked INTEGER NOT NULL DEFAULT 0,
beyond_preferences INTEGER NOT NULL DEFAULT 0,
note TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL, created_at TEXT NOT NULL,
PRIMARY KEY (tenant_id, id), 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, tenant_id TEXT PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
initialized_at TEXT NOT NULL 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 { 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) 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, if _, err := s.db.ExecContext(ctx,
"INSERT INTO schema_meta(key, value) VALUES('schemaVersion', '5') "+ "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', '7') "+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil { "ON CONFLICT(key) DO UPDATE SET value=excluded.value"); err != nil {
return fmt.Errorf("record schema version: %w", err) 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. // 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, if _, err := s.db.ExecContext(ctx,
"DELETE FROM key_wrappers WHERE user_id IN (SELECT id FROM users WHERE role='admin')"); err != nil { "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) 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, ` if _, err := s.db.ExecContext(ctx, `
DELETE FROM key_wrappers WHERE user_id IN ( DELETE FROM key_wrappers WHERE user_id IN (
SELECT u.id FROM users u WHERE u.role='reader' AND ( SELECT id FROM users WHERE role='reader'
u.linked_tenant_id='' OR u.linked_person_id='' OR NOT ( ) AND NOT EXISTS (
key_wrappers.scope_type='person' 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.tenant_id=u.linked_tenant_id
AND key_wrappers.scope_id=u.linked_person_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 { )`); 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 // Dispatch logs used to contain the full recipient address. Remove that
// plaintext now that addresses are stored encrypted. // 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 // KeyScope identifies one encrypted data scope. Tenant scopes hold the SMTP
// credentials, person scopes hold e-mail addresses. Editors hold the person // 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 // scopes of their tenants; a reader holds the scope of the person linked to
// to their account. // their account and the scopes that other readers have shared with them.
type KeyScope struct { type KeyScope struct {
Type string Type string
TenantID string TenantID string
@@ -62,6 +62,14 @@ func (k *Keyring) remember(scope KeyScope, dek []byte) {
k.deks[scope.String()] = append([]byte{}, dek...) 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{} type keyringContextKey struct{}
// WithKeyring attaches an unlocked keyring to a request context. // 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 != "" { if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" {
recipients = append(recipients, 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 { if err := s.grantScope(ctx, keyring, scope, recipients); err != nil {
rememberError(err) 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 // 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 // active editors, the linked reader and every reader the owner shared their
// with a reader keyring that already holds the person's data key; the latter // address with. It works with an editor keyring and with a reader keyring that
// lets a reader refresh editor access after a new editor was created. // 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 { func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantID, personID string) error {
if keyring == nil || !s.SecretIsInitialized(ctx, tenantID) { if keyring == nil || !s.SecretIsInitialized(ctx, tenantID) {
return nil return nil
@@ -681,6 +696,11 @@ func (s *Store) EnsurePersonScope(ctx context.Context, keyring *Keyring, tenantI
if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" { if linked := s.linkedReaderForPerson(ctx, tenantID, personID); linked != "" {
recipients = append(recipients, 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) 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 // PruneUserWrappers enforces the key access policy. Editors keep the scopes of
// their tenant memberships. A reader may hold exactly one wrapper: the person // their tenant memberships. A reader keeps the person scope they are linked to
// scope of the account they are linked to. Administrators never hold key // plus every person scope that its owner has shared with the account.
// material. // Administrators never hold key material.
func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error { func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error {
var role, linkedTenantID, linkedPersonID string var role, linkedTenantID, linkedPersonID string
var active int var active int
@@ -826,8 +846,13 @@ func (s *Store) PruneUserWrappers(ctx context.Context, userID string) error {
} }
_, err = s.db.ExecContext(ctx, ` _, err = s.db.ExecContext(ctx, `
DELETE FROM key_wrappers WHERE user_id=? AND NOT ( DELETE FROM key_wrappers WHERE user_id=? AND NOT (
scope_type='person' AND tenant_id=? AND scope_id=? scope_type='person' AND tenant_id=? AND (
)`, userID, linkedTenantID, linkedPersonID) 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 return err
} }
+60 -15
View File
@@ -49,6 +49,25 @@ func encodeInts(values []int) string {
return string(data) 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. // Churches lists a tenant's churches.
func (s *Store) Churches(ctx context.Context, tenantID string) ([]domain.Church, error) { func (s *Store) Churches(ctx context.Context, tenantID string) ([]domain.Church, error) {
rows, err := s.db.QueryContext(ctx, ` 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. // People lists a tenant's volunteers.
func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, error) { func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, error) {
rows, err := s.db.QueryContext(ctx, ` rows, err := s.db.QueryContext(ctx, `
SELECT id, first_name, last_name, roles, email, preferred_church_ids, SELECT id, short_code, first_name, last_name, roles, email, preferred_church_ids,
preferred_weekdays, preferred_service_titles, max_per_month, active, notes 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) FROM people WHERE tenant_id=? ORDER BY last_name COLLATE NOCASE, first_name COLLATE NOCASE`, tenantID)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -183,8 +203,9 @@ func (s *Store) People(ctx context.Context, tenantID string) ([]domain.Person, e
// Person loads one volunteer. // Person loads one volunteer.
func (s *Store) Person(ctx context.Context, tenantID, id string) (*domain.Person, error) { func (s *Store) Person(ctx context.Context, tenantID, id string) (*domain.Person, error) {
row := s.db.QueryRowContext(ctx, ` row := s.db.QueryRowContext(ctx, `
SELECT id, first_name, last_name, roles, email, preferred_church_ids, SELECT id, short_code, first_name, last_name, roles, email, preferred_church_ids,
preferred_weekdays, preferred_service_titles, max_per_month, active, notes 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) FROM people WHERE tenant_id=? AND id=?`, tenantID, id)
person, err := scanPerson(row) person, err := scanPerson(row)
if errors.Is(err, sql.ErrNoRows) { 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) { func scanPerson(row rowScanner) (*domain.Person, error) {
var person domain.Person var person domain.Person
var roles, churches, weekdays, titles string var roles, churches, weekdays, periods, titles string
var active int var allowBeyond, active int
if err := row.Scan(&person.ID, &person.FirstName, &person.LastName, &roles, if err := row.Scan(&person.ID, &person.ShortCode, &person.FirstName, &person.LastName, &roles,
&person.Email, &churches, &weekdays, &titles, &person.Email, &churches, &weekdays, &periods, &titles,
&person.MaxPerMonth, &active, &person.Notes); err != nil { &person.MaxPerMonth, &allowBeyond, &active, &person.Notes); err != nil {
return nil, err return nil, err
} }
for _, raw := range decodeStrings(roles) { for _, raw := range decodeStrings(roles) {
@@ -233,7 +254,9 @@ func scanPerson(row rowScanner) (*domain.Person, error) {
} }
person.PreferredChurchIDs = decodeStrings(churches) person.PreferredChurchIDs = decodeStrings(churches)
person.PreferredWeekdays = decodeInts(weekdays) person.PreferredWeekdays = decodeInts(weekdays)
person.PreferredWeekdayPeriods = decodeWeekdayPeriods(periods)
person.PreferredServiceTitles = decodeStrings(titles) person.PreferredServiceTitles = decodeStrings(titles)
person.AllowBeyondPreferences = allowBeyond != 0
person.Active = active != 0 person.Active = active != 0
return &person, nil return &person, nil
} }
@@ -285,21 +308,28 @@ func (s *Store) UpsertPerson(ctx context.Context, tenantID string, person domain
email = "" email = ""
} }
_, err := tx.ExecContext(ctx, ` _, err := tx.ExecContext(ctx, `
INSERT INTO people(tenant_id, id, first_name, last_name, roles, email, INSERT INTO people(tenant_id, id, short_code, first_name, last_name, roles, email,
preferred_church_ids, preferred_weekdays, preferred_service_titles, preferred_church_ids, preferred_weekdays, preferred_weekday_periods,
max_per_month, active, notes) preferred_service_titles, max_per_month, allow_beyond_preferences, active, notes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET 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, first_name=excluded.first_name, last_name=excluded.last_name, roles=excluded.roles,
email=CASE WHEN ? THEN excluded.email ELSE people.email END, email=CASE WHEN ? THEN excluded.email ELSE people.email END,
preferred_church_ids=excluded.preferred_church_ids, preferred_church_ids=excluded.preferred_church_ids,
preferred_weekdays=excluded.preferred_weekdays, preferred_weekdays=excluded.preferred_weekdays,
preferred_weekday_periods=excluded.preferred_weekday_periods,
preferred_service_titles=excluded.preferred_service_titles, preferred_service_titles=excluded.preferred_service_titles,
max_per_month=excluded.max_per_month, active=excluded.active, notes=excluded.notes`, max_per_month=excluded.max_per_month,
tenantID, person.ID, person.FirstName, person.LastName, encodeStrings(roleStrings), 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), email, encodeStrings(person.PreferredChurchIDs),
encodeInts(person.PreferredWeekdays), encodeInts(person.PreferredWeekdays),
encodeWeekdayPeriods(person.PreferredWeekdayPeriods),
encodeStrings(person.PreferredServiceTitles), person.MaxPerMonth, encodeStrings(person.PreferredServiceTitles), person.MaxPerMonth,
boolInt(person.AllowBeyondPreferences),
boolInt(person.Active), person.Notes, boolInt(updateLegacyContact)) boolInt(person.Active), person.Notes, boolInt(updateLegacyContact))
if err != nil { if err != nil {
return err return err
@@ -360,6 +390,21 @@ func (s *Store) DeletePerson(ctx context.Context, tenantID, id string) error {
ScopePerson, tenantID, id); err != nil { ScopePerson, tenantID, id); err != nil {
return err 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) _, err := tx.ExecContext(ctx, "DELETE FROM people WHERE tenant_id=? AND id=?", tenantID, id)
return err 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. // Assignments returns assignments whose service lies in the range.
func (s *Store) Assignments(ctx context.Context, tenantID string, r domain.DayRange) ([]domain.Assignment, error) { func (s *Store) Assignments(ctx context.Context, tenantID string, r domain.DayRange) ([]domain.Assignment, error) {
rows, err := s.db.QueryContext(ctx, ` 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 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 <= ? 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)) 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 { for _, id := range serviceIDs {
args = append(args, id) 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 + ")" "WHERE tenant_id=? AND service_id IN (" + placeholders + ")"
rows, err := s.db.QueryContext(ctx, query, args...) rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil { if err != nil {
@@ -305,7 +306,7 @@ func (s *Store) AssignmentsForServices(ctx context.Context, tenantID string, ser
// AssignmentsForPerson lists all assignments of a volunteer. // AssignmentsForPerson lists all assignments of a volunteer.
func (s *Store) AssignmentsForPerson(ctx context.Context, tenantID, personID string) ([]domain.Assignment, error) { func (s *Store) AssignmentsForPerson(ctx context.Context, tenantID, personID string) ([]domain.Assignment, error) {
rows, err := s.db.QueryContext(ctx, ` 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) FROM assignments WHERE tenant_id=? AND person_id=? ORDER BY created_at`, tenantID, personID)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -326,13 +327,14 @@ func scanAssignments(rows *sql.Rows) ([]domain.Assignment, error) {
for rows.Next() { for rows.Next() {
var assignment domain.Assignment var assignment domain.Assignment
var role, created string var role, created string
var locked int var locked, beyond int
if err := rows.Scan(&assignment.ID, &assignment.ServiceID, &assignment.PersonID, 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 return nil, err
} }
assignment.Role = domain.Role(role) assignment.Role = domain.Role(role)
assignment.Locked = locked != 0 assignment.Locked = locked != 0
assignment.BeyondPreferences = beyond != 0
assignment.CreatedAt = parseTime(created) assignment.CreatedAt = parseTime(created)
out = append(out, assignment) out = append(out, assignment)
} }
@@ -351,14 +353,16 @@ func (s *Store) UpsertAssignment(ctx context.Context, tenantID string, assignmen
assignment.CreatedAt = time.Now().UTC() assignment.CreatedAt = time.Now().UTC()
} }
_, err := s.db.ExecContext(ctx, ` _, err := s.db.ExecContext(ctx, `
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked, note, created_at) INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked,
VALUES(?, ?, ?, ?, ?, ?, ?, ?) beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET ON CONFLICT(tenant_id, id) DO UPDATE SET
service_id=excluded.service_id, person_id=excluded.person_id, 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, 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.CreatedAt.Format(time.RFC3339)) assignment.Note, assignment.CreatedAt.Format(time.RFC3339))
if err != nil && isUniqueViolation(err) { if err != nil && isUniqueViolation(err) {
return ErrConflict return ErrConflict
} }
@@ -399,13 +403,16 @@ func (s *Store) SavePlan(ctx context.Context, tenantID string, assignments []dom
assignment.CreatedAt = time.Now().UTC() assignment.CreatedAt = time.Now().UTC()
} }
if _, err := tx.ExecContext(ctx, ` if _, err := tx.ExecContext(ctx, `
INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked, note, created_at) INSERT INTO assignments(tenant_id, id, service_id, person_id, role, locked,
VALUES(?, ?, ?, ?, ?, ?, ?, ?) beyond_preferences, note, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(tenant_id, id) DO UPDATE SET ON CONFLICT(tenant_id, id) DO UPDATE SET
service_id=excluded.service_id, person_id=excluded.person_id, 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, 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 { assignment.CreatedAt.Format(time.RFC3339)); err != nil {
return err 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 package web
import ( import (
"context"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
@@ -69,10 +70,30 @@ func (s *Server) handleLoginPost(w http.ResponseWriter, r *http.Request) {
return return
} }
s.setFlash(w, "Willkommen zurück, "+user.DisplayName+".", "success") 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")) next := safeNext(r.FormValue("next"))
s.redirect(w, r, 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) { func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
s.dropSessionKeyring(session.ID) s.dropSessionKeyring(session.ID)
if cookie, err := r.Cookie(sessionCookie); err == nil { if cookie, err := r.Cookie(sessionCookie); err == nil {
+92 -10
View File
@@ -3,33 +3,41 @@ package web
import ( import (
"net/http" "net/http"
"strings" "strings"
"time"
"lektorenplan/domain" "lektorenplan/domain"
"lektorenplan/store" "lektorenplan/store"
) )
// guestPageData is the read-only public plan. It deliberately contains no // guestPageData is the read-only public plan. It exposes only short labels
// person records: assignments are shown by role only. // (Kürzel or initials) of assigned people, never full names or contact data.
type guestPageData struct { type guestPageData struct {
Range domain.DayRange Range domain.DayRange
Start string Start string
End string End string
MinDate string
MaxDate string
PrevStart string PrevStart string
PrevEnd string PrevEnd string
NextStart string NextStart string
NextEnd string NextEnd string
CanPrev bool
CanNext bool
DefaultStart string
DefaultEnd string
Rows []domain.DayPlanRow Rows []domain.DayPlanRow
Churches []domain.Church Churches []domain.Church
Tenants []store.Tenant Tenants []store.Tenant
TenantID string TenantID string
TenantName string TenantName string
PersonLabels map[string]string
ServiceCount int ServiceCount int
OpenSlots int OpenSlots int
Today string Today string
} }
// handleGuest renders the plan without authentication. It never exposes // 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) { func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
tenants, err := s.store.Tenants(r.Context()) tenants, err := s.store.Tenants(r.Context())
if err != nil { 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) rows, err := s.store.PlanRows(r.Context(), tenant.ID, rng)
if err != nil { if err != nil {
http.Error(w, "Der Gastzugang ist derzeit nicht verfügbar.", http.StatusInternalServerError) 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 return
} }
prev := domain.MonthRange(domain.AddingMonths(-1, rng.Start)) assignedIDs := map[string]bool{}
next := domain.MonthRange(domain.AddingMonths(1, rng.Start)) 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{ page := guestPageData{
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End), Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
PrevStart: domain.Key(prev.Start), PrevEnd: domain.Key(prev.End), MinDate: domain.Key(minDate), MaxDate: domain.Key(maxDate),
NextStart: domain.Key(next.Start), NextEnd: domain.Key(next.End),
Rows: rows, Churches: churches, Tenants: tenants, Rows: rows, Churches: churches, Tenants: tenants,
TenantID: tenant.ID, TenantName: tenant.Name, TenantID: tenant.ID, TenantName: tenant.Name, PersonLabels: labels,
Today: domain.Key(domain.Today()), 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 { for _, row := range rows {
page.ServiceCount += len(row.Services) page.ServiceCount += len(row.Services)
@@ -86,3 +140,31 @@ func (s *Server) handleGuest(w http.ResponseWriter, r *http.Request) {
data.Data = page data.Data = page
s.renderPage(w, r, "guest", data) 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 // activeEditorKeyring returns any unlocked editor keyring from the in-memory
// session cache. It lets an administrator trigger a re-grant after a password // session cache. It lets an administrator trigger a re-grant after a password
// reset without ever decrypting the data themselves. // reset without ever decrypting the data themselves.
+34 -3
View File
@@ -64,6 +64,9 @@ type planPageData struct {
Timeline planTimeline Timeline planTimeline
FilterPeople []domain.Person FilterPeople []domain.Person
PersonFilter string PersonFilter string
SwapMarks map[string]string
PromptBeyond bool
BeyondOpen int
} }
func flattenRows(rows []domain.DayPlanRow) ([]domain.ServiceOccurrence, []domain.Assignment) { 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()) fourWeeks := domain.DaysRange(28, domain.Today())
data := s.baseView(w, r, "Gottesdienstplan", "plan") data := s.baseView(w, r, "Gottesdienstplan", "plan")
data.Data = planPageData{ page := planPageData{
Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End), Range: rng, Start: domain.Key(rng.Start), End: domain.Key(rng.End),
Rows: rows, Churches: churches, People: people, Stats: stats, Rows: rows, Churches: churches, People: people, Stats: stats,
CanEdit: canEdit, 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), PresetFourStart: domain.Key(fourWeeks.Start), PresetFourEnd: domain.Key(fourWeeks.End),
Presets: presets, Timeline: timeline, FilterPeople: filterPeople, PersonFilter: personFilter, 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) 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) rng := formRange(r)
options := s.planningOptions(r, tenant.ID) options := s.planningOptions(r, tenant.ID)
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" options.ReplaceExisting = r.FormValue("replace") == "1" || r.FormValue("replace") == "on"
}
services, err := s.store.Services(r.Context(), tenant.ID, rng) services, err := s.store.Services(r.Context(), tenant.ID, rng)
if err != nil { if err != nil {
@@ -376,9 +392,11 @@ func (s *Server) handleAutoPlan(w http.ResponseWriter, r *http.Request, user *st
s.redirect(w, r, "/plan") s.redirect(w, r, "/plan")
return return
} }
liturgicalDays, _ := s.store.LiturgicalDays(r.Context(), rng)
planner := domain.ServicePlanner{ planner := domain.ServicePlanner{
People: people, Absences: absences, Services: services, People: people, Absences: absences, Services: services,
ExistingAssignments: existing, Churches: churches, Options: options, ExistingAssignments: existing, Churches: churches, LiturgicalDays: liturgicalDays,
Options: options,
} }
result := planner.Plan() result := planner.Plan()
if err := s.store.SavePlan(r.Context(), tenant.ID, result.Assignments, rng, options.ReplaceExisting); err != nil { 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.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 { 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", "login", "plan", "service", "services", "team", "person", "statistics",
"exchange", "settings", "liturgy", "dispatch", "guest", "admin_tenants", "admin_users", "exchange", "settings", "liturgy", "dispatch", "guest", "admin_tenants", "admin_users",
"admin_churches", "password", "unlock", "error", "no_tenant", "admin_churches", "password", "unlock", "error", "no_tenant",
"swap_request", "swap_detail",
} }
views := make(map[string]*template.Template, len(names)) views := make(map[string]*template.Template, len(names))
for _, name := range 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}/delete", s.editor(s.handlePersonDelete))
mux.HandleFunc("POST /team/person/{id}/absence", s.personEditor(s.handleAbsenceSave)) 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/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 /statistics", s.auth(s.handleStatistics))
mux.HandleFunc("GET /exchange", s.auth(s.handleExchange)) mux.HandleFunc("GET /exchange", s.auth(s.handleExchange))
+83 -11
View File
@@ -41,6 +41,8 @@ type serviceDetailData struct {
HelperCandidates []domain.CandidateSuggestion HelperCandidates []domain.CandidateSuggestion
LectorAssigned []domain.Assignment LectorAssigned []domain.Assignment
HelperAssigned []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) { func (s *Server) handleServiceOrder(w http.ResponseWriter, r *http.Request, user *store.User, session *store.Session, tenant *store.Tenant) {
@@ -106,6 +108,16 @@ func (s *Server) handleServiceOrder(w http.ResponseWriter, r *http.Request, user
} }
var editingSpecial *domain.ServiceOccurrence var editingSpecial *domain.ServiceOccurrence
if id := strings.TrimSpace(r.URL.Query().Get("edit_special")); id != "" { if id := strings.TrimSpace(r.URL.Query().Get("edit_special")); id != "" {
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 { for i := range specials {
if specials[i].ID == id { if specials[i].ID == id {
copy := specials[i] copy := specials[i]
@@ -114,6 +126,7 @@ func (s *Server) handleServiceOrder(w http.ResponseWriter, r *http.Request, user
} }
} }
} }
}
data := s.baseView(w, r, "Gottesdienstordnung", "services") data := s.baseView(w, r, "Gottesdienstordnung", "services")
data.Data = serviceOrderData{ data.Data = serviceOrderData{
Churches: churches, Templates: templates, TemplatesByChurch: templatesByChurch, TemplateByID: templateByID, Churches: churches, Templates: templates, TemplatesByChurch: templatesByChurch, TemplateByID: templateByID,
@@ -187,18 +200,55 @@ func (s *Server) handleServiceDetail(w http.ResponseWriter, r *http.Request, use
} }
detail.LectorOpen = withAssignments.OpenSlotsFor(domain.RoleLector) detail.LectorOpen = withAssignments.OpenSlotsFor(domain.RoleLector)
detail.HelperOpen = withAssignments.OpenSlotsFor(domain.RoleHelper) 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 { if detail.LectorOpen > 0 {
detail.LectorCandidates = domain.CandidateSuggestions(*service, domain.RoleLector, people, absences, 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 { if detail.HelperOpen > 0 {
detail.HelperCandidates = domain.CandidateSuggestions(*service, domain.RoleHelper, people, absences, 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 data.Data = detail
s.renderPage(w, r, "service", data) 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 { func (s *Server) serviceRange(r *http.Request, date time.Time) domain.DayRange {
start, startOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("start"))) start, startOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("start")))
end, endOK := domain.DateFromKey(strings.TrimSpace(r.URL.Query().Get("end"))) 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 return
} }
locked := r.FormValue("locked") == "1" || r.FormValue("locked") == "on" 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{ assignment := domain.Assignment{
ID: domain.NewID(), ServiceID: service.ID, PersonID: person.ID, 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 { if err := s.store.UpsertAssignment(r.Context(), tenant.ID, assignment); err != nil {
s.setFlash(w, "Die Einteilung konnte nicht gespeichert werden: "+err.Error(), "error") 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") s.redirect(w, r, "/plan")
return return
} }
if service.Kind == domain.KindRegular { if err := s.store.DeleteService(r.Context(), tenant.ID, id); err != nil {
s.setFlash(w, "Regelmäßige Gottesdienste werden über die Gottesdienstordnung verwaltet und können nicht einzeln gelöscht werden.", "info") s.setFlash(w, "Der Gottesdienst konnte nicht gelöscht werden.", "error")
s.redirectBack(w, r, "/plan") s.redirectBack(w, r, "/plan")
return return
} }
if err := s.store.DeleteService(r.Context(), tenant.ID, id); err != nil { if service.Kind == domain.KindSpecial {
s.setFlash(w, "Der Gottesdienst konnte nicht gelöscht werden.", "error")
s.redirectBack(w, r, "/services")
return
}
s.setFlash(w, "Sondergottesdienst gelöscht.", "success") s.setFlash(w, "Sondergottesdienst gelöscht.", "success")
s.redirectBack(w, r, "/services") } else {
s.setFlash(w, "Gottesdienst gelöscht. Die Gottesdienstordnung bleibt unverändert.", "success")
}
// 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) { 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; show = parseInt(row.getAttribute("data-open") || "0", 10) > 0;
} else if (filter === "feasts") { } else if (filter === "feasts") {
show = row.getAttribute("data-special") === "true"; show = row.getAttribute("data-special") === "true";
} else if (filter === "beyond") {
show = row.getAttribute("data-beyond") === "true";
} }
row.hidden = !show; row.hidden = !show;
if (show) visible++; 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) { @media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; } * { 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")
}
+151 -2
View File
@@ -1,6 +1,7 @@
package web package web
import ( import (
"context"
"net/http" "net/http"
"sort" "sort"
"strings" "strings"
@@ -39,6 +40,21 @@ type teamPageData struct {
LectorCount int LectorCount int
HelperCount int HelperCount int
Year 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 { type personAssignmentRow struct {
@@ -55,6 +71,7 @@ type personPageData struct {
Assignments []personAssignmentRow Assignments []personAssignmentRow
Stats domain.PersonStat Stats domain.PersonStat
Weekdays []weekdayOption Weekdays []weekdayOption
Periods []domain.WeekdayPeriod
CanEdit bool CanEdit bool
CanManageAll bool CanManageAll bool
CanEditContact bool CanEditContact bool
@@ -156,11 +173,134 @@ func (s *Server) handleTeam(w http.ResponseWriter, r *http.Request, user *store.
page.HelperCount++ 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 := s.baseView(w, r, "Team", "team")
data.Data = page data.Data = page
s.renderPage(w, r, "team", data) 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 { func blankPerson() domain.Person {
return domain.Person{ return domain.Person{
ID: domain.NewID(), Roles: []domain.Role{domain.RoleLector}, 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{ page := personPageData{
Person: person, IsNew: isNew, Absences: absences, Churches: churches, Person: person, IsNew: isNew, Absences: absences, Churches: churches,
Assignments: rows, Weekdays: weekdays, Assignments: rows, Weekdays: weekdays, Periods: domain.AllWeekdayPeriods,
CanEdit: canManageAll || !isNew, CanManageAll: canManageAll, CanEdit: canManageAll || !isNew, CanManageAll: canManageAll,
CanEditContact: canManageContacts, CanEditContact: canManageContacts,
OwnContact: ownContact, OwnContact: ownContact,
@@ -336,18 +476,27 @@ func (s *Server) handlePersonSave(w http.ResponseWriter, r *http.Request, user *
return return
} }
person := domain.Person{ person := domain.Person{
ID: id, FirstName: strings.TrimSpace(r.FormValue("first_name")), 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, LastName: strings.TrimSpace(r.FormValue("last_name")), Roles: roles,
Email: strings.TrimSpace(r.FormValue("email")), Email: strings.TrimSpace(r.FormValue("email")),
PreferredChurchIDs: r.Form["preferred_churches"], PreferredChurchIDs: r.Form["preferred_churches"],
PreferredServiceTitles: splitList(r.FormValue("preferred_titles")), PreferredServiceTitles: splitList(r.FormValue("preferred_titles")),
MaxPerMonth: parseInt(r.FormValue("max_per_month"), 6), 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", Active: r.FormValue("active") == "1" || r.FormValue("active") == "on",
Notes: strings.TrimSpace(r.FormValue("notes")), Notes: strings.TrimSpace(r.FormValue("notes")),
} }
for _, raw := range r.Form["preferred_weekdays"] { for _, raw := range r.Form["preferred_weekdays"] {
if value := parseInt(raw, 0); value >= 1 && value <= 7 { if value := parseInt(raw, 0); value >= 1 && value <= 7 {
person.PreferredWeekdays = append(person.PreferredWeekdays, value) 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 { if existing != nil {
+9 -9
View File
@@ -4,7 +4,7 @@
<div> <div>
<span class="eyebrow">Öffentlicher Plan · {{.Data.TenantName}}</span> <span class="eyebrow">Öffentlicher Plan · {{.Data.TenantName}}</span>
<h2>{{rangeLong .Data.Range}}</h2> <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>
<div class="intro-actions"> <div class="intro-actions">
{{if gt (len .Data.Tenants) 1}} {{if gt (len .Data.Tenants) 1}}
@@ -23,17 +23,17 @@
<section class="toolbar card"> <section class="toolbar card">
<div class="toolbar-group range-nav"> <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"> <form class="range-form" method="get" action="/guest">
<input type="hidden" name="tid" value="{{.Data.TenantID}}"> <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>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}}"></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> <button class="btn btn-secondary btn-small" type="submit">Anzeigen</button>
</form> </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>
<div class="toolbar-group"> <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> </div>
</section> </section>
@@ -118,7 +118,7 @@
{{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}} {{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
<span class="service-people"> <span class="service-people">
{{range .Assignments}} {{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}} {{end}}
</span> </span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}} {{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}} {{if .Service.Location}}<span class="service-location">{{deref .Service.Location}}</span>{{end}}
<span class="service-people"> <span class="service-people">
{{range .Assignments}} {{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}} {{end}}
</span> </span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}} {{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> <p class="plan-mobile-empty empty-note" data-plan-mobile-empty hidden>Keine Tage passen zu diesem Filter.</p>
</div> </div>
</section> </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> </div>
{{end}} {{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">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> <label class="field"><span class="field-label">Nachname</span><input type="text" name="last_name" value="{{$person.LastName}}"></label>
</div> </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"> <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> <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> </div>
@@ -58,10 +59,15 @@
</div> </div>
</div> </div>
<div class="field-group"> <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"> <div class="weekday-grid">
{{range .Data.Weekdays}} {{range $weekday := .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> <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}} {{end}}
</div> </div>
</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 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> </label>
</div> </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> <button class="btn btn-primary" type="submit">{{if .Data.IsNew}}Person anlegen{{else}}Person speichern{{end}}</button>
</form> </form>
{{else}} {{else}}
<dl class="detail-list"> <dl class="detail-list">
<dt>Name</dt><dd>{{$person.FullName}}</dd> <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> <dt>Dienste</dt><dd>{{$person.RoleLabel}}</dd>
{{if $person.Email}}<dt>E-Mail</dt><dd>{{$person.Email}}</dd>{{end}} {{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}} {{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> </div>
</section> </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"> <section class="stat-strip">
<article class="mini-stat"> <article class="mini-stat">
<span class="mini-stat-label">Gottesdienste</span> <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="services">Mit Gottesdiensten</button>
<button class="chip" type="button" data-plan-filter="open">Nur offene</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="feasts">Sonn- &amp; Feiertage</button>
<button class="chip" type="button" data-plan-filter="beyond">Über Präferenzen</button>
</div> </div>
<div class="legend-items"> <div class="legend-items">
<span><i class="swatch sunday"></i>Sonntag</span> <span><i class="swatch sunday"></i>Sonntag</span>
<span><i class="swatch feast"></i>Hochfest</span> <span><i class="swatch feast"></i>Hochfest</span>
<span><i class="swatch open"></i>Offener Dienst</span> <span><i class="swatch open"></i>Offener Dienst</span>
<span><span class="beyond-mark">↑</span>Über Präferenzen</span>
</div> </div>
</div> </div>
@@ -145,6 +164,7 @@
</span> </span>
</th> </th>
{{end}} {{end}}
<th class="col-day-action"><span class="visually-hidden">Aktionen</span></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -153,7 +173,8 @@
data-plan-row data-plan-row
data-has-services="{{if .HasServices}}true{{else}}false{{end}}" data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
data-open="{{.OpenSlots}}" 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"> <td class="date-cell">
<div class="date-number">{{dayNumber .Date}}</div> <div class="date-number">{{dayNumber .Date}}</div>
<div class="date-meta"><span>{{shortWeekday .Date}}</span><span>{{shortMonth .Date}}</span></div> <div class="date-meta"><span>{{shortWeekday .Date}}</span><span>{{shortMonth .Date}}</span></div>
@@ -185,6 +206,7 @@
{{if $services}} {{if $services}}
<div class="service-stack"> <div class="service-stack">
{{range $services}} {{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}}"> <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-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> <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"> <span class="service-people">
{{range .Assignments}} {{range .Assignments}}
{{$person := index $.Data.People .PersonID}} {{$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}} {{end}}
</span> </span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}} {{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
</a> </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}} {{end}}
</div> </div>
{{else}} {{else}}
@@ -204,6 +235,11 @@
{{end}} {{end}}
</td> </td>
{{end}} {{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> </tr>
{{end}} {{end}}
</tbody> </tbody>
@@ -217,7 +253,8 @@
data-plan-row data-plan-row
data-has-services="{{if .HasServices}}true{{else}}false{{end}}" data-has-services="{{if .HasServices}}true{{else}}false{{end}}"
data-open="{{.OpenSlots}}" 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"> <summary class="plan-day-summary">
<span class="day-date"> <span class="day-date">
<span class="date-number">{{dayNumber $row.Date}}</span> <span class="date-number">{{dayNumber $row.Date}}</span>
@@ -255,6 +292,9 @@
<span class="day-chevron" aria-hidden="true">{{icon "right"}}</span> <span class="day-chevron" aria-hidden="true">{{icon "right"}}</span>
</summary> </summary>
<div class="day-details"> <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 $row.LiturgicalDay}}
{{if not $row.LiturgicalDay.Readings.IsEmpty}} {{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> <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>
<div class="service-stack"> <div class="service-stack">
{{range $services}} {{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}}"> <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-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> <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"> <span class="service-people">
{{range .Assignments}} {{range .Assignments}}
{{$person := index $.Data.People .PersonID}} {{$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}} {{end}}
</span> </span>
{{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}} {{if not .IsFullyStaffed}}<span class="open-badge">{{plural .OpenSlots "Platz offen" "Plätze offen"}}</span>{{end}}
</a> </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}} {{end}}
</div> </div>
</div> </div>
+14 -6
View File
@@ -21,8 +21,8 @@
</div> </div>
<div class="detail-hero-actions"> <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> <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")}} {{if .Data.CanEdit}}
<form method="post" action="/services/{{$service.ID}}/delete" data-confirm="Diesen Sondergottesdienst wirklich löschen?"> <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="csrf" value="{{.CSRF}}">
<button class="btn btn-danger btn-small" type="submit">{{icon "trash"}} Löschen</button> <button class="btn btn-danger btn-small" type="submit">{{icon "trash"}} Löschen</button>
</form> </form>
@@ -42,8 +42,11 @@
{{$person := index $.Data.People .PersonID}} {{$person := index $.Data.People .PersonID}}
<div class="assignment-row"> <div class="assignment-row">
<span class="avatar small">{{if $person}}{{$person.Initials}}{{else}}?{{end}}</span> <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 .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}} {{if $.Data.CanEdit}}
<div class="assignment-actions"> <div class="assignment-actions">
<form method="post" action="/services/{{$service.ID}}/lock"> <form method="post" action="/services/{{$service.ID}}/lock">
@@ -69,9 +72,10 @@
<div class="candidate {{if .Blocked}}blocked{{end}}"> <div class="candidate {{if .Blocked}}blocked{{end}}">
<div class="candidate-main"> <div class="candidate-main">
<span class="avatar small">{{.Person.Initials}}</span> <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>
<div class="candidate-tags"> <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}} {{if .Preferred}}<span class="badge badge-green">Präferenz</span>{{end}}
{{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}} {{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}}
</div> </div>
@@ -100,8 +104,11 @@
{{$person := index $.Data.People .PersonID}} {{$person := index $.Data.People .PersonID}}
<div class="assignment-row"> <div class="assignment-row">
<span class="avatar small">{{if $person}}{{$person.Initials}}{{else}}?{{end}}</span> <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 .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}} {{if $.Data.CanEdit}}
<div class="assignment-actions"> <div class="assignment-actions">
<form method="post" action="/services/{{$service.ID}}/lock"> <form method="post" action="/services/{{$service.ID}}/lock">
@@ -127,9 +134,10 @@
<div class="candidate {{if .Blocked}}blocked{{end}}"> <div class="candidate {{if .Blocked}}blocked{{end}}">
<div class="candidate-main"> <div class="candidate-main">
<span class="avatar small">{{.Person.Initials}}</span> <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>
<div class="candidate-tags"> <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}} {{if .Preferred}}<span class="badge badge-green">Präferenz</span>{{end}}
{{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}} {{range .Warnings}}<span class="badge badge-burgundy">{{.}}</span>{{end}}
</div> </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> <article class="mini-stat"><span class="mini-stat-label">Abwesenheiten</span><strong>{{len .Data.Absences}}</strong><small>hinterlegte Zeiträume</small></article>
</section> </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"> <div class="team-layout">
<section class="card"> <section class="card">
<div class="card-head"> <div class="card-head">